Files
plainleaf/client/space_lua/eval.test.ts
T
75cc79800f Space Lua: Align numeric/table semantics with Lua, align number formating, optimize loops allocations (#1823)
* Don't know what's going on with the Deno docker image, disabling the deno.lock file for now

* Another try

* Space Lua: Align numeric and table semantics with Lua

This change improves Space Lua compatibility with standard Lua 5.4,
focusing on numeric subtypes and table behavior. The test suite is
extended to lock in the expected semantics and should pass under both
Space Lua and a Lua interpreter.

SUMMARY OF CHANGES
------------------

Tighten Lua compatibility across evaluator and runtime:

- correct metamethod dispatch (`__index`, `__newindex`, `__call`,
  comparison metamethods),

- loop limits,

- raw metamethod lookups.

Rework numeric semantics to preserve Lua **integer** vs **float**
behavior:

- $0$ vs $0.0$ and $-0.0$,

- explicit zero kind representation, and

- updates arithmetic/bitwise coercions accordingly.

Improve parser correctness by rejecting **unary plus** with aligned Lua
errors and better parsing errors reporting.

Fix `stdlib` behavior to match that of Lua:

- `table` function `concat`, `insert`, `remove`, `sort` and `unpack`
  gain metamethod awareness and enforce Lua errors,

- `ipairs` iteration updated to stop on first nil and honor `__index`,

- `tonumber` updated to Luae conversion using `luaToNumberDetailed`,

- `math.modf` return corrected,

- `math.type` accuracy improvements for float/integer and $-0.0$,

- `math.pi` added.

Fix numeric subtypes for `/` and `^` operators so `math.type` matches
Lua results using tagging as well as unary `-`.

Expand test coverage:

- new `metamethods_test.lua` for Lua metamethod/operator semantics,

- extend arithmetic and length tests for zero-kind propagation and
  `rawlen` vs `__len` metamethod,

- Extend `math` test suite to test proper Lua alignment (`math.type` and
  more), and

- update context error expectations for Lua error messages.

RATIONALE
---------

Lua differs from JavaScript by having two numeric subtypes: **integer**
and **float**. Operators depend on the subtype: `+`, `-`, `*`, `//` and
`%` use integer mode when both operands are integers and float mode
otherwise. Bitwise operators require integers and `math.type(x)` reports
"integer" or "float". JavaScript has one numeric primitive type
(`number`) so a plain number value cannot record whether Lua considers
a value to be a float when the value has no fractional part (for example
$2.0$).

Lua also differs from "everything is IEEE 754 double" because the rules
are defined in terms of integer and float subtypes. Float operations
preserve IEEE 754 behavior including `NaN`, infinities and signed zero
($-0.0$) which affects results like $1/0.0$ versus $1/-0.0$. Integer
arithmetic does not preserve $-0$ and collapses it to $0$. Lua integer
arithmetic is exact within its integer range while JavaScript `number`
cannot exactly represent all integers in that range.

Lua numbers are integers or floats. Numeric strings coerce to integer or
float based on _lexical_ form. Each arithmetic operator selects the
result subtype from the operator rules and operand subtypes.  Integer
only operators (bitwise and `//` as integer division) require integer
representability. Mixed arithmetic promotes to float as needed.  Two
operators are **always float** typed: division (`/`) and exponentiation
(`^`) produce floats even if both operands are integers and even if the
numeric value has no fractional part. `math.type` reports that internal
subtype.

Tables are associative arrays and assigning `nil` removes a key. The
length operator `#` uses `__len` metamethod if present otherwise it uses
the raw length rule. `rawlen(table)` ignores `__len`. Without `__len`
Lua defines `#` as some boundary `N` such that `table[N]` is not `nil`
and `table[N+1]` is `nil`. If the table has holes (missing or `nil`
entries in the positive integer key sequence) the boundary may be non
unique so `#` is stable only for proper sequences without holes.

PERFORMANCE NOTES
-----------------

Numeric changes add small checks to preserve Lua integer and float
subtype semantics and avoid allocations except when the subtype would
otherwise be lost.

Some table operations may be slower due to stricter Lua 5.4 behavior
especially around length and sequence boundary handling which currently
requires extra metadata tracking and scans and cannot be avoided without
a completely different internal table representation.

Signed-off-by: Matouš Jan Fialka <mjf@mjf.cz>

* Another try

* Replace `LuaFloatTag` plain objects with boxed Number for float tagging

* Restore pre-merge eval/numeric architecture and fix regressions

This commit restores the original branch architecture.

On top of the restored foundation, float-typed integer results (e.g.
`1.0 + 1.0` = `2.0`, `0.0 // 1.0` = `0.0`) are now correctly tagged via
`makeLuaFloat` so that `tostring` and `math.type` report them as floats.
The *unary minus* fast path for float literals and the `tonumber`
function also preserve float tagging.

Performance regressions from the merge are addressed by avoiding
`Number` boxing for non-integer floats (`3.14` needs no tag — it is
unambiguously float), adding *string key* fast paths in `LuaTable`
`has`/`rawGet`/`rawSet` to skip numeric normalization for the dominant
case, and inlining a `typeof` check in math standard library functions
to avoid function call overhead on plain numbers.

Signed-off-by: Matouš Jan Fialka <mjf@mjf.cz>

* Replace boxed `Number` float tagging with plain tagged objects

* Replace `new Number()` boxing with plain tagged float objects for Lua
  float type tracking.

* Integer-valued floats that need type disambiguation are now
  represented as `{ value: number, isFloat: true }` instead of boxed
  `Number` objects with a symbol property.

* Pre-allocated singletons are used for positive and negative float
  zeros to avoid allocation entirely in common cases.

* Updated all detection, unwrapping, and coercion paths across
  `numeric.ts`, `runtime.ts`, `eval.ts`, `stdlib.ts`, and `stdlib/`
  modules to use the new `isTaggedFloat` type guard.

* Removed all `instanceof Number` checks.

* Deleted the `FloatKind` symbol and eliminated redundant helpers
  `isLuaFloat`, `isFloatTag`, `getZeroBoxKind` and `toPlainNumber` that
  became dead code.

* Simplified `math.type`, `luaToString`, `luaEquals`, `luaTypeName` and
  various other key normalization paths.

Signed-off-by: Matouš Jan Fialka <mjf@mjf.cz>

* Add fast paths in `coerceNumericPair` for tagged float operands

Signed-off-by: Matouš Jan Fialka <mjf@mjf.cz>

* Fix copy/paste typo

Signed-off-by: Matouš Jan Fialka <mjf@mjf.cz>

* Avoid extra `LuaEnv` allocations in "For" and "ForIn" loops

Signed-off-by: Matouš Jan Fialka <mjf@mjf.cz>

* [Space Lua] Reuse loop variable environment in `for` and `for-in` loops

Numeric `for` and generic `for-in` loops allocated a fresh `LuaEnv` on
every iteration to hold loop variables. But this is only necessary when
a closure inside the loop body captures the loop variable.

The optimization uses a two-level check computed at parse time. If no
function definition exists in the loop's subtree, environment reuse is
safe. When a function definition is present a deeper analysis walks the
block to determine whether any function body references the loop
variable names without them being shadowed by its own parameters. When
a closure captures a loop variable the loop fall back to per-iteration
allocation.

Signed-off-by: Matouš Jan Fialka <mjf@mjf.cz>

* [Space Lua] Format numbers using standard Lua rules

Standard Lua formats floats via C `sprintf("%.14g")` (14 significant
digits, scientific notation when shorter, exponent padded to 2 digits,
and a guaranteed `.0` suffix for integer-valued floats).

* Replace the old `luaFormatNumber` with JS `toPrecision(14)`-based
  implementation that reproduces this behavior.

* Integrates it so that `${}` expressions in the UI also display
  numbers correctly.

* Fixes tagged floats (`{ value, isFloat }`) were being stripped by
  `luaValueToJS` or matched as plain objects before reaching the number
  formatter. This caused `${}` expressions to render raw JS numbers.

Examples:

```
- ${tostring(2^63)}
- ${2^63}
- ${(2^63)}
```

All of the the above examples show correct `9.2233720368548e+18` now.

Signed-off-by: Matouš Jan Fialka <mjf@mjf.cz>

* [Space Lua] Fix `string.format` for floats and tagged numbers

Unwrap tagged floats before `printf`, handle `inf`/`-inf`/`-nan` in
`formatDouble`, and fix `%g` producing `0e+00` for zero. Hopefuly it's
enough to gain Lua formatting.

Tests:

```
- ${string.format("%.14g", 0.0)} - `0`
- ${string.format("%.14g", 1.0)} - `1`
- ${string.format("%.14g", 1/3)} - `0.33333333333333`
- ${string.format("%.14g", math.pi)} - `3.1415926535898`
- ${string.format("%.14g", 1e-10)} - `1e-10`
- ${string.format("%.14g", 1e18)} - `1e+18`
- ${string.format("%.14g", 2^63)} - `9.2233720368548e+18`
- ${string.format("%.14g", 2^53)} - `9.007199254741e+15`
- ${string.format("%.14g", 1.7976931348623e+308)} - `1.7976931348623e+308`
- ${string.format("%.14g", 5e-324)} - `4.9406564584125e-324`
- ${string.format("%.14g", 0/0)} - `-nan`
- ${string.format("%.14g", 1/0)} - `inf`
- ${string.format("%.14g", -1/0)} - `-inf`
```

Signed-off-by: Matouš Jan Fialka <mjf@mjf.cz>

* [Space Lua] Add and integrate new `luaFormat` utility and test suite

* Add `luaFormat` string formatting function compatible with Lua, and
  integrate it across the codebase as a replacement for prior formatting
  approaches.

* Add extensive test suite.

Signed-off-by: Matouš Jan Fialka <mjf@mjf.cz>

* Fix check

Signed-off-by: Matouš Jan Fialka <mjf@mjf.cz>

* [Space Lua] Add `%a`/`%A` and `%q` format specifiers to `string.format`

Implement hexadecimal floating-point (`%a`/`%A`) and quoted literal
(`%q`) specifiers.

* Add `%a`/`%A` as IEEE 754 double decomposition with full flag, width
  and precision support.

* Add `%q` as producind valid Lua literals for strings, numbers,
  booleans and nil.

* Use `Math.PI` for `math.pi` to preserve full double precision.

* Remove Deno based test suite and replace it with native Lua test
  suite.

Signed-off-by: Matouš Jan Fialka <mjf@mjf.cz>

* [Space Lua] Add `%p` format specifier to `string.format`

In standard Lua, `%p` formats the internal C heap address of a value,
producing output like `0x55a3bc4e2f10`. It works on tables, functions,
threads, strings, and userdata (GC-ed objects). For `nil`, booleans, and
numbers it returns `(null)`.

In Space Lua, there are no *raw memory addresses* since the runtime is
JavaScript. Instead, `%p` assigns a *stable sequential integer* to each
object via a `WeakMap`, formatted as a 14-digit zero-padded hex value.
The key difference is that identifiers are deterministic and sequential
rather than random-looking heap addresses:

```lua
local t = {}

print(string.format("identifier: %p", t)) -- 0x00000000000001
print(string.format("the same:   %p", t)) -- 0x00000000000001
print(string.format("another:    %p", {}) -- 0x00000000000002
```

For strings, a regular `Map` is used so identical string content always
produces the same identifier.

Signed-off-by: Matouš Jan Fialka <mjf@mjf.cz>

* Revert merge changes to the deno.json

Signed-off-by: Matouš Jan Fialka <mjf@mjf.cz>

* Replace `interface` with `type`

Signed-off-by: Matouš Jan Fialka <mjf@mjf.cz>

* Remove `has_math()` relict function test

Signed-off-by: Matouš Jan Fialka <mjf@mjf.cz>

* Refactor loop to map

Signed-off-by: Matouš Jan Fialka <mjf@mjf.cz>

* Remove `Deno.remove("deno.lock")` weirdness

Signed-off-by: Matouš Jan Fialka <mjf@mjf.cz>

* Refactor: Early return undefined in `astNumberKind` instead of assigning

Signed-off-by: Matouš Jan Fialka <mjf@mjf.cz>

---------

Signed-off-by: Matouš Jan Fialka <mjf@mjf.cz>
Co-authored-by: Zef Hemel <zef@zef.me>
2026-02-12 15:22:12 +01:00

640 lines
15 KiB
TypeScript

import { assertEquals } from "@std/assert/equals";
import {
LuaEnv,
LuaNativeJSFunction,
LuaStackFrame,
LuaTable,
luaValueToJS,
singleResult,
} from "./runtime.ts";
import { parse } from "./parse.ts";
import type { LuaBlock, LuaFunctionCallStatement } from "./ast.ts";
import { evalExpression, evalStatement } from "./eval.ts";
import { luaBuildStandardEnv } from "./stdlib.ts";
const sf = LuaStackFrame.lostFrame;
function evalExpr(s: string, e = new LuaEnv(), sf?: LuaStackFrame): any {
const node = parse(`e(${s})`).statements[0] as LuaFunctionCallStatement;
sf = sf || new LuaStackFrame(e, node.ctx);
return evalExpression(
node.call.args[0],
e,
sf,
);
}
async function evalBlock(s: string, e = new LuaEnv()): Promise<void> {
const node = parse(s) as LuaBlock;
const sf = new LuaStackFrame(e, node.ctx);
await evalStatement(node, e, sf);
}
Deno.test("Evaluator test", async () => {
const env = new LuaEnv();
env.set("test", new LuaNativeJSFunction((n) => n));
env.set("asyncTest", new LuaNativeJSFunction((n) => Promise.resolve(n)));
// Basic arithmetic
assertEquals(evalExpr(`1 + 2 + 3 - 3`), 3);
assertEquals(evalExpr(`4 // 3`), 1);
assertEquals(evalExpr(`4 % 3`), 1);
// Bitwise arithmetic
assertEquals(evalExpr(`~171`), -172); // signed two's complement
assertEquals(evalExpr(`5 & 3`), 1); // 101 & 011 = 001
assertEquals(evalExpr(`5 | 3`), 7); // 101 | 011 = 111
assertEquals(evalExpr(`5 ~ 3`), 6); // 101 ^ 011 = 110
assertEquals(evalExpr(`5 << 3`), 40); // 101 << 3 = 101000
assertEquals(evalExpr(`5 >> 2`), 1); // 101 >> 2 = 1
// Strings
assertEquals(evalExpr(`"a" .. "b"`), "ab");
// Logic
assertEquals(evalExpr(`true and false`), false);
assertEquals(evalExpr(`true or false`), true);
assertEquals(evalExpr(`not true`), false);
// Test eager evaluation of left operand
assertEquals(
evalExpr(
`true or (function() error("this should not be evaluated") end)()`,
),
true,
);
// Tables
const tbl = await evalExpr(`{3, 1, 2}`);
assertEquals(tbl.get(1), 3);
assertEquals(tbl.get(2), 1);
assertEquals(tbl.get(3), 2);
assertEquals(luaValueToJS(tbl, sf), [3, 1, 2]);
assertEquals(
luaValueToJS(await evalExpr(`{name=test("Zef"), age=100}`, env), sf),
{
name: "Zef",
age: 100,
},
);
assertEquals(
luaValueToJS(await evalExpr(`{name="Zef", age=asyncTest(100)}`, env), sf),
{
name: "Zef",
age: 100,
},
);
const result = await evalExpr(`{[3+2]=1, ["a".."b"]=2}`);
assertEquals(result.get(5), 1);
assertEquals(result.get("ab"), 2);
assertEquals(await evalExpr(`#{}`), 0);
assertEquals(await evalExpr(`#{1, 2, 3}`), 3);
// Unary operators
assertEquals(await evalExpr(`-asyncTest(3)`, env), -3);
// Function calls
assertEquals(singleResult(evalExpr(`test(3)`, env)), 3);
assertEquals(singleResult(await evalExpr(`asyncTest(3) + 1`, env)), 4);
// Function expressions and table access
assertEquals(
await evalExpr(`(function() return {name="John"} end)().name`),
"John",
);
// Function definitions
const fn = evalExpr(`function(a, b) return a + b end`);
assertEquals(fn.body.parameters, ["a", "b"]);
});
Deno.test("Parser rejects unary plus - parenthesized", () => {
for (
const src of [
"return +(1)",
"return +((1))",
"return +(1 + 2)",
"return +({})",
]
) {
let err: any = null;
try {
parse(src);
} catch (e: any) {
err = e;
}
assertEquals(err !== null, true, `expected parse error for: ${src}`);
assertEquals(
String(err?.message ?? err).includes("unexpected symbol near '+'"),
true,
`expected unary-plus message for: ${src}`,
);
}
});
Deno.test("Parser rejects unary plus - variables and calls", () => {
for (
const src of [
"return +(a)",
"return +(a.b)",
"return +(a[1])",
"return +f()",
"return +(f())",
]
) {
let err: any = null;
try {
parse(src);
} catch (e: any) {
err = e;
}
assertEquals(err !== null, true, `expected parse error for: ${src}`);
assertEquals(
String(err?.message ?? err).includes("unexpected symbol near '+'"),
true,
`expected unary-plus message for: ${src}`,
);
}
});
Deno.test("Parser rejects unary plus - whitespace/newlines", () => {
for (
const src of [
"return + 1",
"return +\n1",
"return +\t(1)",
"return \n+\n(1)",
]
) {
let err: any = null;
try {
parse(src);
} catch (e: any) {
err = e;
}
assertEquals(err !== null, true, `expected parse error for: ${src}`);
assertEquals(
String(err?.message ?? err).includes("unexpected symbol near '+'"),
true,
`expected unary-plus message for: ${src}`,
);
}
});
Deno.test("Comparison metamethods: __lt", async () => {
const env = new LuaEnv(luaBuildStandardEnv());
await evalBlock(
`
local mt = {
__lt = function(a, b) return a.v < b.v end
}
local a = setmetatable({ v = 1 }, mt)
local b = setmetatable({ v = 2 }, mt)
res = (a < b)
`,
env,
);
assertEquals(env.get("res"), true);
});
Deno.test("Comparison metamethods: __le does not fallback to __lt", async () => {
const env = new LuaEnv(luaBuildStandardEnv());
let threw = false;
try {
await evalBlock(
`
local mt = {
__lt = function(a, b) return a.v < b.v end
}
local a = setmetatable({ v = 2 }, mt)
local b = setmetatable({ v = 2 }, mt)
res = (a <= b)
`,
env,
);
} catch (e: any) {
threw = true;
const msg = String(e?.message ?? e);
if (!msg.includes("attempt to compare")) {
throw e;
}
}
assertEquals(threw, true);
});
Deno.test("Equality metamethod: __eq requires same function", async () => {
const env = new LuaEnv(luaBuildStandardEnv());
await evalBlock(
`
local f1 = function(a, b) return true end
local f2 = function(a, b) return true end
local mt1 = { __eq = f1 }
local mt2 = { __eq = f2 } -- different function object
local a = setmetatable({}, mt1)
local b = setmetatable({}, mt2)
res = (a == b)
`,
env,
);
// Lua calls __eq even when the functions differ
assertEquals(env.get("res"), true);
});
Deno.test("Statement evaluation", async () => {
const env = new LuaEnv();
env.set("test", new LuaNativeJSFunction((n) => n));
env.set("asyncTest", new LuaNativeJSFunction((n) => Promise.resolve(n)));
assertEquals(undefined, await evalBlock(`a = 3`, env));
assertEquals(env.get("a"), 3);
assertEquals(undefined, await evalBlock(`b = test(3)`, env));
assertEquals(env.get("b"), 3);
await evalBlock(`c = asyncTest(3)`, env);
assertEquals(env.get("c"), 3);
// Multiple assignments
const env2 = new LuaEnv();
assertEquals(undefined, await evalBlock(`a, b = 1, 2`, env2));
assertEquals(env2.get("a"), 1);
assertEquals(env2.get("b"), 2);
// Other lvalues
const env3 = new LuaEnv();
await evalBlock(`tbl = {1, 2, 3}`, env3);
await evalBlock(`tbl[1] = 3`, env3);
assertEquals(luaValueToJS(env3.get("tbl"), sf), [3, 2, 3]);
await evalBlock("tbl.name = 'Zef'", env3);
assertEquals(env3.get("tbl").get("name"), "Zef");
await evalBlock(`tbl[2] = {age=10}`, env3);
await evalBlock(`tbl[2].age = 20`, env3);
assertEquals(env3.get("tbl").get(2).get("age"), 20);
// Blocks and scopes
const env4 = new LuaEnv();
env4.set("print", new LuaNativeJSFunction(console.log));
await evalBlock(
`
a = 1
do
-- sets global a to 3
a = 3
print("The number is: " .. a)
end`,
env4,
);
assertEquals(env4.get("a"), 3);
const env5 = new LuaEnv();
env5.set("print", new LuaNativeJSFunction(console.log));
await evalBlock(
`
a = 1
if a > 0 then
a = 3
else
a = 0
end`,
env5,
);
assertEquals(env5.get("a"), 3);
await evalBlock(
`
if a < 0 then
a = -1
elseif a > 0 then
a = 1
else
a = 0
end`,
env5,
);
assertEquals(env5.get("a"), 1);
await evalBlock(
`
var = 1
do
local var
var = 2
end`,
env5,
);
assertEquals(env5.get("var"), 1);
// While loop
const env6 = new LuaEnv();
await evalBlock(
`
c = 0
while true do
c = c + 1
if c == 3 then
break
end
end
`,
env6,
);
assertEquals(env6.get("c"), 3);
// Repeat loop
const env7 = new LuaEnv();
await evalBlock(
`
c = 0
repeat
c = c + 1
if c == 3 then
break
end
until false
`,
env7,
);
assertEquals(env7.get("c"), 3);
// Function definition and calling
const env8 = new LuaEnv();
env8.set("print", new LuaNativeJSFunction(console.log));
await evalBlock(
`
function test(a)
return a + 1
end
print("3 + 1 = " .. test(3))
`,
env8,
);
// Local fucntion definition
const env9 = new LuaEnv();
env9.set("print", new LuaNativeJSFunction(console.log));
await evalBlock(
`
local function test(a)
return a + 1
end
print("3 + 1 = " .. test(3))
`,
env9,
);
// For loop over range
const env10 = new LuaEnv();
await evalBlock(
`
c = 0
for i = 1, 3 do
c = c + i
end
`,
env10,
);
assertEquals(env10.get("c"), 6);
// For loop over iterator
const env11 = new LuaEnv(luaBuildStandardEnv());
await evalBlock(
`
function fruits()
local list = { "apple", "banana", "cherry" }
-- Track index internally
local index = 0
return function()
index = index + 1
if list[index] then
return list[index]
end
end
end
for fruit in fruits() do
print("Fruit: " .. fruit)
end
`,
env11,
);
await evalBlock(
`
for _, f in ipairs({ "apple", "banana", "cherry" }) do
print("Fruit: " .. f)
end`,
luaBuildStandardEnv(),
);
// Passing a Lua function as callback to a JS function
const env12 = new LuaEnv();
env12.set(
"runMe",
new LuaNativeJSFunction((fn) => {
return fn("Lua");
}),
);
assertEquals(
"Hello from Lua",
await evalExpr(
`runMe(function(name) return "Hello from " .. name end)`,
env12,
),
);
});
Deno.test("Thread local _CTX", async () => {
const env = new LuaEnv();
const threadLocal = new LuaEnv();
threadLocal.setLocal("threadValue", "test123");
const sf = new LuaStackFrame(threadLocal, null);
await evalBlock(
`
function test()
return _CTX.threadValue
end
`,
env,
);
const result = await evalExpr("test()", env, sf);
assertEquals(singleResult(result), "test123");
});
Deno.test("Thread local _CTX - advanced cases", async () => {
// Create environment with standard library
const env = new LuaEnv(luaBuildStandardEnv());
const threadLocal = new LuaEnv();
env.setLocal("globalEnv", "GLOBAL");
// Set up some thread local values
threadLocal.setLocal("user", "alice");
threadLocal.setLocal("permissions", new LuaTable());
threadLocal.get("permissions").set("admin", true);
threadLocal.setLocal("data", {
id: 123,
settings: { theme: "dark" },
});
const sf = new LuaStackFrame(threadLocal, null);
// Test 1: Nested function access
await evalBlock(
`
function outer()
local function inner()
return _CTX.user
end
return inner()
end
`,
env,
);
assertEquals(await evalExpr("outer()", env, sf), "alice");
// Test 2: Table access and modification
await evalBlock(
`
function checkAdmin()
return _CTX.permissions.admin
end
function revokeAdmin()
_CTX.permissions.admin = false
return _CTX.permissions.admin
end
`,
env,
);
assertEquals(await evalExpr("checkAdmin()", env, sf), true);
assertEquals(await evalExpr("revokeAdmin()", env, sf), false);
assertEquals(threadLocal.get("permissions").get("admin"), false);
// Test 3: Complex data structures
await evalBlock(
`
function getNestedData()
return _CTX.data.settings.theme
end
function updateTheme(newTheme)
_CTX.data.settings.theme = newTheme
return _CTX.data.settings.theme
end
`,
env,
);
assertEquals(await evalExpr("getNestedData()", env, sf), "dark");
assertEquals(await evalExpr("updateTheme('light')", env, sf), "light");
// Test 4: Multiple thread locals
const threadLocal2 = new LuaEnv();
threadLocal2.setLocal("user", "bob");
const sf2 = new LuaStackFrame(threadLocal2, null);
await evalBlock(
`
function getUser()
return _CTX.user
end
`,
env,
);
// Same function, different thread contexts
assertEquals(await evalExpr("getUser()", env, sf), "alice");
assertEquals(await evalExpr("getUser()", env, sf2), "bob");
// Test 5: Async operations with _CTX
env.set(
"asyncOperation",
new LuaNativeJSFunction(async () => {
await new Promise((resolve) => setTimeout(resolve, 10));
return "done";
}),
);
await evalBlock(
`
function asyncTest()
_CTX.status = "starting"
local result = asyncOperation()
_CTX.status = "completed"
return _CTX.status
end
`,
env,
);
assertEquals(await evalExpr("asyncTest()", env, sf), "completed");
assertEquals(threadLocal.get("status"), "completed");
// Test 6: Error handling with _CTX
await evalBlock(
`
function errorTest()
_CTX.error = nil
local status, err = pcall(function()
error("test error")
end)
_CTX.error = "caught"
return _CTX.error
end
`,
env,
);
assertEquals(await evalExpr("errorTest()", env, sf), "caught");
assertEquals(threadLocal.get("error"), "caught");
// Test string interpolation
sf.threadLocal.setLocal("_GLOBAL", env);
assertEquals(
await evalExpr(
"spacelua.interpolate('Hello, ${globalEnv} and ${loc}!', {loc='local'})",
env,
sf,
),
"Hello, GLOBAL and local!",
);
// Some more complex string interpolation with more complex lua expressions, with nested {}
assertEquals(
await evalExpr(
`spacelua.interpolate('Some JSON \${js.stringify(js.tojs({name="Pete"}))}!')`,
env,
sf,
),
`Some JSON {"name":"Pete"}!`,
);
});
Deno.test("Length: rawlen ignores __len", async () => {
const env = new LuaEnv(luaBuildStandardEnv());
await evalBlock(
`
local t = {1,2,3}
setmetatable(t, { __len = function() return 99 end })
a = #t
b = rawlen(t)
`,
env,
);
assertEquals(env.get("a"), 99);
assertEquals(env.get("b"), 3);
});