Function to Add a Task
Part of the Introduction To Luau section of Coddy's Lua journey — lesson 46 of 73.
Challenge
EasyYour editor already contains the Task type and the tasks array from the previous lesson.
Create a function named addTask that takes two parameters:
listof type{Task}titleof typestring
The function should:
- build a new
Taskwhoseidis#list + 1, whosetitleis the given title, and whosedoneflag isfalse - insert it into
listwithtable.insert - return the new task (return type
Task)
Then call addTask(tasks, "Review the code"), store the result in a variable named added, and print, each on its own line:
- the number of tasks now in
tasks added.idadded.titleadded.done
Try it yourself
-- The shape every task in the manager must follow
type Task = {
id: number,
title: string,
done: boolean,
}
-- The task list: a typed array of Task shapes
local tasks: {Task} = {
{id = 1, title = "Learn Luau types", done = false},
{id = 2, title = "Build a task manager", done = false},
{id = 3, title = "Write tests", done = true},
}
-- Inspect the first task
print(tasks[1].id)
print(tasks[1].title)
print(tasks[1].done)
print(#tasks)
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 Functions7Project: Typed Task Manager
Project: The Task ShapeFunction to Add a Task2Core 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