Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 :)

like image 620
SWIIWII Avatar asked Oct 27 '25 04:10

SWIIWII


1 Answers

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

like image 76
DrCuddles Avatar answered Oct 30 '25 05:10

DrCuddles



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!