Selene icon indicating copy to clipboard operation
Selene copied to clipboard

How to override lua print

Open Zardoz89 opened this issue 9 years ago • 2 comments

I'm trying to override lua print function, so I could redirect output to my console window . I end discovering that I get a null pointer :

auto print = [](const char* str) {
  spdlog::get("console_log")->info("str = {}", str != nullptr); // prints "str = false"
};
this->state["print"] = print;

Also, I try to this that I read on stack overflow :

auto print = [](lua_State* L) {
  int nargs = lua_gettop(L);

  for (int i = 1; i <= nargs; i++) {
    if (lua_isstring(L, i)) {
      /* Pop the next arg using lua_tostring(L, i) and do your print */
      const char *msg = lua_tostring(L, i);
      if (msg != nullptr) {
        spdlog::get("console_log")->info("str = {}", msg);
      }
    } else {
      /* Do something with non-strings if you like */
    }
  }
};
this->state["print"] = print;

Were I get a crash, because L is a null pointer. What is the correct way of override Lua print function from C++

PD: Lua test script (onUpdate called by C++) :

-- test.lua
foo = 4
bar = {}
bar[3] = "hi"
bar["key"] = "there"

function onUpdate(delta)
    print("Hello")
end

Zardoz89 avatar Oct 13 '15 18:10 Zardoz89

I just try something more dumb :

            auto print = [](std::string str) {
                spdlog::get("console_log")->info(str);
            };
            this->state["print"] = print;

Works and autoconvert to string but only gets the first parameter of a call to print. Selene could use variadic lambdas or functors ?

Zardoz89 avatar Oct 13 '15 21:10 Zardoz89

The L is a null, since selene automaps all c++ types to lua. I got it working by binding a lua library and requiring said library: https://github.com/madeso/selene-test/blob/master/test_custom_print.cc

There is a sel::BaseFun functor in selene/BaseFun.h that all bindings seems to use as a base, but I haven't found a way to bind my custom BaseFun to my sel::State.

This will however only remove some C api stuff, variadic lambdas seems the API way to go, but my c++ knowledge is lacking to know if can be, and how that should be exposed.

madeso avatar Jan 01 '16 14:01 madeso