FANDOM


all( tbl )

Returns an iterator for all non-nil items in a sequence in a table, for use with for...in.

tbl
The table to iterate.

The all() function is used exclusively with for...in to iterate over all elements in a sequence in a table. Each non-nil value in the sequence is emitted in sequence order.

Specifically, all() starts at index 1, then steps forward through the table until it reaches the final index, emitting only the elements which are not nil.

When used with a table that contains only unique elements, it is safe to delete the current loop iteration's element from the table. For instance, given a table of all whole numbers, it would be safe to iterate over it and delete prime numbers when they are found. However, in a table with duplicate entries, behavior is undefined and a different method should be used.

Examples Edit

t = {1, 3, nil, 5}
add(t, 7)
add(t, 9)
 
for v in all(t) do
  print(v)  -- prints 1, 3, 5, 7, 9
end
 
function no_primes(t)
  for e in all(t) do
    if is_prime(e) then
      del(t, e)
    end
  end
end

Technical note Edit

Iterating with all() is good because it makes your code both concise and easy to read. When you need to iterate over objects in a table, in order, it's often the preferred method.

It should be noted, though, that this iterator needs to do some extra work to traverse the table in order. This causes it to be a little slower, per iteration, than using pairs() (which does not guarantee order) or a purely-numeric for loop.

Luckily, this is seldom an issue, as the code inside most loops significantly outweighs this overhead. However, in some tight, high-performance loops, it may have a noticeable impact on throughput. In those cases, it may be worth considering other options.

See also Edit