1

I have a directory with several sub-directories and they all have .lua files. I want to calculate the lines of code in all files total.

I have experience in lua, but I've never done file system stuff, so I'm new to this. I understand I would have to recursively iterate the main folder, but I'm not familiar with how the io library works, so if anyone could explain to me how to do this I'd really appreciate it

2 Answers2

2

Is using Lua a requirement? You can use a quick Python script to do that.

Like so:

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

That will print the number of lines of each file in the current working directory.

Partial code from here and here.

Community
  • 1
  • 1
Rob Rose
  • 1,806
  • 22
  • 41
  • No, not a requirement, it's just the only programming language I have installed. – user3806186 Nov 19 '15 at 18:54
  • Ah. I believe [this](http://www.tutorialspoint.com/python/) tutorial has a section on setting up the Python environment. Note that the code I provided is for Python 2, not Python 3. – Rob Rose Nov 19 '15 at 19:15
  • 2
    On Linux you could do `find . -name "*.lua" -print0 | xargs -0 wc -l`. (If you use another OS, I'm sure there are tutorials out there for setting up Linux.) – siffiejoe Nov 19 '15 at 19:45
  • Your code seems to result in: NameError: name "os" is not defined – user3806186 Nov 19 '15 at 19:55
  • Whoops. I forgot to say you have to import stuff. Just put `import os` at the start of the program. – Rob Rose Nov 19 '15 at 19:56
0

Alright I used LuaFileSystem and it seems to work fine. Thanks to Rob Rose for the python example though, even though I did not get it to work properly.

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()