# sol2 3.5.0 documentation

## this_environment

### Search the Documentation

# this_environment

retrieving the environment of the calling function

Sometimes in C++ it’s useful to know where a Lua call is coming from and what environment it is from. The former is covered by Lua’s Debug API, which is extensive and is not fully wrapped up by sol2. But, sol2 covers the latter in letting you get the environment of the calling script / function, if it has one. `sol::this_environment` is a transparent argument and does not need to be passed in Lua scripts or provided when using sol::function, similar to sol::this_state:

     1#define SOL_ALL_SAFETIES_ON
     2#include <sol/sol.hpp>
     3
     4#include <iostream>
     5
     6
     7void env_check(sol::this_state ts, int x, sol::this_environment te) {
     8        std::cout << "In C++, 'int x' is in the second position, and its value is: " << x << std::endl;
     9        if (!te) {
    10                std::cout << "function does not have an environment: exiting function early" << std::endl;
    11                return;
    12        }
    13        sol::environment& env = te;
    14        sol::state_view lua = ts;
    15        sol::environment freshenv = lua["freshenv"];
    16        bool is_same_env = freshenv == env;
    17        std::cout << "env == freshenv : " << is_same_env << std::endl;
    18}
    19
    20int main() {
    21        sol::state lua;
    22        sol::environment freshenv(lua, sol::create, lua.globals());
    23        lua["freshenv"] = freshenv;
    24
    25        lua.set_function("f", env_check);
    26
    27        // note that "f" only takes 1 argument and is okay here
    28        lua.script("f(25)", freshenv);
    29
    30        return 0;
    31}

Also see this example for more details.