MCPcopy Create free account
hub / github.com/ThePhD/sol2 / main

Function main

examples/source/dynamic_object.cpp:37–88  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

35
36
37int main() {
38 std::cout << "=== dynamic_object ===" << std::endl;
39
40 sol::state lua;
41 lua.open_libraries(sol::lib::base);
42
43 lua.new_usertype<dynamic_object>("dynamic_object",
44 sol::meta_function::index,
45 &dynamic_object::dynamic_get,
46 sol::meta_function::new_index,
47 &dynamic_object::dynamic_set,
48 sol::meta_function::length,
49 [](dynamic_object& d) { return d.entries.size(); });
50
51 lua.safe_script(R"(
52d1 = dynamic_object.new()
53d2 = dynamic_object.new()
54
55print(#d1) -- length operator
56print(#d2)
57
58function d2:run(lim)
59 local r = 0
60 for i=0,lim do
61 r = r + i
62 end
63 if (r % 2) == 1 then
64 print("odd")
65 end
66 return r
67end
68
69-- only added an entry to d2
70print(#d1)
71print(#d2)
72
73-- only works on d2
74local value = d2:run(5)
75assert(value == 15)
76)");
77
78 // does not work on d1: 'run' wasn't added to d1, only d2
79 auto script_result = lua.safe_script(
80 "local value = d1:run(5)", sol::script_pass_on_error);
81 SOL_ASSERT(!script_result.valid());
82 sol::error err = script_result;
83 std::cout << "received expected error: " << err.what()
84 << std::endl;
85 std::cout << std::endl;
86
87 return 0;
88}

Callers

nothing calls this directly

Calls 5

open_librariesMethod · 0.80
safe_scriptMethod · 0.80
whatMethod · 0.80
sizeMethod · 0.45
validMethod · 0.45

Tested by

no test coverage detected