Code: Select all
local baseclass
local function newclass(parent, ...)
local t = setmetatable( {
__call = function(t, ...)
return newclass(t, ...)
end
}, parent )
t.__index = t
local init = t.init
if init then init(t, ...) end
return t
end
baseclass = newclass
{
__call = function(t, ...)
return newclass(t, ...)
end
}
return baseclass
Code: Select all
local animal = class()
function animal:init(sound)
self.sound = sound
end
function animal:makesound()
print(self.sound)
end
function animal:walk()
print("Step, step, step...")
end
local dog = animal()
function dog:makesound()
print("BARK! "..self.sound)
end
function dog:jump()
print("I see my house from up here!")
end
local maddog = dog()
function maddog:makesound()
print("RAAH! BARK! "..self.sound)
end
function maddog:explode()
print("BOOM!")
end
local inst1 = animal("Hi!")
inst1:makesound() -- Hi!
-- inst1:jump() -- Crash: undefined.
local inst2 = dog("Bye!")
inst2:makesound() -- BARK! Bye!
inst2:jump() -- I see my house from up here!
local inst3 = maddog("Hey!")
inst3:makesound() -- RAAH! BARK! Bye!
inst3:explode() -- BOOM!
inst3:jump() -- I see my house from up here!
local inst4 = animal("Hello!")
inst4:makesound() -- Hello!
inst1:makesound() -- Hi!
Code: Select all
local c = class()
c.staticfield = 1
function c:updatestatic()
c.staticfield = 2
end