Lua程序設計第4版第18章課後練習答案

–18.1 18.2
其實就是閉包的運用,記住foreach迭代的規則是不變量和變量組合傳入,返回索引和索引對應的值。

--18.1 18.2
local m = 1 --m就是步長,其實就是根據步長輸出表的內容,說話都說不利索,我他嗎真的是想打人,噁心
local function noState(n,i)
    i = i+m
    local v=  n[i]
    if v then
        return i,v
    end
end
for i,v in noState,{1,2,3,4,5},0 do
    print(i.." "..v)
end

18.3

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

18.4

local str = "ice cold";
function getSub(s)
    local bi = 1
    local ei  = 0
   return function()
       ei = ei+1
       if ei>string.len(s) then
           bi= bi+1
           if bi>string.len(s) then
               return nil
           end
           ei = bi
       end
       local sb = str:sub(bi,ei)
       return str:sub(bi,ei)
   end
end
for sb in getSub(str) do
    print(sb)
end

18.5
算了吧,對老迭代器不敢興趣

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章