openresty-best-practices icon indicating copy to clipboard operation
openresty-best-practices copied to clipboard

变量作用范围里关于timer的一处错误

Open RocFang opened this issue 4 years ago • 1 comments

https://github.com/moonbingbing/openresty-best-practices/blob/master/ngx_lua/lua-variable-scope.md

在这一节里,提到:

init_worker_by_lua_block {
    local delay = 5
    local handler
    handler = function()
        counter = counter or 0
        counter = counter + 1
        ngx.log(ngx.ERR, counter)
        local ok, err = ngx.timer.at(delay, handler)
        if not ok then
            ngx.log(ngx.ERR, "failed to create the timer: ", err)
            return
        end
    end
    local ok, err = ngx.timer.at(delay, handler)
    if not ok then
        ngx.log(ngx.ERR, "failed to create the timer: ", err)
        return
    end
}

每次 counter 的输出都是 1。

然后实际的情况是,确实每次 timer 执行都在累加,而并没有重新定义。应该需要更新一下文档。

@membphis

RocFang avatar Jun 23 '21 02:06 RocFang

欢迎 PR ^_^

membphis avatar Jun 30 '21 08:06 membphis