Next: 8.3 Manipulating Strings Up: 8 Some Examples Previous: 8.1 Data Structures

8.2 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 = {}           -- create 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: 8.3 Manipulating Strings Up: 8 Some Examples Previous: 8.1 Data Structures