4 posts
Posted 14 August 2012 - 03:01 PM
This may sound like a noob question but I'm new to Lua.
I'm wondering what declaring a variable does. For example how is x = "Hi" different from local x = "Hi"? I'd always though that it was equivalent to java's public/private.
4 posts
Posted 14 August 2012 - 03:03 PM
I mean: declaring a variable local.
8543 posts
Posted 14 August 2012 - 03:12 PM
It limits the scope of the variable to the block in which it is declared and any sub-blocks. When used in a program, this means that it does not interfere with other running programs that may use the same variable names, etc. There are very few good reasons not to use local.
3790 posts
Location
Lincoln, Nebraska
Posted 14 August 2012 - 03:17 PM
Visual example:
local x = "Top" --exists everywhere, since it is above every subfunction right now
while true do
local y = "Middle" --only exists within this while/do loop, but x still = "Top", since this is a subfunction
end
local x = "Bottom" --now re-declares x.
I hope this explains it a little better.
997 posts
Location
Wellington, New Zealand
Posted 15 August 2012 - 05:04 AM
local a = 4
local b = 7
print(tostring(a)) -- prints 4
repeat
local c = 9
print(tostring(c)) -- prints 9
local b = 4 -- Does not affect the other b. This creates a NEW b which hides the one outside the loop
print(tostring(:P/>/>) -- prints 4
until false
print(tostring(c)) -- prints nil (as c is not visible here)