Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lua: iterate through all pairs in table

I have a sparse lua table and I need to iterate over it. The Problem is, it seems that lua begins the iteration at 1, and terminates as soon as it finds a nil value. Here's and example:

> tab={}
> tab[2]='b'
> tab[5]='e'
> for i,v in ipairs(tab) do print(i,v) end
>               --nothing is output here
> tab[1]='a'
> for i,v in ipairs(tab) do print(i,v) end
1   a
2   b
>               --terminates after 2 (first nil value is tab[3])

Is there any way to get the desired output:

1   a
2   b
5   e
like image 317
ewok Avatar asked Sep 25 '12 13:09

ewok


People also ask

How do you iterate through a table in Lua?

For tables using numeric keys, Lua provides an ipairs function. The ipairs function will always iterate from table[1] , table[2] , etc. until the first nil value is found. A final way to iterate over tables is to use the next selector in a generic for loop.

What does Ipairs mean in Lua?

The ipairs() function will allow iteration over index-value pairs. These are key-value pairs where the keys are indices into an array. The order in which elements are returned is guaranteed to be in the numeric order of the indices, and non-integer keys are simply skipped.

What pairs return Lua?

LuaServer Side ProgrammingProgramming. In Lua, we make use of both the pairs() and ipairs() function when we want to iterate over a given table with the for loop. Both these functions return key-value pairs where the key is the index of the element and the value is the element stored at that index table.

What is next Lua?

Lua next is a function in Lua programming used to Traverse all the fields in a Table. Lua is an open-source programming language on top of the C language. It has its values across multiple platforms in both small mobile applications and large server systems.


1 Answers

You must use pairs instead of ipairs.

tab={}

tab[1]='a'
tab[2]='b'
tab[5]='e'

for k, v in pairs(tab) do print(k, v) end

Will output (in any order):

1   a
2   b
5   e

ipairs iterates over sequential integer keys, starting at 1 and breaking on the first nil pair.

pairs iterates over all key-value pairs in the table. Note that this is not guaranteed to iterate in a specific order.

like image 101
Axel Isouard Avatar answered Sep 28 '22 02:09

Axel Isouard