Garry's Mod Wiki

Revision Difference

Beginner_Tutorial_Variables#528524

<cat>Dev.GettingStarted</cat> <title>Coding - Variables</title> # Variables, what are they? Variables let your script hold information. Using a variable you can put aside some data for later and then call it back whenever you want. Variables themselves don't have a type assigned to them and they can hold absolutely anything. ## Recapitulation and the print function⤶ From now on it is assumed you don't need explanations about opening notepad, saving, and loading a script in Garry's Mod. Refer to the <page text="first page">Beginner_Tutorial_Intro</page> if you forgot. Open up your editor, we'll be making a new script, with variables! ⤶ If you remember, last time we did this:⤶ Variables let your script hold information. Using a variable, you can store some piece of data once and then reference it later whenever you want. Lua doesn't require you to declare a variable as strictly being a certain type, so they can hold absolutely anything, including nothing (`nil`). ## Recap: Saving and running scripts, calling print⤶ From now on, it is assumed you don't need explanations about opening notepad, saving, and loading a script in Garry's Mod. Refer to the <page text="first page">Beginner_Tutorial_Intro</page> if you forgot. Open up your editor. We'll be making a new script, with variables! ⤶ In the last tutorial, we learned how to print a simple `string` to the console:⤶ ``` print( "Hello World!" ) ``` ⤶ This was simple enough. Whenever the script was opened, it said Hello World! in the console.⤶ This was simple enough: whenever our script ran, it said "Hello World!" in the console:⤶ <page>Global.print</page>() is a function. A function is a command that does something when you call it. Many functions can take arguments, which is data you give the function to change exactly what it does. In this case, <page>Global.print</page>() takes one argument, which is a string (a series of letters, numbers, spaces, and so on), and when <page>Global.print</page>() is called, it puts that <page>string</page> into the console. ⤶ So, let's take our script apart so we can understand it. ⤶ Let's dissect the code piece by piece so we can understand it. ``` print( "Hello World!" ) ``` ⤶ print is the name of the binding. The ( and the ) (these symbols are called **parentheses**) are where you put the text for print to print. "Hello World!" is the text we chose to print. Notice the "" (**quotation marks**). The quotation marks tell lua that everything in between them is a <page>string</page>, and not the name of a variable. Doing this: `print` is the name of the function we are calling. The `(` and the `)` (these symbols are called **parentheses**) are where you put the text you want `print` to put in the console. "Hello World!" is the text we chose to print; it is a `string` - Notice the `""` (**quotation marks**). The quotation marks tell Lua that everything in between them is a <page>string</page>, and not the name of a variable. Doing this: ``` print( Hello World! ) ``` ⤶ ⤶ ⤶ doesn't work. Lua will think that Hello and World! are the name of a variable, instead of a <page>string</page>.⤶ ⤶ Any time we want lua to know that the information we're giving it is text, we put it inbetween quotation marks. Text in quotation marks is called a <page>string</page>.⤶ ⤶ won't work, because we're missing the quotation marks! If we do this, Lua will think that `Hello` and `World!` are the names of two variables, instead of a <page>string</page> literal. Remember: any time we want Lua to know that the information we're giving it is some form of text, we put the text in between quotation marks to represent it as a string.⤶ Whew! Are you still with me? These are the words you need to remember so far: Variable⤶ Binding⤶ Function⤶ Print⤶ Parentheses⤶ Quotation Marks⤶ String⤶ ⤶ Okay, now that we've gone over how print works and about text and whatnot, we'll move onto how to write variables. * **Variable** (holds a value)⤶ * **Function** (does something, may take arguments)⤶ * **Arguments**, a.k.a. Parameters (functions take these and do things with them)⤶ * `print` (a function that puts text in the console)⤶ * **String** (a type of variable that holds text data)⤶ * **Parentheses**⤶ * **Quotation Marks**⤶ ⤶ Now that we know about how functions work, how strings are represented, and how to call functions, let's move on to how to define, or declare, variables and assign values to them. # Defining variables A variable can be created by doing this: ⤶ A variable can be created by doing this: ``` myName = "Jeff" ``` ⤶ ⤶ ⤶ The name of the variable is on the left. The equal sign says you want to set this variable to what's on the right. If you remembered well, "Jeff" is a <page>string</page>, because it has quotation marks around it. myName is the name of a variable, because it doesn't have quotation marks around it! Getting the hang of it?⤶ ⤶ The name of the variable (`myName`) is on the left. The equal sign says you want to set this variable's value to what's on the right. If you remember, "Jeff" is a <page>string</page>, because it has quotation marks around it. `myName` is the name of a variable, because it doesn't have quotation marks around it! Getting the hang of it?⤶ So now you're probably thinking, what's the point of this? Well, that's what we're here to see. But first, let's see how to use <page>Global.print</page>() with a variable instead of text. As you know by now, the first way we used message was like so. ``` print("Hello World!") ``` We're using a <page>string</page> inside of <page>Global.print</page>() to tell it what to print. But if we want to use a variable, we do this: ``` myName = "Jeff" print( myName ) ``` Whenever this runs, <page>Global.print</page>() prints Jeff into the console, because myName is Jeff. Heh, see? You can change variables the same way you make them. Like so: ``` myName = "Jeff" print( myName ) myName = "Josh" print( myName ) ``` The example above prints "Jeff" first, and "Josh" second. ⤶ ## Confused? Think back to algebra⤶ ⤶ Hopefully you're not too confused at this point. Luckily, if you've done math before, especially algebra, you've already seen variables and functions, and even arguments! For example, think back to when an algebra problem said ⤶ ```⤶ x = 4⤶ ```⤶ This means that `x`, the name of the variable, holds the value `4`, which can also be said like "4 is assigned to x", or "x is 4". ⤶ ⤶ In algebra, we may have also seen a function named `f` defined as⤶ ```⤶ f(x) = 2x + 1⤶ ```⤶ ⤶ If we "plugged in", or "passed", the value of our variable `x` to the function `f(x)`, the function would use it to calculate `9`, because it would multiply `2 times 4` and add `1`. In this case, `f` is the function, `x` is the argument, and whatever gets calculated inside the function (`2x + 1`) is entirely dependent on the value of the argument `x` that was passed to it. For example, if we passed `3` as the argument instead, then the function would calculate `7`.⤶ ⤶ Knowing how that works, we could try writing it in Lua using what we've learned so far. Since we don't know how to define our own functions yet, we will just tell the code to print the result of `2x+1` using the `print` function:⤶ ⤶ ```⤶ x = 4⤶ print( 2*x + 1 ) -- prints 9⤶ x = 3⤶ print( 2*x + 1 ) -- prints 7⤶ ```⤶ ⤶ Hopefully this might help you understand variables, functions, and arguments a little better.⤶ # Local Variables Local variables are variables that are available only in the code block they are defined in, and in all child code blocks. They are defined like this: Local variables are variables that are available only in the code block they are defined in (also known as the "scope" they are defined in), and in all of the subsequent child code blocks. They are defined like this: ``` local myName = "Jeff" print( myName ) ``` In most cases you want to use local variables, so other scripts can't override them or so that your script won't break other scripts. This example shows the difference between a global variable and a local variable:⤶ In most cases, you will want to use local variables so that other scripts can't override them, or so that your script won't override something from another script. This example shows the difference between a global variable and a local variable - specifically, how scoping works:⤶ ``` -- 2 local variables:⤶ local myName = "Jeff" local myAge = 18 -- 2 global variables:⤶ myPetName = "Peter" filename = "test.lua" print( myName, myPetName, myLastName, myAge, filename ) ⤶ print( myName, myPetName, myLastName, myAge, filename ) -- (Yes, print can actually take more than 1 argument)⤶ if ( true ) then -- now we are in a different code block:⤶ -- any local variable we assign in this block will only be⤶ -- available inside this block, until we reach the "end":⤶ local myName = "George" local myLastName = "Jackson" local filename = "nope.jpg" myPetName = "Bob" myAge = 20 print( myName, myPetName, myLastName, myAge, filename ) end ⤶ print( myName, myPetName, myLastName, myAge, filename ) ⤶ -- myPetName and myAge were changed in the above block! -- The others were not, since they were local to the block.⤶ print( myName, myPetName, myLastName, myAge, filename )⤶ ``` This code will have this output: ``` Jeff Peter nil 18 test.lua George Bob Jackson 20 nope.jpg Jeff Bob nil 20 test.lua ``` # Concatenation Now the next thing we will learn is how to join two <page>string</page>s together. Joining two types of data together to make a <page>string</page> is called **concatenation**. To concatenate, you just need to use .. - See below:⤶ Joining two types of data together to make a <page>string</page> is called **concatenation**. To concatenate, you just need to use `..` Here's an example:⤶ ``` print( "I don't like " .. "being apart. ") ``` ⤶ "I don't like ".."being apart." becomes "I don't like being apart.".⤶ ⤶ Likewise, you can join a <page>string</page> and a variable:⤶ ⤶ `"I don't like " .. "being apart."` becomes `"I don't like being apart."`⤶ ⤶ <note>Now the strings are happy, because they are together as one string.</note>⤶ ⤶ Likewise, you can join a <page>string</page> literal and a variable:⤶ ``` myName = "Jeff" local myName = "Jeff" print( "Welcome to the Atlantic, " .. myName ) ``` This prints "Welcome to the Atlantic, Jeff" because myName is "Jeff". So really what it's doing is: "Welcome to the Atlantic, ".."Jeff"⤶ ⤶ You can use .. as many times as you want. See below:⤶ This prints `"Welcome to the Atlantic, Jeff"` because `myName` is holding the value `"Jeff"`. What it's really doing is:⤶ `"Welcome to the Atlantic, " .. "Jeff"`⤶ ⤶ You can use `..` as many times as you want. See below:⤶ ``` myName = "Jeff" print( "Welcome to the Atlantic, "..myName..". As you know, we are very glad to have you. If you ever get uncomfortable " .. myName .. ", we have a sick bay on board to assist you." ) local myName = "Jeff" print( "Hi, " .. myname .. ". I heard your name is " .. myname .. "! Nice meme." ) -- This prints: Hi, Jeff. I heard your name is Jeff! Nice meme.⤶ ``` ⤶ ⤶ This prints :⤶ ⤶ We can even concatenate other types of values, like numbers, with a string:⤶ ``` Welcome to the Atlantic, Jeff. As you know, we are very glad to have you. If you ever get uncomfortable Jeff, we have a sick bay on board to assist you.⤶ local myAge = 69⤶ print( "I am " .. myAge .. " years young." )⤶ -- prints: I am 69 years young.⤶ ``` ⤶ ⤶ ## Newlines⤶ Last thing we will cover here is how to use **newlines**. Newlines are denoted by **\n** in a <page>string</page>. You can use newlines anywhere in the <page>string</page> to make a new line (see below):⤶ ⤶ # Newlines⤶ The last thing we will cover here is how to use **newlines** inside strings. Newlines are created by writing `\n` in a <page>string</page> where you want the new line to start. You can use newlines anywhere in the <page>string</page> to insert a new line (see below):⤶ ``` myName = "Jeff" local myName = "Jeff" print( "Hello, " .. myName .. "!\nHow are you today?\nI'm feeling great." ) ``` This prints this into the console: ``` Hello, Jeff! How are you today? I'm feeling great. ``` Multiline <page>string</page>s can also be defined by using double square brackets instead of quotes. This allows you to create newlines in the <page>string</page> by just pressing enter. Multiline <page>string</page>s can also be defined by using double square brackets (`[[ ]]`) instead of quotes. This allows you to create newlines in the <page>string</page> without using `\n`. Example: ``` print([[Hello, Jeff! print( [[Hello, Jeff! How are you today? I'm feeling great.]]) I'm feeling great.]] ) ``` ⤶ ⤶ ⤶ Prints:⤶ ``` Hello, Jeff! How are you today? I'm feeling great. ``` # What's next? Next we will learn about <page text="operators">Beginner_Tutorial_If_Then_Else</page>. ⤶ # What's next? Next we will learn about <page text="conditions">Beginner_Tutorial_If_Then_Else</page>.