簡體   English   中英

返回字符串向量的最簡單的lua函數

[英]Simplest lua function that returns a vector of strings

我需要一個非常簡單的c ++函數,該函數調用lua函數,該函數將返回字符串數組,並將其存儲為c ++向量。 該函數可以如下所示:

std::vector<string> call_lua_func(string lua_source_code);

(其中lua源代碼包含一個lua函數,該函數返回字符串數組)。

有任何想法嗎?

謝謝!

這是一些可能對您有用的資源。 它可能需要更多的拋光和測試。 它期望Lua塊返回字符串數組,但是稍加修改就可以在塊中調用命名函數。 因此,按原樣,它使用"return {'a'}" "function a() return {'a'} end"作為參數,而不使用"function a() return {'a'} end"作為參數。

extern "C" {
#include "../src/lua.h"
#include "../src/lauxlib.h"
}

std::vector<string> call_lua_func(string lua_source_code)
{
  std::vector<string> list_strings;

  // create a Lua state
  lua_State *L = luaL_newstate();
  lua_settop(L,0);

  // execute the string chunk
  luaL_dostring(L, lua_source_code.c_str());

  // if only one return value, and value is a table
  if(lua_gettop(L) == 1 && lua_istable(L, 1))
  {
    // for each entry in the table
    int len = lua_objlen(L, 1);
    for(int i=1;i <= len; i++)
    {
      // get the entry to stack
      lua_pushinteger(L, i);
      lua_gettable(L, 1);

      // get table entry as string
      const char *s = lua_tostring(L, -1);
      if(s)
      {
        // push the value to the vector
        list_strings.push_back(s);
      }

      // remove entry from stack
      lua_pop(L,1);
    }
  }

  // destroy the Lua state
  lua_close(L);

  return list_strings;
}

首先,請記住Lua數組不僅可以包含整數,還可以包含其他類型作為鍵。

然后,您可以使用luaL_loadstring導入Lua源代碼。

此時,剩下的唯一要求是“返回向量”。 現在,您可以使用lua_istable檢查值是否為表格(數組),並使用lua_gettable提取多個字段(請參見http://www.lua.org/pil/25.1.html ),然后手動逐個手動添加它們向量。

如果您不知道如何處理堆棧,似乎有一些教程可以為您提供幫助。 為了找到元素的數量,我找到了此郵件列表帖子 ,這可能會有所幫助。

目前,我尚未安裝Lua,因此無法測試此信息。 但我希望它能有所幫助。

並不是您問題的答案:
用普通的lua c-api編寫c ++ <=> lua接口代碼時遇到了很多麻煩。 然后,我測試了許多不同的lua-wrapper,如果您要嘗試實現或多或少的復雜性,我真的建議luabind 可以在幾秒鍾內將類型提供給lua,對智能指針的支持非常有用,並且(與其他項目相比)該文檔或多或少都很好。

暫無
暫無

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

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