Installing Lua socket library

user1248569 picture user1248569 · Apr 27, 2012 · Viewed 21.1k times · Source

Either I'm overtired or blind. I want to learn networking with Lua and therefore I have to install the socket lib, so I can require it easily, but I don't know, which files I should "require". The example says:

local socket = require("socket")

but as I said, I don't know which files I should include, if I use socket.lua it doesn't work and I get: No files found.

I got the lib from here: Lua socket download

Or, is there another way to install the socket lib?

Answer

Adam picture Adam · Apr 28, 2012

When you load a module with require Lua uses the package paths to determine where to look for the module. Have a look at the Modules section of the Lua manual. Specifically, the section on package.path and package.cpath.

package.path: The path used by require to search for a Lua loader (.lua modules)
package.cpath: The path used by require to search for a C loader (.so/.dll modules)

You can check what the current paths are:

print(package.path..'\n'..package.cpath)

If you install LuaSocket into a location within your current package paths Lua should be able to locate and load it.

Alternatively, you can modify the package paths before calling require. For example, if you create a folder for your project and extract the LuaSocket library to a sub-folder called libs within your project folder:

Project
|
> libs
     |
     > lua
         |
         > socket         
     > socket
     > mime

You can set the package paths relative to your project before you require the socket library (substitute /?.dll for /?.so on Linux):

package.path = package.path..';./libs/lua/?.lua'
package.cpath = package.cpath..';./libs/socket/?.dll;./libs/mime/?.dll'
local socket = require 'socket'