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.