property¶
wrapper to specify read and write variable functionality using functions
template <typename Read, typename Write>
decltype(auto) property ( Read&& read_function, Write&& write_function );
template <typename Read>
decltype(auto) property ( Read&& read_function );
template <typename Write>
decltype(auto) property ( Write&& write_function );
These set of functions create a type which allows a setter and getter pair (or a single getter, or a single setter) to be used to create a variable that is either read-write, read-only, or write-only. When used during usertype construction, it will create a variable that uses the setter/getter member function specified.
1#define SOL_ALL_SAFETIES_ON 1
2#include <sol/sol.hpp>
3
4
5#include <iostream>
6
7class Player {
8public:
9 int get_hp() const {
10 return hp;
11 }
12
13 void set_hp(int value) {
14 hp = value;
15 }
16
17 int get_max_hp() const {
18 return maxhp;
19 }
20
21 void set_max_hp(int value) {
22 maxhp = value;
23 }
24
25private:
26 int hp = 50;
27 int maxhp = 50;
28};
29
30int main(int, char*[]) {
31
32 std::cout << "=== properties from C++ functions ==="
33 << std::endl;
34
35 sol::state lua;
36 lua.open_libraries(sol::lib::base);
37
38 lua.set("theplayer", Player());
39
40 // Yes, you can register after you set a value and it will
41 // connect up the usertype automatically
42 lua.new_usertype<Player>("Player",
43 "hp",
44 sol::property(&Player::get_hp, &Player::set_hp),
45 "maxHp",
46 sol::property(
47 &Player::get_max_hp, &Player::set_max_hp));
48
49 const auto& code = R"(
50 -- variable syntax, calls functions
51 theplayer.hp = 20
52 print('hp:', theplayer.hp)
53 print('max hp:', theplayer.maxHp)
54 )";
55
56 lua.script(code);
57
58 return 0;
59}