Tutorial Examples

lua-users home
wiki

Lua command line

If we run the Lua executable without parameters we get the following message and a > command prompt.

Lua 5.1.4  Copyright (C) 1994-2008 Lua.org, PUC-Rio
>

All of the examples in the tutorial are typed at the command prompt > and the output copied and pasted into the wiki.

> print("hello Lua user")
hello Lua user
> print(10*10)
100

If a line begins with an = Lua evaluates the line as an expression. It's shorthand for having to use the print() function. Note that this is just a feature of the interactive prompt, starting a statement with = in an actual Lua script file will be a syntax error.

> = "hello Lua user"
hello Lua user
> = 10*10
100

Multiline entry

We can enter commands over multiple lines if necessary. Lua will try and evaluate what you typed on a given line and assess whether the command is complete. If it is not considered complete a double command prompt appears >> so you can continue typing. E.g.,

> print(
>>  "Hello lua user"
>> )
Hello lua user
In the above example the print( statement is incomplete as the matching closing bracket is missing. The Lua command line assumes that you have more to type so the >> prompt is displayed. This continues until the statement is deemed complete. If you made a mistake you will get an error. This also works for the evaluation shorthand:
> = 10 *
>> 10 +
>> 5
105

Running a lua script file

If you have a long program with a lot of code you don't have to type in all your lines every time again at the Lua command prompt. Then simply save your lua script file in an editor and start lua with the name of the program file (instead of starting lua without parameters). For example: If you want to start my-lua-script.lua, you have to type "lua my-lua-script.lua" (without quotation marks) in your Shell; not in the Lua command prompt. This possibility is not necessary for this tutorial but will be useful if you want to write own programs.

Comments

Where you see "--", followed by text, this is a comment. Everything after the -- is ignored by the Lua compiler on that line.

> = 1+1  -- this is ignored.
2
> = 1+1     no comment
stdin:1: <eof> expected near `no'

Note: It is good behaviour to have but you do not have to type the comments in! They are just comments about what is happening for clarity especially for other maintainers to understand(if there are).

Scope

(If you don't yet understand variable scoping or the local keyword, you can skip this part and keep following the tutorial)

In the interactive interpreter, each command line has its own scope, so local variables won't work like you might expect:

> local x = 5
> = x
nil

So you will need to use globals in the interactive interpreter to keep values that you will want to use in other lines.


RecentChanges · preferences
edit · history
Last edited August 9, 2013 10:13 am GMT (diff)