Pcall doesn't allow function to continue? (SOLVED)

In the screenshot, I am currently using pcall as a filter. I have two GUI scenes which use this function to test a list for a match. In order to separate the two and have it not throw errors at the rest of the code, I’m using pcall to stop it when it’s about to be run through the wrong scene.

“glue” is run without errors when running without pcall, as well as with it. The problem is that it doesn’t “PASS” when the pcall doesn’t throw errors. From what I know, pcall will still throw errors into the editor, but it will also return “false” to state there was an error. Is this correct?

I’ve set it to “false” and it works correctly, but since it’s throwing an error (apparently) that would just let UI run as well, which is what I’m trying to avoid, because UI is also returning an error.

Would there be a simpler way for this, or how would I use this function properly?

Yes, if the function that is called in protected mode generates an error it will be returned as false + error message from pcall().

By looking at your snippet of code I see a couple of different things that I’m curious to know more about:

1 - The UIModules.lua doesn’t like like the classic version of a Lua module since it declares a bunch of global functions. The typical behaviour (but not the only one ofc) is to have the Lua module return a module table, like this:

--- UIModules.lua

local M = {}    -- our module table

function M.scene_check(i, t)
   --- do stuff
end

function M.gui_click(self, action_id, action)
   -- do more stuff
   if pcall(M.scene_check) == true then
       print("passed")
   end
end

return M

Aaaaaand as I’m writing this I see what’s wrong in your code. pcall() works like this:

pcall(fn, arg1, ...)

It’s first argument should be a function and the second and onwards the arguments to that function when it is called in protected mode. This means that your line of code is wrong. You’re doing:

pcall(scene_check(i))

Which is actually making a function call and whatever is returned from that function call is passed into pcall as arguments. And since that fails the pcall will never actually be run (and if it was it wouldn’t work anyway). What you want to do is this:

pcall(scene_check, i)
4 Likes

Thank you! Looking at your example, I can see why this would be a much less confusing way to write a Lua module. I simply wrote it with global functions to be pulled by multiple scripts, and didn’t even think of storing them in a table so that they wouldn’t occasionally get confused with other local functions. I’ll most definitely use this tactic.

:man_facepalming: Well, I got close :wink: . Thanks again @britzl.

2 Likes