6 – Lua Stand-alone

    The options are:

    • - executes stdin as a file;
    • -e stat executes string stat;
    • -i enters interactive mode after running script;
    • -v prints version information;

    After handling its options, lua runs the given script, passing to it the given args. When called without arguments, lua behaves as when stdin is a terminal, and as lua - otherwise.

    Before running any argument, the interpreter checks for an environment variable LUA_INIT. If its format is @filename, then lua executes the file. Otherwise, lua executes the string itself.

    All options are handled in order, except -i. For instance, an invocation like

    1. $ lua -e'a=1' -e 'print(a)' script.lua

    Before starting to run the script, lua collects all arguments in the command line in a global table called . The script name is stored in index 0, the first argument after the script name goes to index 1, and so on. The field n gets the number of arguments after the script name. Any arguments before the script name (that is, the interpreter name plus the options) go to negative indices. For instance, in the call

    the interpreter first runs the file a.lua, then creates a table

    1. arg = { [-2] = "lua", [-1] = "-la.lua", [0] = "b.lua",

    and finally runs the file b.lua.

    In interactive mode, if you write an incomplete statement, the interpreter waits for its completion.

    (the outer pair of quotes is for the shell, the inner is for Lua), or in any Lua programs by assigning to _PROMPT. Note the use of -i to enter interactive mode; otherwise, the program would end just after the assignment to _PROMPT.

    In Unix systems, Lua scripts can be made into executable programs by using chmod +x and the #! form, as in

    1. #!/usr/local/bin/lua

    (Of course, the location of the Lua interpreter may be different in your machine. If is in your PATH, then

    is a more portable solution.)