【问题标题】:Lua Metatables Attempt to Index?Lua Metatables 尝试索引?
【发布时间】:2015-03-09 22:32:59
【问题描述】:

所以这是我写的一些代码:

local fileFunc = {createFolder, openObj, deleteObj, createTxt, theMenu}
setmetatable(fileFunc, mt)

function fileSys()
  local fileAction, code
  print("The File System")
  print("You are currently at "..current_window)
  while true do
    print("1 Create a new Folder\n2 Open an object\n3 Delete an Object\n4 Create a new text file\n5 Other options")
    fileAction = userInInt()
    code = fileFunc[fileAction]()
    if code > 3 then invRet("fileSys()", code) end
    if code == 1 then return 0
    else return code end
  end
end

我以为通过使用__index 元方法,不会有错误,但它仍然会抛出attempt to call field ? 错误。我猜它仍然会抛出错误,所以有没有办法可以使用pcall()

mt 看起来像这样:

local mt = { __index = invalid }

而且无效:

function invalid()
  print("Invalid operand, please try again.")
end

此错误仅在用户输入未在表中列出的操作数时引发 (input > #fileFunc)

【问题讨论】:

    标签: lua metatable


    【解决方案1】:

    invalid 不返回任何内容,但也不会停止程序。如果您尝试从不返回任何内容的函数中获取结果,则会得到 nil

    所以fileFunc[fileAction] 会打印"Invalid operand, please try again.",但程序会继续运行,索引的结果将是nil

    与其使用__index 设置元表并抛出和捕获错误,不如只检查nil 更简单:

    if not fileFunc[fileAction] then
        print("Invalid operand, please try again.")
    else
        local result = fileFunc[fileAction]()
        -- Do something
    end
    

    【讨论】:

    • 可能值得补充的是,当__index 设置为函数时,会调用该函数以确定索引的结果。那么fileFunc[someInvalidIndex]() 所做的实际上是:invalid(someInvalidIndex)(),而不是 invalid()
    猜你喜欢
    • 1970-01-01
    • 2015-10-25
    • 2011-11-05
    • 2019-03-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-04
    • 1970-01-01
    • 2019-08-21
    相关资源
    最近更新 更多