当前位置:   article > 正文

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

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

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

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

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

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

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

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

    local status, output = os.execute("ls -l")
    print(output)
    
    • 1
    • 2
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 之间的随机数
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
  • 三角函数

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

    print(math.pi)  -- 输出 π 的值
    print(math.huge)  -- 输出最大正数
    print(math.minus_huge)  -- 输出最小负数
    
    • 1
    • 2
    • 3
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"))  -- 格式化输出
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
  • 分割字符串

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

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

    for i, v in ipairs(t) do
        print(i, v)
    end
    
    for k, v in pairs(t) do
        print(k, v)
    end
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
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()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
  • 逐行读取文件

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

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

    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)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
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()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
  • 获取调用堆栈

    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()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
8. package 模块
  • 加载模块

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

    package.path = package.path .. ";./modules/?.lua"
    
    • 1
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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
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"
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/黑客灵魂/article/detail/963924
推荐阅读
相关标签
  

闽ICP备14008679号