Allow untrack() in non-reactive scopes

Closes #17
This commit is contained in:
Aaron Smith 2023-09-26 14:11:33 +01:00
parent 71bbaa2092
commit d1f86a3f9e
2 changed files with 13 additions and 11 deletions

View file

@ -9,6 +9,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
### Changed ### Changed
- Reactive scopes created within reactive scopes are now destroyed on rerun. - Reactive scopes created within reactive scopes are now destroyed on rerun.
- `untrack()` can be called outside of reactive scopes.
--- ---

View file

@ -7,21 +7,22 @@ local get_scope = graph.get_scope
local function untrack<T>(source: () -> T): T local function untrack<T>(source: () -> T): T
local scope = get_scope() local scope = get_scope()
if not scope then
throw("cannot untrack in non-reactive scope") if scope then
end; assert(scope) -- sources are only tracked if the node in scope has an effect
local effect = scope.effect
scope.effect = false
-- sources are only tracked if the node in scope has an effect local ok, result = pcall(source)
local effect = scope.effect
scope.effect = false
local ok, result = pcall(source) scope.effect = effect :: () -> ()
scope.effect = effect :: () -> () if not ok then error(result, 0) end
if not ok then error(result, 0) end return result
else
return result return source()
end
end end
return untrack return untrack