7

I am writing a script testmodule.lua and want to check that if this file is imported/required from another script or directly started by lua testmodule.lua.

If it is directly started by command line I can do some test or run a main function, otherwise just export some function and do nothing.

Python has a __name__ statement:

if __name__ == '__main__':
    main_entry()

Is there something similar in lua ??

It is useful to write a shell util in a single file, which can be run directly and imported by other lua scripts. But when some script import this file, I don't like main function to be called.

1

1 Answer 1

10

You can use the following check:

if pcall(debug.getlocal, 4, 1) then
  print("in package")
else
  print("in main script")
end

It checks if there is anything in the 1st variable at the 4th level, which would be the caller of the current module (if required) or nothing in the case of the main script.

Note that it doesn't distinguish between require, dofile, loadfile or other similar calls. You may want to check this recent thread on the Lua mail list that discusses checking for these calls and some alternative ways as well.

5
  • Thanks a lot, I would like to upvote this but I have not got enough reputation. Mar 20, 2018 at 5:46
  • You can always accept the answer if it worked for you. Mar 20, 2018 at 14:45
  • 1
    Is there a particular reason that you used pcall(debug.getlocal, 4, 1) rather than simply calling it as debug.getlocal(4, 1)? Aug 19, 2019 at 2:31
  • 1
    It's because you may get bad argument #1 to 'getlocal' (level out of range) when called from a script. You probably don't want to terminate the script on this check. Aug 19, 2019 at 3:21
  • seems check debug.getinfo(4) not nil can be tested without pcall
    – yurenchen
    Oct 18, 2022 at 19:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.