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

我有一个 Lua 脚本调用了一个 C 函数。 目前这个函数没有返回任何值。 我想把这个函数修改成返回一个字符串,所以在 C 函数的末尾我会把字符串推入 Stack 中。 在调用 Lua 脚本中,我需要获取推送的字符串值。

C 的初始化和注册 Lua

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

   // 新建一个 Lua 状态机
   L = lua_newstate(&luaAlloc, ud);

   /* 加载各种 Lua 库 */
   luaL_openlibs(L);

   /* 注册从 Lua 脚本中调用的执行命令的函数 */
   lua_register(L,"CliCmd",cli_handle_lua_commands);

   //lua_close(L);
   return;
}

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

static int cli_handle_lua_commands(lua_State *L){
   ...
   ...
   char* str = ....; /*指向某个字符串的 char 指针*/
   lua_pushstring(L, str);
   retun 1;
}

这是我的 Lua 脚本

cliCmd("无论什么都没关系");
# 我想获取在 C 函数中推入的字符串 str。
点赞
用户141727
用户141727

在C语言中你可以这样写:

static int foo (lua_State *L) {
   int n = lua_gettop(L);
   //n是参数的数量,如果需要可以使用

  lua_pushstring(L, str); //str是指向字符串的const char*
  return 1; //我们返回一个值,即字符串
}

在Lua中,可以这样写:

lua_string = foo()

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

请查看优秀的文档以了解更多这类任务的示例。

2013-11-05 18:01:48