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.18k stars 515 forks source link

How can I create my own print function in Sol3? #1571

Closed GasimGasimzada closed 8 months ago

GasimGasimzada commented 8 months ago

I want to do two things in Sol3:

  1. Override print function
  2. Convert variadic arguments to string

I have a custom logger that I provide:

auto logger = state.create_table();
logger["debug"] = [](String message) {
  Engine::getUserLogger().debug() << message;
};

I want to make this function accept any argument and automatically convert those arguments to string:

logger["debug"] = [](sol::variadic_args args) {
  auto debug = Engine::getUserLogger().debug();

  for (auto arg: args) {
    debug << arg << " ";
  }
};

I also want to somehow make the global print to do the same:

state["print"] = SAME_FUNCTION_FOR_LOGGING;

Is this a valid way to override the print function?

GasimGasimzada commented 8 months ago

I figured out converting variadic args to string:

logger["debug"] = [](sol::variadic_args args) {
  auto debug = Engine::getUserLogger().debug();

  for (auto arg: args) {
    debug <<  state["tostring"](arg.get<sol::object>()).get<String>() << "\t";
  }
};

And I set the print function by just assigning it to state:

state.set_function("print", [](sol::variadic_args args) { ... });