(→Examples: syntax highlighting) |
(Adding categories) |
||
(9 intermediate revisions by 2 users not shown) | |||
Line 4: | Line 4: | ||
|tbl||The table. |
|tbl||The table. |
||
}} |
}} |
||
− | The <code>pairs()</code> function is used exclusively with <code>for...in</code> to iterate over all elements in a table. It emits the key and value together, which you can assign to variables in the <code>for</code> loop: |
+ | The <code>pairs()</code> iterator function is used exclusively with <code>for...in</code> to iterate over all elements in a table. It emits the key and value together, which you can assign to variables in the <code>for</code> loop: |
<syntaxhighlight lang="lua"> |
<syntaxhighlight lang="lua"> |
||
for k, v in pairs(tbl) do |
for k, v in pairs(tbl) do |
||
Line 11: | Line 11: | ||
</syntaxhighlight> |
</syntaxhighlight> |
||
− | + | This iterator produces every value in the table, not just those with sequential indices. It can produce keys and values for tables being used as mappings (dictionaries) or objects. |
|
+ | Be warned that results are not produced in any guaranteed order. Some small tables may seem to iterate in order, but that is purely coincidental behavior which should ''not'' be relied upon. |
||
− | <code>pairs()</code> does not guarantee the order in which the results are returned. |
||
== Examples == |
== Examples == |
||
Line 38: | Line 38: | ||
* [[Lua]] |
* [[Lua]] |
||
* [[Tables]] |
* [[Tables]] |
||
− | * [[Add|add]] |
+ | * [[Add|<code>add()</code>]] |
− | * [[All|all]] |
+ | * [[All|<code>all()</code>]] |
− | * [[Del|del]] |
+ | * [[Del|<code>del()</code>]] |
− | * [[Foreach|foreach]] |
+ | * [[Foreach|<code>foreach()</code>]] |
− | * [[ |
+ | * [[IPairs|<code>ipairs()</code>]] |
+ | * [[Next|<code>next()</code>]] |
||
[[Category:Reference]] |
[[Category:Reference]] |
||
[[Category:API]] |
[[Category:API]] |
||
+ | [[Category:Iterators]] |
||
+ | [[Category:Lua]] |
Latest revision as of 21:29, 12 March 2021
pairs( tbl )
- Returns an iterator of key-value pairs for all elements in a table, for use with
for...in
.
- tbl
-
- The table.
The pairs()
iterator function is used exclusively with for...in
to iterate over all elements in a table. It emits the key and value together, which you can assign to variables in the for
loop:
for k, v in pairs(tbl) do
-- ...
end
This iterator produces every value in the table, not just those with sequential indices. It can produce keys and values for tables being used as mappings (dictionaries) or objects.
Be warned that results are not produced in any guaranteed order. Some small tables may seem to iterate in order, but that is purely coincidental behavior which should not be relied upon.
Examples[]
t = {111, 222, 333}
for k, v in pairs(t) do
print(k..': '..v)
end
-- 1: 111
-- 2: 222
-- 3: 333
t = {n=42, x=100, y=200}
for k, v in pairs(t) do
print(k..': '..v)
end
-- x: 100
-- y: 200
-- n: 42