Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
lukasm121 opened this issue Mar 16, 2022 · 0 comments
Open

Comments

@lukasm121
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant