luapackage

How to gracefuly try to load packages in Lua?


I would like to try to load a package in Lua. The package is ansicolors and is only to have a better looking console output.

This is sugar and I don't want users to be forced to install this package.

So I tryed something like:

ansicolors = require 'ansicolors' or nil

But as I thought, it raise a module not found error and stops the execution.

So my question is: Is there a graceful solution to try to load packages and fallback on simpler solutions when it is not possible?


Solution

  • local status, module = pcall(require, 'ansicolors')
    ansicolors = status and module or nil