luabridge3, part 2

handing lua your classes, and deciding who owns each object

what youll have by the end

your own c++ types living in lua, made there, called there, with real methods and inheritance

local v = game.vec2(3, 4)
print(v.x, v.y, v:length())
v.x = 6
print(v)
3.0	4.0	5.0
(6.000000, 4.000000)

and a clear answer, for every object, to who deletes it

where this sits

part 2 of the luabridge3 series

  • part 1 setting it up, namespaces, functions and data
  • part 2 classes, and who owns an object
  • part 3 the other way round, c++ reading and calling lua

everything from part 1 carries over, a class gets registered inside a namespace with the same long chain

the big picture

lua has no classes, so a c++ object reaches lua as a userdata, a block of memory lua carries around but cant see inside

on its own a userdata does nothing, what makes v.x and v:length() work is its metatable, a table of hooks lua checks when you index the userdata

luabridge builds that metatable for you, one per class, from a registration that looks a lot like part 1

like a sealed parcel

a userdata is a sealed parcel, lua can carry it, pass it round, store it in a table, but it cant open it

stuck on the outside is a label, the metatable, that lists what you can ask the parcel for, its x, its length

lua reads the label, luabridge does the opening, so lua only ever gets what the label lists

the map

diagram

section 1, a first class

the c++ side

//
//	a 2d vector, a pair of floats
//
struct vec2_t
{
	float x = 0;
	float y = 0;

	vec2_t() = default;
	vec2_t(float _x, float _y) : x(_x), y(_y) {}

	float length() const;
	void scale(float _by);
	vec2_t add(const vec2_t &_other) const;
	std::string to_string() const;

	static vec2_t zero();
};

a plain struct, nothing in it knows lua exists, which is the point, the class stays clean and all the lua stuff lives in the registration

the fields come first, then the functions, the house two phase layout, so you see what it has before what it does, and struct fields go bare, no m_

beginClass and endClass

luabridge::getGlobalNamespace(L)
	.beginNamespace("game")
		.beginClass<vec2_t>("vec2")
			.addConstructor<void(), void(float, float)>()
			.addFunction("length", &vec2_t::length)
		.endClass()
	.endNamespace();

beginClass<vec2_t>("vec2") starts a class, the type goes in the angle brackets, the name lua sees goes in the brackets

endClass steps back out to the namespace, the same as endNamespace does

everything between is about vec2_t, so lua reaches it as game.vec2

addConstructor

.addConstructor<void(), void(float, float)>()

luabridge can read a function type off a function, but there is no way to point at a constructor in c++, so you spell the argument lists out yourself

each void(...) is one constructor, the void is just filler, only the arguments count, list several and luabridge tries them in order till one fits

local a = game.vec2()
local b = game.vec2(3, 4)

calling the class makes a new one, that is the constructor

when no constructor fits

local v = game.vec2("a")
:1: All 2 overloads of vec2 returned an error:
1: Skipped overload #0 with unmatched arity of 0 instead of 1
2: Skipped overload #1 with unmatched arity of 2 instead of 1

arity just means how many arguments, so it tried the 0 argument one and the 2 argument one, and neither takes 1

and with no addConstructor at all lua cant make one, game.entity("x") gives attempt to call a table value, which is how you keep a type c++ only

section 2, members

member functions

.addFunction("length", &vec2_t::length)
.addFunction("scale", &vec2_t::scale)

the same addFunction as part 1, but handed a member function pointer, &vec2_t::length, the way c++ names a function that lives on a class

local v = game.vec2(1, 2)
v:scale(2)
print(v:length())

the colon is lua shorthand, v:scale(2) means v.scale(v, 2), it passes the object in as the first argument, which is the this the c++ side needs

the dot slip

print(v.length())
:1: The lua object can't be cast to desired type

with a dot there is no object passed in, so luabridge goes looking for a vec2 in argument 1, finds nothing, and says so

everyone does this a few times, if a method call says it cant cast, check for a dot that should be a colon

properties on fields

the same rule as part 1, one pointer is read only, two is read and write

.addProperty("x", &vec2_t::x, &vec2_t::x)
.addPropertyReadWrite("y", &vec2_t::y)

addPropertyReadWrite is just a shorter way to write the pointer twice

careful with the docs the luabridge docs still say to pass false for read only, in 3.0 that overload is deleted and wont compile, leave the second pointer off instead

properties on functions

.addProperty("health", &entity_t::get_health, &entity_t::set_health)
//
//	sets health, never below 0
//
void entity_t::set_health(int _health)
{
	m_health = _health < 0 ? 0 : _health;
}
p.health = -5
print(p.health)
0

lua thinks its writing a field, but its really calling your setter, so the clamp holds no matter what a script does

names that dont exist

print(v.z)
v.z = 1
nil
:1: no writable member 'z'

reading a name the label doesnt list gives nil, same as any lua table

writing one is an error, you cant bolt new fields onto a userdata, theres nowhere in the parcel to put them

statics

.addStaticFunction("zero", &vec2_t::zero)
print(game.vec2.zero())

a static belongs to the class, not to any one object, so lua finds it on the class table, game.vec2.zero, with a dot, no object needed

addStaticProperty does the same for static variables, with the same one or two pointer rule

metamethods

.addFunction("__tostring", &vec2_t::to_string)
.addFunction("__add", &vec2_t::add)
local v = game.vec2(1, 2) + game.vec2(1, 1)
print(v)
(2.000000, 3.000000)

a metamethod is one of the hooks lua runs for an operator, + runs __add, print runs __tostring, register one with a plain addFunction and the right name

any of them work except __gc, luabridge owns that one, its how it runs your destructor

const is kept

luabridge spots const methods by their type, so when lua holds a const object it only gets the const methods

say counter_t has a const get and a plain bump, and lua gets a const pointer to one

luabridge::setGlobal(L, (const counter_t *)&g_counter, "counter_view");
print(counter_view:get())
counter_view:bump()
2
:1: attempt to call a nil value (method 'bump')

get is const so it works, bump changes the object so its not even on the label

still with me ?

so far

  • a c++ object in lua is a userdata, a sealed parcel, its metatable is the label
  • beginClass<T>("name") to endClass(), inside a namespace
  • addConstructor spells out each constructor, no constructor means lua cant make one
  • methods with addFunction, called with a colon
  • addProperty one pointer read only, two read write, or a getter and setter
  • statics on the class table, metamethods by name, const is kept

section 3, inheritance

the c++ side

class entity_t
{
public:
	std::string m_name;
	int m_health = 100;

	entity_t(std::string _name);
	virtual ~entity_t() = default;

	virtual std::string describe() const;

	// getters
	int get_health() const { return m_health; }

	// setters
	void set_health(int _health);
};

class player_t : public entity_t
{
public:
	int m_score = 0;

	player_t(std::string _name);

	std::string describe() const override;
	void add_score(int _amount);
};

deriveClass

.beginClass<entity_t>("entity")
	.addProperty("name", &entity_t::m_name)
	.addProperty("health", &entity_t::get_health, &entity_t::set_health)
	.addFunction("describe", &entity_t::describe)
.endClass()
.deriveClass<player_t, entity_t>("player")
	.addPropertyReadWrite("score", &player_t::m_score)
	.addFunction("add_score", &player_t::add_score)
.endClass()

deriveClass<player_t, entity_t> the new class first, then its base, the base has to be registered before it

the player only lists what it adds, name, health and describe come along from the entity for free

what lua sees

diagram

virtual just works

local p = game.get_player()
print(p.name, p.health, p:describe())
finn	100	player finn

describe was registered on the entity, but the object is a player, so c++ runs the player override, luabridge just calls through the pointer like any other c++ code would

the same goes for passing a player into a c++ function that wants an entity_t *, it fits, the normal c++ rules apply

section 4, who owns it

the question

every object lua can touch was made somewhere, and someone has to delete it

get this wrong and you either leak, or lua uses an object c++ already deleted, a dangling pointer, which crashes, or worse, doesnt crash and reads junk

luabridge gives you two answers, and how you hand the object over picks which one

the two lifetimes

diagram

by value T hands lua a copy, lua owns it

by pointer or reference T * T & hands lua a way to reach yours, c++ owns it

by value, lua owns a copy

.addFunction("copy_player", []() { return g_player; })
local p = game.copy_player()
p:add_score(5)
print(p.score)
5

and a printf of g_player.m_score back in c++ still says 0

the return type is player_t, a value, so luabridge copied the player into a new userdata, lua changed the copy, and the real g_player never knew

objects made in lua with a constructor work this way too, game.vec2(3, 4) is owned by lua, and the garbage collector runs ~vec2_t once nothing points at it

by pointer, c++ owns it

.addFunction("get_player", []() { return &g_player; })
local p = game.get_player()
p:add_score(10)

and this time the c++ printf says 10

now the return type is player_t *, so the userdata only holds a pointer, lua is touching the real object, and lua will never delete it, collecting the userdata just drops the pointer

this is the one you want for things the engine owns, the player, the world, the window

handing one in

you dont need a function to get an object across, setGlobal puts one straight into a lua global

luabridge::setGlobal(L, &g_player, "player");
luabridge::setGlobal(L, g_player, "player_copy");

the same rule, a pointer is shared and c++ owns it, a plain value is copied and lua owns it

the dangling trap

with c++ lifetime, lua trusts that the object is still there, luabridge cant check

player_t *p = new player_t("temp");
luabridge::setGlobal(L, p, "temp");
delete p;
print(temp.name)

that last line reads freed memory, undefined behaviour, it might print junk, it might crash, it might work today and break next week

so the rule, an object you hand over by pointer has to outlive every script that can reach it, or you clear the lua side first, temp = nil

shared ownership, briefly

sometimes neither side should own it alone, luabridge also takes std::shared_ptr, where the object lives till both sides let go

it needs the class to derive from std::enable_shared_from_this, and its own constructor call, addConstructorFrom

that one gets its own part later, for now value and pointer cover nearly everything

how a method call flows

diagram

why its built this way

  • the class stays clean nothing in vec2_t mentions lua, the registration is the only place that knows, so the same class works with or without scripting
  • constructors spelled out c++ cant hand you a pointer to a constructor, so the signatures go in by hand, everything else is read off the types
  • ownership by how you pass it value and pointer already mean copy and borrow in c++, luabridge just keeps that meaning on the lua side
  • the house style the _t on vec2_t and player_t marks a type, m_ marks a class member, and struct fields like x go bare

recap

  • a c++ object in lua is a userdata, the metatable is its label
  • beginClass and endClass, addConstructor with each signature spelled out
  • methods with addFunction and a member pointer, called with a colon
  • one pointer read only, two read write, or a getter and setter, false no longer compiles
  • deriveClass<derived, base> gets the base members for free, virtuals work
  • by value, lua owns a copy, by pointer, c++ owns it, and a pointer has to outlive the scripts

have a go

register a rect_t with x y w h

  • a constructor taking all four, and one taking none
  • an area method, a __tostring, and a read only right property off a getter
  • a g_screen rect handed to lua by pointer as screen, and a screen_copy by value

then a script that changes w on both, and a c++ printf after it that shows which one reached g_screen

about 40 minutes, part 3 turns it round and has c++ reach into lua