Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua, Altered Program Flow When Rquired File isn't there

Tags:

module

lua

I want to test to see if a require'd file is there or not.

At the present, when I execute this command in Lua:

require "File_That_May_or_May_Not_Be_There.inc"

All is well if he's there. If not, my script is dead on the spot.

Is there a way for me to recover from this ?

I looked HERE on the Lua.Org site and HERE on StackOverflow and haven't seen this answered.

Is there a way to do something like this ?...

if (this_exists("That_File")) then
    require "That_File"
else
    print "Your file does not exist"
end

I'm trying to let the user have a little better idea of what went wrong, and why.

like image 430
User.1 Avatar asked Dec 11 '25 15:12

User.1


2 Answers

Use pcall.

local ok, mod = pcall(require, "That_File")
like image 152
Etan Reisner Avatar answered Dec 14 '25 13:12

Etan Reisner


If you don't need to use require, which looks for modules in several locations, you can use

local f,e=loadfile(filename)
if f==nil then
  print(e)
else
  f()
end
like image 43
lhf Avatar answered Dec 14 '25 14:12

lhf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!