“main” function in Lua?

前端 未结 8 892
醉酒成梦
醉酒成梦 2020-12-01 12:17

In python, one would usually define a main function, in order to allow the script to be used as module (if needed):

def main():
    print(\"Hello world\")
           


        
8条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-01 12:56

    When Lua requires a module, it passes it the name it's been required with as varargs (...).

    So, if your script doesn't intend to take any arguments (from the command line or otherwise), you can use something like

    if ... then
      return this_mod --module case
    else
      main() --main case
    end
    

    Note, however, that this isn't foolproof in the (entirely) possible case that you take arguments. However, at this point, you can combine this with Lukasz's answer to get:

    if not package.loaded[...] then
      --main case
    else --module case
    end
    

    Still not perfect (for instance, if the script is called with a first argument of string or the name of some other already-loaded module), but likely good enough. In other situations, I defer to MattJ's answer.

提交回复
热议问题