Search code examples
nginxluaredis

Module socket not found lua


I am trying to use Lua to access Redis values from nginx. When I execute Lua files on the command line, I can read and write values to Redis. But when I try to execute the same files from nginx by accessing a location in which the access_by_lua directive is written, the following errors are logged in the error log file

no field package.preload['socket'] 
no file '/home/sivag/redis/redis-lua/src/socket.lua'
no file 'src/socket.lua'
no file '/home/sivag/lua/socket.lua'
no file '/opt/openresty/lualib/socket.so'
no file './socket.so'
no file '/usr/local/lib/lua/5.1/socket.so'
no file '/opt/openresty/luajit/lib/lua/5.1/socket.so'
no file '/usr/local/lib/lua/5.1/loadall.so'

What is the reason for this and how can I resolve this?


Solution

  • You get this error because your code executes the command require("socket") This command will search for a file with that name in several directories. If successful the content will be executed as Lua code. If it is not successful you'll end up with your error message.

    In order to fix this you have to add the path containing the file either to the system variable LUA_PATH or you have to add it to the global table package.path befor you require the file. Lua will replace ? with the name you give to require()

    For example

    package.path = package.path .. ";" .. thisPathContainsTheLuaFile .. "?.lua"
    

    Please read:

    http://www.lua.org/manual/5.3/manual.html#pdf-require

    https://www.lua.org/pil/8.1.html