C++ in Lua

Using user defined types (“usertype”s, or just “udt”s) is simple with sol. If you don’t call any member variables or functions, then you don’t even have to ‘register’ the usertype at all: just pass it through. But if you want variables and functions on your usertype inside of Lua, you need to register it. We’re going to give a short example here that includes a bunch of information on how to work with things.

Take this player struct in C++ in a header file:

player.hpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#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;
};

It’s a fairly minimal class, but we don’t want to have to rewrite this with metatables in Lua. We want this to be part of Lua easily. The following is the Lua code that we’d like to have work properly:

player_script.lua
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
p1 = player.new(2)

-- p2 is still here from being 
-- set with lua["p2"] = player(0); below
local p2shoots = p2:shoot()
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()
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()

To do this, you bind things using the new_usertype and method as shown below. These methods are on both table and state(_view), but we’re going to just use it on state:

main.cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#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);

	// 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;
	// typical member function
	player_type["boost"] = &player::boost;

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

	// 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;
}

There is one more method used in the script that is not in C++ or defined on the C++ code to bind a usertype, called brake. Even if a method does not exist in C++, you can add methods to the class table in Lua:

prelude_script.lua
1
2
3
4
function player:brake ()
	self.speed = 0
	print("we hit the brakes!")
end

That script should run fine now, and you can observe and play around with the values. Even more stuff you can do is described elsewhere, like initializer functions (private constructors / destructors support), “static” functions callable with name.my_function( ... ), and overloaded member functions. You can even bind global variables (even by reference with std::ref) with sol::var. There’s a lot to try out!

This is a powerful way to allow reuse of C++ code from Lua beyond just registering functions, and should get you on your way to having more complex classes and data structures! In the case that you need more customization than just usertypes, however, you can customize sol to behave more fit to your desires by using the desired customization and extension structures.

You can check out this code and more complicated code at the examples directory by looking at the usertype_-prefixed examples.