How can I share data between C ++ and Lua?

I was looking for tutorials demonstrating how to share a C ++ object with Lua using the API. Most tutorials show you how to export a class.

I would like to start very simple and expose the variable (say int myVar = 5

) in such a way that the change in Lua will be reflected in the C ++ application.

Does anyone know of good tutorials that can show me how to do this?

+2


source to share


3 answers


As sbk mentioned, you should access your variable as a member of userdata:

print(cside.myVar) -- 5

      



Here is some sample code to do this using the Lua API. Its simple though tedious. You will either want to create your own code generator or use something like swig or tolua ++

/* gcc -o simple simple.c -llua -lm -ldl */
#include <stdio.h>

#include "lua.h"
#include "lauxlib.h"

int myVar = 5;

int l_set( lua_State *L )
{
 const char *key = luaL_checkstring(L, 2);
 int val = luaL_checkint(L, 3);

 if (strcmp(key, "myVar") == 0)
  myVar = val;
}

int l_get( lua_State *L )
{
 const char *key = luaL_checkstring(L, 2);

 if (strcmp(key, "myVar") == 0)
 {
  lua_pushinteger(L, myVar);
  return 1;
 }
}

int main(int argc, char *argv[])
{
 const struct luaL_Reg somemt[] =
 {
  { "__index", l_get   },
  { "__newindex", l_set   },
  { NULL, NULL }
 };

 lua_State *L = luaL_newstate();
 luaL_openlibs( L );

 lua_newuserdata(L, sizeof(void *));

 luaL_newmetatable(L, "somemt");
 luaL_register( L, NULL, somemt );
 lua_setmetatable(L, -2);

 lua_setglobal(L, "cside");

 luaL_dostring(L, "print('from Lua:', cside.myVar)");
 luaL_dostring(L, "cside.myVar = 200");

 printf( "from C: myVar = %d\n", myVar );
}

      

+3


source


Providing your variables for direct modification using only the Lua API is not easy. You need to create a Lua or userdata table (using lua_newtable or lua_newuserdata respectively) and then create a meta table - in your case it should have __index and __newindex events to read and write, and in these functions you must match your variable by name. not fun to write by hand.

However, it should be clear enough that you cannot expose a variable globally in Lua - you must make it a member of the / userdata table. It will be very similar to a class / object from Lua, so just exposing one variable is no easier than exposing a class. What's more, exposing functions / methods is much easier. So reading these tutorials on class exposure will definitely help.



But using only the Lua API is still not fun. Don't get me wrong, the Lua API is neat and great, but if you have a lot to expose it becomes very tedious and you end up either writing a lot of boring repetitive code to bind you to classes or write some a tool to automate this task for you (using a lot of macros is likely to be your first idea, was there, it was done;)). Such tools already exist, tolua ++ , luabind and maybe many others.

+5


source


It looks like you want to look at tolua ++

+2


source







All Articles