// Module setup stuff DWORD WINAPI Init(LPVOID args) { if (!InitTorqueStuff()) return 0; lua_State *L = luaL_newstate(); gL = L; if (L == NULL) { Printf("Failed to initialize Lua"); return 1; } luaL_openlibs(L); // set up ts_object metatable luaL_newmetatable(L, "ts_object_mt"); lua_pushstring(L, "__index"); lua_pushcfunction(L, lu_ts_obj_index); lua_rawset(L, -3); lua_pushstring(L, "__newindex"); lua_pushcfunction(L, lu_ts_obj_newindex); lua_rawset(L, -3); lua_pop(L, -1); // set up global functions lua_pushcfunction(L, lu_print); lua_setglobal(L, "print"); lua_newtable(L); lua_pushstring(L, "eval"); lua_pushcfunction(L, lu_ts_eval); lua_rawset(L, -3); lua_pushstring(L, "func"); lua_pushcfunction(L, lu_ts_func); lua_rawset(L, -3); lua_pushstring(L, "obj"); lua_pushcfunction(L, lu_ts_obj); lua_rawset(L, -3); lua_pushstring(L, "grab"); lua_pushstring(L, "obj"); lua_rawget(L, -3); lua_rawset(L, -3); // set up ts.global get/set lua_pushstring(L, "global"); lua_newtable(L); lua_newtable(L); lua_pushstring(L, "__index"); lua_pushcfunction(L, lu_ts_global_index); lua_rawset(L, -3); lua_pushstring(L, "__newindex"); lua_pushcfunction(L, lu_ts_global_newindex); lua_rawset(L, -3); lua_setmetatable(L, -2); lua_rawset(L, -3); lua_setglobal(L, "ts"); // set up the con table runlua(L, R"lua( local func = ts.func _G.con = setmetatable({}, { __index = function(t, k) local f = func("", k) t[k] = function(...) return f(nil, ...) end return t[k] end }) )lua"); ConsoleFunction(NULL, "luaEval", ts_luaEval, "luaEval(string code, bool silent=false) - Execute a chunk of code as Lua.", 2, 3); ConsoleFunction(NULL, "luaExec", ts_luaExec, "luaExec(string filename, bool silent=false) - Execute a Lua code file.", 2, 3); ConsoleFunction(NULL, "luaCall", ts_luaCall, "luaCall(string name, ...) - Call a Lua function.", 2, 20); Printf("Lua DLL loaded"); Sleep(100); //runlua(L, "pcall(function()require('autorun')end)"); Eval("$luaLoaded=true;if(isFunction(\"onLuaLoaded\"))onLuaLoaded();"); return 0; }
/** * @brief load_conf load the conf of zimg * * @param conf conf name * * @return 1 for OK and -1 for fail */ static int load_conf(const char *conf) { lua_State *L = luaL_newstate(); luaL_openlibs(L); if (luaL_loadfile(L, conf) || lua_pcall(L, 0, 0, 0)) { lua_close(L); return -1; } lua_getglobal(L, "is_daemon"); //stack index: -12 if (lua_isnumber(L, -1)) settings.is_daemon = (int)lua_tonumber(L, -1); lua_pop(L, 1); lua_getglobal(L, "ip"); if (lua_isstring(L, -1)) str_lcpy(settings.ip, lua_tostring(L, -1), sizeof(settings.ip)); lua_pop(L, 1); lua_getglobal(L, "port"); if (lua_isnumber(L, -1)) settings.port = (int)lua_tonumber(L, -1); lua_pop(L, 1); lua_getglobal(L, "thread_num"); if (lua_isnumber(L, -1)) settings.num_threads = (int)lua_tonumber(L, -1); /* N workers */ lua_pop(L, 1); lua_getglobal(L, "backlog_num"); if (lua_isnumber(L, -1)) settings.backlog = (int)lua_tonumber(L, -1); lua_pop(L, 1); lua_getglobal(L, "max_keepalives"); if (lua_isnumber(L, -1)) settings.max_keepalives = (int)lua_tonumber(L, -1); lua_pop(L, 1); lua_getglobal(L, "retry"); if (lua_isnumber(L, -1)) settings.retry = (int)lua_tonumber(L, -1); lua_pop(L, 1); lua_getglobal(L, "system"); if (lua_isstring(L, -1)) { char tmp[128]; snprintf(tmp, 128, "%s %s", settings.server_name, lua_tostring(L, -1)); snprintf(settings.server_name, 128, "%s", tmp); } lua_pop(L, 1); lua_getglobal(L, "headers"); if (lua_isstring(L, -1)) { settings.headers = conf_get_headers(lua_tostring(L, -1)); } lua_pop(L, 1); lua_getglobal(L, "etag"); if (lua_isnumber(L, -1)) settings.etag = (int)lua_tonumber(L, -1); lua_pop(L, 1); lua_getglobal(L, "upload_rule"); if (lua_isstring(L, -1)) { settings.up_access = conf_get_rules(lua_tostring(L, -1)); } lua_pop(L, 1); lua_getglobal(L, "download_rule"); if (lua_isstring(L, -1)) { settings.down_access = conf_get_rules(lua_tostring(L, -1)); } lua_pop(L, 1); lua_getglobal(L, "admin_rule"); if (lua_isstring(L, -1)) { settings.admin_access = conf_get_rules(lua_tostring(L, -1)); } lua_pop(L, 1); lua_getglobal(L, "cache"); if (lua_isnumber(L, -1)) settings.cache_on = (int)lua_tonumber(L, -1); lua_pop(L, 1); lua_getglobal(L, "mc_ip"); if (lua_isstring(L, -1)) str_lcpy(settings.cache_ip, lua_tostring(L, -1), sizeof(settings.cache_ip)); lua_pop(L, 1); lua_getglobal(L, "mc_port"); if (lua_isnumber(L, -1)) settings.cache_port = (int)lua_tonumber(L, -1); lua_pop(L, 1); lua_getglobal(L, "log_level"); if (lua_isnumber(L, -1)) settings.log_level = (int)lua_tonumber(L, -1); lua_pop(L, 1); lua_getglobal(L, "log_name"); //stack index: -1 if (lua_isstring(L, -1)) str_lcpy(settings.log_name, lua_tostring(L, -1), sizeof(settings.log_name)); lua_pop(L, 1); lua_getglobal(L, "root_path"); if (lua_isstring(L, -1)) str_lcpy(settings.root_path, lua_tostring(L, -1), sizeof(settings.root_path)); lua_pop(L, 1); lua_getglobal(L, "admin_path"); if (lua_isstring(L, -1)) str_lcpy(settings.admin_path, lua_tostring(L, -1), sizeof(settings.admin_path)); lua_pop(L, 1); lua_getglobal(L, "disable_args"); if (lua_isnumber(L, -1)) settings.disable_args = (int)lua_tonumber(L, -1); lua_pop(L, 1); lua_getglobal(L, "disable_type"); if (lua_isnumber(L, -1)) settings.disable_type = (int)lua_tonumber(L, -1); lua_pop(L, 1); lua_getglobal(L, "disable_zoom_up"); if (lua_isnumber(L, -1)) settings.disable_zoom_up = (int)lua_tonumber(L, -1); lua_pop(L, 1); lua_getglobal(L, "script_name"); //stack index: -1 if (lua_isstring(L, -1)) str_lcpy(settings.script_name, lua_tostring(L, -1), sizeof(settings.script_name)); lua_pop(L, 1); lua_getglobal(L, "format"); if (lua_isstring(L, -1)) str_lcpy(settings.format, lua_tostring(L, -1), sizeof(settings.format)); lua_pop(L, 1); lua_getglobal(L, "quality"); if (lua_isnumber(L, -1)) settings.quality = (int)lua_tonumber(L, -1); lua_pop(L, 1); lua_getglobal(L, "mode"); if (lua_isnumber(L, -1)) settings.mode = (int)lua_tonumber(L, -1); lua_pop(L, 1); set_callback(settings.mode); lua_getglobal(L, "save_new"); if (lua_isnumber(L, -1)) settings.save_new = (int)lua_tonumber(L, -1); lua_pop(L, 1); lua_getglobal(L, "max_size"); if (lua_isnumber(L, -1)) settings.max_size = (int)lua_tonumber(L, -1); lua_pop(L, 1); lua_getglobal(L, "img_path"); if (lua_isstring(L, -1)) str_lcpy(settings.img_path, lua_tostring(L, -1), sizeof(settings.img_path)); lua_pop(L, 1); lua_getglobal(L, "beansdb_ip"); if (lua_isstring(L, -1)) str_lcpy(settings.beansdb_ip, lua_tostring(L, -1), sizeof(settings.beansdb_ip)); lua_pop(L, 1); lua_getglobal(L, "beansdb_port"); if (lua_isnumber(L, -1)) settings.beansdb_port = (int)lua_tonumber(L, -1); lua_pop(L, 1); lua_getglobal(L, "ssdb_ip"); if (lua_isstring(L, -1)) str_lcpy(settings.ssdb_ip, lua_tostring(L, -1), sizeof(settings.ssdb_ip)); lua_pop(L, 1); lua_getglobal(L, "ssdb_port"); if (lua_isnumber(L, -1)) settings.ssdb_port = (int)lua_tonumber(L, -1); lua_pop(L, 1); //settings.L = L; lua_close(L); return 1; }
LuaScript::LuaScript( char *name, char *path ) : Resource< LuaScript >( name, path ) { L = lua_open(); luaL_openlibs( L ); }
void CLuaFile::Init(const char *pFile) { //close first Close(); str_copy(m_aFilename, pFile, sizeof(m_aFilename)); m_pLua = luaL_newstate(); dbg_msg("lua", "%i kiB (loaded state)", lua_gc(m_pLua, LUA_GCCOUNT, 0)); luaL_openlibs(m_pLua); dbg_msg("lua", "%i kiB (loaded libs)", lua_gc(m_pLua, LUA_GCCOUNT, 0)); lua_atpanic(m_pLua, &Panic); //include lua_register(m_pLua, ToLower("Include"), this->Include); luaL_dostring(m_pLua, "package.path = \"./lua/?.lua;./lua/lib/?.lua\"\n"); //config lua_register(m_pLua, ToLower("SetScriptUseSettingPage"), this->SetScriptUseSettingPage); lua_register(m_pLua, ToLower("SetScriptTitle"), this->SetScriptTitle); lua_register(m_pLua, ToLower("SetScriptInfo"), this->SetScriptInfo); //events lua_register(m_pLua, ToLower("AddEventListener"), this->AddEventListener); lua_register(m_pLua, ToLower("RemoveEventListener"), this->RemoveEventListener); //player lua_register(m_pLua, ToLower("GetPlayerIP"), this->GetPlayerIP); lua_register(m_pLua, ToLower("GetPlayerSpectateID"), this->GetPlayerSpectateID); lua_register(m_pLua, ToLower("GetPlayerName"), this->GetPlayerName); lua_register(m_pLua, ToLower("GetPlayerClan"), this->GetPlayerClan); lua_register(m_pLua, ToLower("GetPlayerCountry"), this->GetPlayerCountry); lua_register(m_pLua, ToLower("GetPlayerScore"), this->GetPlayerScore); lua_register(m_pLua, ToLower("GetPlayerPing"), this->GetPlayerPing); lua_register(m_pLua, ToLower("GetPlayerTeam"), this->GetPlayerTeam); lua_register(m_pLua, ToLower("GetPlayerSkin"), this->GetPlayerSkin); lua_register(m_pLua, ToLower("GetPlayerColorFeet"), this->GetPlayerColorFeet); lua_register(m_pLua, ToLower("GetPlayerColorBody"), this->GetPlayerColorBody); lua_register(m_pLua, ToLower("SetPlayerScore"), this->SetPlayerScore); lua_register(m_pLua, ToLower("SetPlayerName"), this->SetPlayerName); lua_register(m_pLua, ToLower("SetPlayerTeam"), this->SetPlayerTeam); lua_register(m_pLua, ToLower("SetPlayerClan"), this->SetPlayerClan); lua_register(m_pLua, ToLower("SetPlayerCountry"), this->SetPlayerCountry); lua_register(m_pLua, ToLower("SetPlayerSpectateID"), this->SetPlayerSpectateID); lua_register(m_pLua, ToLower("SetPlayerColorBody"), this->SetPlayerColorBody); lua_register(m_pLua, ToLower("SetPlayerColorFeet"), this->SetPlayerColorFeet); //character lua_register(m_pLua, ToLower("Emote"), this->Emote); lua_register(m_pLua, ToLower("GetCharacterPos"), this->GetCharacterPos); lua_register(m_pLua, ToLower("GetCharacterVel"), this->GetCharacterVel); lua_register(m_pLua, ToLower("SetCharacterPos"), this->SetCharacterPos); lua_register(m_pLua, ToLower("SetCharacterVel"), this->SetCharacterVel); //config lua_register(m_pLua, ToLower("GetConfigValue"), this->GetConfigValue); lua_register(m_pLua, ToLower("SetConfigValue"), this->SetConfigValue); //console lua_register(m_pLua, ToLower("Print"), this->Print); lua_register(m_pLua, ToLower("Console"), this->Console); //game lua_register(m_pLua, ToLower("GetGameType"), this->GetGameType); lua_register(m_pLua, ToLower("IsTeamplay"), this->IsTeamplay); //message // lua_register(m_pLua, ToLower("GetNetError"), this->GetNetError); lua_register(m_pLua, ToLower("SendPacket"), this->SendPacket); lua_register(m_pLua, ToLower("AddModFile"), this->AddModFile); lua_register(m_pLua, ToLower("DeleteModFile"), this->DeleteModFile); lua_register(m_pLua, ToLower("SendFile"), this->SendFile); //collision lua_register(m_pLua, ToLower("IntersectLine"), this->IntersectLine); lua_register(m_pLua, ToLower("GetTile"), this->GetTile); lua_register(m_pLua, ToLower("SetTile"), this->SetTile); lua_register(m_pLua, ToLower("GetMapWidth"), this->GetMapWidth); lua_register(m_pLua, ToLower("GetMapHeight"), this->GetMapHeight); //Chat lua_register(m_pLua, ToLower("SendBroadcast"), this->SendBroadcast); lua_register(m_pLua, ToLower("SendChat"), this->SendChat); lua_register(m_pLua, ToLower("SendChatTarget"), this->SendChatTarget); //Entities lua_register(m_pLua, ToLower("EntityFind"), this->EntityFind); lua_register(m_pLua, ToLower("EntityGetCharacterId"), this->EntityGetCharacterId); lua_register(m_pLua, ToLower("EntityGetPos"), this->EntityGetPos); lua_register(m_pLua, ToLower("EntitySetPos"), this->EntitySetPos); lua_register(m_pLua, ToLower("EntityDestroy"), this->EntityDestroy); lua_register(m_pLua, ToLower("ProjectileFind"), this->ProjectileFind); lua_register(m_pLua, ToLower("ProjectileGetWeapon"), this->ProjectileGetWeapon); lua_register(m_pLua, ToLower("ProjectileGetOwner"), this->ProjectileGetOwner); lua_register(m_pLua, ToLower("ProjectileGetPos"), this->ProjectileGetPos); lua_register(m_pLua, ToLower("ProjectileGetDir"), this->ProjectileGetDir); lua_register(m_pLua, ToLower("ProjectileGetLifespan"), this->ProjectileGetLifespan); lua_register(m_pLua, ToLower("ProjectileGetExplosive"), this->ProjectileGetExplosive); lua_register(m_pLua, ToLower("ProjectileGetSoundImpact"), this->ProjectileGetSoundImpact); lua_register(m_pLua, ToLower("ProjectileGetStartTick"), this->ProjectileGetStartTick); lua_register(m_pLua, ToLower("ProjectileSetWeapon"), this->ProjectileSetWeapon); lua_register(m_pLua, ToLower("ProjectileSetOwner"), this->ProjectileSetOwner); lua_register(m_pLua, ToLower("ProjectileSetStartPos"), this->ProjectileSetStartPos); lua_register(m_pLua, ToLower("ProjectileSetDir"), this->ProjectileSetDir); lua_register(m_pLua, ToLower("ProjectileSetLifespan"), this->ProjectileSetLifespan); lua_register(m_pLua, ToLower("ProjectileSetExplosive"), this->ProjectileSetExplosive); lua_register(m_pLua, ToLower("ProjectileSetSoundImpact"), this->ProjectileSetSoundImpact); lua_register(m_pLua, ToLower("ProjectileSetStartTick"), this->ProjectileSetStartTick); lua_register(m_pLua, ToLower("ProjectileCreate"), this->ProjectileCreate); lua_register(m_pLua, ToLower("LaserCreate"), this->LaserCreate); //game lua_register(m_pLua, ToLower("CreateExplosion"), this->CreateExplosion); lua_register(m_pLua, ToLower("CreateDeath"), this->CreateDeath); lua_register(m_pLua, ToLower("CreateDamageIndicator"), this->CreateDamageIndicator); lua_register(m_pLua, ToLower("CreateHammerHit"), this->CreateHammerHit); lua_register(m_pLua, ToLower("CreateSound"), this->CreateSound); //tunings lua_register(m_pLua, ToLower("GetTuning"), this->GetTuning); lua_register(m_pLua, ToLower("SetTuning"), this->SetTuning); lua_register(m_pLua, ToLower("CharacterSetInputDirection"), this->CharacterSetInputDirection); lua_register(m_pLua, ToLower("CharacterSetInputJump"), this->CharacterSetInputJump); lua_register(m_pLua, ToLower("CharacterSetInputWeapon"), this->CharacterSetInputWeapon); lua_register(m_pLua, ToLower("CharacterSetInputTarget"), this->CharacterSetInputTarget); lua_register(m_pLua, ToLower("CharacterSetInputHook"), this->CharacterSetInputHook); lua_register(m_pLua, ToLower("CharacterSetInputFire"), this->CharacterSetInputFire); lua_register(m_pLua, ToLower("CharacterGetCoreJumped"), this->CharacterGetCoreJumped); lua_register(m_pLua, ToLower("CharacterSpawn"), this->CharacterSpawn); lua_register(m_pLua, ToLower("CharacterIsAlive"), this->CharacterIsAlive); lua_register(m_pLua, ToLower("CharacterKill"), this->CharacterKill); lua_register(m_pLua, ToLower("CharacterIsGrounded"), this->CharacterIsGrounded); lua_register(m_pLua, ToLower("CharacterIncreaseHealth"), this->CharacterIncreaseHealth); lua_register(m_pLua, ToLower("CharacterIncreaseArmor"), this->CharacterIncreaseArmor); lua_register(m_pLua, ToLower("CharacterSetAmmo"), this->CharacterSetAmmo); lua_register(m_pLua, ToLower("CharacterGetAmmo"), this->CharacterGetAmmo); lua_register(m_pLua, ToLower("CharacterGetInputTarget"), this->CharacterGetInputTarget); lua_register(m_pLua, ToLower("CharacterGetActiveWeapon"), this->CharacterGetActiveWeapon); lua_register(m_pLua, ToLower("CharacterSetActiveWeapon"), this->CharacterSetActiveWeapon); lua_register(m_pLua, ToLower("CharacterDirectInput"), this->CharacterDirectInput); lua_register(m_pLua, ToLower("CharacterPredictedInput"), this->CharacterPredictedInput); lua_register(m_pLua, ToLower("CharacterGetHealth"), this->CharacterGetHealth); lua_register(m_pLua, ToLower("CharacterGetArmor"), this->CharacterGetArmor); lua_register(m_pLua, ToLower("CharacterSetHealth"), this->CharacterSetHealth); lua_register(m_pLua, ToLower("CharacterSetArmor"), this->CharacterSetArmor); lua_register(m_pLua, ToLower("CharacterTakeDamage"), this->CharacterTakeDamage); lua_register(m_pLua, ToLower("SendCharacterInfo"), this->SendCharacterInfo); lua_register(m_pLua, ToLower("SetAutoRespawn"), this->SetAutoRespawn); lua_register(m_pLua, ToLower("Win"), this->Win); lua_register(m_pLua, ToLower("SetGametype"), this->SetGametype); lua_register(m_pLua, ToLower("DummyCreate"), this->DummyCreate); lua_register(m_pLua, ToLower("IsDummy"), this->IsDummy); //version lua_register(m_pLua, ToLower("CheckVersion"), this->CheckVersion); lua_register(m_pLua, ToLower("GetVersion"), this->GetVersion); lua_register(m_pLua, ToLower("CreateDirectory"), this->CreateDirectory); lua_register(m_pLua, ToLower("GetDate"), this->GetDate); lua_register(m_pLua, ToLower("GetTick"), this->GetTick); lua_register(m_pLua, ToLower("GetTickSpeed"), this->GetTickSpeed); //MySQL - Yeah lua_register(m_pLua, ToLower("MySQLConnect"), this->MySQLConnect); lua_register(m_pLua, ToLower("MySQLEscapeString"), this->MySQLEscapeString); lua_register(m_pLua, ToLower("MySQLSelectDatabase"), this->MySQLSelectDatabase); lua_register(m_pLua, ToLower("MySQLIsConnected"), this->MySQLIsConnected); lua_register(m_pLua, ToLower("MySQLQuery"), this->MySQLQuery); lua_register(m_pLua, ToLower("MySQLClose"), this->MySQLClose); lua_register(m_pLua, ToLower("MySQLFetchResults"), this->MySQLFetchResults); m_pLuaShared = new CLuaShared<CLuaFile>(this); lua_pushlightuserdata(m_pLua, this); lua_setglobal(m_pLua, "pLUA"); lua_register(m_pLua, ToLower("errorfunc"), this->ErrorFunc); dbg_msg("lua", "%i kiB (loaded fx)", lua_gc(m_pLua, LUA_GCCOUNT, 0)); if (luaL_loadfile(m_pLua, m_aFilename) == 0) { lua_pcall(m_pLua, 0, LUA_MULTRET, 0); ErrorFunc(m_pLua); dbg_msg("lua", "%i kiB (loaded file)", lua_gc(m_pLua, LUA_GCCOUNT, 0)); } else { ErrorFunc(m_pLua); dbg_msg("lua", "fail to load file: %s", pFile); Close(); return; } }
void lua_player::run_global_scope() { QObject::disconnect(this, SIGNAL (started ())); luaL_openlibs(L); luabind::open(L); luabind::module(L, "ghtv") [ luabind::class_<lua_player>("lua_player") ]; init_sandbox(); init_canvas(); init_event(); start_time = boost::posix_time::microsec_clock::universal_time(); QObject::connect(this, SIGNAL(resume_current_frame_signal (int)), this , SLOT(resume_current_frame (int)), Qt::QueuedConnection); QObject::connect(this, SIGNAL(run_require_signal (std::string)), this , SLOT(run_require_slot (std::string)), Qt::QueuedConnection); try { main_file_url = player::create_url(path, root_path); lua_path = main_file_url.path ().toStdString (); { std::string::reverse_iterator iterator = std::find(lua_path.rbegin(), lua_path.rend(), '/') , iterator_backslash = std::find(lua_path.rbegin(), lua_path.rend(), '\\'); iterator = (std::min)(iterator, iterator_backslash); if(iterator != lua_path.rend()) lua_path.erase(boost::prior(iterator.base()), lua_path.end()); else { std::string error_msg = "Couldn't create a absolute path from the path for the NCL file: "; error_msg += lua_path; ncl_window->error_occurred(error_msg); return; } } activate_frame(path, main_file_url.toString ().toStdString ()); QObject::connect(current_activation_frame (), SIGNAL(execution_finished ()) , this, SLOT(global_scope_finished ())); QObject::connect(this, SIGNAL(signal_all_execution_finished ()) , this, SLOT(try_unqueue_events ()), Qt::QueuedConnection); QObject::connect(this, SIGNAL(signal_try_unqueue_event ()) , this, SLOT(try_unqueue_event ()), Qt::QueuedConnection); assert(pending_download_file == 0); pending_download_file = new player::url_file(main_file_url, this); if(!pending_download_file->local()) { QObject::connect(this, SIGNAL(download_lua_signal ()), this , SLOT(download_global ()), Qt::QueuedConnection); QObject::connect(pending_download_file, SIGNAL(download_finished_signal()), this , SLOT(download_lua())); QObject::connect(pending_download_file, SIGNAL(error_signal(std::string)), this , SLOT(download_error(std::string))); } else { QObject::connect(this, SIGNAL(download_lua_signal ()), this , SLOT(download_global ()), Qt::QueuedConnection); Q_EMIT download_lua_signal(); } } catch(std::exception const& e) { std::string error = "Error loading file "; error += root_path; error += '/'; error += path; error += " with error: "; error += e.what(); ncl_window->error_occurred(error); } }
int cache_parse_lua(server *srv, connection *con, plugin_data *p, buffer *fn) { lua_State *L; readme rm; int ret = -1; buffer *b = buffer_init(); int header_tbl = 0; rm.done = 0; stream_open(&rm.st, fn); /* push the lua file to the interpreter and see what happends */ L = luaL_newstate(); luaL_openlibs(L); /* register functions */ lua_register(L, "md5", f_crypto_md5); lua_register(L, "file_mtime", f_file_mtime); lua_register(L, "file_isreg", f_file_isreg); lua_register(L, "file_isdir", f_file_isreg); lua_register(L, "dir_files", f_dir_files); #ifdef HAVE_MEMCACHE_H lua_pushliteral(L, "memcache_get_long"); lua_pushlightuserdata(L, p->conf.mc); lua_pushcclosure(L, f_memcache_get_long, 1); lua_settable(L, LUA_GLOBALSINDEX); lua_pushliteral(L, "memcache_get_string"); lua_pushlightuserdata(L, p->conf.mc); lua_pushcclosure(L, f_memcache_get_string, 1); lua_settable(L, LUA_GLOBALSINDEX); lua_pushliteral(L, "memcache_exists"); lua_pushlightuserdata(L, p->conf.mc); lua_pushcclosure(L, f_memcache_exists, 1); lua_settable(L, LUA_GLOBALSINDEX); #endif /* register CGI environment */ lua_pushliteral(L, "request"); lua_newtable(L); lua_settable(L, LUA_GLOBALSINDEX); lua_pushliteral(L, "request"); header_tbl = lua_gettop(L); lua_gettable(L, LUA_GLOBALSINDEX); c_to_lua_push(L, header_tbl, CONST_STR_LEN("REQUEST_URI"), CONST_BUF_LEN(con->request.orig_uri)); c_to_lua_push(L, header_tbl, CONST_STR_LEN("SCRIPT_NAME"), CONST_BUF_LEN(con->uri.path)); c_to_lua_push(L, header_tbl, CONST_STR_LEN("SCRIPT_FILENAME"), CONST_BUF_LEN(con->physical.path)); c_to_lua_push(L, header_tbl, CONST_STR_LEN("DOCUMENT_ROOT"), CONST_BUF_LEN(con->physical.doc_root)); if (!buffer_is_empty(con->request.pathinfo)) { c_to_lua_push(L, header_tbl, CONST_STR_LEN("PATH_INFO"), CONST_BUF_LEN(con->request.pathinfo)); } c_to_lua_push(L, header_tbl, CONST_STR_LEN("CWD"), CONST_BUF_LEN(p->basedir)); c_to_lua_push(L, header_tbl, CONST_STR_LEN("BASEURL"), CONST_BUF_LEN(p->baseurl)); /* register GET parameter */ lua_pushliteral(L, "get"); lua_newtable(L); lua_settable(L, LUA_GLOBALSINDEX); lua_pushliteral(L, "get"); header_tbl = lua_gettop(L); lua_gettable(L, LUA_GLOBALSINDEX); buffer_copy_string_buffer(b, con->uri.query); cache_export_get_params(L, header_tbl, b); buffer_reset(b); /* 2 default constants */ lua_pushliteral(L, "CACHE_HIT"); lua_pushnumber(L, 0); lua_settable(L, LUA_GLOBALSINDEX); lua_pushliteral(L, "CACHE_MISS"); lua_pushnumber(L, 1); lua_settable(L, LUA_GLOBALSINDEX); /* load lua program */ if (lua_load(L, load_file, &rm, fn->ptr) || lua_pcall(L,0,1,0)) { log_error_write(srv, __FILE__, __LINE__, "s", lua_tostring(L,-1)); goto error; } /* get return value */ ret = (int)lua_tonumber(L, -1); lua_pop(L, 1); /* fetch the data from lua */ lua_to_c_get_string(L, "trigger_handler", p->trigger_handler); if (0 == lua_to_c_get_string(L, "output_contenttype", b)) { response_header_overwrite(srv, con, CONST_STR_LEN("Content-Type"), CONST_BUF_LEN(b)); } if (ret == 0) { /* up to now it is a cache-hit, check if all files exist */ int curelem; time_t mtime = 0; if (!lua_to_c_is_table(L, "output_include")) { log_error_write(srv, __FILE__, __LINE__, "s", "output_include is missing or not a table"); ret = -1; goto error; } lua_pushstring(L, "output_include"); curelem = lua_gettop(L); lua_gettable(L, LUA_GLOBALSINDEX); /* HOW-TO build a etag ? * as we don't just have one file we have to take the stat() * from all base files, merge them and build the etag from * it later. * * The mtime of the content is the mtime of the freshest base file * * */ lua_pushnil(L); /* first key */ while (lua_next(L, curelem) != 0) { stat_cache_entry *sce = NULL; /* key' is at index -2 and value' at index -1 */ if (lua_isstring(L, -1)) { const char *s = lua_tostring(L, -1); /* the file is relative, make it absolute */ if (s[0] != '/') { buffer_copy_string_buffer(b, p->basedir); buffer_append_string(b, lua_tostring(L, -1)); } else { buffer_copy_string(b, lua_tostring(L, -1)); } if (HANDLER_ERROR == stat_cache_get_entry(srv, con, b, &sce)) { /* stat failed */ switch(errno) { case ENOENT: /* a file is missing, call the handler to generate it */ if (!buffer_is_empty(p->trigger_handler)) { ret = 1; /* cache-miss */ log_error_write(srv, __FILE__, __LINE__, "s", "a file is missing, calling handler"); break; } else { /* handler not set -> 500 */ ret = -1; log_error_write(srv, __FILE__, __LINE__, "s", "a file missing and no handler set"); break; } break; default: break; } } else { chunkqueue_append_file(con->write_queue, b, 0, sce->st.st_size); if (sce->st.st_mtime > mtime) mtime = sce->st.st_mtime; } } else { /* not a string */ ret = -1; log_error_write(srv, __FILE__, __LINE__, "s", "not a string"); break; } lua_pop(L, 1); /* removes value'; keeps key' for next iteration */ } lua_settop(L, curelem - 1); if (ret == 0) { data_string *ds; char timebuf[sizeof("Sat, 23 Jul 2005 21:20:01 GMT")]; buffer tbuf; con->file_finished = 1; ds = (data_string *)array_get_element(con->response.headers, "Last-Modified"); /* no Last-Modified specified */ if ((mtime) && (NULL == ds)) { strftime(timebuf, sizeof(timebuf), "%a, %d %b %Y %H:%M:%S GMT", gmtime(&mtime)); response_header_overwrite(srv, con, CONST_STR_LEN("Last-Modified"), timebuf, sizeof(timebuf) - 1); tbuf.ptr = timebuf; tbuf.used = sizeof(timebuf); tbuf.size = sizeof(timebuf); } else if (ds) { tbuf.ptr = ds->value->ptr; tbuf.used = ds->value->used; tbuf.size = ds->value->size; } else { tbuf.size = 0; tbuf.used = 0; tbuf.ptr = NULL; } if (HANDLER_FINISHED == http_response_handle_cachable(srv, con, &tbuf)) { /* ok, the client already has our content, * no need to send it again */ chunkqueue_reset(con->write_queue); ret = 0; /* cache-hit */ } } else { chunkqueue_reset(con->write_queue); } } if (ret == 1 && !buffer_is_empty(p->trigger_handler)) { /* cache-miss */ buffer_copy_string_buffer(con->uri.path, p->baseurl); buffer_append_string_buffer(con->uri.path, p->trigger_handler); buffer_copy_string_buffer(con->physical.path, p->basedir); buffer_append_string_buffer(con->physical.path, p->trigger_handler); chunkqueue_reset(con->write_queue); } error: lua_close(L); stream_close(&rm.st); buffer_free(b); return ret /* cache-error */; }
LuaEngine::LuaEngine() { Lua = lua_open(); luaL_openlibs(Lua); }
/***************************************************************************** * 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; 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_GetString( 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_sd->pf_control = Control; p_sys->psz_filename = vlclua_find_file( "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_object( L ); luaopen_sd( L ); luaopen_strings( L ); luaopen_variables( L ); luaopen_stream( L ); luaopen_gettext( L ); luaopen_xml( L ); lua_pop( L, 1 ); if( vlclua_add_modules_path( 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; vlc_mutex_init( &p_sys->lock ); vlc_cond_init( &p_sys->cond ); TAB_INIT( p_sys->i_query, p_sys->ppsz_query ); if( vlc_clone( &p_sys->thread, Run, p_sd, VLC_THREAD_PRIORITY_LOW ) ) { TAB_CLEAN( p_sys->i_query, p_sys->ppsz_query ); vlc_cond_destroy( &p_sys->cond ); vlc_mutex_destroy( &p_sys->lock ); goto error; } return VLC_SUCCESS; error: if( L ) lua_close( L ); free( p_sys->psz_filename ); free( p_sys ); return VLC_EGENERIC; }
lua_State *luaopen (void) { lua_State *L = lua_open(); /* create state */ if (L == NULL) { l_message(progname, "cannot create state: not enough memory"); return NULL; } lua_gc(L, LUA_GCSTOP, 0); /* stop collector during initialization */ luaL_openlibs(L); /* open libraries */ luaL_opensoplibs(L); /* 0.o */ lua_SOPAngle_register(L); lua_SOPVector_register(L); lua_SOPDamageInfo_register(L); lua_SOPEntity_register(L); lua_SOPPlayer_register(L); lua_SOPPhysObj_register(L); lua_register(L, "include", lua_include); lua_register(L, "Msg", lua_Msg); lua_register(L, "Error", lua_Error); lua_register(L, "CurTime", lua_CurTime); /*lua_pushstring(L, "LUAVERSION"); lua_pushstring(L, LUA_RELEASE " " LUA_COPYRIGHT); lua_settable(L, LUA_GLOBALSINDEX);*/ lua_pushglobalinteger(HUD_PRINTNOTIFY); lua_pushglobalinteger(HUD_PRINTCONSOLE); lua_pushglobalinteger(HUD_PRINTTALK); lua_pushglobalinteger(HUD_PRINTCENTER); lua_pushglobalinteger(MASK_ALL); lua_pushglobalinteger(MASK_SOLID); lua_pushglobalinteger(MASK_PLAYERSOLID); lua_pushglobalinteger(MASK_NPCSOLID); lua_pushglobalinteger(MASK_WATER); lua_pushglobalinteger(MASK_OPAQUE); lua_pushglobalinteger(MASK_OPAQUE_AND_NPCS); lua_pushglobalinteger(MASK_BLOCKLOS); lua_pushglobalinteger(MASK_BLOCKLOS_AND_NPCS); lua_pushglobalinteger(MASK_VISIBLE); lua_pushglobalinteger(MASK_VISIBLE_AND_NPCS); lua_pushglobalinteger(MASK_SHOT); lua_pushglobalinteger(MASK_SHOT_HULL); lua_pushglobalinteger(MASK_SHOT_PORTAL); lua_pushglobalinteger(MASK_SOLID_BRUSHONLY); lua_pushglobalinteger(MASK_PLAYERSOLID_BRUSHONLY); lua_pushglobalinteger(MASK_NPCSOLID_BRUSHONLY); lua_pushglobalinteger(MASK_NPCWORLDSTATIC); lua_pushglobalinteger(MASK_SPLITAREAPORTAL); lua_pushglobalinteger(MASK_CURRENT); lua_pushglobalinteger(MASK_DEADSOLID); lua_pushglobalinteger(SOLID_NONE); lua_pushglobalinteger(SOLID_BSP); lua_pushglobalinteger(SOLID_BBOX); lua_pushglobalinteger(SOLID_OBB); lua_pushglobalinteger(SOLID_OBB_YAW); lua_pushglobalinteger(SOLID_CUSTOM); lua_pushglobalinteger(SOLID_VPHYSICS); lua_pushglobalinteger(SOLID_LAST); lua_pushglobalinteger(COLLISION_GROUP_NONE); lua_pushglobalinteger(COLLISION_GROUP_DEBRIS); lua_pushglobalinteger(COLLISION_GROUP_DEBRIS_TRIGGER); lua_pushglobalinteger(COLLISION_GROUP_INTERACTIVE_DEBRIS); lua_pushglobalinteger(COLLISION_GROUP_INTERACTIVE); lua_pushglobalinteger(COLLISION_GROUP_PLAYER); lua_pushglobalinteger(COLLISION_GROUP_BREAKABLE_GLASS); lua_pushglobalinteger(COLLISION_GROUP_VEHICLE); lua_pushglobalinteger(COLLISION_GROUP_PLAYER_MOVEMENT); lua_pushglobalinteger(COLLISION_GROUP_NPC); lua_pushglobalinteger(COLLISION_GROUP_IN_VEHICLE); lua_pushglobalinteger(COLLISION_GROUP_WEAPON); lua_pushglobalinteger(COLLISION_GROUP_VEHICLE_CLIP); lua_pushglobalinteger(COLLISION_GROUP_PROJECTILE); lua_pushglobalinteger(COLLISION_GROUP_DOOR_BLOCKER); lua_pushglobalinteger(COLLISION_GROUP_PASSABLE_DOOR); lua_pushglobalinteger(COLLISION_GROUP_DISSOLVING); lua_pushglobalinteger(COLLISION_GROUP_PUSHAWAY); lua_pushglobalinteger(COLLISION_GROUP_NPC_ACTOR); lua_pushglobalinteger(COLLISION_GROUP_NPC_SCRIPTED); lua_pushglobalinteger_renamed(COLLISION_GROUP_DEBRIS, "COLLISION_GROUP_WORLD"); lua_pushglobalinteger(EF_BONEMERGE); lua_pushglobalinteger(EF_BRIGHTLIGHT); lua_pushglobalinteger(EF_DIMLIGHT); lua_pushglobalinteger(EF_NOINTERP); lua_pushglobalinteger(EF_NOSHADOW); lua_pushglobalinteger(EF_NODRAW); lua_pushglobalinteger(EF_NORECEIVESHADOW); lua_pushglobalinteger(EF_BONEMERGE_FASTCULL); lua_pushglobalinteger(EF_ITEM_BLINK); lua_pushglobalinteger(EF_PARENT_ANIMATES); lua_pushglobalinteger(FL_ONGROUND); lua_pushglobalinteger(FL_DUCKING); lua_pushglobalinteger(FL_WATERJUMP); lua_pushglobalinteger(FL_ONTRAIN); lua_pushglobalinteger(FL_INRAIN); lua_pushglobalinteger(FL_FROZEN); lua_pushglobalinteger(FL_ATCONTROLS); lua_pushglobalinteger(FL_FAKECLIENT); lua_pushglobalinteger(FL_INWATER); lua_pushglobalinteger(FL_FLY); lua_pushglobalinteger(FL_SWIM); lua_pushglobalinteger(FL_CONVEYOR); lua_pushglobalinteger(FL_NPC); lua_pushglobalinteger(FL_GODMODE); lua_pushglobalinteger(FL_NOTARGET); lua_pushglobalinteger(FL_AIMTARGET); lua_pushglobalinteger(FL_PARTIALGROUND); lua_pushglobalinteger(FL_STATICPROP); lua_pushglobalinteger(FL_GRAPHED); lua_pushglobalinteger(FL_GRENADE); lua_pushglobalinteger(FL_STEPMOVEMENT); lua_pushglobalinteger(FL_DONTTOUCH); lua_pushglobalinteger(FL_BASEVELOCITY); lua_pushglobalinteger(FL_WORLDBRUSH); lua_pushglobalinteger(FL_OBJECT); lua_pushglobalinteger(FL_KILLME); lua_pushglobalinteger(FL_ONFIRE); lua_pushglobalinteger(FL_DISSOLVING); lua_pushglobalinteger(FL_TRANSRAGDOLL); lua_pushglobalinteger(FL_UNBLOCKABLE_BY_PLAYER); lua_pushglobalinteger(MOVETYPE_NONE); lua_pushglobalinteger(MOVETYPE_ISOMETRIC); lua_pushglobalinteger(MOVETYPE_WALK); lua_pushglobalinteger(MOVETYPE_STEP); lua_pushglobalinteger(MOVETYPE_FLY); lua_pushglobalinteger(MOVETYPE_FLYGRAVITY); lua_pushglobalinteger(MOVETYPE_VPHYSICS); lua_pushglobalinteger(MOVETYPE_PUSH); lua_pushglobalinteger(MOVETYPE_NOCLIP); lua_pushglobalinteger(MOVETYPE_LADDER); lua_pushglobalinteger(MOVETYPE_OBSERVER); lua_pushglobalinteger(MOVETYPE_CUSTOM); lua_pushglobalinteger(FEAT_CREDITS); lua_pushglobalinteger(FEAT_ADMINCOMMANDS); lua_pushglobalinteger(FEAT_ENTCOMMANDS); lua_pushglobalinteger(FEAT_ADMINSAYCOMMANDS); lua_pushglobalinteger(FEAT_PLAYERSAYCOMMANDS); lua_pushglobalinteger(FEAT_KILLSOUNDS); lua_pushglobalinteger(FEAT_MAPVOTE); lua_pushglobalinteger(FEAT_CVARVOTE); lua_pushglobalinteger(FEAT_REMOTE); lua_pushglobalinteger(FEAT_HOOK); lua_pushglobalinteger(FEAT_JETPACK); lua_pushglobalinteger(FEAT_SNARK); lua_pushglobalinteger(FEAT_RADIO); lua_pushglobalinteger(FEAT_LUA); lua_pushglobalinteger(FCVAR_NONE); lua_pushglobalinteger(FCVAR_UNREGISTERED); lua_pushglobalinteger(FCVAR_DEVELOPMENTONLY); lua_pushglobalinteger(FCVAR_GAMEDLL); lua_pushglobalinteger(FCVAR_CLIENTDLL); lua_pushglobalinteger(FCVAR_HIDDEN); lua_pushglobalinteger(FCVAR_PROTECTED); lua_pushglobalinteger(FCVAR_SPONLY); lua_pushglobalinteger(FCVAR_ARCHIVE); lua_pushglobalinteger(FCVAR_NOTIFY); lua_pushglobalinteger(FCVAR_USERINFO); lua_pushglobalinteger(FCVAR_CHEAT); lua_pushglobalinteger(FCVAR_PRINTABLEONLY); lua_pushglobalinteger(FCVAR_NEVER_AS_STRING); lua_pushglobalinteger(FCVAR_REPLICATED); lua_pushglobalinteger(FCVAR_DEMO); lua_pushglobalinteger(FCVAR_DONTRECORD); lua_pushglobalinteger(FCVAR_NOT_CONNECTED); lua_pushglobalinteger(FCVAR_ARCHIVE_XBOX); lua_pushglobalinteger(FCVAR_SERVER_CAN_EXECUTE); lua_pushglobalinteger(FCVAR_SERVER_CANNOT_QUERY); lua_pushglobalinteger(FCVAR_CLIENTCMD_CAN_EXECUTE); lua_pushglobalinteger(STALEMATE_JOIN_MID); lua_pushglobalinteger(STALEMATE_TIMER); lua_pushglobalinteger(STALEMATE_SERVER_TIMELIMIT); lua_pushglobalinteger(NUM_STALEMATE_REASONS); lua_pushglobalinteger(DMG_GENERIC); lua_pushglobalinteger(DMG_CRUSH); lua_pushglobalinteger(DMG_BULLET); lua_pushglobalinteger(DMG_SLASH); lua_pushglobalinteger(DMG_BURN); lua_pushglobalinteger(DMG_VEHICLE); lua_pushglobalinteger(DMG_FALL); lua_pushglobalinteger(DMG_BLAST); lua_pushglobalinteger(DMG_CLUB); lua_pushglobalinteger(DMG_SHOCK); lua_pushglobalinteger(DMG_SONIC); lua_pushglobalinteger(DMG_ENERGYBEAM); lua_pushglobalinteger(DMG_PREVENT_PHYSICS_FORCE); lua_pushglobalinteger(DMG_NEVERGIB); lua_pushglobalinteger(DMG_ALWAYSGIB); lua_pushglobalinteger(DMG_DROWN); lua_pushglobalinteger(DMG_PARALYZE); lua_pushglobalinteger(DMG_NERVEGAS); lua_pushglobalinteger(DMG_POISON); lua_pushglobalinteger(DMG_RADIATION); lua_pushglobalinteger(DMG_DROWNRECOVER); lua_pushglobalinteger(DMG_ACID); lua_pushglobalinteger(DMG_SLOWBURN); lua_pushglobalinteger(DMG_REMOVENORAGDOLL); lua_pushglobalinteger(DMG_PHYSGUN); lua_pushglobalinteger(DMG_PLASMA); lua_pushglobalinteger(DMG_AIRBOAT); lua_pushglobalinteger(DMG_DISSOLVE); lua_pushglobalinteger(DMG_BLAST_SURFACE); lua_pushglobalinteger(DMG_DIRECT); lua_pushglobalinteger(DMG_BUCKSHOT); lua_pushglobalinteger(DMG_LASTGENERICFLAG); lua_pushglobalinteger_renamed((1<<24), "DMG_CUSTOM_TF2_IGNITE"); lua_pushglobalinteger(eQueryCvarValueStatus_ValueIntact); lua_pushglobalinteger(eQueryCvarValueStatus_CvarNotFound); lua_pushglobalinteger(eQueryCvarValueStatus_NotACvar); lua_pushglobalinteger(eQueryCvarValueStatus_CvarProtected); lua_pushglobalinteger(IN_ATTACK); lua_pushglobalinteger(IN_JUMP); lua_pushglobalinteger(IN_DUCK); lua_pushglobalinteger(IN_FORWARD); lua_pushglobalinteger(IN_BACK); lua_pushglobalinteger(IN_USE); lua_pushglobalinteger(IN_CANCEL); lua_pushglobalinteger(IN_LEFT); lua_pushglobalinteger(IN_RIGHT); lua_pushglobalinteger(IN_MOVELEFT); lua_pushglobalinteger(IN_MOVERIGHT); lua_pushglobalinteger(IN_ATTACK2); lua_pushglobalinteger(IN_RUN); lua_pushglobalinteger(IN_RELOAD); lua_pushglobalinteger(IN_ALT1); lua_pushglobalinteger(IN_ALT2); lua_pushglobalinteger(IN_SCORE); lua_pushglobalinteger(IN_SPEED); lua_pushglobalinteger(IN_WALK); lua_pushglobalinteger(IN_ZOOM); lua_pushglobalinteger(IN_WEAPON1); lua_pushglobalinteger(IN_WEAPON2); lua_pushglobalinteger(IN_BULLRUSH); lua_pushglobalinteger(IN_GRENADE1); lua_pushglobalinteger(IN_GRENADE2); lua_pushglobalinteger(TF2_CLASS_SCOUT); lua_pushglobalinteger(TF2_CLASS_SNIPER); lua_pushglobalinteger(TF2_CLASS_SOLDIER); lua_pushglobalinteger(TF2_CLASS_DEMOMAN); lua_pushglobalinteger(TF2_CLASS_MEDIC); lua_pushglobalinteger(TF2_CLASS_HEAVY); lua_pushglobalinteger(TF2_CLASS_PYRO); lua_pushglobalinteger(TF2_CLASS_SPY); lua_pushglobalinteger(TF2_CLASS_ENGINEER); lua_pushglobalinteger(TF2_CLASS_CIVILIAN); lua_pushglobalinteger(OBS_MODE_NONE); lua_pushglobalinteger(OBS_MODE_DEATHCAM); lua_pushglobalinteger(OBS_MODE_FREEZECAM); lua_pushglobalinteger(OBS_MODE_FIXED); lua_pushglobalinteger(OBS_MODE_IN_EYE); lua_pushglobalinteger(OBS_MODE_CHASE); lua_pushglobalinteger(OBS_MODE_ROAMING); lua_pushglobalinteger(NUM_OBSERVER_MODES); lua_gc(L, LUA_GCRESTART, 0); luaexec(L, "package.path = string.FixSlashes(sourceop.FullPathToDataDir() .. \"\\\\lua\\\\includes\\\\modules\\\\?.lua;\") .. package.path"); return L; }
int main(int argc, char** argv) { td_bin_allocator bin_alloc; const char *homedir; int res, rc, i; lua_State* L; td_init_portable(); #if !defined(TD_STANDALONE) if (NULL == (homedir = td_init_homedir())) return 1; #else homedir = ""; #endif td_bin_allocator_init(&bin_alloc); L = lua_newstate(td_lua_alloc, &bin_alloc); if (!L) exit(1); lua_atpanic(L, on_lua_panic); luaL_openlibs(L); tundra_open(L); #if defined(TD_STANDALONE) /* this is equivalent to table.insert(package.loaders, 1, td_load_embedded_file) */ /* get the function */ lua_getglobal(L, "table"); lua_getfield(L, -1, "insert"); lua_remove(L, -2); assert(!lua_isnil(L, -1)); /* arg1: the package.loaders table */ lua_getglobal(L, "package"); lua_getfield(L, -1, "loaders"); lua_remove(L, -2); assert(!lua_isnil(L, -1)); lua_pushinteger(L, 1); /* arg 2 */ lua_pushcfunction(L, td_load_embedded_file); /* arg 3 */ lua_call(L, 3, 0); #endif /* setup package.path */ { char ppath[1024]; snprintf(ppath, sizeof(ppath), "%s" TD_PATHSEP_STR "scripts" TD_PATHSEP_STR "?.lua;" "%s" TD_PATHSEP_STR "lua" TD_PATHSEP_STR "etc" TD_PATHSEP_STR "?.lua", homedir, homedir); lua_getglobal(L, "package"); assert(LUA_TTABLE == lua_type(L, -1)); lua_pushstring(L, ppath); lua_setfield(L, -2, "path"); } /* push our error handler on the stack now (before the chunk to run) */ lua_pushcclosure(L, get_traceback, 0); switch (luaL_loadbuffer(L, boot_snippet, sizeof(boot_snippet)-1, "boot_snippet")) { case LUA_ERRMEM: td_croak("out of memory"); return 1; case LUA_ERRSYNTAX: td_croak("syntax error\n%s\n", lua_tostring(L, -1)); return 1; } lua_newtable(L); lua_pushstring(L, homedir); lua_rawseti(L, -2, 1); for (i=1; i<argc; ++i) { lua_pushstring(L, argv[i]); lua_rawseti(L, -2, i+1); } { double t2; script_call_t1 = td_timestamp(); res = lua_pcall(L, /*narg:*/1, /*nres:*/0, /*errorfunc:*/ -3); t2 = td_timestamp(); if (global_tundra_stats) printf("total time spent in tundra: %.4fs\n", t2 - script_call_t1); } if (res == 0) { rc = global_tundra_exit_code; } else { fprintf(stderr, "%s\n", lua_tostring(L, -1)); rc = 1; } lua_close(L); td_bin_allocator_cleanup(&bin_alloc); return rc; }
LuaFile::LuaFile(std::string path) { this->path = path; this->L = luaL_newstate(); luaL_openlibs(L); }
bool cLuaInterpreter::Init() { luaL_openlibs(mL); lua_newtable(mL); RegisterFunction("SendDataToUser", &_SendToUser); /* back compatibility */ RegisterFunction("SendToUser", &_SendToUser); RegisterFunction("SendDataToAll", &_SendToClass); /* back compatibility */ RegisterFunction("SendToClass", &_SendToClass); RegisterFunction("SendToAll", &_SendToAll); RegisterFunction("SendPMToAll", &_SendPMToAll); RegisterFunction("CloseConnection", &_Disconnect); /* back compatibility */ RegisterFunction("Disconnect", &_Disconnect); RegisterFunction("DisconnectByName", &_Disconnect); /* back compatibility */ RegisterFunction("StopHub", &_StopHub); RegisterFunction("GetUserCC", &_GetUserCC); RegisterFunction("GetIPCC", &_GetIPCC); RegisterFunction("GetIPCN", &_GetIPCN); RegisterFunction("GetMyINFO", &_GetMyINFO); RegisterFunction("GetUpTime", &_GetUpTime); RegisterFunction("RegBot", &_RegBot); RegisterFunction("AddRobot", &_RegBot); /* back compatibility */ RegisterFunction("UnRegBot", &_UnRegBot); RegisterFunction("DelRobot", &_UnRegBot); /* back compatibility */ RegisterFunction("EditBot", &_EditBot); RegisterFunction("IsBot", &_IsBot); RegisterFunction("GetHubIp", &_GetHubIp); RegisterFunction("GetHubSecAlias", &_GetHubSecAlias); RegisterFunction("AddRegUser", &_AddRegUser); RegisterFunction("DelRegUser", &_DelRegUser); RegisterFunction("GetUserClass", &_GetUserClass); RegisterFunction("GetUserHost", &_GetUserHost); RegisterFunction("GetUserIP", &_GetUserIP); RegisterFunction("IsUserOnline", &_IsUserOnline); RegisterFunction("InUserSupports", &_InUserSupports); RegisterFunction("Ban", &_Ban); RegisterFunction("KickUser", &_KickUser); RegisterFunction("ReportUser", &_ReportUser); RegisterFunction("SendToOpChat", &_SendToOpChat); RegisterFunction("ParseCommand", &_ParseCommand); RegisterFunction("SetConfig", &_SetConfig); RegisterFunction("GetConfig", &_GetConfig); RegisterFunction("SQLQuery", &_SQLQuery); RegisterFunction("SQLFetch", &_SQLFetch); RegisterFunction("SQLFree", &_SQLFree); RegisterFunction("GetUsersCount", &_GetUsersCount); RegisterFunction("GetTotalShareSize", &_GetTotalShareSize); RegisterFunction("GetNickList", &_GetNickList); RegisterFunction("GetOPList", &_GetOPList); RegisterFunction("GetBotList", &_GetBotList); RegisterFunction("GetBots", &_GetBots); RegisterFunction("GetTempRights", &_GetTempRights); RegisterFunction("SetTempRights", &_SetTempRights); RegisterFunction("GetVHCfgDir", &_GetVHCfgDir); RegisterFunction("GetTopic", &_GetTopic); RegisterFunction("SetTopic", &_SetTopic); RegisterFunction("ScriptCommand", &_ScriptCommand); lua_setglobal(mL, "VH"); int status = luaL_dofile(mL, (char *)mScriptName.c_str()); if(status) { unsigned char *error = (unsigned char *) luaL_checkstring (mL, 1); ReportLuaError((char *) error); return false; } lua_pushstring(mL, LUA_PI_VERSION); lua_setglobal(mL, "_PLUGINVERSION"); lua_pushstring(mL, VERSION); lua_setglobal(mL, "_HUBVERSION"); return true; }
value ml_lua_modinfo (value string) { CAMLparam1 (string); CAMLlocal4 (name, version, depends, tuple); int err, i, n; lua_State *L = luaL_newstate(); luaL_openlibs(L); err = luaL_dostring (L, String_val(string)); if (err != 0) { caml_failwith("Lua.modinfo"); } name = caml_alloc_string(0); version = caml_alloc_string(0); depends = caml_alloc_tuple(0); lua_pushnil(L); while (lua_next(L, -2) != 0) { const char *s = lua_tostring(L, -2); // Get name string if (strcasecmp(s, "name") == 0) { const char *s = lua_tostring(L, -1); name = caml_copy_string(s); } // Get depends array else if (strcasecmp(s, "depend") == 0) { lua_pushstring(L, "table"); lua_gettable(L, LUA_GLOBALSINDEX); lua_pushstring(L, "getn"); lua_gettable(L, -2); lua_pushvalue(L, -3); lua_call(L, 1, 1); n = lua_tonumber(L, -1); lua_pop(L, 2); depends = caml_alloc_tuple(n); i = 0; lua_pushnil(L); while (lua_next(L, -2) != 0) { const char *s = lua_tostring(L, -1); Store_field(depends, i, caml_copy_string(s)); i++; lua_pop(L, 1); } } // Get version string else if (strcasecmp(s, "version") == 0) { const char *s = lua_tostring(L, -1); version = caml_copy_string(s); } lua_pop(L, 1); } tuple = caml_alloc_tuple(3); Store_field(tuple, 0, name); Store_field(tuple, 1, version); Store_field(tuple, 2, depends); CAMLreturn (tuple); }
void invRTSGame::initScriptEngine() { mainL = lua_open(); luaL_openlibs(mainL); // TODO: a macro for lua_register lua_register(mainL, "SleepA", sleep); lua_register(mainL, "Turn", turn); lua_register(mainL, "Move", move); lua_register(mainL, "MouseClickDown", mouseclickdown); lua_register(mainL, "MouseClickUp", mouseclickup); lua_register(mainL, "RegisterUnitDef", CreateUnitDef); lua_register(mainL, "RegisterUnit", registerUnit); lua_register(mainL, "UnregisterUnit", unregisterUnit); lua_register(mainL, "MoveToPoint", moveToPoint); lua_register(mainL, "MoveToEntity", moveToEntity); lua_register(mainL, "KillTasks", killTasks); lua_register(mainL, "KillTasksWithThread", killTasksWithThread); lua_register(mainL, "WaitForMoveA", waitForMove); lua_register(mainL, "CreateQuad", CreateQuad); lua_register(mainL, "LoadFont", loadFont); lua_register(mainL, "CreateTextQuad", CreateTextQuad); lua_register(mainL, "CreateQuadInstance", CreateQuadInstance); lua_register(mainL, "DeleteQuadInstance", deleteQuadInstance); lua_register(mainL, "SetQuadSize", SetQuadSize); lua_register(mainL, "SelectPlaceA", SelectPlace); lua_register(mainL, "GetSelectedResult", getSelectedResult); lua_register(mainL, "SetAnim", SetAnim); lua_register(mainL, "GetPos", getPos); lua_register(mainL, "SetPos", setPos); lua_register(mainL, "OccupArea", occupArea); lua_register(mainL, "LoadMap", loadMap); lua_register(mainL, "GetPixel", getPixel); lua_register(mainL, "UnloadMap", unloadMap); lua_register(mainL, "CreateTerrain", createTerrain); lua_register(mainL, "LoadTerrainTextures", loadTerrainTextures); lua_register(mainL, "DestroyTerrain", destroyTerrain); lua_register(mainL, "InsertMQuad", insertMQuad); lua_register(mainL, "DeleteMQuad", deleteMQuad); lua_register(mainL, "Resize", resize); lua_register(mainL, "ChangeOpacity", changeOpacity); lua_register(mainL, "ResetElapsedTime", resetElapsedTime); lua_register(mainL, "GetResolution", getResolution); lua_register(mainL, "SetQuadVisible", setQuadVisible); lua_register(mainL, "GetMouseRayPos", getMouseRayPos); lua_register(mainL, "SetMinimap", setMinimap); lua_register(mainL, "UpdateQuadZ", updateQuadZ); lua_register(mainL, "CreateTextBuffer", CreateTextBuffer); lua_register(mainL, "DeleteTextBuffer", DeleteTextBuffer); lua_register(mainL, "SetText", setText); lua_register(mainL, "LoadFont", loadFont); lua_register(mainL, "LoadSound", loadSound); lua_register(mainL, "PlaySound", playSound); lua_register(mainL, "SetClearColor", setClearColor); lua_register(mainL, "myprint", myprint); lua_register(mainL, "WaitForKeyA", waitForKey); lua_register(mainL, "TogglePause", togglePause); lua_register(mainL, "TogglePicking", togglePicking); }
int Game::Run(RenderWindow &win, VideoMode &vMode) { lua_State *luaState = luaL_newstate(); luaL_openlibs(luaState); luabind::open(luaState); Map map; Player player(luaState, e_player,0);// 0 should be loaded from file player.RegisterClassToLua(); battle_system battle; Object *object; object = new Object(luaState); Event Event; NPC npc(e_npc_random, luaState, -1); npc.SetPosition(200,200); bool collisionUp = false; bool collisionDown = false; bool collisionLeft = false; bool collisionRight = false; bool change = true; bool running = false; bool gameOver = false; bool load = false; bool load2 = false; Image gameOverImg; gameOverImg.LoadFromFile("../data/Images//presents.png"); Sprite gameOverSp(gameOverImg); vector<string> mapList; vector<string> objectList; mapList.push_back("..\\data\\Levels\\Map1.txt"); mapList.push_back("..\\data\\Levels\\Map2.txt"); mapList.push_back("..\\data\\Levels\\Map3.txt"); mapList.push_back("..\\data\\Levels\\Map2.txt"); mapList.push_back("..\\data\\Levels\\Map1.txt"); mapList.push_back("..\\data\\Levels\\Map2.txt"); mapList.push_back("..\\data\\Levels\\Map3.txt"); mapList.push_back("..\\data\\Levels\\Map3.txt"); mapList.push_back("..\\data\\Levels\\Map1.txt"); mapList.push_back("..\\data\\Levels\\Map2.txt"); objectList.push_back("..\\data\\Levels\\Object1.txt"); objectList.push_back("..\\data\\Levels\\Object2.txt"); objectList.push_back("..\\data\\Levels\\Object3.txt"); objectList.push_back("..\\data\\Levels\\Object4.txt"); objectList.push_back("..\\data\\Levels\\Object5.txt"); objectList.push_back("..\\data\\Levels\\Object6.txt"); objectList.push_back("..\\data\\Levels\\Object7.txt"); objectList.push_back("..\\data\\Levels\\Object8.txt"); objectList.push_back("..\\data\\Levels\\Object9.txt"); objectList.push_back("..\\data\\Levels\\Object10.txt"); string level = mapList[0];//Load from file string levelObject = objectList[0]; HUD hud; Enemy enemy; while(win.IsOpened()) { while(win.GetEvent(Event)) { if(Event.Type == Event::Closed) { win.Close(); } } if(win.GetInput().IsKeyDown(Key::Space)) { level = mapList[1]; change = true; load2 = true; if(!object->LoadObjects(vMode, &win, levelObject, &player, luaState)) { win.Close(); } } if(!win.GetInput().IsKeyDown(Key::Space) && load2 == true) { load2 = false; change = false; } if(win.GetInput().IsKeyDown(Key::T)) { player.RunGoldScript(); } if(win.GetInput().IsKeyDown(Key::LShift)) { level = mapList[0]; change = true; load = true; player.ChangeMap(0); /*if(!map.LoadMap(vMode, &win, "..\\data\\Levels\\Map1.txt")) { win.Close(); }*/ if(!object->LoadObjects(vMode, &win, "..\\data\\Levels\\Object1.txt", &player, luaState)) { win.Close(); } } if(!win.GetInput().IsKeyDown(Key::LShift) && load == true) { load = false; change = false; } if(!object->IsDisabled()) { if(win.GetInput().IsKeyDown(Key::Up)&& !win.GetInput().IsKeyDown(Key::Left) && !win.GetInput().IsKeyDown(Key::Right)) { if(object->HasCollidedWithObject(player, &win) == exitsensor) { cout<<"collided"<<object->GetCollidedExitSensor(player)->GetDestinationID(); if(object->GetCollidedExitSensor(player)->GetDestinationID() == 1) { cout<<"dest:"; if(object->GetCollidedExitSensor(player)->IsObjectiveComplete()) { cout<<"Exit"; level = mapList[object->GetCollidedExitSensor(player)->GetDestinationID()]; levelObject = objectList[object->GetCollidedExitSensor(player)->GetDestinationID()]; change = true; player.ChangeMap(object->GetCollidedExitSensor(player)->GetDestinationID()); object->ClearSensors(); } else { } } else if(object->GetCollidedExitSensor(player)->GetDestinationID() == 2) { cout<<"dest:"; if(object->GetCollidedExitSensor(player)->IsObjectiveComplete()) { cout<<"Exit"; level = mapList[object->GetCollidedExitSensor(player)->GetDestinationID()]; levelObject = objectList[object->GetCollidedExitSensor(player)->GetDestinationID()]; change = true; player.ChangeMap(object->GetCollidedExitSensor(player)->GetDestinationID()); object->ClearSensors(); } else { } } else if(object->GetCollidedExitSensor(player)->GetDestinationID() == 3) { cout<<"dest:"; if(object->GetCollidedExitSensor(player)->IsObjectiveComplete()) { cout<<"Exit"; level = mapList[object->GetCollidedExitSensor(player)->GetDestinationID()]; levelObject = objectList[object->GetCollidedExitSensor(player)->GetDestinationID()]; change = true; player.ChangeMap(object->GetCollidedExitSensor(player)->GetDestinationID()); object->ClearSensors(); } else { } } else if(object->GetCollidedExitSensor(player)->GetDestinationID() == 4) { cout<<"dest:"; if(object->GetCollidedExitSensor(player)->IsObjectiveComplete()) { cout<<"Exit"; level = mapList[object->GetCollidedExitSensor(player)->GetDestinationID()]; levelObject = objectList[object->GetCollidedExitSensor(player)->GetDestinationID()]; change = true; player.ChangeMap(object->GetCollidedExitSensor(player)->GetDestinationID()); object->ClearSensors(); } else { } } else if(object->GetCollidedExitSensor(player)->GetDestinationID() == 5) { cout<<"dest:"; if(object->GetCollidedExitSensor(player)->IsObjectiveComplete()) { cout<<"Exit"; level = mapList[object->GetCollidedExitSensor(player)->GetDestinationID()]; levelObject = objectList[object->GetCollidedExitSensor(player)->GetDestinationID()]; change = true; player.ChangeMap(object->GetCollidedExitSensor(player)->GetDestinationID()); object->ClearSensors(); } else { } } else if(object->GetCollidedExitSensor(player)->GetDestinationID() == 7) { cout<<"dest:"; if(object->GetCollidedExitSensor(player)->IsObjectiveComplete()) { cout<<"Exit"; level = mapList[object->GetCollidedExitSensor(player)->GetDestinationID()]; levelObject = objectList[object->GetCollidedExitSensor(player)->GetDestinationID()]; change = true; player.ChangeMap(object->GetCollidedExitSensor(player)->GetDestinationID()); object->ClearSensors(); } else { } } else if(object->GetCollidedExitSensor(player)->GetDestinationID() == 8) { cout<<"dest:"; if(object->GetCollidedExitSensor(player)->IsObjectiveComplete()) { cout<<"Exit"; level = mapList[object->GetCollidedExitSensor(player)->GetDestinationID()]; levelObject = objectList[object->GetCollidedExitSensor(player)->GetDestinationID()]; change = true; player.ChangeMap(object->GetCollidedExitSensor(player)->GetDestinationID()); object->ClearSensors(); } else { } } else if(object->GetCollidedExitSensor(player)->GetDestinationID() == 9) { cout<<"dest:"; if(object->GetCollidedExitSensor(player)->IsObjectiveComplete()) { cout<<"Exit"; level = mapList[object->GetCollidedExitSensor(player)->GetDestinationID()]; levelObject = objectList[object->GetCollidedExitSensor(player)->GetDestinationID()]; change = true; player.ChangeMap(object->GetCollidedExitSensor(player)->GetDestinationID()); object->ClearSensors(); } else { } } else if(object->GetCollidedExitSensor(player)->GetDestinationID() == 10) { cout<<"dest:"; if(object->GetCollidedExitSensor(player)->IsObjectiveComplete()) { cout<<"Exit"; level = mapList[object->GetCollidedExitSensor(player)->GetDestinationID()]; levelObject = objectList[object->GetCollidedExitSensor(player)->GetDestinationID()]; change = true; player.ChangeMap(object->GetCollidedExitSensor(player)->GetDestinationID()); object->ClearSensors(); } else { } } } else { if(object->HasCollidedWithObject(player, &win) == -1 ) { player.MoveUp(&win); if(player.GetView().GetCenter().y - player.GetView().GetHalfSize().y > -160) { hud.MoveUp(&win); } } else { player.SetPosition(player.GetSprite().GetPosition().x , player.GetSprite().GetPosition().y + 10); } } } if(win.GetInput().IsKeyDown(Key::Down)&& !win.GetInput().IsKeyDown(Key::Left) && !win.GetInput().IsKeyDown(Key::Right)) { if(player.GetSprite().GetPosition().y + player.GetSprite().GetSize().y<600) { if(object->HasCollidedWithObject(player, &win) == exitsensor) { cout<<"collided"<<object->GetCollidedExitSensor(player)->GetDestinationID(); if(object->GetCollidedExitSensor(player)->GetDestinationID() == 1) { cout<<"dest:"; if(object->GetCollidedExitSensor(player)->IsObjectiveComplete()) { cout<<"Exit"; level = mapList[object->GetCollidedExitSensor(player)->GetDestinationID()]; levelObject = objectList[object->GetCollidedExitSensor(player)->GetDestinationID()]; change = true; player.ChangeMap(object->GetCollidedExitSensor(player)->GetDestinationID()); object->ClearSensors(); } else { } } else if(object->GetCollidedExitSensor(player)->GetDestinationID() == 2) { cout<<"dest:"; if(object->GetCollidedExitSensor(player)->IsObjectiveComplete()) { cout<<"Exit"; level = mapList[object->GetCollidedExitSensor(player)->GetDestinationID()]; levelObject = objectList[object->GetCollidedExitSensor(player)->GetDestinationID()]; change = true; player.ChangeMap(object->GetCollidedExitSensor(player)->GetDestinationID()); object->ClearSensors(); } else { } } else if(object->GetCollidedExitSensor(player)->GetDestinationID() == 3) { cout<<"dest:"; if(object->GetCollidedExitSensor(player)->IsObjectiveComplete()) { cout<<"Exit"; level = mapList[object->GetCollidedExitSensor(player)->GetDestinationID()]; levelObject = objectList[object->GetCollidedExitSensor(player)->GetDestinationID()]; change = true; player.ChangeMap(object->GetCollidedExitSensor(player)->GetDestinationID()); object->ClearSensors(); } else { } } else if(object->GetCollidedExitSensor(player)->GetDestinationID() == 4) { cout<<"dest:"; if(object->GetCollidedExitSensor(player)->IsObjectiveComplete()) { cout<<"Exit"; level = mapList[object->GetCollidedExitSensor(player)->GetDestinationID()]; levelObject = objectList[object->GetCollidedExitSensor(player)->GetDestinationID()]; change = true; player.ChangeMap(object->GetCollidedExitSensor(player)->GetDestinationID()); object->ClearSensors(); } else { } } else if(object->GetCollidedExitSensor(player)->GetDestinationID() == 5) { cout<<"dest:"; if(object->GetCollidedExitSensor(player)->IsObjectiveComplete()) { cout<<"Exit"; level = mapList[object->GetCollidedExitSensor(player)->GetDestinationID()]; levelObject = objectList[object->GetCollidedExitSensor(player)->GetDestinationID()]; change = true; player.ChangeMap(object->GetCollidedExitSensor(player)->GetDestinationID()); object->ClearSensors(); } else { } } else if(object->GetCollidedExitSensor(player)->GetDestinationID() == 7) { cout<<"dest:"; if(object->GetCollidedExitSensor(player)->IsObjectiveComplete()) { cout<<"Exit"; level = mapList[object->GetCollidedExitSensor(player)->GetDestinationID()]; levelObject = objectList[object->GetCollidedExitSensor(player)->GetDestinationID()]; change = true; player.ChangeMap(object->GetCollidedExitSensor(player)->GetDestinationID()); object->ClearSensors(); } else { } } else if(object->GetCollidedExitSensor(player)->GetDestinationID() == 8) { cout<<"dest:"; if(object->GetCollidedExitSensor(player)->IsObjectiveComplete()) { cout<<"Exit"; level = mapList[object->GetCollidedExitSensor(player)->GetDestinationID()]; levelObject = objectList[object->GetCollidedExitSensor(player)->GetDestinationID()]; change = true; player.ChangeMap(object->GetCollidedExitSensor(player)->GetDestinationID()); object->ClearSensors(); } else { } } else if(object->GetCollidedExitSensor(player)->GetDestinationID() == 9) { cout<<"dest:"; if(object->GetCollidedExitSensor(player)->IsObjectiveComplete()) { cout<<"Exit"; level = mapList[object->GetCollidedExitSensor(player)->GetDestinationID()]; levelObject = objectList[object->GetCollidedExitSensor(player)->GetDestinationID()]; change = true; player.ChangeMap(object->GetCollidedExitSensor(player)->GetDestinationID()); object->ClearSensors(); } else { } } else if(object->GetCollidedExitSensor(player)->GetDestinationID() == 110) { cout<<"dest:"; if(object->GetCollidedExitSensor(player)->IsObjectiveComplete()) { cout<<"Exit"; level = mapList[object->GetCollidedExitSensor(player)->GetDestinationID()]; levelObject = objectList[object->GetCollidedExitSensor(player)->GetDestinationID()]; change = true; player.ChangeMap(object->GetCollidedExitSensor(player)->GetDestinationID()); object->ClearSensors(); } else { } } } else { if(object->HasCollidedWithObject(player, &win) == -1) { player.MoveDown(&win); if(player.GetView().GetCenter().y <= 300) { hud.MoveDown(&win); } } else { player.SetPosition(player.GetSprite().GetPosition().x , player.GetSprite().GetPosition().y - 10); } } } } if(win.GetInput().IsKeyDown(Key::Left) && !win.GetInput().IsKeyDown(Key::Up) && !win.GetInput().IsKeyDown(Key::Down)&& !win.GetInput().IsKeyDown(Key::Right)) { if(object->HasCollidedWithObject(player, &win) == -1) { player.MoveLeft(&win); } else { player.SetPosition(player.GetSprite().GetPosition().x + 10, player.GetSprite().GetPosition().y); } } if(win.GetInput().IsKeyDown(Key::Right)&& !win.GetInput().IsKeyDown(Key::Up) && !win.GetInput().IsKeyDown(Key::Down)&& !win.GetInput().IsKeyDown(Key::Left)) { if(object->HasCollidedWithObject(player, &win) == -1) { player.MoveRight(&win); } else { player.SetPosition(player.GetSprite().GetPosition().x - 10, player.GetSprite().GetPosition().y); } } } if(win.GetInput().IsKeyDown(Key::A)) { } if(object->HasCollidedWithObject(player, &win) == noncollectible) { if(player.m_up) player.SetPosition(player.GetSprite().GetPosition().x , player.GetSprite().GetPosition().y + 10); if(player.m_down) player.SetPosition(player.GetSprite().GetPosition().x , player.GetSprite().GetPosition().y - 10); if(player.m_right) player.SetPosition(player.GetSprite().GetPosition().x - 10, player.GetSprite().GetPosition().y); if(player.m_left) player.SetPosition(player.GetSprite().GetPosition().x + 10, player.GetSprite().GetPosition().y); } hud.Update(&player); object->Update(player); if(!object->IsBattling()) { win.Clear(); if(change) { if(!map.LoadMap(vMode, &win, level)) { win.Close(); } if(!object->LoadObjects(vMode, &win, levelObject, &player, luaState)) { win.Close(); } change = false; } map.RenderMap(vMode, &win); player.Draw(vMode, &win); if(object->RenderObjects(vMode, &win, &player, luaState) == false) return 0; hud.Draw(&win); } else { win.Clear(); NPC* npc; npc = object->GetCollidedNPC(); battle.Initialize((player.GetView().GetCenter().x-player.GetView().GetHalfSize().x),(player.GetView().GetCenter().y-player.GetView().GetHalfSize().y)); if(battle.Run(vMode, win, &enemy, player) == "Exits") { object->StopBattle(); } else if(battle.Run(vMode, win, &enemy, player) == "Player Win") { object->StopBattle(); object->RemoveNPC(object->GetCollidingIndex(), &win, &player); } else if(battle.Run(vMode, win, &enemy, player) == "Enemy Win") { object->StopBattle(); object->NotDisabled(); player.Default(); enemy.Default(); if(!map.LoadMap(vMode, &win, "..\\data\\Levels\\Map1.txt")) { win.Close(); } if(!object->LoadObjects(vMode, &win, "..\\data\\Levels\\Object1.txt", &player, luaState)) { win.Close(); } } player.SetView(400,300); } object->DrawCommentSystem(); win.SetView(player.GetView()); win.Display(); } lua_close(luaState); return -1; }
int main (int argc, char* argv[]) { #ifdef LUA_VERSION_NUM /* lua 5.1 */ lua_State* L = luaL_newstate(); luaL_openlibs(L); #else lua_State* L = lua_open(); luaopen_base(L); luaopen_io(L); luaopen_string(L); luaopen_table(L); luaopen_math(L); luaopen_debug(L); #endif lua_pushstring(L,TOLUA_VERSION); lua_setglobal(L,"TOLUA_VERSION"); lua_pushstring(L,LUA_VERSION); lua_setglobal(L,"TOLUA_LUA_VERSION"); if (argc==1) { help(); return 0; } else { int i, t; lua_newtable(L); lua_setglobal(L, "_extra_parameters"); lua_newtable(L); lua_pushvalue(L,-1); lua_setglobal(L,"flags"); t = lua_gettop(L); for (i=1; i<argc; ++i) { if (*argv[i] == '-') { switch (argv[i][1]) { case 'v': version(); return 0; case 'h': help(); return 0; case 'p': setfield(L,t,"p",""); break; case 'P': setfield(L,t,"P",""); break; case 'o': setfield(L,t,"o",argv[++i]); break; case 'n': setfield(L,t,"n",argv[++i]); break; case 'H': setfield(L,t,"H",argv[++i]); break; case 'S': setfield(L,t,"S",""); break; case '1': setfield(L,t,"1",""); break; case 'L': setfield(L,t,"L",argv[++i]); break; case 'D': setfield(L,t,"D",""); break; case 'W': setfield(L,t,"W",""); break; case 'C': setfield(L,t,"C",""); break; case 'E': add_extra(L,argv[++i]); break; case 't': setfield(L,t,"t",""); break; case 'q': setfield(L,t,"q",""); break; default: error(argv[i]); break; } } else { setfield(L,t,"f",argv[i]); break; } } lua_pop(L,1); } /* #define TOLUA_SCRIPT_RUN */ #ifndef TOLUA_SCRIPT_RUN { int tolua_tolua_open (lua_State* L); tolua_tolua_open(L); } #else { char* p; char path[BUFSIZ]; strcpy(path,argv[0]); p = strrchr(path,'/'); if (p==NULL) p = strrchr(path,'\\'); p = (p==NULL) ? path : p+1; sprintf(p,"%s","../src/bin/lua/"); lua_pushstring(L,path); lua_setglobal(L,"path"); strcat(path,"all.lua"); lua_dofile(L,path); } #endif return 0; }
void ServerApplication::Init(int argc, char* argv[]) { //NOTE: I might need to rearrange the init process so that lua & SQL can interact with the map system as needed. std::cout << "Beginning " << argv[0] << std::endl; //load the config settings config.Load("rsc/config.cfg", false, argc, argv); //------------------------- //Initialize the APIs //------------------------- //Init SDL if (SDL_Init(0)) { std::ostringstream os; os << "Failed to initialize SDL: " << SDL_GetError(); throw(std::runtime_error(os.str())); } std::cout << "Initialized SDL" << std::endl; //Init SDL_net if (SDLNet_Init()) { throw(std::runtime_error("Failed to initialize SDL_net")); } network.Open(config.Int("server.port")); std::cout << "Initialized SDL_net" << std::endl; //Init SQL int ret = sqlite3_open_v2(config["server.dbname"].c_str(), &database, SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, nullptr); if (ret != SQLITE_OK || !database) { throw(std::runtime_error(std::string() + "Failed to initialize SQL: " + sqlite3_errmsg(database) )); } std::cout << "Initialized SQL" << std::endl; //Init lua luaState = luaL_newstate(); if (!luaState) { throw(std::runtime_error("Failed to initialize lua")); } luaL_openlibs(luaState); std::cout << "Initialized lua" << std::endl; //append config["dir.scripts"] to the module path if (config["dir.scripts"].size() > 0) { //get the original path lua_getglobal(luaState, "package"); lua_getfield(luaState, -1, "path"); //build & push the message std::ostringstream path; path << lua_tostring(luaState, -1) << ";" << config["dir.scripts"] << "?.lua"; lua_pushstring(luaState, path.str().c_str()); //set the new path and clean up the stack lua_setfield(luaState, -3, "path"); lua_pop(luaState, 2); std::cout << "\tLua script directory appended" << std::endl; } //------------------------- //Setup the objects //------------------------- //set the hooks accountMgr.SetDatabase(database); characterMgr.SetDatabase(database); roomMgr.SetLuaState(luaState); roomMgr.SetDatabase(database); std::cout << "Internal managers initialized" << std::endl; //------------------------- //Run the startup scripts //------------------------- //setup the database if (runSQLScript(database, config["dir.scripts"] + "setup_server.sql")) { throw(std::runtime_error("Failed to initialize SQL's setup script")); } std::cout << "Completed SQL's setup script" << std::endl; //run lua's startup script if (luaL_dofile(luaState, (config["dir.scripts"] + "setup_server.lua").c_str())) { throw(std::runtime_error(std::string() + "Failed to initialize lua's setup script: " + lua_tostring(luaState, -1) )); } std::cout << "Completed lua's setup script" << std::endl; //------------------------- //debug output //------------------------- #define DEBUG_INTERNAL_VAR(x) std::cout << "\t" << #x << ": " << x << std::endl; std::cout << "Internal sizes:" << std::endl; DEBUG_INTERNAL_VAR(NETWORK_VERSION); DEBUG_INTERNAL_VAR(sizeof(Region::type_t)); DEBUG_INTERNAL_VAR(sizeof(Region)); DEBUG_INTERNAL_VAR(REGION_WIDTH); DEBUG_INTERNAL_VAR(REGION_HEIGHT); DEBUG_INTERNAL_VAR(REGION_DEPTH); DEBUG_INTERNAL_VAR(REGION_TILE_FOOTPRINT); DEBUG_INTERNAL_VAR(REGION_SOLID_FOOTPRINT); DEBUG_INTERNAL_VAR(PACKET_STRING_SIZE); DEBUG_INTERNAL_VAR(PACKET_BUFFER_SIZE); DEBUG_INTERNAL_VAR(MAX_PACKET_SIZE); DEBUG_INTERNAL_VAR(static_cast<int>(SerialPacketType::LAST)); //------------------------- //finalize the startup //------------------------- std::cout << "Startup completed successfully" << std::endl; //------------------------- //debugging //------------------------- //... }
bool loadDictionaryFromFile( const std::string& filename, ghoul::Dictionary& dictionary, lua_State* state ) { const static std::string _loggerCat = "lua_loadDictionaryFromFile"; if (state == nullptr) { if (_state == nullptr) { LDEBUG("Creating Lua state"); _state = luaL_newstate(); if (_state == nullptr) { LFATAL("Error creating new Lua state: Memory allocation error"); return false; } LDEBUG("Open libraries"); luaL_openlibs(_state); } state = _state; } if (filename.empty()) { LERROR("Filename was empty"); return false; } if (!FileSys.fileExists(absPath(filename))) { LERROR("File '" << absPath(filename) << "' did not exist"); return false; } LDEBUG("Loading dictionary script '" << filename << "'"); int status = luaL_loadfile(state, absPath(filename).c_str()); if (status != LUA_OK) { LERROR("Error loading script: '" << lua_tostring(state, -1) << "'"); return false; } LDEBUG("Executing script"); if (lua_pcall(state, 0, LUA_MULTRET, 0)) { LERROR("Error executing script: " << lua_tostring(state, -1)); return false; } if (lua_isnil(state, -1)) { LERROR("Error in script: '" << filename << "'. Script did not return anything."); return false; } if (!lua_istable(state, -1)) { LERROR("Error in script: '" << filename << "'. Script did not return a table."); return false; } luaDictionaryFromState(state, dictionary); // Clean up after ourselves by cleaning the stack lua_settop(state, 0); return true; }
int main (int argc, char *argv[]) { #ifdef FOR_ONEROBOT if (argc != 3) { fprintf(stderr, "%s 192.168.1.221 4001!\n", argv[0]); return -1; } #else if (argc != 5) { fprintf(stderr, "%s 192.168.1.221 4001 payload begin_idx!\n", argv[0]); return -1; } #endif signal(SIGPIPE ,SIG_IGN); signal(SIGINT ,SIG_IGN); set_max_fds(1024); reactor r; if (r.open(10000, 2192) != 0) { fprintf(stderr, "open failed![%s]\n", strerror(errno)); return -1; } if (init_log() != 0) { fprintf(stderr, "init log err.\n"); return -1; } host = argv[1]; port = ::atoi(argv[2]); #ifndef FOR_ONEROBOT g_total_payload = ::atoi(argv[3]); begin_id = ::atoi(argv[4]); #endif srand(time_value::start_time.sec()); time_util::init(); robot_connector.open(&r); #ifndef FOR_ONEROBOT r.schedule_timer(new timer(begin_id), time_value(0, 800*1000), time_value(0, 800*1000)); #endif if (global_param_cfg::instance()->load_config("../config") != 0) { fprintf(stderr, "Error: config - load global_param_cfg config failed!\n"); return -1; } if (scene_config::instance()->load_config("../config") != 0) { fprintf(stderr, "Error: config - load scene config failed!\n"); return -1; } if (buff_config::instance()->load_config("../config") != 0) { fprintf(stderr, "Error: config - load buff config failed!\n"); return -1; } if (skill_config::instance()->load_config("../config") != 0) { fprintf(stderr, "Error: config - load skill config failed!\n"); return -1; } if (item_config::instance()->load_config("../config") != 0) { fprintf(stderr, "Error: config - load item config failed!\n"); return -1; } L = luaL_newstate(); luaL_openlibs(L); #ifdef FOR_LUA tolua_player_open(L); tolua_lua_istream_open(L); if (luaL_loadfile(L, "src/ai_func.lua") || lua_pcall(L, 0, 0, 0)) { fprintf(stderr, "load ai_func lua file failed!\n"); return -1; } if (luaL_loadfile(L, "src/dispatch_msg.lua") || lua_pcall(L, 0, 0, 0)) { fprintf(stderr, "load dispatch_msg lua file failed!\n"); return -1; } #endif s_log->rinfo("=============================begin================="); e_log->rinfo("=============================begin================="); #ifdef FOR_ONEROBOT ::signal(SIGABRT, svc_core_signal); //::signal(SIGSEGV, svc_core_signal); inet_address remote_addr(port, host); time_value tv(30, 0); char ac_bf[32] = {0}; login_ncurses::input_account(ac_bf); if (robot_connector.connect(new player(ac_bf, ""), remote_addr, &tv) != 0) { e_log->rinfo("connect world failed!"); return 0; } #endif r.run_reactor_event_loop(); #ifdef FOR_ONEROBOT director::instance()->exit(); #endif lua_close(L); return 0; }
int main (int argc, char *argv[]) { #ifdef WIN32 if (__argv[0]) { applicationPath = __argv[0]; applicationPath.erase (applicationPath.find_last_of ('\\')+1, applicationPath.size()); } #else if (argv[0]) { applicationPath = argv[0]; applicationPath.erase (applicationPath.find_last_of ('/')+1, applicationPath.size()); } #endif // Setup logger callback, so error messages are reported with fltk::message logger.AddCallback (LogCallbackProc, 0); #ifdef _DEBUG logger.SetDebugMode (true); #endif // math_test(); // Initialize the class system creg::System::InitializeClasses (); int r = 0; if (ParseCmdLine(argc, argv, r)) { // Bring up the main editor dialog EditorUI editor; editorUI = &editor; editor.Show(true); editor.LoadToolWindowSettings(); // luaBinder.Init(); lua_State *L = lua_open(); luaL_openlibs(L); luaopen_upspring(L); editor.luaState = L; if (luaL_dostring(L, "require(\"jit.opt\").start()") != 0) { const char *err = lua_tostring(L, -1); fltk::message("Unable to start Lua JIT: %s", err); } if (luaL_dofile(L, "scripts/init.lua") != 0) { const char *err = lua_tostring(L, -1); fltk::message("Error while executing init.lua: %s", err); } // NOTE: the "scripts/plugins" literal was changed to "scripts/plugins/" std::list<std::string>* luaFiles = FindFiles("*.lua", false, #ifdef WIN32 "scripts\\plugins"); #else "scripts/plugins/"); #endif for (std::list<std::string>::iterator i = luaFiles->begin(); i != luaFiles->end(); ++i) { if (luaL_dofile(L, i->c_str()) != 0) { const char *err = lua_tostring(L, -1); fltk::message("Error while executing \'%s\': %s", i->c_str(), err); } } fltk::run(); } // Shutdown scripting system and class system creg::System::FreeClasses (); return r; }
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[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", ""); string[CLIENT_VERSION_STR] = getGlobalString(L, "clientVersionStr", "10.80"); integer[SQL_PORT] = getGlobalNumber(L, "mysqlPort", 3306); integer[LOGIN_PORT] = getGlobalNumber(L, "port", 7171); integer[CLIENT_VERSION_MIN] = getGlobalNumber(L, "clientVersionMin", 1080); integer[CLIENT_VERSION_MAX] = getGlobalNumber(L, "clientVersionMax", 1080); integer[STATUS_PORT] = getGlobalNumber(L, "statusProtocolPort", 7171); string[MAP_NAME] = getGlobalString(L, "mapName", "forgotten"); string[MAP_AUTHOR] = getGlobalString(L, "mapAuthor", "Unknown"); } boolean[FREE_PREMIUM] = getGlobalBoolean(L, "freePremium", 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", ""); integer[MOTD_NUM] = getGlobalNumber(L, "motdNum", 0); integer[MAX_PLAYERS] = getGlobalNumber(L, "maxPlayers"); 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[STATUSQUERY_TIMEOUT] = getGlobalNumber(L, "statusTimeout", 5000); integer[MAX_PACKETS_PER_SECOND] = getGlobalNumber(L, "maxPacketsPerSecond", 25); integer[MONSTER_COUNT] = getGlobalNumber(L, "monsterCount", 0); integer[NPC_COUNT] = getGlobalNumber(L, "npcCount", 0); integer[MAP_WIDTH] = getGlobalNumber(L, "mapWidth", 0); integer[MAP_HEIGHT] = getGlobalNumber(L, "mapHeight", 0); loaded = true; lua_close(L); return true; }
//lua 状态机的初始化 static int _init(struct snlua *l, struct server_context *ctx, const char * args, size_t sz) { lua_State *L = l->L; l->ctx = ctx; lua_gc(L, LUA_GCSTOP, 0);//停止gc luaL_openlibs(L);//打开相关库 //注册ctx到lua注册表 lua_pushlightuserdata(L, ctx); lua_setfield(L, LUA_REGISTRYINDEX, "server_context");//lua_setfield:做一个等价于 t[k] = v 的操作, 这里 t 是给出的有效索引 index 处的值, 而 v 是栈顶的那个值 //设置全局变量 const char *path = optstring(ctx, "lua_path","./lualib/?.lua;./lualib/?/init.lua"); lua_pushstring(L, path); lua_setglobal(L, "LUA_PATH"); const char *cpath = optstring(ctx, "lua_cpath","./luaclib/?.so"); lua_pushstring(L, cpath); lua_setglobal(L, "LUA_CPATH"); const char *service = optstring(ctx, "luaservice", "./service/?.lua"); lua_pushstring(L, service); lua_setglobal(L, "LUA_SERVICE"); const char *preload = server_cmd_command(ctx, "GETENV", "preload"); lua_pushstring(L, preload); lua_setglobal(L, "LUA_PRELOAD"); lua_pushcfunction(L, traceback); assert(lua_gettop(L) == 1); //载入首个lua文件,生成chunk到栈顶 const char * loader = optstring(ctx, "lualoader", "./lualib/loader.lua"); int r = luaL_loadfile(L, loader); if (r != LUA_OK) { server_error(ctx, "Can't load %s : %s", loader, lua_tostring(L, -1)); return 1; } lua_pushlstring(L, args, sz); /* lua_pcall(lua_State *L, int nargs, int nresults, int errfunc) nargs:传入参数个数 nresults:需要返回参数个数 errfunc: 0 返回原始错误信息 lua_errrun:运行时错误。 lua_errmem:内存分配错误。对于此类错误,lua并不调用错误处理函数。 lua_errerr:运行时错误处理函数误差。 非0 即处理错误信息函数所在当前栈的位置,如上面执行了lua_pushcfunction(L, traceback);所以errfunc应该为1 */ r = lua_pcall(L,1,0,1);//执行loader.lua if (r != LUA_OK) { server_error(ctx, "lua loader error : %s", lua_tostring(L, -1)); return 1; } //把栈上所有元素移除 lua_settop(L,0); //重启gc lua_gc(L, LUA_GCRESTART, 0); return 0; }
void test_api() { int base = 0; int count = 0; const unsigned char * str; size_t length = 0; lua_State * L = lua_open(); luaL_openlibs(L); printf("---> BEGIN test_api\n"); /* Push stack check value */ lua_pushliteral(L, STACKGUARD); base = lua_gettop(L); /* Sanity check */ check(L, base, 0); /* Save error: inexistant index */ if (luabins_save(L, lua_gettop(L) + 1, lua_gettop(L) + 1) == 0) { fatal(L, "save should fail"); } checkerr(L, base, "can't save: inexistant indices"); if (luabins_save(L, -1, -1) == 0) { fatal(L, "save should fail"); } checkerr(L, base, "can't save: inexistant indices"); /* Assuming other save errors to be tested in test.lua */ /* Trigger load error */ if (luabins_load(L, (const unsigned char *)"", 0, &count) == 0) { fatal(L, "load should fail"); } checkerr(L, base, "can't load: corrupt data"); /* Assuming other load errors to be tested in test.lua */ /* Do empty save */ if (luabins_save(L, base, base - 1) != 0) { fatal(L, "empty save failed"); } check(L, base, 1); str = (const unsigned char *)lua_tolstring(L, -1, &length); if (str == NULL || length == 0) { fatal(L, "bad empty save string"); } /* Load empty save */ if (luabins_load(L, str, length, &count) != 0) { fatal(L, "empty load failed"); } if (count != 0) { fatal(L, "bad empty load count"); } /* Pop saved data string */ check(L, base, 1); lua_pop(L, 1); check(L, base, 0); { /* Save test dataset */ int num_items = push_testdataset(L); check(L, base, num_items); if (luabins_save(L, base + 1, base + num_items) != 0) { fprintf(stderr, "%s\n", lua_tostring(L, -1)); fatal(L, "test dataset save failed"); } check(L, base, num_items + 1); /* Load test dataset */ str = (const unsigned char *)lua_tolstring(L, -1, &length); if (str == NULL || length == 0) { fatal(L, "bad empty save string"); } if (luabins_load(L, str, length, &count) != 0) { fprintf(stderr, "%s\n", lua_tostring(L, -1)); fatal(L, "test dataset load failed"); } if (count != num_items) { fatal(L, "wrong test dataset load count"); } check(L, base, num_items + 1 + num_items); check_testdataset_on_top(L); /* Check loaded data */ lua_pop(L, 1 + num_items); check_testdataset_on_top(L); /* Check original data intact */ lua_pop(L, num_items); check(L, base, 0); /* Assuming further tests are done in test.lua */ } lua_close(L); printf("---> OK\n"); }
int tcf_lua(void) { #else int main(int argc, char ** argv) { #endif int c; int ind; int error; const char * log_name = "-"; const char * script_name = NULL; char * engine_name; lua_State *L; log_mode = 0; #ifndef WIN32 signal(SIGPIPE, SIG_IGN); #endif ini_mdep(); ini_trace(); ini_events_queue(); ini_asyncreq(); #if defined(_WRS_KERNEL) progname = "tcf"; open_log_file("-"); #else progname = argv[0]; /* Parse arguments */ for (ind = 1; ind < argc; ind++) { const char * s = argv[ind]; if (*s != '-') { break; } s++; while ((c = *s++) != '\0') { switch (c) { case 'l': case 'L': case 'S': if (*s == '\0') { if (++ind >= argc) { fprintf(stderr, "%s: error: no argument given to option '%c'\n", progname, c); exit(1); } s = argv[ind]; } switch (c) { case 'l': log_mode = strtol(s, 0, 0); break; case 'L': log_name = s; break; case 'S': script_name = s; break; default: fprintf(stderr, "%s: error: illegal option '%c'\n", progname, c); exit(1); } s = ""; break; default: fprintf(stderr, "%s: error: illegal option '%c'\n", progname, c); exit(1); } } } if (ind >= argc) { fprintf(stderr, "%s: error: no Lua script specified\n", progname); exit(1); } engine_name = argv[ind++]; if (ind < argc) { fprintf(stderr, "%s: error: too many arguments\n", progname); exit(1); } open_log_file(log_name); #endif if (script_name != NULL) { if((lua_read_command_state.req.u.fio.fd = open(script_name, O_RDONLY, 0)) < 0) { fprintf(stderr, "%s: error: cannot open script: %s\n", progname, script_name); exit(1); } } else { lua_read_command_state.req.u.fio.fd = fileno(stdin); } discovery_start(); if((luastate = L = luaL_newstate()) == NULL) { fprintf(stderr, "error from luaL_newstate\n"); exit(1); } luaL_openlibs(L); luaL_register(L, "tcf", tcffuncs); lua_pop(L, 1); /* Peer metatable */ luaL_newmetatable(L, "tcf_peer"); luaL_register(L, NULL, peerfuncs); lua_pushvalue(L, -1); lua_setfield(L, -1, "__index"); /* m.__index = m */ lua_pushvalue(L, -1); lua_setfield(L, -1, "__metatable"); /* m.__metatable = m */ lua_pop(L, 1); /* Protocol metatable */ luaL_newmetatable(L, "tcf_protocol"); luaL_register(L, NULL, protocolfuncs); lua_pushvalue(L, -1); lua_setfield(L, -1, "__index"); /* m.__index = m */ lua_pushvalue(L, -1); lua_setfield(L, -1, "__metatable"); /* m.__metatable = m */ lua_pop(L, 1); /* Channel metatable */ luaL_newmetatable(L, "tcf_channel"); luaL_register(L, NULL, channelfuncs); lua_pushvalue(L, -1); lua_setfield(L, -1, "__index"); /* m.__index = m */ lua_pushvalue(L, -1); lua_setfield(L, -1, "__metatable"); /* m.__metatable = m */ lua_pop(L, 1); /* Post event metatable */ luaL_newmetatable(L, "tcf_post_event"); luaL_register(L, NULL, posteventfuncs); lua_pushvalue(L, -1); lua_setfield(L, -1, "__index"); /* m.__index = m */ lua_pushvalue(L, -1); lua_setfield(L, -1, "__metatable"); /* m.__metatable = m */ lua_pop(L, 1); lua_newtable(L); /* peers = {} */ lua_newtable(L); /* m = {} */ lua_pushstring(L, "v"); /* Values are weak */ lua_setfield(L, -2, "__mode"); /* m.__mode = "v" */ lua_setmetatable(L, -2); /* setmetatable(peer, m) */ peers_refp = luaref_new(L, NULL); peer_server_add_listener(peer_server_changes, L); if((error = luaL_loadfile(L, engine_name)) != 0) { fprintf(stderr, "%s\n", lua_tostring(L,1)); exit(1); } if((error = lua_pcall(L, 0, LUA_MULTRET, 0)) != 0) { fprintf(stderr, "%s\n", lua_tostring(L,1)); exit(1); } /* Process events - must run on the initial thread since ptrace() * returns ECHILD otherwise, thinking we are not the owner. */ run_event_loop(); lua_close(L); return 0; }
static int Start_LuaIntf( vlc_object_t *p_this, const char *name ) { intf_thread_t *p_intf = (intf_thread_t*)p_this; lua_State *L; config_ChainParse( p_intf, "lua-", ppsz_intf_options, p_intf->p_cfg ); if( name == NULL ) { char *n = var_InheritString( p_this, "lua-intf" ); if( unlikely(n == NULL) ) return VLC_EGENERIC; name = p_intf->psz_header = n; } else /* Cleaned up by vlc_object_release() */ p_intf->psz_header = strdup( name ); intf_sys_t *p_sys = malloc( sizeof(*p_sys) ); if( unlikely(p_sys == NULL) ) { free( p_intf->psz_header ); p_intf->psz_header = NULL; return VLC_ENOMEM; } p_intf->p_sys = p_sys; p_sys->psz_filename = vlclua_find_file( "intf", name ); if( !p_sys->psz_filename ) { msg_Err( p_intf, "Couldn't find lua interface script \"%s\".", 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_playlist_internal( L, pl_Get(p_intf) ); luaL_openlibs( L ); /* register our functions */ luaL_register( L, "vlc", p_reg ); /* register submodules */ luaopen_config( L ); luaopen_httpd( L ); luaopen_input( L ); luaopen_msg( L ); luaopen_misc( L ); if( vlclua_fd_init( L, &p_sys->dtable ) ) { lua_close( L ); goto error; } luaopen_object( L ); luaopen_osd( L ); luaopen_playlist( L ); luaopen_sd_intf( 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_equalizer( L ); #if defined(_WIN32) && !VLC_WINSTORE_APP luaopen_win( L ); #endif /* clean up */ lua_pop( L, 1 ); /* Setup the module search path */ if( vlclua_add_modules_path( 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 */ bool b_config_set = false; char *psz_config = var_InheritString( p_intf, "lua-config" ); if( !psz_config ) psz_config = MakeConfig( p_intf, name ); if( psz_config ) { char *psz_buffer; if( asprintf( &psz_buffer, "config={%s}", psz_config ) != -1 ) { char *psz_log = StripPasswords( psz_buffer ); if( psz_log != NULL ) { msg_Dbg( p_intf, "Setting config variable: %s", psz_log ); free( psz_log ); } 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 ) ) { if( !strcmp( name, "cli" ) ) { lua_getfield( L, -1, "rc" ); if( lua_istable( L, -1 ) ) { /* msg_Warn( p_intf, "The `rc' lua interface script " "was renamed `cli', please update " "your configuration!" ); */ lua_setfield( L, -2, "cli" ); } else lua_pop( L, 1 ); } lua_getfield( L, -1, name ); if( lua_istable( L, -1 ) ) { lua_setglobal( L, "config" ); b_config_set = true; } } } free( psz_config ); } if( !b_config_set ) { lua_newtable( L ); lua_setglobal( L, "config" ); } /* Wrapper for legacy telnet config */ if ( !strcmp( name, "telnet" ) ) { /* msg_Warn( p_intf, "The `telnet' lua interface script was replaced " "by `cli', please update your configuration!" ); */ char *wrapped_file = vlclua_find_file( "intf", "cli" ); if( !wrapped_file ) { msg_Err( p_intf, "Couldn't find lua interface script \"cli\", " "needed by telnet wrapper" ); lua_close( p_sys->L ); goto error; } lua_pushstring( L, wrapped_file ); lua_setglobal( L, "wrapped_file" ); free( wrapped_file ); } p_sys->L = L; if( vlc_clone( &p_sys->thread, Run, p_intf, VLC_THREAD_PRIORITY_LOW ) ) { vlclua_fd_cleanup( &p_sys->dtable ); lua_close( p_sys->L ); goto error; } return VLC_SUCCESS; error: free( p_sys->psz_filename ); free( p_sys ); free( p_intf->psz_header ); p_intf->psz_header = NULL; return VLC_EGENERIC; }
qboolean G_LuaStartVM(lvm_t * vm) { int res = 0; char homepath[MAX_QPATH], gamepath[MAX_QPATH]; vm->L = luaL_newstate(); if(!vm->L) { LUA_LOG("Lua: Lua failed to initialise.\n"); return qfalse; } luaL_openlibs(vm->L); trap_Cvar_VariableStringBuffer("fs_homepath", homepath, sizeof(homepath)); trap_Cvar_VariableStringBuffer("fs_game", gamepath, sizeof(gamepath)); lua_getglobal(vm->L, LUA_LOADLIBNAME); if(lua_istable(vm->L, -1)) { lua_pushstring(vm->L, va("%s%s%s%s?.lua;%s%s%s%slualib%slua%s?.lua", homepath, LUA_DIRSEP, gamepath, LUA_DIRSEP, homepath, LUA_DIRSEP, gamepath, LUA_DIRSEP, LUA_DIRSEP, LUA_DIRSEP)); lua_setfield(vm->L, -2, "path"); lua_pushstring(vm->L, va("%s%s%s%s?.%s;%s%s%s%slualib%sclibs%s?.%s", homepath, LUA_DIRSEP, gamepath, LUA_DIRSEP, EXTENSION, homepath, LUA_DIRSEP, gamepath, LUA_DIRSEP, LUA_DIRSEP, LUA_DIRSEP, EXTENSION)); lua_setfield(vm->L, -2, "cpath"); } lua_pop(vm->L, 1); Lua_RegisterGlobal(vm->L, "LUA_PATH", va("%s%s%s%s?.lua;%s%s%s%slualib%slua%s?.lua", homepath, LUA_DIRSEP, gamepath, LUA_DIRSEP, homepath, LUA_DIRSEP, gamepath, LUA_DIRSEP, LUA_DIRSEP, LUA_DIRSEP)); Lua_RegisterGlobal(vm->L, "LUA_CPATH", va("%s%s%s%s?.%s;%s%s%s%slualib%sclibs%s?.%s", homepath, LUA_DIRSEP, gamepath, LUA_DIRSEP, EXTENSION, homepath, LUA_DIRSEP, gamepath, LUA_DIRSEP, LUA_DIRSEP, LUA_DIRSEP, EXTENSION)); Lua_RegisterGlobal(vm->L, "LUA_DIRSEP", LUA_DIRSEP); lua_newtable(vm->L); Lua_RegConstInteger(vm->L, CS_PLAYERS); Lua_RegConstInteger(vm->L, EXEC_NOW); Lua_RegConstInteger(vm->L, EXEC_INSERT); Lua_RegConstInteger(vm->L, EXEC_APPEND); Lua_RegConstInteger(vm->L, FS_READ); Lua_RegConstInteger(vm->L, FS_WRITE); Lua_RegConstInteger(vm->L, FS_APPEND); Lua_RegConstInteger(vm->L, FS_APPEND_SYNC); Lua_RegConstInteger(vm->L, SAY_ALL); Lua_RegConstInteger(vm->L, SAY_TEAM); Lua_RegConstString(vm->L, HOSTARCH); luaopen_base(vm->L); luaopen_string(vm->L); luaopen_coroutine(vm->L); Luaopen_Game(vm->L); Luaopen_Qmath(vm->L); Luaopen_Mover(vm->L); Luaopen_Vector(vm->L); Luaopen_Entity(vm->L); Luaopen_Cinematic(vm->L); Luaopen_Sound(vm->L); Luaopen_Trace(vm->L); res = luaL_loadbuffer(vm->L, vm->code, vm->code_size, vm->filename); if(res == LUA_ERRSYNTAX) { LUA_LOG("Lua: syntax error during pre-compilation: %s\n", (char *)lua_tostring(vm->L, -1)); G_Printf(S_COLOR_YELLOW "Lua: syntax error: %s\n", (char *)lua_tostring(vm->L, -1)); lua_pop(vm->L, 1); vm->error++; return qfalse; } else if(res == LUA_ERRMEM) { LUA_LOG("Lua: memory allocation error #1 ( %s )\n", vm->filename); vm->error++; return qfalse; } if(!G_LuaCall(vm, "G_LuaStartVM", 0, 0)) return qfalse; LUA_LOG("Lua: Loading %s\n", vm->filename); return qtrue; }
/** * @brief sighandler the signal handler of zimg * * @param signal the signal zimg get * @param siginfo signal info * @param arg the arg for handler */ static void sighandler(int signal, siginfo_t *siginfo, void *arg) { char msg[128]; msg[0] = '\0'; str_lcat(msg, "----/--/-- --:--:--:------ [INFO] signal Terminal received zimg shutting down", sizeof(msg)); //str_lcat(msg, strsignal(signal)); log_handler(msg); write(STDOUT_FILENO, "\nbye bye!\n", 10); //evbase_t *evbase = (evbase_t *)arg; struct timeval tv = { .tv_usec = 100000, .tv_sec = 0 }; /* 100 ms */ event_base_loopexit(evbase, &tv); } /** * @brief init_thread the init function of threads * * @param htp evhtp object * @param thread the current thread * @param arg the arg for init */ void init_thread(evhtp_t *htp, evthr_t *thread, void *arg) { thr_arg_t *thr_args; thr_args = calloc(1, sizeof(thr_arg_t)); LOG_PRINT(LOG_DEBUG, "thr_args alloc"); thr_args->thread = thread; char mserver[32]; if (settings.cache_on == true) { memcached_st *memc = memcached_create(NULL); snprintf(mserver, 32, "%s:%d", settings.cache_ip, settings.cache_port); memcached_server_st *servers = memcached_servers_parse(mserver); memcached_server_push(memc, servers); memcached_behavior_set(memc, MEMCACHED_BEHAVIOR_BINARY_PROTOCOL, 1); memcached_behavior_set(memc, MEMCACHED_BEHAVIOR_NO_BLOCK, 1); memcached_behavior_set(memc, MEMCACHED_BEHAVIOR_NOREPLY, 1); memcached_behavior_set(memc, MEMCACHED_BEHAVIOR_TCP_KEEPALIVE, 1); thr_args->cache_conn = memc; LOG_PRINT(LOG_DEBUG, "Memcached Connection Init Finished."); memcached_server_list_free(servers); } else thr_args->cache_conn = NULL; if (settings.mode == 2) { thr_args->ssdb_conn = NULL; memcached_st *beans = memcached_create(NULL); snprintf(mserver, 32, "%s:%d", settings.beansdb_ip, settings.beansdb_port); memcached_server_st *servers = memcached_servers_parse(mserver); servers = memcached_servers_parse(mserver); memcached_server_push(beans, servers); memcached_behavior_set(beans, MEMCACHED_BEHAVIOR_BINARY_PROTOCOL, 0); memcached_behavior_set(beans, MEMCACHED_BEHAVIOR_NO_BLOCK, 1); memcached_behavior_set(beans, MEMCACHED_BEHAVIOR_TCP_KEEPALIVE, 1); thr_args->beansdb_conn = beans; LOG_PRINT(LOG_DEBUG, "beansdb Connection Init Finished."); memcached_server_list_free(servers); } else if (settings.mode == 3) { thr_args->beansdb_conn = NULL; redisContext* c = redisConnect(settings.ssdb_ip, settings.ssdb_port); if (c->err) { redisFree(c); LOG_PRINT(LOG_DEBUG, "Connect to ssdb server faile"); } else { thr_args->ssdb_conn = c; LOG_PRINT(LOG_DEBUG, "Connect to ssdb server Success"); } } thr_args->L = luaL_newstate(); LOG_PRINT(LOG_DEBUG, "luaL_newstate alloc"); if (thr_args->L != NULL) { luaL_openlibs(thr_args->L); luaL_openlib(thr_args->L, "zimg", zimg_lib, 0); luaL_openlib(thr_args->L, "log", loglib, 0); } luaL_loadfile(thr_args->L, settings.script_name); lua_pcall(thr_args->L, 0, 0, 0); evthr_set_aux(thread, thr_args); lua_State *L = luaL_newstate(); if (L != NULL) { luaL_openlibs(L); if (luaL_loadfile(L, conf_file) || lua_pcall(L, 0, 0, 0)) { lua_close(L); } else { pthread_setspecific(gLuaStateKey, (void *)L); } } }
static int pmain(lua_State *L) { struct Smain *s = &smain; char **argv = s->argv; int argn; int flags = 0; globalL = L; if (argv[0] && argv[0][0]) progname = argv[0]; LUAJIT_VERSION_SYM(); /* Linker-enforced version check. */ argn = collectargs(argv, &flags); if (argn < 0) { /* Invalid args? */ print_usage(); s->status = 1; return 0; } if ((flags & FLAGS_NOENV)) { lua_pushboolean(L, 1); lua_setfield(L, LUA_REGISTRYINDEX, "LUA_NOENV"); } /* Set MAD env _before_ libraries are open. */ mad_setenv(L, flags & FLAGS_NOENV); /* Stop collector during library initialization. */ lua_gc(L, LUA_GCSTOP, 0); luaL_openlibs(L); mad_openlibs(L); lua_gc(L, LUA_GCRESTART, -1); createargtable(L, argv, s->argc, argn); if (!(flags & FLAGS_NOENV)) { s->status = handle_luainit(L); if (s->status != LUA_OK) return 0; } /* MAD section. */ mad_setsig(); mad_regfunc(); if ((flags & FLAGS_MADENV)) dolibrary(L, "madl_main"); if (!(flags & FLAGS_NOENV)) { s->status = handle_madinit(L); if (s->status != LUA_OK) return 0; } if ((flags & FLAGS_VERSION)) print_version(); s->status = runargs(L, argv, argn); if (s->status != LUA_OK) return 0; if (s->argc > argn) { s->status = handle_script(L, argv + argn); if (s->status != LUA_OK) return 0; } if ((flags & FLAGS_INTERACTIVE)) { (void)print_jit_status; dotty(L); } else if (s->argc == argn && !(flags & FLAGS_EXEC)) { if (lua_stdin_is_tty()) { (void)print_version; (void)print_jit_status; dotty(L); } else { dofile(L, NULL); /* Executes stdin as a file. */ } } return 0; }
void LuaEngine::Init(const char* main_script_file) { Fini(); int ret = 0; // TODO: 定时器个数采用宏配置 heap_timer_ = new HeapTimer(1024); CHECK(heap_timer_ != NULL) << "timer heap init error!"; master_state_ = luaL_newstate(); CHECK(master_state_ != NULL) << "luaL_newstate error!"; luaL_openlibs(master_state_); lua_tinker::init(master_state_); lua_tinker::init_s64(master_state_); lua_tinker::init_u64(master_state_); // 将script_main.lua所在文件夹路径加入require路径搜索 char script_path[256] = {0}; realpath(main_script_file, script_path); strncpy(script_path, dirname(script_path), 256); AddRequirePath(script_path); AddRequireCPath(script_path); // package.path 处理 std::ostringstream oss_require; oss_require << "package.path = \"" << oss_require_path_.str() << "\""; ret = luaL_dostring(master_state_, oss_require.str().c_str()); LOG(INFO) << "luaL_dostring [" << oss_require.str().c_str() << "]"; CHECK(ret == 0) << "luaL_dostring [" << oss_require.str().c_str() << "] error!"; oss_require.str(""); oss_require_path_.str(""); // package.cpath 处理 oss_require << "package.cpath = \"" << oss_require_cpath_.str() << "\""; ret = luaL_dostring(master_state_, oss_require.str().c_str()); LOG(INFO) << "luaL_dostring [" << oss_require.str().c_str() << "]"; CHECK(ret == 0) << "luaL_dostring [" << oss_require.str().c_str() << "] error!"; oss_require.str(""); oss_require_cpath_.str(""); // 设置LUA_SCRIPT_PATH SetGlobal("LUA_SCRIPT_PATH", script_path); // 注册log函数 RegFunc("C_LOG_INFO", &LuaEngine::LogInfo); RegFunc("C_LOG_ERROR", &LuaEngine::LogError); // lua_tinker中日志函数 RegFunc("_ALERT", &LuaEngine::LogInfo); ret = luaL_dofile(master_state_, main_script_file); if (ret != 0) { LOG(ERROR) << lua_tostring(master_state_, -1); } CHECK(ret == 0) << "luaL_dofile error!"; // 第一次加载模块 Reload(); // 设置检查信号宏 SetGlobal<int>("CHECK_SIG_OK", CHECK_SIG_OK); SetGlobal<int>("CHECK_SIG_TIMEOUT", CHECK_SIG_TIMEOUT); // 设置定时器 SetHandler(this, &LuaEngine::OnTimer); }
void my_lua_openlibs(lua_State* L) { // we edited source of the original to exclude things, // but only get those changes if compile from source; // could copy/paste modified version over here luaL_openlibs(L); }