Throw/Catch in lua?

In C++ there are these things called through and catch. Suppose we wanted to do something but wanted to pause the code and run some other thing incase it errored.

#import <iostream>
using namespace std;
int main() {
  string inp;
  while (true) {
    try {
      cout << "Input number: " << endl;
      cin >> inp;
      int out = stoi(inp); --This is like tonumber() for you guys
      cout << to_string(inp) << endl;
      exit(0);
} catch(exception) {
      cout << "Please enter a number." << endl;
}
}
return 0;
}

My question is, is there a way to catch errors and run code like this in lua?

pcall is probably what you’re looking for. Not sure if it’s exactly the same for your use case but it’s similar.

local state, error_message = pcall(function() x += 2 end) --//x is undefined so this will error end)

if not state then --//state is true/false depending on if this protected call ran without error
print(error_message)
end

Does pcall() run code before in the pcall after a line it has errored?

It runs the given function in protected mode, which prevents errors from affecting the thread that called the pcall.

If it errors I believe it’ll stop executing the function at the line of the error, it just won’t affect the main thread at all so it will keep running

1 Like