/* Release resources related to Lua scripting. * This function is used in order to reset the scripting environment. */ void scriptingRelease(void) { dictRelease(server.lua_scripts); lua_close(server.lua); }
struct lua_debugst* dbg_lua_load(bstring name) { bstring path, modtype; struct lua_debugst* ds; int module; // Calculate full path to file. path = osutil_getmodulepath(); bconchar(path, '/'); bconcat(path, name); // Create the new lua preprocessor structure. ds = malloc(sizeof(struct lua_debugst)); ds->state = lua_open(); assert(ds->state != NULL); luaL_openlibs(ds->state); luaX_loadexpressionlib(ds->state); // Load globals. dcpu_lua_set_constants(ds->state); // Execute the code in the new Lua context. if (luaL_dofile(ds->state, path->data) != 0) { printd(LEVEL_ERROR, "lua error was %s.\n", lua_tostring(ds->state, -1)); // Return NULL. lua_close(ds->state); free(ds); bdestroy(path); return NULL; } // Load tables. lua_getglobal(ds->state, "MODULE"); module = lua_gettop(ds->state); // Ensure module table was provided. if (lua_isnoneornil(ds->state, module)) { printd(LEVEL_ERROR, "failed to load debugger module from %s.\n", path->data); // Return NULL. lua_close(ds->state); free(ds); bdestroy(path); return NULL; } // Check to see whether the module is // a preprocessor module. lua_getfield(ds->state, module, "Type"); modtype = bfromcstr(lua_tostring(ds->state, -1)); if (!biseqcstrcaseless(modtype, "Debugger")) { // Return NULL. lua_pop(ds->state, 1); lua_close(ds->state); free(ds); bdestroy(modtype); bdestroy(path); return NULL; } lua_pop(ds->state, 1); bdestroy(modtype); // Create the handler tables. lua_newtable(ds->state); lua_setglobal(ds->state, HANDLER_TABLE_COMMANDS_NAME); lua_newtable(ds->state); lua_setglobal(ds->state, HANDLER_TABLE_HOOKS_NAME); lua_newtable(ds->state); lua_setglobal(ds->state, HANDLER_TABLE_SYMBOLS_NAME); // Set the global functions. lua_pushcfunction(ds->state, &dbg_lua_add_command); lua_setglobal(ds->state, "add_command"); lua_pushcfunction(ds->state, &dbg_lua_add_hook); lua_setglobal(ds->state, "add_hook"); lua_pushcfunction(ds->state, &dbg_lua_add_symbol_hook); lua_setglobal(ds->state, "add_symbol_hook"); // Run the setup function. lua_getglobal(ds->state, "setup"); if (lua_pcall(ds->state, 0, 0, 0) != 0) { printd(LEVEL_ERROR, "failed to run setup() in debugger module from %s.\n", path->data); printd(LEVEL_ERROR, "lua error was %s.\n", lua_tostring(ds->state, -1)); } // Unset the global functions. lua_pushnil(ds->state); lua_setglobal(ds->state, "add_command"); lua_pushnil(ds->state); lua_setglobal(ds->state, "add_hook"); lua_pushnil(ds->state); lua_setglobal(ds->state, "add_symbol_hook"); // Pop tables from stack. lua_pop(ds->state, 2); // Return new debugger module. return ds; }
lua_State *luaScriptInit(char *buff) { ScriptErrorStr[0]='\0'; ScriptErrorCode=0; setlocale(LC_ALL, ""); // lua_State *L = lua_open(); /* create state */ // 関数を登録する lua_register(L, "out", luaPrint); lua_register(L, "_MX", luaGetMouseX); lua_register(L, "_MY", luaGetMouseY); lua_register(L, "_ML", luaGetMouseL); lua_register(L, "_MR", luaGetMouseR); lua_register(L, "_MM", luaGetMouseM); lua_register(L, "_DT", luaGetDt); lua_register(L, "_FPS", luaGetFps); lua_register(L, "_BASE", luaGetBase); lua_register(L, "_TICKS", luaGetTickCount); lua_register(L, "_SETTICKS", luaSetTicks); lua_register(L, "_KEY", luaKey); lua_register(L, "_KEYDOWN", luaKeyDown); lua_register(L, "_KEYUP", luaKeyUp); lua_register(L, "_ANALOG", luaAnalog); lua_register(L, "_HAT", luaHat); lua_register(L, "_CHIPS", luaChips); lua_register(L, "_WEIGHT", luaWeight); lua_register(L, "_WIDTH", luaGetWidth); lua_register(L, "_HEIGHT", luaGetHeight); lua_register(L, "_FACE", luaGetFaces); lua_register(L, "_ZOOM", luaSetCCDZoom); lua_register(L, "_OX", luaObjPosx); lua_register(L, "_OY", luaObjPosy); lua_register(L, "_OZ", luaObjPosz); lua_register(L, "_X", luaPosx); lua_register(L, "_Y", luaPosy); lua_register(L, "_Z", luaPosz); lua_register(L, "_H", luaGetY); lua_register(L, "_AX", luaAx); lua_register(L, "_AY", luaAy); lua_register(L, "_AZ", luaAz); lua_register(L, "_EX", luaEx); lua_register(L, "_EY", luaEy); lua_register(L, "_EZ", luaEz); lua_register(L, "_GX", luaGx); lua_register(L, "_GY", luaGy); lua_register(L, "_GZ", luaGz); lua_register(L, "_XX", luaXx); lua_register(L, "_XY", luaXy); lua_register(L, "_XZ", luaXz); lua_register(L, "_YX", luaYx); lua_register(L, "_YY", luaYy); lua_register(L, "_YZ", luaYz); lua_register(L, "_ZX", luaZx); lua_register(L, "_ZY", luaZy); lua_register(L, "_ZZ", luaZz); lua_register(L, "_QX", luaQx); lua_register(L, "_QY", luaQy); lua_register(L, "_QZ", luaQz); lua_register(L, "_QW", luaQw); lua_register(L, "_RX", luaRx); lua_register(L, "_RY", luaRy); lua_register(L, "_RZ", luaRz); lua_register(L, "_LX", luaLx); lua_register(L, "_LY", luaLy); lua_register(L, "_LZ", luaLz); lua_register(L, "_VX", luaVx); lua_register(L, "_VY", luaVy); lua_register(L, "_VZ", luaVz); lua_register(L, "_FX", luaFx); lua_register(L, "_FY", luaFy); lua_register(L, "_FZ", luaFz); lua_register(L, "_WX", luaWx); lua_register(L, "_WY", luaWy); lua_register(L, "_WZ", luaWz); lua_register(L, "_CCD", luaGetCCD); lua_register(L, "_RED", luaGetCCDRed); lua_register(L, "_GREEN", luaGetCCDGreen); lua_register(L, "_BLUE", luaGetCCDBlue); lua_register(L, "_BYE", luaUnLinkBye); lua_register(L, "_SPLIT", luaUnLink); lua_register(L, "_RND", luaRnd); lua_register(L, "_TODEG", luaToDeg); lua_register(L, "_TORAD", luaToRad); lua_register(L, "_TYPE", luaGetType); lua_register(L, "_OPTION", luaGetOption); lua_register(L, "_EFFECT", luaGetEffect); lua_register(L, "_USER1", luaGetUserEffect); lua_register(L, "_USER2", luaGetUserOption); lua_register(L, "_DIR", luaGetDir); lua_register(L, "_ANGLE", luaGetAngle); lua_register(L, "_POWER", luaGetPower); lua_register(L, "_SPRING", luaGetSpring); lua_register(L, "_DAMPER", luaGetDamper); lua_register(L, "_BRAKE", luaGetBrake); lua_register(L, "_COLOR", luaGetColor); lua_register(L, "_PARENT", luaGetParent); lua_register(L, "_TOP", luaGetTop); lua_register(L, "_M", luaGetM); lua_register(L, "_I", luaGetI); lua_register(L, "_MOBJ", luaGetObjM); lua_register(L, "_IOBJ", luaGetObjI); lua_register(L, "_E", luaGetEnergy); lua_register(L, "_T",luaGetTolerant); lua_register(L, "_MOVE3D",luaMove3D); lua_register(L, "_LINE3D",luaLine3D); lua_register(L, "_MOVE2D",luaMove2D); lua_register(L, "_LINE2D",luaLine2D); lua_register(L, "_SETCOLOR",luaSetColor); lua_register(L, "_PLAYERS",luaGetPlayers); lua_register(L, "_PLAYERHOSTID",luaGetPlayerHostID); lua_register(L, "_PLAYERMYID",luaGetPlayerMyID); lua_register(L, "_PLAYERID",luaGetPlayerID); lua_register(L, "_PLAYERCHIPS",luaGetPlayerChips); lua_register(L, "_PLAYERCRUSHES",luaGetPlayerCrushes); lua_register(L, "_PLAYERRESETS",luaGetPlayerResets); lua_register(L, "_PLAYERINITS",luaGetPlayerInits); lua_register(L, "_PLAYERCOLOR",luaGetPlayerColor); lua_register(L, "_PLAYERX",luaGetPlayerX); lua_register(L, "_PLAYERY",luaGetPlayerY); lua_register(L, "_PLAYERZ",luaGetPlayerZ); lua_register(L, "_PLAYERARMS",luaGetPlayerArms); lua_register(L, "_PLAYERYFORCES",luaGetPlayerYForces); lua_register(L, "_PLAYERNAME",luaGetPlayerName); lua_register(L, "_FUEL",luaGetFuel); lua_register(L, "_FUELMAX",luaGetFuelMax); luaL3dx=luaL3dy=luaL3dz=0.0f; luaGraColor=0xffffff; //グローバル変数の登録 for(int i=0;i<VarCount;i++) { lua_pushnumber(L,ValList[i].Val); lua_setglobal(L,ValList[i].Name); } //スクリプトをセットする luaopen_string(L); luaopen_base(L); luaopen_table(L); luaopen_math(L); // luaopen_io(L); int e=lua_dobuffer (L,buff,strlen(buff),szUpdateFileName0); if(e!=0) { ScriptErrorCode=-1; sprintf(ScriptErrorStr,"%s\n",lua_tostring(L,0)); lua_close(L); return NULL; } return L; }
static int _load_script(void) { int rc = SLURM_SUCCESS; struct stat st; lua_State *L_orig = L; if (stat(lua_script_path, &st) != 0) { if (L_orig) { (void) error("Unable to stat %s, " "using old script: %s", lua_script_path, strerror(errno)); return SLURM_SUCCESS; } return error("Unable to stat %s: %s", lua_script_path, strerror(errno)); } if (st.st_mtime <= lua_script_last_loaded) { return SLURM_SUCCESS; } /* * Initilize lua */ L = luaL_newstate(); luaL_openlibs(L); if (luaL_loadfile(L, lua_script_path)) { if (L_orig) { (void) error("lua: %s: %s, using previous script", lua_script_path, lua_tostring(L, -1)); lua_close(L); L = L_orig; return SLURM_SUCCESS; } rc = error("lua: %s: %s", lua_script_path, lua_tostring(L, -1)); lua_pop(L, 1); return rc; } /* * Register SLURM functions in lua state: * logging and slurm structure read/write functions */ _register_lua_slurm_output_functions(); _register_lua_slurm_struct_functions(); /* * Run the user script: */ if (lua_pcall(L, 0, 1, 0) != 0) { if (L_orig) { (void) error("job_submit/lua: %s: %s, " "using previous script", lua_script_path, lua_tostring(L, -1)); lua_close(L); L = L_orig; return SLURM_SUCCESS; } rc = error("job_submit/lua: %s: %s", lua_script_path, lua_tostring(L, -1)); lua_pop(L, 1); return rc; } /* * Get any return code from the lua script */ rc = (int) lua_tonumber(L, -1); if (rc != SLURM_SUCCESS) { if (L_orig) { (void) error("job_submit/lua: %s: returned %d " "on load, using previous script", lua_script_path, rc); lua_close(L); L = L_orig; return SLURM_SUCCESS; } (void) error("job_submit/lua: %s: returned %d on load", lua_script_path, rc); lua_pop (L, 1); return rc; } /* * Check for required lua script functions: */ rc = _check_lua_script_functions(); if (rc != SLURM_SUCCESS) { if (L_orig) { (void) error("job_submit/lua: %s: " "required function(s) not present, " "using previous script", lua_script_path); lua_close(L); L = L_orig; return SLURM_SUCCESS; } return rc; } if (L_orig) lua_close(L_orig); lua_script_last_loaded = time(NULL); return SLURM_SUCCESS; }
void VirtualMachine_DeInit(VirtualMachine* vm) { lua_close(vm->m_state); }
/***************************************************************************** * Open: initialize and create stuff *****************************************************************************/ int Open_LuaSD( vlc_object_t *p_this ) { services_discovery_t *p_sd = ( services_discovery_t * )p_this; services_discovery_sys_t *p_sys; lua_State *L = NULL; char *psz_name = NULL; if( !strcmp(p_sd->psz_name, "lua")) { // We want to load the module name "lua" // This module can be used to load lua script not registered // as builtin lua SD modules. config_ChainParse( p_sd, "lua-", ppsz_sd_options, p_sd->p_cfg ); psz_name = var_CreateGetString( p_sd, "lua-sd" ); } else { // We are loading a builtin lua sd module. psz_name = strdup(p_sd->psz_name); } if( !( p_sys = malloc( sizeof( services_discovery_sys_t ) ) ) ) { free( psz_name ); return VLC_ENOMEM; } p_sd->p_sys = p_sys; p_sys->psz_filename = vlclua_find_file( p_this, "sd", psz_name ); if( !p_sys->psz_filename ) { msg_Err( p_sd, "Couldn't find lua services discovery script \"%s\".", psz_name ); free( psz_name ); goto error; } free( psz_name ); L = luaL_newstate(); if( !L ) { msg_Err( p_sd, "Could not create new Lua State" ); goto error; } vlclua_set_this( L, p_sd ); luaL_openlibs( L ); luaL_register( L, "vlc", p_reg ); luaopen_input( L ); luaopen_msg( L ); luaopen_misc( L ); luaopen_net( L ); luaopen_object( L ); luaopen_sd( L ); luaopen_strings( L ); luaopen_variables( L ); luaopen_stream( L ); luaopen_gettext( L ); luaopen_xml( L ); luaopen_md5( L ); lua_pop( L, 1 ); if( vlclua_add_modules_path( p_sd, L, p_sys->psz_filename ) ) { msg_Warn( p_sd, "Error while setting the module search path for %s", p_sys->psz_filename ); goto error; } if( luaL_dofile( L, p_sys->psz_filename ) ) { msg_Err( p_sd, "Error loading script %s: %s", p_sys->psz_filename, lua_tostring( L, lua_gettop( L ) ) ); lua_pop( L, 1 ); goto error; } p_sys->L = L; if( vlc_clone (&p_sd->p_sys->thread, Run, p_sd, VLC_THREAD_PRIORITY_LOW) ) { goto error; } return VLC_SUCCESS; error: if( L ) lua_close( L ); free( p_sys->psz_filename ); free( p_sys ); return VLC_EGENERIC; }
void lua_free(struct lua *lua) { lua_close(lua->L); allocator_free(lua->A); free(lua); }
/** * Close Lua */ void FA_lua_close(void) { lua_close(L); }
bool sinsp_chisel::parse_view_info(lua_State *ls, OUT chisel_desc* cd) { lua_getglobal(ls, "view_info"); if(lua_isnoneornil(ls, -1)) { lua_close(ls); return false; } lua_pushnil(ls); string tmpstr; string id; string name; string description; vector<string> applies_to; string filter; bool use_defaults = false; sinsp_view_info::viewtype vt = sinsp_view_info::T_TABLE; vector<sinsp_view_column_info> columns; vector<string> tags; vector<string> tips; string drilldown_target; bool is_root = false; while(lua_next(ls, -2) != 0) { string fldname = lua_tostring(ls, -2); if(fldname == "name") { name = lua_tostring(ls, -1); } else if(fldname == "id") { id = lua_tostring(ls, -1); } else if(fldname == "description") { description = lua_tostring(ls, -1); } else if(fldname == "tags") { if(lua_istable(ls, -1)) { lua_pushnil(ls); while(lua_next(ls, -2) != 0) { if(lua_isstring(ls, -1)) { tmpstr = lua_tostring(ls, -1); tags.push_back(tmpstr); } else { throw sinsp_exception("error in view " + cd->m_name + ": " + "tags entries must be strings"); } lua_pop(ls, 1); } } else { throw sinsp_exception("error in view " + cd->m_name + ": " + string(lua_tostring(ls, -2)) + " is not a table"); } } else if(fldname == "tips") { if(lua_istable(ls, -1)) { lua_pushnil(ls); while(lua_next(ls, -2) != 0) { if(lua_isstring(ls, -1)) { tmpstr = lua_tostring(ls, -1); tips.push_back(tmpstr); } else { throw sinsp_exception("error in view " + cd->m_name + ": " + "tips column entries must be strings"); } lua_pop(ls, 1); } } else { throw sinsp_exception("error in view " + cd->m_name + ": " + string(lua_tostring(ls, -2)) + " is not a table"); } } else if(fldname == "view_type") { tmpstr = lua_tostring(ls, -1); if(tmpstr == "table") { vt = sinsp_view_info::T_TABLE; } else if(tmpstr == "list") { vt = sinsp_view_info::T_LIST; } else { throw sinsp_exception("error in view " + cd->m_name + ": " + string(lua_tostring(ls, -2)) + " must be either 'table' or 'list'"); } } else if(fldname == "drilldown_target") { drilldown_target = lua_tostring(ls, -1); } else if(fldname == "applies_to") { if(lua_istable(ls, -1)) { lua_pushnil(ls); while(lua_next(ls, -2) != 0) { if(lua_isstring(ls, -1)) { tmpstr = lua_tostring(ls, -1); applies_to.push_back(tmpstr); } else { throw sinsp_exception("error in view " + cd->m_name + ": " + "tips column entries must be strings"); } lua_pop(ls, 1); } } else { throw sinsp_exception("error in view " + cd->m_name + ": " + string(lua_tostring(ls, -2)) + " is not a table"); } } else if(fldname == "filter") { filter = lua_tostring(ls, -1); } else if(fldname == "use_defaults") { if(lua_isboolean(ls, -1)) { use_defaults = (lua_toboolean(ls, -1) != 0); } else { throw sinsp_exception("error in view " + cd->m_name + ": " + string(lua_tostring(ls, -2)) + " must be a boolean"); } } else if(fldname == "is_root") { if(lua_isboolean(ls, -1)) { is_root = (lua_toboolean(ls, -1) != 0); } else { throw sinsp_exception("error in view " + cd->m_name + ": " + string(lua_tostring(ls, -2)) + " must be a boolean"); } } else if(fldname == "columns") { if(lua_istable(ls, -1)) { parse_view_columns(ls, cd, &columns); } else { throw sinsp_exception("error in view " + cd->m_name + ": " + string(lua_tostring(ls, -2)) + " is not a table"); } } lua_pop(ls, 1); } cd->m_viewinfo = sinsp_view_info(vt, id, name, description, tags, tips, columns, applies_to, filter, drilldown_target, use_defaults, is_root); return true; }
void LuaScriptUtilities::DestroyVM(lua_State* const luaVM) { lua_close(luaVM); }
bool ConfigManager::load() { lua_State* L = luaL_newstate(); if (!L) { throw std::runtime_error("Failed to allocate memory"); } 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 (!m_isLoaded) { //info that must be loaded one time (unless we reset the modules involved) m_confBoolean[SERVERSAVE_ENABLED] = booleanString(getGlobalString(L, "serverSaveEnabled", "yes")); m_confBoolean[SAVE_GLOBAL_STORAGE] = booleanString(getGlobalString(L, "saveGlobalStorage", "no")); m_confBoolean[BIND_ONLY_GLOBAL_ADDRESS] = booleanString(getGlobalString(L, "bindOnlyGlobalAddress", "no")); m_confBoolean[OPTIMIZE_DATABASE] = booleanString(getGlobalString(L, "startupDatabaseOptimization", "yes")); m_confString[IP] = getGlobalString(L, "ip", "127.0.0.1"); m_confString[MAP_NAME] = getGlobalString(L, "mapName", "forgotten"); m_confString[MAP_AUTHOR] = getGlobalString(L, "mapAuthor", "Unknown"); m_confString[HOUSE_RENT_PERIOD] = getGlobalString(L, "houseRentPeriod", "monthly"); m_confString[MYSQL_HOST] = getGlobalString(L, "mysqlHost", "localhost"); m_confString[MYSQL_USER] = getGlobalString(L, "mysqlUser", "root"); m_confString[MYSQL_PASS] = getGlobalString(L, "mysqlPass", ""); m_confString[MYSQL_DB] = getGlobalString(L, "mysqlDatabase", "theforgottenserver"); m_confString[PASSWORDTYPE] = getGlobalString(L, "passwordType", "plain"); m_confInteger[SQL_PORT] = getGlobalNumber(L, "mysqlPort", 3306); m_confInteger[PASSWORD_TYPE] = PASSWORD_TYPE_PLAIN; m_confInteger[SERVERSAVE_H] = getGlobalNumber(L, "serverSaveHour", 3); m_confInteger[ADMIN_PORT] = getGlobalNumber(L, "adminProtocolPort", 7171); m_confInteger[GAME_PORT] = getGlobalNumber(L, "gameProtocolPort", 7172); m_confInteger[LOGIN_PORT] = getGlobalNumber(L, "loginProtocolPort", 7171); m_confInteger[STATUS_PORT] = getGlobalNumber(L, "statusProtocolPort", 7171); m_confInteger[MARKET_OFFER_DURATION] = getGlobalNumber(L, "marketOfferDuration", 30 * 24 * 60 * 60); } m_confBoolean[ALLOW_CHANGEOUTFIT] = booleanString(getGlobalString(L, "allowChangeOutfit", "yes")); m_confBoolean[ONE_PLAYER_ON_ACCOUNT] = booleanString(getGlobalString(L, "onePlayerOnlinePerAccount", "yes")); m_confBoolean[CANNOT_ATTACK_SAME_LOOKFEET] = booleanString(getGlobalString(L, "noDamageToSameLookfeet", "no")); m_confBoolean[AIMBOT_HOTKEY_ENABLED] = booleanString(getGlobalString(L, "hotkeyAimbotEnabled", "yes")); m_confBoolean[REMOVE_AMMO] = booleanString(getGlobalString(L, "removeAmmoWhenUsingDistanceWeapon", "yes")); m_confBoolean[REMOVE_RUNE_CHARGES] = booleanString(getGlobalString(L, "removeChargesFromRunes", "yes")); m_confBoolean[REMOVE_WEAPON_CHARGES] = booleanString(getGlobalString(L, "removeChargesFromWeapons", "yes")); m_confBoolean[EXPERIENCE_FROM_PLAYERS] = booleanString(getGlobalString(L, "experienceByKillingPlayers", "no")); m_confBoolean[SHUTDOWN_AT_SERVERSAVE] = booleanString(getGlobalString(L, "shutdownAtServerSave", "no")); m_confBoolean[CLEAN_MAP_AT_SERVERSAVE] = booleanString(getGlobalString(L, "cleanMapAtServerSave", "yes")); m_confBoolean[FREE_PREMIUM] = booleanString(getGlobalString(L, "freePremium", "no")); m_confBoolean[ADMIN_LOGS_ENABLED] = booleanString(getGlobalString(L, "adminLogsEnabled", "no")); m_confBoolean[REPLACE_KICK_ON_LOGIN] = booleanString(getGlobalString(L, "replaceKickOnLogin", "yes")); m_confBoolean[ALLOW_CLONES] = booleanString(getGlobalString(L, "allowClones", "no")); m_confBoolean[MARKET_PREMIUM] = booleanString(getGlobalString(L, "premiumToCreateMarketOffer", "yes")); m_confBoolean[STAMINA_SYSTEM] = booleanString(getGlobalString(L, "staminaSystem", "yes")); m_confString[DEFAULT_PRIORITY] = getGlobalString(L, "defaultPriority", "high"); m_confString[LOGIN_MSG] = getGlobalString(L, "loginMessage", "Welcome to the Forgotten Server!"); m_confString[SERVER_NAME] = getGlobalString(L, "serverName"); m_confString[OWNER_NAME] = getGlobalString(L, "ownerName"); m_confString[OWNER_EMAIL] = getGlobalString(L, "ownerEmail"); m_confString[URL] = getGlobalString(L, "url"); m_confString[LOCATION] = getGlobalString(L, "location"); m_confString[MOTD] = getGlobalString(L, "motd"); m_confString[WORLD_TYPE] = getGlobalString(L, "worldType", "pvp"); m_confInteger[MAX_PLAYERS] = getGlobalNumber(L, "maxPlayers"); m_confInteger[PZ_LOCKED] = getGlobalNumber(L, "pzLocked", 0); m_confInteger[DEFAULT_DESPAWNRANGE] = getGlobalNumber(L, "deSpawnRange", 2); m_confInteger[DEFAULT_DESPAWNRADIUS] = getGlobalNumber(L, "deSpawnRadius", 50); m_confInteger[RATE_EXPERIENCE] = getGlobalNumber(L, "rateExp", 1); m_confInteger[RATE_SKILL] = getGlobalNumber(L, "rateSkill", 1); m_confInteger[RATE_LOOT] = getGlobalNumber(L, "rateLoot", 1); m_confInteger[RATE_MAGIC] = getGlobalNumber(L, "rateMagic", 1); m_confInteger[RATE_SPAWN] = getGlobalNumber(L, "rateSpawn", 1); m_confInteger[HOUSE_PRICE] = getGlobalNumber(L, "housePriceEachSQM", 1000); m_confInteger[KILLS_TO_RED] = getGlobalNumber(L, "killsToRedSkull", 3); m_confInteger[KILLS_TO_BLACK] = getGlobalNumber(L, "killsToBlackSkull", 6); m_confInteger[ACTIONS_DELAY_INTERVAL] = getGlobalNumber(L, "timeBetweenActions", 200); m_confInteger[EX_ACTIONS_DELAY_INTERVAL] = getGlobalNumber(L, "timeBetweenExActions", 1000); m_confInteger[MAX_MESSAGEBUFFER] = getGlobalNumber(L, "maxMessageBuffer", 4); m_confInteger[CRITICAL_HIT_CHANCE] = getGlobalNumber(L, "criticalHitChance", 5); m_confInteger[KICK_AFTER_MINUTES] = getGlobalNumber(L, "kickIdlePlayerAfterMinutes", 15); m_confInteger[PROTECTION_LEVEL] = getGlobalNumber(L, "protectionLevel", 1); m_confInteger[DEATH_LOSE_PERCENT] = getGlobalNumber(L, "deathLosePercent", -1); m_confInteger[STATUSQUERY_TIMEOUT] = getGlobalNumber(L, "statusTimeout", 60000); m_confInteger[FRAG_TIME] = getGlobalNumber(L, "timeToDecreaseFrags", 24 * 60 * 60 * 1000); m_confInteger[WHITE_SKULL_TIME] = getGlobalNumber(L, "whiteSkullTime", 15 * 60 * 1000); m_confInteger[AUTO_SAVE_EACH_MINUTES] = getGlobalNumber(L, "autoSaveEachMinutes", 0); m_confInteger[STAIRHOP_DELAY] = getGlobalNumber(L, "stairJumpExhaustion", 2000); m_confInteger[EXP_FROM_PLAYERS_LEVEL_RANGE] = getGlobalNumber(L, "expFromPlayersLevelRange", 75); m_confInteger[CHECK_EXPIRED_MARKET_OFFERS_EACH_MINUTES] = getGlobalNumber(L, "checkExpiredMarketOffersEachMinutes", 60); m_confInteger[MAX_MARKET_OFFERS_AT_A_TIME_PER_PLAYER] = getGlobalNumber(L, "maxMarketOffersAtATimePerPlayer", 100); m_confInteger[MAX_PACKETS_PER_SECOND] = getGlobalNumber(L, "maxPacketsPerSecond", 40); m_isLoaded = true; lua_close(L); return true; }
void ALua::close() { lua_close(L); }
int addon_output_init(struct output *o) { struct addon *addon = o->info->reg_info->mod->priv; lua_State *L = addon_create_state(addon->filename); // Stack : empty if (!L) { pomlog(POMLOG_ERR "Error while creating new lua state for output %s", o->info->reg_info->name); return POM_ERR; } // Get the output from the outputs table lua_getfield(L, LUA_REGISTRYINDEX, ADDON_OUTPUTS_TABLE); // Stack : outputs lua_getfield(L, -1, o->info->reg_info->name); // Stack : outputs, output // Get rid of the outputs table lua_remove(L, -2); // Stack : output lua_pushnil(L); // Stack : output, nil lua_setfield(L, LUA_REGISTRYINDEX, ADDON_OUTPUTS_TABLE); // Stack : output // Add the output to the registry lua_pushvalue(L, -1); // Stack : output, output lua_setfield(L, LUA_REGISTRYINDEX, ADDON_INSTANCE); // Stack : output // Create the private data // TODO make __priv read-only struct addon_instance_priv *p = lua_newuserdata(L, sizeof(struct addon_instance_priv)); // Stack : output, priv if (!p) { pom_oom(sizeof(struct addon_instance_priv)); return POM_ERR; } memset(p, 0, sizeof(struct addon_instance_priv)); o->priv = p; p->instance = o; p->L = L; if (pthread_mutex_init(&p->lock, NULL)) { pomlog(POMLOG_ERR "Error while initializing mutex : %s", pom_strerror(errno)); abort(); return POM_ERR; } // Assign the output_priv metatable luaL_getmetatable(L, ADDON_OUTPUT_PRIV_METATABLE); // Stack : output, priv, metatable lua_setmetatable(L, -2); // Stack : output, priv // Add it to __priv lua_setfield(L, -2, "__priv"); // Stack : output // Fetch the parameters table lua_getfield(L, -1, "__params"); // Stack : output, params // Parse each param from the class lua_pushnil(L); // Stack : output, params, nil while (lua_next(L, -2) != 0) { // Stack : output, params, key, param if (!lua_istable(L, -1)) { pomlog(POMLOG_ERR "Parameters should be described in tables"); goto err; } // Fetch the name lua_pushinteger(L, 1); // Stack : output, params, key, param, 1 lua_gettable(L, -2); // Stack : output, params, key, param, name if (!lua_isstring(L, -1)) { pomlog(POMLOG_ERR "Parameter name is not a string"); goto err; } const char *name = luaL_checkstring(L, -1); lua_pop(L, 1); // Stack : output, params, key, param // Fetch the ptype type lua_pushinteger(L, 2); // Stack : output, params, key, param, 2 lua_gettable(L, -2); // Stack : output, params, key, param, type if (!lua_isstring(L, -1)) { pomlog(POMLOG_ERR "Parameter type is not a string"); goto err; } const char *type = lua_tostring(L, -1); lua_pop(L, 1); // Stack : output, params, key, param // Fetch the default value lua_pushinteger(L, 3); // Stack : output, params, key, param, 3 lua_gettable(L, -2); // Stack : output, params, key, param, defval if (!lua_isstring(L, -1)) { pomlog(POMLOG_ERR "Parameter default value is not a string"); goto err; } const char *defval = lua_tostring(L, -1); lua_pop(L, 1); // Stack : output, params, key, param // Fetch the description lua_pushinteger(L, 4); // Stack : output, params, key, param, 4 lua_gettable(L, -2); // Stack : output, params, key, param, descr if (!lua_isstring(L, -1)) { pomlog(POMLOG_ERR "Parameter description is not a string"); goto err; } const char *descr = lua_tostring(L, -1); lua_pop(L, 1); // Stack : output, params, key, param // Allocate it struct addon_param *param = malloc(sizeof(struct addon_param)); if (!param) { pom_oom(sizeof(struct addon_param)); goto err; } param->name = strdup(name); if (!param->name) { free(param); pom_oom(strlen(name) + 1); goto err; } param->value = ptype_alloc(type); if (!param->value) { free(param->name); free(param); goto err; } struct registry_param *reg_param = registry_new_param((char*)name, (char*)defval, param->value, (char*)descr, 0); if (output_add_param(o, reg_param) != POM_OK) { pomlog(POMLOG_ERR "Error while adding parameter to the output instance"); if (reg_param) registry_cleanup_param(reg_param); free(param->name); ptype_cleanup(param->value); free(param); goto err; } param->next = p->params; p->params = param; // Pop the value (the param table) lua_pop(L, 1); // Stack : output, params, key } // At this point the stack is : output, params lua_pop(L, 2); // Stack : empty pomlog(POMLOG_DEBUG "Output %s created", o->name); return POM_OK; err: lua_close(L); p->L = NULL; return POM_ERR; }
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(); // consoleInit(GFX_BOTTOM, NULL); 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. // 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 (soundEnabled) ndspExit(); if (romfsExists) romfsExit(); return 0; }
/** * Destructor for Plot */ Plot::~Plot() { /** Close the lua state */ lua_close(this->lua_state); }
// Initializes a lua chisel bool sinsp_chisel::init_lua_chisel(chisel_desc &cd, string const &fpath) { lua_State* ls = lua_open(); if(ls == NULL) { return false; } luaL_openlibs(ls); // // Load our own lua libs // luaL_openlib(ls, "sysdig", ll_sysdig, 0); luaL_openlib(ls, "chisel", ll_chisel, 0); luaL_openlib(ls, "evt", ll_evt, 0); // // Add our chisel paths to package.path // for(vector<chiseldir_info>::const_iterator it = g_chisel_dirs->begin(); it != g_chisel_dirs->end(); ++it) { string path(it->m_dir); path += "?.lua"; add_lua_package_path(ls, path.c_str()); } // // Load the script // if(luaL_loadfile(ls, fpath.c_str()) || lua_pcall(ls, 0, 0, 0)) { goto failure; } // // Extract the description // lua_getglobal(ls, "description"); if(!lua_isstring(ls, -1)) { return parse_view_info(ls, &cd); } cd.m_description = lua_tostring(ls, -1); // // Extract the short description // lua_getglobal(ls, "short_description"); if(!lua_isstring(ls, -1)) { goto failure; } cd.m_shortdesc = lua_tostring(ls, -1); // // Extract the category // cd.m_category = ""; lua_getglobal(ls, "category"); if(lua_isstring(ls, -1)) { cd.m_category = lua_tostring(ls, -1); } // // Extract the hidden flag and skip the chisel if it's set // lua_getglobal(ls, "hidden"); if(lua_isboolean(ls, -1)) { int sares = lua_toboolean(ls, -1); if(sares) { goto failure; } } // // Extract the args // lua_getglobal(ls, "args"); if(lua_isnoneornil(ls, -1)) { goto failure; } try { parse_lua_chisel_args(ls, &cd); } catch(...) { goto failure; } return true; failure: lua_close(ls); return false; }
//##ModelId=4A1E88FC0069 cls_ai::~cls_ai() { lua_close(L); }
void CapASM::Compile(const char * filename) { std::cout << "&Compilation of " << string(filename).c_str() << endl ; char buf[MAX_PATH]; int base_encoding; /* added */ char* p; int i = 1; CleanUP(); // init LUA LUA = lua_open(); lua_atpanic(LUA, (lua_CFunction)LuaFatalError); luaL_openlibs(LUA); luaopen_pack(LUA); tolua_sjasm_open(LUA); // init vars Options::DestionationFName[0] = 0; STRCPY( Options::ListingFName, LINEMAX, "/tmp/caprice.lst"); //TODO generate file name Options::UnrealLabelListFName[0] = 0; STRCPY( Options::SymbolListFName, LINEMAX, "/tmp/caprice.sym"); Options::ExportFName[0] = 0; Options::RAWFName[0] = 0; Options::NoDestinationFile = true; // not *.out files by default // start counter long dwStart; dwStart = GetTickCount(); // get current directory GetCurrentDirectory(MAX_PATH, buf); CurrentDirectory = buf; STRCPY(SourceFNames[SourceFNamesCount++], LINEMAX, filename); if (!SourceFNames[0][0]) { _COUT "No inputfile(s)" _ENDL; return; } if (!Options::DestionationFName[0]) { STRCPY(Options::DestionationFName, LINEMAX, SourceFNames[0]); if (!(p = strchr(Options::DestionationFName, '.'))) { p = Options::DestionationFName; } else { *p = 0; } STRCAT(p, LINEMAX-(p-Options::DestionationFName), ".out"); } // init some vars InitCPU(); // if memory type != none base_encoding = ConvertEncoding; // init first pass InitPass(1); // open lists OpenList(); // open source filenames for (i = 0; i < SourceFNamesCount; i++) { OpenFile(SourceFNames[i]); } _COUT "Pass 1 complete (" _CMDL ErrorCount _CMDL " errors)" _ENDL; ConvertEncoding = base_encoding; do { pass++; InitPass(pass); if (pass == LASTPASS) { OpenDest(); } for (i = 0; i < SourceFNamesCount; i++) { OpenFile(SourceFNames[i]); } if (PseudoORG) { CurAddress = adrdisp; PseudoORG = 0; } if (pass != LASTPASS) { _COUT "Pass " _CMDL pass _CMDL " complete (" _CMDL ErrorCount _CMDL " errors)" _ENDL; } else { _COUT "Pass 3 complete" _ENDL; } } while (pass < 3);//MAXPASSES); pass = 9999; /* added for detect end of compiling */ if (Options::AddLabelListing) { LabelTable.Dump(); } Close(); if (Options::UnrealLabelListFName[0]) { LabelTable.DumpForUnreal(); } if (Options::SymbolListFName[0]) { LabelTable.DumpSymbols(); } _COUT "Errors: " _CMDL ErrorCount _CMDL ", warnings: " _CMDL WarningCount _CMDL ", compiled: " _CMDL CompiledCurrentLine _CMDL " lines" _END; double dwCount; dwCount = GetTickCount() - dwStart; if (dwCount < 0) { dwCount = 0; } printf(", work time: %.3f seconds", dwCount / 1000); _COUT "" _ENDL; #ifndef UNDER_CE cout << flush; #endif // free RAM delete Devices; Devices = 0; // close Lua lua_close(LUA); //return (ErrorCount != 0); }
CLuaVM::~CLuaVM() { lua_close(m_pVM); m_pVM = NULL; }
Config::~Config() { lua_close(L); }
int main(int argc, char ** argv) { #ifdef LOVE_LEGENDARY_UTF8_ARGV_HACK int hack_argc = 0; char ** hack_argv = 0; get_utf8_arguments(hack_argc, hack_argv); argc = hack_argc; argv = hack_argv; #endif // LOVE_LEGENDARY_UTF8_ARGV_HACK // Oh, you just want the version? Okay! if (argc > 1 && strcmp(argv[1],"--version") == 0) { printf("LOVE %s (%s)\n", love::VERSION, love::VERSION_CODENAME); return 0; } // Create the virtual machine. lua_State * L = lua_open(); luaL_openlibs(L); love::luax_preload(L, luaopen_love, "love"); luaopen_love(L); // Add command line arguments to global arg (like stand-alone Lua). { lua_newtable(L); if (argc > 0) { lua_pushstring(L, argv[0]); lua_rawseti(L, -2, -2); } lua_pushstring(L, "embedded boot.lua"); lua_rawseti(L, -2, -1); for (int i = 1; i<argc; i++) { lua_pushstring(L, argv[i]); lua_rawseti(L, -2, i); } lua_setglobal(L, "arg"); } // Add love.__exe = true. // This indicates that we're running the // standalone version of love, and not the // DLL version. { lua_getglobal(L, "love"); lua_pushboolean(L, 1); lua_setfield(L, -2, "_exe"); lua_pop(L, 1); } // Boot if (luaL_loadbuffer(L, (const char *)love::boot_lua, sizeof(love::boot_lua), "boot.lua") == 0) lua_call(L, 0, 0); lua_close(L); #ifdef LOVE_LEGENDARY_UTF8_ARGV_HACK if (hack_argv) { for (int i = 0; i<hack_argc; ++i) delete [] hack_argv[i]; delete [] hack_argv; } #endif // LOVE_LEGENDARY_UTF8_ARGV_HACK return 0; }
void sipstate_close(void) { sipapi_delete_object(siplua_msg); lua_close(siplua_L); siplua_L = 0; }
int fini(void) { lua_close (L); return SLURM_SUCCESS; }
void ShipType::Init() { static bool isInitted = false; if (isInitted) return; isInitted = true; // load all ship definitions namespace fs = FileSystem; for (fs::FileEnumerator files(fs::gameDataFiles, "ships", fs::FileEnumerator::Recurse); !files.Finished(); files.Next()) { const fs::FileInfo &info = files.Current(); if (ends_with_ci(info.GetPath(), ".json")) { const std::string id(info.GetName().substr(0, info.GetName().size()-5)); ShipType st = ShipType(id, info.GetPath()); types.insert(std::make_pair(st.id, st)); // assign the names to the various lists switch( st.tag ) { case TAG_SHIP: player_ships.push_back(id); break; case TAG_STATIC_SHIP: static_ships.push_back(id); break; case TAG_MISSILE: missile_ships.push_back(id); break; break; case TAG_NONE: default: break; } } } #if ALLOW_LUA_SHIP_DEF lua_State *l = luaL_newstate(); LUA_DEBUG_START(l); luaL_requiref(l, "_G", &luaopen_base, 1); luaL_requiref(l, LUA_DBLIBNAME, &luaopen_debug, 1); luaL_requiref(l, LUA_MATHLIBNAME, &luaopen_math, 1); lua_pop(l, 3); LuaConstants::Register(l); LuaVector::Register(l); LUA_DEBUG_CHECK(l, 0); // provide shortcut vector constructor: v = vector.new lua_getglobal(l, LuaVector::LibName); lua_getfield(l, -1, "new"); assert(lua_iscfunction(l, -1)); lua_setglobal(l, "v"); lua_pop(l, 1); // pop the vector library table LUA_DEBUG_CHECK(l, 0); // register ship definition functions lua_register(l, "define_ship", define_ship); lua_register(l, "define_static_ship", define_static_ship); lua_register(l, "define_missile", define_missile); LUA_DEBUG_CHECK(l, 0); // load all ship definitions namespace fs = FileSystem; for (fs::FileEnumerator files(fs::gameDataFiles, "ships", fs::FileEnumerator::Recurse); !files.Finished(); files.Next()) { const fs::FileInfo &info = files.Current(); if (ends_with_ci(info.GetPath(), ".lua")) { const std::string name = info.GetName(); s_currentShipFile = name.substr(0, name.size() - 4); if (ShipType::types.find(s_currentShipFile) == ShipType::types.end()) { pi_lua_dofile(l, info.GetPath()); s_currentShipFile.clear(); } } } LUA_DEBUG_END(l, 0); lua_close(l); #endif //remove unbuyable ships from player ship list ShipType::player_ships.erase( std::remove_if(ShipType::player_ships.begin(), ShipType::player_ships.end(), ShipIsUnbuyable), ShipType::player_ships.end()); if (ShipType::player_ships.empty()) Error("No playable ships have been defined! The game cannot run."); }
static void drv_lazy_uninit(struct vf_instance *vf) { struct vf_priv_s *p = vf->priv; lua_close(p->ls); p->vsapi->freeCore(p->vscore); }
int weechat_lua_load (const char *filename) { FILE *fp; char *weechat_lua_code = { "weechat_outputs = {\n" " write = function (self, str)\n" " weechat.print(\"\", \"lua: stdout/stderr: \" .. str)\n" " end\n" "}\n" "io.stdout = weechat_outputs\n" "io.stderr = weechat_outputs\n" }; if ((fp = fopen (filename, "r")) == NULL) { weechat_printf (NULL, weechat_gettext ("%s%s: script \"%s\" not found"), weechat_prefix ("error"), LUA_PLUGIN_NAME, filename); return 0; } if ((weechat_lua_plugin->debug >= 2) || !lua_quiet) { weechat_printf (NULL, weechat_gettext ("%s: loading script \"%s\""), LUA_PLUGIN_NAME, filename); } lua_current_script = NULL; lua_registered_script = NULL; lua_current_interpreter = luaL_newstate(); if (lua_current_interpreter == NULL) { weechat_printf (NULL, weechat_gettext ("%s%s: unable to create new " "sub-interpreter"), weechat_prefix ("error"), LUA_PLUGIN_NAME); fclose (fp); return 0; } #ifdef LUA_VERSION_NUM /* LUA_VERSION_NUM is defined only in lua >= 5.1.0 */ luaL_openlibs (lua_current_interpreter); #else luaopen_base (lua_current_interpreter); luaopen_string (lua_current_interpreter); luaopen_table (lua_current_interpreter); luaopen_math (lua_current_interpreter); luaopen_io (lua_current_interpreter); luaopen_debug (lua_current_interpreter); #endif /* LUA_VERSION_NUM */ weechat_lua_register_lib (lua_current_interpreter, "weechat", weechat_lua_api_funcs, weechat_lua_api_consts); #ifdef LUA_VERSION_NUM if (luaL_dostring (lua_current_interpreter, weechat_lua_code) != 0) #else if (lua_dostring (lua_current_interpreter, weechat_lua_code) != 0) #endif /* LUA_VERSION_NUM */ { weechat_printf (NULL, weechat_gettext ("%s%s: unable to redirect stdout " "and stderr"), weechat_prefix ("error"), LUA_PLUGIN_NAME); } lua_current_script_filename = filename; if (luaL_loadfile (lua_current_interpreter, filename) != 0) { weechat_printf (NULL, weechat_gettext ("%s%s: unable to load file \"%s\""), weechat_prefix ("error"), LUA_PLUGIN_NAME, filename); weechat_printf (NULL, weechat_gettext ("%s%s: error: %s"), weechat_prefix ("error"), LUA_PLUGIN_NAME, lua_tostring (lua_current_interpreter, -1)); lua_close (lua_current_interpreter); fclose (fp); return 0; } if (lua_pcall (lua_current_interpreter, 0, 0, 0) != 0) { weechat_printf (NULL, weechat_gettext ("%s%s: unable to execute file " "\"%s\""), weechat_prefix ("error"), LUA_PLUGIN_NAME, filename); weechat_printf (NULL, weechat_gettext ("%s%s: error: %s"), weechat_prefix ("error"), LUA_PLUGIN_NAME, lua_tostring (lua_current_interpreter, -1)); lua_close (lua_current_interpreter); fclose (fp); /* if script was registered, remove it from list */ if (lua_current_script) { plugin_script_remove (weechat_lua_plugin, &lua_scripts, &last_lua_script, lua_current_script); lua_current_script = NULL; } return 0; } fclose (fp); if (!lua_registered_script) { weechat_printf (NULL, weechat_gettext ("%s%s: function \"register\" not " "found (or failed) in file \"%s\""), weechat_prefix ("error"), LUA_PLUGIN_NAME, filename); lua_close (lua_current_interpreter); return 0; } lua_current_script = lua_registered_script; /* * set input/close callbacks for buffers created by this script * (to restore callbacks after upgrade) */ plugin_script_set_buffer_callbacks (weechat_lua_plugin, lua_scripts, lua_current_script, &weechat_lua_api_buffer_input_data_cb, &weechat_lua_api_buffer_close_cb); (void) weechat_hook_signal_send ("lua_script_loaded", WEECHAT_HOOK_SIGNAL_STRING, lua_current_script->filename); return 1; }
void luaScriptEnd(lua_State *L) { if(L==NULL) return; lua_close(L); /* create state */ return; }
/* | The effective main for one run. | HUP signals may cause several runs of the one main. */ int main1( int argc, char *argv[] ) { // the Lua interpreter lua_State * L; // the runner file char * lsyncd_runner_file = NULL; int argp = 1; // load Lua L = luaL_newstate( ); luaL_openlibs( L ); { // checks the lua version const char * version; int major, minor; lua_getglobal( L, "_VERSION" ); version = luaL_checkstring( L, -1 ); if( sscanf( version, "Lua %d.%d", &major, &minor ) != 2 ) { fprintf( stderr, "cannot parse lua library version!\n" ); exit (-1 ); } if( major < 5 || (major == 5 && minor < 1) ) { fprintf( stderr, "Lua library is too old. Needs 5.1 at least" ); exit( -1 ); } lua_pop( L, 1 ); } { // logging is prepared quite early int i = 1; add_logcat( "Normal", LOG_NOTICE ); add_logcat( "Warn", LOG_WARNING ); add_logcat( "Error", LOG_ERR ); while( i < argc ) { if( strcmp( argv[ i ], "-log" ) && strcmp( argv[ i ], "--log" ) ) { // arg is neither -log or --log i++; continue; } if( ++i >= argc ) { // -(-)log was last argument break; } if( !add_logcat( argv[ i ], LOG_NOTICE ) ) { printlogf( L, "Error", "'%s' is not a valid logging category", argv[ i ] ); exit( -1 ); } } } // registers Lsycnd's core library register_lsyncd( L ); if( check_logcat( "Debug" ) <= settings.log_level ) { // printlogf doesnt support %ld :-( printf( "kernels clocks_per_sec=%ld\n", clocks_per_sec ); } // checks if the user overrode the default runner file if( argp < argc && !strcmp( argv[ argp ], "--runner" ) ) { if (argp + 1 >= argc) { logstring( "Error", "Lsyncd Lua-runner file missing after --runner " ); exit( -1 ); } lsyncd_runner_file = argv[ argp + 1 ]; argp += 2; } if( lsyncd_runner_file ) { // checks if the runner file exists struct stat st; if( stat( lsyncd_runner_file, &st ) ) { printlogf( L, "Error", "Cannot see a runner at '%s'.", lsyncd_runner_file ); exit( -1 ); } // loads the runner file if( luaL_loadfile(L, lsyncd_runner_file ) ) { printlogf( L, "Error", "error loading '%s': %s", lsyncd_runner_file, lua_tostring( L, -1 ) ); exit( -1 ); } } else { // loads the runner from binary if( luaL_loadbuffer( L, runner_out, runner_size, "runner" ) ) { printlogf( L, "Error", "error loading precompiled runner: %s", lua_tostring( L, -1 ) ); exit( -1 ); } } // prepares the runner executing the script { if( lua_pcall( L, 0, LUA_MULTRET, 0 ) ) { printlogf( L, "Error", "preparing runner: %s", lua_tostring( L, -1 ) ); exit( -1 ); } lua_pushlightuserdata( L, (void *) & runner ); // switches the value ( result of preparing ) and the key &runner lua_insert( L, 1 ); // saves the table of the runners functions in the lua registry lua_settable( L, LUA_REGISTRYINDEX ); // saves the error function extras // &callError is the key lua_pushlightuserdata ( L, (void *) &callError ); // &runner[ callError ] the value lua_pushlightuserdata ( L, (void *) &runner ); lua_gettable ( L, LUA_REGISTRYINDEX ); lua_pushstring ( L, "callError" ); lua_gettable ( L, -2 ); lua_remove ( L, -2 ); lua_settable ( L, LUA_REGISTRYINDEX ); } // asserts the Lsyncd's version matches // between runner and core { const char *lversion; lua_getglobal( L, "lsyncd_version" ); lversion = luaL_checkstring( L, -1 ); if( strcmp( lversion, PACKAGE_VERSION ) ) { printlogf( L, "Error", "Version mismatch '%s' is '%s', but core is '%s'", lsyncd_runner_file ? lsyncd_runner_file : "( internal runner )", lversion, PACKAGE_VERSION ); exit( -1 ); } lua_pop( L, 1 ); } // loads the defaults from binary { if( luaL_loadbuffer( L, defaults_out, defaults_size, "defaults" ) ) { printlogf( L, "Error", "loading defaults: %s", lua_tostring( L, -1 ) ); exit( -1 ); } // prepares the defaults if (lua_pcall( L, 0, 0, 0 ) ) { printlogf( L, "Error", "preparing defaults: %s", lua_tostring( L, -1 ) ); exit( -1 ); } } // checks if there is a "-help" or "--help" { int i; for( i = argp; i < argc; i++ ) { if ( !strcmp( argv[ i ], "-help" ) || !strcmp( argv[ i ], "--help" ) ) { load_runner_func(L, "help"); if (lua_pcall(L, 0, 0, -2)) { exit( -1 ); } lua_pop( L, 1 ); exit( 0 ); } } } // starts the option parser in Lua script { int idx = 1; const char *s; // creates a table with all remaining argv option arguments load_runner_func( L, "configure" ); lua_newtable( L ); while( argp < argc ) { lua_pushnumber ( L, idx++ ); lua_pushstring ( L, argv[ argp++ ] ); lua_settable ( L, -3 ); } // creates a table with the cores event monitor interfaces idx = 0; lua_newtable( L ); while( monitors[ idx ] ) { lua_pushnumber ( L, idx + 1 ); lua_pushstring ( L, monitors[ idx++ ] ); lua_settable ( L, -3 ); } if( lua_pcall( L, 2, 1, -4 ) ) { exit( -1 ); } if( first_time ) { // If not first time, simply retains the config file given s = lua_tostring(L, -1); if( s ) { lsyncd_config_file = s_strdup( s ); } } lua_pop( L, 2 ); } // checks existence of the config file if( lsyncd_config_file ) { struct stat st; // gets the absolute path to the config file // so in case of HUPing the daemon, it finds it again char * apath = get_realpath( lsyncd_config_file ); if( !apath ) { printlogf( L, "Error", "Cannot find config file at '%s'.", lsyncd_config_file ); exit( -1 ); } free( lsyncd_config_file ); lsyncd_config_file = apath; if( stat( lsyncd_config_file, &st ) ) { printlogf( L, "Error", "Cannot find config file at '%s'.", lsyncd_config_file ); exit( -1 ); } // loads and executes the config file if( luaL_loadfile( L, lsyncd_config_file ) ) { printlogf( L, "Error", "error loading %s: %s", lsyncd_config_file, lua_tostring( L, -1 ) ); exit( -1 ); } if( lua_pcall( L, 0, LUA_MULTRET, 0) ) { printlogf( L, "Error", "error preparing %s: %s", lsyncd_config_file, lua_tostring( L, -1 ) ); exit( -1 ); } } #ifdef LSYNCD_WITH_INOTIFY open_inotify( L ); #endif #ifdef LSYNCD_WITH_FSEVENTS open_fsevents( L ); #endif // adds signal handlers // listens to SIGCHLD, but blocks it until pselect( ) // opens the signal handler up { sigset_t set; sigemptyset( &set ); sigaddset( &set, SIGCHLD ); signal( SIGCHLD, sig_child ); sigprocmask( SIG_BLOCK, &set, NULL ); signal( SIGHUP, sig_handler ); signal( SIGTERM, sig_handler ); } // runs initializations from runner // it will set the configuration and add watches { load_runner_func( L, "initialize" ); lua_pushboolean( L, first_time ); if( lua_pcall( L, 1, 0, -3 ) ) { exit( -1 ); } lua_pop( L, 1 ); } // // enters the master loop // masterloop( L ); // // cleanup // // tidies up all observances { int i; for( i = 0; i < observances_len; i++ ) { struct observance *obs = observances + i; obs->tidy( obs ); } observances_len = 0; nonobservances_len = 0; } // frees logging categories { int ci; struct logcat *lc; for( ci = 'A'; ci <= 'Z'; ci++ ) { for( lc = logcats[ ci - 'A' ]; lc && lc->name; lc++) { free( lc->name ); lc->name = NULL; } if( logcats[ci - 'A' ] ) { free( logcats[ ci - 'A' ] ); logcats[ ci - 'A' ] = NULL; } } } lua_close( L ); return 0; }
int main(int argc, char *argv[]) { int i,ii; lua_State *L; L = lua_open(); luaopen_base(L); /* opens the basic library */ luaopen_table(L); /* opens the table library */ luaopen_string(L); /* opens the string lib. */ luaopen_math(L); /* opens the math lib. */ lua_pop(L,5); static const luaL_reg EventNet_meta[] = { {"__gc", Bla_gc}, {"__tostring", Bla_tostring}, {0, 0} }; static const luaL_Reg RegisterEventNet[] = { {"new", BlaNew}, {"sleep", BlaSleep}, {"bla", BlaBla}, {NULL, NULL} }; luaL_openlib(L, "Bla", RegisterEventNet, 0); luaL_newmetatable(L, "Bla"); luaL_openlib(L, 0, EventNet_meta, 0); lua_pushliteral(L, "__index"); lua_pushvalue(L, -3); lua_rawset(L, -3); lua_pushliteral(L, "__metatable"); lua_pushvalue(L, -3); lua_rawset(L, -3); lua_pop(L, 2); luaL_loadstring(L,"function main() local bla=Bla:new() bla:sleep() bla:bla() end"); int count=0; lua_pcall(L,0,0,0); printf("Memory used = %d\n",lua_gc(L, LUA_GCCOUNT, 0)); for(i=0;i<1;i++) { for(ii=0;ii<=len;ii++) { count++; snprintf(bla[ii].bla,50,"bla%d",ii); bla[ii].thread = lua_newthread(L); bla[ii].table = luaL_ref (L,LUA_REGISTRYINDEX); lua_pushthread(bla[ii].thread); lua_pushlightuserdata(bla[ii].thread,(void*) &bla[ii]); lua_settable(bla[ii].thread, LUA_REGISTRYINDEX); lua_getglobal(bla[ii].thread, "main"); lua_resume(bla[ii].thread, 0); // printf("init %s %p\n",bla[ii].bla,bla[ii].thread); } for(ii=0;ii<=len;ii++) { lua_resume(bla[ii].thread, 0); // printf("in c bla[%d] = %p and bla string is %s\n\n",ii,bla[ii].thread,bla[ii].bla); lua_pushthread(bla[ii].thread); lua_pushnil(bla[ii].thread); lua_settable(bla[ii].thread, LUA_REGISTRYINDEX); luaL_unref(L, LUA_REGISTRYINDEX, bla[ii].table ); } } printf("Memory used = %d, cycle %d\n",lua_gc(L, LUA_GCCOUNT, 0),count); lua_gc(L, LUA_GCCOLLECT, 0); printf("Memory used = %d, cycle %d\n",lua_gc(L, LUA_GCCOUNT, 0),count); lua_close(L); return 0; }
/* * Arguments: filename (string) | function_dump (string), * [arguments (string | number | boolean | lightuserdata) ...] * Returns: [thread_ludata] */ static int thread_runvm (lua_State *L) { const char *path = luaL_checkstring(L, 1); lua_State *NL = NULL; struct sys_vmthread *vmtd = (struct sys_vmthread *) sys_get_thread(); #ifndef _WIN32 pthread_attr_t attr; #else HANDLE hThr; #endif int res = 0; if (!vmtd) luaL_argerror(L, 0, "Threading not initialized"); NL = luaL_newstate(); if (!NL) goto err; thread_openlibs(NL); if (path[0] == LUA_SIGNATURE[0] ? luaL_loadbuffer(NL, path, lua_rawlen(L, 1), "thread") : luaL_loadfile(NL, path)) { lua_pushstring(L, lua_tostring(NL, -1)); /* error message */ lua_close(NL); lua_error(L); } /* Arguments */ lua_pushlightuserdata(NL, vmtd); /* master */ { int i, top = lua_gettop(L); for (i = 2; i <= top; ++i) { switch (lua_type(L, i)) { case LUA_TSTRING: lua_pushstring(NL, lua_tostring(L, i)); break; case LUA_TNUMBER: lua_pushnumber(NL, lua_tonumber(L, i)); break; case LUA_TBOOLEAN: lua_pushboolean(NL, lua_toboolean(L, i)); break; case LUA_TLIGHTUSERDATA: case LUA_TUSERDATA: lua_pushlightuserdata(NL, lua_touserdata(L, i)); break; default: luaL_argerror(L, i, "primitive type expected"); } } } if (vmthread_new(NL, &vmtd)) goto err_clean; #ifndef _WIN32 res = pthread_attr_init(&attr); if (res) goto err_clean; pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); res = pthread_create(&vmtd->td.tid, &attr, (thread_func_t) thread_startvm, vmtd); pthread_attr_destroy(&attr); if (!res) { #else hThr = (HANDLE) _beginthreadex(NULL, 0, (thread_func_t) thread_startvm, vmtd, 0, &vmtd->td.tid); if (hThr) { CloseHandle(hThr); #endif lua_pushlightuserdata(L, vmtd); return 1; } err_clean: lua_close(NL); err: return sys_seterror(L, res); } /* * Arguments: thread_ludata */ static int thread_interrupt (lua_State *L) { struct sys_thread *td = lua_touserdata(L, 1); td->interrupted = 1; #ifndef _WIN32 pthread_kill(td->tid, SYS_SIGINTR); #endif return 0; } static int thread_yield (lua_State *L) { (void) L; sys_vm_leave(); #ifndef _WIN32 sched_yield(); #else Sleep(0); #endif sys_vm_enter(); return 0; }