ThePhD / sol2

Sol3 (sol2 v3.0) - a C++ <-> Lua API wrapper with advanced features and top notch performance - is here, and it's great! Documentation:
http://sol2.rtfd.io/
MIT License
4.16k stars 504 forks source link

Contents of a lua function in c++ function #1390

Closed sizeoftrickster closed 2 years ago

sizeoftrickster commented 2 years ago

Hi all. Please help to implement such a thing. I need the content of one function to be passed to a hook.

function Handler() {
    print("!") -- For Example.
}
void GameloopHook() {
    // The same code that is specified in the lua function is passed here. Handler()
}
MJCollett commented 2 years ago

I think that writing an actual C-style function that did the job would require you to have the Lua state available as a global variable:

void GameloopHook() {
   sol::function(lua["Handler"])();
}

That's not nice. But you can make a function wrapper that takes care of it by just saying

sol::function gameloopHook{lua["Handler"]};

which only requires the Lua state to be available at the point of definition. The sol::function isn't a function pointer, but can be passed in anywhere a std::function<void()> is expected.
Alternatively, you can wrap the call in a lambda that captures the Lua state.