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; }
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); }
int colony_runtime_open () { lua_State* L = tm_lua_state = luaL_newstate (); lua_atpanic(L, &runtime_panic); // luaJIT_setmode(L, 0, LUAJIT_MODE_ENGINE|LUAJIT_MODE_ON); // lua_gc(L, LUA_GCSETPAUSE, 90); // lua_gc(L, LUA_GCSETSTEPMUL, 200); // Open libraries. luaL_openlibs(L); // Type of build. #ifdef COLONY_EMBED lua_pushboolean(L, 1); #else lua_pushboolean(L, 0); #endif lua_setglobal(L, "COLONY_EMBED"); #ifndef COLONY_EMBED #ifdef COLONY_COMPILER_PATH lua_pushliteral(L, colony_runtime_xstr(COLONY_COMPILER_PATH)); lua_setglobal(L, "COLONY_COMPILER_PATH"); #endif #endif // Preload Lua modules. lua_getglobal(L, "package"); lua_getfield(L, -1, "preload"); lua_remove(L, -2); // bit32 lua_pushcfunction(L, luaopen_bit); lua_setfield(L, -2, "bit32"); // tm lua_pushcfunction(L, luaopen_tm); lua_setfield(L, -2, "tm"); #ifdef ENABLE_NET // http_parser lua_pushcfunction(L, luaopen_http_parser); lua_setfield(L, -2, "http_parser_lua"); #endif // hsregex lua_pushcfunction(L, luaopen_hsregex); lua_setfield(L, -2, "hsregex"); // rapidjson lua_pushcfunction(L, lua_open_rapidjson); lua_setfield(L, -2, "rapidjson"); // Load lib/*.lua files into memory. for (int i = 0; dir_runtime_lib[i].path != NULL; i++) { lua_pushlstring(L, dir_runtime_lib[i].path, strchr(dir_runtime_lib[i].path, '.') - dir_runtime_lib[i].path); int res = luaL_loadbuffer(L, (const char *) dir_runtime_lib[i].src, dir_runtime_lib[i].len, dir_runtime_lib[i].path); if (res != 0) { printf("Error in runtime lib %s: %d\n", dir_runtime_lib[i].path, res); report(L, res); exit(1); } lua_settable(L, -3); } // Done with preload lua_pop(L, 1); // Given the index of a builtin file to load, this function loads it. lua_pushcfunction(L, builtin_loader); lua_setglobal(L, "_builtin_load"); // Adds builtin files to an array _builtin. lua_newtable(L); for (int i = 0; dir_builtin[i].path != NULL; i++) { lua_pushlstring(L, dir_builtin[i].path, strchr(dir_builtin[i].path, '.') - dir_builtin[i].path); lua_pushnumber(L, i); lua_settable(L, -3); } lua_setglobal(L, "_builtin"); // Initialize runtime semantics. colony_init(L); // Load all builtin libraries immediately on init. // This can trade loss of sped for later access. #ifdef COLONY_PRELOAD lua_pushnumber(L, 1); #else lua_pushnumber(L, 0); #endif lua_setglobal(L, "_colony_preload_on_init"); return tm_eval_lua(L, "require('preload');"); }
static int vlc_sd_probe_Open( vlc_object_t *obj ) { vlc_probe_t *probe = (vlc_probe_t *)obj; char **ppsz_filelist = NULL; char **ppsz_fileend = NULL; char **ppsz_file; char *psz_name; char **ppsz_dir_list = NULL; char **ppsz_dir; lua_State *L = NULL; vlclua_dir_list( obj, "sd", &ppsz_dir_list ); for( ppsz_dir = ppsz_dir_list; *ppsz_dir; ppsz_dir++ ) { int i_files; if( ppsz_filelist ) { for( ppsz_file = ppsz_filelist; ppsz_file < ppsz_fileend; ppsz_file++ ) free( *ppsz_file ); free( ppsz_filelist ); ppsz_filelist = NULL; } i_files = vlc_scandir( *ppsz_dir, &ppsz_filelist, file_select, file_compare ); if( i_files < 1 ) continue; ppsz_fileend = ppsz_filelist + i_files; for( ppsz_file = ppsz_filelist; ppsz_file < ppsz_fileend; ppsz_file++ ) { char *psz_filename; if( asprintf( &psz_filename, "%s" DIR_SEP "%s", *ppsz_dir, *ppsz_file ) < 0 ) { goto error; } L = luaL_newstate(); if( !L ) { msg_Err( probe, "Could not create new Lua State" ); free( psz_filename ); goto error; } luaL_openlibs( L ); if( vlclua_add_modules_path( probe, L, psz_filename ) ) { msg_Err( probe, "Error while setting the module search path for %s", psz_filename ); free( psz_filename ); goto error; } if( luaL_dofile( L, psz_filename ) ) { msg_Err( probe, "Error loading script %s: %s", psz_filename, lua_tostring( L, lua_gettop( L ) ) ); lua_pop( L, 1 ); free( psz_filename ); lua_close( L ); continue; } char *psz_longname; char *temp = strchr( *ppsz_file, '.' ); if( temp ) *temp = '\0'; lua_getglobal( L, "descriptor" ); if( !lua_isfunction( L, lua_gettop( L ) ) || lua_pcall( L, 0, 1, 0 ) ) { msg_Warn( probe, "No 'descriptor' function in '%s'", psz_filename ); lua_pop( L, 1 ); if( !( psz_longname = strdup( *ppsz_file ) ) ) { free( psz_filename ); goto error; } } else { lua_getfield( L, -1, "title" ); if( !lua_isstring( L, -1 ) || !( psz_longname = strdup( lua_tostring( L, -1 ) ) ) ) { free( psz_filename ); goto error; } } char *psz_file_esc = config_StringEscape( *ppsz_file ); char *psz_longname_esc = config_StringEscape( psz_longname ); if( asprintf( &psz_name, "lua{sd='%s',longname='%s'}", psz_file_esc, psz_longname_esc ) < 0 ) { free( psz_file_esc ); free( psz_longname_esc ); free( psz_filename ); free( psz_longname ); goto error; } free( psz_file_esc ); free( psz_longname_esc ); vlc_sd_probe_Add( probe, psz_name, psz_longname, SD_CAT_INTERNET ); free( psz_name ); free( psz_longname ); free( psz_filename ); lua_close( L ); } } if( ppsz_filelist ) { for( ppsz_file = ppsz_filelist; ppsz_file < ppsz_fileend; ppsz_file++ ) free( *ppsz_file ); free( ppsz_filelist ); } vlclua_dir_list_free( ppsz_dir_list ); return VLC_PROBE_CONTINUE; error: if( ppsz_filelist ) { for( ppsz_file = ppsz_filelist; ppsz_file < ppsz_fileend; ppsz_file++ ) free( *ppsz_file ); free( ppsz_filelist ); } if( L ) lua_close( L ); vlclua_dir_list_free( ppsz_dir_list ); return VLC_ENOMEM; }
int main(void) { /* create a new Lua state */ lua_State *L = luaL_newstate(); /* open luadata library */ #if LUA_VERSION_NUM >= 502 luaL_requiref(L, "data", luaopen_data, 1); #else luaopen_data(L); #endif lua_pop(L, 1); /* remove lib */ /* load a script */ assert(luaL_dofile(L, "ctest.lua") == 0); /* get the filter function */ lua_getglobal(L, "filter"); /* create a new data ptr */ size_t data_size = 3; byte_t *data_ptr = (byte_t *) malloc(data_size); data_ptr[0] = 0xAB; data_ptr[1] = 0xCD; data_ptr[2] = 0xEF; /* create a new data object */ int rd = ldata_newref(L, data_ptr, data_size); /* call data_filter(d)*/ assert(lua_pcall(L, 1, 1, 0) == 0); /* get filter result */ int passed = lua_toboolean(L, -1); assert(passed); /* unregister the Lua data object */ ldata_unref(L, rd); /* now we can safely free the data pointer */ free(data_ptr); data_ptr = NULL; data_size = 0; /* get the access_global function */ lua_getglobal(L, "access_global"); /* call access_global() to try to access a data with a freed ptr */ assert(lua_pcall(L, 0, 1, 0) == 0); /* should return nil */ assert(lua_isnil(L, -1)); /* get a pointer of data object created by the Lua script */ lua_getglobal(L, "d"); data_ptr = (byte_t *) ldata_topointer(L, -1, &data_size); assert(data_ptr != NULL); /* check size and values */ assert(data_size == 4); assert(data_ptr[0] == 0xFF); assert(data_ptr[1] == 0xEE); assert(data_ptr[2] == 0xDD); assert(data_ptr[3] == 0x00); lua_pop(L, 1); /* remove data object refered by 'd' from Lua */ lua_pushnil(L); lua_setglobal(L, "d"); lua_gc(L, LUA_GCCOLLECT, 0); lua_getglobal(L, "d"); data_ptr = (byte_t *) ldata_topointer(L, -1, &data_size); assert(data_ptr == NULL); assert(data_size == 0); printf("test passed ;-)\n"); return 0; }
Pimpl(): s(luaL_newstate()) { luaL_openlibs(s); }
bool Config::load(const char *filename) { pState = luaL_newstate(); if(luaL_dofile(pState, filename)){ printf("parse config file error=%s\n", lua_tostring(pState, -1)); return false; } //basic option sFile = filename;//file sHost = readString("HOST");//host nPort = readInt("PORT");//port bDaemonize = readBoolean("DAEMONIZE"); sLogFile = readString("LOG_FILE");//log file nLogLevel = readInt("LOG_LEVEL");//log level bRouter = readBoolean("ROUTER");//router server //router == 1 if(bRouter){ return true; } //worker option nServerId = readInt("SERVER_ID"); bEventConnect = readBoolean("EVENT_CONNECT"); bEventClose = readBoolean("EVENT_CLOSE"); nWorkers = readInt("WORKER_NUM"); if(nWorkers < 1){ printf("WORKER_NUM Invalid(WORKER_NUM>=1)\n"); return false; } nMaxClients = readInt("MAX_CLIENT_NUM"); if(nMaxClients < 1){ printf("MAX_CLIENT_NUM Invalid(MAX_CLIENT_NUM>=1)\n"); return false; } nSendBufferSize = readInt("SEND_BUFF_SIZE"); if(nSendBufferSize < 1){ printf("SEND_BUFF_SIZE Invalid(SEND_BUFF_SIZE>=1)\n"); return false; } nRecvBufferSize = readInt("RECV_BUFF_SIZE"); if(nRecvBufferSize < 1){ printf("RECV_BUFF_SIZE Invalid(RECV_BUFF_SIZE>=1)\n"); return false; } //暂时只能fastcgi nProtocol = readInt("PROTOCOL"); //backend server list nBackendTimeout = readInt("BACKEND_TIMEOUT"); lua_getglobal(pState, "BACKEND_SERVER"); if(lua_isstring(pState, -1)){ const char *val = lua_tostring(pState, -1); if(!addBackendServer(val, 1)){ printf("BACKEND_SERVER Invalid\n"); return false; } }else if(lua_istable(pState, -1)){ lua_pushnil(pState); while(lua_next(pState, -2)) { const char *str = NULL; int weight = 0; if(lua_isstring(pState, -2)){ str = lua_tostring(pState, -2); } if(lua_isnumber(pState, -1)){ weight = lua_tonumber(pState, -1);; } if(str && weight > 0){ if(!addBackendServer(str, weight)){ printf("BACKEND_SERVER Invalid\n"); return false; } } lua_pop(pState, 1); } lua_pop(pState, 1); }else{ printf("BACKEND_SERVER invalid\n"); return false; } //router option sScriptFile = readString("SCRIPT_FILE"); sRouterHost = readString("ROUTER_HOST"); nRouterPort = readInt("ROUTER_PORT"); //fastcgi sFastcgiRoot = readString("FASTCGI_ROOT"); sFastcgiFile = readString("FASTCGI_FILE"); //fastcgi params lua_getglobal(pState, "FASTCGI_PARAMS"); if(lua_istable(pState, -1)){ lua_pushnil(pState); while(lua_next(pState, -2)) { const char *key = NULL; const char *val = NULL; if(lua_isstring(pState, -2)){ key = lua_tostring(pState, -2); } if(lua_isstring(pState, -1)){ val = lua_tostring(pState, -1); } if(key && val){ arFastcgiParams[key] = val; } lua_pop(pState, 1); } lua_pop(pState, 1); }else{ printf("FASTCGI_PARAMS invalid\n"); return false; } return true; }
int main(int argc, char **argv) { dword dflag, vflag, iflag, cflag, stdflag; int error; char *str, *dostring, *filename; lua_State *L = luaL_newstate(); // lua_openlibs_nodebug(L); luaL_openlibs(L); // _G.dbg( func, ... ) lua_pushcfunction(L,l_debugcall); lua_pushvalue(L,-1); lua_setglobal(L,"dbgcall"); lua_setglobal(L,"dbg"); lua_newtable(L); // file list lua_newtable(L); // arg list dostring=NULL; dflag=false, vflag=false, iflag=false, cflag=false, stdflag=false; for (unsigned i=1, arg=0;i!=argc;++i) { if (arg) { // once arg is set, all params are considered arguments to be passed to lua via _G.arg lua_pushstring(L, argv[i]); lua_rawseti(L, -2, i-arg); continue; } if (*(str=argv[i]) != '-') { // It's a file, add it to the list if (str[0]=='\0') { fputs("Empty string \'\' where filename was exepected\n", stderr); goto usage; } lua_pushstring(L, str); lua_rawseti(L, -3, lua_rawlen(L, -3)+1); continue; } if (isalnum(str[1]) && str[2]!='\0') { fputs("invalid option '", stderr); fputs(str, stderr); fputs("'\n", stderr); goto usage; } switch(str[1]) { case '\0': // used to denote to stdin on file list if (stdflag) break; lua_pushstring(L, ""); lua_rawseti(L, -3, lua_rawlen(L, -3)+1); stdflag=true; break; case 'd': dflag=DEBUGMODE=true; break; // debug, todo: enable debug lib on flag set case 'v': vflag=true; break; // verbose case 'i': iflag=true; break; // interactive mode (line by line, with prompt) case 'c': cflag=true; break; // continue on error case 'h': goto usage; // display help case 'e': // execute string if (!(argc-(i+1))) { fputs("string expected for option '-e'\n", stderr); lua_pop(L,2); goto usage; } dostring=argv[++i]; break; case '-': // (--) GNU-style long params, set k,v pair on _G e.g --url=http://www.google.com { char *div, *it, *st=str+2; if (*st=='\0') { arg=i; continue; } // --\0 - stop handling options/files, append the following args to _G.arg if (!strcmp(st, "help")) goto usage; // --help if ((div=strchr(st, '='))) { for (it=st;!isspace(*it) && it!=div;++it) ; if (st!=div && it==div) { lua_pushglobaltable(L); lua_pushlstring(L, st, div-st); if (*(div+1)=='\0') { fputs("expected value for key '", stderr); fputs(lua_tostring(L, -1), stderr); fputs("'\n", stderr); goto usage; } lua_pushstring(L, div+1); lua_rawset(L, -3); lua_pop(L,1); break; } } } default: fputs("invalid option '", stderr); fputs(str, stderr); fputs("'\n", stderr); goto usage; } } // lua_setglobal(L, "arg"); lua_pushglobaltable(L); lua_pushstring(L, "arg"); lua_pushvalue(L, -3); lua_rawset(L, -3); lua_pop(L, 2); if (dostring && lua_runstring(L,dostring)) { // handle -e option lua_poperror(L); if (!cflag) goto fail; } for (unsigned i=0,sz=lua_rawlen(L,-1);i!=sz;++i) { lua_rawgeti(L, -1, i+1); filename=(char*)lua_tostring(L,-1); { lua_pushglobaltable(L); // set _FILE lua_pushstring(L, "_FILE"); if (stdflag && filename[0]=='\0') { // handle non-interactive standard input filename=NULL; lua_pushnil(L); } else { lua_pushvalue(L, -3); } lua_rawset(L, -3); } if (lua_runfile(L, filename)) { // todo: verbose option (use lua_load with reader when you do) lua_poperror(L); if (!cflag) goto fail; } { lua_pushstring(L, "_FILE"); // unset _FILE lua_pushnil(L); lua_rawset(L, -3); lua_pop(L, 1); // pop _G } lua_pop(L, 1); // pop filename } char buffer[256]; if (iflag || (!dostring && !stdflag && !lua_rawlen(L,-1))) { // run interactive mode if -i is set or nothing has been done if (stdflag) clearerr(stdin); // was used by the - option, reset it fputs("lrun " VERSION " " LUA_VERSION " (", stderr); fputs(argv[0], stderr); fputs(")\n" PROMPT, stderr); while(fgets(buffer, sizeof buffer, stdin) != NULL) { if (lua_runstring(L, buffer)) lua_poperror(L); fputs(PROMPT, stderr); } fputc('\n', stderr); } return (0); usage: fputs("Usage: ", stderr); fputs(argv[0], stderr); fputs( " [options] [scripts [-- args ]]\n" "\t-e 's'\tLoad and execute string 's'\n" "\t-i\tStart interactive mode after executing all scripts\n" "\t\tIf no scripts are specified, this mode will begin by default\n" // "\t-v\t\tVerbose. Print file contents as they're loaded." // todo: -l lib (load lib via require) "\t-d\tDebug mode; enable debug library and allow calls with _G.dbg() and _G.dbgcall()\n" "\t\te.g. dbgcall(print, \"foo\")\n" "\t-\tLoad and execute input from stdin\n" "\t--\tStop handling arguments. All subsequent arguments passed are appended to _G.arg\n" "\t--k=v\tDefine _G[ k ] as string 'v'\n" "\t\te.g. --url=http://www.google.com\n" "\t--help\n" "\t-h\tDisplay this menu\n" , stderr); fail: lua_settop(L, 0); return (1); }
GtR* gtr_new(GtError *err) { GtR *gtr; char *seedstr = NULL; int had_err = 0; #ifndef WITHOUT_CAIRO GtStr *style_file = NULL; #endif gtr = gt_calloc(1, sizeof (GtR)); if ((seedstr = getenv("GT_SEED"))) { if (gt_parse_uint(>r->seed, seedstr) != 0) { gt_error_set(err, "invalid seed in GT_SEED environment variable: %s", seedstr); had_err = -1; } } else gtr->seed = 0; if (!had_err) { gtr->debugfp = gt_str_new(); gtr->testspacepeak = gt_str_new(); gtr->test_only = gt_str_new(); gtr->manoutdir = gt_str_new(); gtr->L = luaL_newstate(); if (!gtr->L) { gt_error_set(err, "out of memory (cannot create new lua state)"); had_err = -1; } } if (!had_err) { luaL_openlibs(gtr->L); /* open the standard libraries */ gt_lua_open_lib(gtr->L); /* open the GenomeTools library */ lua_pushcfunction(gtr->L, luaopen_lpeg); lua_pushstring(gtr->L, "lpeg"); lua_call(gtr->L, 1, 0); /* open LPeg library */ lua_pushcfunction(gtr->L, luaopen_md5_core); lua_pushstring(gtr->L, "md5"); lua_call(gtr->L, 1, 0); /* open MD5 library */ lua_pushcfunction(gtr->L, luaopen_lfs); lua_pushstring(gtr->L, "lfs"); lua_call(gtr->L, 1, 0); /* open Lua filesystem */ lua_pushcfunction(gtr->L, luaopen_des56); lua_pushstring(gtr->L, "des56"); lua_call(gtr->L, 1, 0); /* open DES56 library */ had_err = gt_lua_set_modules_path(gtr->L, err); } #ifndef WITHOUT_CAIRO if (!had_err) { lua_settop(gtr->L, 0); if (!(gtr->style = gt_style_new_with_state(gtr->L))) had_err = -1; } if (!had_err) { if (!(style_file = gt_get_gtdata_path(gt_error_get_progname(err), err))) had_err = -1; } if (!had_err) { gt_str_append_cstr(style_file, "/sketch/default.style"); if (gt_file_exists(gt_str_get(style_file))) { if (gt_style_load_file(gtr->style, gt_str_get(style_file), err)) had_err = -1; else gt_lua_put_style_in_registry(gtr->L, gtr->style); } } gt_str_delete(style_file); #endif if (had_err) { gt_free(gtr); return NULL; } return gtr; }
lua_raii() : L_(luaL_newstate()) {}
static lua_State* luastate_New(void) { lua_State* l = luaL_newstate(); lua_gc(l, LUA_GCSETPAUSE, 110); lua_gc(l, LUA_GCSETSTEPMUL, 300); // standard libs luaL_openlibs(l); luastate_RememberTracebackFunc(l); luastate_VoidDebug(l); luastate_AddBlitwizFuncs(l); // own dofile/loadfile/print lua_pushcfunction(l, &luafuncs_loadfile); lua_setglobal(l, "loadfile"); lua_pushcfunction(l, &luafuncs_dofile); lua_setglobal(l, "dofile"); lua_pushcfunction(l, &luafuncs_print); lua_setglobal(l, "print"); // obtain the blitwiz lib lua_getglobal(l, "blitwiz"); // blitwiz.setStep: lua_pushstring(l, "setStep"); lua_pushcfunction(l, &luafuncs_setstep); lua_settable(l, -3); // blitwiz namespaces lua_pushstring(l, "graphics"); luastate_CreateGraphicsTable(l); lua_settable(l, -3); lua_pushstring(l, "net"); luastate_CreateNetTable(l); lua_settable(l, -3); /*lua_pushstring(l, "sound"); luastate_CreateSoundTable(l); lua_settable(l, -3);*/ lua_pushstring(l, "callback"); lua_newtable(l); lua_pushstring(l, "event"); lua_newtable(l); lua_settable(l, -3); lua_settable(l, -3); lua_pushstring(l, "time"); luastate_CreateTimeTable(l); lua_settable(l, -3); lua_pushstring(l, "physics"); luastate_CreatePhysicsTable(l); lua_settable(l, -3); // we still have the module "blitwiz" on the stack here lua_pop(l, 1); // obtain math table lua_getglobal(l, "math"); // math namespace extensions lua_pushstring(l, "trandom"); lua_pushcfunction(l, &luafuncs_trandom); lua_settable(l, -3); // remove math table from stack lua_pop(l, 1); // obtain os table lua_getglobal(l, "os"); // os namespace extensions lua_pushstring(l, "exit"); lua_pushcfunction(l, &luafuncs_exit); lua_settable(l, -3); lua_pushstring(l, "chdir"); lua_pushcfunction(l, &luafuncs_chdir); lua_settable(l, -3); lua_pushstring(l, "openConsole"); lua_pushcfunction(l, &luafuncs_openConsole); lua_settable(l, -3); lua_pushstring(l, "ls"); lua_pushcfunction(l, &luafuncs_ls); lua_settable(l, -3); lua_pushstring(l, "isdir"); lua_pushcfunction(l, &luafuncs_isdir); lua_settable(l, -3); lua_pushstring(l, "getcwd"); lua_pushcfunction(l, &luafuncs_getcwd); lua_settable(l, -3); lua_pushstring(l, "exists"); lua_pushcfunction(l, &luafuncs_exists); lua_settable(l, -3); lua_pushstring(l, "sysname"); lua_pushcfunction(l, &luafuncs_sysname); lua_settable(l, -3); lua_pushstring(l, "sysversion"); lua_pushcfunction(l, &luafuncs_sysversion); lua_settable(l, -3); // throw table "os" off the stack lua_pop(l, 1); // get "string" table for custom string functions lua_getglobal(l, "string"); // set custom string functions lua_pushstring(l, "starts"); lua_pushcfunction(l, &luafuncs_startswith); lua_settable(l, -3); lua_pushstring(l, "ends"); lua_pushcfunction(l, &luafuncs_endswith); lua_settable(l, -3); lua_pushstring(l, "split"); lua_pushcfunction(l, &luafuncs_split); lua_settable(l, -3); // throw table "string" off the stack lua_pop(l, 1); char vstr[512]; char is64bit[] = " (64-bit binary)"; #ifndef _64BIT strcpy(is64bit, ""); #endif snprintf(vstr, sizeof(vstr), "Blitwizard %s based on Lua 5.2%s", VERSION, is64bit); lua_pushstring(l, vstr); lua_setglobal(l, "_VERSION"); return l; }
int main() { L = luaL_newstate(); luaL_openlibs(L); luaL_requiref(L, "love", initLove, 1); sf2d_init(); // 2D Drawing lib. sftd_init(); // Text Drawing lib. cfguInit(); ptmuInit(); Result ir = irrstInit(); //consoleInit(GFX_BOTTOM, NULL); irrstEnabled = (ir) ? false : true; sf2d_set_clear_color(RGBA8(0x0, 0x0, 0x0, 0xFF)); // Reset background color. osSetSpeedupEnable(true); // Enables CPU speedup for a free performance boost. // Detect if we are running on a .cia, because if we are // we load from RomFS rather than the SD Card. // TODO: Load RomFS from .3dsx's aswell. Result rc = romfsInit(); romfsExists = (rc) ? false : true; // Change working directory if (romfsExists) { chdir("romfs:/"); } else { char cwd[256]; getcwd(cwd, 256); char newCwd[261]; strcat(newCwd, cwd); strcat(newCwd, "game"); chdir(newCwd); } luaL_dobuffer(L, boot_lua, boot_lua_size, "boot"); // Do some setup Lua side. //in general, make the LovePotion folder cause ye mkdir(path, 0777); // If main.lua exists, execute it. // If not then just load the nogame screen. if (fileExists("main.lua")) { if (luaL_dofile(L, "main.lua")) displayError(); } else { if (luaL_dobuffer(L, nogame_lua, nogame_lua_size, "nogame")) displayError(); } if (luaL_dostring(L, "love.timer.step()")) displayError(); if (luaL_dostring(L, "if love.load then love.load() end")) displayError(); while (aptMainLoop()) { if (shouldQuit) { if (forceQuit) break; bool shouldAbort = false; // lua_getfield(L, LUA_GLOBALSINDEX, "love"); // lua_getfield(L, -1, "quit"); // lua_remove(L, -2); // if (!lua_isnil(L, -1)) { // lua_call(L, 0, 1); // shouldAbort = lua_toboolean(L, 1); // lua_pop(L, 1); // }; TODO: Do this properly. if (luaL_dostring(L, "if love.quit then love.quit() end")) displayError(); if (!shouldAbort && !errorOccured) break; } // Quit event if (!errorOccured) { if (luaL_dostring(L, "love.keyboard.scan()\n" "love.timer.step()\n" "if love.update then love.update(love.timer.getDelta()) end")) { displayError(); } // Top screen // Left side sf2d_start_frame(GFX_TOP, GFX_LEFT); if (luaL_dostring(L, "if love.draw then love.draw() end")) displayError(); sf2d_end_frame(); // Right side if (is3D) { sf2d_start_frame(GFX_TOP, GFX_RIGHT); if (luaL_dostring(L, "if love.draw then love.draw() end")) displayError(); sf2d_end_frame(); } // Bot screen sf2d_start_frame(GFX_BOTTOM, GFX_LEFT); if (luaL_dostring(L, "if love.draw then love.draw() end")) displayError(); sf2d_end_frame(); luaL_dostring(L, "love.graphics.present()"); } else { hidScanInput(); u32 kTempDown = hidKeysDown(); if (kTempDown & KEY_START) { forceQuit = true; shouldQuit = true; } char *errMsg = lua_tostring(L, -1); sf2d_start_frame(GFX_TOP, GFX_LEFT); lua_getfield(L, LUA_GLOBALSINDEX, "love"); lua_getfield(L, -1, "errhand"); lua_remove(L, -2); if (!lua_isnil(L, -1)) { lua_pushstring(L, errMsg); lua_call(L, 1, 0); } sf2d_end_frame(); sf2d_start_frame(GFX_BOTTOM, GFX_LEFT); lua_getfield(L, LUA_GLOBALSINDEX, "love"); lua_getfield(L, -1, "errhand"); lua_remove(L, -2); if (!lua_isnil(L, -1)) { lua_pushstring(L, errMsg); lua_call(L, 1, 0); } sf2d_end_frame(); luaL_dostring(L, "love.graphics.present()"); } } luaL_dostring(L, "love.audio.stop()"); lua_close(L); sftd_fini(); sf2d_fini(); cfguExit(); ptmuExit(); if (irrstEnabled) irrstExit(); if (soundEnabled) ndspExit(); if (romfsExists) romfsExit(); return 0; }
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; }
Lua::Lua() { L = luaL_newstate(); }
lua_State *lua_open(void) { lua_crtstate = luaL_newstate(); return lua_crtstate; }
bool ConfigManager::load() { lua_State* L = luaL_newstate(); if (!L) { throw std::runtime_error("Failed to allocate memory"); } luaL_openlibs(L); if (luaL_dofile(L, "config.lua")) { std::cout << "[Error - ConfigManager::load] " << lua_tostring(L, -1) << std::endl; lua_close(L); return false; } //parse config if (!loaded) { //info that must be loaded one time (unless we reset the modules involved) boolean[BIND_ONLY_GLOBAL_ADDRESS] = getGlobalBoolean(L, "bindOnlyGlobalAddress", false); boolean[OPTIMIZE_DATABASE] = getGlobalBoolean(L, "startupDatabaseOptimization", true); string[IP] = getGlobalString(L, "ip", "127.0.0.1"); string[MAP_NAME] = getGlobalString(L, "mapName", "forgotten"); string[MAP_AUTHOR] = getGlobalString(L, "mapAuthor", "Unknown"); string[HOUSE_RENT_PERIOD] = getGlobalString(L, "houseRentPeriod", "never"); string[MYSQL_HOST] = getGlobalString(L, "mysqlHost", "127.0.0.1"); string[MYSQL_USER] = getGlobalString(L, "mysqlUser", "forgottenserver"); string[MYSQL_PASS] = getGlobalString(L, "mysqlPass", ""); string[MYSQL_DB] = getGlobalString(L, "mysqlDatabase", "forgottenserver"); string[MYSQL_SOCK] = getGlobalString(L, "mysqlSock", ""); integer[SQL_PORT] = getGlobalNumber(L, "mysqlPort", 3306); integer[GAME_PORT] = getGlobalNumber(L, "gameProtocolPort", 7172); integer[LOGIN_PORT] = getGlobalNumber(L, "loginProtocolPort", 7171); integer[STATUS_PORT] = getGlobalNumber(L, "statusProtocolPort", 7171); integer[MARKET_OFFER_DURATION] = getGlobalNumber(L, "marketOfferDuration", 30 * 24 * 60 * 60); } boolean[ALLOW_CHANGEOUTFIT] = getGlobalBoolean(L, "allowChangeOutfit", true); boolean[ONE_PLAYER_ON_ACCOUNT] = getGlobalBoolean(L, "onePlayerOnlinePerAccount", true); boolean[AIMBOT_HOTKEY_ENABLED] = getGlobalBoolean(L, "hotkeyAimbotEnabled", true); boolean[REMOVE_RUNE_CHARGES] = getGlobalBoolean(L, "removeChargesFromRunes", true); boolean[EXPERIENCE_FROM_PLAYERS] = getGlobalBoolean(L, "experienceByKillingPlayers", false); boolean[FREE_PREMIUM] = getGlobalBoolean(L, "freePremium", false); boolean[REPLACE_KICK_ON_LOGIN] = getGlobalBoolean(L, "replaceKickOnLogin", true); boolean[ALLOW_CLONES] = getGlobalBoolean(L, "allowClones", false); boolean[MARKET_PREMIUM] = getGlobalBoolean(L, "premiumToCreateMarketOffer", true); boolean[EMOTE_SPELLS] = getGlobalBoolean(L, "emoteSpells", false); boolean[STAMINA_SYSTEM] = getGlobalBoolean(L, "staminaSystem", true); boolean[WARN_UNSAFE_SCRIPTS] = getGlobalBoolean(L, "warnUnsafeScripts", true); boolean[CONVERT_UNSAFE_SCRIPTS] = getGlobalBoolean(L, "convertUnsafeScripts", true); boolean[CLASSIC_EQUIPMENT_SLOTS] = getGlobalBoolean(L, "classicEquipmentSlots", false); boolean[ENABLE_LIVE_CASTING] = getGlobalBoolean(L, "enableLiveCasting", false); string[DEFAULT_PRIORITY] = getGlobalString(L, "defaultPriority", "high"); string[SERVER_NAME] = getGlobalString(L, "serverName", ""); string[OWNER_NAME] = getGlobalString(L, "ownerName", ""); string[OWNER_EMAIL] = getGlobalString(L, "ownerEmail", ""); string[URL] = getGlobalString(L, "url", ""); string[LOCATION] = getGlobalString(L, "location", ""); string[MOTD] = getGlobalString(L, "motd", ""); string[WORLD_TYPE] = getGlobalString(L, "worldType", "pvp"); string[COIN_IMAGES_URL] = getGlobalString(L, "coinImagesURL", "http://some.url/images/store/"); integer[MAX_PLAYERS] = getGlobalNumber(L, "maxPlayers"); integer[PZ_LOCKED] = getGlobalNumber(L, "pzLocked", 60000); integer[DEFAULT_DESPAWNRANGE] = getGlobalNumber(L, "deSpawnRange", 2); integer[DEFAULT_DESPAWNRADIUS] = getGlobalNumber(L, "deSpawnRadius", 50); integer[RATE_EXPERIENCE] = getGlobalNumber(L, "rateExp", 5); integer[RATE_SKILL] = getGlobalNumber(L, "rateSkill", 3); integer[RATE_LOOT] = getGlobalNumber(L, "rateLoot", 2); integer[RATE_MAGIC] = getGlobalNumber(L, "rateMagic", 3); integer[RATE_SPAWN] = getGlobalNumber(L, "rateSpawn", 1); integer[HOUSE_PRICE] = getGlobalNumber(L, "housePriceEachSQM", 1000); integer[KILLS_TO_RED] = getGlobalNumber(L, "killsToRedSkull", 3); integer[KILLS_TO_BLACK] = getGlobalNumber(L, "killsToBlackSkull", 6); integer[ACTIONS_DELAY_INTERVAL] = getGlobalNumber(L, "timeBetweenActions", 200); integer[EX_ACTIONS_DELAY_INTERVAL] = getGlobalNumber(L, "timeBetweenExActions", 1000); integer[MAX_MESSAGEBUFFER] = getGlobalNumber(L, "maxMessageBuffer", 4); integer[KICK_AFTER_MINUTES] = getGlobalNumber(L, "kickIdlePlayerAfterMinutes", 15); integer[PROTECTION_LEVEL] = getGlobalNumber(L, "protectionLevel", 1); integer[DEATH_LOSE_PERCENT] = getGlobalNumber(L, "deathLosePercent", -1); integer[STATUSQUERY_TIMEOUT] = getGlobalNumber(L, "statusTimeout", 5000); integer[FRAG_TIME] = getGlobalNumber(L, "timeToDecreaseFrags", 24 * 60 * 60 * 1000); integer[WHITE_SKULL_TIME] = getGlobalNumber(L, "whiteSkullTime", 15 * 60 * 1000); integer[STAIRHOP_DELAY] = getGlobalNumber(L, "stairJumpExhaustion", 2000); integer[EXP_FROM_PLAYERS_LEVEL_RANGE] = getGlobalNumber(L, "expFromPlayersLevelRange", 75); integer[CHECK_EXPIRED_MARKET_OFFERS_EACH_MINUTES] = getGlobalNumber(L, "checkExpiredMarketOffersEachMinutes", 60); integer[MAX_MARKET_OFFERS_AT_A_TIME_PER_PLAYER] = getGlobalNumber(L, "maxMarketOffersAtATimePerPlayer", 100); integer[MAX_PACKETS_PER_SECOND] = getGlobalNumber(L, "maxPacketsPerSecond", 25); integer[LIVE_CAST_PORT] = getGlobalNumber(L, "liveCastPort", 7173); integer[COIN_PACKET_SIZE] = getGlobalNumber(L, "coinPacketSize", 25); loaded = true; lua_close(L); return true; }
lua_State* LuaState::defaultSetup() { return luaL_newstate(); }
state::state() : L(luaL_newstate()) { if(!L) throw elba::out_of_memory_error(L, "ran out of memory while creating Lua state"); }
/* * 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(); }
static int start_lua_script(struct img_type *img, void *data) { int ret; const char *fnname; const char *output; char filename[64]; script_fn scriptfn; lua_State *L = luaL_newstate(); /* opens Lua */ if (!data) return -1; scriptfn = *(script_fn *)data; switch (scriptfn) { case PREINSTALL: fnname="preinst"; break; case POSTINSTALL: fnname="postinst"; break; default: /* no error, simply no call */ return 0; } snprintf(filename, sizeof(filename), "%s%s", TMPDIR, img->fname); TRACE("Calling LUA %s", filename); luaL_openlibs(L); /* opens the standard libraries */ if (luaL_loadfile(L, filename)) { ERROR("ERROR loading %s", filename); lua_close(L); return -1; } ret = lua_pcall(L, 0, 0, 0); if (ret) { LUAstackDump(L); ERROR("ERROR preparing LUA script %s %d", filename, ret); lua_close(L); return -1; } lua_getglobal(L, fnname); if(!lua_isfunction(L,lua_gettop(L))) { lua_close(L); TRACE("Script : no %s in %s script, exiting", fnname, filename); return 0; } /* passing arguments */ lua_pushstring(L, filename); if (lua_pcall(L, 1, 2, 0)) { LUAstackDump(L); ERROR("ERROR Calling LUA script %s", filename); lua_close(L); return -1; } if (lua_type(L, 1) == LUA_TBOOLEAN) ret = lua_toboolean(L, 1) ? 0 : 1; if (lua_type(L, 2) == LUA_TSTRING) { output = lua_tostring(L, 2); TRACE("Script output: %s script end", output); } lua_close(L); return ret; }
int Open_LuaIntf( vlc_object_t *p_this ) { intf_thread_t *p_intf = (intf_thread_t*)p_this; intf_sys_t *p_sys; lua_State *L; config_ChainParse( p_intf, "lua-", ppsz_intf_options, p_intf->p_cfg ); char *psz_name = GetModuleName( p_intf ); const char *psz_config; bool b_config_set = false; if( !psz_name ) psz_name = strdup( "dummy" ); p_intf->p_sys = (intf_sys_t*)malloc( sizeof(intf_sys_t) ); if( !p_intf->p_sys ) { free( psz_name ); return VLC_ENOMEM; } p_sys = p_intf->p_sys; p_sys->psz_filename = FindFile( psz_name ); if( !p_sys->psz_filename ) { msg_Err( p_intf, "Couldn't find lua interface script \"%s\".", psz_name ); free( psz_name ); free( p_sys ); return VLC_EGENERIC; } msg_Dbg( p_intf, "Found lua interface script: %s", p_sys->psz_filename ); L = luaL_newstate(); if( !L ) { msg_Err( p_intf, "Could not create new Lua State" ); free( psz_name ); free( p_sys ); return VLC_EGENERIC; } luaL_openlibs( L ); /* register our functions */ luaL_register( L, "vlc", p_reg ); /* store a pointer to p_intf (FIXME: user could overwrite this) */ lua_pushlightuserdata( L, p_intf ); lua_setfield( L, -2, "private" ); /* register submodules */ luaopen_acl( L ); luaopen_config( L ); luaopen_volume( L ); luaopen_httpd( L ); luaopen_input( L ); luaopen_msg( L ); luaopen_misc( L ); luaopen_net( L ); luaopen_object( L ); luaopen_osd( L ); luaopen_playlist( L ); luaopen_sd( L ); luaopen_stream( L ); luaopen_strings( L ); luaopen_variables( L ); luaopen_video( L ); luaopen_vlm( L ); luaopen_volume( L ); /* clean up */ lua_pop( L, 1 ); /* <gruik> */ /* Setup the module search path */ { char *psz_command; char *psz_char = strrchr(p_sys->psz_filename,DIR_SEP_CHAR); *psz_char = '\0'; /* FIXME: don't use luaL_dostring */ if( asprintf( &psz_command, "package.path = \"%s"DIR_SEP"modules"DIR_SEP"?.lua;\"..package.path", p_sys->psz_filename ) < 0 ) { free( psz_name ); free( p_sys ); return VLC_EGENERIC; } *psz_char = DIR_SEP_CHAR; if( luaL_dostring( L, psz_command ) ) { free( psz_name ); free( p_sys ); return VLC_EGENERIC; } } /* </gruik> */ psz_config = var_CreateGetString( p_intf, "lua-config" ); if( psz_config && *psz_config ) { char *psz_buffer; if( asprintf( &psz_buffer, "config={%s}", psz_config ) != -1 ) { printf("%s\n", psz_buffer); if( luaL_dostring( L, psz_buffer ) == 1 ) msg_Err( p_intf, "Error while parsing \"lua-config\"." ); free( psz_buffer ); lua_getglobal( L, "config" ); if( lua_istable( L, -1 ) ) { lua_getfield( L, -1, psz_name ); if( lua_istable( L, -1 ) ) { lua_setglobal( L, "config" ); b_config_set = true; } } } } if( b_config_set == false ) { lua_newtable( L ); lua_setglobal( L, "config" ); } p_sys->L = L; p_intf->psz_header = psz_name; /* ^^ Do I need to clean that up myself in Close_LuaIntf? */ vlc_mutex_init( &p_sys->lock ); vlc_cond_init( &p_sys->wait ); p_sys->exiting = false; if( vlc_clone( &p_sys->thread, Run, p_intf, VLC_THREAD_PRIORITY_LOW ) ) { p_sys->exiting = true; Close_LuaIntf( p_this ); return VLC_ENOMEM; } return VLC_SUCCESS; }
ScriptManager::ScriptManager() { state = luaL_newstate(); registerFunctions(); }
int main(int argc, char **argv) { int n; int args_start = argc; int show_splash = 0; int no_modules = 0; int ret_on_finish_opts = -1; int quiet = 0; for (n=1; n<argc; ++n) { if (argv[n][0] != '-') { args_start = n; break; } else if (strcmp(argv[n], "--splash") == 0) { show_splash = 1; ret_on_finish_opts = 0; } else if (strcmp(argv[n], "--no-modules") == 0) { no_modules = 1; } else if (strcmp(argv[n], "-q") == 0) { quiet = 1; } else { fprintf(stderr, "[ctf]: no such option: %s\n", argv[n]); return 2; } } if (show_splash) { printf("**************************************************\n"); printf("* Computational Turbulence Framework *\n"); printf("* Jonathan Zrake *\n"); printf("* New York University 2008-2013 *\n"); printf("**************************************************\n"); printf("\nCompiled with support for:\n"); printf("\tMPI : %s\n", HAVE_MPI); printf("\tHDF5 : %s\n", HAVE_HDF5); printf("\tFFTW : %s\n", HAVE_FFTW); printf("\tMPIO : %s\n", HAVE_MPIO); printf("\tMARA : %s\n", HAVE_MARA); printf("\tFISH : %s\n", HAVE_FISH); printf("\tVIS : %s\n", HAVE_VIS); printf("\nBuild details:\n"); printf("\tpath : %s\n", STR(INSTALL_DIR)); printf("\tcommit : %s\n", STR(GIT_SHA)); } // printf("args start on %d, there are %d args\n", args_start, argc); if (ret_on_finish_opts != -1) { return ret_on_finish_opts; } lua_State *L = luaL_newstate(); if (!no_modules) { /* create a fully loaded Lua state */ luaL_openlibs(L); luaL_requiref(L, "buffer", luaopen_buffer, 0); luaL_requiref(L, "HDF5", luaopen_hdf5, 0); luaL_requiref(L, "MPI", luaopen_mpi, 0); luaL_requiref(L, "cow", luaopen_cow, 0); luaL_requiref(L, "Mara", luaopen_Mara, 0); luaL_requiref(L, "fish", luaopen_fish, 0); luaL_requiref(L, "fluids", luaopen_fluids, 0); luaL_requiref(L, "visual", luaopen_visual, 0); lua_pop(L, 8); } else { /* create a minimal Lua state (below is a piece of luaL_openlibs from linit.c) */ luaL_requiref(L, "_G", luaopen_base, 1); luaL_requiref(L, LUA_LOADLIBNAME, luaopen_package, 1); lua_pop(L, 2); } // Create the global `arg` table // --------------------------------------------------------------------------- lua_newtable(L); for (n=1; n<argc; ++n) { lua_pushstring(L, argv[args_start + n - 1]); lua_rawseti(L, -2, n); } lua_setglobal(L, "arg"); // Set the Lua path // --------------------------------------------------------------------------- lua_getglobal(L, "package"); lua_pushstring(L, STR(INSTALL_DIR)"/?.lua;" STR(INSTALL_DIR)"/modules/?.lua;"); lua_setfield(L, -2, "path"); lua_pop(L, 1); // Set the Lua C path // --------------------------------------------------------------------------- lua_getglobal(L, "package"); lua_pushstring(L, STR(INSTALL_DIR)"/lua-glut/?.so;"); lua_setfield(L, -2, "cpath"); lua_pop(L, 1); // Provide some help or run the script // --------------------------------------------------------------------------- lua_pushcfunction(L, traceback); if (args_start >= argc) { fprintf(stderr, "[ctf]: need a program to run\n"); return 2; } else { if (luaL_loadfile(L, argv[args_start])) { printf("%s\n", lua_tostring(L, -1)); } else { if (lua_pcall(L, 0, 0, -2)) { printf("%s\n", lua_tostring(L, -1)); } } } lua_close(L); 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; }
int Open_LuaIntf( vlc_object_t *p_this ) { intf_thread_t *p_intf = (intf_thread_t*)p_this; intf_sys_t *p_sys; lua_State *L; config_ChainParse( p_intf, "lua-", ppsz_intf_options, p_intf->p_cfg ); char *psz_name = NULL; if( !p_intf->psz_intf || !*p_intf->psz_intf ) psz_name = strdup( "rc" ); else psz_name = GetModuleName( p_intf ); if( !psz_name ) psz_name = strdup( "dummy" ); char *psz_config; bool b_config_set = false; p_intf->p_sys = (intf_sys_t*)malloc( sizeof(intf_sys_t) ); if( !p_intf->p_sys ) { free( psz_name ); return VLC_ENOMEM; } p_sys = p_intf->p_sys; p_sys->psz_filename = vlclua_find_file( p_this, "intf", psz_name ); if( !p_sys->psz_filename ) { msg_Err( p_intf, "Couldn't find lua interface script \"%s\".", psz_name ); goto error; } msg_Dbg( p_intf, "Found lua interface script: %s", p_sys->psz_filename ); L = luaL_newstate(); if( !L ) { msg_Err( p_intf, "Could not create new Lua State" ); goto error; } vlclua_set_this( L, p_intf ); vlclua_set_intf( L, p_sys ); luaL_openlibs( L ); /* register our functions */ luaL_register( L, "vlc", p_reg ); /* register submodules */ luaopen_acl( L ); luaopen_config( L ); luaopen_volume( L ); luaopen_httpd( L ); luaopen_input( L ); luaopen_msg( L ); luaopen_misc( L ); luaopen_net( L ); luaopen_object( L ); luaopen_osd( L ); luaopen_playlist( L ); luaopen_sd( L ); luaopen_stream( L ); luaopen_strings( L ); luaopen_variables( L ); luaopen_video( L ); luaopen_vlm( L ); luaopen_volume( L ); luaopen_gettext( L ); luaopen_xml( L ); luaopen_md5( L ); /* clean up */ lua_pop( L, 1 ); /* Setup the module search path */ if( vlclua_add_modules_path( p_intf, L, p_sys->psz_filename ) ) { msg_Warn( p_intf, "Error while setting the module search path for %s", p_sys->psz_filename ); lua_close( L ); goto error; } /* * Get the lua-config string. * If the string is empty, try with the old http-* or telnet-* options * and build the right configuration line */ psz_config = var_CreateGetNonEmptyString( p_intf, "lua-config" ); if( !psz_config ) { if( !strcmp( psz_name, "http" ) ) { char *psz_http_host = var_CreateGetNonEmptyString( p_intf, "http-host" ); char *psz_http_src = var_CreateGetNonEmptyString( p_intf, "http-src" ); bool b_http_index = var_CreateGetBool( p_intf, "http-index" ); if( psz_http_host ) { char *psz_esc = config_StringEscape( psz_http_host ); asprintf( &psz_config, "http={host='%s'", psz_esc ); free( psz_esc ); free( psz_http_host ); } if( psz_http_src ) { char *psz_esc = config_StringEscape( psz_http_src ); if( psz_config ) { char *psz_tmp; asprintf( &psz_tmp, "%s,dir='%s'", psz_config, psz_esc ); free( psz_config ); psz_config = psz_tmp; } else asprintf( &psz_config, "http={dir='%s'", psz_esc ); free( psz_esc ); free( psz_http_src ); } if( psz_config ) { char *psz_tmp; asprintf( &psz_tmp, "%s,no_index=%s}", psz_config, b_http_index ? "true" : "false" ); free( psz_config ); psz_config = psz_tmp; } else asprintf( &psz_config, "http={no_index=%s}", b_http_index ? "true" : "false" ); } else if( !strcmp( psz_name, "telnet" ) ) { char *psz_telnet_host = var_CreateGetString( p_intf, "telnet-host" ); int i_telnet_port = var_CreateGetInteger( p_intf, "telnet-port" ); char *psz_telnet_passwd = var_CreateGetString( p_intf, "telnet-password" ); char *psz_esc_host = config_StringEscape( psz_telnet_host ); char *psz_esc_passwd = config_StringEscape( psz_telnet_passwd ); asprintf( &psz_config, "telnet={host='%s:%d',password='******'}", psz_esc_host ? psz_esc_host : "", i_telnet_port, psz_esc_passwd ); free( psz_esc_host ); free( psz_esc_passwd ); free( psz_telnet_passwd ); free( psz_telnet_host ); } } if( psz_config ) { char *psz_buffer; if( asprintf( &psz_buffer, "config={%s}", psz_config ) != -1 ) { msg_Dbg( p_intf, "Setting config variable: %s", psz_buffer ); if( luaL_dostring( L, psz_buffer ) == 1 ) msg_Err( p_intf, "Error while parsing \"lua-config\"." ); free( psz_buffer ); lua_getglobal( L, "config" ); if( lua_istable( L, -1 ) ) { lua_getfield( L, -1, psz_name ); if( lua_istable( L, -1 ) ) { lua_setglobal( L, "config" ); b_config_set = true; } } } free( psz_config ); } if( b_config_set == false ) { lua_newtable( L ); lua_setglobal( L, "config" ); } p_sys->L = L; p_intf->psz_header = psz_name; /* ^^ Do I need to clean that up myself in Close_LuaIntf? */ vlc_mutex_init( &p_sys->lock ); vlc_cond_init( &p_sys->wait ); p_sys->exiting = false; if( vlc_clone( &p_sys->thread, Run, p_intf, VLC_THREAD_PRIORITY_LOW ) ) { p_intf->psz_header = NULL; vlc_cond_destroy( &p_sys->wait ); vlc_mutex_destroy( &p_sys->lock ); lua_close( p_sys->L ); goto error; } return VLC_SUCCESS; error: free( p_sys->psz_filename ); free( p_sys ); free( psz_name ); return VLC_EGENERIC; }
int main(int argc, const char **argv) { bind_port = default_port; char *cwd = init_process_title(argc, argv); char *msg = NULL; update_time(); if(getarg("cache-size")) { msg = getarg("cache-size"); YAC_CACHE_SIZE = atoi(msg); if(msg[strlen(msg) - 1] == 'm') { YAC_CACHE_SIZE = YAC_CACHE_SIZE * 1024 * 1024; } else if(msg[strlen(msg) - 1] == 'k') { YAC_CACHE_SIZE = YAC_CACHE_SIZE * 1024; } } if(YAC_CACHE_SIZE < 1024 * 1024 * 2) { YAC_CACHE_SIZE = 1024 * 1024 * 2; } if(!yac_storage_startup(YAC_CACHE_SIZE / 16, YAC_CACHE_SIZE - (YAC_CACHE_SIZE / 16), &msg)) { LOGF(ERR, "Shared memory allocator startup failed at '%s': %s", msg, strerror(errno)); exit(1); } lua_State *L = luaL_newstate(); if(!L) { LOGF(ERR, "error for luaL_newstate"); exit(1); } luaL_openlibs(L); lua_getglobal(L, "_VERSION"); const char *lua_ver = lua_tostring(L, -1); lua_getglobal(L, "jit"); if(lua_istable(L, -1)) { lua_getfield(L, -1, "version"); if(lua_isstring(L, -1)) { lua_ver = lua_tostring(L, -1); } } sprintf(hostname, "%s", lua_ver); lua_close(L); _L = luaL_newstate(); lua_gc(_L, LUA_GCSTOP, 0); luaL_openlibs(_L); /* Load Lua libraries */ lua_gc(_L, LUA_GCRESTART, 0); if(getarg("host-route")) { lua_pushstring(_L, getarg("host-route")); lua_setglobal(_L, "HOST_ROUTE"); } if(!update_vhost_routes(getarg("host-route")) && !getarg("app")) { LOGF(WARN, "no host-route or app arguments! using defalut settings."); sprintf(tbuf_4096, "%s/host-route.lua", process_chdir); update_vhost_routes(tbuf_4096); } if(getarg("code-cache-ttl")) { /// default = 60s lua_pushnumber(_L, atoi(getarg("code-cache-ttl"))); lua_setglobal(_L, "CODE_CACHE_TTL"); } else { lua_pushnumber(_L, code_cache_ttl); lua_setglobal(_L, "CODE_CACHE_TTL"); } lua_getglobal(_L, "require"); lua_pushcfunction(_L, lua_f_package_require); lua_getfenv(_L, -2); int ret = lua_setfenv(_L, -2); lua_setglobal(_L, "require"); lua_pop(_L, 1); lua_register(_L, "echo", lua_echo); lua_register(_L, "print_error", lua_print_error); lua_register(_L, "sendfile", lua_sendfile); lua_register(_L, "header", lua_header); lua_register(_L, "clear_header", lua_clear_header); lua_register(_L, "__end", lua_end); lua_register(_L, "die", lua_die); lua_register(_L, "flush", lua_flush); lua_register(_L, "read_request_body", lua_read_request_body); lua_register(_L, "get_boundary", lua_f_get_boundary); lua_register(_L, "check_timeout", lua_check_timeout); lua_register(_L, "is_websocket", lua_f_is_websocket); lua_register(_L, "upgrade_to_websocket", lua_f_upgrade_to_websocket); lua_register(_L, "websocket_send", lua_f_websocket_send); lua_register(_L, "check_websocket_close", lua_f_check_websocket_close); lua_register(_L, "router", lua_f_router); lua_register(_L, "random_string", lua_f_random_string); lua_register(_L, "file_exists", lua_f_file_exists); lua_register(_L, "readfile", lua_f_readfile); lua_register(_L, "filemtime", lua_f_filemtime); lua_register(_L, "cache_set", lua_f_cache_set); lua_register(_L, "cache_get", lua_f_cache_get); lua_register(_L, "cache_del", lua_f_cache_del); luaopen_fastlz(_L); luaopen_coevent(_L); luaopen_libfs(_L); luaopen_string_utils(_L); luaopen_i18n(_L); luaopen_crypto(_L); lua_pop(_L, 1); sprintf(tbuf_4096, "package.path = '%slua-libs/?.lua;' .. package.path package.cpath = '%slua-libs/?.so;' .. package.cpath", cwd, cwd); luaL_dostring(_L, tbuf_4096); luaL_dostring(_L, "" "if not CODE_CACHE_TTL then CODE_CACHE_TTL = 60 end " \ "startloop = nil __CodeCache = {{},{}} __CodeCacheC = {false,false} " ); if(getarg("accesslog")) { ACCESS_LOG = open_log(getarg("accesslog"), 40960); if(!ACCESS_LOG) { LOGF(ERR, "Couldn't open access log file: %s", getarg("accesslog")); } } if(getarg("ssl-bind") && getarg("ssl-cert") && getarg("ssl-key")) { ssl_ctx = SSL_CTX_new(SSLv23_server_method()); if(!ssl_ctx) { LOGF(ERR, "SSL_CTX_new Failed"); exit(1); } if(SSL_CTX_use_certificate_file(ssl_ctx, getarg("ssl-cert"), SSL_FILETYPE_PEM) != 1) { SSL_CTX_free(ssl_ctx); LOGF(ERR, "SSL_CTX_use_certificate_file"); exit(1); } if(SSL_CTX_use_PrivateKey_file(ssl_ctx, getarg("ssl-key"), SSL_FILETYPE_PEM) != 1) { SSL_CTX_free(ssl_ctx); LOGF(ERR, "SSL_CTX_use_PrivateKey_file"); exit(1); } SSL_CTX_set_options(ssl_ctx, SSL_OP_ALL); if(getarg("ssl-ca")) { ssl_epd_idx = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL); if(ssl_epd_idx == -1) { LOGF(ERR, "SSL_get_ex_new_index Failed"); exit(1); } if(SSL_CTX_load_verify_locations(ssl_ctx, getarg("ssl-ca"), NULL) != 1) { SSL_CTX_free(ssl_ctx); LOGF(ERR, "SSL_CTX_load_verify_locations"); exit(1); } else { SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_callback); SSL_CTX_set_verify_depth(ssl_ctx, 4); } } } _shm_serv_status = shm_malloc(sizeof(serv_status_t)); bzero(_shm_serv_status->p, sizeof(serv_status_t)); attach_on_exit(on_master_exit_handler); return merry_start(argc, argv, help, master_main, on_master_exit_handler, worker_main, 0); }
ScriptingEnvironment::ScriptingEnvironment(const char * fileName) { SimpleLogger().Write() << "Using script " << fileName; // Create a new lua state for(int i = 0; i < omp_get_max_threads(); ++i) { luaStateVector.push_back(luaL_newstate()); } // Connect LuaBind to this lua state for all threads #pragma omp parallel { lua_State * myLuaState = getLuaStateForThreadID(omp_get_thread_num()); luabind::open(myLuaState); //open utility libraries string library; luaL_openlibs(myLuaState); luaAddScriptFolderToLoadPath( myLuaState, fileName ); // Add our function to the state's global scope luabind::module(myLuaState) [ luabind::def("print", LUA_print<std::string>), luabind::def("parseMaxspeed", parseMaxspeed), luabind::def("durationIsValid", durationIsValid), luabind::def("parseDuration", parseDuration) ]; luabind::module(myLuaState) [ luabind::class_<HashTable<std::string, std::string> >("keyVals") .def("Add", &HashTable<std::string, std::string>::Add) .def("Find", &HashTable<std::string, std::string>::Find) .def("Holds", &HashTable<std::string, std::string>::Holds) ]; luabind::module(myLuaState) [ luabind::class_<ImportNode>("Node") .def(luabind::constructor<>()) .def_readwrite("lat", &ImportNode::lat) .def_readwrite("lon", &ImportNode::lon) .def_readwrite("id", &ImportNode::id) .def_readwrite("bollard", &ImportNode::bollard) .def_readwrite("traffic_light", &ImportNode::trafficLight) .def_readwrite("tags", &ImportNode::keyVals) ]; luabind::module(myLuaState) [ luabind::class_<ExtractionWay>("Way") .def(luabind::constructor<>()) .def_readwrite("name", &ExtractionWay::name) .def_readwrite("speed", &ExtractionWay::speed) .def_readwrite("backward_speed", &ExtractionWay::backward_speed) .def_readwrite("duration", &ExtractionWay::duration) .def_readwrite("type", &ExtractionWay::type) .def_readwrite("access", &ExtractionWay::access) .def_readwrite("roundabout", &ExtractionWay::roundabout) .def_readwrite("is_access_restricted", &ExtractionWay::isAccessRestricted) .def_readwrite("ignore_in_grid", &ExtractionWay::ignoreInGrid) .def_readwrite("tags", &ExtractionWay::keyVals) .def_readwrite("direction", &ExtractionWay::direction) .enum_("constants") [ luabind::value("notSure", 0), luabind::value("oneway", 1), luabind::value("bidirectional", 2), luabind::value("opposite", 3) ] ]; luabind::module(myLuaState) [ luabind::class_<std::vector<std::string> >("vector") .def("Add", &std::vector<std::string>::push_back) ]; if(0 != luaL_dofile(myLuaState, fileName) ) { throw OSRMException("ERROR occured in scripting block"); } } }
// Ctor, initialization lua_kernel_base::lua_kernel_base(CVideo * video) : mState(luaL_newstate()) , video_(video) , cmd_log_() { get_lua_kernel_base_ptr(mState) = this; lua_State *L = mState; cmd_log_ << "Initializing " << my_name() << "...\n"; // Open safe libraries. // Debug and OS are not, but most of their functions will be disabled below. cmd_log_ << "Adding standard libs...\n"; static const luaL_Reg safe_libs[] = { { "", luaopen_base }, { "table", luaopen_table }, { "string", luaopen_string }, { "math", luaopen_math }, { "coroutine", luaopen_coroutine }, { "debug", luaopen_debug }, { "os", luaopen_os }, { "bit32", luaopen_bit32 }, // added in Lua 5.2 { NULL, NULL } }; for (luaL_Reg const *lib = safe_libs; lib->func; ++lib) { luaL_requiref(L, lib->name, lib->func, 1); lua_pop(L, 1); /* remove lib */ } // Disable functions from os which we don't want. lua_getglobal(L, "os"); lua_pushnil(L); while(lua_next(L, -2) != 0) { lua_pop(L, 1); char const* function = lua_tostring(L, -1); if(strcmp(function, "clock") == 0 || strcmp(function, "date") == 0 || strcmp(function, "time") == 0 || strcmp(function, "difftime") == 0) continue; lua_pushnil(L); lua_setfield(L, -3, function); } lua_pop(L, 1); // Disable functions from debug which we don't want. lua_getglobal(L, "debug"); lua_pushnil(L); while(lua_next(L, -2) != 0) { lua_pop(L, 1); char const* function = lua_tostring(L, -1); if(strcmp(function, "traceback") == 0 || strcmp(function, "getinfo") == 0) continue; //traceback is needed for our error handler lua_pushnil(L); //getinfo is needed for ilua strict mode lua_setfield(L, -3, function); } lua_pop(L, 1); // Delete dofile and loadfile. lua_pushnil(L); lua_setglobal(L, "dofile"); lua_pushnil(L); lua_setglobal(L, "loadfile"); // Store the error handler. cmd_log_ << "Adding error handler...\n"; lua_pushlightuserdata(L , executeKey); lua_getglobal(L, "debug"); lua_getfield(L, -1, "traceback"); lua_remove(L, -2); lua_rawset(L, LUA_REGISTRYINDEX); lua_pop(L, 1); // Create the gettext metatable. cmd_log_ << lua_common::register_gettext_metatable(L); // Create the tstring metatable. cmd_log_ << lua_common::register_tstring_metatable(L); lua_settop(L, 0); // Define the CPP_function metatable ( so we can override print to point to a C++ member function, add "show_dialog" for this kernel, etc. ) cmd_log_ << "Adding boost function proxy...\n"; lua_cpp::register_metatable(L); // Add some callback from the wesnoth lib cmd_log_ << "Registering basic wesnoth API...\n"; static luaL_Reg const callbacks[] = { { "compare_versions", &intf_compare_versions }, { "have_file", &lua_fileops::intf_have_file }, { "textdomain", &lua_common::intf_textdomain }, { "tovconfig", &lua_common::intf_tovconfig }, { "get_dialog_value", &lua_gui2::intf_get_dialog_value }, { "set_dialog_active", &lua_gui2::intf_set_dialog_active }, { "set_dialog_visible", &lua_gui2::intf_set_dialog_visible }, { "add_dialog_tree_node", &lua_gui2::intf_add_dialog_tree_node }, { "set_dialog_callback", &lua_gui2::intf_set_dialog_callback }, { "set_dialog_canvas", &lua_gui2::intf_set_dialog_canvas }, { "set_dialog_focus", &lua_gui2::intf_set_dialog_focus }, { "set_dialog_markup", &lua_gui2::intf_set_dialog_markup }, { "set_dialog_value", &lua_gui2::intf_set_dialog_value }, { "remove_dialog_item", &lua_gui2::intf_remove_dialog_item }, { "dofile", &dispatch<&lua_kernel_base::intf_dofile> }, { "require", &dispatch<&lua_kernel_base::intf_require> }, { "show_dialog", &dispatch<&lua_kernel_base::intf_show_dialog> }, { "show_message_dialog", &dispatch<&lua_kernel_base::intf_show_message_dialog> }, { "show_popup_dialog", &dispatch<&lua_kernel_base::intf_show_popup_dialog> }, { "show_lua_console", &dispatch<&lua_kernel_base::intf_show_lua_console> }, { NULL, NULL } }; lua_cpp::Reg const cpp_callbacks[] = { /* { "dofile", boost::bind(&lua_kernel_base::intf_dofile, this, _1)}, { "require", boost::bind(&lua_kernel_base::intf_require, this, _1)}, { "show_dialog", boost::bind(&lua_kernel_base::intf_show_dialog, this, _1)}, { "show_lua_console", boost::bind(&lua_kernel_base::intf_show_lua_console, this, _1)}, */ { NULL, NULL } }; lua_getglobal(L, "wesnoth"); if (!lua_istable(L,-1)) { lua_newtable(L); } luaL_setfuncs(L, callbacks, 0); lua_cpp::set_functions(L, cpp_callbacks, 0); lua_setglobal(L, "wesnoth"); // Override the print function cmd_log_ << "Redirecting print function...\n"; lua_getglobal(L, "print"); lua_setglobal(L, "std_print"); //storing original impl as 'std_print' lua_settop(L, 0); //clear stack, just to be sure lua_pushcfunction(L, &dispatch<&lua_kernel_base::intf_print>); lua_setglobal(L, "print"); // Create the package table. lua_getglobal(L, "wesnoth"); lua_newtable(L); lua_setfield(L, -2, "package"); lua_pop(L, 1); // Get some callbacks for map locations cmd_log_ << "Adding map_location table...\n"; static luaL_Reg const map_callbacks[] = { { "get_direction", &lua_map_location::intf_get_direction }, { "vector_sum", &lua_map_location::intf_vector_sum }, { "vector_negation", &lua_map_location::intf_vector_negation }, { "zero", &lua_map_location::intf_vector_zero }, { "rotate_right_around_center", &lua_map_location::intf_rotate_right_around_center }, { "tiles_adjacent", &lua_map_location::intf_tiles_adjacent }, { "get_adjacent_tiles", &lua_map_location::intf_get_adjacent_tiles }, { "distance_between", &lua_map_location::intf_distance_between }, { "get_in_basis_N_NE", &lua_map_location::intf_get_in_basis_N_NE }, { "get_relative_dir", &lua_map_location::intf_get_relative_dir }, { "parse_direction", &lua_map_location::intf_parse_direction }, { "write_direction", &lua_map_location::intf_write_direction }, { NULL, NULL } }; // Create the map_location table. lua_getglobal(L, "wesnoth"); lua_newtable(L); luaL_setfuncs(L, map_callbacks, 0); lua_setfield(L, -2, "map_location"); lua_pop(L,1); // Add mersenne twister rng wrapper cmd_log_ << "Adding rng tables...\n"; lua_rng::load_tables(L); // Loading ilua: cmd_log_ << "Loading ilua...\n"; lua_pushstring(L, "lua/ilua.lua"); int result = intf_require(L); if (result == 1) { //run "ilua.set_strict()" lua_pushstring(L, "set_strict"); lua_gettable(L, -2); if (!protected_call(0,0, boost::bind(&lua_kernel_base::log_error, this, _1, _2))) { cmd_log_ << "Failed to activate strict mode.\n"; } else { cmd_log_ << "Activated strict mode.\n"; } lua_setglobal(L, "ilua"); //save ilua table as a global } else { cmd_log_ << "Error: failed to load ilua.\n"; } lua_settop(L, 0); }
void LuaParser::ReloadQuests() { loaded_.clear(); errors_.clear(); lua_encounter_events_registered.clear(); lua_encounters_loaded.clear(); for (auto encounter : lua_encounters) { encounter.second->Depop(); } lua_encounters.clear(); if(L) { lua_close(L); } L = luaL_newstate(); luaL_openlibs(L); if(luaopen_bit(L) != 1) { std::string error = lua_tostring(L, -1); AddError(error); } if(luaL_dostring(L, "math.randomseed(os.time())")) { std::string error = lua_tostring(L, -1); AddError(error); } #ifdef SANITIZE_LUA_LIBS //io lua_pushnil(L); lua_setglobal(L, "io"); //some os/debug are okay some are not lua_getglobal(L, "os"); lua_pushnil(L); lua_setfield(L, -2, "exit"); lua_pushnil(L); lua_setfield(L, -2, "execute"); lua_pushnil(L); lua_setfield(L, -2, "getenv"); lua_pushnil(L); lua_setfield(L, -2, "remove"); lua_pushnil(L); lua_setfield(L, -2, "rename"); lua_pushnil(L); lua_setfield(L, -2, "setlocale"); lua_pushnil(L); lua_setfield(L, -2, "tmpname"); lua_pop(L, 1); lua_pushnil(L); lua_setglobal(L, "collectgarbage"); lua_pushnil(L); lua_setglobal(L, "loadfile"); #endif // lua 5.2+ defines these #if defined(LUA_VERSION_MAJOR) && defined(LUA_VERSION_MINOR) const char lua_version[] = LUA_VERSION_MAJOR "." LUA_VERSION_MINOR; #elif LUA_VERSION_NUM == 501 const char lua_version[] = "5.1"; #else #error Incompatible lua version #endif #ifdef WINDOWS const char libext[] = ".dll"; #else // lua doesn't care OSX doesn't use sonames const char libext[] = ".so"; #endif lua_getglobal(L, "package"); lua_getfield(L, -1, "path"); std::string module_path = lua_tostring(L,-1); module_path += ";./" + Config->LuaModuleDir + "?.lua;./" + Config->LuaModuleDir + "?/init.lua"; // luarock paths using lua_modules as tree // to path it adds foo/share/lua/5.1/?.lua and foo/share/lua/5.1/?/init.lua module_path += ";./" + Config->LuaModuleDir + "share/lua/" + lua_version + "/?.lua"; module_path += ";./" + Config->LuaModuleDir + "share/lua/" + lua_version + "/?/init.lua"; lua_pop(L, 1); lua_pushstring(L, module_path.c_str()); lua_setfield(L, -2, "path"); lua_pop(L, 1); lua_getglobal(L, "package"); lua_getfield(L, -1, "cpath"); module_path = lua_tostring(L, -1); module_path += ";./" + Config->LuaModuleDir + "?" + libext; // luarock paths using lua_modules as tree // luarocks adds foo/lib/lua/5.1/?.so for cpath module_path += ";./" + Config->LuaModuleDir + "lib/lua/" + lua_version + "/?" + libext; lua_pop(L, 1); lua_pushstring(L, module_path.c_str()); lua_setfield(L, -2, "cpath"); lua_pop(L, 1); MapFunctions(L); //load init std::string path = Config->QuestDir; path += "/"; path += QUEST_GLOBAL_DIRECTORY; path += "/script_init.lua"; FILE *f = fopen(path.c_str(), "r"); if(f) { fclose(f); if(luaL_dofile(L, path.c_str())) { std::string error = lua_tostring(L, -1); AddError(error); } } //zone init - always loads after global if(zone) { std::string zone_script = Config->QuestDir; zone_script += "/"; zone_script += zone->GetShortName(); zone_script += "/script_init_v"; zone_script += std::to_string(zone->GetInstanceVersion()); zone_script += ".lua"; f = fopen(zone_script.c_str(), "r"); if(f) { fclose(f); if(luaL_dofile(L, zone_script.c_str())) { std::string error = lua_tostring(L, -1); AddError(error); } return; } zone_script = Config->QuestDir; zone_script += "/"; zone_script += zone->GetShortName(); zone_script += "/script_init.lua"; f = fopen(zone_script.c_str(), "r"); if(f) { fclose(f); if(luaL_dofile(L, zone_script.c_str())) { std::string error = lua_tostring(L, -1); AddError(error); } } } }
/*@-globs -mods@*/ /* XXX hide rpmGlobalMacroContext mods for now. */ rpmlua rpmluaNew(void) { rpmlua lua = rpmluaGetPool(_rpmluaPool); lua_State *L = luaL_newstate(); /*@-readonlytrans -nullassign @*/ /*@observer@*/ /*@unchecked@*/ static const luaL_Reg lualibs[] = { #ifdef WITH_SYCK {"lsyck", luaopen_syck}, #endif /* WITH_SYCK */ /* local LUA libraries (RPM only) */ #ifdef WITH_LUA_INTERNAL {"posix", luaopen_posix_c}, {"rex_posix", luaopen_rex_posix}, {"rex_pcre", luaopen_rex_pcre}, {"uuid", luaopen_uuid}, #ifdef DYING /* XXX not currently internal */ {"wrs", luaopen_wrs}, #endif #ifdef USE_LUA_CRYPTO /* XXX external lua modules instead. */ {"crypto", luaopen_crypto}, {"lxp", luaopen_lxp}, #endif #ifdef USE_LUA_SOCKET /* XXX external lua modules instead. */ {"socket", luaopen_socket_core}, #endif {"local", luaopen_local}, #endif {"rpm", luaopen_rpm}, {NULL, NULL}, }; /*@=readonlytrans =nullassign @*/ /*@observer@*/ /*@unchecked@*/ const luaL_Reg *lib = lualibs; char *path_buf; char *path_next; char *path; lua->L = L; lua->pushsize = 0; lua->storeprint = 0; /* XXX TODO: use an rpmiob here. */ lua->printbufsize = 0; lua->printbufused = 0; lua->printbuf = NULL; luaL_openlibs(L); for (; lib->name; lib++) { luaL_requiref(L, lib->name, lib->func, 1); } { const char * _lua_path = rpmGetPath(rpmluaPath, NULL); if (_lua_path != NULL) { lua_pushliteral(L, "LUA_PATH"); lua_pushstring(L, _lua_path); _lua_path = _free(_lua_path); } } #if defined(LUA_GLOBALSINDEX) lua_rawset(L, LUA_GLOBALSINDEX); #else lua_pushglobaltable(L); #endif lua_pushliteral(L, "print"); lua_pushcfunction(L, rpm_print); #if defined(LUA_GLOBALSINDEX) lua_rawset(L, LUA_GLOBALSINDEX); #else lua_pushglobaltable(L); #endif rpmluaSetData(lua, "lua", lua); /* load all standard RPM Lua script files */ path_buf = xstrdup(rpmluaFiles); for (path = path_buf; path != NULL && *path != '\0'; path = path_next) { const char **av; struct stat st; int ac, i; /* locate start of next path element */ path_next = strchr(path, ':'); if (path_next != NULL && *path_next == ':') *path_next++ = '\0'; else path_next = path + strlen(path); /* glob-expand the path element */ ac = 0; av = NULL; if ((i = rpmGlob(path, &ac, &av)) != 0) continue; /* work-off each resulting file from the path element */ for (i = 0; i < ac; i++) { const char *fn = av[i]; if (fn[0] == '@' /* attention */) { fn++; #if defined(RPM_VENDOR_OPENPKG) /* stick-with-rpm-file-sanity-checking */ || \ !defined(POPT_ERROR_BADCONFIG) /* XXX POPT 1.15 retrofit */ if (!rpmSecuritySaneFile(fn)) #else if (!poptSaneFile(fn)) #endif { rpmlog(RPMLOG_WARNING, "existing RPM Lua script file \"%s\" considered INSECURE -- not loaded\n", fn); /*@innercontinue@*/ continue; } } if (Stat(fn, &st) != -1) (void)rpmluaRunScriptFile(lua, fn); av[i] = _free(av[i]); } av = _free(av); } path_buf = _free(path_buf); return ((rpmlua)rpmioLinkPoolItem((rpmioItem)lua, __FUNCTION__, __FILE__, __LINE__)); }