This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
Traumah's profile picture

Local variables?

Started by Traumah, 14 August 2012 - 01:01 PM
Traumah #1
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.
Traumah #2
Posted 14 August 2012 - 03:03 PM
I mean: declaring a variable local.
Lyqyd #3
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.
Cranium #4
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.
immibis #5
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)