开发者

return or not return

I'm learning Lua coroutines. I found a weired thing to me, both


meta = function ()
    for i = 1, 10 do
        coroutine.yield(i)
    end
end

for i in coroutine.wrap(function() return meta() end) do
    print(i)
end

and



meta = function ()
    for i = 1, 10 do
        coroutine.yield(i)
    end
end

for i in coroutine.wrap(function() meta() end) do
    print(i)
end

(note there is return in the first version)give me

~/test% lua t.lua
1
2
3
4
5
6
7
8
9开发者_开发问答
10

So, what is the role of return? I think meta() will return a value and the anonymous function should return it as well. So why the anonymous function without return is also right?


No, meta does not return anything - at least nothing important.

The output passed to the i variable of the outer loop comes from the yield method, not from the return.

You can see this if you write the loop like this:

for i in coroutine.wrap(function()
           val = {meta()}
           print ("----")
           print (val)
        end) do
    print(i)
end

The output is

1
2
3
4
5
6
7
8
9
10
----
nil

The anoymous function, as well as meta, is called only once.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜