lua语言一个数组的问题。

function minzhi()
local days={"1","2","3","4","5","6","7","8","9","0","a","b","c","d","e","f","g","h","j","k","l","q","w",
"e","r","t","y","u","i","o","p","z","x","c","v","b","n","m"}
end
print (minzhi())
如何让函数每次运行,从第一个数组开起输出,一直到最后一个,又从第一个输出,这样循环显示

慕少森
浏览 873回答 2
2回答

largeQ

用 closure 最简单,比如下面的代码,每次调用 minzhi() 都会打印 days 里的元素。123456789101112131415161718function newMinzhi()    local days={"1","2","3","4","5","6","7","8","9","0","a","b","c","d","e","f","g","h","j","k","l","q","w",        "e","r","t","y","u","i","o","p","z","x","c","v","b","n","m"}    local idx = 1    return function ()        if idx > #days then            idx = 1        end        print(days[idx])        idx = idx + 1    endend minzhi = newMinzhi()minzhi()   -- 打印 1minzhi()   -- 打印 2minzhi()   -- 打印 3................ 

九州编程

1234567891011121314151617-- 之前的版本直接把内容打印出来了,现在的版本改成返回 days 中的值。 function newMinzhi()    local days= {"中", "国"}    local idx = 1    return function ()        if idx > #days then            idx = 1        end        local ret = days[idx]        idx = idx + 1        return ret    endendminzhi = newMinzhi()print(minzhi())print(minzhi()) 
打开App,查看更多内容
随时随地看视频慕课网APP