Menu
CoddyTech

Building a Grid

Part of the Introduction To Luau section of Coddy's Lua journey. Lesson 20 of 80.

A grid does not have to be typed out by hand. You can build it with loops: create an empty row, fill it with table.insert, then insert the whole row into the outer array.

local table10: {{number}} = {}
for i = 1, 3 do
    local row: {number} = {}
    for j = 1, 4 do
        table.insert(row, i * j)
    end
    table.insert(table10, row)
end

The outer loop makes one row per step and the inner loop fills it. #table10 counts the rows and #table10[1] the columns of its first row: here 3 and 4.

challenge icon

Challenge

Easy

Build a small times table grid with nested loops.

  1. Under the grid, create local products: {{number}} = {}.
  2. For i from 1 to 2, make local row: {number} = {}, insert i * j for j from 1 to 3, then insert row into products.
  3. Print products[2][3] and #products.

Press Run Code: the output ends with 6 and 2.

Try it yourself

local gameGrid: {{number}} = {
    {2, 4, 6},
    {8, 10, 12},
    {14, 16, 18},
}

-- Row first, then column; both start at 1
print(gameGrid[2][1])
print(gameGrid[3][3])

All lessons in Introduction To Luau

Practice on your own: Online Luau compiler