Learn how to create reusable code with functions and understand variable scope.
Functions are reusable blocks of code that perform specific tasks.
local function greet()
print("Hello, World!")
end
greet() -- Call the function
Functions are defined once and can be called multiple times.
local function greet(name)
print("Hello, " .. name .. "!")
end
greet("Alice")
greet("Bob")
Parameters allow you to pass data into functions.
local function add(a, b)
local sum = a + b
print(a .. " + " .. b .. " = " .. sum)
end
add(5, 3)
add(10, 20)
You can have as many parameters as needed, separated by commas.
Functions can return values that can be used in your code.
local function multiply(a, b)
return a * b
end
local result = multiply(5, 4)
print(result) -- 20
-- Use directly in expressions
print(multiply(3, 7) + 10)
The return keyword sends a value back from the function.
local function getPlayerInfo()
local name = "Steve"
local level = 10
local health = 100
return name, level, health
end
local playerName, playerLevel, playerHealth = getPlayerInfo()
print(playerName, playerLevel, playerHealth)
Lua functions can return multiple values!
Scope determines where variables can be accessed in your code.
-- Global variable (accessible everywhere)
globalVar = "I'm global"
local function testScope()
-- Local variable (only inside function)
local localVar = "I'm local"
print(localVar) -- Works
print(globalVar) -- Works
end
testScope()
print(globalVar) -- Works
-- print(localVar) -- ERROR! Not accessible here
Local variables only exist in their scope. Global variables persist everywhere.
Create a function that calculates damage with attack and defense values.
-- Create your calculateDamage function here
-- Test it
print(calculateDamage(50, 10)) -- Should print 40
local function calculateDamage(attack, defense)
local damage = attack - defense
return damage
end
print(calculateDamage(50, 10))
Create a function that returns player name and level.
-- Create getPlayerStats function
local name, level = getPlayerStats()
print("Player: " .. name .. ", Level: " .. level)
local function getPlayerStats()
local name = "Hero"
local level = 25
return name, level
end
local name, level = getPlayerStats()
print("Player: " .. name .. ", Level: " .. level)
Continue your learning journey