Variables are holders or buckets for values with a name. For example:
i = 3
In this, i is the name of the variable, and the value three is being placed in
the variable. Later if we say
i = 5 i will still be the same variable, but
it will contain a different value.
Variables can be different kinds of values called types. Lua has these types:
For our first few lessons we will be working mostly with numbers and strings. We will not get into threads or userdata for a while, and not into tables or writing our own functions just yet.
It is a tradition for the first program in a new computer language to print the message "Hello, World!".
-- Lines which start with -- are comments, they have no effect on the -- program's execution -- These are all ways to print the same message in Lua -- print is a function which takes one or more arguments or parameters print("Hello, World") -- Things inside quotations in Lua are string literals, just like 4.3 is a number literal. print("Hello,", "World") -- The .. operator concatenates (joins in order) two strings. print("Hello," .. "World")
Create a text file, and try one of these ways to print the message. Name it something like hello.lua.
If your program is named hello.lua, you can execute it like this:
You can also just run the command lua to enter the Lua interpreter in immediate mode to enter commands that execute as you type them.
Loops are how you repeat something in a program. For example, to do something 10 times you could write a for loop like this.
-- i is a new variable -- i has a different value each time thru the loop, from 1 to 10 for i = 1, 10 do -- whatever you want to do 10 times goes here. end -- you could create a similar loop using a while statement instead i = 1 while i <= 10 do -- whatever you want to do 10 times i = i + 1 do
Now try printing out the numbers 1 thru 10 using a loop.
If statements allow you to test a condition, something which may be true or false, then execute certain parts of your code contained inside the if statement, only when the condition is true.
if age < 18 then print("child") end
This will only print "child" if the variable age contains a number less than 18.
If statements can also have an else clause which will be executed whenever the if statement was false.
if age < 18 then print("child") else print("adult") end
If statements can also include elseif clauses, which are checked against a condition only if the primary if statement and any preceding if statements were false. You can have as many elseif clauses as you like.
if age < 1 then print("infant") elseif age < 3 then print("toddler") elseif age < 13 then print("child") elseif age < 18 then print("teenager") else print("adult") end
The statements inside the if/elseif/or else clause can contain other control flow statements, such as entirely separate if block or a loop.