Explanation of the "self"argument for dummies

Please, I need a ‘for dummies’ explanation of the “self” argument used in functions in scripts.

For all practical purposes, it is a table that you can use to store properties that are specific to one, single object (since you can have many different copies of the same object).

If you define a local variable at the top of your script, that variable will be shared by all instance of the script. If one of them changes it, it will be different for all. But if you put something in self, it will only be changed for, and only be accessible to, that one instance.

For example if you have a bullet object with a script on it. When you fire a shotgun, you will spawn a bunch of these bullets. If you do this:

local speed = 500

function init(self)
	speed = math.random(300, 600)
end

function update(self, dt)
	local p = go.get_position()
	p.x = p.x + speed * dt
	go.set_position(p)
end

You randomize the value of speed when each bullet is spawned, but since you define it as a local variable like that, it is shared between all of them, and they will all use the same value (as set by the last bullet to spawn).

If instead you do this:

function init(self)
	self.speed = math.random(300, 600)
end

function update(self, dt)
	local p = go.get_position()
	p.x = p.x + self.speed * dt
	go.set_position(p)
end

Then each individual bullet will have its own random speed that it will use. It won’t interfere with any other bullets.

13 Likes

I was fighting with the very unclear bug, and I’m currently describing it on my devlog and it was exactly about misunderstanding of local in script, while I had multiple instances of it. Already found this cause, but it took me so long, I’m sad I just read it on forum, because it’s a little bit to late :stuck_out_tongue: but what I learnt remains mine and I’ll never forget :smiley: it is a very clear explanation! :wink:

4 Likes

Thanks @ross.grams
So the self table is automatically created without a constructor?

It’s also documented here: https://www.defold.com/manuals/lua/#_script_execution_and_callbacks

5 Likes