int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { int argc; char ** argv = CommandLineToArgvA(GetCommandLineA(),&argc); #else int main (int argc, char *argv[]) { #endif HINSTANCE hinstLib; char buffer[MAX_PATH],*file; if (!GetFullPathName(argv[0],MAX_PATH,buffer,&file)) { MessageBox(NULL, TEXT("Couldn't find the correct working directory"), TEXT("Failed to start editor"), MB_OK|MB_ICONERROR); return 0; } if (file!=NULL) *file = 0; // finish the string, don't need the appname SetCurrentDirectory(buffer); // set the application as DPI aware typedef enum _Process_DPI_Awareness { Process_DPI_Unaware = 0, Process_System_DPI_Aware = 1, Process_Per_Monitor_DPI_Aware = 2 } Process_DPI_Awareness; typedef BOOL (WINAPI *SetProcessDPIAwareness_t)(Process_DPI_Awareness); SetProcessDPIAwareness_t pfnSetProcessDPIAwareness = (SetProcessDPIAwareness_t) GetProcAddress(GetModuleHandle(TEXT("user32.dll")), "SetProcessDPIAware"); if (NULL != pfnSetProcessDPIAwareness) pfnSetProcessDPIAwareness(Process_System_DPI_Aware); hinstLib = LoadLibrary(".\\bin\\lua51.dll"); if (hinstLib != NULL) { luaL_newstate = (voidfunc*) GetProcAddress(hinstLib, "luaL_newstate"); luaL_loadbuffer = (varfunc*) GetProcAddress(hinstLib, "luaL_loadbuffer"); luaL_openlibs = (varfunc*) GetProcAddress(hinstLib, "luaL_openlibs"); lua_pcall = (varfunc*)GetProcAddress(hinstLib, "lua_pcall"); lua_tolstring = (varfunc*)GetProcAddress(hinstLib, "lua_tolstring"); lua_setfield = (varfunc*)GetProcAddress(hinstLib, "lua_setfield"); lua_pushcclosure = (varfunc*)GetProcAddress(hinstLib, "lua_pushcclosure"); lua_createtable = (varfuncvoid*)GetProcAddress(hinstLib, "lua_createtable"); lua_pushstring = (varfuncvoid*)GetProcAddress(hinstLib, "lua_pushstring"); lua_rawseti = (varfuncvoid*)GetProcAddress(hinstLib, "lua_rawseti"); // If the function address is valid, call the function. if (luaL_newstate && luaL_loadbuffer && luaL_openlibs && lua_pcall && lua_pushcclosure && lua_setfield && lua_tolstring && lua_createtable && lua_pushstring && lua_rawseti) { // OK, I don't do any error checking here, which COULD // lead to bugs that are hard to find, but considered the simplicity // of the whole process, it SHOULD be pretty unlikely to fail here // but don't come back on me if it does... void *L = luaL_newstate(); int i; if (L!=NULL) { lua_createtable(L,argc,0); for (i=0;i<argc;i++) { lua_pushstring(L,argv[i]); lua_rawseti(L,-2,i+1); } lua_setfield(L,LUA_GLOBALSINDEX,"_ARG"); luaL_openlibs(L); lua_pushcclosure(L,luafunc_mbox,0); lua_setfield(L,LUA_GLOBALSINDEX,"_ERRMSG"); if (luaL_loadbuffer(L,luacode,strlen(luacode),"Initializer") == 0) lua_pcall(L,0,0,0); else MessageBox(NULL, TEXT("An unexpected error occured while loading the lua chunk."), TEXT("Failed to start editor"), MB_OK|MB_ICONERROR); } else MessageBox(NULL, TEXT("Couldn't initialize a luastate"), TEXT("Failed to start editor"), MB_OK|MB_ICONERROR); } else { MessageBox(NULL, TEXT("Could not load all functions that are supposed to be located in the lua51.dll\n" "This is not supposed to be happening..."), TEXT("Failed to start editor"), MB_OK|MB_ICONERROR); } // Free the DLL module. FreeLibrary(hinstLib); } else { MessageBox(NULL, TEXT("The lua51.dll could not be found or loaded, please check the working directory of the application.\n"), TEXT("Failed to initialize editor"), MB_OK|MB_ICONERROR); } return 0; }
/** * @brief Loads up an event from an XML node. * * @param temp Event to load up. * @param parent Event parent node. * @return 0 on success. */ static int event_parse( EventData_t *temp, const xmlNodePtr parent ) { xmlNodePtr node, cur; char str[PATH_MAX] = "\0"; char *buf; #ifdef DEBUGGING /* To check if event is valid. */ lua_State *L; int ret; uint32_t len; #endif /* DEBUGGING */ memset( temp, 0, sizeof(EventData_t) ); /* get the name */ temp->name = xml_nodeProp(parent, "name"); if (temp->name == NULL) WARN("Event in "EVENT_DATA_PATH" has invalid or no name"); node = parent->xmlChildrenNode; do { /* load all the data */ /* Only check nodes. */ xml_onlyNodes(node); if (xml_isNode(node,"lua")) { nsnprintf( str, PATH_MAX, EVENT_LUA_PATH"%s.lua", xml_get(node) ); temp->lua = strdup( str ); str[0] = '\0'; #ifdef DEBUGGING /* Check to see if syntax is valid. */ L = luaL_newstate(); buf = ndata_read( temp->lua, &len ); ret = luaL_loadbuffer(L, buf, len, temp->name ); if (ret == LUA_ERRSYNTAX) { WARN("Event Lua '%s' of event '%s' syntax error: %s", temp->name, temp->lua, lua_tostring(L,-1) ); } free(buf); lua_close(L); #endif /* DEBUGGING */ continue; } /* Trigger. */ else if (xml_isNode(node,"trigger")) { buf = xml_get(node); if (buf == NULL) WARN("Event '%s': Null trigger type.", temp->name); else if (strcmp(buf,"enter")==0) temp->trigger = EVENT_TRIGGER_ENTER; else if (strcmp(buf,"land")==0) temp->trigger = EVENT_TRIGGER_LAND; else if (strcmp(buf,"load")==0) temp->trigger = EVENT_TRIGGER_LOAD; else if (strcmp(buf,"none")==0) temp->trigger = EVENT_TRIGGER_NONE; else WARN("Event '%s' has invalid 'trigger' parameter: %s", temp->name, buf); continue; } /* Flags. */ else if (xml_isNode(node,"flags")) { /* set the various flags */ cur = node->children; do { xml_onlyNodes(cur); if (xml_isNode(cur,"unique")) { temp->flags |= EVENT_FLAG_UNIQUE; continue; } WARN("Event '%s' has unknown flag node '%s'.", temp->name, cur->name); } while (xml_nextNode(cur)); continue; } /* Condition. */ xmlr_strd(node,"cond",temp->cond); /* Get chance. */ xmlr_float(node,"chance",temp->chance); DEBUG("Unknown node '%s' in event '%s'", node->name, temp->name); } while (xml_nextNode(node)); /* Process. */ temp->chance /= 100.; #define MELEMENT(o,s) \ if (o) WARN("Mission '%s' missing/invalid '"s"' element", temp->name) MELEMENT(temp->lua==NULL,"lua"); MELEMENT((temp->trigger!=EVENT_TRIGGER_NONE) && (temp->chance==0.),"chance"); MELEMENT(temp->trigger==EVENT_TRIGGER_NULL,"trigger"); #undef MELEMENT return 0; }
LUALIB_API int (luaL_loadstring) (lua_State *L, const char *s) { return luaL_loadbuffer(L, s, strlen(s), s); }
/** * @brief Executes the Lua script from bytecode. * * @param pUser The user running the script. * @param pNpc The NPC attached to the script. * @param nEventID Identifier for the event. * @param bSelectedReward The reward selected, if applicable. * @param filename The script's filename for debugging purposes. * @param bytecode The script's compiled bytecode. * * @return true if it succeeds, false if it fails. */ bool CLuaScript::ExecuteScript(CUser * pUser, CNpc * pNpc, int32 nEventID, int8 bSelectedReward, const char * filename, BytecodeBuffer & bytecode) { // Ensure that we wait until the last user's done executing their script. FastGuard lock(m_lock); /* Attempt to run the script. */ // Load the buffer with our bytecode. int err = luaL_loadbuffer(m_luaState, reinterpret_cast<const char *>(&bytecode[0]), bytecode.size(), nullptr); if (err != LUA_OK) { RetrieveLoadError(err, filename); return false; } #if !defined(USE_ORIGINAL_QUESTS) // our quest implementation // The user & NPC instances are globals. As is the selected quest reward. lua_tsetglobal(m_luaState, LUA_SCRIPT_GLOBAL_USER, pUser); lua_tsetglobal(m_luaState, LUA_SCRIPT_GLOBAL_NPC, pNpc); lua_tsetglobal(m_luaState, LUA_SCRIPT_GLOBAL_SELECTED_REWARD, bSelectedReward); // Find & assign script's entry point to the stack lua_getglobal(m_luaState, LUA_SCRIPT_ENTRY_POINT); // Entry point requires 1 arguments: the event ID. lua_tpush(m_luaState, nEventID); // Try calling the script's entry point (Main()). err = lua_pcall(m_luaState, 1, // 1 arguments 0, // 0 returned values 0); // no error handler #else lua_tsetglobal(m_luaState, "UID", pUser->GetID()); lua_tsetglobal(m_luaState, "STEP", bSelectedReward); lua_tsetglobal(m_luaState, "EVENT", nEventID); // Try calling the script's entry point err = lua_pcall(m_luaState, 0, // no arguments 0, // 0 returned values 0); // no error handler #endif // Nothing returned, so we can finish up here. if (err == LUA_OK) { #if defined(USE_ORIGINAL_QUESTS) lua_settop(m_luaState, 0); #endif return true; } // Attempt to provide somewhat informative errors to help the user figure out what's wrong. switch (err) { case LUA_ERRRUN: printf("ERROR: A runtime error occurred within Lua script `%s`.\n", filename); break; case LUA_ERRMEM: printf("ERROR: Unable to allocate memory during execution of Lua script `%s`.\n", filename); break; case LUA_ERRERR: printf("ERROR: An error occurred during Lua script `%s`. Error handler failed.\n", filename); break; default: printf("ERROR: An unknown error occurred in Lua script `%s`.\n", filename); break; } // Is there an error set? That can be more useful than our generic error. if (lua_isstring(m_luaState, -1)) { printf("ERROR: [%s] The following error was provided:\n%s\n", filename, lua_to<const char *>(m_luaState, -1)); } #if defined(USE_ORIGINAL_QUESTS) lua_settop(m_luaState, 0); #endif return false; }
int terra_loadandrunbytecodes(lua_State * L, const unsigned char * bytecodes, size_t size, const char * name) { return luaL_loadbuffer(L, (const char *)bytecodes, size, name) || lua_pcall(L,0,LUA_MULTRET,0); }
static int dostring (lua_State *L, const char *s, const char *name) { int status = luaL_loadbuffer(L, s, strlen(s), name); if (status == LUA_OK) status = docall(L, 0, 0); return report(L, status); }
int main_core(int argc,char* argv[]) { const char *lua_err; int status; const char *p = NULL; size_t sz = 0; int rv = 0; #ifdef EQ_TEST_HARNESS #define BOOTSTRAP_MODULE "bootstrap-test" #else #ifndef LOCAL_DEV #define BOOTSTRAP_MODULE "bootstrap-http" #else #define BOOTSTRAP_MODULE "bootstrap-local" #endif #endif equus_set_argv(argc, argv); rv = equus_util_init(); if (rv < 0) { return EXIT_FAILURE; } #ifndef _WIN32 if (signal (SIGHUP, hup_handler) == SIG_IGN) { signal (SIGHUP, SIG_IGN); } if (signal (SIGUSR1, usr1_handler) == SIG_IGN) { signal (SIGUSR1, SIG_IGN); } #endif status = equus_bootstrap_get_module(BOOTSTRAP_MODULE, &p, &sz); if (status != 0) { logCrit("Errorcode: bootstrap broken.\n"); return EXIT_FAILURE; } do { lua_State* L; equus_restart_set(0); g_equus_run_count++; L = equus_lua_vm(); status = luaL_loadbuffer(L, p, sz, "bootstrap.lua"); if (status != 0) { lua_err = lua_tostring(L, -1); logCrit("Load Buffer Error: %s\n\n", lua_err); return EXIT_FAILURE; } status = lua_pcall(L, 0, 0, 0); if (status != 0) { lua_err = lua_tostring(L, -1); logCrit("Runtime Error: %s", lua_err); return EXIT_FAILURE; } lua_close(L); equus_local_cache_clear(); } while (equus_restart_get() == 1); return 0; }
hHeartEngine::hHeartEngine(const hChar* config_script, hSize_t config_script_len) : firstLoaded_(nullptr) , coreAssetsLoaded_(nullptr) , mainUpdate_(nullptr) , mainRender_(nullptr) , shutdownUpdate_(nullptr) , onShutdown_(nullptr) { GOOGLE_PROTOBUF_VERIFY_VERSION; ////////////////////////////////////////////////////////////////////////// // Read in the config //////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// luaVM_ = new hLuaStateManager; luaVM_->Initialise(); hConfigurationVariables::loadCVars(luaVM_->GetMainState(), config_script, config_script_len); hUint32 sdlFlags = 0; sdlFlags |= SDL_INIT_VIDEO; sdlFlags |= SDL_INIT_GAMECONTROLLER; sdlFlags |= SDL_INIT_HAPTIC; sdlFlags |= SDL_INIT_EVENTS; SDL_Init(sdlFlags); hInitFreetype2(); hRenderer::loadRendererModule(hConfigurationVariables::getCVarStr("plugin.renderer", "none"), &cvars); hFileSystemInterface fileInterface; auto plugin_loaded = loadFileSystemInterface(hConfigurationVariables::getCVarStr("plugin.filesystem", "none"), &fileInterface); hcAssertMsg(plugin_loaded, "Failed to load file interface \"%s\"", hConfigurationVariables::getCVarStr("plugin.filesystem", "none")); fileMananger_ = new hIFileSystem(fileInterface); fileMananger_->getCurrentWorkingDir(workingDir_.GetBuffer(), workingDir_.GetMaxSize()); fileMananger_->getProcessDirectory(processDir_.GetBuffer(), processDir_.GetMaxSize()); hcPrintf("Current Directory: %s\nProcess Directory: %s", workingDir_.GetBuffer(), processDir_.GetBuffer()); // current working is already mounted to / fileMananger_->mountPoint(processDir_, "/proc"); fileMananger_->mountPoint(hConfigurationVariables::getCVarStr("filesystem.scripts_dir", "/script"), "/scripts"); fileMananger_->mountPoint(hConfigurationVariables::getCVarStr("filesystem.data_dir", "/data"), "/data" ); fileMananger_->mountPoint(hConfigurationVariables::getCVarStr("filesystem.tmp_dir", "/tmp"), "/tmp"); fileMananger_->mountPoint(hConfigurationVariables::getCVarStr("filesystem.save_dir", "/save"), "/save"); const hChar* script_name = hConfigurationVariables::getCVarStr("startup.script", nullptr); hcAssertMsg(script_name, "startup.script is not set"); hFileHandle start_script_file; auto op = fileMananger_->openFile(script_name, FILEMODE_READ, &start_script_file); auto er = fileMananger_->fileOpWait(op); fileMananger_->fileOpClose(op); hcAssertMsg(er == FileError::Ok, "failed to open startup.script \"%s\"", script_name); hFileStat scriptfstat; op = fileMananger_->fstatAsync(start_script_file, &scriptfstat); fileMananger_->fileOpWait(op); fileMananger_->fileOpClose(op); std::unique_ptr<hChar[]> scriptdata(new hChar[scriptfstat.filesize]); op = fileMananger_->freadAsync(start_script_file, scriptdata.get(), scriptfstat.filesize, 0); google::protobuf::SetLogHandler(&hHeartEngine::ProtoBufLogHandler); /** if (rootdir) hStrCopy(workingDir_.GetBuffer(), workingDir_.GetMaxSize(), rootdir); else hSysCall::GetCurrentWorkingDir(workingDir_.GetBuffer(), workingDir_.GetMaxSize()); hUint end = hStrLen(workingDir_.GetBuffer())-1; if (workingDir_[end] != '\\' && workingDir_[end] != '/') { hStrCat(workingDir_.GetBuffer(), workingDir_.GetMaxSize(), "/"); } */ hNetwork::initialise(); mainPublisherCtx_ = new hPublisherContext; actionManager_ = new hActionManager; system_ = new hSystem; soundManager_ = nullptr;//new hSoundManager; console_ = nullptr;//new hSystemConsole(consoleCb, consoleUser); debugServer_=new hNetHost; config_.Width_ = hConfigurationVariables::getCVarUint("renderer.width", 640); config_.Height_ = hConfigurationVariables::getCVarUint("renderer.height", 480); config_.Fullscreen_ = hConfigurationVariables::getCVarBool("renderer.fullscreen", false); config_.vsync_ = hConfigurationVariables::getCVarBool("renderer.vsync", false); //deviceConfig_ = deviceConfig; deviceConfig_ = nullptr; ////////////////////////////////////////////////////////////////////////// // Init Engine Classes /////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// //hcSetOutputStringCallback(hSystemConsole::printConsoleMessage); hTaskScheduler::initialise(hConfigurationVariables::getCVarUint("taskgraph.workercount", hSysCall::getProcessorCount()), hConfigurationVariables::getCVarUint("taskgraph.jobqueuesize", 256)); debugServer_->initialise(hConfigurationVariables::getCVarInt("debug.server.port", 8335)); mainPublisherCtx_->initialise(1024*1024); system_->Create(config_); actionManager_->initialise(system_); hClock::initialise(); config_.Width_ = system_->getWindowWidth(); config_.Height_ = system_->getWindowHeight(); hRenderer::create( system_, config_.Width_, config_.Height_, config_.bpp_, config_.MinShaderVersion_, config_.Fullscreen_, config_.vsync_); hResourceManager::initialise(fileMananger_); hTileRenderer2D::initialise(); //!!JM todo: soundManager_->Initialise(); /////////////////////////////////////////////////////////////////////////////////////////////////// // Initialise Engine scripting elements /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// OpenHeartLuaLib(luaVM_->GetMainState(), this); actionManager_->registerLuaLib(luaVM_); //Run the start up script er = fileMananger_->fileOpWait(op); hcAssertMsg(er == FileError::Ok, "Failed to read startup script \"%s\"", script_name); fileMananger_->fileOpClose(op); { luaL_loadbuffer(luaVM_->GetMainState(), scriptdata.get(), scriptfstat.filesize, script_name); if (lua_pcall(luaVM_->GetMainState(), 0, LUA_MULTRET, 0) != 0) { hcAssertFailMsg("startup.lua Failed to run, Error: %s", lua_tostring(luaVM_->GetMainState(), -1)); lua_pop(luaVM_->GetMainState(), 1); } fileMananger_->closeFile(start_script_file); } // Workaround for dead stripping of these types hBool register_type = hTrue; register_type &= hShaderProgram::auto_object_registered; register_type &= hTTFFontFace::auto_object_registered; register_type &= hTextureResource::auto_object_registered; register_type &= hTextureAtlasResource::auto_object_registered; register_type &= hLevel::auto_object_registered; register_type &= hTileRenderer2D::registerComponents(); register_type &= hMaterial::auto_object_registered; register_type &= hUniformBufferResource::auto_object_registered; register_type &= hRenderingPipeline::auto_object_registered; if (register_type) { engineState_ = hHeartState_LoadingCore; } //Setup the standard task graph to call when no custom task graph is installed. registerEngineTasks(); createFrameTaskGraph(); mem_track_marker("AfterEngineInit"); }
LUALIB_API int luaLS_loadbuffer(lua_State *L, const char *buff, int sz, const char *name) { return luaL_loadbuffer(L, buff, (size_t)sz, name); }
LUALIB_API int (luaL_loadstring)(lua_State *L, const char *s) { unsigned int uiLength = strlen(s); return luaL_loadbuffer(L, s,uiLength , s); }
int get_pgfunc(lua_State *L) { Lua_pgfunc *lf; Pgfunc_options opt; MemoryContext m; const char* reg_name = NULL; HeapTuple proctup; Form_pg_proc proc; int luasrc = 0; Oid funcid = 0; BEGINLUA; opt.only_internal = true; opt.throwable = true; if (lua_gettop(L) == 2){ luaL_checktype(L, 2, LUA_TTABLE); parse_options(L, &opt); }else if (lua_gettop(L) != 1){ return luaL_error(L, "pgfunc(text): wrong arguments"); } if(lua_type(L, 1) == LUA_TSTRING){ reg_name = luaL_checkstring(L, 1); m = MemoryContextSwitchTo(tmpcontext); PG_TRY(); { funcid = DatumGetObjectId(DirectFunctionCall1(regprocedurein, CStringGetDatum(reg_name))); } PG_CATCH();{} PG_END_TRY(); MemoryContextSwitchTo(m); MemoryContextReset(tmpcontext); }else if (lua_type(L, 1) == LUA_TNUMBER){ funcid = luaL_checkinteger(L, 1); } if (!OidIsValid(funcid)){ if (reg_name) return luaL_error(L,"failed to register %s", reg_name); return luaL_error(L,"failed to register function with oid %d", funcid); } proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid)); if (!HeapTupleIsValid(proctup)){ return luaL_error(L,"cache lookup failed for function %d", funcid); } proc = (Form_pg_proc) GETSTRUCT(proctup); luasrc = ((proc->prolang == get_pllua_oid()) || (proc->prolang == get_plluau_oid())); if ( opt.only_internal &&(proc->prolang != INTERNALlanguageId) &&(!luasrc) ){ ReleaseSysCache(proctup); return luaL_error(L, "supported only SQL/internal functions"); } lf = (Lua_pgfunc *)lua_newuserdata(L, sizeof(Lua_pgfunc)); /*make it g/collected*/ luaP_getfield(L, pg_func_type_name); lua_setmetatable(L, -2); lf->prorettype = proc->prorettype; lf->funcid = funcid; lf->options = opt; { Oid *argtypes; char **argnames; char *argmodes; int argc; MemoryContext cur = CurrentMemoryContext; MemoryContextSwitchTo(tmpcontext); argc = get_func_arg_info(proctup, &argtypes, &argnames, &argmodes); MemoryContextSwitchTo(get_common_ctx()); lf->numargs = argc; lf->argtypes = (Oid*)palloc(argc * sizeof(Oid)); memcpy(lf->argtypes, argtypes, argc * sizeof(Oid)); MemoryContextSwitchTo(cur); MemoryContextReset(tmpcontext); } if (luasrc){ bool isnull; text *t; const char *s; luaL_Buffer b; int pcall_result; Datum prosrc; if((lf->numargs != 1) || (lf->argtypes[0] != INTERNALOID) || (lf->prorettype != INTERNALOID)){ luaL_error(L, "pgfunc accepts only 'internal' pllua/u functions with internal argument"); } prosrc = SysCacheGetAttr(PROCOID, proctup, Anum_pg_proc_prosrc, &isnull); if (isnull) elog(ERROR, "[pgfunc]: null lua prosrc"); luaL_buffinit(L, &b); luaL_addstring(&b,"do "); t = DatumGetTextP(prosrc); luaL_addlstring(&b, VARDATA(t), VARSIZE(t) - VARHDRSZ); luaL_addstring(&b, " end"); luaL_pushresult(&b); s = lua_tostring(L, -1); ReleaseSysCache(proctup); clean_pgfuncinfo(lf); if (luaL_loadbuffer(L, s, strlen(s), "pgfunc chunk")) luaL_error(L, "compile"); lua_remove(L, -2); /*delete source element*/ pcall_result = lua_pcall(L, 0, 1, 0); lua_remove(L, -2); /*delete chunk*/ if(pcall_result == 0){ ENDLUAV(1); return 1; } if( pcall_result == LUA_ERRRUN) luaL_error(L,"%s %s","Runtime error:",lua_tostring(L, -1)); else if(pcall_result == LUA_ERRMEM) luaL_error(L,"%s %s","Memory error:",lua_tostring(L, -1)); else if(pcall_result == LUA_ERRERR) luaL_error(L,"%s %s","Error:",lua_tostring(L, -1)); return luaL_error(L, "pgfunc unknown error"); } if(proc->proretset) { lua_pushcclosure(L, pgfunc_rows, 1); } else { fmgr_info(funcid, &lf->fi); lua_pushcclosure(L, pg_callable_func, 1); } ReleaseSysCache(proctup); ENDLUAV(1); return 1; }
LUA_API int luanet_loadbuffer (lua_State *L, const char *buff, size_t sz, const char *name) { if (sz == 0) sz = strlen (buff); return luaL_loadbuffer (L, buff, sz, name); }
static int push(lua_State* state, const LuaCodeChunk& ref) { int status = luaL_loadbuffer(state, ref.code_.c_str(), ref.code_.size(), ref.chunk_name_.empty() ? ref.code_.c_str() : ref.chunk_name_.c_str()); if (!except::checkErrorAndThrow(status, state)) { return 0; } return 1; }
static bool inter_copy_func(lua_State* from, lua_State* to, int cache, int i){ ASSERT(lua_isfunction(from, i)); if(push_cached_func(from, to, cache, i)){ lua_remove(to, -2); // remove the key return true; } int to_top = lua_gettop(to); bool ret = true; bool needToPush = (i != lua_gettop(from)); if(needToPush) lua_pushvalue(from, i); luaL_Buffer b; luaL_buffinit(from, &b); lua_CFunction cfunc = NULL; if(lua_dump(from, buf_writer, &b) == 0) { luaL_pushresult(&b); size_t sz; char const* s = lua_tolstring(from, -1, &sz); if(!luaL_loadbuffer(to, s, sz, NULL)){ ret = false; // todo: error out }else{ // cache the function // ... key, function lua_insert(to, -2); // ... function, key lua_pushvalue(to, -2); // ... function, key, function lua_rawset(to, cache); // ... function } lua_pop(from, 1); // pop the compilied source }else{ // c function? cfunc = lua_tocfunction(from, i); ret = cfunc != NULL; // c function won't be cached because the closure could be different lua_pop(to, 1); // pop th key } if(needToPush) lua_pop(from, 1); // copy the upvalues int j = 0; for(;ret && lua_getupvalue(from, i, j+1) != NULL; ++j) { ret = inter_copy_one(from, to, cache, lua_gettop(from)); lua_pop(from, 1); } if(ret == false){ return false; } if(cfunc != NULL){ lua_pushcclosure(to, cfunc, j); }else{ for(;j>0;--j){ lua_setupvalue(to, to_top + 1, j); } } ASSERT(lua_isfunction(to, -1)); return true; }
int main(int argc, char** argv) { td_bin_allocator bin_alloc; const char *homedir; char exepath[512]; int res, rc, i; lua_State* L; td_init_portable(); if (0 != td_get_executable_path(exepath, sizeof exepath)) { fprintf(stderr, "couldn't find path to tundra executable"); return 1; } if (NULL == (homedir = td_init_homedir())) { fprintf(stderr, "couldn't find tundra home dir"); return 1; } td_bin_allocator_init(&bin_alloc); L = lua_newstate(td_lua_alloc, &bin_alloc); if (!L) exit(1); lua_atpanic(L, on_lua_panic); luaL_openlibs(L); tundra_open(L); #if defined(TD_STANDALONE) /* this is equivalent to table.insert(package.loaders, 1, td_load_embedded_file) */ /* get the function */ lua_getglobal(L, "table"); lua_getfield(L, -1, "insert"); lua_remove(L, -2); assert(!lua_isnil(L, -1)); /* arg1: the package.loaders table */ lua_getglobal(L, "package"); lua_getfield(L, -1, "loaders"); lua_remove(L, -2); assert(!lua_isnil(L, -1)); lua_pushinteger(L, 1); /* arg 2 */ lua_pushcfunction(L, td_load_embedded_file); /* arg 3 */ lua_call(L, 3, 0); #endif /* setup package.path */ { char ppath[1024]; snprintf(ppath, sizeof(ppath), "%s" TD_PATHSEP_STR "scripts" TD_PATHSEP_STR "?.lua;" "%s" TD_PATHSEP_STR "lua" TD_PATHSEP_STR "etc" TD_PATHSEP_STR "?.lua", homedir, homedir); lua_getglobal(L, "package"); assert(LUA_TTABLE == lua_type(L, -1)); lua_pushstring(L, ppath); lua_setfield(L, -2, "path"); } /* push our error handler on the stack now (before the chunk to run) */ lua_pushcclosure(L, get_traceback, 0); switch (luaL_loadbuffer(L, boot_snippet, sizeof(boot_snippet)-1, "boot_snippet")) { case LUA_ERRMEM: td_croak("out of memory"); return 1; case LUA_ERRSYNTAX: td_croak("syntax error\n%s\n", lua_tostring(L, -1)); return 1; } lua_pushstring(L, homedir); lua_newtable(L); lua_pushstring(L, exepath); lua_rawseti(L, -2, 1); for (i=1; i<argc; ++i) { lua_pushstring(L, argv[i]); lua_rawseti(L, -2, i + 1); } { double t2; script_call_t1 = td_timestamp(); res = lua_pcall(L, /*narg:*/2, /*nres:*/0, /*errorfunc:*/ -4); t2 = td_timestamp(); if (global_tundra_stats) printf("total time spent in tundra: %.4fs\n", t2 - script_call_t1); } if (res == 0) { rc = global_tundra_exit_code; } else { fprintf(stderr, "%s\n", lua_tostring(L, -1)); rc = 1; } lua_close(L); td_bin_allocator_cleanup(&bin_alloc); return rc; }
int load_game_scripts(lua_State* L, const char* zipfile) { size_t size = 0; unsigned char* filedata = s_read(zipfile, &size, 0); if (!filedata) { fprintf(stderr, "unable to read zipfile = %s\n", zipfile); return 1; } unzFile unzfile = unzOpenBuffer(filedata, size); if(!unzfile) { fprintf(stderr, "open zip from buffer failed.\n"); return 1; } lua_getglobal(L, "package"); lua_getfield(L, -1, "preload"); char filename[1024] = ""; int err = unzGoToFirstFile(unzfile); if (err) { fprintf(stderr, "go to first file failed"); return 1; } bool succeed = true; while (true) { unz_file_info info; err = unzGetCurrentFileInfo(unzfile, &info, filename, 1024, NULL, 0, NULL, 0); if (err) { fprintf(stderr, "get current file info failed, filename = %s\n", filename); succeed = false; break; } unz_file_pos file_pos; err = unzGetFilePos(unzfile, &file_pos); err = unzGoToFilePos(unzfile, &file_pos); err = unzOpenCurrentFile(unzfile); unsigned long size = info.uncompressed_size; unsigned char* buffer = s_malloc(size); unsigned int readed = unzReadCurrentFile(unzfile, buffer, (unsigned int)size); if(readed != size) { succeed = false; fprintf(stderr, "read zip file failed? error size, required = %ld, readed = %d, filename = %s\n", size, readed, filename); goto error; } err = luaL_loadbuffer(L, (const char*)buffer, size, filename); if(err) { fprintf(stderr, "error loadL_loadbuffer, filename = %s\n", filename); goto error; } lua_setfield(L, -2, filename); if(unzGoToNextFile(unzfile) == UNZ_END_OF_LIST_OF_FILE) { succeed = true; break; } unzCloseCurrentFile(unzfile); s_free(buffer); continue; error: succeed = false; unzCloseCurrentFile(unzfile); s_free(buffer); break; } lua_pop(L, -1); return succeed ? 1 : 0; }
/* * Start the Lua interpreter, export IMAP core and system functions, load the * Lua interface functions, load and execute imapfilter's configuration file. */ void start_lua() { lua = luaL_newstate(); luaL_openlibs(lua); luaopen_ifcore(lua); luaopen_ifsys(lua); luaopen_ifre(lua); lua_settop(lua, 0); init_options(); if (luaL_loadfile(lua, PATHNAME_COMMON) || lua_pcall(lua, 0, LUA_MULTRET, 0)) fatal(ERROR_CONFIG, "%s\n", lua_tostring(lua, -1)); if (luaL_loadfile(lua, PATHNAME_SET) || lua_pcall(lua, 0, LUA_MULTRET, 0)) fatal(ERROR_CONFIG, "%s\n", lua_tostring(lua, -1)); if (luaL_loadfile(lua, PATHNAME_REGEX) || lua_pcall(lua, 0, LUA_MULTRET, 0)) fatal(ERROR_CONFIG, "%s\n", lua_tostring(lua, -1)); if (luaL_loadfile(lua, PATHNAME_ACCOUNT) || lua_pcall(lua, 0, LUA_MULTRET, 0)) fatal(ERROR_CONFIG, "%s\n", lua_tostring(lua, -1)); if (luaL_loadfile(lua, PATHNAME_MAILBOX) || lua_pcall(lua, 0, LUA_MULTRET, 0)) fatal(ERROR_CONFIG, "%s\n", lua_tostring(lua, -1)); if (luaL_loadfile(lua, PATHNAME_MESSAGE) || lua_pcall(lua, 0, LUA_MULTRET, 0)) fatal(ERROR_CONFIG, "%s\n", lua_tostring(lua, -1)); if (luaL_loadfile(lua, PATHNAME_OPTIONS) || lua_pcall(lua, 0, LUA_MULTRET, 0)) fatal(ERROR_CONFIG, "%s\n", lua_tostring(lua, -1)); if (luaL_loadfile(lua, PATHNAME_AUXILIARY) || lua_pcall(lua, 0, LUA_MULTRET, 0)) fatal(ERROR_CONFIG, "%s\n", lua_tostring(lua, -1)); if (opts.oneline != NULL) { if (luaL_loadbuffer(lua, opts.oneline, strlen(opts.oneline), "=<command line>") || lua_pcall(lua, 0, LUA_MULTRET, 0)) fatal(ERROR_CONFIG, "%s\n", lua_tostring(lua, -1)); } else { if (luaL_loadfile(lua, strcmp(opts.config, "-") == 0 ? NULL : opts.config)) fatal(ERROR_CONFIG, "%s\n", lua_tostring(lua, -1)); lua_pushcfunction(lua, traceback_handler); lua_insert(lua, 1); if (lua_pcall(lua, 0, LUA_MULTRET, -2)) fatal(ERROR_CONFIG, "%s\n", lua_tostring(lua, -1)); } if (opts.interactive) interactive_mode(); }
LUALIB_API int lua_dobuffer (lua_State *L, const char *buff, size_t size, const char *name) { return aux_do(L, luaL_loadbuffer(L, buff, size, name)); }
static int dostring (lua_State *L, const char *s, const char *name) { int status = luaL_loadbuffer(L, s, strlen(s), name) || docall(L, 0, 1); return report(L, status); }
void android_main(struct android_app* state) { lua_State *L; AAsset* luaCode; const void *buf; off_t bufsize; int status; // Suppress link-time optimization that removes unreferenced code // to make sure glue isn't stripped. app_dummy(); // wait until everything is initialized before launching LuaJIT assets state->onAppCmd = handle_cmd; LOGI("Waiting for app ready..."); int events; struct android_poll_source* source; // we block forever waiting for events. while (ALooper_pollAll(-1, NULL, &events, (void**)&source) >= 0) { // Process this event. if (source != NULL) { source->process(state, source); } if (window_ready && gained_focus) { break; } // Check if we are exiting. if (state->destroyRequested != 0) { return; } } LOGI("Launching LuaJIT assets..."); luaCode = AAssetManager_open(state->activity->assetManager, LOADER_ASSET, AASSET_MODE_BUFFER); if (luaCode == NULL) { LOGE("error loading loader asset"); goto quit; } bufsize = AAsset_getLength(luaCode); buf = AAsset_getBuffer(luaCode); if (buf == NULL) { LOGE("error getting loader asset buffer"); goto quit; } // Load initial Lua loader from our asset store: L = luaL_newstate(); luaL_openlibs(L); status = luaL_loadbuffer(L, (const char*) buf, (size_t) bufsize, LOADER_ASSET); AAsset_close(luaCode); if (status) { LOGE("error loading file: %s", lua_tostring(L, -1)); goto quit; } // pass the android_app state to Lua land: lua_pushlightuserdata(L, state); status = lua_pcall(L, 1, LUA_MULTRET, 0); if (status) { LOGE("Failed to run script: %s", lua_tostring(L, -1)); goto quit; } lua_close(L); quit: ANativeActivity_finish(state->activity); }
static int dostring (lua_State *L, const char *s, const char *name) { return dochunk(L, luaL_loadbuffer(L, s, strlen(s), name)); }
bool LuaScriptEngine::init() { // Lua-State initialisation, as well as standard libaries initialisation _state = luaL_newstate(); if (!_state || ! registerStandardLibs() || !registerStandardLibExtensions()) { error("Lua could not be initialized."); return false; } // Register panic callback function lua_atpanic(_state, panicCB); // Error handler for lua_pcall calls // The code below contains a local error handler function const char errorHandlerCode[] = "local function ErrorHandler(message) " " return message .. '\\n' .. debug.traceback('', 2) " "end " "return ErrorHandler"; // Compile the code if (luaL_loadbuffer(_state, errorHandlerCode, strlen(errorHandlerCode), "PCALL ERRORHANDLER") != 0) { // An error occurred, so dislay the reason and exit error("Couldn't compile luaL_pcall errorhandler:\n%s", lua_tostring(_state, -1)); lua_pop(_state, 1); return false; } // Running the code, the error handler function sets the top of the stack if (lua_pcall(_state, 0, 1, 0) != 0) { // An error occurred, so dislay the reason and exit error("Couldn't prepare luaL_pcall errorhandler:\n%s", lua_tostring(_state, -1)); lua_pop(_state, 1); return false; } // Place the error handler function in the Lua registry, and remember the index _pcallErrorhandlerRegistryIndex = luaL_ref(_state, LUA_REGISTRYINDEX); // Initialize the Pluto-Persistence library luaopen_pluto(_state); lua_pop(_state, 1); // Initialize debugging callback if (DebugMan.isDebugChannelEnabled(kDebugScript)) { int mask = 0; if ((gDebugLevel & 1) != 0) mask |= LUA_MASKCALL; if ((gDebugLevel & 2) != 0) mask |= LUA_MASKRET; if ((gDebugLevel & 4) != 0) mask |= LUA_MASKLINE; if (mask != 0) lua_sethook(_state, debugHook, mask, 0); } debugC(kDebugScript, "Lua initialized."); return true; }
static int luaB_loadstring (lua_State *L) { size_t l; const char *s = luaL_checklstring(L, 1, &l); const char *chunkname = luaL_optstring(L, 2, s); return load_aux(L, luaL_loadbuffer(L, s, l, chunkname)); }
/** * @brief Executes the Lua script from bytecode. * * @param pUser The user running the script. * @param pNpc The NPC attached to the script. * @param nEventID Identifier for the event. * @param bSelectedReward The reward selected, if applicable. * @param filename The script's filename for debugging purposes. * @param bytecode The script's compiled bytecode. * * @return true if it succeeds, false if it fails. */ bool CLuaScript::ExecuteScript(CUser * pUser, CNpc * pNpc, int32 nEventID, int8 bSelectedReward, const char * filename, BytecodeBuffer & bytecode) { // Ensure that we wait until the last user's done executing their script. FastGuard lock(m_lock); /* Attempt to run the script. */ // Load the buffer with our bytecode. int err = luaL_loadbuffer(m_luaState, reinterpret_cast<const char *>(&bytecode[0]), bytecode.size(), nullptr); if (err != LUA_OK) { RetrieveLoadError(err, filename); return false; } lua_tsetglobal(m_luaState, "UID", pUser->GetID()); lua_tsetglobal(m_luaState, "STEP", bSelectedReward); lua_tsetglobal(m_luaState, "EVENT", nEventID); // Try calling the script's entry point err = lua_pcall(m_luaState, 0, // no arguments 0, // 0 returned values 0); // no error handler // Nothing returned, so we can finish up here. if (err == LUA_OK) { lua_settop(m_luaState, 0); return true; } // Attempt to provide somewhat informative errors to help the user figure out what's wrong. switch (err) { case LUA_ERRRUN: printf("ERROR: A runtime error occurred within Lua script.\n"); printf("FILE: %s\n", filename); printf("USER: %s\n", pUser->GetName().c_str()); printf("ZONE: %d\n", pUser->GetZoneID()); printf("NPC ID: %d\n", pNpc->m_sSid); printf("-\n"); break; case LUA_ERRMEM: printf("ERROR: Unable to allocate memory during execution of Lua script.\n"); printf("FILE: %s\n", filename); printf("USER: %s\n", pUser->GetName().c_str()); printf("ZONE: %d\n", pUser->GetZoneID()); printf("NPC ID: %d\n", pNpc->m_sSid); printf("-\n"); break; case LUA_ERRERR: printf("ERROR: An error occurred during Lua script, Error handler failed.\n"); printf("FILE: %s\n", filename); printf("USER: %s\n", pUser->GetName().c_str()); printf("ZONE: %d\n", pUser->GetZoneID()); printf("NPC ID: %d\n", pNpc->m_sSid); printf("-\n"); break; default: printf("ERROR: An unknown error occurred in Lua script.\n"); printf("FILE: %s\n", filename); printf("USER: %s\n", pUser->GetName().c_str()); printf("ZONE: %d\n", pUser->GetZoneID()); printf("NPC ID: %d\n", pNpc->m_sSid); printf("-\n"); break; } // Is there an error set? That can be more useful than our generic error. if (lua_isstring(m_luaState, -1)) { printf("ERROR: [%s] The following error was provided.\n",filename); printf("MESSAGE: %s\n", lua_to<const char *>(m_luaState, -1)); printf("-\n"); } lua_settop(m_luaState, 0); return false; }