イテレータ メモ

必要に応じて複数の要素を消費するloopのメモ。

#!/usr/bin/env lua

function process(file)
    local f=assert(io.open(file, "rb"))
    print("process:", file)
    local _f, _s, _var=string.gmatch(f:read("*all"), "(.-)\r?\n")
    while true do
        local line=_f(_s, _var)
        if line==nil then 
            break 
        elseif line=="" or string.sub(line, 1, 1)=="#" then
            -- comment
        elseif line=="comment" then
            while true do
                local line=_f(_s, _var)
                if line==nil then break end
                if line=="/comment" then
                    break
                end
            end
        elseif line=="title" then
            while true do
                local line=_f(_s, _var)
                if line==nil then break end
                if line=="/title" then
                    break
                end
            end
        else
            key, value=string.match(line, "([%a_]+)%s+(.*)")
            if key then
                print(key)
            else
                print("no match:", line)
            end
        end
    end
end

for i, v in ipairs(arg) do
    process(v)
end

テキスト形式の処理ではよくあること。。。