为了账号安全,请及时绑定邮箱和手机立即绑定

lua语言一个数组的问题。

lua语言一个数组的问题。

慕少森 2019-04-11 10:06:08
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"}endprint (minzhi())如何让函数每次运行,从第一个数组开起输出,一直到最后一个,又从第一个输出,这样循环显示
查看完整描述

2 回答

?
largeQ

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

................

 


查看完整回答
反对 回复 2019-04-12
?
九州编程

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


 


查看完整回答
反对 回复 2019-04-12
  • 2 回答
  • 0 关注
  • 872 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信