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, AliceYou can also define the function separately and then add it to the table:
local myTable = {}
myTable.greet = function(name)
return "Hello, " .. name
endOr use this cleaner shorthand syntax:
local myTable = {}
function myTable.greet(name)
return "Hello, " .. name
endAll 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
EasyCreate a table named calculator that contains four arithmetic functions:
add(a, b)- returns the sum ofaandbsubtract(a, b)- returnsaminusbmultiply(a, b)- returns the product ofaandbdivide(a, b)- returnsadivided byb
You will receive three inputs:
- An operation name (one of:
add,subtract,multiply,divide) - First number
- Second number
Call the appropriate function from your calculator table based on the operation name and print the result.
Cheat sheet
In Lua, tables can store functions alongside data. To add a function to a table, assign it to a key:
local myTable = {
greet = function(name)
return "Hello, " .. name
end
}
print(myTable.greet("Alice")) -- Output: Hello, AliceYou can also define functions separately and add them to the table:
local myTable = {}
myTable.greet = function(name)
return "Hello, " .. name
endOr use the shorthand syntax:
local myTable = {}
function myTable.greet(name)
return "Hello, " .. name
endCall table functions using dot notation: myTable.greet("Alice")
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 resultThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1The 'Self' Concept
Tables with FunctionsExplicit 'self'The Colon SyntaxDot vs ColonRecap - Moving Point4Project: Digital Bank
Project SetupDeposit Method7Polymorphism & Overriding
Overriding MethodsCalling Parent MethodsDuck TypingCommon InterfaceChecking TypeRecap - Employee Roles10Project: Shape Manager
Project SetupRectangle Class2Class Prototype Pattern
The Prototype ConceptLinking with __indexThe :new() ConstructorInitializing AttributesIndependent InstancesRecap - Car Factory5Operator Overloading in OOP
Adding ObjectsSubtracting ObjectsConcatenating ObjectsComparing Objects (<, >)Recap - Wallet Math8Encapsulation
Naming ConventionsClosures for PrivacyAccess via ClosuresRead-Only TablesValidation LogicRecap - Secure Vault11Design Patterns (Lite)
Factory FunctionsSingleton TableIterator PatternObserver (Listener)Recap - Logger Factory3Object State and Behavior
Instance VariablesGetter MethodsSetter MethodsCalculated PropertiesFormatting StringsEquality ChecksRecap - Student Grade6Inheritance Basics
The Inheritance SetupInheriting MethodsExtending the ConstructorAdding Child MethodsShared vs UniqueRecap - Shape Hierarchy