[英]attempt to call method 'func' (a nil value)
无论我如何接近Lua,我都会遇到这个错误,所以我不能理解继承语言的东西:
尝试调用方法'func'(零值)
我已经在这里看过几次这个错误,但这个问题对我来说似乎并不清楚。
这是我的模块:
actor.lua
Actor = {
x = 0,
mt = {},
new = function()
local new_actor = {}
new_actor.x = Actor.x
new_actor.mt = Actor.mt
return new_actor
end,
test = function(self, a, b)
print(a, b)
end
}
我正在使用Löve。
main.lua
require "game/actor"
local a = Actor:new() --works fine
function love.load()
a.x = 10
print(a.x) --output: 10
a:test(11, 12) --error: attempt to call method 'test' (a nil value)
end
我也不确定何时在模块中使用之前的样式是合适的。
Actor = {
x = 0
}
Actor.mt = {}
function Actor.new()
print(42)
end
我老实说不确定什么比另一个更正确,但考虑到我遇到一个简单的错误,可能有些东西我完全错过了?
看起来你正试图用一种由metatables组成的类。 你基本上需要分配new_actor
用的元表Actor.mt
。 (恢复问题:当你索引new_actor
时,在这种情况下你没有索引Actor
)
setmetatable(new_actor, Actor.mt);
即使添加了元表,也只有在将元“__index”事件索引到包含类方法/值的表时才会有效,在这种情况下:
Actor.mt = {
__index = Actor
};
我建议将类方法/值移动到一个新表中,如Actor.prototype
, Actor.fn
等...避免冲突:
Actor.fn = {
test = function(self, a, b)
print(a, b)
end
};
Actor.mt = {
__index = Actor.fn
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.