Menu
Coddy logo textTech

Typing Anonymous Functions

Part of the Introduction To Luau section of Coddy's Lua journey — lesson 23 of 73.

In Lua, functions are values — you've stored them in variables and passed them around: local f = function(x) return x * 2 end. These anonymous functions (function expressions) take type annotations exactly like named functions do:

local double = function(x: number): number
    return x * 2
end

local shout = function(text: string): string
    return string.upper(text) .. "!"
end

Parameters get name: type inside the parentheses, and the return type follows the closing parenthesis — the only difference from a named function is that the function keyword has no name and the whole expression is assigned to a variable.

If you've seen JavaScript or TypeScript, note that Luau has no arrow functions — there is no => syntax. Every function expression is written with function ... end, long or short.

Once assigned, you call it through the variable like any function: double(21) returns 42, and the checker verifies every call against the annotations you wrote.

challenge icon

Challenge

Easy

Rewrite this named function as an anonymous function stored in a local variable, keeping all type annotations:

function subtract(a: number, b: number): number
    return a - b
end

So: create local subtract = function(...) ... end with the same parameter and return types.

Then create two more typed anonymous functions:

  • createMessage — takes text: string, returns the string "Message: [text]" (return type string)
  • isPositive — takes num: number, returns true if the number is greater than 0, otherwise false (return type boolean)

Call and print, each on its own line:

  1. subtract(10, 3)
  2. createMessage("Hello World")
  3. isPositive(-5)
  4. isPositive(8)

Try it yourself

-- Write code here
-- local subtract = function(a: number, b: number): number ... end
-- local createMessage = function(text: string): string ... end
-- local isPositive = function(num: number): boolean ... end
-- then print the four results
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Introduction To Luau