Wednesday, February 8, 2017

Consider the following code which registers a free function (plus()) as a member function of class A:

#include <string>
#include <iostream>
#include <luabind/luabind.hpp>
struct A
{
A(int val): a(val) {}
int a;
};
int plus(A* o, int v)
{
return o->a + v;
}
extern "C" int init(lua_State* L)
{
using namespace luabind;
open(L);
module(L)
[
class_<A>("A")
.def(constructor<int>())
.def("plus", &plus)
];
return 0;
}
When run:

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

No comments:

Post a Comment