Courses/Lua/Functions and Tables

    Functions and Tables

    Learn to define functions with multiple returns and master Lua's most powerful data structure.

    What You'll Learn

    • Define and call functions with multiple return values
    • Understand closures and variadic functions
    • Use tables as arrays, dictionaries, and objects
    • Iterate tables with pairs() and ipairs()

    Functions in Lua

    Functions in Lua are first-class values โ€” they can be stored in variables, passed as arguments, and returned from other functions. This makes Lua extremely flexible for scripting.

    -- Basic function
    local function greet(name)
      return "Hello, " .. name .. "!"
    end
    
    -- Anonymous function stored in a variable
    local square = function(x) return x * x end
    
    -- Multiple return values (unique to Lua!)
    local function divide(a, b)
      return math.floor(a / b), a % b
    end
    local q, r = divide(17, 5)   -- q = 3, r = 2

    ๐ŸŽฎ Real-World Analogy: Lua functions are like vending machine buttons โ€” you press one (call it), insert input (arguments), and get one or more items back (return values). Unlike most vending machines, Lua can dispense multiple items at once!

    Variadic Functions

    local function sum(...)
      local total = 0
      for _, v in ipairs({...}) do
        total = total + v
      end
      return total
    end
    print(sum(1, 2, 3, 4, 5))  -- 15

    Functions

    Try defining functions with multiple returns and closures.

    Try it Yourself ยป
    JavaScript
    // Lua Functions โ€” simulated in JavaScript
    console.log("=== Basic Functions ===");
    
    function greet(name) {
      return "Hello, " + name + "!";
    }
    console.log(greet("Alice"));
    console.log(greet("Bob"));
    console.log();
    
    console.log("=== Multiple Return Values ===");
    console.log("Lua functions can return multiple values!");
    function divide(a, b) {
      return [Math.floor(a / b), a % b]; // quotient, remainder
    }
    const [quotient, remainder] = divide(17, 5);
    console.log("17 / 5 = " + quotient + " remainder "
    ...

    Tables โ€” Lua's Universal Data Structure

    Tables are Lua's only compound data structure. They replace arrays, dictionaries, objects, modules, and even classes in other languages. This simplicity is what makes Lua so lightweight.

    โš ๏ธ Important: Lua Arrays Start at 1

    Unlike most programming languages, Lua array indices start at 1, not 0. The # operator and ipairs() both rely on this convention.

    -- As an array (sequential integer keys)
    local colors = {"red", "green", "blue"}
    print(colors[1])    -- "red" (index starts at 1!)
    print(#colors)      -- 3
    
    -- As a dictionary (string keys)
    local player = {
      name = "Hero",
      health = 100,
      level = 5
    }
    print(player.name)        -- "Hero"
    print(player["health"])   -- 100 (bracket notation)
    
    -- Mixed (both array and dictionary parts)
    local config = {
      "default",              -- config[1]
      "fallback",             -- config[2]
      debug = true,           -- config.debug
      version = "1.0"         -- config.version
    }

    Table Methods

    table.insert(colors, "yellow")   -- append
    table.insert(colors, 2, "pink")  -- insert at index 2
    table.remove(colors, 1)          -- remove first element
    table.sort(colors)               -- sort in-place
    print(table.concat(colors, ", "))-- join with separator

    Tables

    Explore Lua's table data structure as arrays and dictionaries.

    Try it Yourself ยป
    JavaScript
    // Lua Tables โ€” simulated in JavaScript
    console.log("=== Tables as Arrays ===");
    const fruits = ["apple", "banana", "cherry"];
    console.log("Lua arrays start at index 1 (not 0)!");
    fruits.forEach((f, i) => console.log("  fruits[" + (i+1) + "] = " + f));
    console.log("  #fruits =", fruits.length);
    console.log();
    
    console.log("=== Tables as Dictionaries ===");
    const player = {
      name: "Hero",
      health: 100,
      level: 5,
      inventory: ["sword", "shield"]
    };
    console.log("player.name    =", player.name);
    ...

    ๐Ÿ’ก Pro Tip

    Use pairs() to iterate all key-value pairs (including string keys), and ipairs() to iterate only the sequential array portion starting from index 1. In game development, ipairs() is preferred for ordered lists like inventory items.

    ๐Ÿ“‹ Quick Reference

    ConceptSyntax
    Named functionlocal function f(x) end
    Anonymous functionlocal f = function(x) end
    Multiple returnreturn a, b
    Create table{1, 2, key = "val"}
    Appendtable.insert(t, val)
    Iteratefor k, v in pairs(t) do

    ๐ŸŽ‰ Lesson Complete!

    You can now define functions and use tables โ€” Lua's most important building blocks. Next, we'll learn control flow: conditionals and loops.

    Sign up for free to track which lessons you've completed and get learning reminders.

    Previous

    Cookie & Privacy Settings

    We use cookies to improve your experience, analyze traffic, and show personalized ads. You can manage your preferences below.

    By clicking "Accept All", you consent to our use of cookies for analytics and personalized advertising. You can customize your preferences or reject non-essential cookies.

    Privacy Policy โ€ข Terms of Service