2019-05-22 07:17:31 +08:00
|
|
|
#define SOL_ALL_SAFETIES_ON 1
|
2018-09-28 13:27:38 +08:00
|
|
|
#include <sol/sol.hpp>
|
2018-03-16 05:16:28 +08:00
|
|
|
|
|
|
|
|
|
|
|
#include <iostream>
|
|
|
|
|
|
|
|
class Player {
|
|
|
|
public:
|
|
|
|
int get_hp() const {
|
|
|
|
return hp;
|
|
|
|
}
|
|
|
|
|
2021-03-06 14:03:23 +08:00
|
|
|
void set_hp(int value) {
|
2018-03-16 05:16:28 +08:00
|
|
|
hp = value;
|
|
|
|
}
|
|
|
|
|
|
|
|
int get_max_hp() const {
|
2023-02-19 01:27:03 +08:00
|
|
|
return maxhp;
|
2018-03-16 05:16:28 +08:00
|
|
|
}
|
|
|
|
|
2021-03-06 14:03:23 +08:00
|
|
|
void set_max_hp(int value) {
|
2018-03-16 05:16:28 +08:00
|
|
|
maxhp = value;
|
|
|
|
}
|
|
|
|
|
|
|
|
private:
|
|
|
|
int hp = 50;
|
|
|
|
int maxhp = 50;
|
|
|
|
};
|
|
|
|
|
2021-03-06 14:03:23 +08:00
|
|
|
int main(int, char*[]) {
|
2018-03-16 05:16:28 +08:00
|
|
|
|
2021-03-06 23:14:48 +08:00
|
|
|
std::cout << "=== properties from C++ functions ==="
|
|
|
|
<< std::endl;
|
2018-03-16 05:16:28 +08:00
|
|
|
|
|
|
|
sol::state lua;
|
|
|
|
lua.open_libraries(sol::lib::base);
|
|
|
|
|
|
|
|
lua.set("theplayer", Player());
|
|
|
|
|
|
|
|
// Yes, you can register after you set a value and it will
|
|
|
|
// connect up the usertype automatically
|
2021-03-06 23:14:48 +08:00
|
|
|
lua.new_usertype<Player>("Player",
|
|
|
|
"hp",
|
|
|
|
sol::property(&Player::get_hp, &Player::set_hp),
|
|
|
|
"maxHp",
|
|
|
|
sol::property(
|
|
|
|
&Player::get_max_hp, &Player::set_max_hp));
|
2018-03-16 05:16:28 +08:00
|
|
|
|
|
|
|
const auto& code = R"(
|
|
|
|
-- variable syntax, calls functions
|
|
|
|
theplayer.hp = 20
|
|
|
|
print('hp:', theplayer.hp)
|
|
|
|
print('max hp:', theplayer.maxHp)
|
|
|
|
)";
|
|
|
|
|
|
|
|
lua.script(code);
|
|
|
|
|
|
|
|
return 0;
|
|
|
|
}
|