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条)