It depends on how you wish to access the variable. If you declare a variable on self it will be available from everywhere in the script where you have a self reference. If you declare a variable as local it will be available within the scope in which it is declared. Here’s an example of the different scopes. Given a script my_script.script
:
-- this value will be available from all scripts, gui_scripts and
-- modules (Lua files)
global_foo = "global scope"
-- this value will be shared by all my_script.script instances
local script_foo = "script scope"
function init(self, dt)
-- this value will be available on this instance of my_script.script and
-- after it's set here in init()
self.foo = "self scope"
-- this value will be available inside init() and after it's declaration
local local_foo = "local scope"
print(local_foo)
end
function update(self, dt)
print(self.foo) -- "self scope"
print(global_foo) -- "global scope"
print(script_foo) -- "script scope"
print(local_foo) -- will print nil, since local_foo is only visible from init()
end
You should also read up on and understand how variables can shadow each other:
foo = "global"
print(foo) -- will print "global"
local foo = "abc"
print(foo) -- will print "abc"
local function test(foo)
print(foo) -- will print "fgh"
end
function init(self)
local foo = "cde"
print(foo) -- will print "cde"
test("fgh")
end