因在项目开发中会出现引用了不存在的常量,为了方便检查这种情况,所以想着添加针对性脚本check
思路
- 加载要检查的常量结构到KEYWORD
- 通过gmatch匹配指定路径下的所有文件,依次检查引用到目标变量的key是否存在于KEYWORD(主要会排除掉当前脚本路径,最好检查到第三层key)
代码
-- 获取当前脚本的路径(用于排除)
local function get_current_file_path()
local current_file = debug.getinfo(1, "S").source
if current_file:sub(1, 1) == "@" then
current_file = current_file:sub(2)
end
return current_file
end
local current_file = get_current_file_path()
-- 目标目录
local target_dir = "./mod/"
-- 目标常量
local S_KEYWORD = "G_COMMON"
-- 可自定义,保证KEYWORD是指向要验证的常量数据就行
local KEYWORD = _G[S_KEYWORD]
-- 这里只解析到第三层key,可以处理大多数情况了
local function check_g_const_key()
local lua_files = io.popen( 'find ' .. target_dir .. ' -name "*.lua"'):read("*a")
for file in lua_files:gmatch("[^\r\n]+") do
if file ~= current_file then
local content = io.open(file):read("*a")
-- 查找所有G_KEYWORD.XXX的引用
for key1 in content:gmatch(S_KEYWORD .. "%.([%w_]+)") do
if not KEYWORD[key1] == nil then
print(string.format("ref_fail: file: %s ===> key1: %s ", file, key1))
else
-- 查找所有G_KEYWORD.XXX.XXX的引用
for key2 in content:gmatch(S_KEYWORD .. "." .. key1 .. "%.([%w_]+)") do
if KEYWORD[key1][key2] == nil then
print(string.format("ref_fail: file: %s ===> key1: %s, key2: %s ", file, key1, key2))
else
-- 查找所有G_KEYWORD.XXX.XXX.XXX的引用
for key3 in content:gmatch(S_KEYWORD .. "." .. key1 .. "." .. key2 .. "%.([%w_]+)") do
if KEYWORD[key1][key2][key3] == nil then
print(string.format("ref_fail: file: %s ===> key1: %s, key2: %s, key3: %s ", file, key1, key2, key3))
end
end
end
end
end
end
end
end
end
check_g_const_key()