乐闻世界logo
搜索文章和话题

What is the difference between pairs() and ipairs() in Lua?

1个答案

1

In Lua, both pairs() and ipairs() are used for iterating over tables, but their purposes and behaviors differ. I will explain their differences in two aspects: the content being iterated over and the iteration order.

1. Content Being Iterated Over

  • pairs() function iterates over all elements in the table, including both the array portion and the hash portion. It processes all key-value pairs regardless of whether the keys are numbers or strings.

  • ipairs() function is limited to iterating over the array portion of the table, specifically elements with consecutive integer indices. It starts iteration from index 1 and stops when it encounters the first nil value. This means it cannot iterate over non-integer keys or array portions containing nil values in between.

2. Iteration Order

  • pairs() does not guarantee a specific iteration order, as it depends on the internal hash implementation of the table.

  • ipairs() always iterates elements in ascending order of the index, starting from 1, until the last consecutive integer index that is not nil.

Example

Suppose we have the following Lua table:

lua
local tbl = { [1] = "apple", [3] = "banana", "orange", ["four"] = "strawberry" }

When using ipairs() to iterate over this table, the output is:

lua
for i, v in ipairs(tbl) do print(i, v) -- Output: 1 apple end

Note that it only outputs the element at index 1. Since index 2 is nil, ipairs() stops iterating immediately after that.

When using pairs() to iterate over this table, the output is:

lua
for key, value in pairs(tbl) do print(key, value) -- Possible output (order is not guaranteed): -- 1 apple -- 3 banana -- 1 orange -- four strawberry end

Here, pairs() outputs all key-value pairs, regardless of whether the keys are integers or strings.

Conclusion

  • When using ipairs(), it is a suitable choice if you are certain the table is a pure array or that array indices are consecutive.
  • When using pairs(), it is appropriate for cases requiring iteration over the entire table, including non-consecutive index arrays and hash portions.

I hope this clearly explains the differences between pairs() and ipairs(), helping you make more appropriate choices in practical usage.

2024年7月25日 13:50 回复

你的答案