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
this is part 1 of a short series on luabridge3 with lua 5.5, the first three are
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 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
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
you write the menu and the functions, luabridge writes the wrappers in the middle, the stack is still there, you just stop touching it
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
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
same as the c api intro, plus one more search path
lua-5.5.1/source and LuaBridge3/Source+, add other, pick liblua.aor 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
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
#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
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
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
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
so lua reaches it as game.maths.add and game.shout
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
//
// 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
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
.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
| 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
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
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
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
the same dance as a hand written wrapper, luabridge just wrote the middle actor
so far
getGlobalNamespace(L) is the globals, beginNamespace makes a table in itaddFunction takes a name and any function or lambda, the types do the restnext, handing lua your variables
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
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
//
// 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("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
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
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
game.add the same as it sees string.format_a _b on the args means its the given argument, not a local, and g_score with the g_ is a true globalliblua.abeginNamespace to go in, endNamespace to come outaddFunction for functions and lambdas, a std::tuple gives several returnsaddProperty for live variables, one pointer read only, two pointers read write, or a getter and setteraddVariable for a copy lua ownsbuild a game table with
clamp(value, lo, hi) as a lambdaversion a read only property off a const char * globalvolume a property with a setter that clamps it to 0 and 1, and prints when it changesthen 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