lua语言一个数组的问题。

functionminzhi()localdays={"1","2","3","4","5","6","7","8","9","0","a","b","c","d","e... 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())
如何让函数每次运行,从第一个数组开起输出,一直到最后一个,又从第一个输出,这样循环显示
展开
 我来答
kwydwuf
推荐于2016-08-03 · TA获得超过7411个赞
知道大有可为答主
回答量:1527
采纳率:71%
帮助的人:2013万
展开全部

用 closure 最简单,比如下面的代码,每次调用 minzhi() 都会打印 days 里的元素。

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
................
追问

下面显示的怎么都是楼字,和英文。中文是字符串。要怎么弄。直接调用这个函数。可以用的。

追答
-- 之前的版本直接把内容打印出来了,现在的版本改成返回 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())
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式