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

でメタテーブルを設定し、エラーをスローしてキャッチする代わりに、__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 に答える