【问题标题】:Why Lua+Nginx says it cannot call global function?为什么 Lua+Nginx 说不能调用全局函数?
【发布时间】:2016-09-19 20:41:01
【问题描述】:

我有两个基于用户代理检测浏览器和操作系统的简单函数,它们存储在文件useragent.lua 中。

function detect_browser_platform(user_agent)
    -- Here goes some string matching and similar stuff
    return browser_platform
end

function detect_os_platform(user_agent)
    -- Here goes some string matching and similar stuff
    return os_platform
end

function detect_env_pattern(user_agent)
    return detect_operating_system_platform(user_agent) .. "-" .. detect_browser_platform(user_agent) .. "-" .. ngx.var.geoip2_data_country_code
end

在虚拟主机配置文件中,有一行说当请求看起来像/lua时执行lua脚本:/var/www/default/test.lua

test.lua我有这个代码:

local posix = require('posix')
local redis = require('redis')
require('useragent')

-- Some code goes here

local user_agent = ngx.req.get_headers()['User-Agent']
local pattern_string = detect_env_pattern(user_agent)

ngx.say(pattern_string)
ngx.exit(200)

但由于某种原因,当我重新加载 nginx nginx -s reload 时,此代码仅在第一次工作。当我提出另一个请求时,它说这个错误:

2016/09/19 12:30:08 [error] 19201#0: *125956 lua entry thread aborted: runtime error: /var/www/default/test.lua:199: attempt to call global 'detect_env_pattern' (a nil value)

而且我不知道这里发生了什么。我刚开始在 Lua 中编程,没有时间深入了解语言……那为什么会出现这个错误?

【问题讨论】:

    标签: nginx lua


    【解决方案1】:

    用一张桌子把它包起来:

    local M={};
    
    
    
    function detect_browser_platform(user_agent)
        -- Here goes some string matching and similar stuff
        return browser_platform
    end
    
    function detect_os_platform(user_agent)
        -- Here goes some string matching and similar stuff
        return os_platform
    end
    
    function detect_env_pattern(user_agent)
        return detect_operating_system_platform(user_agent) .. "-" .. detect_browser_platform(user_agent) .. "-" .. ngx.var.geoip2_data_country_code
    end
    
    M.detect_env_pattern = detect_env_pattern
    return M
    

    在基础lua 文件中:

      local useragent = require('useragent')
        --.....
        local user_agent = ngx.req.get_headers()['User-Agent']
    local pattern_string = useragent.detect_env_pattern(user_agent)
    
    ngx.say(pattern_string)
    ngx.exit(200)
    

    【讨论】:

      猜你喜欢
      • 2012-03-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-11
      • 1970-01-01
      • 2011-04-22
      • 2021-08-31
      • 1970-01-01
      • 2012-08-08
      相关资源
      最近更新 更多