Menu
Coddy logo textTech

Tables with Functions

Part of the Object Oriented Programming section of Coddy's Lua journey — lesson 1 of 70.

In Lua, tables are incredibly versatile. Beyond storing data, they can also hold functions. This allows you to group related operations together, keeping your code organized and easy to manage.

To place a function inside a table, you simply assign it to a key just like any other value:

local myTable = {
    greet = function(name)
        return "Hello, " .. name
    end
}

print(myTable.greet("Alice"))  -- Output: Hello, Alice

You can also define the function separately and then add it to the table:

local myTable = {}

myTable.greet = function(name)
    return "Hello, " .. name
end

Or use this cleaner shorthand syntax:

local myTable = {}

function myTable.greet(name)
    return "Hello, " .. name
end

All three approaches produce the same result. You call the function using dot notation: myTable.greet("Alice"). This pattern of bundling functions with data is the foundation of object-oriented programming in Lua.

challenge icon

Challenge

Easy

Create a table named calculator that contains four arithmetic functions:

  • add(a, b) - returns the sum of a and b
  • subtract(a, b) - returns a minus b
  • multiply(a, b) - returns the product of a and b
  • divide(a, b) - returns a divided by b

You will receive three inputs:

  1. An operation name (one of: add, subtract, multiply, divide)
  2. First number
  3. Second number

Call the appropriate function from your calculator table based on the operation name and print the result.

Try it yourself

-- Read inputs
local operation = io.read()
local num1 = tonumber(io.read())
local num2 = tonumber(io.read())

-- TODO: Create a calculator table with four functions:
-- add(a, b), subtract(a, b), multiply(a, b), divide(a, b)


-- TODO: Call the appropriate function from calculator table using the operation name
-- and print the result
quiz iconTest yourself

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

All lessons in Object Oriented Programming