Next
- A stateless iterator of key-value pairs for all elements in a table.
- tbl
-
- The table.
- key
-
- The current key.
The next()
function is the stateless iterator that underpins pairs()
, as used in for k,v in pairs(t)
to iterate over all elements in a table. It takes the table and the current key and returns the next key/value pair, or nil if there isn't one. The key passed in may be omitted or nil to retrieve the first key/value pair of the table.
Under normal conditions, next()
is not referred to directly, instead being supplied under the hood by pairs()
. However, it has its uses. For instance, it can be called with just the table to get the first key/value pair, and thus determine quickly whether or not the table is empty:
function empty(tbl)
-- note that we compare to nil, since 'false' is a legal key
return next(tbl) == nil
end
As noted with pairs()
, this will iterate over 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.
Also note that the concept of "next" here is based on the next value in the internal representation of the table (an unordered hash table). This does not guarantee the order in which the results are returned, only that you will see all entries in the table exactly once.
Examples
t = {n=42, x=100, y=200}
-- write "for k, v in pairs(t) do ... end" manually
local k, v
while true do
k,v = next(t, k)
if(k == nil) break
print(k..': '..v)
end
-- output:
-- x: 100
-- y: 200
-- n: 42