Lua oop - 计时器实现

时间:2011-07-02 08:14:08

标签: oop lua corona

我正在按照本教程http://www.crawlspacegames.com/blog/inheritance-in-lua/创建2个继承自MusicalInstrument的对象(鼓和吉他)。一切正常,直到我添加了计时器功能,然后由于某种原因,从MusicalInstrument继承的2个对象中只有1个被调用

MusicalInstrument.lua:

module(...,package.seeall)

MusicalInstrument.type="undefined"

local function listener()
print("timer action: "..MusicalInstrument.type)
end

function MusicalInstrument:play(tpe)
    MusicalInstrument.type = tpe;
    print("play called by: "..MusicalInstrument.type)
    timer.performWithDelay(500,listener,3)
end

function MusicalInstrument:new( o )
    x = x or {} -- can be parameterized, defaults to a new table
    setmetatable(x, self)
    self.__index = self
    return x
end

Guitar.lua

module(...,package.seeall)
require("MusicalInstrument")

gtr = {}

setmetatable(gtr, {__index = MusicalInstrument:new()})

return gtr

Drums.lua

module(...,package.seeall)
require("MusicalInstrument")

drms = {}

setmetatable(drms, {__index = MusicalInstrument:new()})

return drms

main.lua

--    CLEAR TERMINAL    --
os.execute('clear')
print( "clear" ) 
--------------------------


local drms=require("Drums")

drms:play("Drums")

local gtr=require("Guitar")

gtr:play("Guitar")

这是终端输出:

clear
play called by: Drums
play called by: Guitar
timer action: Guitar
timer action: Guitar
timer action: Guitar
timer action: Guitar
timer action: Guitar
timer action: Guitar

我除了输出有3个吉他时间和3个鼓定时器电话

关于如何完成这项工作的任何想法都将受到赞赏!!

由于

-----------------------------经过另外一次尝试编辑-------------- -----

MusicalInstrument中的以下更改

module(...,package.seeall)

MusicalInstrument.type="undefined"

function MusicalInstrument:listener()
print("timer action: "..MusicalInstrument.type)
end

function MusicalInstrument:play(tpe)
    MusicalInstrument.type = tpe;
    print("play called by: "..MusicalInstrument.type)
    timer.performWithDelay(500,MusicalInstrument:listener(),3)
end

function MusicalInstrument:new( o )
    x = x or {} -- can be parameterized, defaults to a new table
    setmetatable(x, self)
    self.__index = self
    return x
end

导致以下输出结果:

clear
play called by: Drums
timer action: Drums
play called by: Guitar
timer action: Guitar

计时器调用了正确的乐器,但只有一次

1 个答案:

答案 0 :(得分:2)

listenerMusicalInstrument:play()中,您为两个实例编写并读取相同的变量。

您实际上想要在此设置每个实例的仪器类型。 Lua不完全是我的主要语言,但是类似的东西:

function MusicalInstrument:listener()
    print("timer action: "..self.type)
end

function MusicalInstrument:play(tpe)
    self.type = tpe;
    local f = function() self:listener() end
    timer.performWithDelay(500, f, 3)
end