查看: 35|回复: 0

Lua 入门教程——函数

[复制链接]

48

主题

75

回帖

1991

积分

金牌会员

积分
1991
QQ
发表于 2026-5-25 17:54:23 | 显示全部楼层 |阅读模式
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)

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表