Multi-dimensional Typed Arrays
Part of the Introduction To Luau section of Coddy's Lua journey — lesson 19 of 73.
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.
You can also build grids with loops: create an empty row, fill it with table.insert, then insert the whole row into the outer array. #grid counts the rows and #grid[1] the columns of the first row:
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)
endChallenge
EasyCreate a 2D typed array gameGrid: {{number}} as a 3×3 grid:
- first row
1, 2, 3 - second row
4, 5, 6 - third row
7, 8, 9
Print the element at the second row, first column, then the element at the third row, third column.
Next, build products: {{number}} with nested loops: for each row i from 1 to 2, create an empty typed row, insert i * j for j from 1 to 3, and insert the row into products.
Finally print the element at row 2, column 3 of products, then the number of rows in products. Four lines of output in total.
Try it yourself
-- Write code here
-- 1) declare gameGrid: {{number}} as the 3x3 grid of 1..9
-- 2) print gameGrid[2][1] and gameGrid[3][3]
-- 3) build products: {{number}} with nested loops (i * j)
-- 4) print products[2][3] and #products
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Introduction To Luau
1Getting Started with Luau
What Is Luau?Why Use Luau?Your First Luau CodeType Checking & Error ModesRecap: Introduction to Luau4Working with Functions
Typing Params & Return ValuesTyping Anonymous FunctionsFunctions Returning NothingOptional ParametersDefault Parameter ValuesVariadic FunctionsDefining Function TypesRecap: Typed Functions2Core Types
Basic Types: num, str, boolThe 'any' Type: Escape HatchThe 'unknown' TypeNil & Optional TypesType Inference in ActionExplicit Type AnnotationsRecap: Core Types Practice5Aliases, Unions, Intersections
Type Aliases for PrimitivesUnion TypesWorking with Union TypesLiteral TypesIntersection TypesCombining Type AliasesRecap: Advanced Type Combos3Typed Tables: Arrays & Maps
Typed ArraysAdding and Reading ElementsWhat is a Map Type?Declaring and Accessing MapsIterating TablesMixed-Shape TablesMulti-dimensional Typed Arraystable.unpack and VarargsRecap: Arrays and Maps