4
votes

I have a Lua script which is calling a C function. Currently this function is returning nothing. I want to change this function to return a string, so at the end of this function in C I will push the string into Stack. Inside the calling Lua script I need to get back the pushed string value.

C initialization and registration with Lua

void cliInitLua( void )
{
   void* ud = NULL;
   Task task;

   // Create a new Lua state
   L = lua_newstate(&luaAlloc, ud);

   /* load various Lua libraries */
   luaL_openlibs(L);

   /*Register the function to be called from LUA script to execute commands*/
   lua_register(L,"CliCmd",cli_handle_lua_commands);

   //lua_close(L);
   return;
}

This is my c Function to return a string:

static int cli_handle_lua_commands(lua_State *L){
   ...
   ...
   char* str = ....; /*Char pointer to some string*/
   lua_pushstring(L, str);
   retun 1;
}

This is my Lua script

cliCmd("Anything here doesn't matter");
# I want to retreive the string str pushed in the c function.
1
The code you have already would be a nice starting point for an answer to work off of.Stephan van den Heuvel
See the 'In LUA' section of my answer.Stephan van den Heuvel
It is Lua, not LUA. Lua is the Portuguese word for moon, not an acronym.Lorenzo Donati -- Codidact.com
desculpe, I fixed my answer.Stephan van den Heuvel

1 Answers

5
votes

In C you have something like

 static int foo (lua_State *L) {
   int n = lua_gettop(L);
   //n is the number of arguments, use if needed

  lua_pushstring(L, str); //str is the const char* that points to your string
  return 1; //we are returning one value, the string
}

In Lua

lua_string = foo()

This assumes you have already registered your function with lua_register

Pleas see the great documentation for more examples on these sorts of tasks.