0Pricing
Lua Academy · Lesson

Generic for and break

Use generic for with pairs/ipairs and control loop flow with break.

Generic for Protocol

Lua's generic for loop works with an iterator function. The syntax is for vars in iter_func, state, init do. On each iteration, Lua calls iter_func(state, lastVar) and assigns return values to vars. The loop stops when the first return value is nil.

-- Manual use of next() iterator
local t = {a=1, b=2, c=3}
local key, val = next(t, nil)   -- first entry
while key ~= nil do
  print(key, val)
  key, val = next(t, key)       -- advance
end

pairs() for All Keys

pairs(t) returns an iterator that traverses all key-value pairs in a table, including string keys, integer keys, and mixed. The iteration order for non-integer keys is unspecified (hash order). Array portion and hash portion are both included.

local config = {
  host = "localhost",
  port = 8080,
  debug = true,
  [1] = "first",
}

for key, value in pairs(config) do
  print(key, value)
end
-- Prints all 4 entries in any order

All lessons in this course

  1. if, elseif and else Statements
  2. while and repeat-until Loops
  3. Numeric for Loop
  4. Generic for and break
← Back to Lua Academy