2024-04-01 07:07:43 +01:00
|
|
|
local Option = {}
|
|
|
|
export type Option<T> = typeof(Option) & {
|
2024-04-01 07:35:59 +01:00
|
|
|
_optValue: T?,
|
|
|
|
typeId: "Option",
|
2024-04-01 07:07:43 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
function None<T>(): Option<T>
|
2024-04-01 07:35:59 +01:00
|
|
|
return Option.new(nil) :: Option<T>
|
2024-04-01 07:07:43 +01:00
|
|
|
end
|
|
|
|
|
|
|
|
function Some<T>(val: T): Option<T>
|
2024-04-01 07:35:59 +01:00
|
|
|
return Option.new(val) :: Option<T>
|
2024-04-01 07:07:43 +01:00
|
|
|
end
|
|
|
|
|
|
|
|
function Option.new<T>(val: T?)
|
2024-04-01 07:35:59 +01:00
|
|
|
return setmetatable(
|
|
|
|
{
|
|
|
|
_optValue = val,
|
|
|
|
typeId = "Option",
|
|
|
|
} :: Option<T>,
|
|
|
|
{
|
|
|
|
__index = Option,
|
|
|
|
__tostring = function<T>(self: Option<T>)
|
|
|
|
-- TODO: Return formatted enum variants too
|
2024-04-01 07:07:43 +01:00
|
|
|
|
2024-04-01 07:35:59 +01:00
|
|
|
if self._optValue == nil then
|
|
|
|
return `{self.typeId}::None`
|
|
|
|
else
|
|
|
|
return `{self.typeId}::Some({self._optValue})`
|
|
|
|
end
|
|
|
|
end,
|
|
|
|
}
|
|
|
|
)
|
2024-04-01 07:07:43 +01:00
|
|
|
end
|
|
|
|
|
|
|
|
return {
|
2024-04-01 07:35:59 +01:00
|
|
|
-- TODO: Implement Option utility methods
|
|
|
|
Option = Option,
|
|
|
|
Some = Some,
|
|
|
|
None = None,
|
|
|
|
}
|