Lua 学习笔记之四(Lua中的基本函数库)

当然可以!下面是一份关于 Lua 中基本函数库的学习笔记。这份笔记将涵盖 Lua 标准库中的一些常用函数和模块,以及如何使用它们来完成常见的任务。

Lua 学习笔记之四:Lua 中的基本函数库

1. os 模块
  • 获取当前时间

    local now = os.time()
    print(now)
    
  • 格式化日期

    local dateStr = os.date("%Y-%m-%d %H:%M:%S", now)
    print(dateStr)
    
  • 获取环境变量

    local homeDir = os.getenv("HOME")
    print(homeDir)
    
  • 执行外部命令

    local status, output = os.execute("ls -l")
    print(output)
    
2. math 模块
  • 基本数学函数

    print(math.abs(-5))  -- 输出 5
    print(math.sqrt(16))  -- 输出 4
    print(math.pow(2, 3))  -- 输出 8
    print(math.floor(3.7))  -- 输出 3
    print(math.ceil(3.2))  -- 输出 4
    print(math.random(1, 10))  -- 输出 1 到 10 之间的随机数
    
  • 三角函数

    print(math.sin(math.pi / 2))  -- 输出 1
    print(math.cos(math.pi))  -- 输出 -1
    
  • 常数

    print(math.pi)  -- 输出 π 的值
    print(math.huge)  -- 输出最大正数
    print(math.minus_huge)  -- 输出最小负数
    
3. string 模块
  • 字符串操作

    local str = "Hello, Lua!"
    
    print(string.len(str))  -- 输出字符串长度
    print(string.lower(str))  -- 转换为小写
    print(string.upper(str))  -- 转换为大写
    print(string.find(str, "Lua"))  -- 查找子串的位置
    print(string.gsub(str, "Lua", "World"))  -- 替换子串
    print(string.format("%s is fun!", "Lua"))  -- 格式化输出
    
  • 分割字符串

    local words = string.split("one two three four", " ")
    for _, word in ipairs(words) do
        print(word)
    end
    
4. table 模块
  • 表操作

    local t = {1, 2, 3}
    
    table.insert(t, 4)  -- 在末尾添加元素
    table.sort(t)  -- 对表排序
    table.remove(t, 2)  -- 移除指定位置的元素
    print(table.maxn(t))  -- 获取表的最大索引
    
  • 迭代表

    for i, v in ipairs(t) do
        print(i, v)
    end
    
    for k, v in pairs(t) do
        print(k, v)
    end
    
5. io 模块
  • 文件读写

    local file = io.open("example.txt", "w")
    file:write("Hello, Lua!\n")
    file:close()
    
    file = io.open("example.txt", "r")
    local content = file:read("*a")  -- 读取整个文件
    print(content)
    file:close()
    
  • 逐行读取文件

    file = io.open("example.txt", "r")
    for line in file:lines() do
        print(line)
    end
    file:close()
    
6. coroutine 模块
  • 创建协同程序

    local co = coroutine.create(function()
        print("Hello from coroutine!")
    end)
    
    coroutine.resume(co)
    
  • 传递值

    local co = coroutine.create(function(x, y)
        local sum = x + y
        print("Sum:", sum)
        return sum
    end)
    
    local status, result = coroutine.resume(co, 10, 5)
    print("Result:", result)
    
7. debug 模块
  • 获取函数调用信息

    local function debugPrint(level)
        local info = debug.getinfo(2, "Sl")
        print("Function name:", info.short_src .. ":" .. info.currentline)
        print("Local variables:")
        for i = 1, level do
            local name, value = debug.getlocal(level, i)
            print("  ", name, "=", value)
        end
    end
    
    local function foo()
        local x = 10
        local y = 20
        debugPrint(1)
    end
    
    foo()
    
  • 获取调用堆栈

    local function handleErrors()
        local status, result = pcall(function()
            local x = 10
            local y = 0
            assert(y ~= 0, "y must not be zero")
            return x / y
        end)
        if not status then
            print("Error:", result)
            local info = debug.getinfo(2, "Sln")
            print("Error occurred at:", info.source .. ":" .. info.currentline)
            print(debug.traceback())
        end
    end
    
    handleErrors()
    
8. package 模块
  • 加载模块

    local mathlib = require 'mathlib'
    local result = mathlib.add(10, 5)
    print(result)  -- 输出 15
    
  • 自定义包路径

    package.path = package.path .. ";./modules/?.lua"
    
9. 示例:使用 math 模块计算圆的面积
local function circleArea(radius)
    return math.pi * radius * radius
end

local r = 5
local area = circleArea(r)
print("Area of the circle with radius " .. r .. " is " .. area)
10. 示例:使用 string 模块处理字符串
local function formatPhoneNumber(phoneNumber)
    return string.format("(%s) %s-%s",
        phoneNumber:sub(1, 3),
        phoneNumber:sub(4, 6),
        phoneNumber:sub(7, 10)
    )
end

local phone = "1234567890"
local formattedPhone = formatPhoneNumber(phone)
print(formattedPhone)  -- 输出 "(123) 456-7890"

这些是在 Lua 中基本函数库的学习笔记。希望这些内容对你有所帮助!如果你有任何问题或需要进一步的解释,请随时提问。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值