备份个可用的测试代码
[C] 纯文本查看 复制代码 int getdata(lua_State* L) {
// 参数检查
if (lua_gettop(L) != 2 || !lua_istable(L, 1) || !lua_isnumber(L, 2)) {
return luaL_error(L, "usage: getdata(table, count)");
}
int count = lua_tointeger(L, 2);
// 安全限制
if (count > 1000) count = 1000;
if (count < 0) count = 0;
// 第一阶段:收集所有数据到临时数组,同时清空栈
double* temp_values = (double*)malloc(count * sizeof(double));
if (temp_values == NULL) {
return luaL_error(L, "memory allocation failed");
}
for (int i = 1; i <= count; i++) {
lua_rawgeti(L, 1, i); // 获取table[i]
if (lua_isnumber(L, -1)) {
temp_values[i-1] = lua_tonumber(L, -1);
} else {
temp_values[i-1] = 0.0; // 非数字默认为0.0
}
lua_pop(L, 1); // 立即pop,保持栈清洁
}
// 此时栈应该只有最初的2个参数
// 清空栈,只保留我们需要的结果
lua_settop(L, 0);
// 第二阶段:创建结果table并填充数据
lua_newtable(L);
for (int i = 0; i < count; i++) {
lua_pushnumber(L, temp_values[i]);
lua_rawseti(L, -2, i + 1);
}
// 释放临时数组
free(temp_values);
return 1; // 返回table
}
|