Lua: lua_resume and lua_yield arguments

What is the purpose of passing the arguments lua_resume and lua_yield?

I understand that the first call to lua_resume, the arguments are passed to the lua function, which resumes. It makes sense. However, I would expect all subsequent calls to lua_resume to โ€œupdateโ€ the arguments in the coroutine function. However, it is not.

What is the purpose of passing lua_resume arguments to return lua_yield? Can the lua function running under coroutine coroutine have access to the arguments passed to lua_resume?

+6
source share
2 answers

What did Nichol say. You can save the values โ€‹โ€‹from the first call to resume if you want:

 do local firstcall function willyield(a) firstcall = a while a do print(a, firstcall) a = coroutine.yield() end end end local coro = coroutine.create(willyield) coroutine.resume(coro, 1) coroutine.resume(coro, 10) coroutine.resume(coro, 100) coroutine.resume(coro) 

will print

 1 1 10 1 100 1 
+10
source

Lua cannot magically give new arguments to the original arguments. Perhaps they will no longer be on the stack, depending on the optimization. In addition, there is no indication of where the code was when it gave way, so it will no longer be able to see these arguments. For example, if a coroutine is called a function, this new function cannot see the arguments passed to the old one.

coroutine.yield() returns the arguments passed to the resume call, which continues the coroutine, so that the yield call site can process the parameters it wants. This allows the code making the resume to communicate with the specific code that performs the return. yield() passes its arguments as return values โ€‹โ€‹from resume , and resume passes its arguments as return values โ€‹โ€‹to yield . This sets the path to communication.

You cannot do it otherwise. Of course, not by changing the arguments, which may not be available from the yield site. It is simple, elegant and makes sense.

It was also considered extremely rude to shout out any values. Especially the function is already working. Remember: arguments are only local variables filled with values. The user should not expect the contents of these variables to change unless it changes them themselves. After all, these are local variables. They can only be changed locally; hence the name.

+5
source

All Articles