Willi Ballenthin
Willi Ballenthin

Reputation: 6624

What are idiomatic ways to signal errors in pure Lua?

I'm working on building out a set of common libraries for use with an embedded instances of the Lua interpreter (the target audience is users of a particular product). Assume I have no access to changing the capabilities of the Lua executables, and have only the basic standard Lua libraries (math, string, ..., exception is no io).

What is an idiomatic way for handling runtime errors in the pure Lua libraries?

I've considered returning nil, but this doesn't signal what went wrong, especially if the error occurred somewhere deeply nested. My next thought is to return two values, nil and an error code or description. I've also considered a set of global functions similar to the Windows API's GetLastError (and corresponding, SetError).

What do you use? What do you see as the various pros/cons to the various approaches? Should I consider something more radical like wrapping everything in pcall and intentionally indexing userdata to cause an error?

Upvotes: 3

Views: 257

Answers (1)

lhf
lhf

Reputation: 72422

Errors that cannot be recovered from should just abort execution. For those, call error. Otherwise, returning nil or false and an error message is the standard Lua way.

Upvotes: 7

Related Questions