sol2 icon indicating copy to clipboard operation
sol2 copied to clipboard

empty sol::this_environment in method when called from function in lua

Open lukasm121 opened this issue 3 years ago • 0 comments

I get an empty sol::this_environment when method is called from lua function where object is passed as argument.

When it's called directly from container that is binded to sol it works fine, but when method is called from function where object is passed as argument, sol::this_environment is empty. One way to fix this is to call some global variable or function before calling this method. I don't know why but this seems to fix the issue.

Here is minimum example. I have objects in a map that is binded to Lua.

#include "sol/sol.hpp"

class C
{
public:
    C(uint32_t id) : id(id)
    {
    }

    void func(const sol::this_state& s, const sol::this_environment& e)
    {
        std::cout << "Env " << (e ? "OK!" : "EMPTY!") << std::endl;
    }

    void func2(const std::string& param, const sol::this_state& s, const sol::this_environment& e)
    {
        std::cout << "Env " << (e ? "OK! " : "EMPTY! ") << param <<  std::endl;
    }

private:
    uint32_t id;
};

using ObjectCollection = std::unordered_map<uint32_t, C>;

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

    sol::environment environment{state, sol::create};

    environment.new_usertype<C>("C",
        "func", &C::func,
        "func2", &C::func2
    );

    ObjectCollection objects{};
    objects.insert({1, C{1}});

    environment["objects"] = objects;

    const std::string code = R"(
    function test1(ob)
        ob:func()
        ob:func2("from test1")
    end

    function test2(ob)
        objects[1]:func()  -- this call fixes the problem in test2 function
        ob:func()
        ob:func2("from test2")
    end

    test1(objects[1])
    test2(objects[1])
    test1(objects[1])
    )";

    state.script(code, environment);
    return 0;
}

Here is output from code above

Env EMPTY!
Env EMPTY! from test1
Env OK!
Env OK!
Env OK! from test2
Env EMPTY!
Env EMPTY! from test1

I use gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0 lua version 5.3 sol single file from latest develop branch 50b62c93 halx99 Sun Dec 12 00:51:19 2021 +0800 Add missing parenthesis for std::max

Compile command

gcc lua_example.cpp -o lua_example -Isol2/single/include -I/usr/include/lua5.3 -DSOL_USING_CXX_LUA -O0 -std=c++17 -llua5.3 -lstdc++ -lm

lukasm121 avatar Mar 16 '22 16:03 lukasm121