How to ignore module not found

classic Classic list List threaded Threaded
4 messages Options
Reply | Threaded
Open this post in threaded view
|

How to ignore module not found

Dan Christian
How do I make require() not cause a stack trace when a module is not found?

I have a program that sometime runs on an embedded system where some
modules may not be available.  I can't just install the module for
various reasons.

If it matters, the module is zlib.  Everything works without it, but
it can reduce bandwidth if I have it.

I tried wrapping it in pcall, but that didn't work.

Thanks,
Dan

Reply | Threaded
Open this post in threaded view
|

Re: How to ignore module not found

Tomás Guisasola-2
Hi Dan

> I tried wrapping it in pcall, but that didn't work.
It does work.  How did you do it?

-- not tested! --
-- local opt = require("optionalmod")
local ok, opt = pcall (require, "optionalmod")
if ok then
   -- opt is the module
else
   -- opt is the error message
end

Regards,
Tomás

Reply | Threaded
Open this post in threaded view
|

Re: How to ignore module not found

Matthew Wild
In reply to this post by Dan Christian
On 9 May 2016 at 17:19, Dan Christian <[hidden email]> wrote:
> How do I make require() not cause a stack trace when a module is not found?

----------------------

local have_library, library = pcall(require, "mylibrary")

-- Do something if the library was not found, if you want
if not have_library then
    print("Library was not found. Error:", library)
end

-- ... --

if have_library then
    -- Use the library
    library.foo("bar")
end

----------------------

You said pcall didn't work. Easy mistake to make is:
pcall(require("mylibrary")). Which is wrong, after you think about it
more :)

Regards,
Matthew

Reply | Threaded
Open this post in threaded view
|

Re: How to ignore module not found

Dan Christian
Doh, newbie mistake.  I put in pcall(require('zlib')), when it should
have been: pcall(require, 'zlib')

Thanks for setting me straight,
Dan


On Mon, May 9, 2016 at 9:25 AM, Matthew Wild <[hidden email]> wrote:

> On 9 May 2016 at 17:19, Dan Christian <[hidden email]> wrote:
>> How do I make require() not cause a stack trace when a module is not found?
>
> ----------------------
>
> local have_library, library = pcall(require, "mylibrary")
>
> -- Do something if the library was not found, if you want
> if not have_library then
>     print("Library was not found. Error:", library)
> end
>
> -- ... --
>
> if have_library then
>     -- Use the library
>     library.foo("bar")
> end
>
> ----------------------
>
> You said pcall didn't work. Easy mistake to make is:
> pcall(require("mylibrary")). Which is wrong, after you think about it
> more :)
>
> Regards,
> Matthew
>