From 4fc3507328161bfac6572a55f99dd89707ec2cf6 Mon Sep 17 00:00:00 2001 From: ceifa Date: Thu, 19 Nov 2026 21:25:57 -0300 Subject: [PATCH] one value convention: nil is undefined, first result everywhere nil reads as undefined wherever it comes from, so a JS default parameter applies to a nil argument and a Lua function that returns nothing gives the same value sync and async. null is only what the injected sentinel reads back as. Every entry point gives back the first result, and returns: 'all' asks for all of them as a LuaMultiReturn: doString, doFile, their Sync twins, state.async and state.call. state.call is now call(target, args, options): the synchronous counterpart of state.async, taking a global's name or a Lua function. It no longer leaves its results on the state's stack. --- README.md | 50 +++++++++-- src/index.ts | 3 + src/state.ts | 104 +++++++++++++++++---- src/thread.ts | 21 +---- src/type-extensions/function.ts | 38 ++++---- src/type-extensions/proxy.ts | 2 +- src/types.ts | 26 +++++- test/async.test.js | 13 ++- test/initialization.test.js | 6 +- test/state.test.js | 154 ++++++++++++++++++++++++++++++-- 10 files changed, 346 insertions(+), 71 deletions(-) diff --git a/README.md b/README.md index 153b32f..59479c0 100644 --- a/README.md +++ b/README.md @@ -220,11 +220,49 @@ Building the wasm needs either [emscripten](https://emscripten.org/) or otherwise (always on Windows), so there is nothing to pick between. Drop the `:dev` for an optimized build. -## Edge Cases +## Values + +### nil, undefined and null + +Lua's `nil` is JS's `undefined`, in both directions and everywhere: a global that is not set, a +function that returned `nil` or nothing at all, a `nil` argument. A JS default parameter therefore +applies to it: + +```js +state.set('greet', (name = 'world') => `hello ${name}`) +await state.doString('return greet(nil)') // "hello world" +state.get('missing') // undefined +``` + +Lua has nothing for a JS `null` to be, so it becomes `nil` as well and reads back as `undefined`. To +keep the two apart, inject the `null` sentinel (`inject: true`, or one that names `'null'`): a `null` +is then marshalled as that userdata, and reads back as `null`. It works as expected except that, not +being `nil`, it is truthy in Lua. + +### Several results -### Null +Whatever runs Lua gives back the first result, or `undefined` when there was none. `returns: 'all'` +asks for every one of them, as a `LuaMultiReturn`, which is an array: -`null` is injected as userdata type if `inject` is `true` or names `'null'`. This works as expected except that it will evaluate to `true` in Lua. +```js +await state.doString('return 7 // 2, 7 % 2') // 3 +const [quotient, remainder] = await state.doString('return 7 // 2, 7 % 2', { returns: 'all' }) + +const divmod = state.get('divmod') +divmod(7, 2) // 3 +state.call(divmod, [7, 2], { returns: 'all' }) // [3, 1] +await state.async(divmod, { returns: 'all' })(7, 2) // [3, 1] +``` + +`doString`, `doFile`, `doStringSync`, `doFileSync`, `state.call` and `state.async` all take it. +`state.call(target, args, options)` is the synchronous counterpart of `state.async`: it calls a Lua +function, or a global one by its name, with a place for the options a direct call has none for. +Only the stack level `thread.run` and `thread.runSync` differ, which give back every value left on +the stack. + +In the other direction, a JS function returns several values to Lua with `LuaMultiReturn.of(a, b)`. + +## Edge Cases ### Promises @@ -314,9 +352,9 @@ process. Pass `onAsyncError` when creating the state to receive those errors ins const state = lua.createState({ inject: true, onAsyncError: (error) => console.error(error) }) ``` -`inject: true` defines `Promise`, `async`, `Error` and `null`. That last one is a sentinel a JS -`null` is marshalled as, and it is truthy in Lua; to leave it out, name the ones you want: -`inject: ['Promise', 'async']`. +`inject: true` defines `Promise`, `async`, `Error` and `null`. That last one is +[the sentinel](#nil-undefined-and-null) a JS `null` is marshalled as, and it is truthy in Lua; to +leave it out, name the ones you want: `inject: ['Promise', 'async']`. #### Interrupting a parked run diff --git a/src/index.ts b/src/index.ts index 32f34aa..9a0a8b8 100755 --- a/src/index.ts +++ b/src/index.ts @@ -51,6 +51,9 @@ export { type LuaRunOptions, type LuaLoadOptions, type LuaDoOptions, + type LuaCallOptions, + type LuaReturnOptions, + type LuaAllReturns, type LuaThreadLimits, type LuaResumeResult, type LuaGetCache, diff --git a/src/state.ts b/src/state.ts index 14395a1..488e55a 100755 --- a/src/state.ts +++ b/src/state.ts @@ -1,5 +1,6 @@ import LuaGarbageCollector from './gc' import type LuaModule from './module' +import type MultiReturn from './multireturn' import Thread from './thread' import type LuaTypeExtension from './type-extension' import createErrorType from './type-extensions/error' @@ -13,10 +14,11 @@ import { type CreateStateOptions, LUA_REGISTRYINDEX, type LuaAddress, + type LuaAllReturns, + type LuaCallOptions, type LuaDoOptions, type LuaInjectName, type LuaMemoryOptions, - type LuaRunOptions, LuaType, resolveLibraryMask, } from './types' @@ -121,6 +123,7 @@ export default class LuaState extends Thread { private readonly allocatorFunctionPointer: number | undefined private readonly defaultMaxInstructions: number | undefined + private readonly functionTimeout: number | undefined private readonly functions: FunctionTypeExtension public constructor(cmodule: LuaModule, options: CreateStateOptions = {}) { @@ -171,6 +174,7 @@ export default class LuaState extends Thread { } this.defaultMaxInstructions = limits?.maxInstructions + this.functionTimeout = limits?.functionTimeout if (injects('async')) { this.functions.injectAsync() @@ -179,18 +183,23 @@ export default class LuaState extends Thread { /** * Executes Lua code from a string asynchronously. - * @returns A Promise that resolves to the result returned by the Lua script execution. Nothing - * checks it against `T`, which only saves the caller a cast. + * @returns A Promise that resolves to the first result the script returned, or to all of them + * as a `LuaMultiReturn` with `returns: 'all'`. Nothing checks it against `T`, which only saves + * the caller a cast. */ - public doString(script: string, options?: LuaDoOptions): Promise { + public doString(script: string, options: LuaAllReturns): Promise> + public doString(script: string, options?: LuaDoOptions): Promise + public doString(script: string, options?: LuaDoOptions): Promise { return this.callByteCode((thread) => thread.loadString(script, options), this.runOptions(options)) } /** * Executes Lua code from a file asynchronously. - * @returns A Promise that resolves to the result returned by the Lua script execution. + * @returns A Promise that resolves like {@link doString}'s. */ - public doFile(filename: string, options?: LuaDoOptions): Promise { + public doFile(filename: string, options: LuaAllReturns): Promise> + public doFile(filename: string, options?: LuaDoOptions): Promise + public doFile(filename: string, options?: LuaDoOptions): Promise { return this.callByteCode((thread) => thread.loadFile(filename, options), this.runOptions(options)) } @@ -198,7 +207,9 @@ export default class LuaState extends Thread { * Executes Lua code from a string synchronously. Nothing can suspend a synchronous run, so * `:await()` and a top level `coroutine.yield` are errors here. */ - public doStringSync(script: string, options?: LuaDoOptions): T { + public doStringSync(script: string, options: LuaAllReturns): MultiReturn + public doStringSync(script: string, options?: LuaDoOptions): T + public doStringSync(script: string, options?: LuaDoOptions): unknown { return this.callByteCodeSync((thread) => thread.loadString(script, options), this.runOptions(options)) } @@ -206,15 +217,70 @@ export default class LuaState extends Thread { * Executes Lua code from a file synchronously. Nothing can suspend a synchronous run, so * `:await()` and a top level `coroutine.yield` are errors here. */ - public doFileSync(filename: string, options?: LuaDoOptions): T { + public doFileSync(filename: string, options: LuaAllReturns): MultiReturn + public doFileSync(filename: string, options?: LuaDoOptions): T + public doFileSync(filename: string, options?: LuaDoOptions): unknown { return this.callByteCodeSync((thread) => thread.loadFile(filename, options), this.runOptions(options)) } + /** + * Calls a Lua function synchronously, with a place for options: a global by its name, or a + * function obtained from this state. It is to {@link async} what `doStringSync` is to + * `doString`. + * + * ```js + * state.call('greet', ['bob']) + * const [quotient, remainder] = state.call(divmod, [7, 2], { returns: 'all' }) + * state.call(handler, [event], { timeout: 50 }) + * ``` + * + * Each call is a run like a `doStringSync`, under the same limits, with `limits.functionTimeout` + * on top unless `options.timeout` replaces it. Nothing can suspend it, so `:await()` and + * `coroutine.yield` are errors here. + */ + public call( + target: string | ((...args: any[]) => any), + args: readonly unknown[], + options: LuaAllReturns, + ): MultiReturn + public call(target: string | ((...args: any[]) => any), args?: readonly unknown[], options?: LuaCallOptions): T + public call(target: string | ((...args: any[]) => any), args: readonly unknown[] = [], options?: LuaCallOptions): unknown { + this.assertNotClosed() + if (!Array.isArray(args)) { + throw new TypeError('call takes the arguments as an array: call(target, [first, second])') + } + + // On the state's own thread, as the synchronous do* are, which is what puts the call under + // the limits set on the state. Whatever it leaves there is rewound. + const startStackTop = this.getTop() + try { + if (typeof target !== 'string') { + this.functions.pushLuaFunction(this, target) + } else { + const type = this.module.lua_getglobal(this.address, target) + if (type !== LuaType.Function) { + throw new TypeError(`cannot call '${target}': expected a function, got ${LuaType[type]}`) + } + } + for (const arg of args) { + this.pushValue(arg) + } + + const timeout = options?.timeout ?? this.functionTimeout + const values = this.runSync(args.length, this.runOptions(timeout === undefined ? options : { ...options, timeout })) + return options?.returns === 'all' ? values : values[0] + } finally { + if (!this.isClosed()) { + this.setTop(startStackTop) + } + } + } + /** * The asynchronous counterpart of a Lua function obtained from this state, as `async function` * is to `function`. Called directly a Lua function runs synchronously, and an `:await()` in it * is an error; what this returns starts it as a run of its own instead, and gives back a - * promise of its first result. + * promise of its first result, or of all of them with `returns: 'all'`. * * ```js * emitter.on('request', state.async(handler)) @@ -224,8 +290,10 @@ export default class LuaState extends Thread { * Each call is a run like a `doString`, under the same limits, with `limits.functionTimeout` * on top unless `options.timeout` replaces it. */ - public async(fn: (...args: any[]) => any, options?: LuaRunOptions): (...args: any[]) => Promise { - return this.functions.async(fn, options) as (...args: any[]) => Promise + public async(fn: (...args: any[]) => any, options: LuaAllReturns): (...args: any[]) => Promise> + public async(fn: (...args: any[]) => any, options?: LuaCallOptions): (...args: any[]) => Promise + public async(fn: (...args: any[]) => any, options?: LuaCallOptions): (...args: any[]) => Promise { + return this.functions.async(fn, options) } /** Whether `value` is a Lua function obtained from this state, the kind {@link async} takes. */ @@ -250,7 +318,7 @@ export default class LuaState extends Thread { this.pop(1) } - /** Retrieves the value of a global variable. */ + /** Retrieves the value of a global variable, which is undefined for one that is not set. */ public get(name: string): T { // Without this a read from a closed state returns whatever the freed memory now holds, // which is the one failure mode with nothing to notice it by. @@ -313,14 +381,14 @@ export default class LuaState extends Thread { } /** Folds the state wide budget in, so run() does the save and restore in one place. */ - private runOptions(options?: LuaDoOptions): LuaRunOptions | undefined { + private runOptions(options?: LuaDoOptions): LuaDoOptions | undefined { if (this.defaultMaxInstructions === undefined) { return options } return { maxInstructions: this.defaultMaxInstructions, ...options } } - private callByteCodeSync(loader: (thread: Thread) => void, options?: LuaRunOptions): any { + private callByteCodeSync(loader: (thread: Thread) => void, options?: LuaDoOptions): unknown { // Ahead of the stack bookkeeping below rather than left to the loader, so that a closed // state is refused before anything reads or rewinds the freed one. this.assertNotClosed() @@ -330,7 +398,8 @@ export default class LuaState extends Thread { const startStackTop = this.getTop() try { loader(this) - return this.runSync(0, options)[0] + const values = this.runSync(0, options) + return options?.returns === 'all' ? values : values[0] } finally { // Closing runs the state's own teardown, which leaves nothing here to rewind. if (!this.isClosed()) { @@ -340,7 +409,7 @@ export default class LuaState extends Thread { } // WARNING: It will not wait for open handles and can potentially cause bugs if JS code tries to reference Lua after executed - private async callByteCode(loader: (thread: Thread) => void, options?: LuaRunOptions): Promise { + private async callByteCode(loader: (thread: Thread) => void, options?: LuaDoOptions): Promise { this.assertNotClosed() // Anchored so the run doesn't pile threads up on the global stack. @@ -351,7 +420,8 @@ export default class LuaState extends Thread { // so going through getLimits first would copy the same configuration twice. thread.setLimits(this.limits) loader(thread) - return (await thread.run(0, options))[0] + const values = await thread.run(0, options) + return options?.returns === 'all' ? values : values[0] } finally { thread.close() // The await above gives anything else a chance to close the state, and lua_close has diff --git a/src/thread.ts b/src/thread.ts index 14e3c67..8c79b8c 100755 --- a/src/thread.ts +++ b/src/thread.ts @@ -384,22 +384,6 @@ export default class Thread { this.module.lua_pop(this.address, count) } - public call(name: string, ...args: any[]): MultiReturn { - this.assertNotClosed() - const type = this.module.lua_getglobal(this.address, name) - if (type !== LuaType.Function) { - throw new TypeError(`cannot call '${name}': expected a function, got ${LuaType[type]}`) - } - - for (const arg of args) { - this.pushValue(arg) - } - - const base = this.getTop() - args.length - 1 // The 1 is for the function to run - this.pcall(args.length) - return this.getStackValues(base) - } - /** A synchronous call, which nothing can suspend: an `:await()` reached through it is an error. */ private pcall(argCount: number): void { const module = this.module @@ -548,10 +532,11 @@ export default class Thread { const type: LuaType = inputType ?? this.module.lua_type(this.address, index) switch (type) { + // nil is undefined, never null: a JS default parameter then applies to a nil argument, + // and an absent value reads the same whether Lua returned nil or nothing at all. case LuaType.None: - return undefined case LuaType.Nil: - return null + return undefined case LuaType.Number: { const value = this.module.lua_tonumberx(this.address, index, null) // Only outside the safe range can the integer subtype change the result, and diff --git a/src/type-extensions/function.ts b/src/type-extensions/function.ts index bb31197..5c6a151 100644 --- a/src/type-extensions/function.ts +++ b/src/type-extensions/function.ts @@ -3,7 +3,7 @@ import RawResult from '../raw-result' import type LuaState from '../state' import type Thread from '../thread' import TypeExtension from '../type-extension' -import { LUA_REGISTRYINDEX, LuaReturn, type LuaAddress, type LuaRunOptions, LuaType } from '../types' +import { LUA_REGISTRYINDEX, LuaReturn, type LuaAddress, type LuaCallOptions, LuaType } from '../types' import { isEmscriptenUnwind } from '../utils' import { reportIfUnobserved, SUSPEND } from '../async' @@ -244,7 +244,7 @@ export class FunctionTypeExtension extends TypeExtension { throw new Error('cannot yield in a Lua function called synchronously from JS, wrap it with state.async to let it') } callThread.assertOk(resumed.result) - result = resumed.resultCount >= 1 ? callThread.getValue(1) : null + result = resumed.resultCount >= 1 ? callThread.getValue(1) : undefined } catch (err) { this.releaseCallThread(callThread, true) throw err @@ -263,19 +263,13 @@ export class FunctionTypeExtension extends TypeExtension { return typeof value === 'function' && (value as LuaFunction)[this.luaFunction] !== undefined } - public async(jsFunc: FunctionType, options?: LuaRunOptions): (...args: unknown[]) => Promise { + public async(jsFunc: FunctionType, options?: LuaCallOptions): (...args: unknown[]) => Promise { if (!this.isLuaFunction(jsFunc)) { throw new TypeError('async expects a Lua function obtained from this state') } return (...args) => this.runCall((thread) => { - // Read off the function on every call rather than once above: holding on to it is - // what keeps its registry reference from being released. - const func = (jsFunc as LuaFunction)[this.luaFunction]! - const internalType = thread.module.lua_rawgeti(thread.address, LUA_REGISTRYINDEX, func) - if (internalType !== LuaType.Function) { - this.assertHasCallMetamethod(thread, internalType) - } + this.pushLuaFunction(thread, jsFunc) for (const arg of args) { thread.pushValue(arg) } @@ -283,6 +277,21 @@ export class FunctionTypeExtension extends TypeExtension { }, options) } + /** + * Pushes the Lua function behind `jsFunc`. Read off the function on every call rather than + * once by the caller: holding on to it is what keeps its registry reference from being released. + */ + public pushLuaFunction(thread: Thread, jsFunc: FunctionType): void { + const func = (jsFunc as LuaFunction)[this.luaFunction] + if (func === undefined) { + throw new TypeError('expected a Lua function obtained from this state') + } + const internalType = thread.module.lua_rawgeti(thread.address, LUA_REGISTRYINDEX, func) + if (internalType !== LuaType.Function) { + this.assertHasCallMetamethod(thread, internalType) + } + } + /** * Defines the Lua global `async`. What `async(fn)` returns is a Lua closure over `fn`, built by * {@link ASYNC_SOURCE}, rather than a JS function holding it: that way nothing has to be @@ -330,11 +339,10 @@ export class FunctionTypeExtension extends TypeExtension { /** * Runs what `prepare` leaves on a new thread -- a function, and as many arguments as it returns - * the count of -- as a run of its own, and resolves to its first result. A function that - * returned nil resolves to undefined like one that returned nothing, rather than to the null - * that `inject` marshals back into Lua as a sentinel, which is truthy there. + * the count of -- as a run of its own, and resolves to its first result, or to all of them + * with `returns: 'all'`. */ - private async runCall(prepare: (thread: Thread) => number, options?: LuaRunOptions): Promise { + private async runCall(prepare: (thread: Thread) => number, options?: LuaCallOptions): Promise { this.assertCallable() // A thread of its own rather than the pooled one, which a parked run would keep from every @@ -345,7 +353,7 @@ export class FunctionTypeExtension extends TypeExtension { const { functionTimeout: timeout, maxInstructions } = this const defaults = timeout !== undefined || maxInstructions !== undefined const values = await thread.run(prepare(thread), defaults ? { timeout, maxInstructions, ...options } : options) - return values[0] ?? undefined + return options?.returns === 'all' ? values : values[0] } finally { // The same teardown as LuaState.callByteCode. Sharing it through a helper costs each // parked doString a closure its suspended frame keeps alive. diff --git a/src/type-extensions/proxy.ts b/src/type-extensions/proxy.ts index 38d2382..928175c 100644 --- a/src/type-extensions/proxy.ts +++ b/src/type-extensions/proxy.ts @@ -65,7 +65,7 @@ class ProxyTypeExtension extends TypeExtension { return ret }, self, - null, + undefined, ) }, __eq: (self: any, other: any) => self === other, diff --git a/src/types.ts b/src/types.ts index fcc0e90..b6494fa 100755 --- a/src/types.ts +++ b/src/types.ts @@ -74,12 +74,14 @@ export interface LuaMemoryOptions { export interface LuaLimitOptions { /** * Milliseconds a Lua function called from JS may run before being interrupted, whether it is - * called directly or as a run of its own through `state.async` or Lua's `async`. + * called directly, through `state.call`, or as a run of its own through `state.async` or Lua's + * `async`. */ functionTimeout?: number | undefined /** * Instructions a single run may execute before being interrupted. A run is a `doString` or - * `doFile`, or a function started through `state.async`, Lua's `async` or a promise reaction. + * `doFile`, a `state.call`, or a function started through `state.async`, Lua's `async` or a + * promise reaction. */ maxInstructions?: number | undefined } @@ -125,7 +127,9 @@ export interface CreateStateOptions { * - `async`: `async(fn)` returns a function that runs `fn` as a run of its own and gives back * a promise of its first result, so that it can `:await()` whoever calls it. * - `Error`: `Error.create`, where the error bridge is registered (see `errors`). - * - `null`: a sentinel that a JS `null` is marshalled as instead of `nil`. It is truthy in Lua. + * - `null`: a sentinel that a JS `null` is marshalled as instead of `nil`, and that reads back + * as `null`. It is truthy in Lua. Without it `null` becomes `nil`, which reads back as + * `undefined` like every other `nil`. */ inject?: LuaInjectName[] | boolean | undefined /** @@ -176,7 +180,21 @@ export interface LuaLoadOptions { name?: string | undefined } -export type LuaDoOptions = LuaRunOptions & LuaLoadOptions +export interface LuaReturnOptions { + /** + * Which of the results Lua returned to give back. `'first'`, the default, gives the first one, + * or undefined when there was none; `'all'` gives every one of them as a `LuaMultiReturn`. + */ + returns?: 'first' | 'all' | undefined +} + +/** Options that ask for every result, which is what makes a call give back a `LuaMultiReturn`. */ +export type LuaAllReturns = Options & { returns: 'all' } + +/** What calling a Lua function takes: `state.call` and `state.async`. */ +export type LuaCallOptions = LuaRunOptions & LuaReturnOptions + +export type LuaDoOptions = LuaCallOptions & LuaLoadOptions /** * Deadline and budget enforced by the debug hook while a thread runs. Every field accepts an diff --git a/test/async.test.js b/test/async.test.js index c2db4f4..9362de5 100644 --- a/test/async.test.js +++ b/test/async.test.js @@ -254,6 +254,17 @@ describe('state.async', () => { expect(await state.doString('')).to.be.equal(undefined) }) + it('resolves to every result with returns all', async () => { + using state = await getState() + state.set('later', later) + const fn = state.doStringSync('return function(a, b) return later(a):await() + b, nil, "kept" end') + + const values = await state.async(fn, { returns: 'all' })(1, 2) + expect(values).to.be.instanceOf(LuaMultiReturn) + expect(values).to.be.eql([3, undefined, 'kept']) + expect(await state.async(state.doStringSync('return function() end'), { returns: 'all' })()).to.be.eql([]) + }) + it('returns a function to hand to whatever takes a callback', async () => { using state = await getState() state.set('later', later) @@ -494,7 +505,7 @@ describe('async', () => { it('is not there without inject, and does not need the standard libraries', async () => { using plain = await getState({ inject: false }) - expect(plain.doStringSync('return async')).to.be.equal(null) + expect(plain.doStringSync('return async')).to.be.equal(undefined) using bare = await getState({ libs: false }) bare.set('later', later) diff --git a/test/initialization.test.js b/test/initialization.test.js index 3042477..74ff57f 100644 --- a/test/initialization.test.js +++ b/test/initialization.test.js @@ -90,8 +90,8 @@ describe('Standard libraries', () => { using state = lua.createState({ libs: false }) // Without the base library there is no `type` either, so this reads the globals directly. - expect(state.get('print')).to.be.null - expect(state.get('tostring')).to.be.null + expect(state.get('print')).to.be.undefined + expect(state.get('tostring')).to.be.undefined }) it('libs defaults to all of them', async () => { @@ -170,7 +170,7 @@ describe('Disposal', () => { set: (state) => state.set('x', 1), doStringSync: (state) => state.doStringSync('return 1'), doFileSync: (state) => state.doFileSync('script.lua'), - call: (state) => state.call('print', 'hi'), + call: (state) => state.call('print', ['hi']), getTable: (state) => state.getTable('_G', () => undefined), loadString: (state) => state.loadString('return 1'), loadFile: (state) => state.loadFile('script.lua'), diff --git a/test/state.test.js b/test/state.test.js index 4b7cdb7..02cc570 100644 --- a/test/state.test.js +++ b/test/state.test.js @@ -1,5 +1,5 @@ import { EventEmitter } from 'events' -import { LuaReturn, LuaThread, LuaType, decorate } from '../dist/index.js' +import { LuaInstructionLimitError, LuaMultiReturn, LuaReturn, LuaThread, LuaTimeoutError, LuaType, decorate } from '../dist/index.js' import { expect } from 'chai' import { getState, getLua } from './utils.js' import { setTimeout } from 'node:timers/promises' @@ -347,12 +347,75 @@ describe('State', () => { end `) - const returns = state.call('f', 10, 25) + expect(state.call('f', [10, 25])).to.be.equal(1) + + const returns = state.call('f', [10, 25], { returns: 'all' }) + expect(returns).to.be.instanceOf(LuaMultiReturn) expect(returns).to.have.length(6) expect(returns.slice(0, -1)).to.eql([1, 10, 25, 'Hello World', {}]) expect(returns.at(-1)).to.be.a('function') }) + it('call a lua function with options should succeed', async () => { + using state = await getState() + const divmod = state.doStringSync('return function(a, b) return a // b, a % b end') + + expect(state.call(divmod, [7, 2])).to.be.equal(3) + expect(state.call(divmod, [7, 2], { returns: 'all' })).to.be.eql([3, 1]) + + const spin = state.doStringSync('return function() while true do end end') + expect(() => state.call(spin, [], { timeout: 5 })).to.throw(LuaTimeoutError) + expect(() => state.call(spin, [], { maxInstructions: 1000 })).to.throw(LuaInstructionLimitError) + // A limit set for one call is gone by the next. + expect(state.call(divmod, [9, 2])).to.be.equal(4) + }) + + it('call should run under limits.functionTimeout like a direct call', async () => { + using state = await getState({ limits: { functionTimeout: 5 } }) + state.doStringSync('function spin() while true do end end') + + expect(() => state.call('spin')).to.throw(LuaTimeoutError) + expect(() => state.get('spin')()).to.throw(LuaTimeoutError) + }) + + it('call should run under the limits set on the state', async () => { + using state = await getState({ limits: { maxInstructions: 1000 } }) + const spin = state.doStringSync('function spin() while true do end end return spin') + + expect(() => state.call('spin')).to.throw(LuaInstructionLimitError) + expect(() => state.call(spin)).to.throw(LuaInstructionLimitError) + + using timed = await getState() + timed.doStringSync('function spin() while true do end end') + timed.setDeadline(Date.now() + 5) + expect(() => timed.call('spin')).to.throw(LuaTimeoutError) + }) + + it('call should refuse anything but an array of arguments and a lua function', async () => { + using state = await getState() + using other = await getState() + state.doStringSync('function f(...) return ... end') + + expect(() => state.call('f', 10, 25)).to.throw('call takes the arguments as an array') + expect(() => state.call('missing')).to.throw(`cannot call 'missing': expected a function, got Nil`) + expect(() => state.call(() => 1)).to.throw('expected a Lua function obtained from this state') + expect(() => state.call(other.doStringSync('return function() end'))).to.throw('expected a Lua function obtained from this state') + }) + + it('call should not grow the lua stack', async () => { + using state = await getState() + state.doStringSync('function f(...) return ... end') + const top = state.getTop() + + for (let i = 0; i < 100; i++) { + state.call('f', [1, 2, 3]) + state.call('f', [1, 2, 3], { returns: 'all' }) + } + expect(() => state.call('missing')).to.throw() + + expect(state.getTop()).to.be.equal(top) + }) + it('call a global function that raises should throw instead of panicking', async () => { using state = await getState() state.doStringSync('function boom() error("kaboom") end') @@ -961,12 +1024,13 @@ describe('State', () => { const a = await state.doString(`return 1`) const b = state.doStringSync(`return 5`) - const values = state.call('hello', 'joao') + const value = state.call('hello', ['joao']) + const values = state.call('hello', ['joao'], { returns: 'all' }) expect(a).to.be.equal(1) expect(b).to.be.equal(5) - expect(values).to.have.length(1) - expect(values[0]).to.be.equal('Hello joao!') + expect(value).to.be.equal('Hello joao!') + expect(values).to.be.eql(['Hello joao!']) }) it('create a large string variable should succeed', async () => { @@ -1265,7 +1329,20 @@ describe('State', () => { `) state.pushValue(null) const res = await state.run(1) - expect(res).to.deep.equal([null, null, 'nil']) + expect(res).to.deep.equal([undefined, undefined, 'nil']) + }) + + it('null and nil should stay apart when null is injected', async () => { + using state = await getState() + const seen = [] + state.set('record', (...args) => void seen.push(args)) + + await state.doString('record(nil, null, 1)') + expect(seen).to.be.eql([[undefined, null, 1]]) + expect(await state.doString('return nil, null', { returns: 'all' })).to.be.eql([undefined, null]) + // And back again: undefined is nil, null is the sentinel. + state.set('echo', (...args) => LuaMultiReturn.of(...args)) + expect(await state.doString('return type(echo(nil)), type(echo(null))', { returns: 'all' })).to.be.eql(['nil', 'userdata']) }) it('reassigning the null global should not affect pushing null', async () => { @@ -1366,6 +1443,71 @@ describe('State', () => { }) }) +describe('Value conventions', () => { + it('nil should read as undefined wherever it comes from', async () => { + using state = await getState({ inject: false }) + + expect(state.get('missing')).to.be.undefined + expect(state.doStringSync('return nil')).to.be.undefined + expect(await state.doString('return nil')).to.be.undefined + expect(state.doStringSync('return function() return nil end')()).to.be.undefined + expect(state.doStringSync('return function() end')()).to.be.undefined + expect(state.call('tostring', [1], { returns: 'all' })).to.be.eql(['1']) + expect(state.doStringSync('return { present = 1 }').absent).to.be.undefined + }) + + it('a nil argument should take the default of a JS parameter', async () => { + using state = await getState({ inject: false }) + const seen = [] + state.set('greet', (name = 'world', ...rest) => { + seen.push(rest) + return `hello ${name}` + }) + + expect(state.doStringSync('return greet()')).to.be.equal('hello world') + expect(state.doStringSync('return greet(nil)')).to.be.equal('hello world') + expect(state.doStringSync('return greet(nil, nil, 3)')).to.be.equal('hello world') + expect(seen).to.be.eql([[], [], [undefined, 3]]) + }) + + it('a JS null and undefined should both be nil without the null sentinel', async () => { + using state = await getState({ inject: false }) + state.set('values', () => LuaMultiReturn.of(null, undefined)) + + expect( + state.doStringSync('return select("#", values()), type((values())), type((select(2, values())))', { returns: 'all' }), + ).to.be.eql([2, 'nil', 'nil']) + }) + + for (const [name, run] of Object.entries({ + doString: (state, options) => state.doString('return 1, nil, "three"', options), + doStringSync: (state, options) => state.doStringSync('return 1, nil, "three"', options), + doFile: (state, options) => state.doFile('/values.lua', options), + doFileSync: (state, options) => state.doFileSync('/values.lua', options), + })) { + it(`${name} should give the first result, and every one of them with returns all`, async () => { + const lua = await getLua() + lua.writeFile('/values.lua', 'return 1, nil, "three"') + using state = lua.createState() + + expect(await run(state)).to.be.equal(1) + expect(await run(state, { returns: 'first' })).to.be.equal(1) + + const values = await run(state, { returns: 'all' }) + expect(values).to.be.instanceOf(LuaMultiReturn) + expect(values).to.be.eql([1, undefined, 'three']) + }) + } + + it('returns all should give an empty list for a script that returns nothing', async () => { + using state = await getState() + + expect(await state.doString('', { returns: 'all' })).to.be.eql([]) + expect(state.doStringSync('', { returns: 'all' })).to.be.eql([]) + expect(await state.doString('')).to.be.undefined + }) +}) + describe('Load mode', () => { it('loadString refuses bytecode by default', async () => { using state = await getState()