Avoiding Require Errors

Posted by Candido on Sat 10 Jul 2010 05:14 PM — 5 posts, 23,457 views.

USA #0
So I made a plugin that works fine without lua socket, but also has some added functionality if you have lua socket. The problem is that if you don't have lua socket, require will spam you with the 'not found' error. I feel like there should be a simple way to check for the existence of an add on like lua socket before you require it, but I can't seem to figure it out. I tried the obvious,

if require("socket.http") then http = require("socket.http") end

but that still generates the error. Anyone have some insight?
USA #1
I believe you can pcall(require , "socket") and then check package.loaded.socket if it actually did.


pcall (require, "socket")

-- Do happy stuff


if package.loaded.socket then 
  -- do enhanced functionality stuff.
end



actually, if socket should be enough, but package.loaded may be the safer route.
Amended on Sat 10 Jul 2010 07:53 PM by WillFa
USA #2
Did the trick. Thanks.
Australia Forum Administrator #3
The pcall tells you if it succeeded or not, so this is more reliable:


ok = pcall (require, "socket"); 

if ok then 
  -- use socket library now
end -- if

Australia Forum Administrator #4
You can also do this, to find what require returned:


ok, socket = pcall (require, "socket"); 

if ok then 
  -- use socket library now 

  -- the value "socket" is non-nil and is the same as
  -- package.loaded.socket 

end -- if


This effectively lets you test later on if the require worked (which is pretty-much what Willfa suggested).

This works because the pcall returns as its second (and subsequent) return values what the original function returned, on success.