1
votes

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)

1

1 Answers

3
votes

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