Yuescript
Yuescript copied to clipboard
[Feature request] Better semantics for try/catch
Note: this is a breaking change!
I would like to see the semantics of try/catch be changed to make it (in my opinion) more useful.
I think that
x = try
do_something()
catch err
handle_error(err)
should be changed from compiling to
local x = xpcall(function()
return do_something()
end, function(err)
return handle_error(err)
end)
into compiling to this:
local x = select(2, xpcall(function()
return do_something()
end, function(err)
return handle_error(err)
end))
The addition of select(2, [...]) causes the boolean that's normally returned by xpcall() to be skipped. This would feel more natural to use in many cases, and allow for patterns like this:
x = (try maybe_failing_operation()) ?? "default"
The expression:
x = select(2, try maybe_failing_operation!) ?? 'default'
won’t work as expected, because Lua’s pcall / xpcall return two values: (true, result) on success, or (false, errorMessage) on failure.
A more accurate and idiomatic pattern for now would be:
x = res if ok, res := try maybe_failing_operation!
x ??= 'default'
To make this cleaner, I propose introducing a try! syntax:
x, y = try! maybe_failing_operation!
This could expand to:
x, y = res1, res2 if ok, res1, res2 := try maybe_failing_operation!
This keeps the original try semantics intact while offering a more ergonomic opt-in for common use cases.