Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

In this Discussion

Why does "nil" in a table breaks the ipairs for loop?

AnatolyAnatoly Mod
in Bugs Posts: 891

I noticed that

..., function() return end, ...

won't break the table - why nil itself does?


  • Posts: 160

    I think you mean, why does ipairs not work on an array with nil in it. It's because ipairs stops once it reaches a nil value in the array you gave it.

  • edited September 2016 Posts: 160

    If you want to iterate through your array and your array has nil in it, you could use this for loop:

    local arr = {17,58,nil,64,788}
    for i = 1, #arr do
        print("arr["..i.."] = ",arr[i])

    Just make sure you have a non-nil value at the end of your array or it will not count any nils at the end of your array, eg:

    local incorrect = {10,23,40,nil,nil,nil}
    local correct = {10,23,40,nil,nil,nil,0}
    for i = 1, #incorrect do
        print(incorrect[i]) -- prints: 10, 23, 40
    for i = 1, #correct do
        print(correct[i]) -- prints: 10,23,40,nil,nil,nil,0

    But there's one problem. There's a zero getting printed which we don't want, so we do this instead:

    for i = 1, #correct - 1 do -- #correct - 1!
        print(correct[i]) -- prints: 10, 23, 40, nil, nil, nil
  • Posts: 160

    But let's not forget. I'm not an expert. I recommend waiting to see what other people have to say.

Sign In or Register to comment.