Skip to content

Commit 2863282

Browse files
committed
fix: correct relative offsets in getfield and setfield polyfills
1 parent 00aae45 commit 2863282

File tree

1 file changed

+10
-8
lines changed

1 file changed

+10
-8
lines changed

src/binding-factory.ts

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,11 @@ const luaBindings: Record<string, luaBindingFactoryFunc> = {
2929
},
3030
lua_getfield: function(L: LuaState, index: number, k: string) {
3131
(this as Lua).lua_pushstring(L, k);
32-
return (this as Lua).lua_gettable(L, index);
32+
33+
// If the index is a relative offset, it needs to be corrected for the grown stack
34+
const isOffset = index < 0 && index !== LUA_GLOBALSINDEX_50;
35+
36+
return (this as Lua).lua_gettable(L, isOffset ? index - 1 : index);
3337
},
3438
lua_setfield: function(L: LuaState, index: number, k: string) {
3539
// The value to set is expected to be on the top of the stack
@@ -38,14 +42,12 @@ const luaBindings: Record<string, luaBindingFactoryFunc> = {
3842
(this as Lua).lua_pushstring(L, k);
3943

4044
// Swap key and value because settable expects stack in that order
41-
42-
// Copy value to top of stack
43-
(this as Lua).lua_pushvalue(L, -2);
45+
(this as Lua).lua_insert(L, -2);
4446

45-
// Remove original value from stack
46-
(this as Lua).lua_remove(L, -3);
47-
48-
const result = (this as Lua).lua_settable(L, index);
47+
// If the index is a relative offset, it needs to be corrected for the grown stack
48+
const isOffset = index < 0 && index !== LUA_GLOBALSINDEX_50;
49+
50+
const result = (this as Lua).lua_settable(L, isOffset ? index - 1 : index);
4951

5052
return result;
5153
},

0 commit comments

Comments
 (0)