Questions about nested for loops

So, I have code to create an “grid” of squares that are all the same size, and I know how many squares long and tall it is supposed to be. I have been trying to do this with nested for loops, like so:

    local colors = {}
    for i = 1, y do
        for j = 1, x do
            if i == 1 and j == 1 then
                colors[i] = {}
                colors[i[j]] = 0
            elseif j == 1 then
                colors[i] = {}
            local newcolor = math.random(1, nColors)
            colors[i[j]] = newcolor
            colorUsage[newcolor] = colorUsage + 1

Basically, this code is meant to create a table that has a nested table and the nested table has an id number that maps to a color. The nColors variable is the number of colors in the palette, as it varies. The bottom line of code allows me to quickly verify that the grid is valid for the difficulty level. BTW, the thing where the first color is 0 is because of something else, don’t worry about that.

The main problem is that I don’t think I understand nested for loops correctly. As I understand it, the inside for loops runs once for every iteration of the outer loop. So, if y=5, the inside loops runs completely 5 times. Am I correct?

Anyways, the error I am getting is attempts to index local ‘i’ (a number value) on the line where I have colors[i[j]] = 0. The problem might also be that I don’t know the syntax for nested tables.

I’m pretty sure you have to replace

@Codea__User Maybe this will help some.


function setup()
    col={}  -- table of 20 colors
    for z=1,20 do
    x=10    -- number of rows and columns
    size=60 -- size of squares    
    colors = {} -- table of color numbers    
    for i = 1, y do
        for j = 1, x do
            colors[i][j] = col[math.random(20)] -- number from 1 to 20

function draw()
    for i=1,y do
        for j=1,x do
            rect(i*size,j*size,size,size)   -- draw squares

@Doge - Thanks, I’ll see if that works.
@dave1707 - I already have code, that is just part of one function.