2015-11-19 49 views
1

我有一個包含多個子目錄的目錄,它們都有.lua文件。 我想計算總共所有文件中的代碼行。計算目錄中的代碼總行數

我有在lua的經驗,但我從來沒有做過文件系統的東西,所以我對此很陌生。我知道我將不得不遞歸迭代主文件夾,但我不熟悉io庫的工作方式,所以如果有人能向我解釋如何做到這一點,我真的很感激它

回答

2

正在使用Lua a需求?你可以使用一個快速的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 

,將打印在當前工作目錄下的每個文件的行數。

部分代碼來自herehere

+0

不,不是要求,它只是我安裝的唯一編程語言。 – user3806186

+0

啊。我相信[this](http://www.tutorialspoint.com/python/)教程中有關於設置Python環境的一節。請注意,我提供的代碼是針對Python 2的,而不是Python 3. –

+2

在Linux上,您可以「查找」。 -name「* .lua」-print0 | xargs -0 wc -l'。 (如果您使用其他操作系統,我確定有設置Linux的教程。) – siffiejoe

0

好吧我使用了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("total lines in working directory: "..numlines) 
end 

local s,e = pcall(main) 
if not s then 
    print(e) 
end 
io.read()