我开始与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}
答案 0 :(得分:0)
我假设您在问如何将数组中的所有值相加?
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}
可以更简单地写为t={20, 30, 40}
。通常就是这样写数组的。
您可能还想看看manual's example code for summing a variable number of arguments。除了您可能更喜欢传递多个参数而不需要使用表之外,与我们在此处所做的几乎相同。