
hello
your first program
> examples hello > edit hello
The very first program: it asks for your name, says hello, counts down from 3 and invites you to edit it. It shows the three functions every program uses sooner or later: print to show a line, read to get what the player types, and sleep to wait.
What to build
Nothing: hello only uses the screen and the keyboard, on any computer. The first program tutorial walks through it step by step.
> examples hello > hello What is your name? Steve Hello, Steve! 3... 2... 1... Edit me: edit hello
How it works
write("What is your name? ")
local name = read()write shows text without going to the next line, so the cursor waits right after the question. read() then pauses the program until the player presses Enter, and gives back the line typed, as a string. While it waits, the computer spends no instructions. The answer goes into a local variable called name.
print("Hello, " .. name .. "!").. glues strings together. print writes the result and goes to the next line.
for i = 3, 1, -1 do
print(i .. "...")
sleep(1)
endA for loop with a third number: i starts at 3, goes down by 1 (the -1), and stops after 1. sleep(1) waits one second each time round.
Ideas
Count from 10 instead of 3, or count by twos. The third number of the
foris the step:Brass for i = 10, 0, -2 do write(i .. " ") end print("liftoff!")10 8 6 4 2 0 liftoff!
- Handle an empty answer: after
read(), addif name == "" then name = "stranger" end. - Ask a second question (
What do you build?) and use both answers in the greeting. - Greet by the time of day:
os.day_time()gives the time of the world, see the clock example. - Make it a door greeter: put it in
startupwith awhile true do ... endaround it, on a computer by your front door.
The program
-- Your first program. Run it by typing its name: hello
-- print() writes a line, read() waits for what you type.
write("What is your name? ")
local name = read()
print("Hello, " .. name .. "!")
for i = 3, 1, -1 do
print(i .. "...")
sleep(1) -- waits one second
end
print("Edit me: edit hello")