Files
plainleaf/client/space_lua/stdlib.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

490 lines
14 KiB
TypeScript

import {
type ILuaFunction,
isILuaFunction,
isLuaTable,
LuaBuiltinFunction,
luaCall,
luaCloseFromMark,
luaEnsureCloseStack,
LuaEnv,
luaGet,
luaKeys,
luaLen,
LuaMultiRes,
LuaRuntimeError,
type LuaStackFrame,
type LuaTable,
luaToString,
luaTypeOf,
type LuaValue,
} from "./runtime.ts";
import { stringApi } from "./stdlib/string.ts";
import { tableApi } from "./stdlib/table.ts";
import { osApi } from "./stdlib/os.ts";
import { jsApi } from "./stdlib/js.ts";
import { spaceluaApi } from "./stdlib/space_lua.ts";
import { mathApi } from "./stdlib/math.ts";
import { parse } from "./parse.ts";
import { evalStatement } from "./eval.ts";
import { encodingApi } from "./stdlib/encoding.ts";
import { luaToNumberDetailed } from "./tonumber.ts";
import { luaLoad } from "./stdlib/load.ts";
import { cryptoApi } from "./stdlib/crypto.ts";
import { netApi } from "./stdlib/net.ts";
import { isTaggedFloat, makeLuaFloat } from "./numeric.ts";
const printFunction = new LuaBuiltinFunction(async (_sf, ...args) => {
console.log(
"[Lua]",
...(await Promise.all(args.map((v) => luaToString(v)))),
);
});
const assertFunction = new LuaBuiltinFunction(
async (sf, value: any, message?: string) => {
if (!await value) {
throw new LuaRuntimeError(`Assertion failed: ${message}`, sf);
}
},
);
const ipairsFunction = new LuaBuiltinFunction((sf, t: LuaTable | any[]) => {
let i = 0;
return async () => {
i = i + 1;
const v = await luaGet(t, i, sf.astCtx ?? null, sf);
if (v === null || v === undefined) {
return;
}
return new LuaMultiRes([i, v]);
};
});
const pairsFunction = new LuaBuiltinFunction(
(sf, t: LuaTable | any[] | Record<string, any>) => {
// Respect `__pairs` metamethod for Lua tables
if (isLuaTable(t)) {
const mt = (t as any).metatable as LuaTable | null | undefined;
if (mt) {
const mm = mt.get("__pairs", sf);
if (mm && (typeof mm === "function" || isILuaFunction(mm))) {
// __pairs must return (iter, state, control, closing)
return luaCall(mm, [t], sf.astCtx ?? {}, sf);
}
}
}
let keys: (string | number)[];
if (Array.isArray(t)) {
keys = Array.from({ length: t.length }, (_, i) => i + 1); // For arrays, generate 1-based indices
} else if (isLuaTable(t) || t instanceof LuaEnv) {
keys = t.keys();
} else {
// For plain JavaScript objects case, note: this will also include keys from the prototype
keys = [];
for (const key in t) {
keys.push(key);
}
}
let i = 0;
const iter = async () => {
if (i >= keys.length) {
return;
}
const key = keys[i];
i++;
const value = await luaGet(t, key, sf.astCtx ?? null, sf);
return new LuaMultiRes([key, value]);
};
// Must return (iter, state, control) for generic for
return new LuaMultiRes([iter, t, null]);
},
);
export const eachFunction = new LuaBuiltinFunction(
(sf, ar: LuaTable | any[]) => {
let i = 1;
const length = (ar as any).length;
return async () => {
if (i > length) {
return;
}
const result = await luaGet(ar, i, sf.astCtx ?? null, sf);
i++;
return result;
};
},
);
const unpackFunction = new LuaBuiltinFunction(async (sf, t: LuaTable) => {
const values: LuaValue[] = [];
for (let i = 1; i <= (t as any).length; i++) {
values.push(await luaGet(t, i, sf.astCtx ?? null, sf));
}
return new LuaMultiRes(values);
});
const typeFunction = new LuaBuiltinFunction(
(_sf, value: LuaValue): string | Promise<string> => {
return luaTypeOf(value);
},
);
const tostringFunction = new LuaBuiltinFunction((_sf, value: any) => {
return luaToString(value);
});
const tonumberFunction = new LuaBuiltinFunction(
(sf, value: LuaValue, base?: number) => {
if (base !== undefined) {
if (!(typeof base === "number" && base >= 2 && base <= 36)) {
throw new LuaRuntimeError(
"bad argument #2 to 'tonumber' (base out of range)",
sf,
);
}
}
if (typeof value === "number") {
return value;
}
if (isTaggedFloat(value)) {
return value;
}
if (typeof value !== "string") {
return null;
}
const result = luaToNumberDetailed(value, base);
if (result === null) {
return null;
}
if (result.numericType === "float") {
return makeLuaFloat(result.value);
}
return result.value;
},
);
const errorFunction = new LuaBuiltinFunction((sf, message: string) => {
throw new LuaRuntimeError(message, sf);
});
async function pcallBoundary(
sf: LuaStackFrame,
fn: ILuaFunction,
args: LuaValue[],
): Promise<
| { ok: true; values: LuaValue[] }
| { ok: false; message: string }
> {
const closeStack = luaEnsureCloseStack(sf);
const mark = closeStack.length;
const errMsgOf = (e: any): string =>
e instanceof LuaRuntimeError ? e.message : (e?.message ?? String(e));
try {
const r = await luaCall(fn, args, sf.astCtx!, sf);
await luaCloseFromMark(sf, mark, null);
const values = r instanceof LuaMultiRes ? r.flatten().values : [r];
return { ok: true, values };
} catch (e: any) {
const msg = errMsgOf(e);
try {
await luaCloseFromMark(sf, mark, msg);
return { ok: false, message: msg };
} catch (closeErr: any) {
return { ok: false, message: errMsgOf(closeErr) };
}
}
}
const pcallFunction = new LuaBuiltinFunction(
async (sf, fn: ILuaFunction, ...args) => {
// To-be-closed variables must be closed when unwinding to the
// protected call boundary. Space Lua uses a per-thread close
// stack, so we snapshot its length and close anything pushed
// after that.
//
// The protected call boundary must be established *before*
// evaluating the function and its arguments. Otherwise, any
// `<close>` locals created while evaluating `pcall`'s arguments
// will be wrongly treated as "inside" the protected call, and
// `pcall` may end up closing them (or affecting close ordering).
//
// `threadState` is read-only on the stack frame; do not reassign!
const res = await pcallBoundary(sf, fn, args);
if (res.ok) {
return new LuaMultiRes([true, ...res.values]);
}
return new LuaMultiRes([false, res.message]);
},
);
const xpcallFunction = new LuaBuiltinFunction(
async (sf, fn: ILuaFunction, errorHandler: ILuaFunction, ...args) => {
// Same semantic as `pcall` (see comments there)
const res = await pcallBoundary(sf, fn, args);
if (res.ok) {
return new LuaMultiRes([true, ...res.values]);
}
const hr = await luaCall(errorHandler, [res.message], sf.astCtx!, sf);
const outVals = hr instanceof LuaMultiRes ? hr.flatten().values : [hr];
return new LuaMultiRes([false, ...outVals]);
},
);
const setmetatableFunction = new LuaBuiltinFunction(
(sf, table: LuaTable, metatable: LuaTable) => {
if (!metatable) {
throw new LuaRuntimeError("metatable cannot be set to nil", sf);
}
table.metatable = metatable;
return table;
},
);
const rawlenFunction = new LuaBuiltinFunction(
(_sf, value: LuaValue) => {
return luaLen(value, _sf);
},
);
const rawsetFunction = new LuaBuiltinFunction(
(_sf, table: LuaTable, key: LuaValue, value: LuaValue) => {
return (table as any).rawSet(key, value);
},
);
const rawgetFunction = new LuaBuiltinFunction(
(_sf, table: any, key: LuaValue) => {
const isArray = Array.isArray(table);
const isPlainObj = typeof table === "object" &&
table !== null &&
(table as any).constructor === Object;
if (!isLuaTable(table) && !isArray && !isPlainObj) {
let typeName = "userdata";
if (table === null || table === undefined) {
typeName = "nil";
} else if (typeof table === "boolean") {
typeName = "boolean";
} else if (typeof table === "number" || isTaggedFloat(table)) {
typeName = "number";
} else if (typeof table === "string") {
typeName = "string";
} else if (
typeof table === "function" ||
(typeof table === "object" &&
table !== null &&
typeof (table as any).call === "function")
) {
typeName = "function";
}
throw new LuaRuntimeError(
`bad argument #1 to 'rawget' (table expected, got ${typeName})`,
_sf,
);
}
if (isLuaTable(table)) {
const v = table.rawGet(key);
return v === undefined ? null : v;
}
const k = isTaggedFloat(key) ? key.value : key;
if (isArray) {
if (typeof k === "number") {
const v = (table as any[])[k - 1];
return v === undefined ? null : v;
}
const v = (table as Record<string, any>)[k];
return v === undefined ? null : v;
}
const v = (table as Record<string | number, any>)[k as any];
return v === undefined ? null : v;
},
);
const rawequalFunction = new LuaBuiltinFunction(
(_sf, a: any, b: any) => {
const av = isTaggedFloat(a) ? a.value : a;
const bv = isTaggedFloat(b) ? b.value : b;
return av === bv;
},
);
const getmetatableFunction = new LuaBuiltinFunction((_sf, table: LuaTable) => {
return (table as any).metatable;
});
const dofileFunction = new LuaBuiltinFunction(async (sf, filename: string) => {
const global = sf.threadLocal.get("_GLOBAL") as LuaEnv;
const file = await luaCall(
(global.get("space") as any).get("readFile"),
[filename],
sf.astCtx!,
sf,
) as Uint8Array;
const code = new TextDecoder().decode(file);
try {
const parsedExpr = parse(code);
const env = new LuaEnv(global);
await evalStatement(parsedExpr, env, sf.withCtx(parsedExpr.ctx));
} catch (e: any) {
throw new LuaRuntimeError(
`Error evaluating "${filename}": ${e.message}`,
sf,
);
}
});
/**
* From the Lua docs:
*
* If index is a number, returns all arguments after argument number
* index; a negative number indexes from the end (-1 is the last
* argument). Otherwise, index must be the string "#", and select
* returns the total number of extra arguments it received.
*/
const selectFunction = new LuaBuiltinFunction(
(_sf, index: number | "#", ...args: LuaValue[]) => {
if (index === "#") {
return args.length;
}
if (typeof index === "number") {
if (index >= 0) {
return new LuaMultiRes(args.slice(index - 1));
}
return new LuaMultiRes(args.slice(args.length + index));
}
},
);
/**
* From the Lua docs:
*
* Allows a program to traverse all fields of a table. Its first
* argument is a table and its second argument is an index in this
* table. A call to next returns the next index of the table and its
* associated value. When called with nil as its second argument, next
* returns an initial index and its associated value. When called with
* the last index, or with nil in an empty table, next returns nil. If
* the second argument is absent, then it is interpreted as nil. In
* particular, you can use next(t) to check whether a table is empty.
*
* The order in which the indices are enumerated is not specified, even
* for numeric indices. (To traverse a table in numerical order, use
* a numerical for.)
*
* You should not assign any value to a non-existent field in a table
* during its traversal. You may however modify existing fields. In
* particular, you may set existing fields to nil.
*/
const nextFunction = new LuaBuiltinFunction(
(sf, table: LuaTable | Record<string, any>, index: number | null = null) => {
if (!table) {
// When nil value
return null;
}
const keys = luaKeys(table);
// Empty table -> null return value
if (keys.length === 0) {
return null;
}
if (index === null) {
// Return the first key, value
const key = keys[0];
return new LuaMultiRes([key, luaGet(table, key, sf.astCtx ?? null, sf)]);
}
// Find index in the key list
const idx = keys.indexOf(index);
if (idx === -1) { // Not found
throw new LuaRuntimeError("invalid key to 'next': key not found", sf);
}
const key = keys[idx + 1];
if (key === undefined) {
// When called with the last key, should return nil
return null;
}
return new LuaMultiRes([key, luaGet(table, key, sf.astCtx ?? null, sf)]);
},
);
// Non-standard, but useful
const someFunction = new LuaBuiltinFunction(async (_sf, value: any) => {
switch (await luaTypeOf(value)) {
case "number":
if (!isFinite(value)) return null;
break;
case "string":
if (value.trim() === "") return null;
break;
case "table":
if (luaKeys(value).length === 0) return null;
}
return value;
});
const loadFunction = new LuaBuiltinFunction((sf, s) => luaLoad(s, sf));
export function luaBuildStandardEnv() {
const env = new LuaEnv();
// _G global
env.set("_G", env);
// Top-level builtins
env.set("print", printFunction);
env.set("assert", assertFunction);
env.set("type", typeFunction);
env.set("tostring", tostringFunction);
env.set("tonumber", tonumberFunction);
env.set("unpack", unpackFunction);
env.set("select", selectFunction);
env.set("next", nextFunction);
// Iterators
env.set("pairs", pairsFunction);
env.set("ipairs", ipairsFunction);
// meta table stuff
env.set("setmetatable", setmetatableFunction);
env.set("getmetatable", getmetatableFunction);
env.set("rawlen", rawlenFunction);
env.set("rawset", rawsetFunction);
env.set("rawget", rawgetFunction);
env.set("rawequal", rawequalFunction);
env.set("dofile", dofileFunction);
// Error handling
env.set("error", errorFunction);
env.set("pcall", pcallFunction);
env.set("xpcall", xpcallFunction);
// Evaluation
env.set("load", loadFunction);
// APIs
env.set("string", stringApi);
env.set("table", tableApi);
env.set("os", osApi);
env.set("js", jsApi);
env.set("math", mathApi);
// Non-standard
env.set("each", eachFunction);
env.set("spacelua", spaceluaApi);
env.set("encoding", encodingApi);
env.set("crypto", cryptoApi);
env.set("net", netApi);
env.set("some", someFunction);
return env;
}