Menu
CoddyTech

Typing Anonymous Functions

Part of the Introduction To Luau section of Coddy's Lua journey. Lesson 24 of 80.

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

Store typed functions in local variables.

  1. Rewrite subtract as local subtract = function(a: number, b: number): number, keeping its body.
  2. Add local isPositive = function(num: number): boolean that returns num > 0.
  3. Print subtract(10, 3) and isPositive(-5).

Press Run Code: the output shows 7 and false.

Try it yourself

-- Rewrite this as an anonymous function stored in a local
function subtract(a: number, b: number): number
    return a - b
end

All lessons in Introduction To Luau

Practice on your own: Online Luau compiler