Tables or Arrays to store multiple data

Suppose we decided to paint a rainbow consisting of 7 colors as 7 vertical bands. We could start like this:

graph.init()
graph.rect(0, 0, 90, graph.h, 'red')
graph.rect(90, 0, 90, graph.h, 'orange')
graph.rect(180, 0, 90, graph.h, 'yellow')
-- and so on

You can try, this works, but seems tedious. We obviously want a loop of some kind. The only thing changing between lines are:

We can pack all necessary colors into the curious structure called table (in other languages it is array or list often). Then assign this structure to single variable and pick the necessary color using number. Try this:

colors = {'red', 'green', 'blue'}
print(colors[1])
print(colors[3], colors[2])

You see the "indexing" with square brackets works quite straightforward - it picks the value from the "table" according to the number given. Enumeration starts generally with 1 (in other languages it is more often started with 0).

The other convenient thing with tables is getting their size. Just use symbol # before the variable name

colors = {'red', 'green', 'blue'}
print(#colors)   -- prints 3

Now we are well armed to solve our initial task with a loop:

graph.init()
colors = {'red', 'orange', 'yellow', 'green', 'cyan', 'blue', 'purple'}
bar_width = graph.w // 7
for i = 1,#colors do
    graph.rect(bar_width * (i-1), 0, bar_width, graph.h, colors[i])
end

You'll see there is a small issue with narrow white line at the right side - obviously because width of the canvas doesn't divide equally by 7. You can try improving this according to your skills in math.

As an exercise try to make bars horizontal rather than vertical and use different number and coloring - make 20 bands with only 5 colors (red, yellow, green, blue, purple) repeated 4 times.