local

Local variables are created with the local statement. Their scope is limited to the block where they are declared.

eg.

a = 1 -- global variable
local b = 2 -- local variable
Global variables are stored in the "global environment table" which is generally accessible to all functions. Local variables are only visible to the block in which they are "seen". For example:

function foo ()
  local x = 42  -- x is only visible inside foo
  y = 63  -- global variable y is changed
end -- function foo
In this example if there was another variable "x" somewhere else in the program, it would not be affected by the local variable x inside foo.

Be aware that if you redefine a local variable you get a new one of the same name. Eg.

function foo ()
  local x = 42  -- x is only visible inside foo
  
  -- do various things here

  local x = 43  -- this is a new variable x, we have not changed the earlier one
end -- function foo
If you want to change an existing local variable, do not use the word local again, eg.

function foo ()
  local x = 42  -- x is only visible inside foo
  
  -- do various things here

  x = 43  -- we have changed the earlier one
end -- function foo

Lua keyword/topics

Topics