Lua 异步封装

在lua里面的异步代码主要是通过闭包实现,结合asio,一些简单的封装,方便编写异步代码,比如异步的while,异步的for等

222454_dXBI_1391394.png

useage:

222326_wUkM_1391394.png

 


--[[
* Author: caoshanshan
* Email: me@dreamyouxi.com
异步lib 封装 方便快速写异步lua代码
@see useage
]]

local t = { }

-- 异步循环调用 直到成功 或者达到深度
-- cb需要执行的函数 第一个参数是async对象,调用async:_continue() 继续执行
-- auto_run  run auto ? if not you should call it manual
-- max run depth ,just for avoid run forever
function t.async_while_true(cb, auto_run, MAX_DEPTH)
    local depth = 0;
    if auto_run == nil then
        auto_run = true;
    end
    MAX_DEPTH = MAX_DEPTH or 1000;
    local obj = { };
    obj.run = true;
    obj.cb = cb;
    obj._continue = function(self)
        if self.run and depth < MAX_DEPTH then
            depth = depth + 1;
            self:cb();
        else
            --  print("  out of range");
        end
    end
    obj._break = function(self)
        self.run = false;
    end
    if auto_run then
        obj:_continue();
    end
    return obj;
end


return t;


useage:


function t.ttttt(ctx, msg, cb)
    local redis_key = redis_key.get_uuid_gen();

    async.async_while_true( function(async)
        redis.incr(redis_key, function(v)
            if v and v ~= "" then
                local ok = uuid_helper.check_is_valid(v);
                if ok then
                    local uuid = v;
                    cb(uuid);
                else
                    -- re gen
                    async:_continue();
                    return;
                end
            end
        end )
    end );
end

 

转载于:https://my.oschina.net/kkkkkkkkkkkkk/blog/1595353

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值