Example #1
2
void ScriptController::setLong(const char* name, long v)
{
    lua_pushinteger(_lua, v);
    lua_setglobal(_lua, name);
}
Example #2
0
void CLuaHandleSynced::Init(const string& syncedFile,
                            const string& unsyncedFile,
                            const string& modes)
{
	if (!IsValid())
		return;

	if (GetFullCtrl()) {
		watchUnitDefs.resize(unitDefHandler->unitDefs.size() + 1, false);
		watchFeatureDefs.resize(featureHandler->GetFeatureDefs().size(), false);
		watchWeaponDefs.resize(weaponDefHandler->numWeaponDefs, false);
	}

	const string syncedCode   = LoadFile(syncedFile, modes);
	const string unsyncedCode = LoadFile(unsyncedFile, modes);
	if (syncedCode.empty() && unsyncedCode.empty()) {
		KillLua();
		return;
	}

	BEGIN_ITERATE_LUA_STATES();

	// load the standard libraries
	LUA_OPEN_LIB(L, luaopen_base);
	LUA_OPEN_LIB(L, luaopen_math);
	LUA_OPEN_LIB(L, luaopen_table);
	LUA_OPEN_LIB(L, luaopen_string);
	//LUA_OPEN_LIB(L, luaopen_io);
	//LUA_OPEN_LIB(L, luaopen_os);
	//LUA_OPEN_LIB(L, luaopen_package);
	//LUA_OPEN_LIB(L, luaopen_debug);

	// delete some dangerous functions
	lua_pushnil(L); lua_setglobal(L, "dofile");
	lua_pushnil(L); lua_setglobal(L, "loadfile");
	lua_pushnil(L); lua_setglobal(L, "loadlib");
	lua_pushnil(L); lua_setglobal(L, "loadstring"); // replaced
	lua_pushnil(L); lua_setglobal(L, "require");
	lua_pushnil(L); lua_setglobal(L, "rawequal");
	lua_pushnil(L); lua_setglobal(L, "rawget");
	lua_pushnil(L); lua_setglobal(L, "rawset");
//	lua_pushnil(L); lua_setglobal(L, "getfenv");
//	lua_pushnil(L); lua_setglobal(L, "setfenv");
	lua_pushnil(L); lua_setglobal(L, "newproxy");
	lua_pushnil(L); lua_setglobal(L, "gcinfo");
	lua_pushnil(L); lua_setglobal(L, "collectgarbage");

	// use gs->randFloat() for the synchronized code, and disable randomseed()
	// (this first copies the original functions to the registry for unsynced)
	if (!SyncifyRandomFuncs(L)) {
		KillLua();
		return;
	}

	SetAllowChanges(true, true);
	SetSynced(true, true);

	const bool haveSynced = (SingleState() || L == L_Sim) && SetupSynced(L, syncedCode, syncedFile);
	if (!IsValid())
		return;

	SetAllowChanges(false, true);
	SetSynced(false, true);

	const bool haveUnsynced = (SingleState() || L == L_Draw) && SetupUnsynced(L, unsyncedCode, unsyncedFile);
	if (!IsValid())
		return;

	SetSynced(true, true);
	SetAllowChanges(true, true);

	if (!haveSynced && !haveUnsynced) {
		KillLua();
		return;
	}

	// register for call-ins
	eventHandler.AddClient(this);

	END_ITERATE_LUA_STATES();
}
int luaopen_coevent(lua_State *L)
{
    luaopen_uthread(L);

    LM = L;
    _loop_fd = -1;

    swop_top = malloc(sizeof(cosocket_swop_t));
    swop_top->next = NULL;

    pid = getpid();
    update_time();

    SSL_library_init();
    OpenSSL_add_all_algorithms();

    lua_pushlightuserdata(L, NULL);
    lua_setglobal(L, "null");

    lua_register(L, "startloop", lua_f_startloop);
    lua_register(L, "swop", lua_f_coroutine_swop);
    lua_register(L, "sleep", lua_f_sleep);
    lua_register(L, "md5", lua_f_md5);
    lua_register(L, "sha1bin", lua_f_sha1bin);
    lua_register(L, "hmac_sha1", lua_f_hmac_sha1);
    lua_register(L, "base64_encode", lua_f_base64_encode);
    lua_register(L, "base64_decode", lua_f_base64_decode);
    lua_register(L, "base64_encode_url", lua_f_base64_encode_url);
    lua_register(L, "base64_decode_url", lua_f_base64_decode_url);
    lua_register(L, "escape", cosocket_lua_f_escape);
    lua_register(L, "escape_uri", lua_f_escape_uri);
    lua_register(L, "unescape_uri", lua_f_unescape_uri);
    lua_register(L, "time", lua_f_time);
    lua_register(L, "longtime", lua_f_longtime);
    lua_register(L, "build_dns_query_packet", lua_co_build_dns_query_packet);
    lua_register(L, "parse_dns_result", lua_co_parse_dns_result);
    lua_register(L, "LOG", lua_f_log);
    lua_register(L, "open_log", lua_f_open_log);
    luaopen_eio(L);

    luaL_loadstring(L, " \
DEBUG,INFO,NOTICE,WARN,ALERT,ERR = 1,2,3,4,5,6 \
coroutine_resume=coroutine.resume \
coroutine_create=coroutine.create \
coroutine_wait=coroutine.wait \
wait=coroutine.wait \
newthread=coroutine.spawn \
newco = newthread ");

    lua_pcall(L, 0, 0, 0);

    luaL_newmetatable(L, "cosocket:tcp");
    lua_pushvalue(L, lua_upvalueindex(1));
    setfuncs(L, M, 1);
    lua_pushvalue(L, -1);
    lua_setfield(L, -2, "__index");
    lua_pop(L, 1);

    luaL_newmetatable(L, "cosocket:udp");
    lua_pushvalue(L, lua_upvalueindex(1));
    setfuncs(L, M_UDP, 1);
    lua_pushvalue(L, -1);
    lua_setfield(L, -2, "__index");
    lua_pop(L, 1);

    static const struct luaL_reg _MT[] = {{NULL, NULL}};
    luaL_openlib(L, "cosocket", cosocket_methods, 0);

    luaL_newmetatable(L, "cosocket*");
    luaL_register(L, NULL, _MT);
    lua_pushliteral(L, "__index");
    lua_pushvalue(L, -3);               /* dup methods table*/
    lua_rawset(L, -3);                  /* metatable.__index = methods */
    lua_pushliteral(L, "__metatable");
    lua_pushvalue(L, -3);               /* dup methods table*/
    lua_rawset(L, -3);                  /* hide metatable:
                                         metatable.__metatable = methods */
    lua_pop(L, 1);                      /* drop metatable */

    lua_pushcfunction(L, lua_f_startloop);
    return 1;
}
Example #4
0
void luasrc_LoadEntities (const char *path)
{
	FileFindHandle_t fh;

	if ( !path )
	{
		path = "";
	}

	char root[ MAX_PATH ] = { 0 };

	char filename[ MAX_PATH ] = { 0 };
	char fullpath[ MAX_PATH ] = { 0 };
	char className[ 255 ] = { 0 };

	Q_snprintf( root, sizeof( root ), "%s" LUA_PATH_ENTITIES "\\*", path );

	char const *fn = g_pFullFileSystem->FindFirstEx( root, "MOD", &fh );
	while ( fn )
	{
		Q_strcpy( className, fn );
		Q_strlower( className );
		if ( fn[0] != '.' )
		{
			if ( g_pFullFileSystem->FindIsDirectory( fh ) )
			{
#ifdef CLIENT_DLL
				Q_snprintf( filename, sizeof( filename ), "%s" LUA_PATH_ENTITIES "\\%s\\cl_init.lua", path, className );
#else
				Q_snprintf( filename, sizeof( filename ), "%s" LUA_PATH_ENTITIES "\\%s\\init.lua", path, className );
#endif
				if ( filesystem->FileExists( filename, "MOD" ) )
				{
					filesystem->RelativePathToFullPath( filename, "MOD", fullpath, sizeof( fullpath ) );
					lua_newtable( L );
					char entDir[ MAX_PATH ];
					Q_snprintf( entDir, sizeof( entDir ), "entities\\%s", className );
					lua_pushstring( L, entDir );
					lua_setfield( L, -2, "__folder" );
					lua_pushstring( L, LUA_BASE_ENTITY_CLASS );
					lua_setfield( L, -2, "__base" );
					lua_pushstring( L, LUA_BASE_ENTITY_FACTORY );
					lua_setfield( L, -2, "__factory" );
					lua_setglobal( L, "ENT" );
					if ( luasrc_dofile( L, fullpath ) == 0 )
					{
						lua_getglobal( L, "entity" );
						if ( lua_istable( L, -1 ) )
						{
							lua_getfield( L, -1, "register" );
							if ( lua_isfunction( L, -1 ) )
							{
								lua_remove( L, -2 );
								lua_getglobal( L, "ENT" );
								lua_pushstring( L, className );
								luasrc_pcall( L, 2, 0, 0 );
								lua_getglobal( L, "ENT" );
								if ( lua_istable( L, -1 ) )
								{
									lua_getfield( L, -1, "__factory" );
									if ( lua_isstring( L, -1 ) )
									{
										const char *pszClassname = lua_tostring( L, -1 );
										if (Q_strcmp(pszClassname, "CBaseAnimating") == 0)
											RegisterScriptedEntity( className );
#ifndef CLIENT_DLL
										else if (Q_strcmp(pszClassname, "CBaseTrigger") == 0)
											RegisterScriptedTrigger( className );
#endif
									}
									lua_pop( L, 2 );
								}
								else
								{
									lua_pop( L, 1 );
								}
							}
							else
							{
								lua_pop( L, 2 );
							}
						}
						else
						{
							lua_pop( L, 1 );
						}
					}
					lua_pushnil( L );
					lua_setglobal( L, "ENT" );
				}
			}
		}

		fn = g_pFullFileSystem->FindNext( fh );
	}
	g_pFullFileSystem->FindClose( fh );
}
Example #5
0
void ScriptController::setString(const char* name, const char* v)
{
    lua_pushstring(_lua, v);
    lua_setglobal(_lua, name);
}
void registerEngineLuaAPI(Engine& engine, UniverseContext& ctx, lua_State* L)
{
	lua_pushlightuserdata(L, &ctx);
	lua_setglobal(L, "g_universe_context");

	lua_pushlightuserdata(L, ctx.m_universe);
	lua_setglobal(L, "g_universe");

	lua_pushlightuserdata(L, &engine);
	lua_setglobal(L, "g_engine");

	registerCFunction(
		L,
		"API_getScene",
		LuaWrapper::wrap<decltype(&LuaAPI::getScene), LuaAPI::getScene>);

	registerCFunction(L,
					  "API_setEntityPosition",
					  LuaWrapper::wrap<decltype(&LuaAPI::setEntityPosition),
									   LuaAPI::setEntityPosition>);

	registerCFunction(L,
					  "API_setEntityRotation",
					  LuaWrapper::wrap<decltype(&LuaAPI::setEntityRotation),
									   LuaAPI::setEntityRotation>);

	registerCFunction(
		L,
		"API_setEntityLocalRotation",
		LuaWrapper::wrap<decltype(&LuaAPI::setEntityLocalRotation),
						 LuaAPI::setEntityLocalRotation>);

	registerCFunction(L,
					  "API_createComponent",
					  LuaWrapper::wrap<decltype(&LuaAPI::createComponent),
									   LuaAPI::createComponent>);

	registerCFunction(L,
					  "API_setRenderablePath",
					  LuaWrapper::wrap<decltype(&LuaAPI::setRenderablePath),
									   LuaAPI::setRenderablePath>);

	registerCFunction(L,
					  "API_getInputActionValue",
					  LuaWrapper::wrap<decltype(&LuaAPI::getInputActionValue),
									   LuaAPI::getInputActionValue>);
	registerCFunction(L,
					  "API_addInputAction",
					  LuaWrapper::wrap<decltype(&LuaAPI::addInputAction),
									   LuaAPI::addInputAction>);

	registerCFunction(
		L,
		"API_logError",
		LuaWrapper::wrap<decltype(&LuaAPI::logError), LuaAPI::logError>);

	registerCFunction(
		L,
		"API_logInfo",
		LuaWrapper::wrap<decltype(&LuaAPI::logInfo), LuaAPI::logInfo>);

	registerCFunction(L, "API_multVecQuat", &LuaAPI::multVecQuat);
}
Example #7
0
 object &operator =(T value) {
   detail::push<T>(lua_, value);
   lua_setglobal(lua_, identify_.c_str());
   return *this;
 }
Example #8
0
void ScriptController::setFloat(const char* name, float v)
{
    lua_pushnumber(_lua, v);
    lua_setglobal(_lua, name);
}
Example #9
0
LUALIB_API void lua_baselibopen (lua_State *L) {
  luaL_openl(L, base_funcs);
  lua_pushstring(L, LUA_VERSION);
  lua_setglobal(L, "_VERSION");
  deprecated_funcs(L);
}
Example #10
0
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("GetLuaBots", &_GetLuaBots);
	RegisterFunction("GetBots", &_GetLuaBots); /* back compatibility */
	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;
}
Example #11
0
static int luaB_setglobal (lua_State *L) {
  luaL_checkany(L, 2);
  lua_setglobal(L, luaL_check_string(L, 1));
  return 0;
}
Example #12
0
// Ctor, initialization
lua_kernel_base::lua_kernel_base(CVideo * video)
 : mState(luaL_newstate())
 , video_(video)
 , cmd_log_()
{
	get_lua_kernel_base_ptr(mState) = this;
	lua_State *L = mState;

	cmd_log_ << "Initializing " << my_name() << "...\n";

	// Open safe libraries.
	// Debug and OS are not, but most of their functions will be disabled below.
	cmd_log_ << "Adding standard libs...\n";

	static const luaL_Reg safe_libs[] = {
		{ "",       luaopen_base   },
		{ "table",  luaopen_table  },
		{ "string", luaopen_string },
		{ "math",   luaopen_math   },
		{ "coroutine",   luaopen_coroutine   },
		{ "debug",  luaopen_debug  },
		{ "os",     luaopen_os     },
		{ "bit32",  luaopen_bit32  }, // added in Lua 5.2
		{ nullptr, nullptr }
	};
	for (luaL_Reg const *lib = safe_libs; lib->func; ++lib)
	{
		luaL_requiref(L, lib->name, lib->func, 1);
		lua_pop(L, 1);  /* remove lib */
	}

	// Disable functions from os which we don't want.
	lua_getglobal(L, "os");
	lua_pushnil(L);
	while(lua_next(L, -2) != 0) {
		lua_pop(L, 1);
		char const* function = lua_tostring(L, -1);
		if(strcmp(function, "clock") == 0 || strcmp(function, "date") == 0
			|| strcmp(function, "time") == 0 || strcmp(function, "difftime") == 0) continue;
		lua_pushnil(L);
		lua_setfield(L, -3, function);
	}
	lua_pop(L, 1);

	// Disable functions from debug which we don't want.
	lua_getglobal(L, "debug");
	lua_pushnil(L);
	while(lua_next(L, -2) != 0) {
		lua_pop(L, 1);
		char const* function = lua_tostring(L, -1);
		if(strcmp(function, "traceback") == 0 || strcmp(function, "getinfo") == 0) continue;	//traceback is needed for our error handler
		lua_pushnil(L);										//getinfo is needed for ilua strict mode
		lua_setfield(L, -3, function);
	}
	lua_pop(L, 1);

	// Delete dofile and loadfile.
	lua_pushnil(L);
	lua_setglobal(L, "dofile");
	lua_pushnil(L);
	lua_setglobal(L, "loadfile");

	// Store the error handler.
	cmd_log_ << "Adding error handler...\n";
	push_error_handler(L);

	// Create the gettext metatable.
	cmd_log_ << lua_common::register_gettext_metatable(L);

	// Create the tstring metatable.
	cmd_log_ << lua_common::register_tstring_metatable(L);


	lua_settop(L, 0);

	// Define the CPP_function metatable ( so we can override print to point to a C++ member function, add "show_dialog" for this kernel, etc. )
	cmd_log_ << "Adding boost function proxy...\n";

	lua_cpp::register_metatable(L);

	// Add some callback from the wesnoth lib
	cmd_log_ << "Registering basic wesnoth API...\n";

	static luaL_Reg const callbacks[] = {
		{ "compare_versions",         &intf_compare_versions         		},
		{ "have_file",                &lua_fileops::intf_have_file          },
		{ "read_file",                &lua_fileops::intf_read_file          },
		{ "textdomain",               &lua_common::intf_textdomain   		},
		{ "tovconfig",                &lua_common::intf_tovconfig		},
		{ "get_dialog_value",         &lua_gui2::intf_get_dialog_value		},
		{ "set_dialog_active",        &lua_gui2::intf_set_dialog_active		},
		{ "set_dialog_visible",       &lua_gui2::intf_set_dialog_visible    },
		{ "add_dialog_tree_node",     &lua_gui2::intf_add_dialog_tree_node	},
		{ "set_dialog_callback",      &lua_gui2::intf_set_dialog_callback	},
		{ "set_dialog_canvas",        &lua_gui2::intf_set_dialog_canvas		},
		{ "set_dialog_focus",         &lua_gui2::intf_set_dialog_focus      },
		{ "set_dialog_markup",        &lua_gui2::intf_set_dialog_markup		},
		{ "set_dialog_value",         &lua_gui2::intf_set_dialog_value		},
		{ "remove_dialog_item",       &lua_gui2::intf_remove_dialog_item    },
		{ "dofile", 		      &dispatch<&lua_kernel_base::intf_dofile>           },
		{ "require", 		      &dispatch<&lua_kernel_base::intf_require>          },
		{ "show_dialog",	      &video_dispatch<lua_gui2::show_dialog>   },
		{ "show_menu",               &video_dispatch<lua_gui2::show_menu>  },
		{ "show_message_dialog",     &video_dispatch<lua_gui2::show_message_dialog> },
		{ "show_popup_dialog",       &video_dispatch<lua_gui2::show_popup_dialog>   },
		{ "show_lua_console",	      &dispatch<&lua_kernel_base::intf_show_lua_console> },
		{ "compile_formula",          &lua_formula_bridge::intf_compile_formula},
		{ "eval_formula",             &lua_formula_bridge::intf_eval_formula},
		{ "name_generator",           &intf_name_generator           },
		{ nullptr, nullptr }
	};

	lua_getglobal(L, "wesnoth");
	if (!lua_istable(L,-1)) {
		lua_newtable(L);
	}
	luaL_setfuncs(L, callbacks, 0);
	//lua_cpp::set_functions(L, cpp_callbacks, 0);
	lua_setglobal(L, "wesnoth");

	// Override the print function
	cmd_log_ << "Redirecting print function...\n";

	lua_getglobal(L, "print");
	lua_setglobal(L, "std_print"); //storing original impl as 'std_print'
	lua_settop(L, 0); //clear stack, just to be sure

	lua_pushcfunction(L, &dispatch<&lua_kernel_base::intf_print>);
	lua_setglobal(L, "print");

	// Create the package table.
	lua_getglobal(L, "wesnoth");
	lua_newtable(L);
	lua_setfield(L, -2, "package");
	lua_pop(L, 1);

	// Get some callbacks for map locations
	cmd_log_ << "Adding map_location table...\n";

	static luaL_Reg const map_callbacks[] = {
		{ "get_direction",		&lua_map_location::intf_get_direction         		},
		{ "vector_sum",			&lua_map_location::intf_vector_sum			},
		{ "vector_negation",		&lua_map_location::intf_vector_negation			},
		{ "zero",			&lua_map_location::intf_vector_zero			},
		{ "rotate_right_around_center",	&lua_map_location::intf_rotate_right_around_center	},
		{ "tiles_adjacent",		&lua_map_location::intf_tiles_adjacent			},
		{ "get_adjacent_tiles",		&lua_map_location::intf_get_adjacent_tiles		},
		{ "distance_between",		&lua_map_location::intf_distance_between		},
		{ "get_in_basis_N_NE",		&lua_map_location::intf_get_in_basis_N_NE		},
		{ "get_relative_dir",		&lua_map_location::intf_get_relative_dir		},
		{ "parse_direction",		&lua_map_location::intf_parse_direction			},
		{ "write_direction",		&lua_map_location::intf_write_direction			},
		{ nullptr, nullptr }
	};

	// Create the map_location table.
	lua_getglobal(L, "wesnoth");
	lua_newtable(L);
	luaL_setfuncs(L, map_callbacks, 0);
	lua_setfield(L, -2, "map_location");
	lua_pop(L, 1);

	// Add mersenne twister rng wrapper
	cmd_log_ << "Adding rng tables...\n";
	lua_rng::load_tables(L);

	cmd_log_ << "Adding name generator metatable...\n";
	luaL_newmetatable(L, Gen);
	static luaL_Reg const generator[] = {
		{ "__call", &impl_name_generator_call},
		{ "__gc", &impl_name_generator_collect},
		{ nullptr, nullptr}
	};
	luaL_setfuncs(L, generator, 0);

	// Create formula bridge metatables
	cmd_log_ << lua_formula_bridge::register_metatables(L);

	// Loading ilua:
	cmd_log_ << "Loading ilua...\n";

	lua_settop(L, 0);
	lua_pushstring(L, "lua/ilua.lua");
	int result = intf_require(L);
	if (result == 1) {
		//run "ilua.set_strict()"
		lua_pushstring(L, "set_strict");
		lua_gettable(L, -2);
		if (!protected_call(0,0, std::bind(&lua_kernel_base::log_error, this, _1, _2))) {
			cmd_log_ << "Failed to activate strict mode.\n";
		} else {
			cmd_log_ << "Activated strict mode.\n";
		}

		lua_setglobal(L, "ilua"); //save ilua table as a global
	} else {
		cmd_log_ << "Error: failed to load ilua.\n";
	}
	lua_settop(L, 0);
}
Example #13
0
int luaopen_normalize(lua_State *L) {
	luaL_openlib(L, "normalize", normalize, 0);
	lua_getfield(L, -1, "normalize");
	lua_setglobal(L, "normalize");
	return(0);
}
Example #14
0
void ScriptController::setUnsignedShort(const char* name, unsigned short v)
{
    lua_pushunsigned(_lua, v);
    lua_setglobal(_lua, name);
}
Example #15
0
ERROR_CODE _send_response_handler_lua(struct http_parser_t *http_parser) {
    /* retrieves the connection from the HTTP parser parameters */
    struct connection_t *connection = (struct connection_t *) http_parser->parameters;

    /* retrieves the HTTP connection from the io connection and uses it to retrieve
    the correct (mod Lua) handler to operate around it */
    struct http_connection_t *http_connection = (struct http_connection_t *) ((struct io_connection_t *) connection->lower)->lower;
    struct mod_lua_http_handler_t *mod_lua_http_handler = (struct mod_lua_http_handler_t *) http_connection->http_handler->lower;

    /* allocates space for the result code */
    ERROR_CODE result_code;

    /* acquires the lock on the HTTP connection, this will avoids further
    messages to be processed, no parallel request handling problems */
    http_connection->acquire(http_connection);

    /* in case the Lua state is not started an error must
    have occured so need to return immediately in error */
    if(mod_lua_http_handler->lua_state == NULL) {
        /* writes the error to the connection and then returns
        in error to the caller function */
        _write_error_connection_lua(http_parser, "no Lua state available");
        RAISE_ERROR_M(RUNTIME_EXCEPTION_ERROR_CODE, (unsigned char *) "Problem accessing Lua state");
    }

    /* registers the current connection in Lua */
    lua_pushlightuserdata(mod_lua_http_handler->lua_state, (void *) http_parser);
    lua_setglobal(mod_lua_http_handler->lua_state, "connection");

    /* registers the write connection function in Lua */
    lua_register(mod_lua_http_handler->lua_state, "write_connection", _lua_write_connection);

    /* runs the script in case the current file is considered to be
    dirty, this is the case for the loading of the module and reloading*/
    if(mod_lua_http_handler->file_dirty) { result_code = luaL_dofile(mod_lua_http_handler->lua_state, mod_lua_http_handler->file_path); mod_lua_http_handler->file_dirty = 0; }
    else { result_code = 0; }

    /* in case there was an error in Lua */
    if(LUA_ERROR(result_code)) {
        /* retrieves the error message and then writes it to the connection
        so that the end user may be able to respond to it */
        char *error_message = (char *) lua_tostring(mod_lua_http_handler->lua_state, -1);
        _write_error_connection_lua(http_parser, error_message);

        /* sets the file as dirty (forces reload) and then reloads the curernt
        internal Lua state, virtual machine reset (to avoid corruption) */
        mod_lua_http_handler->file_dirty = 1;
        _reload_lua_state(&mod_lua_http_handler->lua_state);

        /* prints a warning message, closes the Lua interpreter and then
        raises the error to the upper levels */
        V_WARNING_F("There was a problem executing: %s\n", mod_lua_http_handler->file_path);
        RAISE_ERROR_M(RUNTIME_EXCEPTION_ERROR_CODE, (unsigned char *) "Problem executing script file");
    }

    /* retrieves the field reference to the handle method that symbol
    to call the function (in protected mode) and retrieves the result */
    lua_getfield(mod_lua_http_handler->lua_state, LUA_GLOBALSINDEX, "handle");
    result_code = lua_pcall(mod_lua_http_handler->lua_state, 0, 0, 0);

    /* in case there was an error in Lua */
    if(LUA_ERROR(result_code)) {
        /* retrieves the error message and then writes it to the connection
        so that the end user may be able to respond to it */
        char *error_message = (char *) lua_tostring(mod_lua_http_handler->lua_state, -1);
        _write_error_connection_lua(http_parser, error_message);

        /* sets the file reference as dirty, this will force the script file
        to be reload on next request */
        mod_lua_http_handler->file_dirty = 1;

        /* prints a warning message, closes the Lua interpreter and then
        raises the error to the upper levels */
        V_WARNING_F("There was a problem running call on file: %s\n", mod_lua_http_handler->file_path);
        RAISE_ERROR_M(RUNTIME_EXCEPTION_ERROR_CODE, (unsigned char *) "Problem calling the handle method");
    }

    /* raise no error */
    RAISE_NO_ERROR;
}
Example #16
0
void ScriptController::setUnsignedLong(const char* name, unsigned long v)
{
    lua_pushunsigned(_lua, v);
    lua_setglobal(_lua, name);
}
Example #17
0
void merger_open_api( lua_State *L )
{
   /* Create the map interface. */
   lua_newuserdata( L, sizeof(void*) );
   
   /* Create the metatable for it. */
   lua_newtable( L );
   lua_pushcfunction( L, merger_map_index );
   lua_setfield( L, -2, "__index" );
   lua_pushcfunction( L, merger_map_newindex );
   lua_setfield( L, -2, "__newindex" );
   
   lua_setmetatable( L, -2 );
   
   lua_setglobal( L, "map" );
   
   /* Create the rooms[] interface. */
   lua_newuserdata( L, sizeof(void*) );
   
   /* Create the metatable for it. */
   lua_newtable( L );
   lua_pushcfunction( L, merger_rooms_index );
   lua_setfield( L, -2, "__index" );
   
   lua_setmetatable( L, -2 );
   lua_setglobal( L, "rooms" );
   
   /* Create the room metatable, and store it for later use. */
   lua_newtable( L );
   lua_pushcfunction( L, merger_room_index );
   lua_setfield( L, -2, "__index" );
   lua_pushcfunction( L, merger_room_equality );
   lua_setfield( L, -2, "__eq" );
   
   lua_setfield( L, LUA_REGISTRYINDEX, "merger_room_metatable" );
   
   /* Create the exits metatable. */
   lua_newtable( L );
   lua_pushcfunction( L, merger_exits_index );
   lua_setfield( L, -2, "__index" );
   lua_pushcfunction( L, merger_exits_call );
   lua_setfield( L, -2, "__call" );
   
   lua_setfield( L, LUA_REGISTRYINDEX, "merger_exits_metatable" );
   
   /* Create the exit metatable. */
   lua_newtable( L );
   lua_pushcfunction( L, merger_exit_index );
   lua_setfield( L, -2, "__index" );
   
   lua_setfield( L, LUA_REGISTRYINDEX, "merger_exit_metatable" );
   
   /* Create the special exits metatable. */
   lua_newtable( L );
   lua_pushcfunction( L, merger_spexits_index );
   lua_setfield( L, -2, "__index" );
   lua_pushcfunction( L, merger_spexits_call );
   lua_setfield( L, -2, "__call" );
   
   lua_setfield( L, LUA_REGISTRYINDEX, "merger_spexits_metatable" );
   
   /* Create the special exit metatable. */
   lua_newtable( L );
   lua_pushcfunction( L, merger_spexit_index );
   lua_setfield( L, -2, "__index" );
   
   lua_setfield( L, LUA_REGISTRYINDEX, "merger_spexit_metatable" );
   
   /* Create area metatable. */
   lua_newtable( L );
   lua_pushcfunction( L, merger_area_index );
   lua_setfield( L, -2, "__index" );
   
   lua_setfield( L, LUA_REGISTRYINDEX, "merger_area_metatable" );
   
   /* Create environment metatable. */
   lua_newtable( L );
   lua_pushcfunction( L, merger_environment_index );
   lua_setfield( L, -2, "__index" );
   
   lua_setfield( L, LUA_REGISTRYINDEX, "merger_environment_metatable" );
}
Example #18
0
void ScriptController::setDouble(const char* name, double v)
{
    lua_pushnumber(_lua, v);
    lua_setglobal(_lua, name);
}
Example #19
0
void ScriptUtil::registerClass(const char* name, const luaL_Reg* members, lua_CFunction newFunction, 
    lua_CFunction deleteFunction, const luaL_Reg* statics,  const std::vector<std::string>& scopePath)
{
    ScriptController* sc = Game::getInstance()->getScriptController();

    // If the type is an inner type, get the correct parent 
    // table on the stack before creating the table for the class.
    if (!scopePath.empty())
    {
        std::string tablename = name;

        // Strip off the scope path part of the name.
        lua_getglobal(sc->_lua, scopePath[0].c_str());
        std::size_t index = tablename.find(scopePath[0]);
        if (index != std::string::npos)
            tablename = tablename.substr(index + scopePath[0].size());
        
        for (unsigned int i = 1; i < scopePath.size(); i++)
        {
            lua_pushstring(sc->_lua, scopePath[i].c_str());
            lua_gettable(sc->_lua, -2);

            index = tablename.find(scopePath[i]);
            if (index != std::string::npos)
                tablename = tablename.substr(index + scopePath[i].size());
        }

        lua_pushstring(sc->_lua, tablename.c_str());
        lua_newtable(sc->_lua);
    }
    else
    {
        // If the type is not an inner type, set it as a global table.
        lua_newtable(sc->_lua);
        lua_pushvalue(sc->_lua, -1);
        lua_setglobal(sc->_lua, name);
    }
    
    // Create the metatable and populate it with the member functions.
    lua_pushliteral(sc->_lua, "__metatable");
    luaL_newmetatable(sc->_lua, name);
    if (members)
        luaL_setfuncs(sc->_lua, members, 0);
    lua_pushstring(sc->_lua, "__index");
    lua_pushvalue(sc->_lua, -2);
    lua_settable(sc->_lua, -3);

    // Add the delete function if it was specified.
    if (deleteFunction)
    {
        lua_pushstring(sc->_lua, "__gc");
        lua_pushcfunction(sc->_lua, deleteFunction);
        lua_settable(sc->_lua, -3);
    }

    // Set the metatable on the main table.
    lua_settable(sc->_lua, -3);
    
    // Populate the main table with the static functions.
    if (statics)
        luaL_setfuncs(sc->_lua, statics, 0);

    // Set the new function(s) for the class.
    if (newFunction)
    {
        lua_pushliteral(sc->_lua, "new");
        lua_pushcfunction(sc->_lua, newFunction);
        lua_settable(sc->_lua, -3);
    }

    // Set the table we just created within the correct parent table.
    if (!scopePath.empty())
    {
        lua_settable(sc->_lua, -3);

        // Pop all the parent tables off the stack.
        int size = scopePath.size();
        lua_pop(sc->_lua, size);
    }
    else
    {
        // Pop the main table off the stack.
        lua_pop(sc->_lua, 1);
    }
}
static void
registerCFunction(lua_State* L, const char* name, lua_CFunction func)
{
	lua_pushcfunction(L, func);
	lua_setglobal(L, name);
}
Example #21
0
void ScriptUtil::registerFunction(const char* luaFunction, lua_CFunction cppFunction)
{
    lua_pushcfunction(Game::getInstance()->getScriptController()->_lua, cppFunction);
    lua_setglobal(Game::getInstance()->getScriptController()->_lua, luaFunction);
}
Example #22
0
int luaopen_combine( lua_State *L) {
  lua_pushcfunction( L, lua_combine);
  lua_setglobal( L, "combine");
  return 0;
}
Example #23
0
void ScriptController::setBool(const char* name, bool v)
{
    lua_pushboolean(_lua, v);
    lua_setglobal(_lua, name);
}
Example #24
0
int
main(int argc, char **argv)
{
	int	ch;
	const char	*scriptpath = "/tmp/test.lua";

	log_init(-1);

	log_debug("debug: filter-lua: args: %s", argv[1]);
	while ((ch = getopt(argc, argv, "")) != -1) {
		switch (ch) {
		default:
			log_warnx("warn: filter-lua: bad option");
			return (1);
			/* NOTREACHED */
		}
	}
	argc -= optind;
	argv += optind;

	log_debug("debug: filter-lua: starting...");

	if ((L = luaL_newstate()) == NULL) {
		log_warnx("warn: filter-lua: can't create lua state");
		return (1);
	}
	luaL_openlibs(L);
	luaL_newlib(L, l_filter);
	luaL_newmetatable(L, "filter");
	lua_setmetatable(L, -2);

	lua_pushnumber(L, FILTER_OK);
	lua_setfield(L, -2, "FILTER_OK");
	lua_pushnumber(L, FILTER_FAIL);
	lua_setfield(L, -2, "FILTER_FAIL");
	lua_pushnumber(L, FILTER_CLOSE);
	lua_setfield(L, -2, "FILTER_CLOSE");

	lua_setglobal(L, "filter");

	if (luaL_loadfile(L, scriptpath) != 0) {
		log_warnx("warn: filter-lua: error loading script: %s", scriptpath);
		return (1);
	}

	if (lua_pcall(L, 0, 0, 0)) {
		log_warnx("warn: filter-lua: error running script: %s", scriptpath);
		return (1);
	}

	lua_getglobal(L, "on_connect");
	if (lua_isfunction(L, 1)) {
		log_debug("debug: filter-lua: on_connect is present");
		filter_api_on_connect(on_connect);
	}
	lua_getglobal(L, "on_helo");
	if (lua_isfunction(L, 1)) {
		log_debug("debug: filter-lua: on_helo is present");
		filter_api_on_helo(on_helo);
	}
	lua_getglobal(L, "on_mail");
	if (lua_isfunction(L, 1)) {
		log_debug("debug: filter-lua: on_mail is present");
		filter_api_on_mail(on_mail);
	}
	lua_getglobal(L, "on_rcpt");
	if (lua_isfunction(L, 1)) {
		log_debug("debug: filter-lua: on_rcpt is present");
		filter_api_on_rcpt(on_rcpt);
	}
	lua_getglobal(L, "on_data");
	if (lua_isfunction(L, 1)) {
		log_debug("debug: filter-lua: on_data is present");
		filter_api_on_data(on_data);
	}
	lua_getglobal(L, "on_eom");
	if (lua_isfunction(L, 1)) {
		log_debug("debug: filter-lua: on_eom is present");
		filter_api_on_eom(on_eom);
	}

	filter_api_loop();

	log_debug("debug: filter-lua: exiting");

	return (0);
}
Example #25
0
void ScriptController::setInt(const char* name, int v)
{
    lua_pushinteger(_lua, v);
    lua_setglobal(_lua, name);
}
Example #26
0
void luasrc_LoadWeapons (const char *path)
{
	FileFindHandle_t fh;

	if ( !path )
	{
		path = "";
	}

	char root[ MAX_PATH ] = { 0 };

	char filename[ MAX_PATH ] = { 0 };
	char fullpath[ MAX_PATH ] = { 0 };
	char className[ MAX_WEAPON_STRING ] = { 0 };

	Q_snprintf( root, sizeof( root ), "%s" LUA_PATH_WEAPONS "\\*", path );

	char const *fn = g_pFullFileSystem->FindFirstEx( root, "MOD", &fh );
	while ( fn )
	{
		Q_strcpy( className, fn );
		Q_strlower( className );
		if ( fn[0] != '.' )
		{
			if ( g_pFullFileSystem->FindIsDirectory( fh ) )
			{
#ifdef CLIENT_DLL
				Q_snprintf( filename, sizeof( filename ), "%s" LUA_PATH_WEAPONS "\\%s\\cl_init.lua", path, className );
#else
				Q_snprintf( filename, sizeof( filename ), "%s" LUA_PATH_WEAPONS "\\%s\\init.lua", path, className );
#endif
				if ( filesystem->FileExists( filename, "MOD" ) )
				{
					filesystem->RelativePathToFullPath( filename, "MOD", fullpath, sizeof( fullpath ) );
					lua_newtable( L );
					char entDir[ MAX_PATH ];
					Q_snprintf( entDir, sizeof( entDir ), "weapons\\%s", className );
					lua_pushstring( L, entDir );
					lua_setfield( L, -2, "__folder" );
					lua_pushstring( L, LUA_BASE_WEAPON );
					lua_setfield( L, -2, "__base" );
					lua_setglobal( L, "SWEP" );
					if ( luasrc_dofile( L, fullpath ) == 0 )
					{
						lua_getglobal( L, "weapon" );
						if ( lua_istable( L, -1 ) )
						{
							lua_getfield( L, -1, "register" );
							if ( lua_isfunction( L, -1 ) )
							{
								lua_remove( L, -2 );
								lua_getglobal( L, "SWEP" );
								lua_pushstring( L, className );
								luasrc_pcall( L, 2, 0, 0 );
								RegisterScriptedWeapon( className );
							}
							else
							{
								lua_pop( L, 2 );
							}
						}
						else
						{
							lua_pop( L, 1 );
						}
					}
					lua_pushnil( L );
					lua_setglobal( L, "SWEP" );
				}
			}
		}

		fn = g_pFullFileSystem->FindNext( fh );
	}
	g_pFullFileSystem->FindClose( fh );
}
//---------------------------------------------------------------------
// ● コンストラクタ
//---------------------------------------------------------------------
CharacterScriptInterface::CharacterScriptInterface()
{
    for ( int i = 0; i < WEAPON_MAX_NUM; ++i )
    {
        mLuaStates[ i ] = NULL;

        if ( CharaResourceNames[ i ].Script )
        {
        
            lua_State* l = luaL_newstate();
            luaopen_base( l );
            luaL_openlibs( l );
            if ( luaL_dofile( l, CharaResourceNames[ i ].Script ) )
            {
                assert( 0, "スクリプトのエラー:\n\n%s", lua_tostring( l, lua_gettop( l ) ) );
            }

            // グローバル変数 (定数) の登録

            // キャラクターの状態
	        lua_pushnumber( l, CHARASTATE_WAIT );   // 値
	        lua_setglobal( l, "CHARASTATE_WAIT" );  // 変数名
            lua_pushnumber( l, CHARASTATE_RUN );
	        lua_setglobal( l, "CHARASTATE_RUN" );
            lua_pushnumber( l, CHARASTATE_JUMP );
	        lua_setglobal( l, "CHARASTATE_JUMP" );
            lua_pushnumber( l, CHARASTATE_SQUAT );
	        lua_setglobal( l, "CHARASTATE_SQUAT" );
            lua_pushnumber( l, CHARASTATE_STUN );
	        lua_setglobal( l, "CHARASTATE_STUN" );
            lua_pushnumber( l, CHARASTATE_BLOW );
	        lua_setglobal( l, "CHARASTATE_BLOW" );
            lua_pushnumber( l, CHARASTATE_SQUAT );
	        lua_setglobal( l, "CHARASTATE_SQUAT" );
            lua_pushnumber( l, CHARASTATE_GUARD );
	        lua_setglobal( l, "CHARASTATE_GUARD" );
            lua_pushnumber( l, CHARASTATE_SQUAT );
	        lua_setglobal( l, "CHARASTATE_SQUAT" );
            lua_pushnumber( l, CHARASTATE_SQGUARD );
	        lua_setglobal( l, "CHARASTATE_SQGUARD" );
            lua_pushnumber( l, CHARASTATE_LADDER_WAIT );
	        lua_setglobal( l, "CHARASTATE_LADDER_WAIT" );
            lua_pushnumber( l, CHARASTATE_LADDER_UP );
	        lua_setglobal( l, "CHARASTATE_LADDER_UP" );
            lua_pushnumber( l, CHARASTATE_LADDER_DOWN );
	        lua_setglobal( l, "CHARASTATE_LADDER_DOWN" );
            lua_pushnumber( l, CHARASTATE_ITENGET );
	        lua_setglobal( l, "CHARASTATE_ITENGET" );
            lua_pushnumber( l, CHARASTATE_DEAD );
	        lua_setglobal( l, "CHARASTATE_DEAD" );
            lua_pushnumber( l, CHARASTATE_ATTACK_1 );
	        lua_setglobal( l, "CHARASTATE_ATTACK_1" );
            lua_pushnumber( l, CHARASTATE_ATTACK_2 );
	        lua_setglobal( l, "CHARASTATE_ATTACK_2" );
            lua_pushnumber( l, CHARASTATE_ATTACK_3 );
	        lua_setglobal( l, "CHARASTATE_ATTACK_3" );
            lua_pushnumber( l, CHARASTATE_ATTACK_SQUAT_ATTACK );
	        lua_setglobal( l, "CHARASTATE_ATTACK_SQUAT_ATTACK" );
            lua_pushnumber( l, CHARASTATE_ATTACK_JUMP_ATTACK );
	        lua_setglobal( l, "CHARASTATE_ATTACK_JUMP_ATTACK" );
            lua_pushnumber( l, CHARASTATE_ATTACK_ANTIAIR_ATTACK );
	        lua_setglobal( l, "CHARASTATE_ATTACK_ANTIAIR_ATTACK" );
            lua_pushnumber( l, CHARASTATE_ATTACK_DUSH_ATTACK );
	        lua_setglobal( l, "CHARASTATE_ATTACK_DUSH_ATTACK" );

            // 攻撃対象グループ
            lua_pushnumber( l, ATKGROUP_PLAYER );
	        lua_setglobal( l, "ATKGROUP_PLAYER" );
            lua_pushnumber( l, ATKGROUP_ENEMY );
	        lua_setglobal( l, "ATKGROUP_ENEMY" );
            lua_pushnumber( l, ATKGROUP_ALL );
	        lua_setglobal( l, "ATKGROUP_ALL" );

        // 関数の登録
        lua_register( l, "getCharaAttackedGroup",   getCharaAttackedGroup );
		lua_register( l, "getCharaPosition",        getCharaPosition );
        lua_register( l, "setCharaState",           setCharaState );
        lua_register( l, "setFrameCount",           setFrameCount );
        lua_register( l, "setPuttern",              setPuttern );
        lua_register( l, "judgeAttackCollision",    judgeAttackCollision );
        lua_register( l, "attackEffect",            attackEffect );
        lua_register( l, "disposeObject",           disposeObject );
		lua_register( l, "AttackLock",				AttackLock );
		lua_register( l, "AttackUnLock",			AttackUnLock );
		lua_register( l, "getOnGround",             getOnGround );
		lua_register( l, "PlaySE",			        PlaySE );
		lua_register( l, "CreateEffect",		    CreateEffect );
		lua_register( l, "PlaySE",			PlaySE );
		lua_register( l, "CreateEffect",			CreateEffect );
		lua_register( l, "setVelocity",				setVelocity );
		lua_register( l, "CheckWeaponBreak",		CheckWeaponBreak );
		lua_register( l, "setBreakWeapon",			setBreakWeapon );
		lua_register( l, "getBreakWeapon",			getBreakWeapon );
		lua_register( l, "setDirection",			setDirection );
		lua_register( l, "setPosition",			    setPosition );
		lua_register( l, "GrenadeGenerate",			GrenadeGenerate );
		lua_register( l, "BulletGenerate",			BulletGenerate );
		lua_register( l, "setInvincibleFrame",     setInvincibleFrame);
		lua_register( l, "getLife",                getLife);
		lua_register( l, "getMaxLife",     getMaxLife);
		lua_register( l,"setLife",            setLife);
		lua_register( l, "setAccel",               setAccel);
		lua_register( l, "getDirection",           getDirection);
		lua_register( l, "getRank",               getRank);
		lua_register( l, "getPlayerPos",               getPlayerPos);
		lua_register( l, "Rand",               Rand);
		lua_register(l,"getPhase", getPhase);
		lua_register(l,"getNum", getNum);
		lua_register(l,"setNum", setNum);
		lua_register(l ,"SummonEnemy",SummonEnemy);
		lua_register(l ,"Division",Division);
		lua_register(l ,"SetOpacity",SetOpacity);
		lua_register(l ,"SetDestructfrag",SetDestructfrag);
		lua_register(l ,"GetDestructfrag",GetDestructfrag);
		lua_register(l ,"ThunderGenerate",ThunderGenerate);
		lua_register(l ,"SummonSoul",SummonSoul);
            mLuaStates[ i ]  = l;
        }
    }
}