使用Lua语言解析Lua脚本中的函数,打印函数名和函数参数。考虑匿名函数 ,共计入了4种定义函数的形式。
function printFunction()
local handle = io.popen('需要解析的脚本文件夹路径')
local resultFile = io.open('存放结果的文件路径', 'w')
for file in handle:lines() do
local temp, _ = string.find(file, '.lua')
if temp then
resultFile:write("fileName: " .. file)
resultFile:write("\n")
local fileHandle = io.open(file, "r")
local tempLines = ""
for line in fileHandle:lines() do
local commentLoc, _ = string.find(line, '%-%-')
-- 去除注释
if commentLoc then
line = string.sub(line, 1, commentLoc - 1)
end
line = line .. "\n"
-- 考虑逗号后面换行的情况,进行拼接
tempLines = tempLines .. line
local nextPos, _ = string.find(line, ',%s*\n')
if not nextPos then
-- function xx(...)
local _, leftBorder1, functionName1 = string.find(tempLines, 'function%s+([%a_%d]+)%s*%(')
-- xx = function(...)
local _, leftBorder2, functionName2 = string.find(tempLines, "%[[\'\"]([%a_%d]+)[\'\"]%]%s*=%s*function%s*%(")
-- ['xx'] = function(...)
local _, leftBorder3, functionName3 = string.find(tempLines, '([%a_%d]+)%s*=%s*function%s*%(')
-- function(...),没有名字也没有赋值给任何变量,被当作参数传递
local _, leftBorder4 = string.find(tempLines, '[^%a^_^%d]function%s*%(')
local functionName4 = leftBorder4 and ""
-- 找到第一个可以匹配的名字
local functionName = functionName1 or functionName2 or functionName3 or functionName4
if functionName then
resultFile:write("functionName: " .. functionName)
resultFile:write("\n")
local leftBorder = leftBorder1 or leftBorder2 or leftBorder3 or leftBorder4
local endPos, _ = string.find(tempLines, '%)', leftBorder + 1) or 0
local subLine = string.sub(tempLines, leftBorder + 1, endPos - 1)
for argName in string.gmatch(subLine, '[%a_%d]+') do
resultFile:write("argName: ", argName)
resultFile:write("\n")
end
end
tempLines = ""
end
end
fileHandle:close()
end
end
resultFile:close()
handle:close()
end
1342



被折叠的 条评论
为什么被折叠?



