Typed Arrays
Part of the Introduction To Luau section of Coddy's Lua journey. Lesson 13 of 80.
Typed arrays are one of Luau's most useful features for organizing multiple values while keeping type safety.
In Lua, an array is just a table with values at positions 1, 2, 3, …, and it will happily hold a number, a string and a boolean all at once. Luau lets you declare that a table should only contain elements of one type, using the {Type} syntax:
local numbers: {number} = {1, 2, 3, 4, 5}
local names: {string} = {"Alice", "Bob", "Charlie"}
local flags: {boolean} = {true, false, true}When you declare a typed array, Luau's type checker enforces that only values of the declared type go in. Insert a string into a {number} array and you get a type error while editing, before the code ever runs:
local scores: {number} = {85, 90, 78}
table.insert(scores, "oops") -- ✗ type error: string is not a numberEverything you already know about Lua tables still applies: arrays are 1-based (scores[1] is the first element), #scores is the length, and table.insert / table.remove work as usual. The annotation adds safety, not new runtime behavior.
Challenge
EasyStore scores and names in typed arrays.
- Declare
local scores: {number} = {85, 92, 78}. - Declare
local studentNames: {string} = {"Alice", "Bob", "Charlie"}. - Print
scores[1],#scoresandstudentNames[2], one per line.
Press Run Code: the output shows 85, 3 and Bob.
Try it yourself
-- 1) declare scores: {number} and studentNames: {string}
-- 2) print the first score, the number of scores and the second name
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