lua中檢查靜態常量是否正確引用
- 思路
- 代碼
因在項目開發中會出現引用了不存在的常量,為了方便檢查這種情況,所以想著添加針對性腳本check
思路
- 加載要檢查的常量結構到KEYWORD
- 通過gmatch匹配指定路徑下的所有文件,依次檢查引用到目標變量的key是否存在于KEYWORD(主要會排除掉當前腳本路徑,最好檢查到第三層key)
代碼
-- 獲取當前腳本的路徑(用于排除)local function get_current_file_path()local current_file = debug.getinfo(1, "S").sourceif current_file:sub(1, 1) == "@" thencurrent_file = current_file:sub(2)endreturn current_fileendlocal 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]+") doif file ~= current_file thenlocal content = io.open(file):read("*a")-- 查找所有G_KEYWORD.XXX的引用for key1 in content:gmatch(S_KEYWORD .. "%.([%w_]+)") doif not KEYWORD[key1] == nil thenprint(string.format("ref_fail: file: %s ===> key1: %s ", file, key1))else-- 查找所有G_KEYWORD.XXX.XXX的引用for key2 in content:gmatch(S_KEYWORD .. "." .. key1 .. "%.([%w_]+)") doif KEYWORD[key1][key2] == nil thenprint(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_]+)") doif KEYWORD[key1][key2][key3] == nil thenprint(string.format("ref_fail: file: %s ===> key1: %s, key2: %s, key3: %s ", file, key1, key2, key3))endendendendendendendendendcheck_g_const_key()