There is a primitive function next
, you can call next(t,k)
, where k
is a key of the table t
, returns a next key in the table, in an arbitrary order, and the value associated with this key.
If k
is nil
, next(t,k)
returns the first element if there is one. So you can iterate the table from calling next(t,nil)
and end when the next key is nil
.
This is an simple example to demonstrate the use of next
:
local t = {a = "va", b = "vb", c = "vc"}
local k,v = next(t,nil)
print(k,v)
k,v = next(t,k)
print(k,v)
k,v = next(t,k)
print(k,v)
k,v = next(t,k)
print(k,v)
Output:
a va
c vc
b vb
nil nil