3
votes

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?

2
Mind-bender: local x=12 local x=x+11 Two 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

2 Answers

4
votes

You can think of it as two totally independent things:

  1. local x creates a "slot" in the local scope to hold a value, i.e. a variable. This variable is named x. From that point forward, until you exit that scope, any reference to x will refer to that local x.

  2. x = 12 puts a value into the variable x. If you've previously created a local slot named x, that's where it'll go. If there is no local x in 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.

2
votes

You only use the local keyword once per scope, so that second access of x in your example will use the local x. If you then wish to access the global x, you can use __G.x