So, the question is simple (or not?) - how to use Modules? I mean, I’ve read tutorial, but I have a lack of knowledge of working with functions and their arguments, returning values, etc. So I need a little bit of help here.
I have some code which I want to share with two or more objects (movement of different types of mobs). So, I don’t want just copypaste code to each of new types of mobs, here Modules come in handy. But I am a little bit stuck.
Module code:
function init(self)
self.direction = 1 -- -1 - left, 1 - right
self.id = go.get_id()
end
function update(self, dt)
local p = go.get_position()
-- apply the speed
p.x = p.x + self.speed * dt * self.direction
go.set_position(p)
if p.x == 204 or p.x == 39 then
p.y = p.y - 56
self.direction = self.direction*-1
if self.direction == -1 then
sprite.set_hflip("#mob1", true)
sprite.set_hflip("#mob2", true)
else
sprite.set_hflip("#mob1", false)
sprite.set_hflip("#mob2", false)
end
go.set_position(p)
end
--arrive to Reactor
if p.x == 192 and p.y == 25 then
msg.post("/reactor#behavior_TurretReactor", "do_damageReactor")
go.delete()
end
--draw HP
msg.post("@render:", "draw_text", {text = "" .. self.hp, position = vmath.vector3(p.x - 10, p.y+30, p.z)})
--msg.post("@render:", "draw_text", {text = "" .. self.id, position = vmath.vector3(p.x - 10, p.y+50, p.z)})
--delete mobs if 0 hp
if self.hp <= 0 then
go.delete()
end
end
function on_message(self, message_id, message, sender)
--damage from laser
if message_id == hash("do_damage") then
self.hp = self.hp - message.damage
--msg.post("@render:", "draw_text", {text = "dmg" .. message.damage, position = vmath.vector3(p.x - 10, p.y+30, p.z)})
end
end
Mob’s script:
hpIncrement = 0
function init(self)
self.speed = 30
self.hp = math.random(1000+hpIncrement, 1700+hpIncrement) + hpIncrement
local id = timer.seconds(2, function(self, id)
hpIncrement = hpIncrement + 10
end)
end
function update(self, dt)
if self.hp <= 0 then
money = money + 10
end
end
I know that I need to name functions in Module and just paste functions in mob’s script, but I don’t quite understand which arguments and return values must be.