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
EasyRead two cells from a typed grid.
- Declare
local gameGrid: {{number}}with the rows{2, 4, 6},{8, 10, 12}and{14, 16, 18}. - Print the cell at row 2, column 1:
gameGrid[2][1]. - 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
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 ValuesDefaults for BooleansVariadic FunctionsDefining Function TypesRecap: Typed Functions2Core Types
Number, String and BooleanThe '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 TablesReading a GridBuilding a Gridtable.unpackRecap: Arrays and MapsPractice on your own: Online Luau compiler