【IT168 技术文档】遍历表的方式
第一, 我们可以简单的遍历表中有效索引的值.
for i=1,table.getn(tbl) do local v=tbl[i]; ... end
第二, 或许这样的方式更加常见.
for i,v in ipairs(tbl) do ... end
第三, 你可以使用内建方法, table.foreachi
table.foreachi(tbl, function(i,v) ... end);
Stylistically, 我更倾向于第三种方法, 简洁明了. 其次是第二种方式.
第三种形式要比前2中方法高级, 即使他也会被书写为多行. 在Lua中, 可以使用break语句来中断循环. 某些语言中提供中断单一迭代循环并且继续下一次循环的语句. 在table.foreachi中, return语句会中断循环, 如果退出后函数返回一个非空值, 则会通过table.foreachi返出.
table.foreachi(tbl, function(i,v) ... if (deeplyNestedTestToIgnoreSomething) then return; --skip to next end ... end);