《Lua 常见问题》
1. 模块之间循环引用 —— loop or previous error
问题表现:由于模块之间的循环引用导致 Nginx/OpenResty 报错:
lua entry thread aborted: runtime error: ...lua/guard/security/js_challenge/passport.lua:12: attempt to index a userdata value
failed to run header_filter_by_lua: .../lua/duedge/mode/bypass.lua:18: loop or previous error loading module 'duedge.security.postprocess'
根因:模块 A 需要引入 B 调用其中的方法 y,B 又需要引入 A 调用其中的方法 x,造成循环引用。
错误的解决方案:在引入模块前先用 or 判断是否已引入。
-- A 模块
local b = b or require("B")
b.y()
-- B 模块
local a = a or require("A")
a.x()
实测该方法仍然行不通。
推荐方案:将 A、B 模块公共的部分抽离出来,放在独立的公共模块(如 common.lua)中,A、B 分别引用 common 即可。
2. 单元测试
推荐使用 busted,一个行为驱动的 Lua 单元测试框架:
luarocks install busted
busted test_spec.lua
阅读 —
·
全站 —