Normal access to the network will use callbacks, and now through the process of changing the callback mode, so that asynchronous methods to use synchronous method
--Co.luayield =Coroutine.yieldco =function(Func, CB)Local Cor =Coroutine.create (func)LocalNext =Coroutine.resumeLocal hasnext; Hasnext =function(Status, Func, ...)--SuspendedIfNot status and return end --only function if type (func) = = "function" then --CA ll function func (--[[callback]]function(...) hasnext (next (Cor, ...)) end) ElseIf CB then CB (func, ...) End End Hasnext (next cor)end
--Test.luaRequire"CO")--Network asynchronous operationfunctionrequest(URL) return function(next) ... Next ("network return result") endEnd--runs a co-process method (function() Local result = Yield (Request ( "Http://login.9173.com")) local Result_json = Json.decode (Result) if Result_json.ok then – other Code EndEnd)
Two functions are used here altogetherco
Andyield
co
Takes a function as a parameter, and the function is executed by the coroutine
co-process.
yield
To receive a function as a parameter, the passed-in function will have a parameter of the next
function type, and the return value is next
the value passed in by the function, i.e.
local result = yield(function(next) next("success") -- 调用next()表示该函数运行结束,如果没有返回值直接next()即可end)-- result: success
Use of the association in LUA