尝试使用Lua元表进行索引?

以下是我写的一些代码:

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

function fileSys()
  local fileAction, code
  print("文件系统")
  print("你当前在"..current_window.."窗口中")
  while true do
    print("1 创建新的文件夹\n2 打开对象\n3 删除对象\n4 创建新的文本文件\n5 其他选项")
    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元方法会没有错误,但它仍然抛出了“尝试调用字段?”错误。我猜测它仍然会抛出错误,所以是否有一种方法可以使用“pcall()”捕捉它呢?

mt看起来像这样:

local mt = { __index = invalid }

而invalid是这样的:

function invalid()
  print("不合法的操作数,请重试。")
end

只有当用户输入未列在表中的操作数时才会抛出此错误(input > #fileFunc)。

点赞
用户646619
用户646619

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

因此执行 fileFunc [fileAction] 将打印“无效的操作数,请重试。”,但程序将继续运行并且索引的结果将是nil

与设置具有 __index 并抛出和捕获错误的 metatable 不同,最简单的方法是仅检查 nil

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