SWIIWII
SWIIWII

Reputation: 417

access to global variables in lua

I have a Lua code below :

a, b = 1, 10
if a<b then
    print(a)
    local a
    print(a)
end
print(a, b)


Just a small question :

first of all, I created a global variable a = 1;

then in the then block I use the global variable a to print it;

and then I declared a local variable a that is not initialized (thus it gets the value nil)

Then my question comes : how could I get access to the global variable a after having created the local variable a in the then block, is that possible ? If so, please give me an answer :)

Upvotes: 4

Views: 9302

Answers (1)

DrCuddles
DrCuddles

Reputation: 386

Use _ENV.a to access the global variable after using the same name for a local one!

Note, Lua versions 5.1 and below use _G

Edit, Just tested this:

a, b = 1, 10
if a<b then
    local a = 12
    print(a) -- Will print 12
    print(_ENV.a) -- Will print 1
end
print(a, b) -- Will print 1 10

And it worked fine, gave me the desired output referencing _ENV.a

Upvotes: 7

Related Questions