1. 基本函数
-- 函数定义
function add(a, b)
return a + b -- 返回值
end
-- 函数调用
local result = add(5, 3)
print(result) -- 8
-- 无返回值函数
function say_hello(name)
print("Hello, " .. name .. "!")
end
say_hello("Lua") -- Hello, Lua!
2. 多返回值函数function get_user()
return "张三", 25, "男" -- 返回多个值
end
local name, age, gender = get_user()
print(name, age, gender) -- 张三 25 男
3. 可变参数函数function sum(...)
local total = 0
for _, num in ipairs({...}) do -- {...} 获取所有参数
total = total + num
end
return total
end
print(sum(1, 2, 3, 4)) -- 10
print(sum(5, 10, 15)) -- 30
4. 匿名函数local multiply = function(a, b)
return a * b
end
print(multiply(4, 5)) -- 20
-- 作为参数传递
local numbers = {1, 2, 3, 4}
table.sort(numbers, function(a, b)
return a > b -- 降序排序
end)
|