lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Hello all,

I have to say that allowing functions as well as tables in for loops is a
subtle but very powerful change. Very nice.


For example, I've always disliked having to do the for i=1,getn(t)...
business to iterate through a "array" style table.

So the old way:

    t = {"now", "is", "the", "time"}

    for i=1,getn(t) do
        print(i,t[i])
    end


But now a simple generic iteration function can be defined:

    function indexiter(tab)
        local i=0
        return function()
            i=i+1
            if i<=getn(tab)
                return i,tab[i]
            end
        end
    end

After which indexed operators can use this form:

    t = {"now", "is", "the", "time"}

    for k,v in indexiter(t) do
        print(k,v)
    end


Likewise an iterator for the lines of text in a file can be created:

    function lineiter(fname)
        local counter = 0
        local f = openfile(fname,"r")
        return function()
            counter = counter + 1
            local line = read(f,"*l")
            if line~=nil then
                return counter, line
            else
                closefile(f)
            end
        end
    end


And now the lines in the file "data.txt" can be printed out (with line
numbers) like this:

    for k,v in lineiter("data.txt") do
        print(k,v)
    end


Of course you can do something considerably more interesting than just
print the lines of text. 

Other iterators can be built for reading files by word or character.


In short his feature is seriously cool.

  - Tom