#### Howdy, Stranger!

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

# Questions about nested for loops

edited July 2014 Posts: 6

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] = {}
end

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 [i]every[/i] 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.

Tagged:

• Posts: 135

I'm pretty sure you have to replace
~ colors[i[j]] ~ with ~ colors[i][j] ~

• Mod
Posts: 9,813

@Codea__User Maybe this will help some.

``````displayMode(FULLSCREEN)

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

function draw()
background(40,40,50)
fill(255)
for i=1,y do
for j=1,x do
fill(colors[i][j])
rect(i*size,j*size,size,size)   -- draw squares
end
end
end
``````
• Posts: 6

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