[英]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.