尝试调用方法 'func'(零值)
attempt to call method 'func' (a nil value)
无论我如何处理 Lua,我总是 运行 遇到这个错误,所以我一定不明白语言继承的东西:
attempt to call method 'func' (a nil value)
我也在这里看到过几次错误,但问题对我来说似乎不太清楚。
这是我的模块:
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
老实说,我不确定哪个更正确,但考虑到我 运行 无论如何都犯了一个简单的错误,我可能完全遗漏了什么?
您似乎在尝试实例化一种由 metatable 构成的 class。您基本上需要将 new_actor
的元 table 分配给 Actor.mt
。 (恢复问题:当您索引 new_actor
时,在这种情况下您没有索引 Actor
)
setmetatable(new_actor, Actor.mt);
即使正在添加元table,它也不会起作用,直到您将元“__index”事件放入索引包含您的[=31=的table ] methods/values,在这种情况下:
Actor.mt = {
__index = Actor
};
我建议将您的 class methods/values 移动到新的 table,例如 Actor.prototype
、Actor.fn
等...避免冲突:
Actor.fn = {
test = function(self, a, b)
print(a, b)
end
};
Actor.mt = {
__index = Actor.fn
};
无论我如何处理 Lua,我总是 运行 遇到这个错误,所以我一定不明白语言继承的东西:
attempt to call method 'func' (a nil value)
我也在这里看到过几次错误,但问题对我来说似乎不太清楚。
这是我的模块:
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
老实说,我不确定哪个更正确,但考虑到我 运行 无论如何都犯了一个简单的错误,我可能完全遗漏了什么?
您似乎在尝试实例化一种由 metatable 构成的 class。您基本上需要将 new_actor
的元 table 分配给 Actor.mt
。 (恢复问题:当您索引 new_actor
时,在这种情况下您没有索引 Actor
)
setmetatable(new_actor, Actor.mt);
即使正在添加元table,它也不会起作用,直到您将元“__index”事件放入索引包含您的[=31=的table ] methods/values,在这种情况下:
Actor.mt = {
__index = Actor
};
我建议将您的 class methods/values 移动到新的 table,例如 Actor.prototype
、Actor.fn
等...避免冲突:
Actor.fn = {
test = function(self, a, b)
print(a, b)
end
};
Actor.mt = {
__index = Actor.fn
};