Make context functions return result

This commit is contained in:
aaron 2024-10-09 02:12:25 +01:00
parent 1d565262e1
commit 6ead93088a
3 changed files with 15 additions and 3 deletions

View file

@ -6,6 +6,14 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
-------------------------------------------------------------------------------- --------------------------------------------------------------------------------
## Unreleased
### Added
- Context functions now also return results.
--------------------------------------------------------------------------------
## [0.3.0] - 2024-10-06 ## [0.3.0] - 2024-10-06
### Added ### Added

View file

@ -9,7 +9,7 @@ local push_scope = graph.push_scope
local pop_scope = graph.pop_scope local pop_scope = graph.pop_scope
local set_context = graph.set_context local set_context = graph.set_context
export type Context<T> = (() -> T) & ((T, () -> ()) -> ()) export type Context<T> = (() -> T) & (<U>(T, () -> U) -> U)
local nil_symbol = newproxy() local nil_symbol = newproxy()
local count = 0 local count = 0
@ -21,7 +21,7 @@ local function context<T>(...: T): Context<T>
local has_default = select("#", ...) > 0 local has_default = select("#", ...) > 0
local default_value = ... local default_value = ...
return function(...) return function<T>(...): any -- todo: fix type error
local scope: Node<unknown>? | false = get_scope() local scope: Node<unknown>? | false = get_scope()
if select("#", ...) == 0 then -- get if select("#", ...) == 0 then -- get
@ -66,6 +66,8 @@ local function context<T>(...: T): Context<T>
if not ok then if not ok then
throw(`error while running context:\n\n{result}`) throw(`error while running context:\n\n{result}`)
end end
return result
end end
return nil :: any return nil :: any

View file

@ -2192,10 +2192,12 @@ TEST("context()", function()
CHECK(ctx() == 1) CHECK(ctx() == 1)
root(function() root(function()
ctx(2, function() local v = ctx(2, function()
CHECK(ctx() == 2) CHECK(ctx() == 2)
return ctx()
end) end)
CHECK(v == 2)
CHECK(ctx() == 1) CHECK(ctx() == 1)
end) end)
end end