我一直在研究这个元表,这个错误是最难修复的:
local Check = {
InvitedMembers = {
John = "Allowed",
Mary = "Allowed",
Halley = "Allowed"
}
}
local Filter = {
__index = function(t,k)
for i ,v in pairs(t.InvitedMembers) do
if i ~= k then
error("You're not invited by us")
elseif i == k then
return "This way"
end
end
end
}
local ConnectFilter = setmetatable(Check,Filter)
print(Check.InvitedMembers.Sans)
我尝试创建一个过滤器,但是此代码返回一个 nil
值。
最佳答案
您的代码中有两个错误:
您正在为错误的表编制索引
您在 Check
上调用 setmetatable
,而不是在 Check.InvitedMembers
上调用。因此,要修复您的代码,您可以编写
print(Check.Sans)
并且您会收到错误“我们没有邀请您”
您太早抛出错误
在循环中,您要么返回
,要么抛出错误,因此您将永远无法通过第一次迭代。
如果你想修复循环,你必须这样写:
for i ,v in pairs(t.InvitedMembers) do
if i == k then
return "This way"
end
end
error("You're not invited by us")
也就是说,遍历列表并在找到名称时立即返回,但在完成整个列表之前不要出错。
但解决此问题的更好方法是简单地执行以下操作:
local Filter = {
__index = function(t,k)
if t.InvitedMembers[k] then
return "This way"
else
error("You're not invited by us")
end
end
}
由于使用没有的键对表进行索引只会返回 nil
,因此您可以轻松找出表中是否存在键。
关于lua - 调试元表脚本中的意外空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60167732/