lua - 调试元表脚本中的意外空值

标签 lua

我一直在研究这个元表,这个错误是最难修复的:

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/

相关文章:

ruby-on-rails - Lua 在 Rails 上?

lua - NeoVim中如何获取window的所有属性?

function - 如何在Lua中将函数作为参数传递?

string - 使用 Lua 从 URL 获取文件名

c - luasocket.c :20:17: error: lua. h: 没有那个文件或目录

serialization - 如何在没有外部库的任何lua中将 double 转换为小字符串表示而不会丢失数据?

具有可变数量键的 Lua 访问表

LuaJIT 和 FFI : How to use char* properly?

c++ - lua数组转换成c++数组

Lua字符串,在每个备用索引处插入一个整数