Add timer.delay() that returns a task

This commit is contained in:
Alessandro Proto 2023-03-10 15:41:30 +01:00
parent f9a88f39bb
commit b7a956bfd6

View file

@ -14,6 +14,7 @@
// limitations under the License. // limitations under the License.
using Capy64.API; using Capy64.API;
using Capy64.Runtime.Objects;
using KeraLua; using KeraLua;
using System; using System;
using System.Collections.Concurrent; using System.Collections.Concurrent;
@ -30,6 +31,11 @@ class Timer : IComponent
function = L_StartTimer, function = L_StartTimer,
}, },
new() new()
{
name = "delay",
function = L_Delay,
},
new()
{ {
name = "now", name = "now",
function = L_Now function = L_Now
@ -88,20 +94,49 @@ class Timer : IComponent
timer.Elapsed += (o, e) => 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; return 1;
}); });
timers.TryRemove(timerId, out _);
}; };
L.PushInteger(timerId); L.PushInteger(timerId);
return 1; 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) private static int L_Now(IntPtr state)
{ {
var now = DateTimeOffset.UtcNow; var now = DateTimeOffset.UtcNow;