|
3 | 3 | WASM bindings and binaries for Lua 5.1 to 5.4. |
4 | 4 |
|
5 | 5 | Make sure to run `./scripts/setup.ts` (requires emscripten sdk) first before using `npm run build`. |
6 | | -### Important: This currently only includes bindings used to test TypescriptToLua |
| 6 | +### Important: This currently only includes the bindings used to test TypescriptToLua |
7 | 7 |
|
8 | | -In the future Bindings for the complte API may be added. |
| 8 | +In the future Bindings for the complete API may be added. |
| 9 | + |
| 10 | +### Example |
| 11 | + |
| 12 | +```ts |
| 13 | +import { LUA_OK } from "lua-wasm-bindings/dist/lua"; |
| 14 | + |
| 15 | +import { lauxlib, lua, lualib } from "lua-wasm-bindings/dist/lua.54"; |
| 16 | + |
| 17 | + |
| 18 | +const luaCode = `return "Hello"`; |
| 19 | +consol.log(executeLua(luaCode)); |
| 20 | + |
| 21 | +function executeLua (luaCode: string): string { |
| 22 | + const L = lauxlib.luaL_newstate(); |
| 23 | + lualib.luaL_openlibs(L); |
| 24 | + |
| 25 | + // Optional Load modules |
| 26 | + // lua.lua_getglobal(L, "package"); |
| 27 | + // lua.lua_getfield(L, -1, "preload"); |
| 28 | + // lauxlib.luaL_loadstring(L, jsonLib); // Load extenal package from string |
| 29 | + // lua.lua_setfield(L, -2, "json"); |
| 30 | + |
| 31 | + const status = lauxlib.luaL_dostring(L, luaCode); |
| 32 | + |
| 33 | + if (status === LUA_OK) { |
| 34 | + if (lua.lua_isstring(L, -1)) { |
| 35 | + const result = lua.lua_tostring(L, -1); |
| 36 | + lua.lua_close(L); |
| 37 | + return result === null ? undefined : result; |
| 38 | + } else { |
| 39 | + const returnType = lua.lua_typename(L, lua.lua_type(L, -1)); |
| 40 | + lua.lua_close(L); |
| 41 | + throw new Error(`Unsupported Lua return type: ${returnType}`); |
| 42 | + } |
| 43 | + } else { |
| 44 | + const luaStackString = lua.lua_tostring(L, -1); |
| 45 | + const message = luaStackString.replace(/^\[string "(--)?\.\.\."\]:\d+: /, ""); |
| 46 | + lua.lua_close(L); |
| 47 | + return new Error(message); |
| 48 | + } |
| 49 | +} |
| 50 | +``` |
| 51 | + |
0 commit comments