Thursday, February 23, 2017

Luabind: enums demonstration

Consider the following code:

#include <string>
#include <iostream>
#include <luabind/luabind.hpp>
struct A
{
A() {}
enum
{
first = 1
, second = 2
, thirds = 3
};
};
extern "C" int init(lua_State* L)
{
using namespace luabind;
open(L);
module(L)
[
class_<A>("A")
.def(constructor<>())
.enum_("constants")
[
value("first", 1),
value("second", 2),
value("third", 3)
]
];
return 0;
}
view raw enums.cpp hosted with ❤ by GitHub
When run:

kuyu@ub16:~/dkuyu/Dropbox/practice/lua/luabind/enums$ cat test.lua 
package.loadlib('./testclass.so', 'init')()
print(A.first)
print(A.second)
print(A.third)
kuyu@ub16:~/dkuyu/Dropbox/practice/lua/luabind/enums$ cat ./commands.bash 
#!/bin/bash
g++ testclass.cpp -I/usr/include/lua5.2/ -c -fPIC
g++ -shared -Wl,--whole-archive -o testclass.so testclass.o -lluabind -Wl,--no-whole-archive
lua test.lua
kuyu@ub16:~/dkuyu/Dropbox/practice/lua/luabind/enums$ ./commands.bash 
1
2
3
kuyu@ub16:~/dkuyu/Dropbox/practice/lua/luabind/enums$ 

You actually don't have to define the enum in the C++ struct A. Try removing it and the test.lua will still work.

No comments:

Post a Comment