oop - lua: attempt to call field 'run' (a table value) - Stack Overflow

engine.lua and car.lua are two modules. car accesses engine and provides access of it's state to e

engine.lua and car.lua are two modules. car accesses engine and provides access of it's state to engine using dependency injection. engine.lua on require statements uses different metatable than when later called with new().

engine.lua

-- engine.lua:

local Engine = {}
Engine.__index = Engine
Engine.__call = Engine.run

Engine.new = function(car)
    -- for dependency injection
    Engine.car = car
    local self = setmetatable({}, Engine)
    return self
end

Engine.run = function(self, opts) 
    print(self.car.name)
end

return setmetatable(Engine, { __call = Engine.new })

car.lua:

-- car.lua

local Car = {name = "ferrari"}
local Engine = require('engine') 
-- since in metatable __call = Engine.new

Car.run = Engine(Car)

-- now Engine is metatable for new object
-- so __call = Engine.run
local opts = {}
Car.run(opts)

when I run car.lua, I get: attempt to call field 'run' (a table value). On printing metatable of Car.run I see there is no __call method in metatable. Shouldn't it be there, since it is a key of Engine? why am I not able to call it?

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744846089a4596845.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信