“main” function in Lua?

前端 未结 8 755
醉酒成梦
醉酒成梦 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 13:03

    I am going to suggest yet another variation, that seems to work on lua5.1 as well as lua5.2:

    function is_main(offset)
        return debug.getinfo(4 + (offset or 0)) == nil
    end
    
    if is_main() then
        print("Main chunk!")
    else
        print("Library chunk!")
    end
    

    If you do not feel like defining an extra function is_main for this purpose, you can just do:

    if debug.getinfo(3) == nil then
        print("Main chunk!")
    else
        print("Library chunk!")
    end
    
    0 讨论(0)
  • 2020-12-01 13:04
    if arg ~= nil and arg[0] == string.sub(debug.getinfo(1,'S').source,2) then
      print "Main file"
    else
      print "Library"
    end
    

    An explanation:

    1. Lua calls a script from the interpreter with the arg table, with arg[0] being the name of the script.
    2. The debug.getinfo function returns a table of information describing the function at the level of the stack given by its numbered argument (1 refers to the function calling getinfo; 0 refers to getinfo itself). Its second parameter is optional: it specifies which subset of the getinfo fields to retrieve. The 'S' defines Source names.
    3. The source field of the table returned by getinfo for files contains the name of the file the function was defined in, prefixed with an @. By passing the value of that field to string.sub(...,2), we strip that @. (The short_src field contains the name without the @, but that's because it's defined as a "print-friendly" name, and is less safe than stripping source.)

    Note that this code uses a debug function, so in 5.2 you'll have to require debug to be able to use it.

    0 讨论(0)
提交回复
热议问题