diff --git a/Capy64/Runtime/Libraries/Timer.cs b/Capy64/Runtime/Libraries/Timer.cs index a687d93..35b168e 100644 --- a/Capy64/Runtime/Libraries/Timer.cs +++ b/Capy64/Runtime/Libraries/Timer.cs @@ -14,6 +14,7 @@ // limitations under the License. using Capy64.API; +using Capy64.Runtime.Objects; using KeraLua; using System; using System.Collections.Concurrent; @@ -30,6 +31,11 @@ class Timer : IComponent function = L_StartTimer, }, new() + { + name = "delay", + function = L_Delay, + }, + new() { name = "now", function = L_Now @@ -88,20 +94,49 @@ class Timer : IComponent timer.Elapsed += (o, e) => { - timers.TryRemove(timerId, out _); - - _game.LuaRuntime.QueueEvent("timer", LK => + _game.LuaRuntime.QueueEvent("timer", lk => { - LK.PushInteger(timerId); + lk.PushInteger(timerId); return 1; }); + timers.TryRemove(timerId, out _); }; L.PushInteger(timerId); return 1; } + private static int L_Delay(IntPtr state) + { + var L = Lua.FromIntPtr(state); + + var delay = L.CheckNumber(1); + L.ArgumentCheck(delay > 0, 1, "delay must be greater than 0"); + + var task = TaskMeta.Push(L, "timer"); + + var timerId = _timerId++; + var timer = new System.Timers.Timer + { + AutoReset = false, + Enabled = true, + Interval = delay, + }; + + timers[timerId] = timer; + + timer.Elapsed += (o, e) => + { + task.Fulfill(lk => { + lk.PushInteger(timerId); + }); + timers.TryRemove(timerId, out _); + }; + + return 1; + } + private static int L_Now(IntPtr state) { var now = DateTimeOffset.UtcNow;