I'm trying to learn Lua scripting from within C and I'm now stuck on this (simple?) problem. I want to pass a value from C to Lua, and then get a value from Lua back to C.
Here's an example of a piece of C-code which gets a value from Lua and which works fine for me:
Expand|Select|Wrap|Line Numbers
- int test_Lua()
- {
- lua_State *L=lua_open();
- char myArg[] = "result = \"Lua-string\"";
- luaL_dostring(L,myArg);
- lua_pushstring(L,"result");
- lua_gettable(L,LUA_GLOBALSINDEX);
- char *result = lua_tostring(L,-1);
- printf("\nValue of result fetched from Lua: %s\n",result);
- lua_close(L);
- return 0;
- }
Value of result fetched from Lua: Lua-string
However, I want to pass a string from C to Lua and in Lua concatenate it with another string and then pass the result back to C again.
This is how I try to do it:
Expand|Select|Wrap|Line Numbers
- int test_Lua2()
- {
- lua_State *L=lua_open();
- char myArg[] = "result = \"Lua-string and\" .. cstr";
- char cstr[] = "C-string";
- lua_pushstring(L,cstr); /*This is how I try to pass the c-string to Lua*/
- /*I now 'assume' the c-string is at the top of the Lua stack, so Lua should know it (?)*/
- luaL_dostring(L,myArg);
- lua_pushstring(L,"result");
- lua_gettable(L,LUA_GLOBALSINDEX);
- char *result = lua_tostring(L,-1);
- printf("\nValue of result fetched from Lua: %s\n",result);
- lua_close(L);
- return 0;
- }
(I get the printout "Value of result fetched from Lua: (null)")
Does anyone know what I'm doing wrong and how to do it right?
Any help greatly appreciated!
Cheers