2 回答

TA貢獻(xiàn)2039條經(jīng)驗(yàn) 獲得超8個(gè)贊
用 closure 最簡(jiǎn)單,比如下面的代碼,每次調(diào)用 minzhi() 都會(huì)打印 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貢獻(xiàn)1785條經(jīng)驗(yàn) 獲得超4個(gè)贊
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | -- 之前的版本直接把內(nèi)容打印出來了,現(xiàn)在的版本改成返回 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 關(guān)注
- 887 瀏覽
添加回答
舉報(bào)