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

Function main

examples/source/usertype_advanced.cpp:48–145  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

46};
47
48int main() {
49 std::cout << "=== usertype_advanced ===" << std::endl;
50 sol::state lua;
51
52 lua.open_libraries(sol::lib::base);
53
54 // note that you can set a
55 // userdata before you register a usertype,
56 // and it will still carry
57 // the right metatable if you register it later
58
59 // set a variable "p2" of type "player" with 0 ammo
60 lua["p2"] = player(0);
61
62 // make usertype metatable
63 sol::usertype<player> player_type
64 = lua.new_usertype<player>("player",
65 // 3 constructors
66 sol::constructors<player(),
67 player(int),
68 player(int, int)>());
69
70 // typical member function that returns a variable
71 player_type["shoot"] = &player::shoot;
72 // typical member function
73 player_type["boost"] = &player::boost;
74
75 // gets or set the value using member variable syntax
76 player_type["hp"]
77 = sol::property(&player::get_hp, &player::set_hp);
78
79 // read and write variable
80 player_type["speed"] = &player::speed;
81 // can only read from, not write to
82 // .set(foo, bar) is the same as [foo] = bar;
83 player_type.set("bullets", sol::readonly(&player::bullets));
84
85 // You can also add members to the code, defined in Lua!
86 // This lets you have a high degree of flexibility in the
87 // code
88 std::string prelude_script = R"(
89function player:brake ()
90 self.speed = 0
91 print("we hit the brakes!")
92end
93)";
94
95 std::string player_script = R"(
96-- call single argument integer constructor
97p1 = player.new(2)
98
99-- p2 is still here from being
100-- set with lua["p2"] = player(0); below
101local p2shoots = p2:shoot()
102assert(not p2shoots)
103-- had 0 ammo
104
105-- set variable property setter

Callers

nothing calls this directly

Calls 6

playerClass · 0.85
propertyFunction · 0.85
readonlyFunction · 0.85
open_librariesMethod · 0.80
scriptMethod · 0.80
setMethod · 0.45

Tested by

no test coverage detected