Recap: Fine-Tuning Types
Part of the Introduction To Luau section of Coddy's Lua journey — lesson 73 of 73.
Challenge
MediumBuild a small configuration processor.
- Declare
type Config = {[string]: string | number | boolean}. - Write
valueType(config: Config, key: string): stringthat returnsmissingif the key's value isnil, otherwisestring,numberorbooleanaccording totypeof. - Write
processValue(config: Config, key: string): stringthat usesvalueType, then returns:- the value uppercased (
string.upper, cast with:: string) for strings tostringof the value times 10 (cast with:: number) for numberstostringof the opposite value (cast with:: boolean) for booleansmissingwhen the key isn't there
- the value uppercased (
- Create
settings: ConfigwithappName = "MyApp",version = 2.5,debugMode = true,maxUsers = 100andtheme = "dark".
Then print, each on its own line:
valueType(settings, "appName")valueType(settings, "version")valueType(settings, "debugMode")valueType(settings, "timeout")processValue(settings, "theme")processValue(settings, "maxUsers")processValue(settings, "debugMode")processValue(settings, "timeout")
Try it yourself
-- Write code here
-- 1) type Config = {[string]: string | number | boolean}
-- 2) valueType(config, key): "missing" / "string" / "number" / "boolean"
-- 3) processValue(config, key): upper / *10 / opposite / "missing"
-- (guard with valueType first, then cast with ::)
-- 4) build the settings table and print the eight test calls
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 Combos8Enums, the Luau Way
The Enum Pattern in LuauNumeric Enums with TablesString Enums as UnionsUsing Literal Union EnumsFreezing Constant TablesRecap: Enums, the Luau Way11Advanced Topics
Type AssertionsType Guards With typeofThe never TypeNil Safety In Strict ModeIndex SignaturesRecap: Fine-Tuning Types3Typed 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