Use of the association in LUA

Source: Internet
Author: User

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 altogethercoAndyield


coTakes a function as a parameter, and the function is executed by the coroutine co-process.

yieldTo 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.