i have a physic.lua script and i want to use it in player and enemy game object.
so, i wrote te next line in they controller script
local physics = require ("path")
but the problem is that i overwrite the local variables in physics.lua.
-- in player script
local pyshics1 = require("path")
physics1.a = 1
-- in enemy script
local pyshics2 = require("path")
physics2.a = 2
--then when i want to get the value i got something like this
-- in player script
physics1.get_a() -- Value : 2
-- in enemy script
physics2.get_a() -- Value: 2
in java i would solve it using something like this
-- in player
Physics physics1= new Physics();
physic1.set_a(1);
-- in enemy
Physycs physics2 = new Physics();
physic.2_set_a(2)
--then
-- in player
physics1.get_a() -- Value: 1
-- in enemy
physics2.get_a() -- Value: 2
so, how can i do that ? two diferent instance of the same script ?
Worth noting is that this is close to doing object oriented programming in Lua. Depending on what your goal is, it might make sense to actually taking a look at my first answer, maybe some of the features Defold exposes natively (especially script properties) can be used instead?
But if I would make something like you are asking for, I would make physics.lua actually return a constructor function that will return a new “physics instance”. Something like this:
-- physics.lua
local function physics_constructor()
local new_instance = {
a = 0
b = 0
}
new_instance.set_a = function(self, new_value)
self.a = new_value
end
new_instance.get_a = function(self)
return self.a
end
return new_instance
end
return physics_constructor
And when using in your different scripts;
-- player.script
local physics_constructor = require("path_to_physics.lua")
function init(self)
self.physics_instance = physics_constructor()
self.physics_instance:set_a(1)
self.physics_instance.b = 1
print(self.physics_instance:get_a(), self.physics_instance.b)
-- -> 1 1
end
...
-- enemy.script
local physics_constructor = require("path_to_physics.lua")
function init(self)
self.physics_instance = physics_constructor()
self.physics_instance:set_a(2)
self.physics_instance.b = 2
print(self.physics_instance:get_a(), self.physics_instance.b)
-- -> 2 2
end