Forest Logo
search
package_2

result

By @xonae

Roblox

Mirrored from Wally

Result

A lightweight functional-style Result implementation based off of Rust's Result type.

Inspired by this amazing port from Nightcycle. My variant was made to leverage the functional-style paradigm that I find myself using more and more these days.

Usage

-- create an ok result
local ok = Result.ok(10)

-- create an err result
local err = Result.err("not a number")

-- check if a result is ok
local isOk = Result.isOk(ok)

-- check if a result is err
local isErr = Result.isErr(err)

-- get the ok value. throws the err value if the result is err
local value = Result.unwrap(ok)

-- get the err value. throws if the result is ok
local reason = Result.unwrapErr(err)

-- get the ok value, or a fallback if the result is err
local valueOrZero = Result.unwrapOr(err, 0)

-- get the ok value, or compute a fallback from the err value
local valueOrLength = Result.unwrapOrElse(err, function (message: string)
    return #message
end)

-- get the ok value, throws "amount was invalid: not a number" if the result is err
local expected = Result.expect(ok, "amount was invalid")

-- get the ok value, or nil if the result is err
local maybeValue = Result.asNullable(err)

-- run one callback for ok and another for err, then get the output
local text = Result.match(ok, function (amount: number)
    return `got {amount}`
end, function (message: string)
    return `failed: {message}`
end)

-- run a callback on the ok value, if any
Result.inspect(ok, function (amount: number)
    print(amount)
end)

-- run a callback on the err value, if any
Result.inspectErr(err, function (message: string)
    print(message)
end)

-- change the ok value. an err result passes through
local doubled = Result.map(ok, function (amount: number)
    return amount * 2
end)

-- change the err value. an ok result passes through
local detailed = Result.mapErr(err, function (message: string)
    return `parse failed: {message}`
end)

-- run a step that can fail on the ok value. the output type can change
local asText = Result.andThen(ok, function (amount: number)
    return if amount > 0 then Result.ok(tostring(amount)) else Result.err("not positive")
end)

-- run many steps that can fail. stops at the first err
local checked = Result.chain(ok, function (amount: number)
    return if amount > 0 then Result.ok(amount) else Result.err("not positive")
end, function (amount: number)
    return if amount % 1 == 0 then Result.ok(amount) else Result.err("not whole")
end)

Installation

Wally

[dependencies]
Result = "xonae/result@1.0.0"

Everything Else

You can also manually copy the source from src/init.luau into a ModuleScript or file.

Package Details

Install command (Click to copy)


Version

1.0.0

License

MIT

check_circle

Safe for commercial use

Automated license review — not legal advice.