I know this is very basic question but i'm pretty much confused by the local variables & their scope in lua, for instance if i write local x=12, it means that the variable x is a local variable & it's value is 12, but instead if i write local x & in the next line x=12, does this mean the same as in previous case or x=12 is treated as a global variable?
3
votes
2 Answers
4
votes
You can think of it as two totally independent things:
local xcreates a "slot" in the local scope to hold a value, i.e. a variable. This variable is namedx. From that point forward, until you exit that scope, any reference toxwill refer to that localx.x = 12puts a value into the variablex. If you've previously created a local slot named x, that's where it'll go. If there is no localxin scope, it'll go into the global scope.
local x = 12 is just a shorthand for combining these two things, creating a local variable and assigning it a value at the same time.
So yes, your two scenarios are effectively equivalent.
local x
x = 12
And
local x = 12
Do the same thing.
local x=12 local x=x+11Two variables: The second has the value 23; The first still has the value 12 but is thereafter inaccessible due to being shadowed by the second. - Tom Blodget