加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

关于lua corountine的简历和收益函数的困惑

发布时间:2020-12-14 21:42:11 所属栏目:大数据 来源:网络整理
导读:我正在通过这个 video tutorial学习lua,它有这段代码: co = coroutine.create(function() for i=1,5 do print(coroutine.yield(i)) end end)print(coroutine.resume(co,1,2))print(coroutine.resume(co,3,4))print(coroutine.resume(co,5,6))print(coroutin
我正在通过这个 video tutorial学习lua,它有这段代码:

co = coroutine.create(function()
    for i=1,5 do
      print(coroutine.yield(i))
    end
  end)

print(coroutine.resume(co,1,2))
print(coroutine.resume(co,3,4))
print(coroutine.resume(co,5,6))
print(coroutine.resume(co,7,8))
print(coroutine.resume(co,9,10))
print(coroutine.resume(co,11,12))

输出是这样的:

true    1
3   4
true    2
5   6
true    3
7   8
true    4
9   10
true    5
11  12
true

但是我不明白收益和恢复如何将参数传递给对方以及为什么收益率不输出恢复传递给它的前1,2,有人可以解释一下吗?谢谢

解决方法

普通的Lua函数有一个条目(其中传入参数)和一个exit(传递返回值):

local function f( a,b )
  print( "arguments",a,b )
  return "I'm","done"
end

print( "f returned",f( 1,2 ) )
--> arguments       1       2
--> f returned      I'm     done

通过将参数放在括号中将参数绑定到参数名称(局部变量),可以通过将函数调用表达式放在赋值语句的右侧来检索作为return语句的一部分列出的返回值,或者在更大的表达式内(例如另一个函数调用).

有其他方法可以调用函数.例如. pcall()调用一个函数并捕获可能在其中引发的任何运行时错误.通过将它们作为参数放入pcall()函数调用(在函数本身之后)传入参数. pcall()还预置了一个额外的返回值,指示函数是正常退出还是通过错误退出.被调用函数的内部不变.

print( "f returned",pcall( f,2 ) )
--> arguments       1       2
--> f returned      true    I'm     done

您可以使用coroutine.resume()而不是pcall()来调用协同程序的main函数.传递参数的方式和额外的返回值保持不变:

local th = coroutine.create( f )
print( "f returns",coroutine.resume( th,2 ) )
--> arguments       1       2
--> f returns       true    I'm     done

但是使用协同程序,你可以通过另一种方式(临时)退出函数:coroutine.yield().您可以通过coroutine.yield()将值作为参数传递给yield()函数调用来传递出去.这些值可以作为coroutine.resume()调用的返回值而不是正常返回值在外部检索.

但是,您可以通过再次调用coroutine.resume()重新输入生成的协同程序.协程从它停止的地方继续,并且传递给coroutine.resume()的额外值可用作之前暂停协程的yield()函数调用的返回值.

local function g( a,b )
  local c,d = coroutine.yield( "a" )
  print( "yield returned",c,d )
  return "I'm","done"
end

local th = coroutine.create( g )
print( "g yielded",2 ) )
print( "g returned",4 ) )
--> arguments       1       2
--> g yielded       true    a
--> yield returned  3       4
--> g returned      true    I'm     done

注意,yield不需要直接在coroutine的main函数中,它可以在嵌套函数调用中.执行跳转回coroutine.resume(),首先(重新)启动协同程序.

现在问你为什么第一个resume()中的1,2不会出现在你的输出中:你的coroutine main函数没有列出任何参数,因此忽略了传递给它的所有参数(在第一个函数入口上).在类似的说明中,由于您的main函数不返回任何返回值,因此最后一个resume()除了表示成功执行的t??rue之外不返回任何额外的返回值.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读