2016-09-19 35 views
1

我有兩個簡單的功能,基於用戶代理檢測瀏覽器和操作系統,它們存儲在文件useragent.lua爲什麼Lua + Nginx說它不能調用全局函數?

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開始編程,沒有時間深入語言理解......那麼爲什麼我會得到這個錯誤?

回答

4

由表總結吧:

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) 
+0

謝謝,現在的工作! – clzola