如何在 C API 中生成 ipairs(而不是对)行为 [英] How to produce ipairs (as opposed to pairs) behavior in the C API

查看:28
本文介绍了如何在 C API 中生成 ipairs(而不是对)行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Lua 中,pairsipairs 可以以不同的顺序迭代相同的元素:

In Lua, pairs and ipairs can iterate over the same elements in a different order:

> t = {[1]=1, [2]=2, [3]=3}
> for k,v in pairs(t) do print(k,v) end
2       2
1       1
3       3
> for k,v in ipairs(t) do print(k,v) end
1       1
2       2
3       3

在使用 C API 时,我只看到一个用于遍历表的工具:lua_next() 函数的作用非常像 pairs() Lua 函数,它产生上面显示的 2-1-3 顺序.

When using the C API, I see only one tool for iterating over a table: the lua_next() function which acts very much like the pairs() Lua function which produces the 2-1-3 order shown above.

我正在寻找一种高效的 C 方法来按顺序迭代表的整数键(ipairs 的 C API 版本).

I am looking for an efficient C method for iterating over the integer keys of a table sequentially(a C API version of ipairs).

天真地,我考虑过:

int tableLength = luaL_len(L, tableIndex);
for (i=0, i++, i>tableLength){   
    // if t[i] is not null ...
}

但我不清楚表大小与连续整数键的数量不匹配的潜在性能问题:

but I am unclear of potential performance issues where table sizes do not match the number of consecutive integer keys:

t = {[1]=1, [2]=2, [4]=4}     -- has a (reported) length of 4
t = {[1]=1, [2]=2, [40000]=4} -- has a (reported) length of 2

如果这确实是 ipairs 的做法,那么是否有一种简单的方法可以开始使用 lua_next 和最后找到的整数键继续遍历表的其余部分,避免再次遍历整数键部分?这样做我有没有机会看到一些整数键两次?

If this is indeed the way ipairs does it, then is there an easy way to start using lua_next with the last found integer key to continue to walk the rest of the table avoiding walking the integer-key portion again? Is there a chance I will see some integer keys twice by doing so?

推荐答案

你只需要使用 rawgeti 直到你得到一个 nil 键:

You just use rawgeti until you get a nil key:

// Tabs is on top of stack
for ( int i=1 ; ; i++ ) {
    lua_rawgeti(L,-1,i);
    if ( lua_isnil(L,-1) ) {
        lua_pop(L,1);
        break;
    }
    /* Do something */
    lua_pop(L,1);
}

通过查看源代码,您可以看到 ipairs 在内部是这样做的:http://www.lua.org/source/5.1/lbaselib.c.html#ipairsaux

By looking at the source you can see that this is what ipairs does internally: http://www.lua.org/source/5.1/lbaselib.c.html#ipairsaux

这篇关于如何在 C API 中生成 ipairs(而不是对)行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆