OOP inheritance question

I was following this tutorial http://www.crawlspacegames.com/blog/inheritance-in-lua/ and created 2 objects (drums and Guitar) that inherit from MusicalInstrument. Everything worked fine until I added timer functions, then for some reason only 1 from the 2 objects that inherit from MusicalInstrument gets called

MusicalInstrument.lua:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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

got an answer in stackoverflow :
http://stackoverflow.com/questions/6555889/lua-oop-timer-implementation/6558206#6558206

In both listener and MusicalInstrument:play() you write and read the same variable for both instances.

You actually want to set the instrument type per instance here. Lua is not exactly my primary language, but e.g. something like:

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
link|edit|flag
edited 14 hours ago

answered 15 hours ago
Georg Fritzsche
34.4k34174

You might also consider "duck typing" instead of inheritance.

http://en.wikipedia.org/wiki/Duck_typing

views:668 update:2011/10/5 21:23:48
corona forums © 2003-2011