From 11bbd9dac36e9a09da1a2807a8ed3d0f4c4d58c0 Mon Sep 17 00:00:00 2001 From: gudzpoz Date: Wed, 3 Apr 2024 22:16:11 +0800 Subject: [PATCH] Default null to nil when injectObjects is not set --- src/thread.ts | 9 +++++++-- src/type-extensions/promise.ts | 2 +- test/engine.test.js | 12 ++++++++++++ 3 files changed, 20 insertions(+), 3 deletions(-) diff --git a/src/thread.ts b/src/thread.ts index 12e26f4..7df595f 100755 --- a/src/thread.ts +++ b/src/thread.ts @@ -217,9 +217,14 @@ export default class Thread { this.lua.lua_pushboolean(this.address, target ? 1 : 0) break default: - if (!this.typeExtensions.find((wrapper) => wrapper.extension.pushValue(this, decoratedValue, userdata))) { - throw new Error(`The type '${typeof target}' is not supported by Lua`) + if (this.typeExtensions.find((wrapper) => wrapper.extension.pushValue(this, decoratedValue, userdata))) { + break } + if (target === null) { + this.lua.lua_pushnil(this.address) + break + } + throw new Error(`The type '${typeof target}' is not supported by Lua`) } if (decoratedValue.options.metatable) { diff --git a/src/type-extensions/promise.ts b/src/type-extensions/promise.ts index 6331869..160c463 100644 --- a/src/type-extensions/promise.ts +++ b/src/type-extensions/promise.ts @@ -131,7 +131,7 @@ class PromiseTypeExtension extends TypeExtension> { } public pushValue(thread: Thread, decoration: Decoration>): boolean { - if (Promise.resolve(decoration.target) !== decoration.target && typeof decoration.target.then !== 'function') { + if (Promise.resolve(decoration.target) !== decoration.target && typeof decoration.target?.then !== 'function') { return false } return super.pushValue(thread, decoration) diff --git a/test/engine.test.js b/test/engine.test.js index 7677358..a2cdbb5 100755 --- a/test/engine.test.js +++ b/test/engine.test.js @@ -782,6 +782,18 @@ describe('Engine', () => { expect(res).to.deep.equal([null, null, 'null']) }) + it('null injected as nil', async () => { + const engine = await getEngine({ injectObjects: false }) + engine.global.loadString(` + local args = { ... } + assert(type(args[1]) == "nil", string.format("expected first argument to be nil, got %s", type(args[1]))) + return nil, args[1], tostring(nil) + `) + engine.global.pushValue(null) + const res = await engine.global.run(1) + expect(res).to.deep.equal([null, null, 'nil']) + }) + it('Nested callback from JS to Lua', async () => { const engine = await getEngine() engine.global.set('call', (fn) => fn())