sol 三 C++ in Lua

 先定义一个类

#include <iostream>

struct player {
public:
	int bullets;
	int speed;

	player()
		: player(3, 100) {

	}

	player(int ammo)
		: player(ammo, 100) {

	}

	player(int ammo, int hitpoints)
		: bullets(ammo), hp(hitpoints) {

	}

	void boost() {
		speed += 10;
	}

	bool shoot() {
		if (bullets < 1)
			return false;
		--bullets;
		return true;
	}

	void set_hp(int value) {
		hp = value;
	}

	int get_hp() const {
		return hp;
	}

private:
	int hp;
};

在lua中使用

p1 = player.new(2) //new一个出来

-- p2 is still here from being 
-- set with lua["p2"] = player(0); below
local p2shoots = p2:shoot()  //执行shoot函数,p2是在C++里面new的
assert(not p2shoots)
-- had 0 ammo
	
-- set variable property setter
p1.hp = 545  //设置变量
-- get variable through property unqualified_getter
print(p1.hp)
assert(p1.hp == 545)

local did_shoot_1 = p1:shoot()  //执行p1的shoot
print(did_shoot_1)
print(p1.bullets)
local did_shoot_2 = p1:shoot()
print(did_shoot_2)
print(p1.bullets)
local did_shoot_3 = p1:shoot()
print(did_shoot_3)
	
-- can read
print(p1.bullets)
-- would error: is a readonly variable, cannot write
-- p1.bullets = 20

p1:boost()
-- call the function we define at runtime from a Lua script
p1:brake()

下面是绑定

#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>

#include "player.hpp"

#include <iostream>

int main() {
	sol::state lua;

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

	// note that you can set a 
	// userdata before you register a usertype,
	// and it will still carry 
	// the right metatable if you register it later

	// set a variable "p2" of type "player" with 0 ammo
	lua["p2"] = player(0);  //先new个出来

	// make usertype metatable
	sol::usertype<player> player_type = lua.new_usertype<player>("player",
		// 3 constructors
		sol::constructors<player(), player(int), player(int, int)>()); //构造函数

	// typical member function that returns a variable
	player_type["shoot"] = &player::shoot; //绑定shoot函数
	// typical member function
	player_type["boost"] = &player::boost; //绑定boost函数

	// gets or set the value using member variable syntax
	player_type["hp"] = sol::property(&player::get_hp, &player::set_hp); //绑定变量hp,并绑定get/set

	// read and write variable
	player_type["speed"] = &player::speed; //绑定变量
	// can only read from, not write to
	// .set(foo, bar) is the same as [foo] = bar;
	player_type.set("bullets", sol::readonly(&player::bullets)); //绑定只读变量

	lua.script_file("prelude_script.lua"); //加载脚本
	lua.script_file("player_script.lua"); 
	return 0;
}

其中,brake函数不在C++中,在prelude_script.lua中,也可以连接到C++后面,

prelude_script.lua

function player:brake ()
	self.speed = 0
	print("we hit the brakes!")
end

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值