Command Line Arguments in Lua

Command-line arguments are a common way to parameterize execution of programs. For example, lua script.lua uses script.lua as an argument to the lua program.

-- In Lua, we don't need to import packages for basic functionality

-- The main logic of our program
local function main()
    -- In Lua, command-line arguments are accessed through the 'arg' table
    -- The program name is typically arg[0], so we start from index 1
    local argsWithProg = arg
    local argsWithoutProg = {}
    for i = 1, #arg do
        argsWithoutProg[i] = arg[i]
    end

    -- You can get individual args with normal indexing
    local arg3 = arg[3]

    -- Print the arguments
    print(table.concat(argsWithProg, " "))
    print(table.concat(argsWithoutProg, " "))
    print(arg3)
end

-- Call the main function
main()

To experiment with command-line arguments, save this script to a file (e.g., command_line_arguments.lua) and run it with Lua:

$ lua command_line_arguments.lua a b c d
lua command_line_arguments.lua a b c d
a b c d
c

In Lua, command-line arguments are automatically available in the arg table. The program name is typically stored in arg[0], and the actual arguments start from arg[1]. Unlike Go, we don’t need to import any special packages to access command-line arguments.

Next, we’ll look at more advanced command-line processing techniques in Lua.