1

So here is some code I wrote up:

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

I thought that by using the __index metamethod, there would be no errors, but it still throws an attempt to call field ? error. I'm guessing that it still throws the error, so is there a way I can catch it using pcall()

mt looks like this:

local mt = { __index = invalid }

And invalid:

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

This error is only thrown when the user enters an operand that is not listed in the table (input > #fileFunc)

Lee Yi
  • 517
  • 6
  • 17

1 Answers1

3

invalid doesn't return anything, but it doesn't stop the program either. If you try to get a result from a function that doesn't return anything, you get nil instead.

So doing fileFunc[fileAction] will print "Invalid operand, please try again.", but the program will keep going and the result of the index will be nil.

Instead of setting a metatable with an __index and throwing and catching an error, it's much simpler to just check for nil:

if not fileFunc[fileAction] then
    print("Invalid operand, please try again.")
else
    local result = fileFunc[fileAction]()
    -- Do something
end
Colonel Thirty Two
  • 23,953
  • 8
  • 45
  • 85
  • Might be worth adding that when `__index` is set to a function, that function is called in order to determine the result of the indexing. So what `fileFunc[someInvalidIndex]()` does, is actually: `invalid(someInvalidIndex)()`, NOT `invalid()`! – Henrik Ilgen Mar 10 '15 at 08:52