typestar

pairs and ipairs in Lua

ipairs walks the array part in order; pairs walks every key.

-- ipairs walks the array part in order; pairs walks every key.
local loot = { "coin", "coin", "idol" }
for i, item in ipairs(loot) do
  print(i .. ". " .. item)
end

local prices = { idol = 300, coin = 1, lantern = 12 }
local total_kinds = 0
for item, price in pairs(prices) do
  total_kinds = total_kinds + 1
  print(string.format("%s sells for %d", item, price))
end
print(total_kinds .. " kinds appraised")

How it works

  1. ipairs stops at the first nil hole.
  2. pairs visits string keys too, in no promised order.
  3. Both drive the same generic for k, v in shape.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
404
Tokens
94
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 87 seconds.

Type this snippet

Step 3 of 4 in Tables, step 9 of 27 in Language basics.

← Previous Next →