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 493 forks source link

Calling a Lua function from C++ with any number and multiple types of arguments #1479

Closed UltraEngine closed 1 year ago

UltraEngine commented 1 year ago

I'm working on the new implementation of our component flowgraph for Lua:

I want to add user-defined arguments to the connections so that when a function is triggered, any arguments can be supplied to it.

I found a way to use as_args to handle a variable number of arguments, but they have to be the same type: https://github.com/ThePhD/sol2/issues/471

However, I want to account for mixed argument types. I am doing this in C++ with std::any. Is there a way to make this work with sol? I know this can be done with lua_pcall (I think) but I prefer to do things the sol way:

bool Component::CallMethod(std::string name, std::vector<std::any> args)
{
    state->push(this);
    LuaGetField(name.c_str());
    if (LuaIsFunction())
    {
        auto f = sol::protected_function(L);
        if (f.valid())
        {
            auto sol_args = ???

            for (int n = 0; n < args.size(); ++n)
            {
                std::string name = args]n].type().name();
                if (name == "int")
                {
                    sol_args.push_back(std::any_cast<int>(args[n]));
                }
                else if (name == "string")
                {
                    sol_args.push_back(std::any_cast<std::string>(args[n]));
                }
                else if (name == "shared_ptr<Object>")
                {
                    sol_args.push_back(std::any_cast<shared_ptr<Object>>(args[n]));
                }
                else
                {
                    sol_args.push_back(nullptr);
                }
            }
            f(this, sol_args);
        }
    }
}
UltraEngine commented 1 year ago

It's working fine using lua_pcall.