1

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

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)

4

1 回答 1

3

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

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

与其使用 an 设置元表__index并抛出和捕获错误,不如只检查以下内容要简单得多nil

if not fileFunc[fileAction] then
    print("Invalid operand, please try again.")
else
    local result = fileFunc[fileAction]()
    -- Do something
end
于 2015-03-09T14:32:59.083 回答