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.
Correct. A local variable is available only in the block where it is declared. It’s only local variables declared outside the scope of the init(), final(), update() etc that are available to all scripts of the same type. Consider them similar to private static variable declarations in a Java class or something similar.
A go.property() declared variable is accessible by other scripts using go.get().
So is it considered good practice to use local variables declared outside a block - or better to use go.property() instead? Just trying to parse this further.
go.property(“foobar”, 123)
If would primarily use go.property() when I need a variable on a script to vary between script instances (eg changed from the Properties window or when passed as an argument to factory.create)
self.foobar = 123
I would use this for any other instance variable that I need on my scripts
local foobar = 123
I use local variables declared at the top level of a script for stuff I need to share between multiple instances of the same type of script. This can be some kind of shared counter or perhaps a shared list of instances so I can do things like broadcasting to all script instances of a certain type.