Lua面向对象编程:定时器实现

我正在遵循这个教程 http://www.crawlspacegames.com/blog/inheritance-in-lua/,创建了两个对象(架子鼓和吉他)从 MusicalInstrument 继承。在我添加计时器函数之前,一切都很正常,然后由于某种原因 ,只有一个从 MusicalInstrument 继承的对象被调用。

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 {} -- 可以参数化,默认为新表
    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 {} -- 可以参数化,默认为新表
    setmetatable(x, self)
    self.__index = self
    return x
end

导致以下输出:

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

正确的乐器被计时器调用,但仅一次。

原文链接 https://stackoverflow.com/questions/6555889

点赞
stackoverflow用户168225
stackoverflow用户168225

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
2011-07-02 16:26:45