Right, it does sound like you need to understand scoping in Lua. Read this section of the manual (in fact the whole page is useful).
In simple terms, the “scope” of a variable (or function) in Lua has to do with where it is available (“blocks”). A block might be a function, or an entire script.
Something with the prefix ‘local’ is available only in the block where it is defined. Without that prefix, it is global, and available everywhere. Using global variables can quickly get messy, and you risk accidentally overwriting them.
Say you define these two variables in script A:
local here = "value1"
everywhere = "value2"
In script B, you do this:
print(here)
print(everywhere)
The output will be:
nil
value2
In the example above, ‘here’ is local to script A, whereas ‘everywhere’ is a global variable, and thus available everywhere.
Another example, but this time the block will be a function rather than a script.
function init(self)
local var1 = 1 --defined in the init() block
local function do_stuff()
local var2 = 1 -- defined in the do_stuff() block, a subset of the init() block
var1 = var1 + 1
var2 = var2 + 1
end
do_stuff()
print(var1)
print(var2)
end
var1 is defined inside the init() scope, and is therefore available inside the entirety of that scope (including inside the local function do_stuff()). On the other hand, var2 is defined only inside do_stuff().
The output:
2
nil
This is because var2 is not available outside of the do_stuff() block.
You also need to understand referencing. When you pass in variables containing values to a function, you are passing in just the value - not the variable. So if you modify the value in the function, you are just modifying the value and not the variable.
function init(self)
local var1 = 1
local function do_stuff(var)
var = var + 1
print(var)
end
do_stuff(var1)
print(var1)
end
Output:
2
1
The first output is the value modified inside the function. As stated, this doesn’t change the variable, which is illustrated by the second print. Actually modifying the variable could be achieved using a return however, as you have already hinted at:
function init(self)
local var1 = 1
local function do_stuff(var)
var = var + 1
return var
end
var1 = do_stuff(var1)
print(var1)
end
Output:
2
Programming in Lua is an excellent (and free) resource to learn everything about Lua.