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

How to return anything from a function in Sol3? #1557

Closed GasimGasimzada closed 7 months ago

GasimGasimzada commented 7 months ago

I want to create the following interface:

local entity_query = game:get("EntityQuery")
local entity_spawner = game:get("EntitySpawner")

To make the code more maintainable, I want to create a function that returns anything and internall, return the needed user types and tables:

sol::object GameLuaTable::get(String name) {
  // I am planning to dynamically identify all these services
  // using some form of map
  if (name == "EntityQuery") {
    return EntityQueryLuaTable(state);
  }

  if (name == "EntitySpawner") {
    return EntitySpawnerLuaTable(state);
  }

  // ...
}

Currently, I need to return std::variadic for this but I do not want to think about this part and want to just return anything. Is it possible to do it in Sol?

Rochet2 commented 7 months ago

If you dont want to explicitly declare the return types with std::variant (which should also work AFAIK), you can create a sol::object with sol::make_object(lua, anything_here). And you can get lua from within a function bound with sol by using sol::this_state. Here is an example that should work

struct Foo {};

sol::object exampleFunction(sol::this_state const& s, int value)
{
    sol::state_view lua(s);
    if (value == 1)
        return sol::make_object(lua, "something");
    if (value == 2)
        return sol::make_object(lua, 123);
    if (value == 3)
        return sol::make_object(lua, Foo());
    return sol::make_object(lua, sol::lua_nil);
}
GasimGasimzada commented 7 months ago

Thank you!