簡體   English   中英

如何訪問 lua_pcall 調用的 C function 的返回值?

[英]How to access the return value of a C function called by lua_pcall?

我有這個 function:

static int generic_pcall_wrapper(lua_State* L, int (*funct)(lua_State*)){
    int narg = lua_gettop(L);
    lua_pushcfunction(L, funct);
    lua_rotate(L, 1, 1);

    int res = lua_pcall(L, narg, LUA_MULTRET, 0);
    if(res != 0){
        //handle error
    }
    return ??; // I would like to return 1 as in sum()
}

static int sum(lua_State* L){
    int a = lua_tointeger(L, -1);
    int b = lua_tointeger(L, -2);    
    lua_pop(L, 1);   
    lua_pushnumber(L, a + b);
    return 1;
}

static int foo(lua_State* L){
    return generic_pcall_wrapper(L, sum);
}

我想讓 generic_pcall_wrapper() 返回 sum() 返回的值。

請注意,此 function 應該采用許多不同的函數,並且未指定它們如何處理返回值,唯一可靠的值是每個函數返回的數字。

我不太明白的第一件事是總和function中需要lua_pop 這個對 lua_pop 的調用非常不尋常,並且在官方示例中沒有出現。

static int sum(lua_State* L)
{
  int a = lua_tointeger(L, -1);
  int b = lua_tointeger(L, -2);    
  lua_pop(L, 1); /* unusual, probably not needed */
  lua_pushnumber(L, a + b);
  return 1;
}

關於原始問題,在回調sum中,返回值表示已將多少結果壓入堆棧。 此值由 Lua 運行時使用,並且對 Lua API 的用戶不可用。 因此,如果 API 用戶稍后需要此值,則需要使用 Lua 函數保存此值。

對於 Lua API,很自然的做法是將其推入堆棧。

static int sum(lua_State* L)
{
  int a = lua_tointeger(L, -1);
  int b = lua_tointeger(L, -2);
  lua_pushnumber(L, a + b); /* push the result of sum          */
  lua_pushinteger(L, 1);    /* sum return 1 value on the stack */
  return 2; /* return all the values (sum) and then #values */
}

然后:

  1. 通用包裝器獲取堆棧上返回值的數量
  2. 包裝器從堆棧中移除這個特殊值
  3. 返回給調用者的值的數量
static int generic_pcall_wrapper(lua_State* L, int (*funct)(lua_State*))
{
  int narg = lua_gettop(L);
  lua_pushcfunction(L, funct);

  //push argument again, but above the function
  int stack_size = lua_gettop(L);
  
  for (int i = 1; i < stack_size; i++)
    lua_pushvalue(L, i);
    
  int res = lua_pcall(L, narg, LUA_MULTRET, 0);

  /* Get the number of values which have been pushed */
  int res_count = lua_tointeger(L, -1);

  /* Remove the number of values */
  lua_pop(L);

  return res_count;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM