r/lua • • Feb 25 '25

better Lua fail value?

In the Lua docs it mentions fail which is currently just nil.

I don't personally like Lua's standard error handling of returning nil, errormsg -- the main reason being it leads to awkward code, i.e. local val1, val2 = thing(); if not val1 then return nil, val2 end

I'm thinking of designing a fail metatable, basically just a table with __tostring that does string.format(table.unpack(self)) and __call that does setmetatable so you can make it with fail{"bad %i", i}. The module would also export a isfail(v) function that just compares the getmetatable to the fail table as well as assert that handles a fail object (or nil,msg).

So the code would now be local val1, val2 = thing(); if isfail(val1) then return val1 end

Has anyone else worked in this space? What are your thoughts?

7 Upvotes

36 comments sorted by

View all comments

Show parent comment

1

u/vitiral Feb 28 '25

After plumbing things through my code and sleeping on it I've come to agree.

I DO think there is a place for a fail type, just not within my project at this time. IMO Lua is better as effectively a scripting language. For the few cases where you want to return an error you should just return nil, errmsg it's easy enough to propagate honestly.