Skip to content

Commit

Permalink
Make context functions return result
Browse files Browse the repository at this point in the history
  • Loading branch information
centau committed Oct 9, 2024
1 parent 1d56526 commit 6ead930
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 3 deletions.
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

### Added
Expand Down
6 changes: 4 additions & 2 deletions src/context.luau
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ local push_scope = graph.push_scope
local pop_scope = graph.pop_scope
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 count = 0
Expand All @@ -21,7 +21,7 @@ local function context<T>(...: T): Context<T>
local has_default = select("#", ...) > 0
local default_value = ...

return function(...)
return function<T>(...): any -- todo: fix type error
local scope: Node<unknown>? | false = get_scope()

if select("#", ...) == 0 then -- get
Expand Down Expand Up @@ -66,6 +66,8 @@ local function context<T>(...: T): Context<T>
if not ok then
throw(`error while running context:\n\n{result}`)
end

return result
end

return nil :: any
Expand Down
4 changes: 3 additions & 1 deletion test/tests.luau
Original file line number Diff line number Diff line change
Expand Up @@ -2192,10 +2192,12 @@ TEST("context()", function()
CHECK(ctx() == 1)

root(function()
ctx(2, function()
local v = ctx(2, function()
CHECK(ctx() == 2)
return ctx()
end)

CHECK(v == 2)
CHECK(ctx() == 1)
end)
end
Expand Down

0 comments on commit 6ead930

Please sign in to comment.