开发者社区> 问答> 正文

lua中,重写for循环迭代器的不解之处。?报错

local function iter(a, i)
	print("**  iter >>> " .. i)
	i = i + 1
	local v = a[i]
	if v then
		return i, v
	end
end

function test(a)
	return iter, a, 0
end

local tab = {4, 5, 6}

for i,v in test(tab) do
	print("##   for >>> " .. i .. " = " .. v)
	print("\n")
end



代码如上,不明白为什么test(a)中,为什么是:
return iter, a, 0

试过改成:

return iter(a, 0)
但是报错。

贴出的正常代码输出如下:

**  iter >>> 0
##   for >>> 1 = 4


**  iter >>> 1
##   for >>> 2 = 5


**  iter >>> 2
##   for >>> 3 = 6


**  iter >>> 3
[Finished in 0.4s]
求解答。

展开
收起
爱吃鱼的程序员 2020-06-08 20:28:56 938 0
1 条回答
写回答
取消 提交回答
  • https://developer.aliyun.com/profile/5yerqm5bn5yqg?spm=a2c6h.12873639.0.0.6eae304abcjaIB

    这个是lua的语法设计,文档: http://www.lua.org/manual/5.3/manual.html#3.3.5

    --Aforstatementlikeforvar_1,···,var_ninexplistdoblockend--isequivalenttothecode:dolocalf,s,var=explistwhiletruedolocalvar_1,···,var_n=f(s,var)ifvar_1==nilthenbreakendvar=var_1blockendend



    非常感谢您的解释和指导。^_^
    2020-06-08 20:29:13
    赞同 展开评论 打赏
问答分类:
问答标签:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
JAVA反射原理以及一些常见的应用 立即下载
低代码开发师(初级)实战教程 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载