2011-07-02 34 views
1

我按照這個教程http://www.crawlspacegames.com/blog/inheritance-in-lua/創建了2個繼承自MusicalInstrument的對象(鼓和吉他)。Lua oop - 定時器的實現

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 

:一切從2個對象,從MusicalInstrument繼承被稱爲

MusicalInstrument.lua工作得很好,直到我說的定時器功能,然後由於某種原因,只有1 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 

正確的儀器由被叫定時器但只有一次

回答

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 
+0

你搖滾! @#@ 1234567890 – Eran

+0

你推薦的任何lua資源? – Eran

+0

@Eran:在需要時,我只通過[Lua文檔](http://www.lua.org/docs.html)閱讀。但是,我再次只用一個現有的Lua代碼庫來替代一個mod。 –