Howdy, Stranger!

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

Simple Generic Loop Bug

edited October 2014 in Bugs Posts: 63

I've been trying to wrap my head around Generic For loops and I decided to make this code based on my current understanding:

function setup()
 n = {}
 numberxplacement = {}
for i, v in pairs(n) do


This code is supposed to multiply the number in the n table by its placement. So since 2 was put into the n table first, the equation should be: 2x1 and since the 5 was put into the table second, the equation should be 5x2. This code, however, will not run for what is most likely the simplest syntax error. Please tell me what that syntax error is so that I may finally be able to understand how generic for loops work. Side Note: does the i (in "for i,v") AKA the "key" always represent the value's placement number in the table or could it mean something else?


  • dave1707dave1707 Mod
    Posts: 9,432

    function setup() n = {} numberxplacement = {} table.insert(n,2) table.insert(n,5) for i, v in pairs(n) do numberxplacement[i]=v*i end print(numberxplacement[1]) print(numberxplacement[2]) end
  • dave1707dave1707 Mod
    edited October 2014 Posts: 9,432

    @Paintcannon There isn't a table.addValue(), it's table.insert(). As for the "for i,v", the "i" is the offset into the table, meaning the 1st, 2nd, 3rd position, etc. The "v" is the value in the table at offset "i". The print statement should be [1] and [2] because that's where the information was put with the "for" loop.

  • Ok, I have a pretty good understanding of generic loops work now.

Sign In or Register to comment.