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.12k stars 500 forks source link

sol::this_environment has no value (nullopt) when accessing from a metamethod #1464

Open ensisoft opened 1 year ago

ensisoft commented 1 year ago

Hello,

I have the following code

#include <string>
#include <cstdio>

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

struct MyEntity {};

std::string GetSomething(MyEntity& entity, const char* key, sol::this_state this_state, sol::this_environment this_env)
{
    std::printf("GetSomething, key='%s', has environment = %s\n", key, this_env ? "yes" : "no");

    return "dummy";
}

void environment_variable_test_entity()
{
    sol::state L;
    L.open_libraries();

    auto entity = L.new_usertype<MyEntity>("MyEntity",
      sol::meta_function::index, &GetSomething);

    sol::environment env(L, sol::create, L.globals());

    L.script(R"(
function Tick(entity)
   --print(entity.test_value)
   --print('hello')
   local var = entity.test_value
end
    )", env);

    MyEntity e;

    env["Tick"](&e);

}

int main(int argc, char* argv[])
{
    environment_variable_test_entity();

    return 0;
}

sol::this_environment doesn't have a value, i.e. the underlying std::optional is nullopt. However , the problem goes away when either one of the prints is enabled in the Tick function !

It seems that the prints cause some side effect that sets the this_environment ?

Tested with Sol 3.3.0 (which reports 3.2.0 in sol.hpp) and with GCC 12.2.1.

Thanks!