Skip to content

Commit cf13fff

Browse files
committed
refactor: put the loadstring cstring on the stack, so it can be easily reclaimed
1 parent d4a5d7b commit cf13fff

File tree

3 files changed

+10
-5
lines changed

3 files changed

+10
-5
lines changed

scripts/build.sh

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ cd ../..
2020
if [[ "$1" == "lua-5.0.3" ]]; then
2121
emcc -Ithirdparty/$1 thirdparty/$1/lib/liblua.a thirdparty/$1/lib/liblualib.a \
2222
-s WASM=1 -O3 -o dist/glue/glue-$1.js \
23-
-s EXPORTED_RUNTIME_METHODS="['cwrap', 'allocateUTF8', 'lengthBytesUTF8']" \
23+
-s EXPORTED_RUNTIME_METHODS="['cwrap', 'stackSave', 'stackRestore', 'lengthBytesUTF8', 'allocateUTF8OnStack']" \
2424
-s MODULARIZE=1 \
2525
-s ALLOW_TABLE_GROWTH \
2626
-s EXPORT_NAME="glue" \

src/binding-factory.ts

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -165,8 +165,11 @@ const lauxBindings: Record<string, lauxBindingFactoryFunc> = {
165165
return (this as LauxLib).luaL_loadstring(L, s) || lua.lua_pcall(L, 0, LUA_MULTRET, 0);
166166
},
167167
luaL_loadstring: function(L: LuaState, s: string) {
168-
const ptr = luaGlue.allocateUTF8(s) as unknown;
169-
return (this as LauxLib).luaL_loadbuffer(L, ptr as string, luaGlue.lengthBytesUTF8(s), s);
168+
const lastStack = luaGlue.stackSave();
169+
const cstr = luaGlue.allocateUTF8OnStack(s) as unknown;
170+
const result = (this as LauxLib).luaL_loadbuffer(L, cstr as string, luaGlue.lengthBytesUTF8(s), s);
171+
luaGlue.stackRestore(lastStack);
172+
return result;
170173
},
171174
// Note that s has a "number" type, so we can pass a raw pointer
172175
luaL_loadbuffer: luaGlue.cwrap("luaL_loadbuffer", "number", ["number", "number", "number", "string"]),

src/glue/glue.ts

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
export interface LuaEmscriptenModule extends EmscriptenModule {
2-
allocateUTF8: typeof allocateUTF8;
3-
lengthBytesUTF8: typeof lengthBytesUTF8;
42
cwrap: typeof cwrap;
3+
stackSave: typeof stackSave;
4+
stackRestore: typeof stackRestore;
5+
lengthBytesUTF8: typeof lengthBytesUTF8;
6+
allocateUTF8OnStack: typeof allocateUTF8;
57
}
68

79
export type EmscriptenModuleFactorySync<T extends EmscriptenModule = EmscriptenModule> = (

0 commit comments

Comments
 (0)