Skip to content

Instantly share code, notes, and snippets.

@helloj
Last active September 5, 2022 13:39
Show Gist options
  • Save helloj/e4e9a50e3235dd4308210c3d1011ac68 to your computer and use it in GitHub Desktop.
Save helloj/e4e9a50e3235dd4308210c3d1011ac68 to your computer and use it in GitHub Desktop.
Lua simple class
function simpleclass(base)
return setmetatable(base, {
__call = function(t, ...)
local obj = setmetatable({}, t)
if rawget(t, '__new') then
t.__new(obj, ...)
end
return obj
end
})
end
nn = simpleclass({
-- constructor
__new = function(self, name1)
print("__new"..name1)
self:m1()
end,
-- destructor
__gc = function(self)
print("run __gc")
end,
-- metamethods
__len = function(self)
print("run __len")
return 100
end,
__tostring = function(self)
print("run __tostring")
return "nn"
end,
-- class methods, properties
class_p1 = 123,
class_m1 = function()
print("class_m1")
end,
-- methods, properties
__index = {
p1 = 'p1p1',
p2 = 'p2p2',
m1 = function(self)
print("m1")
nn.class_m1()
end,
}
})
aa = nn('aaa')
print(aa, #aa)
print(aa.p1, aa.m1, aa:m11())
print(nn.class_p1, nn.class_m1())
print(nn.m1) -- m1 is object method, invisit in class
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment