import Global from './global' ; import Thread from './thread' ; import createErrorType from './type-extensions/error' ; import createFunctionType from './type-extensions/function' ; import createPromiseType from './type-extensions/promise' ; import createProxyType from './type-extensions/proxy' ; import createTableType from './type-extensions/table' ; import createUserdataType from './type-extensions/userdata' ; import type LuaWasm from './luawasm' ; export default class LuaEngine { public global : Global ; public constructor ( private cmodule , { openStandardLibs = true , injectObjects = false , enableProxy = true , traceAllocations = false } = { } ) { this . global = new Global ( this . cmodule , traceAllocations ) ; this . global . registerTypeExtension ( 0 , createTableType ( this . global ) ) ; this . global . registerTypeExtension ( 0 , createFunctionType ( this . global ) ) ; this . global . registerTypeExtension ( 1 , createPromiseType ( this . global , injectObjects ) ) ; if ( enableProxy ) { this . global . registerTypeExtension ( 3 , createProxyType ( this . global ) ) ; } else { this . global . registerTypeExtension ( 1 , createErrorType ( this . global , injectObjects ) ) ; } this . global . registerTypeExtension ( 4 , createUserdataType ( this . global ) ) ; if ( openStandardLibs ) { this . cmodule . luaL_openlibs ( this . global . address ) ; } } public doString ( script ) { return this . callByteCode ( ( thread ) => thread . loadString ( script ) ) ; } public doFile ( filename ) { return this . callByteCode ( ( thread ) => thread . loadFile ( filename ) ) ; } public doStringSync ( script ) { this . global . loadString ( script ) ; const result = this . global . runSync ( ) ; return result [ 0 ] ; } public doFileSync ( filename ) { this . global . loadFile ( filename ) ; const result = this . global . runSync ( ) ; return result [ 0 ] ; } private async callByteCode ( loader ) { const thread = this . global . newThread ( ) ; const threadIndex = this . global . getTop ( ) ; try { loader ( thread ) ; const result = await thread . run ( 0 ) ; if ( result . length > 0 ) { this . cmodule . lua_xmove ( thread . address , this . global . address , result . length ) ; } return result [ 0 ] ; } finally { this . global . remove ( threadIndex ) ; } } }