1- //import {lauxlib, lua, lualib, to_jsstring, to_luastring } from "fengari";
1+ import { lauxlib , lua , lualib , to_jsstring , to_luastring , interop } from "fengari-web" ;
2+
3+ declare var self : any ;
4+
5+ function executeLua ( luaStr : string ) : any {
6+ // clear print buffer and patch lua print
7+ self . printStream = "" ;
8+ const printToGlobal = `
9+ local js = require "js"
10+ local oldPrint = print
11+ _G.print = function(...)
12+ local elements = table.pack(...)
13+ for i = 1, elements.n do
14+ js.global.printStream = js.global.printStream .. tostring(elements[i]) .. "\\t"
15+ end
16+ js.global.printStream = js.global.printStream .. "\\n"
17+ end
18+ ` ;
19+
20+ luaStr = printToGlobal + luaStr ;
21+
22+ const L = lauxlib . luaL_newstate ( ) ;
23+ lualib . luaL_openlibs ( L ) ;
24+ lauxlib . luaL_requiref ( L , to_luastring ( "js" ) , interop . luaopen_js , 1 ) ;
25+ lua . lua_pop ( L , 1 ) ;
26+ const status = lauxlib . luaL_dostring ( L , to_luastring ( luaStr ) ) ;
27+
28+ if ( status === lua . LUA_OK ) {
29+ // Read the return value from stack depending on its type.
30+ if ( lua . lua_isboolean ( L , - 1 ) ) {
31+ return lua . lua_toboolean ( L , - 1 ) ;
32+ } else if ( lua . lua_isnil ( L , - 1 ) ) {
33+ return null ;
34+ } else if ( lua . lua_isnumber ( L , - 1 ) ) {
35+ return lua . lua_tonumber ( L , - 1 ) ;
36+ } else if ( lua . lua_isstring ( L , - 1 ) ) {
37+ return lua . lua_tojsstring ( L , - 1 ) ;
38+ } else {
39+ throw new Error ( "Unsupported lua return type: " + to_jsstring ( lua . lua_typename ( L , lua . lua_type ( L , - 1 ) ) ) ) ;
40+ }
41+ } else {
42+ // If the lua VM did not terminate with status code LUA_OK an error occurred.
43+ // Throw a JS error with the message, retrieved by reading a string from the stack.
44+
45+ // Filter control characters out of string which are in there because ????
46+ throw new Error ( "LUA ERROR: " + to_jsstring ( lua . lua_tostring ( L , - 1 ) . filter ( ( c : number ) => c >= 20 ) ) ) ;
47+ }
48+ }
249
350onmessage = ( event : MessageEvent ) => {
4- //postMessage({luaStr: transpileString(event.data.tsStr)});
51+ executeLua ( event . data . luaStr ) ;
52+ postMessage ( { luaPrint : self . printStream } ) ;
553} ;
0 commit comments