2011-07-02 4 views
1

이 튜토리얼 http://www.crawlspacegames.com/blog/inheritance-in-lua/을 따라 MusicalInstrument를 상속받은 2 개의 개체 (드럼 및 기타)를 만들었습니다.루아 oop-timer 구현

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 호출되는 MusicalInstrument에서 상속 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 개 드럼을 가지고 출력을 제외 훨씬을 이해할 수있을 것이다 !! !!

감사

----------------------------- 다른 시도 후 편집 -------- -----------

다음 출력 결과 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() 모두 두 변수에 대해 동일한 변수를 쓰고 읽습니다.

실제로 인스턴스 당 악기 유형을 설정하려고합니다. 루아는 정확하게 내 기본 언어가 아니지만 예를 들어 다음과 같습니다.

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를 위해 기존의 루아 코드베이스를 사용하여 조금만 조작하십시오. –