Simple Lua question? Maybe?

So I’m pretty new to Lua, but familiar with a few other languages. I just wanted some clarification on variable declaration/usage. Specifically looking at the Getting Started tutorial, part two (http://www.defold.com/tutorials/getting-started-part2), hero.script. Some variables are stored as local variables (local gravity = 30), while some are stored on self (self.position = go.get_position())

This is just a little confusing to me, and I hope I’m just missing something simple. Why wouldn’t you just make all of these local variable, or “self.” variables?

2 Likes

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
4 Likes

Cool, thanks for the clarification. That really makes sense now

1 Like