2011-07-02 6 views
1

私はこのチュートリアルhttp://www.crawlspacegames.com/blog/inheritance-in-lua/に従い、MusicalInstrumentを継承した2つのオブジェクト(ドラムとギター)を作成しました。ルアオップタイマーの実装

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 

:私はタイマー機能を追加するまで、すべてが

MusicalInstrument.lua呼び出される楽器から継承2つのオブジェクトから何らかの理由で、その後、罰金のみ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つのドラムを持っているために、出力を除外!!別の試行後に編集

おかげ

----------------------------- --------

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

正しい楽器をで呼ばれていました:-----------楽器

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 

次の変更は、次のような出力となりましたタイマーだけです。

答えて

2

listenerMusicalInstrument:play()の両方で、両方のインスタンスで同じ変数を書き込んで読み込みます。

実際には、ここでインスタンスごとに計測器タイプを設定する必要があります。ルアは私の主要な言語ではありませんが、次のようなもの:

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

お勧めのリソースはありますか? – Eran

+0

@ Eran:必要なときに[Lua docs](http://www.lua.org/docs.html)を少し読んだだけです。しかし、もう一度、私はmodのための既存のLuaコードベースでちょっと手を加えてしまいます。 –