Next: 7.2 Manipulating Strings Up: 7 Some Examples Previous: 7 Some Examples

7.1 The Functions next and nextvar

This example shows how to use the function next to iterate over the fields of a table. Function clone receives any table and returns a clone of it.
function clone (t)           -- t is a table
  local new_t = {}           -- creates a new table
  local i, v = next(t, nil)  -- i is an index of t, v = t[i]
  while i do
    new_t[i] = v
    i, v = next(t, i)        -- get next index
  end
  return new_t
end

The next example prints the names of all global variables in the system with non nil values:

function printGlobalVariables ()
  local i, v = nextvar(nil)
  while i do
    print(i)
    i, v = nextvar(i)
  end
end


Next: 7.2 Manipulating Strings Up: 7 Some Examples Previous: 7 Some Examples