Skip to content

Add result to @batteries #159

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
May 4, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions batteries/result.luau
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
type T<Value> = | { success: true, value: Value } | { success: false, traceback: string, err: string }

local result = {}

function result.ok<Value>(value: Value): T<Value>
return {
success = true,
value = value,
}
end

function result.fail<Value>(err: string): T<Value>
-- Ignore the current call to debug.traceback, and the call to fail.
local traceback = debug.traceback(nil, 2)

return {
success = false,

traceback = traceback,
err = err,
}
end

function result.pcall<R, T...>(f: (T...) -> R, ...: T...): T<R>
local success, value = pcall(f, ...)

if success then
return result.ok(value)
else
local err = value :: any

return result.fail(err)
end
end

return result