计算目录中的代码总行数

我有一个包含多个子目录的目录,它们都有.lua文件。 我想计算所有文件的代码行数。

我有Lua经验,但我从未涉足文件系统相关的技术,因此我很陌生。我理解要递归迭代主目录,但我不熟悉io库的工作原理,如果有人可以向我解释如何做到这一点,我将非常感激。

点赞
用户1021259
用户1021259

Lua 是否必须使用?您可以使用快速的 Python 脚本来完成此操作。

代码如下:

import os

for i in os.listdir(os.getcwd()):
    if i.endswith(".lua"):
        with open(i) as f:
            num_lines = sum(1 for _ in f)
            print i + str(num_lines)
            # Do whatever else you want to do with the number of lines
        continue
    else:
        continue

这将打印当前工作目录中每个文件的行数。

代码部分取自这里这里

2015-11-19 18:25:14
用户3806186
用户3806186

好的,我使用了 LuaFileSystem 并且似乎运行良好。 感谢 Rob Rose 的 python 示例,虽然我没有成功地运行它。

require("lfs")
local numlines = 0

function attrdir (path)
    for file in lfs.dir(path) do
        if file ~= "." and file ~= ".." then
            local f = path..'/'..file
            local attr = lfs.attributes (f)
            assert(type(attr) == "table")
            if attr.mode == "directory" then
                attrdir(f)
            else
                --print(f)
                --f = io.open(f, "r")
                for line in io.lines(f) do
                numlines = numlines + 1
                end
            end
        end
    end
end

function main()
    attrdir(".")
    print("working directory 中的总行数: "..numlines)
end

local s,e = pcall(main)
if not s then
    print(e)
end
io.read()
2015-11-19 20:10:40