User:JulienDethurens/Guide/Chapter 1

Note: considering we are not yet in the ROBLOX-specific section, you can use the Lua demo, on the official Lua website. You can use it to run code. However, note that it uses Lua 5.2 and that ROBLOX uses Lua 5.1. Therefore, some of the things I will teach you will not work with it. Don't worry, though, almost everything still works in Lua 5.2. And I'll try to tell you whenever something I am talking about is no longer available in Lua 5.2.

You can also run code using codepad, an useful tool that allows you to run code in Lua and in other languages. It uses Lua 5.1 too, so you shouldn't have any compatibility problem.

I suggest using the Lua demo or codepad to test code, as it avoids you the trouble of starting the studio and everything. But you can also use the studio if you want.

Syntax

First of all, what is syntax? What does that word mean? Well, syntax is actually like grammar, but for a programming language. It explains how you must structure your scripts.

ROBLOX Lua uses exactly the same syntax as Lua. Some functions were edited, added or removed, but the syntax is exactly the same. You can find the syntax of Lua in extended BNF here, but I promise you won't understand anything if you read it.

Don't worry, though, you're not going to have to understand any of that. It's extended BNF, which doesn't really have anything to do with what you'll need to learn.

Names

Names, in Lua, are also called identifiers. They can be any text composed of letters, digits, and underscores and not beginning with a digit. They are used to name variables and table fields (you'll know what both of these are later).

Here are some valid names:

name
hello
_
_tomatoes
me41
_thisIs_StillaValid23name

Here are some invalid names:

2hello
th$i
hel!o
563text
82_something

Also, the following keywords are reserved by Lua and can not be used as names (oh, and you'll notice that they're all colored in yellow, they will be colored the exact same way in all of this guide):

and       break     do        else      elseif
end       false     for       function  if
in        local     nil       not       or
repeat    return    then      true      until     while

When naming a variable or a table field, you must choose a valid name for it. It must therefore start with a letter or an underscore and only contain letters, underscores and digits.

You don't know yet what a variable and a table field are, but don't worry, I'll explain that soon. However, first, I'll talk about comments, then, about the different types of data.

Note: Lua is case sensitive. This means that 'Hello' and 'hello' are two different names.

Comments

I'm talking about these right now because I'll use them soon, so I want you to know what they are.

A comment is simply text that is ignored by Lua. You can use comments to describe one or many lines of code, or for any reason you want to.

A comment starts with a double hyphen, like this:

-- This is a comment!

Usually, I tend to put a space between the hyphen and the text, but it's just a preference. You can do this too:

--This is a comment!

And you can put the comment on the end of a line of code too:

print 'Hello world!' -- This is a comment that was put after a line of code!

These are short comments. They only continue until the next line. However, sometimes, you might want to make a comment that continues on many lines. You can do this with a long comment.

A long comment starts with a long bracket. Here is an example:

--[[ This is a comment
This is still in the comment
This is in the comment too!
]]

Sometimes, you might want to use comments to disable code temporarily (because, remember, Lua ignores everything that is a comment and doesn't run them). In a such case, it is possible that you run in the following problem:

--[[
variable = [[this is a string, and the other thing is a variable, but you don't need to know about that yet]]
]]

Don't worry about the code, it is just an example. The point is that double brackets can also be used for other things than long comments, which will make the comment stop. But there is a simple solution:

--[===[ This is another long comment and you can still put text on any line. ]===] </syntaxhighlight>

As you can see, the comment is not colored here. That's because I disabled the syntax highlighting on this one, because the syntax highlighting doesn't understand this type of long comment. Trust me, though, they work.

Just as a note, you can put any number of equal signs between the two opening and closing brackets. Just make sure both the opening and the closing brackets have the same number of equal signs. The number of equal signs between the two brackets is called the level of the long bracket.

I will use comments a lot in this guide, so don't be surprised if you see one.

Variables

I've talked about variables not long ago. But, what are variables? Well, variables are used to store data. Each variable has its own name. Since Lua is a dynamically typed (which means that values have a type, but that variables don't), you can store any value in a variable, even if its type doesn't correspond with the previous value.

To store a value in a variable, you use the '=' sign. Here is an example:

variable = 5

This will set the value of variable to 5.

Variables can store all kinds of data, but I'll describe data types in the next section.

You can also make a variable local by adding the keyword 'local' in front of it, like this:

local variable = 5

This will set the value of variable to 5 and make it a local variable.

In fact, you should always use local variables. There is a small difference between local variables and normal variables (normal variables being variables that are not local), but I will explain this later, when you will have learned about statements, since you will need to know them to understand what is the difference. For now, just remember that you should always put the local keyword in front of all your variables.

Terminology

Note: this section is extremly important to understand anything in this whole book. If there is a section you don't want to skip, it is this one. Read it and make sure you understand everything in it.

Each piece of code that Lua executes is a chunk. A chunk is a sequence of statements.

A statement is something you execute, something you run. Something that, when ran, does something. For example, setting a variable:

local var = 9

Statements can optionally be followed by semicolons, like this, though there is no real reason to ever put one:

local var = 10;

Expressions are things you evaluate. Evaluating an expression means getting its value. Here is an example:

8 + 4

(yes, you can do math in Lua. I'll explain this later)

The code above is an expression. When evaluated, it will give you 12.

Statements will usually use expressions when executed.

To summarize:

  • Expressions are what you evaluate, what you get the value of.
  • Statements are what you execute or run, things that perform actions.
  • Chunks are sequences of statements.

A chunk may be composed of a single statement, or of a mix of multiple statements. There is no limit to how big chunks can be.

I've just described three words to you. Three. Actually, let's call them concepts, not words. So three concepts. Well, these concepts are extremly important to understand.

Types

You must know that there are simple data types, and more complex data types. Here, I am only going to talk about data types you can find in Lua, simple Lua. I'll talk again about data types later, in the ROBLOX API section, to explain the ROBLOX-specific data types.

As a note, you can get the type of a value with the type function. It works like the print function; you can get the type of a value like this:

print(type("test"))

In this case, the output would be string, because "test" is a string. Of course, you can put a variable instead of a value in the parenthesis, like this:

local var = 3053
print(type(var))

This would print 3053.

I encourage you to play a little with it. Actually, I encourage you to play with everything you'll see in this book. If you want to learn to script, reading won't do it all; you'll also need to understand, and playing with what you learn can help you a lot to learn. Try examples I give you in the Lua demo or in codepad (I mentioned them at the beginning of this chapter) and edit them. This will help you a lot to understand.

Numbers

You probably already know what a number is. A number is a value composed of digits that represents a quantity. That's true in Lua too. And I won't have much to explain, as they work the same way as the numbers you already know.

In Lua, you can create numbers the same way as the way you learnt in school. In fact, you can use decimal points, decimal exponents and you can even write your numbers in hexadecimal, if you prefix them with 0x (hexadecimal is the base 16, it is a different way to express numbers. If you don't know about it, don't worry, you don't need to know about it to learn Lua).

Here are some valid numbers:

3 3.0 3.1416 314.16e-2 0.31416E1 0xff 0x56 </syntaxhighlight>

You might not know what some of these are, but that doesn't matter.

Integers

Integers are not a type you will really have to worry about in Lua, but it's still good to know about it.

Integers are exactly like the integers you've learnt about at school (if you have. If not, I'll explain anyways). They are exactly like numbers, except they can't be decimal. In fact, you can't encounter integers in pure Lua, but you can in ROBLOX, because of IntValues. I don't know if you've already seen someone, at a tycoon for example, have so much money that it turned negative. The reason that happens is because integers are limited to 2^31-1, which is equal to 2,147,483,647. If a player's score is higher than that, it will turn negative, as the values on the leaderboard are IntValues. Usually, you won't run in problems because of this, because Lua doesn't use integers, but if you have to use IntValues, just try to stay under 2,147,483,647. However, it shouldn't be a problem if your game is well-thought, because if a player gets 2 billion points, your game probably gives too much points for certain things…

Booleans

Booleans are easy to understand. Their value is either true or false. That's it. Nothing else. Either true or false, either yes or no, either 1 or 0. These all mean the same thing. However, you usually call these two values true and false, not yes or no, nor 1 or 0.

You can create a boolean like this:

local boolean = true

This will put the value true in the variable boolean.

Conditions, which are not a type, but just a term, are very similar to booleans, but they have a difference:

When using conditions, everything except false and nil is considered as true and both false and nil are considered as false.

Conditions are used in many cases, which will be described later, when we will talk about statements.

Strings

Strings are simple to understand, they are text. Yes, text. A string can contain any form of text.

Strings can be delimited by single or double quotes ('' and "", respectively). They can contain the following escape characters (and some others that I won't bother mentionning):

Escape Characters
Character Description
\n A newline.
\" A double quote (")
\' A single quote (or apostrophe) (')
\\ A backslash (\)
\t An horizontal tab
\[number] [number] must be a number from 0 to 255. The result will be the ASCII character with the corresponding code.

You can use these in strings to reproduce characters that, if put in the string under their normal form, might cause a problem.

Here is an example of using the escaped characters:

"this is a string with \" quotes and \n a new line, as well as some backslashes \\"

Strings can also be defined using a long format enclosed by long brackets. We define an opening long bracket of level n as an opening square bracket followed by n equal signs followed by another opening square bracket. So, an opening long bracket of level 0 is written as [[, an opening long bracket of level 1 is written as [=[, and so on. A closing long bracket is defined similarly; for instance, a closing long bracket of level 4 is written as ]====]. A long string starts with an opening long bracket of any level and ends at the first closing long bracket of the same level. Strings in this bracketed form can run for several lines, do not interpret any escape sequences, and ignore long brackets of any other level. They can contain anything except a closing bracket of the proper level.

For convenience, when the opening long bracket is immediately followed by a newline, the newline is not included in the string.

Here is an example of a multiline string:

[[this is a multiline string! it can continue on many lines and it can contain quotes like this: " and any other character it can even contain something like this \n and it won't be converted to a new line it can even contain a comment like this: -- and that comment will still get inserted in the string it stops when it encounters closing double brackets like this: ]] </syntaxhighlight>

As you can see, there is no syntax highlighting here either. I disabled it, because, once more, the syntax highlighting doesn't recognize them.

Concatenation

To quote Wikipedia:

In computer programming, string concatenation is the operation of joining two character strings end-to-end. For example, the strings "snow" and "ball" may be concatenated to give "snowball".

The string concatenation operator in Lua is denoted by two dots (..). Here is an example of concatenation that concatenates "snow" and "ball" :

print("snow" .. "ball")
snowball

That code will concatenate "snow" and "ball" and will print the result, snowball. Note: throughout this tutorial, I will often use this to illustrate a script and its output. The code is at the left and the output is at the right.

Nil

Nil is the type of the value nil, whose main property is to be different from any other value; it usually represents the absence of a useful value. The value nil could be considered as nothing, as the absence of something.

Understanding nil isn't really complicated, all you need to know is that it represents nothing.

Variables that were not set yet are equal to nil by default. Setting a variable to nil will also remove it, so you can set variables to nil when you don't need them anymore:

local var = 5 -- Define the variable.
var = var + 8 -- Perform some arithmetic on the variable.
var = nil -- We don't need the variable anymore, so we can get rid of it by setting it to nil!

Tables

Here is what the Lua 5.1 Reference Manual says about tables:

The type table implements associative arrays, that is, arrays that can be indexed not only with numbers, but with any value (except nil). Tables can be heterogeneous; that is, they can contain values of all types (except nil). Tables are the sole data structuring mechanism in Lua; they can be used to represent ordinary arrays, symbol tables, sets, records, graphs, trees, etc. To represent records, Lua uses the field name as an index. The language supports this representation by providing a.name as syntactic sugar for a["name"]. There are several convenient ways to create tables in Lua.

Now, that might be a bit complicated to understand for you, and that's perfectly normal.

Tables are mainly used for data storage, but they can also be used to represent almost anything. They are the only data structuring mechanism in Lua, but they are more powerful than the data structuring mechanisms you'd typically find in other languages.

Tables contain fields, which consist of a key (also called an index), and a value. The key can be any value, except nil, while the value can also be any value, again, except nil.

I will not explain tables thoroughly here, but I will explain them more in detail later on. There'll be a whole section dedicated to them.

Table constructors

Tables are usually created using a table constructor. A table constructor is an expression that create tables. Every time a constructor is evaluated, a new table is created. A constructor can be used to create an empty table or to create a table and initialize some of its fields.

You can create a table like this:

local t = {}

The {} is the table constructor. You can use it to initialize fields, like this:

local t = {"Hello", "World", 1337, {"You can nest tables in each others too!"}}

As you can see, the values are separated by commas, but you can also separate them with semicolons. Personally, I use semicolons when making my tables continue on many lines, like this:

local t = {
	"Hello";
	"World";
	1337;
	{
		"You can nest tables in each others too!";
	};
}

However, that's just my personal preference. You could also use commas, like in the earlier example.

When you separate values like this, with commas, the keys become 1, 2, 3, and so on. However, you can also set a different key by enclosing it into brackets, like this:

local t = {
	[14] = "This is the value and its key is the number 14.";
	["chicken"] = "This is a string and its key is the name of something Shedletsky likes to eat when it is fried.";
}

In the case of the key "chicken", I could also have just wrote {{{1}}}. It is the same thing, but it only works with strings, though. And it will not work if the string contains spaces or any character other than numbers and letters. The names of table fields, except when enclosed in brackets, follow the same rules as the rules for variable names, which we've talked about earlier.

Indexing and editing a table

You can get the value of any field in a table as long as you know its key. Similarly, if you know the key of any value in the table, you can edit that value, and even add new fields in the table.

You can index a field in the table like this (indexing a field is accessing it to get its value):

local t = {
	[14] = "This is the value and its key is the number 14.";
	chicken = "Yummy!";
}
print(t.chicken)
Yummy!

Note that, since 14 is a number, to access it, you would need to use brackets, like this:

print(t[14])

And you can edit a value like this:

local t = {
	[14] = "This is the value and its key is the number 14.";
	chicken = "Yummy!";
}
t.chicken = "Telamon"
print(t.chicken)
Telamon

As you can see, we modified the value of the field with the key "chicken" to the value "Telamon" and we printed it. Once more, to edit the key 14, you would need to use brackets:

t[14] = 546

Finally, you can add a new field in the table. This is done exactly the same way as editing an existing field, though, so I won't give an example.

Other types

There are other types of values that I will not mention here.

These are userdatas, functions and threads. Userdatas will be mentioned some times during the tutorial, but they are not really important to know about.

Functions are one of the things you will use the most, and there will be a whole section (if not more!) dedicated to them.

As for threads, they will be described when I will talk about coroutines, later in this guide.

[…]

Previous: IntroductionNext: Chapter 2