For easier to understand purposes I'm going to call modules that need to be loaded using require in garry's mod gmodules.
So normally to add C++ functions to lua you would have to make a gmodule. Well I didn't want to use that method because I don't want any modules in my garry's mod folder that garry or anyone else could scan/steal.
Normally you would have to do the following to add your functions. MyExampleFunction could be a necessary function for nospread or anything else you can't do with lua alone.
Code:
int MyExampleFunction( lua_State* state )
{
LUA->PushString( "This string is returned" );
return 1;
}
GMOD_MODULE_OPEN()
{
LUA->PushSpecial( GarrysMod::Lua::SPECIAL_GLOB );
LUA->PushString( "TestFunction" );
LUA->PushCFunction( MyExampleFunction );
LUA->SetTable( -3 );
return 0;
}
GMOD_MODULE_CLOSE()
{
return 0;
}
The method above requires you to add your gmodule using lua and garry can keep track of your module this way.
I found an alternative method that does not require that include a module in your lua code. You can instead inject your binary into garry's mod and it will do the same thing as above.
Code:
int MyExampleFunction( lua_State* state )
{
LUA->PushString( "This string is returned" );
return 1;
}
//Inside whatever hook or function you choose.
lua_State* L = g_Lua->GetLuaState(); // Get the lua state
lua_pushvalue( L, -10002 ); // Push the global tabl
lua_pushstring( L, "TestFunction" ); // Pus h the name of the function
lua_pushcfunction( L, MyExampleFunction ); // Push the function
lua_settable( L, -3 ); // Set the table
lua_pop( L, 1 ); // Pop the function off the stack so we don't get an error
Note: you can get all the lua_ function by using GetProcAddress.
If used properly, this code is extremely helpful. You can completely remove your need for gmodules. Hopefully someone finds this helpful. PM me if you need the index for GetLuaState.
Useful macros.
Code:
#define lua_pushcfunction(L,f) lua_pushcclosure(L, (f), 0)
#define lua_pop(L,n) lua_settop(L, -(n)-1)
#define lua_register(L,n,f) (lua_pushvalue(L, -10002), lua_pushstring(L, n), lua_pushcfunction(L, f), lua_settable(L, -3), lua_pop(L, 1))
#define LUA state->luabase