How to gracefuly try to load packages in Lua?

2020-02-01 19:12发布

问题:

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?

回答1:

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


标签: lua packages