Menu
CoddyTech

Reading a Grid

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

Grids, boards and matrices are arrays of arrays, and the type follows the same nesting: {{number}} is an array whose elements are {number} arrays.

local grid: {{number}} = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9},
}

local board: {{string}} = {
    {"white", "black"},
    {"black", "white"},
}

Nested indexing reads one level at a time: grid[2] is the second row (a {number}), and grid[2][1] is that row's first element: 4. Both indices are 1-based, so the top-left corner is grid[1][1], not grid[0][0].

Watch out when a row might not exist: grid[10] is nil, so grid[10][1] raises a runtime error: you'd be indexing into nil.

challenge icon

Challenge

Easy

Read two cells from a typed grid.

  1. Declare local gameGrid: {{number}} with the rows {2, 4, 6}, {8, 10, 12} and {14, 16, 18}.
  2. Print the cell at row 2, column 1: gameGrid[2][1].
  3. Print the cell at row 3, column 3.

Press Run Code: the output shows 8 and 18.

Try it yourself

-- 1) declare gameGrid: {{number}} with three rows
-- 2) print row 2, column 1, then row 3, column 3

All lessons in Introduction To Luau

Practice on your own: Online Luau compiler