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.25k stars 519 forks source link

How to secure such a pointer? #1615

Open tangjiands opened 4 months ago

tangjiands commented 4 months ago

class Base { public: virtual void print() { std::cout << "base print:" << x << endl; } private: int x; };

class A: public Base { public: void print() override { std::cout << "A print:" << y << endl; } private: int y; };

class C { public: void print() { std::cout << "B print:" << z << endl; } private: int z; }; void funcBase(Base* base) { return base->print(); }

A a;
C c;
Base base;
sol::state lua;
luaL_openlibs(lua); 

lua.new_usertype<Base>(
    "Base");
lua.new_usertype<A>(
    "A", sol::base_classes, sol::bases<Base>());
lua["base"] = &base;
lua["a"] = &a;
lua["c"] = &c;
lua.safe_script("function startup() return funcBase(b) end");
// set funcBase
lua.set_function("funcBase", funcBase);
**//An error parameter &c was passed**
lua["funcBase"](&c);
deadlocklogic commented 1 month ago

Please next time use a correctly formatted snippet in markdown, filtering all unused code so we can assist you better.

The call to lua["funcBase"](&c); returns a sol::protected_function_result. You can then check if this result was valid yourself like:

auto res = lua["funcBase"](&c);
if (!res.valid()) {
    std::cout << "error occured!" << std::endl;
}

To make this call automatically print the error result you can call it from a protected function:

sol::protected_function protected_function(
    lua["funcBase"], [](std::string message) {
        std::cout << "error occurred : " << message << std::endl;
    });
protected_function(&c);