Friday, February 3, 2017

Luabind for sin math function

First we register the cmath sin() function as a function named sin() in Lua:

#include <iostream>
#include <luabind/luabind.hpp>
#include <cmath>
extern "C" int init(lua_State* L)
{
using namespace luabind;
open(L);
module(L)
[
def("sin", (float(*)(float)) &std::sin)
];
return 0;
}
view raw sin.cpp hosted with ❤ by GitHub
We write a simple script to test the Lua sin() function:

kuyu@castor-ub:~/dkuyu/Dropbox/practice/lua/luabind/sin$ cat test.lua 
package.loadlib('./c.so', 'init')()
print(sin(1.57))

We compile and test it as follows:

kuyu@castor-ub:~/dkuyu/Dropbox/practice/lua/luabind/sin$ cat commands.bash 
#!/bin/bash
g++ c.cpp -I/usr/include/lua5.2/ -c -fPIC
g++ -shared -Wl,--whole-archive -o c.so c.o -lluabind -Wl,--no-whole-archive
lua test.lua
kuyu@castor-ub:~/dkuyu/Dropbox/practice/lua/luabind/sin$ ./commands.bash 
0.99999970197678

(1.57 is very close to pi/2 and the sin of pi/2 is 1.)

No comments:

Post a Comment