2024-10-10 02:35:07 +08:00
|
|
|
import {
|
2024-10-11 21:34:27 +08:00
|
|
|
jsToLuaValue,
|
|
|
|
LuaBuiltinFunction,
|
|
|
|
LuaTable,
|
|
|
|
luaValueToJS,
|
2024-10-10 02:35:07 +08:00
|
|
|
} from "$common/space_lua/runtime.ts";
|
|
|
|
|
|
|
|
export const jsApi = new LuaTable({
|
2025-01-16 03:47:58 +08:00
|
|
|
/**
|
|
|
|
* Creates a new instance of a JavaScript class.
|
|
|
|
* @param constructorFn - The constructor function.
|
|
|
|
* @param args - The arguments to pass to the constructor.
|
|
|
|
* @returns The new instance.
|
|
|
|
*/
|
2024-10-11 21:34:27 +08:00
|
|
|
new: new LuaBuiltinFunction(
|
2025-01-16 03:47:58 +08:00
|
|
|
(_sf, constructorFn: any, ...args) => {
|
2024-10-11 21:34:27 +08:00
|
|
|
return new constructorFn(
|
|
|
|
...args.map(luaValueToJS),
|
|
|
|
);
|
|
|
|
},
|
|
|
|
),
|
2025-01-16 03:47:58 +08:00
|
|
|
/**
|
|
|
|
* Imports a JavaScript module.
|
|
|
|
* @param url - The URL of the module to import.
|
|
|
|
* @returns The imported module.
|
|
|
|
*/
|
|
|
|
import: new LuaBuiltinFunction(async (_sf, url) => {
|
|
|
|
let m = await import(url);
|
|
|
|
// Unwrap default if it exists
|
|
|
|
if (Object.keys(m).length === 1 && m.default) {
|
|
|
|
m = m.default;
|
|
|
|
}
|
|
|
|
return m;
|
2024-10-11 21:34:27 +08:00
|
|
|
}),
|
2025-01-16 19:35:15 +08:00
|
|
|
each_iterable: new LuaBuiltinFunction((_sf, val) => {
|
2025-01-16 22:35:56 +08:00
|
|
|
const iterator = val[Symbol.asyncIterator]();
|
2025-01-16 19:35:15 +08:00
|
|
|
return async () => {
|
|
|
|
const result = await iterator.next();
|
|
|
|
if (result.done) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
return result.value;
|
|
|
|
};
|
|
|
|
}),
|
2025-01-16 03:47:58 +08:00
|
|
|
/**
|
|
|
|
* Converts a JavaScript value to a Lua value.
|
|
|
|
* @param val - The JavaScript value to convert.
|
|
|
|
* @returns The Lua value.
|
|
|
|
*/
|
2024-10-20 21:06:23 +08:00
|
|
|
tolua: new LuaBuiltinFunction((_sf, val) => jsToLuaValue(val)),
|
2025-01-16 03:47:58 +08:00
|
|
|
/**
|
|
|
|
* Converts a Lua value to a JavaScript value.
|
|
|
|
* @param val - The Lua value to convert.
|
|
|
|
* @returns The JavaScript value.
|
|
|
|
*/
|
2024-10-20 21:06:23 +08:00
|
|
|
tojs: new LuaBuiltinFunction((_sf, val) => luaValueToJS(val)),
|
2025-01-16 03:47:58 +08:00
|
|
|
/**
|
|
|
|
* Logs a message to the console.
|
|
|
|
* @param args - The arguments to log.
|
|
|
|
*/
|
2024-10-20 21:06:23 +08:00
|
|
|
log: new LuaBuiltinFunction((_sf, ...args) => {
|
2024-10-11 21:34:27 +08:00
|
|
|
console.log(...args);
|
|
|
|
}),
|
2025-01-16 03:47:58 +08:00
|
|
|
/**
|
|
|
|
* Converts a Lua value to a JSON string.
|
|
|
|
* @param val - The Lua value to convert.
|
|
|
|
* @returns The JSON string.
|
|
|
|
*/
|
2025-01-09 00:09:09 +08:00
|
|
|
stringify: new LuaBuiltinFunction((_sf, val) => JSON.stringify(val)),
|
2024-10-10 02:35:07 +08:00
|
|
|
});
|