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
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>

#include "assert.hpp"
#include <iostream>

void create_namespace_sf(sol::state& lua) {
	// this would explode
	// lua["sf"]["value"] = 256;
	lua[sol::create_if_nil]["sf"]["value"] = 256;
}

int main(int, char*[]) {

	std::cout << "=== sol::lua_value/sol::array_value ===" << std::endl;

	sol::state lua;
	lua.open_libraries(sol::lib::base);

	const auto& code = R"(
		print(sf)
		print(sf.value)
		assert(sf.value == 256)
	)";

	auto result = lua.safe_script(code, sol::script_pass_on_error);
	// did not work
	c_assert(!result.valid());

	// create values
	create_namespace_sf(lua);

	auto result2 = lua.safe_script(code, sol::script_pass_on_error);
	// it worked properly
	c_assert(result2.valid());

	std::cout << std::endl;

	return 0;
}