Thursday, February 23, 2017

Luabind tostring demonstration

Consider the following code:

#include <string>
#include <iostream>
#include <luabind/luabind.hpp>
#include <luabind/operator.hpp>
class testclass
{
public:
testclass(int val) : m_int(val) {}
friend std::ostream& operator<<(std::ostream& os, testclass const& tc);
private:
int m_int;
};
std::ostream& operator<<(std::ostream& os, testclass const& tc)
{
os << tc.m_int;
return os;
}
extern "C" int init(lua_State* L)
{
using namespace luabind;
open(L);
module(L)
[
class_<testclass>("testclass")
.def(constructor<int>())
.def(tostring(self))
];
return 0;
}
view raw tostring.cpp hosted with ❤ by GitHub
When run:

kuyu@ub16:~/dkuyu/Dropbox/practice/lua/luabind/tostring$ cat test.lua
package.loadlib('./testclass.so', 'init')()
a = testclass(101)
print(tostring(a))
kuyu@ub16:~/dkuyu/Dropbox/practice/lua/luabind/tostring$ 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/tostring$ ./commands.bash
101
kuyu@ub16:~/dkuyu/Dropbox/practice/lua/luabind/tostring$

No comments:

Post a Comment