MCPcopy Index your code
hub / github.com/TypeScriptToLua/TypeScriptToLua / executeLua

Function executeLua

test/util.ts:442–497  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

440 }
441
442 private executeLua(): any {
443 // Main file
444 const mainFile = this.getMainLuaCodeChunk();
445
446 const luaTarget = this.options.luaTarget ?? tstl.LuaTarget.Lua55;
447 const { lauxlib, lua, lualib } = getLuaBindingsForVersion(luaTarget);
448
449 const L = lauxlib.luaL_newstate();
450 lualib.luaL_openlibs(L);
451
452 // Load modules
453 // Json
454 this.injectLuaFile(L, lua, lauxlib, "json", jsonLib(luaTarget));
455 // Lua lib
456 if (
457 this.options.luaLibImport === tstl.LuaLibImportKind.Require ||
458 mainFile.includes('require("lualib_bundle")')
459 ) {
460 this.injectLuaFile(L, lua, lauxlib, "lualib_bundle", readLuaLib(luaTarget));
461 }
462
463 // Load all transpiled files into Lua's package cache
464 const { transpiledFiles } = this.getLuaResult();
465 for (const transpiledFile of transpiledFiles) {
466 if (transpiledFile.lua) {
467 const filePath = path.relative(getEmitOutDir(this.getProgram()), transpiledFile.outPath);
468 this.injectLuaFile(L, lua, lauxlib, filePath, transpiledFile.lua);
469 }
470 }
471
472 // Execute Main
473 const wrappedMainCode = `
474local JSON = require("json");
475return JSON.stringify((function()
476 ${this.getLuaCodeWithWrapper(mainFile)}
477end)());`;
478
479 const status = lauxlib.luaL_dostring(L, wrappedMainCode);
480
481 if (status === LUA_OK) {
482 if (lua.lua_isstring(L, -1)) {
483 const result = eval(`(${lua.lua_tostring(L, -1)})`);
484 lua.lua_close(L);
485 return result === null ? undefined : result;
486 } else {
487 const returnType = lua.lua_typename(L, lua.lua_type(L, -1));
488 lua.lua_close(L);
489 throw new Error(`Unsupported Lua return type: ${returnType}`);
490 }
491 } else {
492 const luaStackString = lua.lua_tostring(L, -1);
493 const message = luaStackString.replace(/^\[string "(--)?\.\.\."\]:\d+: /, "");
494 lua.lua_close(L);
495 return new ExecutionError(message);
496 }
497 }
498
499 private injectLuaFile(state: LuaState, lua: Lua, lauxlib: LauxLib, fileName: string, fileContent: string) {

Callers

nothing calls this directly

Calls 6

getEmitOutDirFunction · 0.90
getLuaBindingsForVersionFunction · 0.85
jsonLibFunction · 0.85
readLuaLibFunction · 0.85
getLuaResultMethod · 0.80
getLuaCodeWithWrapperMethod · 0.80

Tested by

no test coverage detected