Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to loop through an array without using pairs()?

Tags:

arrays

loops

lua

I can iterate through an array/table (for example {'a', 'b', 'c'}) using a regular for loop. And then there is iteration using pairs

for _, v in pairs({'a', 'b', 'c'}) do
  io.write(v..'\n')
end

but when I have a plain old array, I really don't find myself caring about the keys.

Is there a way of iterating like

for value in array do end

I do see instances of this. For example I'm using a library to create a map in my game and I see you can access objects in a map layer like this

for object in map.layer["platform"].nameIs("platform") do  

Any way to iterate like this?

like image 460
hamobi Avatar asked Dec 10 '22 18:12

hamobi


1 Answers

For arrays, the natural way is to use ipairs, not pairs. However, it still needs a key:

for _, v in arr do

If you really want to avoid the key item, make your own iterator. Programming in Lua provides one as an example:

function values(t)
    local i = 0
    return function() i = i + 1; return t[i] end
end

Then you can use it like this:

local arr = {'a', 'b', 'c', 'd'}
for e in values(arr) do
    print(e)
end
like image 130
Yu Hao Avatar answered Mar 06 '23 21:03

Yu Hao