Variables: Difference between revisions

From Legacy Roblox Wiki
Jump to navigationJump to search
>Oysi93
If you mind about the 'johndoe' -> 'oysi93', then change back. I will make this article better tomorow, I promise! =) (A lot here was wrong)
m Text replacement - "</SyntaxHighlight>" to "</syntaxhighlight>"
 
(21 intermediate revisions by 9 users not shown)
Line 1: Line 1:
{{CatUp|Tutorials}}
A '''variable''' is a name you can use to hold a value. In Lua, a variable can have any [[Data Types|data type]], such as a [[number]] or a [[string]].
__TOC__
__TOC__
== Assignment ==
Assigning a value to a variable can be done using the '''=''' [[operator]], like so:
<syntaxhighlight lang="lua">
x = 10
word = "Hello"
</syntaxhighlight>


== Introduction ==
Variable ''x'' now has a value of the number 10, and ''word'' has a value of the string "Hello". If we print out these variables, we should see the value they have:
<syntaxhighlight lang="lua">
print(x)    --> 10
print(word)  --> Hello
</syntaxhighlight>


This guide is for absolute beginners.  It is intended to familiarize you with Variables in Lua.  If you haven't already, please see [[Your first script]] as a beginner tutorial.
A variable can be changed simply by assigning another value to it:
<syntaxhighlight lang="lua">
n = 12
print(n)    --> 12


== What are we trying to do? ==
n = 24
print(n)    --> 24
</syntaxhighlight>
Even though ''n'' was assigned to a value of 12, it was overwritten by the second assignment of 24.


At the end of this guide, you will be able to:


* Know what a variable is
You can also use a variable as a value when assigning.
* Create a variable
<syntaxhighlight lang="lua">
* Assign a value to a variable
n = 78
* Use a variable in a mathematical equation
x = n


== Setup ==
print(x)  --> 78
</syntaxhighlight>
When ''x'' was assigned to ''n'', it's value became the value of ''n''.


You will need to open [[Roblox Studio]].  Once you have done that, you will need to click "My ROBLOX", select your map, and click "Edit". At this point, you should see your familiar map.


You will need some essentials in [[Roblox Studio]] to make this work:
'''Remember!''' A ''variable'' is always on the '''left''' side of the ''='' while a ''value'' is on the '''right''' side.


* The Output window:
== Names ==
[[Image:Outputwindow.JPG]]
The name you give a variable can only contain letters (uppercase and lowercase), numbers, or an underscore ( _ ), this means that you shouldn't use space characters in the name of your variable. It must start with an underscore or a letter. It cannot be a keyword (one that is highlighted blue in the editor).
* The Explorer window:
[[Image:Explorerwindow.JPG]]
and
* The Command bar:
[[Image:Commandtoolbar.JPG]]


* To make sure you have the Output window, click View / Output.
<syntaxhighlight lang="lua">
* To make sure you have the Explorer window visible, click View / Explorer.
LETTERS = "ABC"          -- valid
* To make sure you have the Command bar visible, click View / Toolbars / Command.
x86 = 1978              -- valid
var_name = "variable"    -- valid
_ = "blank"              -- valid


== Discussion ==
if = 12                  -- NOT valid!
16th = "Lincoln"        -- NOT valid!
</syntaxhighlight>


A '''variable''' is a word or letter you can assign a value to. For instance, in algebra you can give "x" the value of 10. In lua, there's a little more liberty -- Not only can a variable be a number, but it can also be a word, like your name:
== Multiple Assignment ==
Lua allows you to assign more than one value to more than one variable.


<pre>
<syntaxhighlight lang="lua">
x = 1
a, b, c = 1, 2, 3
myname = "oysi93"
</pre>


Notice that the word "oysi93" is in quotes, but the number 1 is not in quotes. That's because "oysi93" is considered a [[String]], or in other words, considered as text. In short, you can perform arithmetic on numbers, but not on "oysi93".
print(a, b, c)    --> 1 2 3
</syntaxhighlight>


Arithmetic can be performed on variables, just as on numbers. For example, if x is equal to 2 and y is equal to 3, then x+y would be 5. Let's try that in the scripting section:
Each variable and each value is separated by a comma. Values to the right of the ''='' are assigned to their corresponding variables to the left. The first variable is assigned to the first value, the second variable is assigned to the second value, and so on. The above example is the same as this. You can see how it saves a lot of space:
<syntaxhighlight lang="lua">
a = 1
b = 2
c = 3


== Scripting ==
print(a, b, c)    --> 1 2 3
</syntaxhighlight>


Open [[Roblox Studio]] and make sure that there aren't any other scripts in the [[Explorer]] window.  We're going to start off with a fresh script.
=== Swapping ===
Multiple assignment is useful because it allows you to easily swap the values of two variables.


* Click Workspace in the Explorer Window.
<syntaxhighlight lang="lua">
* Click Insert > Object > Script.
x, y = 8, 36
* Double click the newly inserted script.
print(x, y)    --> 8 36
* A blank window should open up.
* Insert the following script:


<pre>
x, y = y, x
x = 2 -- This assigns x to the value of 2
y = 3 -- This assigns y to the value of 3
print(x + y) -- This prints out the sum of (x+y))
</pre>


* Test the script by pressing the play button [[Image:Play.JPG]]
print(x, y)    --> 36 8
* Your Output bar should show the number 5, which is the sum of x+y.
</syntaxhighlight>
In this example, ''x'' is assigned to the original value of ''y'', and ''y'' is assigned to the original value of ''x''.


== In depth ==


Variables are essential to use in a good script. A variable is a shortcut to values that you can store, then retrieve and/or change later. Defining a variable is very easy, as well. To define a variable, you just type "variableName = value":


<pre>
== Variable Scopes ==
sometext = "Hello"
[[Image:Scope visual.png|thumb|300px|Every time a block is opened, a new scope is created. Variables in the outer scope are visible, while variables in the inner scope are not. Variables that aren't local are apart of the global scope (shown in <span style="color:blue">blue</span>), and are visible to all scopes, no matter where they were created.]]
luckynumber = 93
Sometimes you may want to limit the access of one variable to another. You can do this by allowing a variable to be visible only to others in the same area. These areas are called '''scopes'''.
brick5 = "Green"
In normal Lua, there are two scopes, known as '''global''' and '''local'''.
VariableIDoNotWantToDefineJustYet = nil
</pre>


To change a variable, you just do the same thing:
Each [[block]] of code has its own scope. Since blocks can be [[nested]], each scope may have an '''outer scope''' and an '''inner scope'''.
*The inner scope is a "child" of the current scope. The current scope cannot access variables in the inner scope.
*The outer scope is a the "parent" of the current scope. The current scope has access to any variables in the outer scope.


<pre>
=== Global Variables ===
variable = 1 -- This assigns "variable" to the value 1.
A global variable is a variable that is visible to all scopes of a script. (Not to be confused with adding variables to the "_G" or "shared" tables, which are shared amongst scripts.)
print(variable) -- This prints the variable, which is 1 now.


variable = 7 -- This makes the variable 7 instead of 1.
<syntaxhighlight lang="lua">
print(variable) -- This prints 7, because "variable" is now equal to 7.
a = 1
 
if true then
variable = variable + 5 -- Adds 5 to the variable, making the variable 7+5.
    print(a)       --> 1
print(variable) -- This prints 12, because 7 + 5 is 12, you should know this math...
    if true then
</pre>
        a = 2
 
        print(a)    --> 2
Please note that a variable cannot start with a number, nor can it be a keyword. Which means these variable names are invalid:
    end
 
    print(a)       --> 2
<pre>
end
-- DON'T EVER USE THESE NAMES WHEN ASSIGNING VARIABLES --
print(a)            --> 2
if = 1
</syntaxhighlight>
12 = 2
do = "hello"
</pre>


While these and many others aswell are valid:
All variables will default to global, unless they are declared local (explained next).
 
<pre>
a = 1
hello = "hey"
mom = "nice"
</pre>


=== Local Variables ===
=== Local Variables ===
A local variable is a variable that can only be accessed by other things in the same scope. A variable is made local by adding the keyword '''local''' before the variable. It is true that local variables are obtained faster than normal variables. This is because they are integrated into the current environment they were created in.
<syntaxhighlight lang="lua">
local word = "Hello"
</syntaxhighlight>


A local variable is a variable that is ONLY known to it's scope of the script. To define one you have to have "local" before it:
A local variable is not visible to things in its outer scope.
<syntaxhighlight lang="lua">
if true then    -- a new block is created
    local b = 2
end
print(b)        --> nil
</syntaxhighlight>


<pre>
However, they are visible to things in its inner scope.
local var = "Hello" -- This assigns var to the string "Hello"
<syntaxhighlight lang="lua">
</pre>
local b = 2
if true then
    print(b)    --> 2
end
</syntaxhighlight>


You might not understand what these scopes are, just yet, so let me show you:
If a variable has the same name as one in its outer scope, the outer scope's value is overwritten in the inner scope, but not the outer scope.


<pre>
<syntaxhighlight lang="lua">
function Test() -- Creates a new scope (Test)
a = 1
local A = 1
if true then
print(A)
    local a = 2
end -- This ends the scope 'Test', making the variable A unaccessable outside.
    print(a)     --> 2
 
end
Test() -- Runs the function above
print(a)         --> 1
print(A) -- Tries to print A, but since A is local to the 'Test', it prints nothing
</syntaxhighlight>
</pre>
 
Which will print 1 and then nil, because the variable A can only be accessed from within the 'Test'.
 
=== Global Variables ===
A global variable is a variable that is "readable" by all scripts. For example, one is 'Game'. When you state 'Game' it thinks of the Data Model that is your game. To define a such global variable yourself, you state "_G." and then the variable name, table indexing if you know what that is. Then when another script states the variable, it will think of the variable you set it to:
 
Script 1


<pre>
=== Shared Variables ===
_G.Var = 10 -- This defines the variable 'Var' to a global, and set it equal to 10.
[[Image:Shared variables2.png|thumb|300px|Shared variables are partially visible to the global scope, such that they can be accessed, but not changed.]]
</pre>
In Roblox Lua, there is a third type of variable called a shared variable. Shared variables are variables that are visible to every script (that is, they are shared between them). Some examples of a shared variable include [[Function_Dump/Core_Functions#print_.28.C2.B7.C2.B7.C2.B7.29|print]], [[game]], or [[Instance]]. A list of all shared variables can be found at the [[Function Dump]].


Script 2
Remember that there are some major differences between normal Lua and Roblox Lua.
*In normal Lua, these variables are considered global variables, because they are completely visible in the global scope.
*In Roblox Lua, these variables have been separated from the global scope because Roblox uses multiple scripts, each having they're own [[environment]].
*In Roblox Lua, these variables cannot be modified for security reasons.


<pre>
<!-- Advanced explanation; probably not suited for this article
wait(1) -- If Script 2 runs before Script 1, the global will not have been defined...
Since an environment is a table, they can have a [[metatable]]. Shared variables can be indexed because a script's environment has it's metatable set to index the original global environment.
print(_G.Var) -- This prints 10 in the output! =D
-->
</pre>


== See Also ==  
== See Also ==
*[[Global Functions]]
*[[Scope]]


[[Intro to Scripting: Make a Dance Floor]]
[[Absolute beginner's guide to scripting]]
[[Category:Scripting Tutorials]]
[[Category:Scripting Tutorials]]

Latest revision as of 06:16, 27 April 2023

A variable is a name you can use to hold a value. In Lua, a variable can have any data type, such as a number or a string.

Assignment

Assigning a value to a variable can be done using the = operator, like so:

x = 10
word = "Hello"

Variable x now has a value of the number 10, and word has a value of the string "Hello". If we print out these variables, we should see the value they have:

print(x)     --> 10
print(word)  --> Hello

A variable can be changed simply by assigning another value to it:

n = 12
print(n)    --> 12

n = 24
print(n)    --> 24

Even though n was assigned to a value of 12, it was overwritten by the second assignment of 24.


You can also use a variable as a value when assigning.

n = 78
x = n

print(x)   --> 78

When x was assigned to n, it's value became the value of n.


Remember! A variable is always on the left side of the = while a value is on the right side.

Names

The name you give a variable can only contain letters (uppercase and lowercase), numbers, or an underscore ( _ ), this means that you shouldn't use space characters in the name of your variable. It must start with an underscore or a letter. It cannot be a keyword (one that is highlighted blue in the editor).

LETTERS = "ABC"          -- valid
x86 = 1978               -- valid
var_name = "variable"    -- valid
_ = "blank"              -- valid

if = 12                  -- NOT valid!
16th = "Lincoln"         -- NOT valid!

Multiple Assignment

Lua allows you to assign more than one value to more than one variable.

a, b, c = 1, 2, 3

print(a, b, c)    --> 1 2 3

Each variable and each value is separated by a comma. Values to the right of the = are assigned to their corresponding variables to the left. The first variable is assigned to the first value, the second variable is assigned to the second value, and so on. The above example is the same as this. You can see how it saves a lot of space:

a = 1
b = 2
c = 3

print(a, b, c)    --> 1 2 3

Swapping

Multiple assignment is useful because it allows you to easily swap the values of two variables.

x, y = 8, 36
print(x, y)    --> 8 36

x, y = y, x

print(x, y)    --> 36 8

In this example, x is assigned to the original value of y, and y is assigned to the original value of x.


Variable Scopes

Every time a block is opened, a new scope is created. Variables in the outer scope are visible, while variables in the inner scope are not. Variables that aren't local are apart of the global scope (shown in blue), and are visible to all scopes, no matter where they were created.

Sometimes you may want to limit the access of one variable to another. You can do this by allowing a variable to be visible only to others in the same area. These areas are called scopes. In normal Lua, there are two scopes, known as global and local.

Each block of code has its own scope. Since blocks can be nested, each scope may have an outer scope and an inner scope.

  • The inner scope is a "child" of the current scope. The current scope cannot access variables in the inner scope.
  • The outer scope is a the "parent" of the current scope. The current scope has access to any variables in the outer scope.

Global Variables

A global variable is a variable that is visible to all scopes of a script. (Not to be confused with adding variables to the "_G" or "shared" tables, which are shared amongst scripts.)

a = 1
if true then
    print(a)        --> 1
    if true then
        a = 2
        print(a)    --> 2
    end
    print(a)        --> 2
end
print(a)            --> 2

All variables will default to global, unless they are declared local (explained next).

Local Variables

A local variable is a variable that can only be accessed by other things in the same scope. A variable is made local by adding the keyword local before the variable. It is true that local variables are obtained faster than normal variables. This is because they are integrated into the current environment they were created in.

local word = "Hello"

A local variable is not visible to things in its outer scope.

if true then    -- a new block is created
    local b = 2
end
print(b)        --> nil

However, they are visible to things in its inner scope.

local b = 2
if true then
    print(b)    --> 2
end

If a variable has the same name as one in its outer scope, the outer scope's value is overwritten in the inner scope, but not the outer scope.

a = 1
if true then
    local a = 2
    print(a)      --> 2
end
print(a)          --> 1

Shared Variables

Shared variables are partially visible to the global scope, such that they can be accessed, but not changed.

In Roblox Lua, there is a third type of variable called a shared variable. Shared variables are variables that are visible to every script (that is, they are shared between them). Some examples of a shared variable include print, game, or Instance. A list of all shared variables can be found at the Function Dump.

Remember that there are some major differences between normal Lua and Roblox Lua.

  • In normal Lua, these variables are considered global variables, because they are completely visible in the global scope.
  • In Roblox Lua, these variables have been separated from the global scope because Roblox uses multiple scripts, each having they're own environment.
  • In Roblox Lua, these variables cannot be modified for security reasons.


See Also