Lua Tutorial - All the Basics!
Why hello there, this is a Lua tutorial! For those of you that have, unfortunately, never even heard of Lua, it is a lightweight, high-level multi-paradigm programming language, that can also be used as a scripting language. And yes, nobody really uses Lua in replit, but it has been used in many well-known games. Lua is written in C and the version replit uses is 5.1.5, but there are newer versions around.
This tutorial is directed toward people that have learned one or more programming languages. Even with this recommendation, this tutorial is quite basic and probably has explained some topics in excessive detail that is not needed. With that said, it would be good for beginners. But, I would not recommend learning Lua as a first programming language. Go for a low-level language first. :)
Without further ado, let's get started!
First, create a Lua repl. For those who don't know how to create a new Lua repl, just click the
+ button on the top right corner and search "Lua". Select Lua and click the
Create repl button. Now we are done and let's get to the real code!
Most of the time, Lua does not use semicolons, unlike many other programming languages. It sometimes does use semicolons when writing 1-line statements, but we will not learn that in this tutorial.
Also, some handy tips and charts will be in the "Tips & References" section. You may be directed to visit that section in some parts of the tutorial. If you want to learn more elaborate things about a section, visit the "Tips & References" section; you might learn a bit more!
Also, just a fun fact -- "Lua" is the word for "moon" in Portuguese, hence the Lua logo.
Now it's time to write an actual statement. Why don't we start by learning the
Behold the amazing
You can also write a
(By the way, in replit, when you write codeblocks in Lua, there's no syntax highlighting, unfortunately. I think it's not "popular" enough to support syntax highlighting in codeblocks that are in Lua.)
NOTE: When writing a print statement in Lua, it doesn't matter whether you put no space between the
("Hello World!") part, or put 10 spaces between them. But it does matter if there's not on the same line, because then it will return an error.
You can use comments to explain what your code does, or save code for later. Lua supports single-line comments and multi-line comments. Now let's learn how to write a comment.
Single-line comments in Lua start out like this:
-- This is a comment!
When you run the code, the comments don't do anything.
Let's try this code:
-- print("Hello World!)
When you run the code, it doesn't output anything. Why? Everything after a
-- on a line is a comment. Let's say that we want to print
Hello World! on the console but you also want a comment saying what it does. Well, that's quite easy, here is how to do it:
print("Hello World!") -- This will print "Hello World!" onto the screen
Now let's learn how to write multi-line comments.
This is how to write a multi-line comment:
--[[ This is a multi-line comment ]]
Yes, I know, comments in Lua don't look a lot like most other programming languages. I, myself, believe that multi-line comments in Lua aren't really... uh... ergonomic? Probably not the best word to describe it, but we are learning about Lua, not my opinion, so let's learn more about Lua!
The way Lua declares variables are actually quite easy.
Here you go:
variable = 0
For people that know Python, you can see that Lua is a little similar to Python. You don't have to use
let or anything like JS, and you don't have to put semicolons either. You also don't have to declare what kind of variable it is, like C++. Easy, eh?
Let's try declaring even more variables:
number = 0 letter = "a" word = "hello" sentence = "This is a sentence" anotherNumber = 1.97
Yay, variables! But what if you want to print them onto the console?
Well, that's quite easy! Simply do this:
number = 0 print(number)
That prints out a 0 onto the console.
Why don't we print a string? Try this:
string = "Hello World!" print(string)
Now run the code and see what it does.
It prints out
Hello World! into the console (as you probably expected).
Yay, you now know about variables in Lua! Let's continue to learn more about strings.
You've already learned a bit about strings in the section above.
This is a string:
string = "This is a string"
However, there are other ways to declare a string.
The codeblock below will show you the three ways to declare a string.
string1 = "This is a string" string2 = 'This is a string' string3 = [["This is a string"]]
So you can see the ways you can declare a string:
- Using double quotes
- Using single quotes
- Using double quotes and brackets
Please check the "Tips & References" section to learn about escape characters. You'll probably need them sometime when coding in Lua.
Printing with Variables, Cookies, and More
Let's say that you want to
eat some cookies and exercise your newfound skills in Lua. But wait! Maybe when you're printing a statement, you want to use variables and print statements together.
I've already done that! See?
variable = "something" print(variable)
No, no, no, not like that. Sorry if I was unclear. I meant like this:
variable = "something" print(variable .. " is yummy.")
Why are there these
.. in between?
They act like something to "put" those together so they will print one statement, which is
something is yummy. Kind of like the
+ in Python. Or a
,. Let's try a few more examples.
variable = "something" food = "cookie" print(variable .. " is yummy.") print("i want to eat that " .. variable .. ". oh wait, it is a " .. food .. "!")
Magic! Right? It prints out
something is yummy., skips onto the next line, and prints
i want to eat that something. oh wait, it is a cookie!. Remember that
Now let's try one final thing. Here it is:
variable = 5.7 print(variable .. " is a number")
You can use the
.. to join numbers too!
You can also use
, to join variables and strings; I prefer
.., but it's your choice.
Practice - The Kookie Likes Cookies
Now let's practice your new skills in Lua with a challenge!
Make a program that prints your name onto the screen and your favorite food in Lua. The name and food you like must be variables.
An example output would look like this:
My name is Kookiez. My favorite food is cookies!
Oh yes, and the grand prize for the person that first completes the challenge correctly will be...
a "good job!" comment!
Yes, I believe everyone will be wanting this prize!
To "submit" your code, link your code in the comments and write in in this format:
This is for the practice: https://replit/@Kookiez/practice-repl
NOTE: The code cannot be a private repl because then I can't see it. The "competition" is purely for fun and practice.
Who Likes Cookies and Inputs?
Now you know about print statements, comments, variables, and printing them onto the console. Now let's learn about inputs.
io.write("Hello, please enter something. ")
Oh wait, you can't enter anything! That's because inputs in Lua have 2 parts. Try this:
io.write("Hello, please enter something. ") something = io.read()
Now you can enter a response! But wait, what if you want to print out the response onto the console? How would you do that? Well first, let's explain.
So you see the part that is
something = io.read? It's like making a variable, isn't it? So let's treat it like a variable. If you know about variables in Lua, it's pretty self-explainable now:
io.write("Hello, please enter something. ") something = io.read() print(something)
It works! :D
Let's try playing around with variables. How about this:
io.write("What's your favorite food? ") food = io.read() print("Oh, so you like " .. food .. ".")
Let's say I enter "cookies" as the input. Well,
io.write("What's your favorite food?") asks you for an input. The part
food = io.read "reads" the input, which is "cookies" and stores the response as
food. Then, the part that is
print("Oh, so you like " .. food .. ".") will print out
Oh, so you like cookies. to the console.
Good explanation? Hopefully. We'll learn about if and if else statements in the next section.
(Also, the difference between
print() is that
print() adds a new line whereas
io.write() does not. Kind of like
System.out.print() in java)
Kookie > Cookie
Well, we've come so far, right?! We've covered print statements, comments, variables, and inputs. Now we'll learn about if statements, and then continue on to learn if else statements. Oh, wait. Before we do anything else, we have to learn about operators.
I should've told you about operators a LONG time ago. Nevermind, this is the perfect time to teach about operators!
Now let's reveal the question that we've all been waiting for...
...WHAT ARE OPERATORS???
If you passed 3rd grade, I'm pretty sure you should know what operators are.
I'm assuming that the people reading this tutorial have learned about operators, but we'll do a quick review about them.
Operators are the
But, right now we're learning about relational operators.
Now, what are relational operators?
They are the operators such as
The ones I just listed above are probably the most common operators that you will see in Lua.
Here is also a handy table that I created:
|Greater Than or Equal To||>=|
|Less Than or Equal To||<=|
Hopefully you have understood operators and what they are now. If you haven't please comment and I will help you as soon as I can. We'll learn about
if statements in the next section.
If Kookie > Cookie Then...
We'll learn about if statements in this section.
Why learn if statements? Because you should... eat cookies instead of kookiez? Yes, but it can be used many different things other than trying to convince people that kookiez are superior to cookies. Oh, and @xxpertHacker, they can also be used to convince people that birds are better than spiders, obviously.
Let's assign a value of 5 to a variable called
number. Then, I will demonstrate what an if statement looks like. Ready? Here we go:
number = 5 if number == 5 then print("The number is 5.") end
You have written an if statement! :D
Now let's break down what does what.
We'll just look at the if statement for now:
if number == 5 then print("The number is 5.") end
if statement starts by stating the condition:
if number == 5. This, translated to English, is basically "if the value of the variable
number is equal to 5"... and is continued onto the next lines.
then means, well, "then".
And then the the next line is
print("The number is 5."). That, translated into English, is "output "The number is 5." into the console".
The last line has one word:
end tells the program "why hello there, the
if statement is done".
Now let's string together all the peices of text and see what it looks like translated to English!
If the value of the variable
number is equal to 5, then output 5 onto the console. Now this
if statement is done, bye.
Yay, now we
hopefully understand if statements! We'll learn about
if else statements in the next section, which will build on what we have already learned.
Now let's learn about if else and if then else statements in this section.
If else statements in Lua look like this:
if number == 5 then print("The number is 5.") else print("The number is not 5.") end
For it to excute properly, of course, we need a variable named
Let's add it to the chunk of code.
number = 4 if number == 5 then print("The number is 5.") else print("The number is not 5.") end
Let's run the code and see what happens. It outputs
The number is not 5. into the console.
We can try using inputs with
if else statements!
io.write("What's your name? ") name = io.read() if name == "Kookiez" then print("Hi there, Kookiez!") else print("I don't think I know you...") end
Let's explain what this code does.
io.write("What's your name? ") "asks" for your name.
name = io.read() is basically assigning a name for the response, so it's like a variable. So if I enter Kookiez, the name's value is "Kookiez".
The next line is assigning a condition. If the value of
name is "Kookiez, then it will print "Hi there, Kookiez!" to the console. There's another condition: the
else. It means, "if the value of
name isn't Kookiez, then do this." Well, what is the this? The "this" we are talking about is to output "I don't think I know you..." into the console.
end ends the if statement, so it can know that the if statement is done.
Now we understand what
if else statements are. Now there's also something that builds on if else statements.
Now we can learn about
if then else statements.
Here's an amazing example:
a = 1 b = 3 if a > b then print("The value of a is greater than b.") elseif a == b then print("The value of a is equal to b.") else print("The value of a is less than b.") end
We now have a fully functioning piece of code! Run it and see what happens:
The value of a is less than b.
If we change the value of a to 5, then it will output this:
The value of a is greater than b.
If we change the value of a to equal the value of b, which is 3, you know what it will output.
For those who don't know, here you go:
The value of a is equal to b.
Let's take a closer look at the
if then else statement.
if a > b then print("The value of a is greater than b.") elseif a == b then print("The value of a is equal to b.") else print("The value of a is less than b.") end
It's basically an
if else statement, just with an
elseif basically means that if the condition above isn't true, then try my condition.
You can have multiple
elseifs. You can also leave out the
else below and it will still work. Try this:
a = 1 b = 3 if a > b then print("The value of a is greater than b.") elseif a == b then print("The value of a is equal to b.") end
See what happens when you run the code. It doesn't output anything at all, since you didn't tell it to.
Let's try another example:
io.write("What is your favorite food?") food = io.read() if food == "cookies" then print("Cookies are yummy.") elseif food == "pizza" then print("I like pizza, too!") elseif food == "strawberries" then print("Some strawberries are #FF0000.") else print("That's interesting.") end
Here's an explanation, as always.
It asks you "What is your favorite food?". It reads your response and stores it as
Then, if the response is "cookies", it will print "Cookies are yummy." into the console.
If the response isn't "cookies", move onto the next step.
Well, the next step checks if the response is "pizza". If so, it prints "I like pizza, too!" to the console.
If the input is not "pizza", it moves onto the next step.
It then checks whether the response is "strawberries". If that is true, then it outputs "Some strawberries are #FF0000." onto the console.
Then, if that is not true, it moves onto the
All other responses will say, "That's interesting.".
Then the program will end, of course, hence the
We will have a "coding challenge" in the next section.
Practice - I WANTS CHEEZBURGER
In this challenge, you will receive an input, process it, and output something.
Let's outline what your program should do.
You are a fast food takeout worker. A cat goes by and wants to buy something. The choices are:
This cat is talented and can speak in the hooman English language too.
So, the steps are here:
- You ask the cat, "What do you want? You can have a choice of pizza, cheeseburger, or a keyboard."
- The cat says something, which (hint hint hint) has something to do with
- You process what the cat says, and says a thing for each response (such as "I like to eat keyboards too.").
- If the cat does not say "pizza", "cheeseburger", or "keyboard", you then say another response.
If you finish this correctly, you will get...
*100% guaranteed. May arrive in your mailbox in a moldy and/or poor condition or in a repl. Nonreturnable.
Ah yes, just comment and link a repl!
We're learning about loops in this section.
Here are those loops we will be covering:
- While Loops
- For Loops
- Repeat... Until Loops
- Nested Loops
Loops can also repeat an infinite number of times if the condition is always true.
Here's an example, press the stop button after a few seconds, please :)
while(true) do print("Lua") end
This will print
Lua to the console an infinite number of times.
You've just gotten a taste of
Well coincidentally, you're learning about
while loops in the next section.
While loops pretty much follow this format:
while(condition) do <insert code here> end
That's pretty much it. ;)
So it is basically like this:
<insert code here> and if it is now false, end the while loop.
Easy, right? :D
while loop might not excute at all, if the conditions are not met. If it isn't true, it will excute the next line of working code after the while loop.
There is also another format, credit to @EpicGamer007 for pointing this out.
Let's try an example. ```lua number = 0 while(number < 5) do print("The value of the variable number is: " .. number) number = number + 1 end
The loop excutes its code 5 times. Why?
Because the value of
number is 0. The value of 0, of course, is less than 5.
While the number is less than 5, it repeats this:
print("The value of the variable number is: " .. number) number = number + 1
So, the code above prints "The value of the variable number is: " and the value of
After that, the value of
number increases by 1.
This can only repeat 5 times. Why?
Because you can see what numbers the program outputted, which are
When adding the value of number by 1, and repeating, and so that they cannot equal 5 or be greater than 5, those are the only numbers that can be outputted.
Hopefully that clears it up :D
We'll be learning about
for loops in the next section.
For loops in Lua, in my opinion, are harder than while loops.
First, we'll see what the definition of a
for loop in Lua is.
Here is an explanation from TutorialsPoint:
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.
The syntax of a for loop in Lua programming language is as follows −
for init,max/min value, increment do statement(s) end
Now let's break down the parts of a for loop.
- The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables.
- Next, the max/min. This is the maximum or minimum value till which the loop continues to execute. It creates a condition check internally to compare between the initial value and maximum/minimum value.
- After the body of the for loop executes, the flow of the control jumps back up to the increment/decrement statement. This statement allows you to update any loop control variables.
- The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the for loop terminates.
I think the explantions above will give you an idea of what
for loops do!
Let's see an example of a for loop.
for i = 20, 0, -2 do print(i) end
The example above is a for loop.
Let's explain what this for loop does.
First, you see
for i = 20, 0, -2.
So, the first part,
20,, is the maximum value of
Then, after the
20, there is a
0. That means the minimum value of
i is 0.
So now we can see that
20, 0, means that the maximum value of
i is 20, and the minimum is 0.
Now there's the
-2. The -2 is subtracting 2 from
And then, there is a
do, well, tells the program what to do.
What to do is to output the value of
i on the console.
So, it would start as
20, then it would be
10... and so on, until it reaches
After that, there is the
end. The loop ends when it reaches the minimum value.
Hopefully, we now know a bit about for loops!
Repeat... Until Loops
In this section we will be learning about repeat... until loops.
The syntax of a repeat... until loop is like this:
repeat <insert code here> until(condition)
Unlike the first two loops we talked about, this one doesn't have an
Also, the loop checks the condition at the bottom, not the top.
So, that means the loop can excute at least one time.
The loop basically repeats the code where the
<insert code here> until the condition at the bottom is true. Then, it will stop.
So let's have an example here.
variable = 5 -- This defines a variable repeat print("The variable is " .. variable) variable = variable - 1 until(variable < 0)
We now have written a repeat... until loop!
Let's break down what this program does.
The value of
variable is 5.
So, first it'll print "The variable is " plus the value of the variable.
Then, the variable's value is decreased by 1.
If the variable is less than 0, stop the loop. If not, repeat this process again.
This is basically the whole breakdown of a repeat... until loop!
So now that we've learned about repeat... until loops, let's learn about nested loops.
This section will give you a quick overview about nested loops.
Nested loops aren't really one single type of loop, it basically allows you to have a loop nested in another loop. As in, having a loop inside a loop.
Here is the syntax for a nested
for init, max/min value, increment do for init, max/min value, increment do <insert code here> end <insert code here> end
See that the second for loop is nested in the other for loop?
Confused? Here's an explanation:
So after the
do, (second line), it says to, well, do something. And that something is the other for loop! If you want to, the second
<insert code here> can do something, and that something is based on the conditions of the first for loop.
If it's still confusing, ping me and I will elaborate more on it. Or you could do it yourself and then understand it (that method works best for me). "Doing it yourself" means to fill in the blanks. So I could do this:
for i = 1, 5, 2 do for j = 10, 3, -3 do print("Hello World!") end print(i) end
The loop above is actually really basic -- you could add variables, use operators, etc., to make it more interesting.
And actually writing the code, rather than just reading it, makes it easier to learn. For me, that is, but I bet a bunch of other people learn better like that as well.
Remember to name the variable for the inner loop different from the name for your outer loop.
Now let's move on to learning about nested while loops.
This is the basic syntax for a nested while loop:
while(condition) do while(condition) do <insert code here> end <insert code here> end
Last but not least, this is the syntax for a nested repeat loop:
repeat <insert code here> repeat <insert code here> until(condition) until(condition)
Ta-da! Now you are done with nested loops.
In this tutorial, we will not go very deep into functions. However, we will still learn about it.
An example of a function is here:
function wait(time) os.execute("sleep " .. tonumber(time)) end
This code is made to wait for a given amount of time.
If you want to change around the code, please note that the "sleep " there in the second line should not be changed. It's something specific, not like putting in any random thing in a print statement's paretheses and it still works.
But, when you run the code, nothing happens!
Let's add this to the next line. (After the
end, of course!)
wait(5) print("Hello World!")
Now it works. Why? Because the function is defining what the function is supposed to do. When you call the function by having the
wait(5), it does what it's supposed to do -- wait 5 seconds. You can also change around the time, just make sure it's not too high. :)
For those Roblox users, you may be confused and say that
wait is already given for us! But when you run the code, it gives an error. Why?
It's because Roblox already has that implemented. Roblox Lua, not Lua 5.1.5. So some things will be different, but most will stay the same.
We are almost at the end of the tutorial, but first we have our Tips & References page...
Tips & References
Here is a nice list of escape characters that you can use:
- \t Inserts a tab in the text at this point.
- \b Inserts a backspace in the text at this point.
- \n Inserts a newline in the text at this point.
- \r Inserts a carriage return in the text at this point.
- \f Inserts a form feed in the text at this point.
- \' Inserts a single quote character in the text at this point.
- \" Inserts a double quote character in the text at this point.
- \ Inserts a backslash character in the text at this point.
For example, here is a print statement using an escape character:
Some other helpful tips include turning a string into an integer/number.
You can use
tonumber to do this.
n = tonumber(n)
But of course, you first need to have a variable called
If the variable's value is "51", it will become 51. If the variable is "hello" or something like that, it will be
nil because it's not a number.
You can also reverse this so a number can turn into a string!
s = tostring(s)
But, like I said before, you must have a variable named
s first before you begin.
We have made it this far with this tutorial!
This tutorial is the result of about 2 months of work.
Also, thanks to @EpicGamer007 for helping to proofread the tutorial.
A good website to learn Lua is TutorialsPoint, but one drawback to it is that it has ads. However, it also covers advanced topics, so that's nice. ;)
You can also go to the official Lua website here.
Good luck with your coding!
If this (reposted) tutorial taught me anything, it's that this code prints
print(spider > bird)
@xxpertHacker perhaps you did not understand what I meant. Simply counting the number of letters in a word is not a sufficient way to determine whether spider or birds are better. declaring variables is a more acceptable solution. as in my previous comment, i rated spiders and birds on their logic, interest level,
cuteness factor, as turkey vultures are one of my favorites etc.
FINALLY an actual programming language tutorial that isn't on Python or related things.
I had no idea what I was doing, Lua is one of my first programming languages, aside from Python, and I forgot an "end" at the end. But it worked out in the end. Let me know what you think about it :D
"lightweight, high-level multi-paradigm programming language, that can also be used as a scripting language. "
could someone tell me what this means
@amaddentcsec lightweight means that it has a small memory footprint, easy to implement, and a minimalist design, etc. high level languages are ones like python and stuff like that, they're closer to human languages. multi-paradigm is that it is suited for more than one pardigram, such as OOP. scrpting language is how it's used in roblox
Thanks for the tutorial! I'm just a beginner and came across this detailed tutorial with explanations. I can agree the fact that this is so similar to Python and I'm quite good at python, probably meaning that I will learn LUA in not time! Once again, thanks for the tutorial! Appreciate it!
if you passed 3rd grade, I'm pretty sure you should know what operators are.
Bold of you to assume I know what 3rd grade is, or that I have passed it.
Fun Fact: All Roblox Games are coded in an edited version of Lua, known as Luau. I can code in Luau, sadly not Lua.
This is an awesome tutorial! Have you noticed that Lua compiles sooooo fast on repl (like as fast as html)?
Anyways, here's the link to my pizza cheeseburger of keyboard thing: https://replit.com/@codingjlu/WavyIrresponsibleStartups?v=1