【问题标题】:How to retrieve a returned string by C function in Lua script?如何在 Lua 脚本中检索 C 函数返回的字符串?
【发布时间】:2023-04-02 22:04:01
【问题描述】:

我有一个调用 C 函数的 Lua 脚本。 目前这个函数没有返回任何东西。 我想更改此函数以返回一个字符串,因此在 C 中此函数的末尾,我会将字符串推入堆栈。 在调用 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;
}

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

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

这是我的 Lua 脚本

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

【问题讨论】:

  • 您已经拥有的代码将是一个很好的起点。
  • 请参阅我的答案的“在 LUA 中”部分。
  • 这是 Lua,不是 LUA。 Lua 是葡萄牙语中月亮的意思,不是首字母缩写词。
  • desculpe,我修正了我的答案。

标签: c lua


【解决方案1】:

在 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
}

在 Lua 中

lua_string = foo()

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

请参阅伟大的documentation,了解有关此类任务的更多示例。

【讨论】:

  • 除非你有非常具体的要求,否则接受比你需要的更多的参数是好的做法(并且符合一般的 lua 约定)。
  • @EtanReisner 这是一个很好的观点。根据您的建议,我冒昧地编辑了我的答案。我仍然留下了签入,因为如果你得到更多的参数,你将不得不从堆栈中清除它们。
  • 您不需要清除它们。 lua 在 luaC 转换点为您处理堆栈。您可以简单地推送您的字符串并返回 1,一切正常。如果您从另一个 C 函数调用此函数,则需要保持堆栈清洁。
猜你喜欢
  • 2011-03-08
  • 2017-10-25
  • 2017-01-07
  • 2012-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-06
相关资源
最近更新 更多