推荐答案
在 Lua 中,遍历 table 的常见方法有以下几种:
使用
pairs函数:local t = {a = 1, b = 2, c = 3} for key, value in pairs(t) do print(key, value) endpairs函数会遍历 table 中的所有键值对,适用于非数组部分的 table。使用
ipairs函数:local t = {10, 20, 30} for index, value in ipairs(t) do print(index, value) endipairs函数会从索引 1 开始,依次遍历 table 中的数组部分,直到遇到nil。使用数值
for循环:local t = {10, 20, 30} for i = 1, #t do print(i, t[i]) end这种方法适用于数组部分的 table,通过
#t获取 table 的长度。
本题详细解读
pairs 函数
pairs 是 Lua 中用于遍历 table 的通用函数。它会返回一个迭代器函数,用于遍历 table 中的所有键值对。pairs 不保证遍历的顺序,适用于遍历非数组部分的 table。
ipairs 函数
ipairs 是 Lua 中用于遍历数组部分的 table 的函数。它从索引 1 开始,依次遍历 table 中的元素,直到遇到 nil。ipairs 适用于遍历数组部分的 table,且保证遍历的顺序。
数值 for 循环
数值 for 循环是一种常见的遍历数组部分 table 的方法。通过 #t 获取 table 的长度,然后从 1 开始遍历到 table 的长度。这种方法适用于数组部分的 table,且保证遍历的顺序。
选择遍历方法
- 如果需要遍历 table 中的所有键值对,且不关心顺序,使用
pairs。 - 如果需要遍历数组部分的 table,且关心顺序,使用
ipairs或数值for循环。 - 如果 table 是纯数组(即所有键都是连续的整数),数值
for循环和ipairs都可以使用。