Lua table pair和ipair区别
2014-06-20 15:10 youxin 阅读(1402) 评论(0) 编辑 收藏 举报官方描述:
ipairs (t)
Returns three values: an iterator function, the table t, and 0, so that the construction
for i,v in ipairs(t) do body end
will iterate over the pairs (1,t[1]), (2,t[2]), ···, up to the first integer key absent from the table.
pairs (t)
Returns three values: the next function, the table t, and nil, so that the construction
for k,v in pairs(t) do body end
will iterate over all key–value pairs of table t.
See function next for the caveats of modifying the table during its traversal.
这样就可以看出 ipairs以及pairs 的不同。pairs可以遍历表中所有的key,并且除了迭代器本身以及遍历表本身还可以返回nil;但是ipairs则不能返回nil,只能返回数字0,如果遇到nil则退出。它只能遍历到表中出现的第一个不是整数的key。
- local tabFiles = {
- [3] = "test2",
- [6] = "test3",
- [4] = "test1"
- }
- for k, v in ipairs(tabFiles) do
- print(k, v)
- end
猜测它的输出结果是什么呢?根据刚才的分析,它在 ipairs(tabFiles) 遍历中,当key=1时候value就是nil,所以直接跳出循环不输出任何值。
那么,如果是
- for k, v in pairs(tabFiles) do
- print(k, v)
- end
则会输出所有:
- >lua -e "io.stdout:setvbuf 'no'" "test.lua"
- 3 test2
- 6 test3
- 4 test1
- >Exit code: 0
现在改变一下表内容,
- local tabFiles = {
- [1] = "test1",
- [6] = "test2",
- [4] = "test3"
- }
- for k, v in ipairs(tabFiles) do
- print(k, v)
- end
现在的输出结果显而易见就是key=1时的value值test1。
更多:http://blog.csdn.net/tony7758/article/details/6334001
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通