Absolute beginner's guide to scripting: Difference between revisions

Improving code and using SyntaxHighlight
(replaced the open studio thing with how to open the studio via the client)
(Improving code and using SyntaxHighlight)
Line 63: Line 63:
This is almost a working ROBLOX Lua statement! Now, to actually remove the head, a '''method''' must be used. Methods are functions that do specific things in ROBLOX for you by '''calling''' them. Methods are functions of objects in ROBLOX Lua. To call a method on an object in Lua, you use a colon (''':''') after the object. You then state the name of the method, then two parenthesis with nothing in them. Methods and functions take '''arguments''', which are values given to the function to change how it works. The "Destroy" method takes no arguments, so we place the parenthesis there to show that there's nothing else we have to give to the Destroy method.
This is almost a working ROBLOX Lua statement! Now, to actually remove the head, a '''method''' must be used. Methods are functions that do specific things in ROBLOX for you by '''calling''' them. Methods are functions of objects in ROBLOX Lua. To call a method on an object in Lua, you use a colon (''':''') after the object. You then state the name of the method, then two parenthesis with nothing in them. Methods and functions take '''arguments''', which are values given to the function to change how it works. The "Destroy" method takes no arguments, so we place the parenthesis there to show that there's nothing else we have to give to the Destroy method.


<code lua>game.Workspace.USERNAME.Head:Destroy()</code>
<syntaxhighlight lang="lua">
workspace.USERNAME.Head:Destroy()
</syntaxhighlight>


The above statement is '''syntactically correct''' Lua code. However, your name isn't USERNAME, so substitute your name in. If your name was "AwesomeSocks", then you would use the following:
The above statement is '''syntactically correct''' Lua code. However, your name isn't USERNAME, so substitute your name in. If your name was "AwesomeSocks", then you would use the following:


<code lua>game.Workspace.AwesomeSocks.Head:Destroy()</code>
<syntaxhighlight lang="lua">
workspace.AwesomeSocks.Head:Destroy()
</syntaxhighlight>


To compare this to English, it would be like saying "The sky has trees". It is ''grammatically correct'' English, but an ''untrue'' statement. If you state the name of things that do not exist, your script won't work and an error will occur.
To compare this to English, it would be like saying "The sky has trees". It is ''grammatically correct'' English, but an ''untrue'' statement. If you state the name of things that do not exist, your script won't work and an error will occur.
 
=== Testing the script ===
===Testing the script===
 
To test your fine script, enter any normal ROBLOX place in solo mode (or build mode) so that you can walk around with your character. Open up [[Roblox Studio]] and open the [[Scripting#Fundamentals|command bar]]. Type your one-lined wonder in, and hit enter to run it.
To test your fine script, enter any normal ROBLOX place in solo mode (or build mode) so that you can walk around with your character. Open up [[Roblox Studio]] and open the [[Scripting#Fundamentals|command bar]]. Type your one-lined wonder in, and hit enter to run it.


Line 80: Line 82:


If your script does not work and nothing happens, expect this to happen a lot. Scripters (and programmers alike) run into the problem of their scripts not doing something right because their code has bugs in it. Not to worry, though - there is the [[output]], a key tool that can help you debug your scripts and get them working.
If your script does not work and nothing happens, expect this to happen a lot. Scripters (and programmers alike) run into the problem of their scripts not doing something right because their code has bugs in it. Not to worry, though - there is the [[output]], a key tool that can help you debug your scripts and get them working.
 
== Setting Values in ROBLOX Lua ==
==Setting Values in ROBLOX Lua==
What about changing values of objects in ROBLOX Lua? There is a way to do that, and it's more of the same. To set your health to zero (rather than going "''Off with your head!''") you need to set the Health property of your humanoid to zero. To set properties of objects, you use a period ('''.'''), the property's name, an equals sign and the value.
What about changing values of objects in ROBLOX Lua? There is a way to do that, and it's more of the same. To set your health to zero (rather than going "''Off with your head!''") you need to set the Health property of your humanoid to zero. To set properties of objects, you use a period ('''.'''), the property's name, an equals sign and the value.


<code lua>game.Workspace.USERNAME.Humanoid.Health = 0</code>
<syntaxhighlight lang="lua">
workspace.USERNAME.Humanoid.Health = 0
</syntaxhighlight>


You will learn specifics about what is what in ROBLOX Lua later (such as "''What does the equals sign really do?''"). For now, you can consider yourself a really basic scripter that can call methods and change properties's values.
You will learn specifics about what is what in ROBLOX Lua later (such as "''What does the equals sign really do?''"). For now, you can consider yourself a really basic scripter that can call methods and change property values.


Protip: The Workspace is a special game service. Since it is used a lot in scripting, ROBLOX Lua has a built-in constant (just like '''game''') called '''Workspace''' rather than '''game.Workspace'''. You'll learn about constants and variables later, but know that the Workspace is the only object in ROBLOX Lua that has it's own built in constant. You can therefore do this:
Pro tip: The Workspace is a special game service. Since it is used a lot in scripting, ROBLOX Lua has a built-in constant (just like '''game''') called '''Workspace''' rather than '''game.Workspace'''. You'll learn about constants and variables later, but know that the Workspace is the only object in ROBLOX Lua that has it's own built in constant.


<code lua>Workspace.USERNAME.Humanoid.Health = 0</code>
<syntaxhighlight lang="lua">
workspace.USERNAME.Humanoid.Health = 0
</syntaxhighlight>


==Inserting a Script object==
== Inserting a Script object ==
To add a new script in [[Roblox_Studio|ROBLOX Studio]], just click ''Insert'' > ''Object...'' > ''Script''. You'll find a blank script that has been added to the Workspace.
To add a new script in [[Roblox_Studio|ROBLOX Studio]], just click ''Insert'' > ''Object...'' > ''Script''. You'll find a blank script that has been added to the Workspace.
[[Image:Explorerwindow.JPG|none]]
[[Image:Explorerwindow.JPG|none]]
Try modifying it to do different things. It is exactly like the command bar we have been using, but now you can have multiple lines of code.[[Image:Insertscript.JPG]]
Try modifying it to do different things. It is exactly like the command bar we have been using, but now you can have multiple lines of code.[[Image:Insertscript.JPG]]


===Editing a script in ROBLOX Studio===
=== Editing a script in ROBLOX Studio ===
To open a script object's '''source''' (the code in the script object) for editing in ROBLOX Studio, you can double-click it in the Explorer window and a text editor will open where you can change your script's source. Whatever you add, remove or change in this text editor is ''permanent'', and besides the "undo" button, these changes cannot be undone once the editor is closed.
To open a script object's '''source''' (the code in the script object) for editing in ROBLOX Studio, you can double-click it in the Explorer window and a text editor will open where you can change your script's source. Whatever you add, remove or change in this text editor is ''permanent'', and besides the "undo" button, these changes cannot be undone once the editor is closed.


===Starting and Stopping your script===
=== Starting and Stopping your script ===
Script objects run their code under the following conditions:
Script objects run their code under the following conditions:
* The script is added to the game (Select the script in the Explorer window and cut it (CTRL+X), then paste it back into the game (CTRL+V, or right click Workspace and click "Paste Into").
* The script is added to the game (Select the script in the Explorer window and cut it (CTRL+X), then paste it back into the game (CTRL+V, or right click Workspace and click "Paste Into").
* The script's disabled property is changed to false (select the script in the Explorer window and toggle it's Disabled property in the Properties window).
* The script's disabled property is changed to false (select the script in the Explorer window and toggle it's Disabled property in the Properties window).
== Script Creation ==
== Script Creation ==
There are 5 topics that will be answered here:  
There are 5 topics that will be answered here:  
* Creating the script
* Creating the script
* Storing references to objects
* Storing references to objects
* Listening to events
* Listening to events
* Functions
* Functions
* Modifying objects
* Modifying objects


Line 125: Line 123:
To get a script, go in Roblox Studio and then simply select Insert>Object. Now, a window will appear. In the newly appeared window, click on "Script" and OK. You should find the script inside "Workspace" in the explorer tab. If you don't see any explorer window up, go to View >Explorer.  
To get a script, go in Roblox Studio and then simply select Insert>Object. Now, a window will appear. In the newly appeared window, click on "Script" and OK. You should find the script inside "Workspace" in the explorer tab. If you don't see any explorer window up, go to View >Explorer.  


Now to open the script, just double-click it. If you did it right, a window will cover the whole ingame screen. And you will find the line "print "Hello World!"" Before you start, just go ahead and delete that line.
Now to open the script, just double-click it. If you did it right, a window will cover the whole in-game screen. And you will find the line "print "Hello World!"" Before you start, just go ahead and delete that line.


=== Making References to Objects ===
=== Making References to Objects ===
Line 133: Line 131:
Now, making references to objects is not necessary, but it can make scripting a lot less work. Here's an example of how you do it:  
Now, making references to objects is not necessary, but it can make scripting a lot less work. Here's an example of how you do it:  


<code lua>local brick = Workspace.Brick</code>
<syntaxhighlight lang="lua">
 
local brick = workspace.Brick
That will make `brick` refer to {{`|game.Workspace.Brick}}. You can set the name to absolutely '''anything'''. This is an example of a [[variable]]. You can have as many variables as you want in a script.
</syntaxhighlight>


If you didn't store it in a variable, every time you try making the script modify the object, you would have to put the line "Workspace.Brick". Variables make it much simpler, since you only have to put the name you assigned. Name the brick desired to "Brick", and make a reference to it in the script by typing the example above. Note that making a reference to an object is the same as assigning a variable.
That will make `brick` refer to {{`|workspace.Brick}}. You can set the name to absolutely '''anything'''. This is an example of a [[variable]]. You can have as many variables as you want in a script.


If you didn't store it in a variable, every time you try making the script modify the object, you would have to put the line "workspace.Brick". Variables make it much simpler, since you only have to put the name you assigned. Name the brick desired to "Brick", and make a reference to it in the script by typing the example above. Note that making a reference to an object is the same as assigning a variable.
=== Event Listeners ===
=== Event Listeners ===
Now we're getting into the meat of scripting. Sure, the script knows where the brick is, but that's all. It can't do anything else. Now we're jumping into a listening event.
Now we're getting into the meat of scripting. Sure, the script knows where the brick is, but that's all. It can't do anything else. Now we're jumping into a listening event.


Line 147: Line 145:
You still should have the script with the variable in it. We're going to make the script listen for being touched (the [[Touched]] event). Here's an example:  
You still should have the script with the variable in it. We're going to make the script listen for being touched (the [[Touched]] event). Here's an example:  


<code lua>brick.Touched:connect(onTouch)</code>
<syntaxhighlight lang="lua">
brick.Touched:connect(onTouched)
</syntaxhighlight>


When the brick is touched, it will execute the [[function]] named {{`|onTouch}}. Keep in mind that the name inside the parentheses is the name of the function.
When the brick is touched, it will execute the [[function]] named {{`|onTouched}}. Keep in mind that the name inside the parentheses is the name of the function.


This is not the only listener type. There are many more to use, some of which require some familiarity with scripting. [[Class reference|Here]] is a very well-done reference page set up by MrDoomBringer.  
This is not the only listener type. There are many more to use, some of which require some familiarity with scripting. [[Class reference|Here]] is a very well-done reference page set up by MrDoomBringer.  
Line 155: Line 155:
This is where you can find more help in the future, when you begin to understand scripting more. Not only does it show Events, but also shows other scripting references need for other aspects of scripting.  
This is where you can find more help in the future, when you begin to understand scripting more. Not only does it show Events, but also shows other scripting references need for other aspects of scripting.  


Put the line <code lua>brick.Touched:connect(onTouch)</code> a line or two below the variable assignment <code lua>local brick = Workspace.Brick</code>
Put the line
 
<syntaxhighlight lang="lua">
brick.Touched:connect(onTouched)
</syntaxhighlight>
a line or two below the variable assignment
<syntaxhighlight lang="lua">
local brick = Workspace.Brick
</syntaxhighlight>
=== Functions ===
=== Functions ===
Your script is getting better and better, but where is the function? Your script will break if it doesn't have one of those for the listener to refer the script to.  
Your script is getting better and better, but where is the function? Your script will break if it doesn't have one of those for the listener to refer the script to.  


What is a function? It is where all your modifying work will be done. It is also an important part to your scripting. Without it, you could not make the script modify objects from listeners. Another example:  
What is a function? It is where all your modifying work will be done. It is also an important part to your scripting. Without it, you could not make the script modify objects from listeners. Another example:
 
<syntaxhighlight lang="lua">
<code lua>
local function onTouched(part)
function onTouch(part)


end  
end  
</code>
</syntaxhighlight>
There is the function. As you can see, the word "function" is followed by "onTouch", the name of the function. The listener from last lesson is trying to refer to the function. The listener is going to tell the script to run through this function and do whatever is found inside. Notice the "(part)" after the function name. This is a reference to the object that the listener found that touched the brick. This is not always needed, especially for some event listeners.
There is the function. As you can see, the word "function" is followed by "onTouched", the name of the function. The listener from last lesson is trying to refer to the function. The listener is going to tell the script to run through this function and do whatever is found inside. Notice the "(part)" after the function name. This is a reference to the object that the listener found that touched the brick. This is not always needed, especially for some event listeners.


But back to what we're looking at. The variable "part" is the object that touched the brick. You can play with this object for fun later. Now notice also two lines below the function: "end". You will need one of these for every function and other block structures in scripting, such as "if" statements. Always remember this when scripting.  
But back to what we're looking at. The variable "part" is the object that touched the brick. You can play with this object for fun later. Now notice also two lines below the function: "end". You will need one of these for every function and other block structures in scripting, such as "if" statements. Always remember this when scripting.  


Now, make the lines from first example, except put it two lines under the variable assignment, and one line above the listener.
Now, make the lines from first example, except put it two lines under the variable assignment, and one line above the listener.
=== Modifying Objects ===
=== Modifying Objects ===
The script knows the brick, will wait until it's touched, and has the function to use. But it doesn't know what to do to the brick.  
The script knows the brick, will wait until it's touched, and has the function to use. But it doesn't know what to do to the brick.  


This is where storing references to objects saves you time. We wanted it to flicker invisible/visible, so here's an example:  
This is where storing references to objects saves you time. We wanted it to flicker invisible/visible, so here's an example:  
<code lua>
<syntaxhighlight lang="lua">
brick.Transparency = 1  
brick.Transparency = 1
wait(1)  
 
wait(1)
 
brick.Transparency = 0  
brick.Transparency = 0  
</code>
</syntaxhighlight>
These lines will alter the brick as we wanted. The brick's transparency is changed to "1", which is completely invisible. The "wait(1)" line will make the script wait for one second before continuing, then the brick's transparency will be put back at 0, which is completely visible. You can alter "wait(1)" to any number inside the parentheses. Whatever number you put inside the parentheses will be the amount of time it will wait in seconds.  
These lines will alter the brick as we wanted. The brick's transparency is changed to "1", which is completely invisible. The "wait(1)" line will make the script wait for one second before continuing, then the brick's transparency will be put back at 0, which is completely visible. You can alter "wait(1)" to any number inside the parentheses. Whatever number you put inside the parentheses will be the amount of time it will wait in seconds.  


Put those 3 lines right under the line "function onTouch(part)" and above the line "end".  
Put those 3 lines right under the line "local function onTouched(part)" and above the line "end".
=== Complete script ===
<syntaxhighlight lang="lua" line>
local brick = workspace.Brick -- Store a reference to the brick.


=== Complete script ===
local function onTouched(part) -- The function that runs when the part is touched.
brick.Transparency = 1


<code lua>
wait(1)
local brick = Workspace.Brick -- Store a reference to the brick.


function onTouch(part) -- The function that runs when the part is touched.
brick.Transparency = 1
wait(1)
brick.Transparency = 0  
brick.Transparency = 0  
end  
end  


brick.Touched:connect(onTouch) -- The line that connects the function to the event.
brick.Touched:connect(onTouched) -- The line that connects the function to the event.
</code>
</syntaxhighlight>
 
== Advanced scripting techniques ==
==Advanced scripting techniques==
=== Make your own functions ===
 
===Make your own functions===
While scripting, you may want to make your own function to call later. This is easy enough, here is the syntax (grammar) for doing so: (NOTE: These functions are called ''without'' a colon [:])
While scripting, you may want to make your own function to call later. This is easy enough, here is the syntax (grammar) for doing so: (NOTE: These functions are called ''without'' a colon [:])
<pre>function <functionname>(<parameter>)
<pre>
<statements>
function <functionname>(<parameter>)
    <statements>
end
end


Line 214: Line 217:
</pre>
</pre>


A parameter is a way to give data to a function. An example of a parameter: a Humanoid has a takeDamage() function. You have to tell it how much damage to take. You would type Humanoid:takeDamage(100) to take 100 damage.
A parameter is a way to give data to a function. An example of a parameter: a Humanoid has a TakeDamage() function. You have to tell it how much damage to take. You would type Humanoid:TakeDamage(100) to take 100 damage.
(NOTE: the takeDamage function will not take damage if the humanoid has a [[RBX.lua.ForceField (Object)|ForceField]]. Use this function for weapons instead of directly setting the health, to prevent spawnkillers)
(NOTE: the TakeDamage function will not take damage if the humanoid has a [[RBX.lua.ForceField (Object)|ForceField]]. Use this function for weapons instead of directly setting the health, to prevent spawn killers)


Functions can also return a value, which means they can be used instead of a constant (like a number) or a variable (covered below):
Functions can also return a value, which means they can be used instead of a constant (like a number) or a variable (covered below):
<pre>function <functionname>(<parameters>)
<pre>
<statements>
function <functionname>(<parameters>)
return <valueobtainedfromstatements>
    <statements>
 
    return <valueobtainedfromstatements>
end
end


Line 230: Line 235:


[[Concatenation|Example 1]]
[[Concatenation|Example 1]]
<pre>
<syntaxhighlight lang="lua">
function sayHello(name)
local function sayHello(name)
print("Hello, " .. name .. "!")
    print("Hello, " .. name .. "!")
end
end


sayHello("Bob")
sayHello("Bob")
</pre>
</syntaxhighlight>


Example 2
Example 2
<pre>
<syntaxhighlight lang="lua">
function addNumbers(a,b)
local function addNumbers(a, b)
ans = a + b
    local answer = a + b
return ans
    return answer
end
end


answer = addNumbers(1,2)
local answer = addNumbers(1, 2)
 
print(answer) --> Prints in the output 3
print(answer) --> Prints in the output 3


</pre>
</syntaxhighlight>
 
'''Functions that return values'''
<br>'''Functions that return values'''
Note the return statement in Example 2. The return statement automatically ends the function at that line, and then gives the value to the variable on the LEFT SIDE of the equals sign. Let's look at that again, this time with detailed comments:
Note the return statement in Example 2. The return statement automatically ends the function at that line, and then gives the value to the variable on the LEFT SIDE of the equals sign. Let's look at that again, this time with detailed comments:
<pre>
<syntaxhighlight lang="lua">
--Define a function called addNumbers with the arguments "a" and "b"
-- Define a function called addNumbers with the arguments "a" and "b"
function addNumbers(a,b)
local function addNumbers(a, b)
--make a variable called "ans", and set it to the sum of a and b.
    -- make a variable called "answer", and set it to the sum of a and b.
ans = a + b
    answer = a + b
--Return the variable called ans. This ends the function.
    -- Return the variable called answer. This ends the function.
return ans
    return answer
end
end


--Set a variable called "answer" to the return value (ans) of addNumbers, with the arguments 1 and 2.
-- Set a variable called "answer" to the return value (answer) of addNumbers, with the arguments 1 and 2.
answer = addNumbers(1,2)
local answer = addNumbers(1, 2)
 
print(answer) -- Prints in the output 3
print(answer) -- Prints in the output 3
</syntaxhighlight>


</pre>
=== Flow control ===
 
Flow control, or Control statements basically means doing different things depending on the situation. They can also control the way the code is executed in the end.  
===Flow control===
Flow control, or Control statments basically means doing different things depending on the situation. They can also control the way the code is executed in the end.  
There are two main ways to do it in Lua, both involve conditions.
There are two main ways to do it in Lua, both involve conditions.
====Conditions====
==== Conditions ====
A condition is a situation. A simple condition is this:
A condition is a situation. A simple condition is this:
<pre>1 == 2</pre>
<pre>1 == 2</pre>
Line 279: Line 284:


These are all of the conditions that you can use:
These are all of the conditions that you can use:


<pre>== Is equal to
<pre>== Is equal to
Line 289: Line 293:


A reminder about these conditions is you put the symbol first, and then the "=", although this doesn't apply to the less than, or greater than conditions.
A reminder about these conditions is you put the symbol first, and then the "=", although this doesn't apply to the less than, or greater than conditions.
 
==== If statements ====
====If statements====
The <b>if</b> statement does something only if a condition is true.
The <b>if</b> statement does something only if a condition is true.
Syntax:
Syntax:
<pre>
<pre>
if (<condition>) then
if (<condition>) then
<statements>
    <statements>
end
end
</pre>
</pre>
Example:
Example:
<pre>
<syntaxhighlight lang="lua" line>
if (2 + 2 == 4) then
if (2 + 2 == 4) then
print("All is right in the world")
    print("All is right in the world")
end
end
</pre>
</syntaxhighlight>
That would always print "All is right in the world", because 2 + 2 is always equal to 4.  
That would always print "All is right in the world", because 2 + 2 is always equal to 4.  


Line 309: Line 312:
<pre>  
<pre>  
if (<condition>) then
if (<condition>) then
<statements>
    <statements>
else
else
<statements>
    <statements>
end
end
</pre>
</pre>


Example:  
Example:  
<pre>  
<syntaxhighlight lang="lua" line>
if (2 + 2 == 4) then
if (2 + 2 == 4) then
print("All is right in the world")
    print("All is right in the world")
else
else
print("Warning! Warning! Computer Self-Destruction!")
    print("Warning! Warning! Computer Self-Destruction!")
end
end
</pre>
</syntaxhighlight>


====While====
====While====
<pre>
<pre>
while <condition> do
while <condition> do
<statements>
    <statements>
end
end
</pre>
</pre>
Line 334: Line 337:


Example:
Example:
<pre>
<syntaxhighlight lang="lua" line>
while true do
while true do
print("Lagging up your computer...")
    print("Lagging up your computer...")
wait(0.5)
 
    wait(0.5)
end
end
</pre>
</syntaxhighlight>
 
== See also ==
== See also ==
*[[Scripting]]
*[[Scripting]]
Line 351: Line 354:
*[[In-Depth_Scripting_Guide|In-Depth Scripting Guide]]
*[[In-Depth_Scripting_Guide|In-Depth Scripting Guide]]
*[[Tutorials]]
*[[Tutorials]]
[[Category:Scripting Tutorials]]
[[Category:Scripting Tutorials]]