Recreating class objects from Python
Features:
- Similar to Python
- Easy to add in project: just copy paste the code
- Supports class extending
Examples:
entity = class()
entity.init = function(self)
self.pos = { 0, 0, 0 }
self.rot = { 0, 0, 0 }
end
entity.print = function(self)
print("Entity info:", self.pos, self.rot)
end
animal = class(entity)
animal.init = function(self, sound)
entity.init(self)
self._sound = sound
end
animal.sound = function(self)
print(self._sound)
end
cat = animal("meow")
cat:print()
cat:sound()
Code:
function class_copy(obj, seen)
if type(obj) ~= "table" then return obj end if seen and seen[obj] then return seen[obj] end local s = seen or {} local res = {} s[obj] = res for k, v in pairs(obj) do res[class_copy(k, s)] = class_copy(v, s) end return res
end
class = function(original)
local t = {}
local _mt
if original == nil then
_mt = {
__call = function(self, ...)
local obj = class_copy(self)
if obj.init ~= nil then
obj:init(...)
end
return obj
end,
}
else
_mt = {
__call = function(self, ...)
local obj = class_copy(self)
for key, value in pairs(original) do
if self[key] == nil then
obj[key] = value
end
end
if obj.init ~= nil then
obj:init(...)
end
return obj
end,
}
end
return setmetatable(t, _mt)
end