in Lua we do OO programming like this:
MyClass = {}
function MyClass:new()
local obj = {}
setmetatable(obj, self)
self.__index = self
obj.hello = "hello world"
return obj
end
function MyClass:sayHi()
print(self.hello)
end
function main()
local obj = MyClass:new()
obj:sayHi()
end
When working with more compelx stuff, usually I take advantage of Lua's metamethods to proxy function calls and do whatever I need with it, like arguments parsing etc, by adding this:
MyClassMeta = {}
function MyClassMeta.__index(obj, funcName)
return function (self, ...)
//do some stuff
print("you called " .. funcName .. " with args", ...)
end
end
and changing the line:
setmetatable(obj, self)
to:
setmetatable(obj, MyClassMeta)
every function I call with an instance of MyClass
will execute the code implemented in MyClassMeta.__index
metamethod.
What I want to do now is inherit the MyClass
existing methods, and execute MyClassMeta.__index
only for functions that are not part of MyClass
.
In the above example, the code will always execute the MyClassMeta.__index
metamethod even when calling MyClass:sayHi()
:
function main()
local obj = MyClass:new()
obj:sayHi("hello")
end
you called sayHi with args hello