# sol2 3.5.0 documentation

## var

### Search the Documentation

# var

For hooking up static / global variables to Lua usertypes

The sole purpose of this tagging type is to work with usertypes to provide `my_class.my_static_var` access, and to also provide reference-based access as well.

     1#define SOL_ALL_SAFETIES_ON 1
     2#include <sol/sol.hpp>
     3
     4#include <iostream>
     5
     6struct test {
     7	static int number;
     8};
     9int test::number = 25;
    10
    11
    12int main() {
    13	sol::state lua;
    14	lua.open_libraries();
    15	lua.new_usertype<test>("test",
    16	     "direct",
    17	     sol::var(2),
    18	     "number",
    19	     sol::var(test::number),
    20	     "ref_number",
    21	     sol::var(std::ref(test::number)));
    22
    23	int direct_value = lua["test"]["direct"];
    24	SOL_ASSERT(direct_value == 2);
    25
    26	int number = lua["test"]["number"];
    27	SOL_ASSERT(number == 25);
    28	int ref_number = lua["test"]["ref_number"];
    29	SOL_ASSERT(ref_number == 25);
    30
    31	test::number = 542;
    32
    33	// number is its own memory: was passed by value
    34	// So does not change
    35	int number_again = lua["test"]["number"];
    36	SOL_ASSERT(number_again == 25);
    37
    38	// ref_number is just test::number
    39	// passed through std::ref
    40	// so, it holds a reference
    41	// which can be updated
    42	int ref_number_again = lua["test"]["ref_number"];
    43	SOL_ASSERT(ref_number_again == 542);
    44	// be careful about referencing local variables,
    45	// if they go out of scope but are still reference
    46	// you'll suffer dangling reference bugs!
    47
    48	return 0;
    49}