Luwra
A header-only C++ library which provides a Lua wrapper with minimal overhead.
Usage
Refer to the wiki pages or the documentation. In order to use the library you must clone this repository and include lib/luwra.hpp.
Have a question? Simply ask or open an issue.
Examples
In the following examples lua refers to an instance of lua_State*.
Easily push values onto the stack:
3 luwra::push(lua, 1338);
6 luwra::push(lua, 13.37);
9 luwra::push(lua, false);
12 luwra::push(lua, "Hello World");
Or retrieve them:
3 int my_fun(int a, int b) {
11 // Apply your function
12 int result = luwra::apply(lua, my_fun);
14 // which is equivalent to
15 int result = luwra::apply(lua, 1, my_fun);
18 int result = luwra::apply(lua, -2, my_fun);
20 // All of this is essentially syntactic sugar for
21 int result = my_fun(luwra::read<int>(lua, 1), luwra::read<int>(lua, 2));
Generate a C function which can be used by Lua:
2 // Assuming your function looks something like this
3 int my_function(const char* a, int b) {
7 // Convert to lua_CFunction
8 lua_CFunction cfun = LUWRA_WRAP(my_function);
10 // Do something with it, for example set it as a Lua global function
11 luwra::setGlobal(lua, "my_function", cfun);
1 -- Invoke the registered function
2 local my_result = my_function("Hello World", 1337)
Or register your own class:
5 Point(double x, double y):
8 std::cout << "Construct Point(" << x << ", " << y << ")" << std::endl;
12 std::cout << "Destruct Point(" << x << ", " << y << ")" << std::endl;
15 void scale(double f) {
20 std::string __tostring() {
21 return "<Point(" + std::to_string(x) + ", " + std::to_string(y) + ")>";
25 // Register the metatable and constructor
26 luwra::registerUserType<Point(double, double)>(
32 // Methods need to be declared here
34 LUWRA_MEMBER(Point, scale),
35 LUWRA_MEMBER(Point, x),
36 LUWRA_MEMBER(Point, y)
39 // Meta methods may be registered aswell
41 LUWRA_MEMBER(Point, __tostring)
2 local point = Point(13, 37)
4 -- Invoke 'scale' method
7 -- Convert to string via '__tostring' meta method
10 -- Read properties 'x' and 'y'
11 print(point:x(), point:y())
Requirements
You need a C++11-compliant compiler and at least Lua 5.1 to get this library to work. I recommend using Lua 5.3 or later, to avoid the messy lua_Integer situation. LuaJIT 2.0 seems to work, apart from user types, which fail for yet unknown reasons.
Tests
The attached GNU Makefile allows you to run both examples and tests using make examples and make test respectively. You might need to adjust LUA_* variables, so Luwra finds the Lua headers and library.
Assuming all headers are located in /usr/include/lua5.3 and the shared object name is liblua5.3.so, you need to invoke this:
1 make LUA_INCDIR=/usr/include/lua5.3 LUA_LIBNAME=lua5.3 test