如何在Lua脚本中通过C函数检索返回的字符串?

Fou*_*uda 4 c lua

我有一个调用C函数的Lua脚本.目前这个函数什么也没有返回.我想更改此函数以返回一个字符串,因此在CI中此函数的末尾会将字符串推入Stack.在调用Lua脚本中,我需要取回推送的字符串值.

C初始化和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;
}
Run Code Online (Sandbox Code Playgroud)

这是我的函数返回一个字符串:

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

这是我的Lua脚本

cliCmd("Anything here doesn't matter");
# I want to retreive the string str pushed in the c function.
Run Code Online (Sandbox Code Playgroud)

Ste*_*vel 5

在C你有类似的东西

 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
}
Run Code Online (Sandbox Code Playgroud)

在Lua

lua_string = foo()
Run Code Online (Sandbox Code Playgroud)

这假设您已经使用lua_register注册了您的函数

请阅读有关这些类型任务的更多示例的精彩文档.

  • 你不需要清除它们.lua在lua < - > C转换点为你处理堆栈.你可以简单地推动你的字符串并返回1并且一切正常.如果您从另一个C函数调用此函数,则需要保持堆栈清洁. (4认同)
  • 除非你有非常具体的要求接受比你需要的更多的参数是好的做法(并且符合一般的lua惯例). (2认同)