I have difficulty to explain this problem, but I'll do my best.
I'm trying to refactor my code, moving away from classes with only static members, to regular functions in a certain namespace. One of such is my "Script" class, which handles Lua scripting for the game I'm trying to write. I use an external library called 'Sol' for the binding between C++ and Lua. The Script class has a private sol::state. It was some template functions along with some other code which all work just fine, such as "RunFile()" to run some script file.
The problem I get, is that the template function to Register a function to Lua, gets called but somehow doesnt work. I'm using the Sol library, in which you can use: m_lua[functionName] = function; to register a function to Lua. If I type this hardcoded m_lua[PushEvent] = PushEvent; it still works.
class Script
{
private:
static sol::state m_lua;
...
template <typename T>
static void RegisterFunction(std::string functionName, T function);
};
template <typename T>
void Script::RegisterFunction(std::string functionName, T function)
{
m_lua[functionName] = function;
}
#include "Script.h"
sol::state Script::m_lua;
It works as I want, I can register a function to Lua using:
Script::RegisterFunction("PushEvent", Events::PushEvent);
For some reason, when I remove the class and put everything into a namespace Script instead of the class, and put the m_lua variable into an anonymous namespace, it no longer works:
<pre>
namespace Script
{
namespace {
static sol::state m_lua;
}
...
template <typename T>
void RegisterFunction(std::string functionName, T function)
{
m_lua[functionName] = function;
}
}
#include "Script.h"
sol::state Script::m_lua;
I don't understand this. I tought using regular functions rather then a class shouldn't make much of a difference.
The program compiles and links just fine, but the functions do not get registered to Lua, so I get a runtime error that it cannot find the function name (PushEvent for example). It really boils down to this RegisterFunction template, and I can not get my head around it why it shouldn't just work.
During debugging all the functions get called (m_lua[functionName] = function; gets executed when I walk over the code).
If anyone knows an answer it would be highly appreciated!
What I have tried:
Changing back to a class, which works fine.