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.22k stars 517 forks source link

How to pass NULL to a function in Lua? #1343

Closed GreedyTactician closed 2 years ago

GreedyTactician commented 2 years ago

nil doesn't work. 0 doesn't work.

Putting NULL in a variable in Lua just gives me 0

Rochet2 commented 2 years ago

You should likely use nullptr instead, as NULL is usually defined just as 0. And nil should work. Unsure what the issue with nil is that you have, as it seems to work for me. Also unsure if you are trying to pass data from lua to C++ or the other way around.

But here are some examples of both https://godbolt.org/z/anrMcfrbb

#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>

struct Test {
};

int main() {
    sol::state lua;
    lua.open_libraries();

    lua["f"] = [](Test* t) { return t == nullptr; };
    // lua.script("print(f())"); // error: expected userdata, received no value
    lua.script("print(f(nil))"); // true

    lua["n"] = nullptr;
    lua.script("print(n == nil)"); // true
    lua["n"] = sol::nil;
    lua.script("print(n == nil)"); // true
    lua["n"] = NULL;
    lua.script("print(n == nil)"); // false
    return 0;
}

Some relevant docs: https://sol2.readthedocs.io/en/latest/api/types.html https://sol2.readthedocs.io/en/latest/tutorial/ownership.html?highlight=nullptr#pointer-lifetime-nil https://sol2.readthedocs.io/en/latest/functions.html?highlight=nullptr#functions-and-argument-passing

GreedyTactician commented 2 years ago

No, you are right, it totally works.

I was trying it on const char*, but I realize now the library probably treats that differently. And one can use empty strings as they are nearly the same thing.