luabridge3, part 1

setting it up, and handing lua your functions and data

what youll have by the end

a c++ program with a game table in lua, full of your c++ functions and variables, and not one push or pop written by hand

print(game.add(2, 3))
print(game.shout("hi"))
game.score = 99
5
hi!

and c++ sees g_score change to 99 straight after

where this sits

this is part 1 of a short series on luabridge3 with lua 5.5, the first three are

  • 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

it helps to have seen the lua c api intro (lua-c-api-intro-1), the stack and luaL_dostring come up here and dont get re-taught

the big picture

the lua c api works, but every function you hand lua needs a little wrapper, read each argument off the stack, check its type, call the real thing, push the result back

luabridge3 is a library that writes those wrappers for you, you tell it what to expose once, by name, and it works out the stack side from the c++ types

that telling it once is called registration, its the word for this whole deck

like a waiter at the hatch

back in the c api intro lua sat in the kitchen next door, and everything went through a serving hatch as a stack of plates

luabridge is a waiter standing at that hatch, you hand them a menu at the start of the night, this dish is called add, it takes two ints, and from then on they carry every plate both ways for you

the hatch is still there, the waiter just means you stop touching the plates

the map

diagram

you write the menu and the functions, luabridge writes the wrappers in the middle, the stack is still there, you just stop touching it

section 1, setting it up

what you need

lua 5.5 the repo has lua-5.5.1, a bugfix release of 5.5.0 with the same api, already built to lua-5.5.1/build/Release/liblua.a

luabridge3 header only, there is nothing to build, no .cpp and no lib, you just point the compiler at its headers

c++17 or newer luabridge leans hard on templates from c++17, we build with c++20 anyway

luabridge3 lists 5.5.0 as tested, the newest tag at the time of writing is 3.0-rc13

getting luabridge3

clone it next to lua-5.5.1 at the repo root

git clone https://github.com/kunitoki/LuaBridge3.git

two folders in there matter

Source the real headers, one file per piece, nicer to read and step through in the debugger

Distribution the same library squashed into one LuaBridge.h, plus the optional extras like Vector.h, easier to copy into a project

both are included the same way, #include <LuaBridge/LuaBridge.h>, we use Source

building it, xcode

same as the c api intro, plus one more search path

  • build settings, header search paths add lua-5.5.1/source and LuaBridge3/Source
  • build settings, c++ language dialect c++20
  • build phases, link binary with libraries +, add other, pick liblua.a

or straight from a terminal at the repo root

clang++ -std=c++20 -I lua-5.5.1/source -I LuaBridge3/Source main.cpp lua-5.5.1/build/Release/liblua.a -o host

no extra lib on the end, bc luabridge has nothing to link

the one include rule

lua has to be included before luabridge, every time

#include <lua.hpp>
#include <LuaBridge/LuaBridge.h>

luabridge uses lua types like lua_State but never includes lua itself, so you get to pick which lua it talks to, 5.1, 5.5, luajit, luau. get the order wrong and the first error says it plainly

error: "Lua headers must be included prior to LuaBridge ones"

followed by a few hundred more, ignore those, its only the first one that counts

the smallest host

#include <lua.hpp>
#include <LuaBridge/LuaBridge.h>

//
//	adds the two given ints
//
int add(int _a, int _b)
{
	return _a + _b;
}

int main()
{
	lua_State *L = luaL_newstate();
	luaL_openlibs(L);

	luabridge::getGlobalNamespace(L)
		.beginNamespace("game")
			.addFunction("add", add)
		.endNamespace();

	luaL_dostring(L, "print(game.add(2, 3))");

	lua_close(L);
	return 0;
}
5

the state, the libs, the dostring, the close, all the same as before, only the middle block is new

section 2, namespaces

getGlobalNamespace

luabridge::getGlobalNamespace(L)

hands back an object that stands for the lua global table, the table every global lives in, lua calls it _G

on its own it does nothing, its the starting point you hang registrations off

you could register straight into it, but then add sits loose beside print and string, the docs say dont, and so do we

beginNamespace and endNamespace

luabridge::getGlobalNamespace(L)
	.beginNamespace("game")
		.addFunction("add", add)
	.endNamespace();

a namespace here is just a lua table, nothing to do with a c++ namespace, beginNamespace("game") makes a table called game in the globals, or opens it if its already there

endNamespace steps back out to whatever you were in before

so in lua this is game.add, one table, one function inside it

the chain

every registration call hands back the namespace it was called on, so the next call can go straight on the end with a dot

luabridge::getGlobalNamespace(L)
	.beginNamespace("game")
		.beginNamespace("maths")
			.addFunction("add", add)
		.endNamespace()
		.addFunction("shout", shout)
	.endNamespace();

its all one statement, one long line of dots, the indents mean nothing to the compiler, they just show us which table each thing lands in

what that builds

diagram

so lua reaches it as game.maths.add and game.shout

reopening a namespace

you can open the same namespace again later and add more, nothing gets wiped

luabridge::getGlobalNamespace(L)
	.beginNamespace("game")
		.addFunction("add", add)
	.endNamespace();

luabridge::getGlobalNamespace(L)
	.beginNamespace("game")
		.addFunction("shout", shout)
	.endNamespace();

handy once a project grows, the audio code registers its bits into game from its own file, the input code does the same from another

the one thing to never do is register two things with the same name in the same namespace, luabridge lets it through and what happens after is undefined

section 3, functions

addFunction

//
//	adds the two given ints
//
int add(int _a, int _b)
{
	return _a + _b;
}
.addFunction("add", add)

two things, the name lua sees, then the c++ function

luabridge reads the function type, int(int, int), at compile time, and from that alone it knows to read two integers off the stack and push one integer back

the name lua sees doesnt have to match the c++ one, though matching saves everyone a headache

what it wrote for you

this is roughly the wrapper luabridge made, the one we wrote by hand in the c api intro

//
//	reads two ints off the stack and pushes their sum
//
int lua_add(lua_State *L)
{
	lua_Integer a = luaL_checkinteger(L, 1);
	lua_Integer b = luaL_checkinteger(L, 2);

	lua_pushinteger(L, add(a, b));
	return 1;
}

one of these per function, times every function in a game, thats the job luabridge takes off you

lambdas work too

.addFunction("shout", [](std::string _s) { return _s + "!"; })
.addFunction("half", [](double _x) { return _x / 2; })
print(game.shout("hi"), game.half(5))
hi!	2.5

a lambda is a function written inline, right where its used, and luabridge3 takes them anywhere it takes a function, even ones that capture, that grab local variables from around them

a capturing lambda is how you hand lua something with a bit of state, a pointer to your game, a counter, without making a global for it

which types cross over

c++ lua
int, int64_t, unsigned ... integer
float, double float
bool boolean
std::string, const char *, std::string_view string
std::tuple<...> as a return several return values
void as a return nothing

all built in, nothing to include, std::vector and friends need an extra header each, LuaBridge/Vector.h, they come in a later part

more than one return

lua functions can return several values, c++ functions cant, so luabridge treats a returned std::tuple as one value per slot

.addFunction("minmax", [](int _a, int _b) { return std::make_tuple(std::min(_a, _b), std::max(_a, _b)); })
local lo, hi = game.minmax(9, 3)
print(lo, hi)
3	9

when lua passes the wrong thing

luabridge checks every argument against the c++ type, a bad one turns into a normal lua error, the kind pcall catches

game.add("x", 1)
game.add(1)
:1: Error decoding argument #1: The lua object can't be cast to desired type
:1: Error decoding argument #2: The lua object can't be cast to desired type

the second one is a missing argument, lua fills it with nil, and nil isnt an int

extra arguments go the other way, game.add(1, 2, 3) quietly drops the 3 and prints 3

the two number gotchas

game.add(2.0, 1)
game.add(2.5, 1)
game.add("4", 1)
3
:1: Error decoding argument #1: The native integer can't fit inside a lua integer
:1: Error decoding argument #1: The lua object can't be cast to desired type

2.0 works bc it has a whole number value, so it fits in an int, 2.5 doesnt, and the message for that one reads backwards, it means this float wont fit in your int

"4" fails even though plain lua would happily turn it into 4, luabridge is stricter than the c api here

how it flows

diagram

the same dance as a hand written wrapper, luabridge just wrote the middle actor

still with me ?

so far

  • lua before luabridge in the includes, and nothing to link but lua
  • getGlobalNamespace(L) is the globals, beginNamespace makes a table in it
  • every call returns the namespace, so registration is one long chain
  • addFunction takes a name and any function or lambda, the types do the rest
  • bad arguments become ordinary lua errors

next, handing lua your variables

section 4, data

a property from a variable

int g_score = 10;
.addProperty("score", &g_score)

a property looks like a plain field to lua, game.score, but every read goes through luabridge to the real g_score, so lua always sees the current value

hand it one pointer and the property is read only

print(game.score)
game.score = 99
10
:1: 'score' is read-only

read and write

hand it the same pointer twice, once for reading, once for writing

.addProperty("score", &g_score, &g_score)
game.score = 99
printf("c++ sees %d\n", g_score);
c++ sees 99

lua wrote straight into the c++ variable, no copy, no sync step, this is the one from the slide at the very start

a property from functions

//
//	hands back the player name
//
std::string get_name()
{
	return g_name;
}

//
//	sets the player name and says so
//
void set_name(std::string _name)
{
	g_name = _name;
	printf("name is now %s\n", _name.c_str());
}
.addProperty("name", get_name, set_name)

same idea, but instead of a variable you hand it a getter and a setter, and luabridge calls them on every read and every write

so game.name = "bob" runs set_name("bob"), which means you get to check the value, clamp it, or kick something off when it changes, leave the setter off and its read only

addVariable, a copy

.addVariable("speed", 2.5)
print(game.speed)
game.speed = 5
print(game.speed)
2.5
5

this puts a plain copy of the value in the table, then forgets about it, lua can change it all it likes and nothing on the c++ side ever hears about it

its the cheapest of the lot, no function call on every read, good for constants and starting values

which one to pick

addProperty, one pointer lua can read your variable, never change it, the default for anything c++ owns

addProperty, two pointers lua and c++ share the one variable, both see every change

addProperty, getter and setter you want a say whenever lua reads or writes it

addVariable a starting value that lua owns from then on

how a property works

a property isnt really stored in the game table at all, luabridge gives game a metatable with __index and __newindex, the two hooks lua runs when a key is missing

so game.score misses, lua asks __index, and that looks up the getter for score and calls it, writes go the same way through __newindex

the metatables deck (lua-metatables) covers those two hooks properly, this is the same trick, luabridge just set it up for you

why its built this way

  • registration at startup, then hands off you describe everything once, after that its plain lua calls, no per frame cost for the describing
  • templates, not macros the wrappers come out of the c++ types at compile time, so a mismatch is a compiler error, not a crash at runtime
  • namespaces are just tables nothing new for lua to learn, a script sees game.add the same as it sees string.format
  • no exceptions needed it builds with exceptions off, common in game code, errors go through lua like any other
  • the house style the _a _b on the args means its the given argument, not a local, and g_score with the g_ is a true global

recap

  • luabridge3 writes the stack wrappers for you, you just describe what to expose
  • header only, include lua first, link only liblua.a
  • a namespace is a lua table, beginNamespace to go in, endNamespace to come out
  • addFunction for functions and lambdas, a std::tuple gives several returns
  • addProperty for live variables, one pointer read only, two pointers read write, or a getter and setter
  • addVariable for a copy lua owns

have a go

build a game table with

  • clamp(value, lo, hi) as a lambda
  • version a read only property off a const char * global
  • volume a property with a setter that clamps it to 0 and 1, and prints when it changes

then a script that tries game.version = "2", game.volume = 5, and game.clamp("a", 0, 1), wrap each in pcall and print the error that comes back

about 30 minutes, part 2 picks up with classes