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)
endThe 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
EasyBuild a small times table grid with nested loops.
- Under the grid, create
local products: {{number}} = {}. - For
ifrom 1 to 2, makelocal row: {number} = {}, inserti * jforjfrom 1 to 3, then insertrowintoproducts. - 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
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