lua

How to determine whether my code is running in a lua module?


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.


Solution

  • 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.