Why Lua+Nginx says it cannot call global function?
<p>I have two simple functions that detects browser and operating system based on user agent and they are stored in file <code>useragent.lua</code>. </p>

<pre><code>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
</code></pre>

<p>In virtual host configuration file, there is a line that says when request looks like <code>/lua</code> execute lua script: <code>/var/www/default/test.lua</code>.</p>

<p>In <code>test.lua</code> I have this code:</p>

<pre><code>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)
</code></pre>

<p>But for some reason when I reload nginx <code>nginx -s reload</code>, this codes works only first time. When I make another request it says this error:</p>

<pre><code>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)
</code></pre>

<p>And I have no idea what is happening here. I have just started programming in Lua and don't have time to go deep with language understandings... So why am I getting this error?</p>