Arrays, and incrementing values

Hi!

This is a very simple question, but i can’t understand what’s wrong… (so sorry!!)

If we take this code:

local record = {}

local list = {}

 

for i=1, 5 do

    record.value = i

    list[i] = record

end

 

print(list[1].value, list[2].value, list[3].value, list[4].value, list[5].value)

 

 

I’m specting to see: 1, 2, 3, 4, 5

But, what I see, is just: 5, 5, 5, 5, 5

What’s wrong in the code? How is the correct way do this?

Thanks!!

There are two issues you’re running into.  First, if you trace your code, the value of record.value will be 5 after the for loop completes. 

The second issue is a scope issue. Because you declared record outside of the for loop, you only have one memory address for that table.  Each time you do:

list[i] = record

You’re assigning the same memory address to list[i] so at the end. So lets say the memory address of record is 0x987ABC43, then list[1] =  0x987ABC43, list[2] = 0x987ABC43, etc. The value of .value will be the last value processed in the loop since your pointing to the same table.

The fix is to not declare record outside of the loop, but make it local inside the loop.

 

local list = {} for i=1, 5 do     local record = {}     record.value = i     list[i] = record end

In this case, because you’re declaring a local table named record inside the loop, you will get a different memory address for each record each time the loop iterates.

Rob

Hi Rob.

Thanks for your quick answer!

And yes, you’re right… I saw mi error just few minuts after I send this post.

J.M.

There are two issues you’re running into.  First, if you trace your code, the value of record.value will be 5 after the for loop completes. 

The second issue is a scope issue. Because you declared record outside of the for loop, you only have one memory address for that table.  Each time you do:

list[i] = record

You’re assigning the same memory address to list[i] so at the end. So lets say the memory address of record is 0x987ABC43, then list[1] =  0x987ABC43, list[2] = 0x987ABC43, etc. The value of .value will be the last value processed in the loop since your pointing to the same table.

The fix is to not declare record outside of the loop, but make it local inside the loop.

 

local list = {} for i=1, 5 do     local record = {}     record.value = i     list[i] = record end

In this case, because you’re declaring a local table named record inside the loop, you will get a different memory address for each record each time the loop iterates.

Rob

Hi Rob.

Thanks for your quick answer!

And yes, you’re right… I saw mi error just few minuts after I send this post.

J.M.