3
votes

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

1
that sounds very confusing and error prone. - Piglet
@Piglet Look at the answer, plz. This question is logical so that someone can answer. - SWIIWII
not your question. I mean reusing variable names that way. its dangerous and the code becomes hard to read - Piglet
@Piglet I see, thx for the advice :) - SWIIWII
It kinda makes sense once you've finished the code and want to minimize it as much as possible to reuse variable names like this, there's only so many letters and words out there and if lua let's us reuse some of them. Great! Whilst you're testing and doing work like this though I recommend using more verbose variable names to avoid confusion. - Kershrew

1 Answers

6
votes

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