欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Lua程序设计第4版第18章练习答案

程序员文章站 2024-03-17 23:32:28
...
--18.1 18.2
function fromto(n,m)
    local k = 0
    return function()
        k = k+m
        return n[k]
    end
end
local n = {1,2,3}
local m = 2
for i in fromto(n,m) do
    if i ==nil then
        break
    end
    print(i)
end
--18.3
function allWords(fname)
    io.input(fname)
    local d = {}
    local r = {}
    local pos = 1
    local rpos = 0
    local line = io.read()
    while line do
        local word,p = string.match(line,"(%w+)()",pos)
        if word then
            d[word] = d[word]==nil and 1 or d[word]+1
            pos = p
        else
            line = io.read()
            pos = 1
        end
    end
    local cnt = 1
    for k,v in pairs(d) do
        if v==1 then
            r[cnt] = k
            cnt = cnt+1
        end
    end
    return function()
        rpos = rpos+1
        return r[rpos]
    end
end
for word in allWords("data.lua") do
    print(word)
end

 

相关标签: LUA