Lua 学习笔记之三(高阶话题)

当然可以!下面是一份关于 Lua 高阶话题的学习笔记。这份笔记将涵盖 Lua 的一些高级特性,包括面向对象编程、模块与包管理、异步编程、性能优化等。

Lua 高阶学习笔记

1. 面向对象编程 (OOP)
  • 使用表和元表模拟类

    local Person = {}
    
    function Person:new(name, age)
        local person = setmetatable({}, self)
        person.name = name
        person.age = age
        return person
    end
    
    function Person:sayHello()
        print("Hello, my name is " .. self.name)
    end
    
    local alice = Person:new("Alice", 25)
    alice:sayHello()
    
  • 继承

    local Animal = {}
    
    function Animal:new(name)
        local animal = setmetatable({}, self)
        animal.name = name
        return animal
    end
    
    function Animal:speak()
        print("Some sound")
    end
    
    local Dog = {}
    
    setmetatable(Dog, Animal)
    
    function Dog:new(name)
        local dog = Animal:new(name)
        setmetatable(dog, self)
        return dog
    end
    
    function Dog:speak()
        print("Woof woof!")
    end
    
    local myDog = Dog:new("Buddy")
    myDog:speak()
    
  • 多重继承

    local Movable = {}
    
    function Movable:moved()
        print("Moving")
    end
    
    local Animal = {}
    
    setmetatable(Animal, Movable)
    
    function Animal:new(name)
        local animal = setmetatable({}, self)
        animal.name = name
        return animal
    end
    
    function Animal:speak()
        print("Some sound")
    end
    
    local Bird = {}
    
    setmetatable(Bird, Animal)
    
    function Bird:new(name)
        local bird = Animal:new(name)
        setmetatable(bird, self)
        return bird
    end
    
    function Bird:fly()
        print("Flying")
    end
    
    local myBird = Bird:new("Polly")
    myBird:fly()
    myBird:speak()
    myBird:moved()
    
  • 使用类库:Lua 社区有一些库可以帮助更容易地实现面向对象编程,例如 moonlightluaclasses

2. 模块与包管理
  • 创建模块

    -- mathlib.lua
    local mathlib = {}
    
    function mathlib.add(a, b)
        return a + b
    end
    
    function mathlib.sub(a, b)
        return a - b
    end
    
    return mathlib
    
  • 加载模块

    local mathlib = require 'mathlib'
    local result = mathlib.add(10, 5)
    print(result)  -- 输出 15
    
  • 使用 LuaRocks:LuaRocks 是 Lua 的包管理器,用于安装和管理 Lua 模块。

    luarocks install luacrypto
    
  • 自定义包路径

    package.path = package.path .. ";./modules/?.lua"
    
3. 异步编程
  • 使用协同程序实现异步

    local function asyncTask(callback)
        print("Task started.")
        coroutine.yield()
        callback("Task finished.")
    end
    
    local function main()
        local co = coroutine.create(function()
            asyncTask(function(result)
                print(result)
            end)
        end)
    
        coroutine.resume(co)
        print("Main function continues...")
    end
    
    main()
    
  • 使用第三方库:Lua 社区有一些库支持异步编程,例如 LuaSocketLuaSec

4. 性能优化
  • 减少全局变量:尽可能减少全局变量的使用,因为它们可能会增加垃圾回收的压力。

    local myVar = 10
    function doSomething()
        local localVar = myVar * 2
        print(localVar)
    end
    
  • 使用弱表:在 Lua 5.2 及更高版本中,可以使用弱表来避免循环引用,从而减轻垃圾回收的压力。

    local weakTable = setmetatable({}, {__mode = "v"})  -- 或 "k" 为弱键
    
    weakTable.someValue = someObject
    
  • 避免大对象:尽量避免创建大型的对象或数组,因为它们可能会导致更多的内存碎片。

    local bigArray = {}
    for i = 1, 1000000 do
        bigArray[i] = i
    end
    
  • 减少函数调用:函数调用有一定的开销,特别是在循环中频繁调用时。

    local function calculate(x)
        return x * 2
    end
    
    for i = 1, 1000000 do
        calculate(i)
    end
    
5. 示例:使用面向对象实现一个简单的游戏
local Game = {}

function Game:new()
    local game = setmetatable({}, self)
    game.players = {}
    return game
end

function Game:addPlayer(name)
    local player = Player:new(name)
    table.insert(self.players, player)
    return player
end

local Player = {}

function Player:new(name)
    local player = setmetatable({
        name = name,
        score = 0
    }, self)
    return player
end

function Player:getScore()
    return self.score
end

function Player:setScore(score)
    self.score = score
end

local game = Game:new()
local alice = game:addPlayer("Alice")
local bob = game:addPlayer("Bob")

alice:setScore(100)
bob:setScore(200)

print(alice:getScore())  -- 输出 100
print(bob:getScore())  -- 输出 200
6. 示例:使用模块实现一个简单的 HTTP 服务器
-- server.lua
local http = require "socket.http"
local http_status = require "socket.http.status"

local function handleRequest(request)
    local method = request.method
    local path = request.path
    local headers = request.headers
    local body = request.body

    if method == "GET" and path == "/" then
        return http_status.OK, "Hello, World!", {["Content-Type"] = "text/plain"}
    else
        return http_status.NOT_FOUND, "Not Found", {["Content-Type"] = "text/plain"}
    end
end

local function startServer(host, port)
    local server = assert(socket.bind(host, port))
    server:listen(100)

    while true do
        local client, addr = server:accept()
        print("Connection from:", addr)
        local request = http.request(client)
        local status, body, headers = handleRequest(request)
        http.send_headers(client, status, headers)
        client:send(body)
        client:close()
    end
end

startServer("127.0.0.1", 8080)

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

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值