Menu
Coddy logo textTech

Recap: Generic Functions

Part of the Introduction To Luau section of Coddy's Lua journey. Lesson 62 of 73.

challenge icon

Challenge

Medium

Combine generic aliases and generic functions in one program.

Define a generic type alias named Pair with two type parameters T and U, describing a table with:

  • first of type T
  • second of type U

Create a generic function named makePair that declares T and U, accepts first: T and second: U, and returns them packed into a Pair<T, U>.

Create a generic function named describePair that declares T and U, accepts a pair: Pair<T, U>, and returns the string ({first}, {second}) built with string interpolation (return type string).

Then:

  1. create playerScore of type Pair<string, number> by calling makePair("<code>Nova", 87)
  2. create levelDone of type Pair<number, boolean> by calling makePair(3, true)
  3. print playerScore.first
  4. print playerScore.second
  5. print describePair(playerScore)
  6. print describePair(levelDone)
  7. print describePair(makePair("Luau", 2026)) in a single line

Try it yourself

-- Write code here
-- 1) define type Pair<T, U> = {first: T, second: U}
-- 2) define makePair<T, U>(first: T, second: U): Pair<T, U>
-- 3) define describePair<T, U>(pair: Pair<T, U>): string
--    returning `({pair.first}, {pair.second})`
-- 4) build playerScore (the exact text from the instructions, 87) and levelDone (3, true),
--    then print the five required lines

All lessons in Introduction To Luau

Practice on your own: Online Lua compiler