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
part 2 of the luabridge3 series
everything from part 1 carries over, a class gets registered inside a namespace with the same long chain
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
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
//
// 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_
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<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
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
.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
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
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
.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
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
.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
.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
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
so far
beginClass<T>("name") to endClass(), inside a namespaceaddConstructor spells out each constructor, no constructor means lua cant make oneaddFunction, called with a colonaddProperty one pointer read only, two read write, or a getter and setterclass 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);
};
.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
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
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
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
.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
.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
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
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
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
vec2_t mentions lua, the registration is the only place that knows, so the same class works with or without scripting_t on vec2_t and player_t marks a type, m_ marks a class member, and struct fields like x go barebeginClass and endClass, addConstructor with each signature spelled outaddFunction and a member pointer, called with a colonfalse no longer compilesderiveClass<derived, base> gets the base members for free, virtuals workregister a rect_t with x y w h
area method, a __tostring, and a read only right property off a getterg_screen rect handed to lua by pointer as screen, and a screen_copy by valuethen 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