hamobi
hamobi

Reputation: 8130

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

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?

Upvotes: 4

Views: 10577

Answers (2)

Vlad
Vlad

Reputation: 5857

and i see you can access objects in a map layer like this
for object in map.layer["platform"].nameIs("platform") do

What you see here is nothing else than generic for used with custom iterator.
.nameIs("platform") returns functions that essentially behaves like ipairs.

For example, that syntax might be implemented like this (though it's not what your library might do actually):

local object = {
    platform = {1,2,3,4},
    mob = {4,3,2,1}
}

function object.nameIs(idx)
    local array = object[idx]
    local i = 0
    return function ()
        i = i+1
        return array[i]
    end
end

print "-- Platforms --"
for value in object.nameIs("platform") do
    print(value)
end

print "-- Mobs --"
for value in object.nameIs("mob") do
    print(value)
end

For more detailed explanation see "Programming in Lua" online book, you want to see section 7 - Iterators and the Generic For

Upvotes: 6

Yu Hao
Yu Hao

Reputation: 122443

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

Upvotes: 7

Related Questions