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

Asked

Viewed 1,273 times

3

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 the "ipairs" instead of the "pairs", returns nothing.

2 answers

3

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 hole between the keys.

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

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

See an 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

Exit:

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

ipairs:
1   alpha
2   bravo
3   charlie

1

The "pairs" iterator traverses the entire table.

The iterator iterator "ipairs" traverses the table using the indexes/keys 1, 2, etc.
Your table has no keys 1, 2, etc., its keys are "rice" and "beans", so the iterator does not run at all.

The example below with ipairs should work (warning: 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.