3 ms·
Lua uses this to handle errors---I don't find it really tedious. A common pattern is kind of the same---to return either one return value and nil and then an er
by thegeomaster 12y ago
Lua uses this to handle errors---I don't find it really tedious. A common pattern is kind of the same---to return either one return value and nil and then an error message or an error code (Lua, like Go, has multiple returns) in case of errors. This results in code like
let res, err = some_function()
if res == nil then -- you can also check for err ~= nil like in Go
-- return from this function with something, err contains more
-- information
end
I think it's very neat---you can also return nil, err from this function if you can't deal with it and some code up the stack should be able to handle it in a meaningful manner. I don't find it particularly tedious; i.e. not less tedious than writing try..catch blocks, and you can clearly see where are the function exit points, whereas with exceptions, any line can theoretically throw an exception. A missed error check can be troublesome, but generally using nil as a value further down in the function will hopefully trigger another error which might be then caught so you can spot the bug.
Lisp's continuations are also IMHO a great mechanism---you catch the error and then you can tell the function down the stack what it should do: you can abort, or you can try fixing the error and continuing, or you can try again for some number of times and then report a new error if that fails. It's more flexible than stuff I've heard of before.
- shiro 12y agoJust curious---doesn't that pattern inhibit you to return nil as a meaningful, valid result? Or is nil treated as invalid value in Lua culture?
- kazagistar 12y agoNeither. It just basically never happens that you want both error reporting and a maybe (nil or value) from the same function. Not in list? Nil. Could not parse? Nil. Iteration ended? Nil.