2010-09-14 82 views
1

我需要一個非常簡單的C++函數來調用返回字符串數組的lua函數,並將它們存儲爲C++向量。該功能可能如下所示:最簡單的lua函數,返回字符串的向量

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

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

任何想法?

謝謝!

回答

2

以下是一些可能適合您的來源。它可能需要更多的波蘭和測試。它期望Lua塊正在返回字符串數組,但稍作修改就可以調用塊中的命名函數。因此,它可以與"return {'a'}"一起作爲參數,但不作爲參數使用"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; 
} 
+0

非常感謝!你的代碼幫了我很多!但是我忘了一件事,也許你也可以幫助我:我需要lua函數也可以從C++接收一個字符串,所以我需要一個額外的步驟來推送一個字符串參數並從lua函數中訪問它。如果你能提供幫助,這將是非常棒的。再次感謝!! – Koko 2010-09-20 11:56:01

+0

使用'lua_pushstring(L,argument.c_str())'調用'luaL_dostring()'之前,在棧上推動字符串;'然後將'luaL_dostring()'改爲'if(0 == luaL_loadstring(L,lua_source_code。 c_str()))lua_pcall(L,1,1,0));' – gwell 2010-09-21 01:56:59

1

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

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

此時,剩下的唯一要求就是「返回向量」。 現在,您可以使用lua_istable來檢查值是否爲表(數組),並使用lua_gettable來提取多個字段(請參閱http://www.lua.org/pil/25.1.html)並手動將它們逐個添加到向量中。

如果你不知道如何處理堆棧,似乎有一些tutorials可以幫助你。要找到元素的數量,我發現這mailing list post,這可能會有所幫助。

現在,我沒有安裝Lua,所以我無法測試這些信息。但我希望它有幫助。

0

對你的問題不是一個真正的答案:
我寫了C++ < => lua與普通的lua c-api接口代碼時遇到了很多麻煩。然後,我測試了許多不同的lua包裝,如果您試圖獲得更多或更少的複雜性,我真的建議使用luabind。有可能在幾秒鐘內讓類型可用於lua,對智能指針的支持效果很好,(與其他項目相比)文檔或多或少都很好。