Skip to content

Commit aed3720

Browse files
committed
Fixes #1251
1 parent e0fff9d commit aed3720

File tree

1 file changed

+32
-5
lines changed
  • web/space_lua/stdlib

1 file changed

+32
-5
lines changed

web/space_lua/stdlib/os.ts

Lines changed: 32 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { secureHeapUsed } from "node:crypto";
12
import { LuaBuiltinFunction, LuaTable } from "../runtime.ts";
23

34
const ONE_DAY = 1000 * 60 * 60 * 24;
@@ -90,6 +91,28 @@ export const osApi = new LuaTable({
9091
return date.toDateString() + " " + date.toLocaleTimeString();
9192
}
9293

94+
if (format === "*t") {
95+
/*
96+
To produce a date table, we use the format string "*t". For instance, the following code
97+
98+
temp = os.date("*t", 906000490)
99+
produces the table
100+
{year = 1998, month = 9, day = 16, yday = 259, wday = 4,
101+
hour = 23, min = 48, sec = 10, isdst = false}
102+
*/
103+
return new LuaTable({
104+
year: date.getFullYear(),
105+
month: date.getMonth() + 1,
106+
day: date.getDate(),
107+
yday: dayOfYear(date),
108+
wday: date.getDay() + 1,
109+
hour: date.getHours(),
110+
min: date.getMinutes(),
111+
sec: date.getSeconds(),
112+
// TODO: Add isdst
113+
});
114+
}
115+
93116
// Define mappings for Lua-style placeholders
94117
const formatMap: { [key: string]: () => string } = {
95118
// Year
@@ -114,13 +137,10 @@ export const osApi = new LuaTable({
114137
// Day of the week
115138
"%A": () => date.toLocaleString("en-US", { weekday: "long" }),
116139
"%a": () => date.toLocaleString("en-US", { weekday: "short" }),
117-
"%w": () => date.getDay().toString(),
140+
"%w": () => "" + (date.getDay() + 1),
118141
// Day of the year
119142
"%j": () => {
120-
const start = new Date(date.getFullYear(), 0, 0);
121-
const diff = date.getTime() - start.getTime();
122-
const dayOfYear = Math.floor(diff / ONE_DAY);
123-
return dayOfYear.toString().padStart(3, "0");
143+
return dayOfYear(date).toString().padStart(3, "0");
124144
},
125145
// Week
126146
"%U": () => weekNumber(date, 0, false).toString().padStart(2, "0"),
@@ -153,3 +173,10 @@ export const osApi = new LuaTable({
153173
});
154174
}),
155175
});
176+
177+
function dayOfYear(date: Date) {
178+
const start = new Date(date.getFullYear(), 0, 0);
179+
const diff = date.getTime() - start.getTime();
180+
const dayOfYear = Math.floor(diff / ONE_DAY);
181+
return dayOfYear;
182+
}

0 commit comments

Comments
 (0)