Last active
November 30, 2022 02:55
-
-
Save hoelzro/5883621 to your computer and use it in GitHub Desktop.
Multiple inheritance in Lua
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local Mom = {} | |
local Dad = {} | |
local Child = {} | |
function Mom:work() | |
print "I'm a particle physicist!" | |
end | |
function Dad:work() | |
print "I'm a computer guy!" | |
end | |
local parents = { Mom, Dad } | |
local rawset = rawset | |
local cache_mt = {} | |
function cache_mt:__index(key) | |
for i = 1, #parents do | |
local parent = parents[i] | |
local value = parent[key] | |
if value ~= nil then | |
rawset(self, key, value) | |
return value | |
end | |
end | |
end | |
local cache = setmetatable({}, cache_mt) | |
setmetatable(Child, { __index = cache }) | |
Child:work() | |
Child:work() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment