What is the difference between "in pairs" and "in ipairs" in Lua?

produtos = {
    arroz = 10,
    feijao = 15
}

for produtos, valor in pairs(produtos) do
    print(produtos .. " custa R$" .. valor)
end

Returns:

feijao custa R$15
arroz custa R$10

But when I use "ipairs" instead of" pairs", it returns nothing.

 3
lua
Author: accv, 2019-04-13

2 answers

The ipairs returns an iterator of ordered key-value pairs. It only iterates from numeric keys, needing to be necessarily sequential, starting from 1 and having no holes between the keys.

This is why your loop doesn't work, its keys are a string, causing it to return an empty iterator.

Already pairs returns an iterator of arbitrary order, it works independent of the established key, and can be of any type.

See a example to better understand the differences:

local tbl = { two = 2, one = 1, "alpha", "bravo", [3] = "charlie", [5] = "echo", [6] = "foxtrot" }

print( "pairs:" )
for k, v in pairs( tbl ) do
    print( k, v )
end

print( "\nipairs:" )
for k, v in ipairs( tbl ) do
    print( k, v )
end

Output:

pairs:
1   alpha
2   bravo
3   charlie
5   echo
6   foxtrot
one 1
two 2

ipairs:
1   alpha
2   bravo
3   charlie
 3
Author: Francisco, 2019-12-26 03:20:30

The "pairs" iterator traverses the entire table.

Iterator iterator "ipairs" traverses the table using indexes / Keys 1, 2, etc.
Your table has no keys 1, 2, etc, its keys are " rice "and" bean", so the iterator doesn't run any times.

The example below with ipairs should work (warning: I have not tested)

local val_prod  = { 10, 15 }
local nome_prod = { "arroz", "feijao" }

for i, valor in ipairs(val_prod) do
    print(nome_prod[i] .." custa R$" .. valor)
end
 1
Author: zentrunix, 2019-04-13 19:09:03