From 1cda87318bba5321f44acf1d198f5feeb426e089 Mon Sep 17 00:00:00 2001 From: Lennart Ochel Date: Sun, 4 May 2025 20:53:48 +0200 Subject: [PATCH] Implement Lua built-in function os.difftime (#1367) * Implement Lua built-in function os.difftime * Test os.difftime --------- Co-authored-by: Zef Hemel --- common/space_lua/stdlib/os.ts | 8 ++++++++ common/space_lua/stdlib/os_test.lua | 5 +++++ 2 files changed, 13 insertions(+) diff --git a/common/space_lua/stdlib/os.ts b/common/space_lua/stdlib/os.ts index eb18cbc6..398df383 100644 --- a/common/space_lua/stdlib/os.ts +++ b/common/space_lua/stdlib/os.ts @@ -67,6 +67,14 @@ export const osApi = new LuaTable({ return Math.floor(Date.now() / 1000); } }), + /** + * Returns the difference, in seconds, from time t1 to time t2 + * (where the times are values returned by os.time). In POSIX, + * Windows, and some other systems, this value is exactly t2-t1. + */ + difftime: new LuaBuiltinFunction((_sf, t2: number, t1: number): number => { + return t2 - t1; + }), /** * Returns a string or a table containing date and time, formatted according to the given string format. * If the time argument is present, this is the time to be formatted (see the os.time function for a description of this value). Otherwise, date formats the current time. diff --git a/common/space_lua/stdlib/os_test.lua b/common/space_lua/stdlib/os_test.lua index 160f9f29..6f8b0652 100644 --- a/common/space_lua/stdlib/os_test.lua +++ b/common/space_lua/stdlib/os_test.lua @@ -10,6 +10,11 @@ assert(os.date("%Y-%m-%d", os.time({ year = 2020, month = 1, day = 1 })) == "202 -- Week calculations assert(os.date("%U %V %W", os.time({ year = 2051, month = 1, day = 1 })) == "01 52 00") + +local t = os.time() +assert(os.difftime(t+10, t) == 10) +assert(os.difftime(t, t+10) == -10) +assert(os.difftime(t, t) == 0) assert(os.date("%U %V %W", os.time({ year = 2024, month = 1, day = 7 })) == "01 01 01") assert(os.date("%U %V %W", os.time({ year = 2025, month = 1, day = 5 })) == "01 01 00") assert(os.date("%U %V %W", os.time({ year = 2025, month = 1, day = 6 })) == "01 02 01")