Skip to content

13 - Lua 面试题

按主题分类的高频面试题,每题含代码示例与答案要点。

一、基础

1. Lua 的数据类型?

8 种:nil / boolean / number / string / function / userdata / thread / table。

table 是 Lua 唯一的复合类型,同时充当数组和哈希表。

2. nil 与 false 的区别?

-- 只有 nil 和 false 为假,其他都真(0、空字符串、空表都真)
if 0 then print("0 is truthy") end           -- 真
if "" then print("empty string is truthy") end -- 真

-- 删除全局变量
x = nil

3. local 与全局变量?

global = 1             -- 全局
local local_var = 2    -- 局部,块作用域

do
    local x = 10        -- 仅 do 块内可见
    print(x)            -- 10
end
print(x)                -- nil

4. Lua 字符串的特性?

-- 不可变(immutable)
-- intern(内化):相同字符串共享存储
-- 相等比较 O(1)
local a = "hello"
local b = "hello"
print(a == b)          -- true(内部 hash 比较)

-- 字符串拼接用 .. 但循环中用 table.concat 性能更好

二、table

1. table 是数组还是哈希表?

两者皆是。Lua table 是关联数组,key 可以是 nil 外的任意值。

-- 数组(连续整数下标)
local arr = {10, 20, 30}

-- 哈希(字符串 key)
local h = {name = "alice", age = 30}

-- 混合
local m = {100, 200, name = "test"}

2. # 运算符的限制?

local t = {1, 2, 3}
print(#t)              -- 3

-- 只对"序列"(1..n 形式)有意义
local sparse = {1, 2, nil, 4}
print(#sparse)         -- 4 或 5(取决于实现,不保证)

-- 哈希表的 # 是未定义的
local h = {a = 1, b = 2}
print(#h)              -- 0 或 2(不确定)

3. pairs vs ipairs?

-- pairs:遍历所有 key-value(顺序**不固定**),跳过 nil
for k, v in pairs({a = 1, b = 2, [3] = 3}) do
    print(k, v)
end

-- ipairs:遍历数组(从 1 开始),遇 nil 停止
for i, v in ipairs({10, 20, 30}) do
    print(i, v)
end

local sparse = {10, 20, nil, 40}
for i, v in ipairs(sparse) do
    -- 只迭代到 10,20(遇 nil 停)
end

4. table 是值传递还是引用传递?

引用传递。

local function modify(t)
    t.x = 100     -- 改外部
end

local data = {x = 1}
modify(data)
print(data.x)      -- 100

5. 删除 table 字段?

local t = {a = 1, b = 2}
t.a = nil              -- ✅ 唯一方法
-- table.remove 仅用于数组(按位置删)

三、元表

1. 元表是什么?

给 table 附加行为的特殊 table。

local mt = {
    __tostring = function(t) return "Custom: " .. t.x end,
    __add = function(a, b) return {x = a.x + b.x} end,
}

local obj = setmetatable({x = 10}, mt)
print(obj)             -- "Custom: 10"(触发 __tostring)

2. __index 与 __newindex?

-- __index:字段查找不到时 fallback
local parent = {x = 10}
local child = setmetatable({}, {__index = parent})
print(child.x)         -- 10(从 parent 找)

-- __newindex:字段赋值时拦截
local t = setmetatable({}, {
    __newindex = function(t, k, v)
        print("setting", k, "=", v)
        rawset(t, k, v)  -- 真正写入
    end
})
t.foo = 42            -- 打印 "setting foo = 42"

3. Lua OOP 实现?

通过 __index 实现继承。

local Animal = {}
Animal.__index = Animal

function Animal:new(name)
    return setmetatable({name = name}, Animal)
end

function Animal:speak() return self.name .. " sound" end

local Dog = setmetatable({}, {__index = Animal})
Dog.__index = Dog
setmetatable(Dog, {__index = Animal})  -- 继承 Animal

function Dog:new(name)
    local self = setmetatable({}, Dog)
    self.name = name
    return self
end

function Dog:speak() return self.name .. " barks" end

local d = Dog:new("Buddy")
print(d:speak())       -- "Buddy barks"

4. 常见运算符重载?

local mt = {
    __add      = function(a, b) ... end,  -- +
    __sub      = ...,                       -- -
    __mul      = ...,                       -- *
    __div      = ...,                       -- /
    __mod      = ...,                       -- %
    __pow      = ...,                       -- ^
    __unm      = ...,                       -- 一元 -
    __concat   = ...,                       -- ..
    __len      = ...,                       -- #
    __eq       = ...,                       -- ==
    __lt       = ...,                       -- <
    __le       = ...,                       -- <=
    __index    = ...,                       -- 读
    __newindex = ...,                       -- 写
    __call     = ...,                       -- 调用
    __tostring = ...,                       -- 字符串化
    __gc       = ...,                       -- GC 钩子
    __metatable = ...,                      -- 保护元表
}

5. rawget / rawset / rawequal?

绕过元方法,直接操作 table。

-- rawget:不走 __index,直接读
local t = setmetatable({}, {__index = {x = 1}})
print(t.x)              -- 1(走 __index)
print(rawget(t, "x"))   -- nil(不走)

-- rawset:不走 __newindex
-- rawequal:不走 __eq

四、模块与 require

1. require 的缓存机制?

-- 模块只加载一次
local m1 = require("foo")
local m2 = require("foo")
print(m1 == m2)        -- true(同一个)

-- 强制重新加载
package.loaded["foo"] = nil
local m = require("foo")

2. package.path?

print(package.path)
-- "./?.lua;/usr/share/lua/5.4/?.lua;..."
-- ? 替换模块名

-- 自定义路径
package.path = "./src/?.lua;" .. package.path

3. 模块如何返回多个文件?

-- 主模块返回子模块
-- main.lua
return {
    config = require("mod.config"),
    logger = require("mod.logger"),
}

-- 使用
local app = require("main")
app.config.host

五、协程

1. coroutine 与 thread 的区别?

Lua coroutine 是协作式,同一时刻只有一个在跑。OS thread 是抢占式,可并行。

local co = coroutine.create(function()
    print("running")
    coroutine.yield()        -- 主动让出
    print("resumed")
end)

coroutine.resume(co)         -- running
coroutine.resume(co)         -- resumed

2. coroutine.create vs wrap?

-- create:返回 thread,需用 resume 启动
local co = coroutine.create(f)
coroutine.resume(co)

-- wrap:返回函数,调用即 resume(无法获取 ok/err)
local f = coroutine.wrap(f)
f()    -- 自动 resume

3. yield 的值传递?

local co = coroutine.create(function(x)
    local y = coroutine.yield(x + 1)  -- yield 后,resume(y) 会传 y
    print("got:", y)
end)

local ok, val = coroutine.resume(co, 10)
print(val)                 -- 11(yield 返回 x+1)

coroutine.resume(co, "hello")
-- got: hello

六、错误处理

1. pcall vs xpcall?

-- pcall(f, ...):简单捕获,返回 (ok, result/err)
local ok, err = pcall(function() error("oops") end)
-- ok = false, err = "oops"

-- xpcall(f, err_handler, ...):可自定义错误处理
local ok, err = xpcall(function() error("oops") end, function(e)
    print("handled:", e)
    return e  -- 必须返回字符串
end)

2. error 的 level 参数?

-- level 1(默认):错误位置在 error() 调用处
-- level 2:错误位置在调用 error() 的函数的调用者

local function deep() error("from deep", 2) end
local function mid() deep() end
mid()
-- 错误信息指向 mid

3. 调试调用栈?

print(debug.traceback("manual trace"))
-- 输出完整调用栈

local info = debug.getinfo(2, "Sl")
print(info.short_src, info.currentline)

七、性能

1. 字符串拼接性能?

-- ❌ O(n²)
local s = ""
for i = 1, 10000 do
    s = s .. i
end

-- ✅ O(n)
local t = {}
for i = 1, 10000 do
    t[i] = tostring(i)
end
local s = table.concat(t, ",")

2. table 访问 vs 局部变量?

-- 局部变量访问最快
local n = 0
for i = 1, 10000 do
    n = n + 1
end

-- table 访问慢几倍
local t = {n = 0}
for i = 1, 10000 do
    t.n = t.n + 1
end

-- 优化:用 local 缓存
local t = {n = 0}
for i = 1, 10000 do
    local n = t.n
    t.n = n + 1
end

3. string intern 的好处?

-- 相同字符串只存一份
-- 相等比较 O(1)(hash 比较)
-- 创建时查全局 hash 表(稍慢)

local s1 = "hello world"
local s2 = "hello world"
print(s1 == s2)          -- true(同地址)
print(rawequal(s1, s2))  -- true(同对象)

八、标准库

1. string.match vs string.find?

-- find:返回起止位置
print(string.find("hello", "ll"))     -- 3  4

-- match:返回匹配的捕获组
print(string.match("hello", "(l+)"))    -- "ll"

-- gmatch:迭代器
for word in string.gmatch("a b c", "%w+") do
    print(word)        -- a b c
end

-- gsub:全局替换,返回 (新串, 替换次数)
print(string.gsub("hello", "l", "L"))   -- "heLLo"  2

2. table.concat 的限制?

-- 只拼接数组部分(连续整数下标)
local t = {a = 1, b = 2, "x", "y"}
print(table.concat(t, ","))     -- "x,y"(只取数字下标)

3. math.randomseed?

-- 必须先设种子,否则序列固定
math.randomseed(os.time())    -- 用当前时间

-- Lua 5.4:可省种子,默认行为
-- 旧版本 Lua:不设种子则每次序列相同

九、GC

1. Lua 的 GC 算法?

增量标记-清除(incremental mark-and-sweep)。

  • 标记阶段:从根集合出发,标记所有可达对象
  • 清除阶段:回收不可达对象
  • 增量:分步执行,与用户代码交替,避免长时间 STW

2. pause 与 stepmul?

collectgarbage("setpause", 200)    -- 堆翻倍时启动新循环
collectgarbage("setstepmul", 200)   -- GC 速度 = 2x 分配速度

-- 增大 pause = GC 更不积极(内存大,暂停少)
-- 减小 pause = GC 更频繁(内存小,可能卡顿)

3. weak table 用途?

-- 不阻止 GC,缓存 / 对象池

local cache = setmetatable({}, {__mode = "v"})
local function expensive(key)
    if cache[key] then return cache[key] end
    local v = compute(key)
    cache[key] = v
    return v
end

4. __gc 元方法?

-- 对象被 GC 时调用,用于资源清理

local Resource = {}
Resource.__index = Resource
setmetatable(Resource, {__gc = function(self)
    if self.handle then
        self.handle:close()
    end
end})

function Resource.new()
    return setmetatable({handle = io.open("x.txt", "r")}, Resource)
end

十、综合题

1. 实现深拷贝?

function deep_copy(t)
    if type(t) ~= "table" then return t end
    local out = {}
    for k, v in pairs(t) do
        out[deep_copy(k)] = deep_copy(v)
    end
    return out
end

2. 实现栈 / 队列?

-- 栈(LIFO)
local Stack = {}
Stack.__index = Stack

function Stack.new()
    return setmetatable({items = {}}, Stack)
end

function Stack:push(v) table.insert(self.items, v) end
function Stack:pop()   return table.remove(self.items) end
function Stack:top()   return self.items[#self.items] end
function Stack:len()    return #self.items end

-- 队列(FIFO):用两个栈或循环数组
local Queue = {}
Queue.__index = Queue

function Queue.new()
    return setmetatable({in = {}, out = {}}, Queue)
end

function Queue:enqueue(v) table.insert(self.in, v) end

function Queue:dequeue()
    if #self.out == 0 then
        while #self.in > 0 do
            table.insert(self.out, table.remove(self.in))
        end
    end
    return table.remove(self.out)
end

3. 实现带超时的 sleep?

-- 用 socket 实现
local socket = require("socket")
local function sleep(ms)
    socket.sleep(ms / 1000)
end

-- 或用 coroutine + os.time()
local function sleep(ms)
    local co = coroutine.running()
    socket.select(nil, nil, ms / 1000)  -- 等待
    -- 实际是挂起调度
end

4. 手写 LRU cache?

local LRU = {}
LRU.__index = LRU

function LRU.new(cap)
    return setmetatable({
        cap = cap,
        map = {},
        order = {},  -- 顺序:key 列表,front 是最新
    }, LRU)
end

function LRU:get(k)
    if not self.map[k] then return nil end
    -- 更新顺序
    for i, key in ipairs(self.order) do
        if key == k then table.remove(self.order, i) break end
    end
    table.insert(self.order, 1, k)
    return self.map[k]
end

function LRU:set(k, v)
    if self.map[k] then
        for i, key in ipairs(self.order) do
            if key == k then table.remove(self.order, i) break end
        end
    end
    self.map[k] = v
    table.insert(self.order, 1, k)

    while #self.order > self.cap do
        local evicted = table.remove(self.order)
        self.map[evicted] = nil
    end
end

十一、面试必备清单

基础必答

  • [ ] 8 种数据类型 / nil 与 false
  • [ ] local 块作用域 / 全局变量
  • [ ] table 同时是数组和哈希表
  • [ ] pairs / ipairs 区别
  • [ ] # 的限制(只对序列)
  • [ ] table 是引用传递
  • [ ] nil 删除字段
  • [ ] 字符串不可变 / intern 机制

元表与 OOP

  • [ ] __index 字段查找 fallback
  • [ ] __newindex 字段赋值拦截
  • [ ] 常用运算符重载元方法
  • [ ] Lua OOP 通过 metatable + __index
  • [ ] 继承:子类 metatable.__index = 父类
  • [ ] rawget / rawset 绕过元方法

模块与 require

  • [ ] 模块返回 table,local M = {}
  • [ ] require 缓存,package.loaded
  • [ ] package.path 搜索路径,? 替换
  • [ ] pcall(require, ...) 安全加载

协程

  • [ ] create / resume / yield / wrap
  • [ ] 协作式 vs OS 线程
  • [ ] yield 的值传递
  • [ ] 状态:suspended / running / dead

错误处理

  • [ ] error(msg, level) 抛出
  • [ ] assert(v, msg) 断言
  • [ ] pcall 返回 (ok, result)
  • [ ] xpcall 自定义错误处理
  • [ ] debug.traceback 调试

性能与 GC

  • [ ] 字符串拼接用 table.concat
  • [ ] 局部变量 > table 访问
  • [ ] 增量标记清除 GC
  • [ ] pause + stepmul 控制
  • [ ] weak table 不阻止 GC
  • [ ] __gc 钩子清理资源

十二、要点速记

  • 8 种类型,table 是唯一复合类型
  • 只有 nil / false 为假,其他都真
  • local 块作用域,默认全局
  • # 仅对 1..n 序列有意义
  • pairs 无序遍历所有,ipairs 数组遍历遇 nil 停
  • table 引用传递,删字段 t.k = nil
  • __index 是字段查找 fallback,OOP 核心
  • OOP:setmetatable(obj, {__index = cls})
  • 继承:setmetatable(Child, {__index = Parent})
  • require 缓存,package.path 搜索
  • 协程协作式,yield 主动让出
  • pcall 捕获错误,返回 (ok, result)
  • GC 增量标记清除,pause 与 stepmul 控制
  • weak table __mode = "k/v/kv" 不阻止 GC