为什么Lua+Nginx无法调用全局函数?

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

function detect_browser_platform(user_agent)
    -- 在此处执行一些字符串匹配和类似的操作
    return browser_platform
end

function detect_os_platform(user_agent)
    -- 在此处执行一些字符串匹配和类似的操作
    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')

-- 一些代码写在这里

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 -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,没有时间深入了解这种语言... 那么我为什么会出现这个错误呢?

点赞
用户1979882
用户1979882
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)
2016-09-19 12:41:01