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.06k stars 492 forks source link

Q: Lua function in C++ function arguments #1519

Closed shierru closed 10 months ago

shierru commented 10 months ago

Question

Hi, I would like to ask you how I could implement a C++ function accessible from Lua, to which I could "pass" another function?

Perhaps with an example it will be easier to understand:

funcLua = function() -- Lua function
    print("call testPrint")
end

test(funcLua) -- Call C++ function

On the C++ side it should be possible to call a Lua function passed through arguments.

Thanks in advance for your help!

Rochet2 commented 10 months ago
lua["test"] = [](sol::function funcLua) {
    return funcLua();
};

I believe it should be as easy as that. This code is C++ side code that defines test function to take in some kind of callable object (any function or object with __call metamethod) and then it calls it and returns the return value to the caller.

shierru commented 10 months ago

Man, this issue is useless from the start. I'm sorry!

Before my issue I first tried the option you suggested and it didn't work for me, throwing a "runtime error". And just now I found a completely stupid error ^_^

Thank you very much for your reply!