The lua C api provides a function lua_pushcfunction
which allows you to take a function pointer int
(*)(lua_State
*) and pass it to lua, where scripts
can use it like a lua function. When a script calls such a function, your
function pointer is called, and the arguments appear on the stack. You
have to explicitly use lua_istring
etc. to test and obtain the arguments, when using the pure C api.
int is_pythag(lua_State * L) { int a = luaL_checkinteger(L, 1); int b = luaL_checkinteger(L, 2); int c = luaL_checkinteger(L, 3); lua_pushboolean(L, (a * a) + (b * b) == (c * c)); return 1; } // ... lua_pushcfunction(L, &is_pythag);
When using primer, you can automate that to some extent, and pass C++
// functions directly to lua. primer::result new_is_pythag(lua_State * L, int a, int b, int c) { primer::push(L, (a * a) + (b * b) == (c * c)); return 1; } // ... lua_pushcfunction(L, PRIMER_ADAPT(&new_is_pythag));
PRIMER_ADAPT is used to
"convert" the primer signature primer::result (*)(lua_State
*, ...)
to the lua signature int (*)(lua_State
*). PRIMER_ADAPT
generates the boiler-plate which reads the arguments off of the stack,
using primer::read to do the work. That is: If you
implement primer::read for your custom data types, then
they can be arguments to functions which are adapted this way. See the
reference pages for details.