Monday, March 21, 2016

Using C++ Template Meta-Programming to expose C functions in Lua


I've written an article on auto-magical language bindings, which you can find here: http://inspired-code.blogspot.com/p/automagical-language-bindings-using-c.html

The specifics of the article shows how to expose C functions to lua.

The summary is, all you need to do to expose a function is add it to the list of exposed functions wrapped with the macro AUTO_BIND_C_FUNTION_TO_LUA such as in the following code snippet:


// Some function prototypes to expose
void someFunc(int arg1, int arg2, const char* arg3);
void anotherFunc(const char* arg1, double arg2, int arg2);
// ... etc ...
// Import table
static const struct luaL_Reg scriptCallableFunctions[] =
{
  AUTO_BIND_C_FUNTION_TO_LUA(someFunc)
  AUTO_BIND_C_FUNTION_TO_LUA(anotherFunc)
  // ... etc ...
};

// Register all the functions we want wrapped
void registerLuaBindings(lua_State* L)
{
  // Register all of our bindings
  for (luaL_Reg r : scriptCallableFunctions) {
    lua_pushcclosure(L, r.func, 0);
    lua_setglobal(L, r.name);
  }
}


That certainly simplifies the work of exposing a function to Lua. I believe the approach could be adapted relatively easily for possibly other languages, such as python also.

Hope you like it.

No comments:

Post a Comment