Loops/Foreach: Difference between revisions

Add Lua implementation
(pike)
(Add Lua implementation)
Line 256:
print i
)</lang>
 
=={{header|Lua}}==
Lua has 2 built-in iterators over tables.
 
<code>pairs()</code> iterates over all entries in a table, but in no particular order:
<lang lua>
t={monday=1, tuesday=2, wednesday=3, thursday=4, friday=5, saturday=6, sunday=0, [7]="fooday"}
for key, value in pairs(t) do
print(value, key)
end
</lang>
 
Output:
<pre>
0 sunday
fooday 7
2 tuesday
3 wednesday
5 friday
4 thursday
6 saturday
1 monday
</pre>
 
<code>ipairs()</code> iterates over table entries with positive integer keys,
and is used to iterate over lists in order.
<lang lua>
l={'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday', not_a_number='fooday', [0]='today', [-1]='yesterday' }
for key, value in ipairs(l) do
print(key, value)
end
</lang>
 
Output:
<pre>
1 monday
2 tuesday
3 wednesday
4 thursday
5 friday
6 saturday
7 sunday
</pre>
 
Note that <code>ipairs()</code> ignores non-numeric and non-positive integer keys.
 
=={{header|Metafont}}==
Anonymous user