>>109231461
I just recently looked into Lua because I got interested into prototype based OOP languages like self and io and to me their object model implementation makes more sense than a class-instance based one
Lua is already similar in terms of delegation to prototype OOP and it's really easy to implement it under Lua. I asked chatgpt to write a simple library and seems to work pretty fine, at least for toying around
-- object.lua
local Object = {}
local Meta = {}
local function lookup(self, key)
local value = rawget(self, key)
if value ~= nil then
return value
end
local proto = rawget(self, "__proto")
if proto then
return lookup(proto, key)
end
end
Meta.__index = function(self, key)
local value = lookup(rawget(self, "__proto"), key)
if value ~= nil then
return value
end
local forward = lookup(self, "forward")
if forward then
return forward(self, key)
end
end
function Object:clone(slots)
local obj = slots or {}
rawset(obj, "__proto", self)
return setmetatable(obj, Meta)
end
function Object:proto()
return rawget(self, "__proto")
end
function Object:slotNames()
local names = {}
for name in pairs(self) do
if name ~= "__proto" then
names[#names + 1] = name
end
end
return names
end
function Object:forward(name)
error("message not understood: " .. tostring(name), 2)
end
setmetatable(Object, Meta)
return Object
So I can do
local Animal = Object:clone {
speak = function()
print(self.sound .. "!")
end
}
local Dog = Animal:clone {
sound = "woof"
}
Dog:speak()