When to use self? When to use local?

If you would create a local variable in a script like this:

local speed = 1

function update(self, dt)
speed = speed + 1 * dt
end

it would be a problem as soon as you use several instances of the same gameobject as they would all refer to the same variable ‘speed’. If you had 5 cars with this script speed would be updated 5 times in the same frame and all cars would have the same speed.

If you on the other hand would do this:

function init(self)
self.speed = 0
end

function update(self, dt)
self.speed = self.speed + 1 * dt
end

Here all the cars will have an individual speed in self.speed.

Conclusion.
self is an instance variable meanwhile local will be shared with all using the same script.

9 Likes