Help regarding scope?
Posted: Thu Mar 07, 2013 8:58 am
The next stumbling block for me writing Lua well is scope. I seem to be stumbling around it. I get the right answer eventually, but I don't have a good understanding of why-- it's just trial and error. Since there are some good people around here, I thought I might ask for help. Really, I want an abstract understanding of how Lua handles it. Tutorials haven't been much use, because they don't deal with any complicated situations.
To start the ball rolling, let's look at dofile. Imagine I have a file named File, and in that file I have the following:
So if I
I get 1 as my output. But if I
then I get 2.
What's going on with that? Why can't I retrieve table keys and values via dofile? (I want to be able to write files with various keys, and not have to create every possible key I could generate before reading my file.) This seems like a scope issue, because I can't even get any values without declaring the variable first in my code (I'll just get nil), and if I declare my variable as local, then the dofile won't write to it at all, even though it seems like the dofile is part of the same scope.
To start the ball rolling, let's look at dofile. Imagine I have a file named File, and in that file I have the following:
Code: Select all
t= {}
t.first = true
someothervalue = 1
Code: Select all
someothervalue = 2
dofile(File)
print(someothervalue)
Code: Select all
t={}
dofile(File)
if t.first then print("1") else print("2") end
What's going on with that? Why can't I retrieve table keys and values via dofile? (I want to be able to write files with various keys, and not have to create every possible key I could generate before reading my file.) This seems like a scope issue, because I can't even get any values without declaring the variable first in my code (I'll just get nil), and if I declare my variable as local, then the dofile won't write to it at all, even though it seems like the dofile is part of the same scope.