Skip to content
Merged
Show file tree
Hide file tree
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
9 changes: 9 additions & 0 deletions src/std/option/init.luau
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,14 @@ local function none(): None
return NONE
end

--- Constructs a new `None` value if the given value is `nil`, Otherwise returns `Some<T>`.
local function from<T>(value: T?): Some<T> | None
return
if value ~= nil
then some(value)
else NONE
end

--- Returns `true` if the option is a `Some` value.
function Option.is_some<T>(self: Option<T>): boolean
return self._is_some
Expand Down Expand Up @@ -206,4 +214,5 @@ return {
is = is;
some = some;
none = none;
from = from;
}
4 changes: 4 additions & 0 deletions tests/std/option/.check.luau
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,7 @@ local some: Option.Some<number> = do_nothing(some_1)
local none: Option.None = do_nothing(none_1)

-- do_nothing(1) -- should error

local some_or_none = Option.from(nil)
-- some = some_or_none -- should error
-- none = some_or_none -- should error
9 changes: 9 additions & 0 deletions tests/std/option/.spec.luau
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,15 @@ test.suite("std.option", function(suite)
asserts.eq(Option.is("some"), false)
end)

suite:case(".from", function(asserts)
asserts.eq(Option.from(1):is_some(), true)
asserts.eq(Option.from(1):is_none(), false)
asserts.eq(Option.from(nil):is_some(), false)
asserts.eq(Option.from(nil):is_none(), true)
asserts.eq(Option.is(Option.from(42)), true)
asserts.eq(Option.is(Option.from(nil)), true)
end)

suite:case(":is_some_and", function(asserts)
local even = function(n: number) return n % 2 == 0 end

Expand Down