5

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.
4
  • 1
    The code you have already would be a nice starting point for an answer to work off of. Commented Nov 5, 2013 at 17:53
  • See the 'In LUA' section of my answer. Commented Nov 5, 2013 at 18:17
  • 2
    It is Lua, not LUA. Lua is the Portuguese word for moon, not an acronym. Commented Nov 5, 2013 at 21:18
  • desculpe, I fixed my answer. Commented Nov 5, 2013 at 23:39

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Unless you have very specific requirements accepting more arguments than you need is good practice (and matches general lua conventions).
@EtanReisner That is a great point. I took the liberty of editing my answer per your suggestion. I still left the check in, because if you get more arguments you will have to clear them from the stack.
You don't need to clear them. lua handles the stack for you at the lua<->C transition points. You can simply push your string and return 1 and everything works. If you were calling this function from another C function you would need to maintain stack cleanliness though.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.