No edit summary Tags: Visual edit apiedit |
(→Examples: syntax highlighting) |
||
Line 5: | Line 5: | ||
}} |
}} |
||
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> 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"> |
||
− | <pre> |
||
for k, v in pairs(tbl) do |
for k, v in pairs(tbl) do |
||
-- ... |
-- ... |
||
end |
end |
||
+ | </syntaxhighlight> |
||
− | </pre> |
||
<code>pairs()</code> returns every value in the table, not just those with sequential indexes. It can return keys and values for tables being used as mappings (dictionaries) or objects. |
<code>pairs()</code> returns every value in the table, not just those with sequential indexes. It can return keys and values for tables being used as mappings (dictionaries) or objects. |
||
Line 16: | Line 16: | ||
== Examples == |
== Examples == |
||
+ | <syntaxhighlight lang="lua"> |
||
− | <pre> |
||
t = {111, 222, 333} |
t = {111, 222, 333} |
||
for k, v in pairs(t) do |
for k, v in pairs(t) do |
||
Line 32: | Line 32: | ||
-- y: 200 |
-- y: 200 |
||
-- n: 42 |
-- n: 42 |
||
+ | </syntaxhighlight> |
||
− | </pre> |
||
== See also == |
== See also == |
Revision as of 02:49, 13 February 2018
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()
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
pairs()
returns every value in the table, not just those with sequential indexes. It can return keys and values for tables being used as mappings (dictionaries) or objects.
pairs()
does not guarantee the order in which the results are returned.
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