2 回答
TA贡献2039条经验 获得超7个赞
用 closure 最简单,比如下面的代码,每次调用 minzhi() 都会打印 days 里的元素。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | function 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 end end
minzhi = newMinzhi() minzhi() -- 打印 1 minzhi() -- 打印 2 minzhi() -- 打印 3 ................ |
TA贡献1785条经验 获得超4个赞
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | -- 之前的版本直接把内容打印出来了,现在的版本改成返回 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 end end minzhi = newMinzhi() print(minzhi()) print(minzhi()) |
- 2 回答
- 0 关注
- 872 浏览
添加回答
举报