# HG changeset patch # User Matthew Wild # Date 1521705361 0 # Node ID 9246f64d6f1e6da8463175e03215e7dd9a27b07f # Parent ca710a71d730f6ba4bd8fd013cb9db7ab7979d47 util.async: Add once() to create temporary runners diff -r ca710a71d730 -r 9246f64d6f1e spec/util_async_spec.lua --- a/spec/util_async_spec.lua Thu Mar 22 07:46:23 2018 +0000 +++ b/spec/util_async_spec.lua Thu Mar 22 07:56:01 2018 +0000 @@ -593,4 +593,14 @@ assert.spy(r.watchers.error).was_not.called(); end); end); + + describe("#once()", function () + it("should work", function () + local f = spy.new(function () + assert.truthy(async.ready()); + end); + async.once(f); + assert.spy(f).was.called(); + end); + end); end); diff -r ca710a71d730 -r 9246f64d6f1e util/async.lua --- a/util/async.lua Thu Mar 22 07:46:23 2018 +0000 +++ b/util/async.lua Thu Mar 22 07:56:01 2018 +0000 @@ -219,4 +219,24 @@ return pcall(checkthread); end -return { ready = ready, waiter = waiter, guarder = guarder, runner = runner }; +local once; -- forward declaration +do + local once_watchers = { + error = function (_, err) + error(err); + end; + }; + local function once_runner(func) func(); end + function once(func) + local r = runner(func, once_watchers); + return r:run(func); + end +end + +return { + once = once; + ready = ready; + waiter = waiter; + guarder = guarder; + runner = runner +};