Quick Links: Download Gideros Studio | Gideros Documentation | Gideros community chat | DONATE
Metamethods inheritance — Gideros Forum

Metamethods inheritance

rrraptorrrraptor Member
edited July 2020 in General questions
Is there a way to make this work:
local Foo = Core.class()
 
function Foo:__call(a, b)
	return a + b
end
 
local Bar = Core.class(Foo)
 
local foo = Foo.new()
local bar = Bar.new()
 
print(foo(10, 20)) --< OK
print(bar(10, 20)) --< error
Meta function are not inherited?

Comments

  • hgy29 said:
    Didn't help much :smile:

    I came up with another solution. Not the best, but it works :)
    local Foo = Core.class()
    --
    function Foo:postInit()	
    	local mt = getmetatable(self)
    	mt.__call = function(self, a, b)
    		return "base call", a + b
    	end
    	setmetatable(self, mt)
    end
     
    local Bar = Core.class(Foo)
     
    function Bar:postInit()	
    	local mt = getmetatable(self)
    	mt.__call = function(self, a, b)
    		return "overridden", a * b
    	end
    	setmetatable(self, mt)
    end
     
    local foo = Foo.new()
    local bar = Bar.new()
     
    print(foo(10, 20)) --< 30
    print(bar(10, 20)) --< 200
  • rrraptorrrraptor Member
    edited July 2020
    Better solution:
    -- since I have custom methods that starts from "__" I need to reject them
    local metamethods = { "__add","__call","__concat","__div","__le","__lt","__mod","__mul","__pow","__sub","__tostring","__unm" } 
     
    local Foo = Core.class()
     
    function Foo:postInit()
    	local mt = getmetatable(self)
    	for _,k in ipairs(metamethods) do
    		if (not rawget(self,k) and self[k]) then
    			mt[k] = self[k]
    		end
    	end
    end
     
    function Foo:__call(a, b)
    	return a + b
    end
     
    local Bar = Core.class(Foo)
     
    --[[ can be overridden
    function Bar:__call(a, b)
    	return a * b
    end
    --]]
     
    local foo = Foo.new()
    local bar = Bar.new()
     
    print(foo(10, 20)) --< 30
    print(bar(10, 10)) --< 20
Sign In or Register to comment.