Command Line arguments in Lua

LuaServer Side ProgrammingProgramming

Handling command line arguments in Lua is one of the key features of any programming language. In Lua, the command line arguments are stored in a table named args and we can use the indices to extract any particular command line argument we require.

Syntax

lua [options] [script [args]]

The options are −

  • -e stat− executes string stat;
  • -l mod− "requires" mod;
  • -i− enters interactive mode after running script;
  • -v− prints version information;
  • --− stops handling options;
  • -− executes stdin as a file and stops handling
  • options.

Example

Let’s consider an example where we will open a Lua shell in interactive mode and we will pass the script as dev/null and then we will pass our arguments.

lua -i -- /dev/null one two three

It should be noted that the above command will work only if Lua is installed on your local machine.

The above command opens the terminal in an interactive mode.

Output

Lua 5.1.5 Copyright (C) 1994-2012 Lua.org, PUC-Rio

Now we can access the arguments that we passed, as we know they are stored in a table named args.

Example

Consider the example shown below −

lua -i -- /dev/null one two three
Lua 5.1.5 Copyright (C) 1994-2012 Lua.org, PUC-Rio
>print(arg[1]) one
>print(arg[2]) two
>print(arg[3]0
stdin:1: ')' expected near '0'
>print(arg[3]) three
>print(arg[0])
/dev/null

Output

one
two
three
/dev/null
raja
Published on 20-Jul-2021 13:56:15
Advertisements