[英]using lua with c++ dll
我開始與lua一起使用C ++ dll。 很難開始。 我需要幫助來處理表格。 我在C ++代碼中執行以下操作:
static int forLua_AddTwoNumbers(lua_State *L) {
double d1 = luaL_checknumber(L, 1);
double d2 = luaL_checknumber(L, 2);
lua_pushnumber(L, d1 + d2);
return(1);
}
並在lua中調用此函數:
r = runfast.AddTwoNumbers(2, 5)
有用。 我如何用這樣的表做同樣的事情:
lua table t={1=20, 2=30, 3=40}
我假設您要問如何將數組中的所有值相加?
static int forLua_SumArray (lua_State* L) {
// Get the length of the table (same as # operator in Lua)
int n = luaL_len(L, 1);
double sum = 0.0;
// For each index from 1 to n, get the table value as a number and add to sum
for (int i = 1; i <= n; ++i) {
lua_rawgeti(L, 1, i);
sum += lua_tonumber(L, -1);
lua_pop(L, 1);
}
lua_pushnumber(L, sum);
return 1;
}
順便說一下,在Lua中, t={1=20, 2=30, 3=40}
20,2 t={1=20, 2=30, 3=40}
30,3 t={1=20, 2=30, 3=40}
可以更簡單地寫為t={20, 30, 40}
。 這就是通常寫數組的方式。
您可能還想看看手冊中用於匯總可變數量的arguments的示例代碼 。 與您在此處執行的操作幾乎相同,除了您可能更喜歡傳遞多個參數而不是必須使用表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.