Lua Objektorientierung
From Ghoulwiki
-- creates a new class, optionally derived from a parentclass
function CreateClass(parentclass_or_nil)
local p = parentclass_or_nil and setmetatable({},parentclass_or_nil._class_metatable) or {}
p.New = CreateClassInstance
p._class_metatable = { __index=p }
p._parent_class = parentclass_or_nil
return p
end
-- creates a class instance and calls the Init function if it exists with the given parameter ...
function CreateClassInstance(class, ...)
local o = setmetatable({},class._class_metatable)
if o.Init then o:Init(...) end
return o
end
cObjBase = CreateClass()
-- konstruktor
function cObjBase:Init (a)
self.x = 5+a
end
function cObjBase:MyMethod ()
print("MyMethod:",self.x)
end
local o = cObjBase:New(3)
o:MyMethod() -- ausgabe : MyMethod: 8