table traversal keys¶
the definitive way to get and set things easily
Objects sol::update_if_empty, sol::create_if_nil, and sol::override_value are special keys one can pass into a table traversal to enable creating tables as they go in nil/empty spaces, optionally updating a value at the end of a chain of lookups if it is empty, or overriding the values and tables along a chain as they go. Each special key can be used in lookup and setting functionality on tables. It is primarily to enable easy use and creation of functionality like so:
1#define SOL_ALL_SAFETIES_ON 1
2#include <sol/sol.hpp>
3
4#include <iostream>
5
6void create_namespace_sf(sol::state& lua) {
7 // this would explode
8 // lua["sf"]["value"] = 256;
9 lua[sol::create_if_nil]["sf"]["value"] = 256;
10}
11
12int main(int, char*[]) {
13
14 std::cout << "=== sol::lua_value/sol::array_value ==="
15 << std::endl;
16
17 sol::state lua;
18 lua.open_libraries(sol::lib::base);
19
20 const auto& code = R"(
21 print(sf)
22 print(sf.value)
23 assert(sf.value == 256)
24 )";
25
26 auto result
27 = lua.safe_script(code, sol::script_pass_on_error);
28 // did not work
29 SOL_ASSERT(!result.valid());
30
31 // create values
32 create_namespace_sf(lua);
33
34 auto result2
35 = lua.safe_script(code, sol::script_pass_on_error);
36 // it worked properly
37 SOL_ASSERT(result2.valid());
38
39 std::cout << std::endl;
40
41 return 0;
42}