【发布时间】:2011-07-03 00:58:03
【问题描述】:
我正在关注本教程 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
吉他.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
计时器调用了正确的工具,但只调用了一次
【问题讨论】: