Absolute beginner's guide to scripting: Difference between revisions

From Legacy Roblox Wiki
Jump to navigationJump to search
>Mindraker
No edit summary
Fixing
 
(156 intermediate revisions by 20 users not shown)
Line 1: Line 1:
{{CatUp|Tutorials}}
{{CatUp|Tutorials}}
__TOC__
{{Outdated|reason=Windows XP screenshots.}}


==Introduction==
==Introducing ROBLOX Lua==
This tutorial shows how to do some basic scripting. It explains how to script in the simplest terms possible, and is designed for people with little or no experience with scripting.
This tutorial shows you how to do some basic scripting, or programming. However, you must follow instructions exactly.


==What is scripting?==
{{EmphasisBox/start|green}}'''Please Note:''' In order to learn scripting, you must '''do''' the actionsReading will not help that much. Actually '''FOLLOW''' the instructions. {{EmphasisBox/end}}
Scripting is a way to tell the game what to do.  However, computers can only understand commands if you tell them '''exactly''' what to do, in a specific code. ROBLOX [[RBX.lua.Script (Object)|Scripts]] are commands in a coding language called [[Lua_Help|Lua]]. Lua is not-so-hard to understand, depending on the way you want to use it.


==Your first script==
=== What is scripting? ===
Already you're about to make your very first script. We'll be executing the script from a place in ROBLOX Studio called the [[Scripting#Fundamentals|Command Bar]], which allows you to execute a single line of script instantly.
Scripting is a way to tell the computer what to do.  However, computers can only understand commands to do things if you tell them '''exactly''' what to do, in a specific code or language. ROBLOX  [[RBX.lua.Script (Object)|Scripts]] are commands in a coding language called [[Lua_Help|Lua]]. Lua is not-so-hard to understand, depending on the way you want to use it. Lua was made to be simple to read and easy to understand, along with being simple to put into games. Lua was '''not''' specifically designed for ROBLOX.  Instead, it was designed to be put into games ''like'' ROBLOX.  The Lua in ROBLOX is a version of 'normal' Lua that has been modified for ROBLOX.  We will be learning this modified version.


===Being specific===
{{EmphasisBox/start|red}}'''Please note:''' It's "Lua", not "LUA", because Lua is not an acronym.{{EmphasisBox/end}}
Let's make the most basic script:  a suicide script.  When it executes, it kills you.  Scripting is just giving commands to the computer.


How ''do'' you kill a player?  There are two ways to kill a character:  disconnect their Head from their Torso, or have their [[RBX.lua.Humanoid (Object)|Humanoid's]] health dropped to zero.  Don't worry what a [[RBX.lua.Humanoid (Object)|Humanoid]] is, we'll use the first method for right now.
A key addition to ROBLOX Lua is the ability to navigate a tree of objects in your game using a '''parent-child relationship''' between objects (sometimes called 'Instances' in ROBLOX Lua)


The game doesn't know whom to kill, until you specify the username of the person whom you want to kill.  Think of the structure of a ROBLOX game as a tree. The trunk is called "game".  Then there is a branch, called "Workspace".  Think of all the bricks as branches on that "Workspace" branch.  ([[RBX.lua.Part (Object)|Bricks]], by the way, are not stored by their position in the game. They are organized like leaves on the branches of this tree.) You are going to be a branch, called by your username, on the "Workspace" branch, on the "game" trunk.   
== Your first program ==
You are about to make your very first script - a script to kill yourself. There is multiple ways to execute (or run) code in ROBLOX, but you will be executing the script from a place in ROBLOX [[Studio]] called the [[Scripting#Fundamentals|command bar]]. The command bar allows you to execute a single line of script instantly in a blank [[place]]. The command bar will only run one line of code at a timeThe first thing we want to do, is to open up the command bar, which is in ROBLOX [[Studio]].   


[[Image:tree.png|A visual description of the ROBLOX game tree]]
{{TitledBox/start|heading=How do I open [[Studio]], and how do I enable the command bar?}}
*'''[[Novetus]]'''
*#Open "NovetusBootstrapper", located in the root of your Novetus directory.
*#Click "PLAY NOVETUS".
*#If you're editing an existing place, select your place from the place box. Otherwise, ignore this step.
*#Click the "Build" button.
*#You should then see this prompt pop up. If you're editing an existing place, click "Yes", otherwise, click no.
[[File:Novetus_build_confirmation.png]]


Note that both the Players and the Workspace branch has a branch named after a specific user "jediknightkrazy". That's because there are two branches named after you, your player, and your character.
*'''Enabling the Command Bar'''
::You can enable the command bar by going to: '''View > Toolbars > Command''' (if there is no check mark next to it). A text box will appear at the bottom of the software. You can insert code in there and it will execute.
{{TitledBox/end}}


===Translating to Lua===
=== Being specific ===
A script needs to be in a special coding language called [[Lua_Help|Lua]].
When you first create a script, you have to '''know what it is meant''' to do at '''exactly what time''' and '''under what conditions'''. For a script that kills your character it's pretty obvious what it needs to do: it kills you. Scripting is just giving commands to the computer, so you just need a line of code to do something to kill your character.
This section will walk you through translating a basic English command to Lua.


'''''Remember that scripts can break with just one letter or symbol being wrong.'''''


Here's our starting command:
How ''do'' you kill your character?  You need to set the [[RBX.lua.Humanoid (Object)|Humanoid's]] health to zero. A [[RBX.lua.Humanoid (Object)|Humanoid]] is one of the types of objects in ROBLOX Lua that controls player's health. There's many ways to set the health to zero, such as removing the character's head or specifically setting the health to zero. For now, we'll just remove the head.
<pre>Delete jediknightkrazy's head</pre>


Naturally, ROBLOX won't like that very much. Remember the tree from the last section? First we have to tell ROBLOX where to find "jediknightkrazy"
ROBLOX won't remove anything until told, so we need to navigate the tree structure of ROBLOX games to find the character's head and remove it.  The structure of a ROBLOX game is like a tree, and the trunk is a [[DataModel]] object called '''game'''.  There is a "branch" (known as a '''child''') called [[Workspace]].  Think of all the bricks in your game '''children''' on the Workspace children.  [[RBX.lua.Part (Object)|bricks]] are organized as more children of the workspace.  Your character is a child of the Workspace, and the Workspace is a child of '''game'''.


<pre>In the game, in the Workspace, there is jediknightkrazy's Head</pre>
[[Image:tree.png|A visual description of the ROBLOX game "family tree"]]


In Lua, you go down the tree like this by using a dot: (.)
Note that children of '''game''' are known as '''game services''', which provide functionality for your game automatically. When you enter any place, you have a [[Player]] object named after you inside the [[Players]] game service and a model named after you in the Workspace (called a character). Your character holds your head, torso, limbs and other visual stuff. The player object does other things that won't be covered right now.


<pre>delete game.Workspace.jediknightkrazy.Head</pre>
ROBLOX Studio has a nice tool that lets you view the family tree visually. It is called the [[Explorer#The_Explorer_and_Properties_Bar,Explorer window]]. To open it, click View > Explorer. It is very self explanatory.


This is almost a working statement. Now, to actually delete the head, a ''function'' must be used. To use a function, just type a colon (:) after the object you want to execute it on (in this case, Head), and then the function you want to use, which in this case, is "Remove". Then, put a pair of parentheses after the function name.
===Writing Lua code===


<pre>game.Workspace.jediknightkrazy.Head:Remove()</pre>
The ultimate trick to being a scripter is to mastering how to make code that does what you want, when you want it. Since you are a beginner, you will be walked through the steps to making your code do what you want starting from English to Lua code. Do not think of scripting as translating to a language; think of scripting as giving orders on what to do.


If your name isn't jediknightkrazy, substitute your name for mine:
Here's our starting command. It's what we want to happen, and it has been written in plain English.


<pre>game.Workspace.SomeGuy.Head:Remove()</pre>
<pre>Remove USERNAME's head.</pre>


To experiment a bit, try deleting the Torso instead.
Naturally, ROBLOX will not like that very much because it's in English! You have to figure out how to express what you want to happen in Lua code.


===Testing the script===
<pre>In game, find Workspace, find USERNAME, find his Head, and remove it.</pre>
Open ROBLOX Studio and click File > New. Add a baseplate and a spawn.


To add a baseplate: Click Insert in the game window, NOT in the menu. Select "Free Models" in the drop down list at the right of the screen. Type "baseplate" and click Search. Add one that looks good. 
'''game''' is the root of all things in your game. We need to "go down" the family tree and find the right brick to remove. To get an object that is a child of another object this, you use a period ('''.''') after the parent object, then the child object's name. Going through the family tree, we get this:


To add a spawn: Select "Game Objects" in the drop-down list and click on a grey (neutral) spawn. + 
<pre>Delete game.Workspace.USERNAME.Head</pre>
Now, in the menu, click Tools > Test > Visit Solo. This is where you can test your places without uploading them! + 
Once it loads, right click in the Toolbar and check Command if it isn't checked already. A small textbox bar labelled "Command" should appear at bottom of the screen. In there, type:
<pre>game.Workspace.Player.Head:Remove()</pre>  
 
Don't replace Player with your username in Test mode, because your name is always "Player" in Test mode.
Type it, don't just copy and paste! 
Hit enter. If your head vanishes and you die, you've done it! You've made your first script. 
Now, try your Torso. Try removing the Baseplate; it's called "Base".


==Setting values and making objects==
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.
What about actually changing the value of an object, as opposed to removing an object?  Earlier it was mentioned that there were two ways to kill someone. The more complicated way is setting one's Health to 0.  The Health is contained in a [[RBX.lua.Humanoid (Object)|Humanoid]] object, which is contained within the character (Player.Humanoid.Health).  


Example:
<syntaxhighlight lang="lua">
<pre>game.Workspace.Player.Humanoid.Health</pre>
workspace.USERNAME.Head:Destroy()
However, what about setting a value?  In Lua, you set a value with the = sign. Put what you want to set on the left, and what you want to set it to on the right:
</syntaxhighlight>
<pre>game.Workspace.Player.Humanoid.Health = 0</pre>
 
Type it in the command bar like before, and you should be able to kill yourself without beheading yourself.
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:


==Getting a script in your place==
<syntaxhighlight lang="lua">
To make a script in [[Roblox_Studio|ROBLOX Studio]], just click Insert>Object...>Script, then you've got a script you can edit in your own place.  To learn how to make useful scripts, I recommend trying to read an existing script, like a Reset Tool or a deadly block.  Try modifying it to do different things.
workspace.AwesomeSocks.Head:Destroy()
</syntaxhighlight>


===Adding a script===
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.
Remember to use [[Roblox_Studio|ROBLOX Studio]], '''NOT''' "build", or [[Solo_mode|"solo"]] to edit your scripts.  Just click on Insert > Object, then double-click on Script.
=== Testing the script ===
[[Image:Insertscript.JPG]]
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.
<br>
This script will execute as soon as your place loads, so none of the killing scripts from last tutorial are going to work in your place.


'''IMPORTANT:''' When a script encounters an error, it stops running, or ''breaks''. So, if only half of your script gets run, there's a good chance that there's a problem somewhere in the middle.
'''NOTE: You must open build mode or solo mode from the studio, if you open it from the browser, you will not be able to open the command bar.'''


===Editing a script in ROBLOX Studio===
If your head just disappeared and you heard an "Oughh!" sound because your character just died, then you have succeeded. Your script works.
To edit a script, find it in the Explorer window: [[Image:Explorerwindow.JPG|none]]<br> and double-click on it.  Now it should open up a text editor that says
<pre>print("Hello World")</pre>
"What does 'print()' do?".  Print() simply prints that line into the Output Window.  To show it, click View > Output. Click the [http://wiki.roblox.com/index.php?title=Image:Play.JPG Play] button in toolbar and look in the Output Window.


===Testing your script===
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.
To test, open the Test mode as described before. This time, don't type anything in the Command bar. They should run automatically.
== 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.


== Script Creation ==
<syntaxhighlight lang="lua">
workspace.USERNAME.Humanoid.Health = 0
</syntaxhighlight>


There are 5 topics that will be answered here:
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.


* Creating the Script
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.


* Tagging Objects
<syntaxhighlight lang="lua">
workspace.USERNAME.Humanoid.Health = 0
</syntaxhighlight>


* The Listening Event
== 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.
[[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]]


* The Function
=== 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.


* Modifying Objects/Tags
=== Starting and Stopping your script ===
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'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 ==
There are 5 topics that will be answered here:
* Creating the script
* Storing references to objects
* Listening to events
* Functions
* Modifying objects


NOTE: All work, building and scripting, should be done in Edit Mode. All these lessons will be shown as if you are in Edit Mode. To open Edit Mode, on your desktop screen, hit Start>Programs>ROBLOX>ROBLOX Studio. Then go to your profile, then click "Edit".  
NOTE: All work, building and scripting, should be done in Edit Mode. All these lessons will be shown as if you are in Edit Mode. To open Edit Mode, on your desktop screen, hit Start>Programs>ROBLOX>ROBLOX Studio. Then go to your profile, then click "Edit". You can also press CTRL+N or click File>New to get a completely empty place.


=== Creating the Script ===
=== Creating the Script ===


To get a script go in Roblox Studio or Solo Mode 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 the browser should look a bit more like Microsoft Word. 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.


=== Tagging Objects ===
=== Making References to Objects ===


Assuming the script is still under '''Workspace''', that is where your script will run. Let's say you want a brick turning invisible/visible, back and forth when touched. The script needs to know where that brick is before modifying it.
Assuming the script is still under '''Workspace''', that is where your script will run. Let's say you want a brick turning invisible/visible, back and forth when touched. The script needs to know where that brick is before modifying it.


Now, tagging objects are not necessary, but it can make scripting a lot less work. Here's an example of tagging objects:  
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:  
 
<pre>brick = game.Workspace.Brick</pre>


That will tag the brick under the name you assigned. You can set the name to absolutely '''anything'''. You can have as many tags as you want.  
<syntaxhighlight lang="lua">
local brick = workspace.Brick
</syntaxhighlight>


If you didn't tag it, every time you try making the script modify the object, you would have to put the line "game.Workspace.Brick" every single time. Tags are much simpler, since you would only have to put the name you assigned. Name the brick desired to "Brick", and tag it in the script by typing the example above. Note that tagging 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.


=== The Listening Event ===
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 ===
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.  
An event listener watches what's going on, and waits for an event to happen. When it does, it tells the script to do something. This is one important part of the script, otherwise you couldn't really make scripts wait for anything.  


A listening event is the trigger of the script. This is going to tell the script to do something if the listener finds the trigger fired. This is one important part of the script, otherwise you couldn't really make scripts wait for anything.
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 tag in it. We're going to make the script listen for being touched. Here's an example:  
<syntaxhighlight lang="lua">
brick.Touched:connect(onTouched)
</syntaxhighlight>


<pre>brick.Touched:connect(onTouch)</pre>
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.
 
If the brick is Touched, it will connect the (function). 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 141: 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 "brick.Touched:connect(onTouch)" a line or two below the tag    "brick = game.Workspace.Brick"
Put the line
 
<syntaxhighlight lang="lua">
=== The Function ===
brick.Touched:connect(onTouched)
 
</syntaxhighlight>
a line or two below the variable assignment
<syntaxhighlight lang="lua">
local brick = Workspace.Brick
</syntaxhighlight>
=== 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">
<pre>function onTouch(part)
local function onTouched(part)


end  
end  
</pre>
</syntaxhighlight>
There is the function. As you can see, the function has "onTouch". 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 after "onTouch". This is the tag of the object that the listener found that touched the brick. This is not always needed, especially for different listeners. Most times, with other listening types unlike touching listeners, you would just place this:
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.
<pre>
function onTouch()


end
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.  
</pre>
But back to what we're looking at. The tag 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 aspect of scripting, such as "if" statements. Always remember this when scripting.  


Now, make the lines from first example, except put it two lines under the tag, 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 ===
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.  


=== Modifying Objects/Tags ===
This is where storing references to objects saves you time. We wanted it to flicker invisible/visible, so here's an example:
<syntaxhighlight lang="lua">
brick.Transparency = 1


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.
wait(1)


This is where tagging objects saves you time. We wanted it to flicker invisible/visible, so here's an example:
<pre>
brick.Transparency = 1
wait(1)
brick.Transparency = 0  
brick.Transparency = 0  
</pre>
</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 ===
=== Complete script ===
<syntaxhighlight lang="lua" line>
local brick = workspace.Brick -- Store a reference to the brick.


<pre>
local function onTouched(part) -- The function that runs when the part is touched.
brick = game.Workspace.Brick --tagging the brick
brick.Transparency = 1


function onTouch(part) --the function
wait(1)


brick.Transparency = 1 --what the function is to do with the brick
wait(1)
brick.Transparency = 0  
brick.Transparency = 0  
end  
end  


brick.Touched:connect(onTouch) --listening event
brick.Touched:connect(onTouched) -- The line that connects the function to the event.
</pre>  
</syntaxhighlight>
 
== Advanced scripting techniques ==
 
=== Make your own functions ===
==Advanced scripting techniques==
 
===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>(<args>)
<pre>
<statements>
local function <functionname>(<parameter>)
    <statements>
end
end


<functionname>(<arguments>)
<functionname>(<parameters>)


</pre>
</pre>


An argument is a way to give data to a function. An example of an argument: 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>(<args>)
<pre>
<statements>
local function <functionname>(<parameters>)
return <valueobtainedfromstatements>
    <statements>
 
    return <valueobtainedfromstatements>
end
end


Line 221: 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 basically means doing different things depending on the situation.  
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 269: Line 283:
That would be true, because 1 is less than 2.
That would be true, because 1 is less than 2.


====If statements====
These are all of the conditions that you can use:
 
<pre>== Is equal to
< Less than
> Greater than
<= Less than, or equal to
>= Greater than or equal to
~= Not equal to</pre>
 
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 ====
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 288: 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 313: 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 ==
<br>[[Scripting]]
*[[Scripting]]
<br>[[Class reference|The Class Reference]]  
*[[Class reference|The Class Reference]]  
<br>[[Edit]]
*[[Edit]]
<br>[[Roblox Studio]]
*[[Roblox Studio]]
<br>[[Script]]
*[[Script]]
<br>[[RBX.lua.Workspace (Service)|Workspace]]
*[[RBX.lua.Workspace (Service)|Workspace]]
<br>[[Scripting]]
*[[Scripting]]
<br>[[Beginner%27s_Guide_to_Advanced_Scripting|Beginner's Guide to Advanced Scripting]]
*[[In-Depth_Scripting_Guide|In-Depth Scripting Guide]]
<br>[[In-Depth_Scripting_Guide|In-Depth Scripting Guide]]
*[[Tutorials]]
<br>[[Tutorials]]
 
[[Category:Scripting Tutorials]]
[[Category:Scripting Tutorials]]

Latest revision as of 03:34, 27 April 2023

Information Outdated Page
This article has outdated information. Please update this page to fit our current standards!

Specifically: Windows XP screenshots.


Introducing ROBLOX Lua

This tutorial shows you how to do some basic scripting, or programming. However, you must follow instructions exactly.

Please Note: In order to learn scripting, you must do the actions. Reading will not help that much. Actually FOLLOW the instructions.

What is scripting?

Scripting is a way to tell the computer what to do. However, computers can only understand commands to do things if you tell them exactly what to do, in a specific code or language. ROBLOX Scripts are commands in a coding language called Lua. Lua is not-so-hard to understand, depending on the way you want to use it. Lua was made to be simple to read and easy to understand, along with being simple to put into games. Lua was not specifically designed for ROBLOX. Instead, it was designed to be put into games like ROBLOX. The Lua in ROBLOX is a version of 'normal' Lua that has been modified for ROBLOX. We will be learning this modified version.

Please note: It's "Lua", not "LUA", because Lua is not an acronym.

A key addition to ROBLOX Lua is the ability to navigate a tree of objects in your game using a parent-child relationship between objects (sometimes called 'Instances' in ROBLOX Lua)

Your first program

You are about to make your very first script - a script to kill yourself. There is multiple ways to execute (or run) code in ROBLOX, but you will be executing the script from a place in ROBLOX Studio called the command bar. The command bar allows you to execute a single line of script instantly in a blank place. The command bar will only run one line of code at a time. The first thing we want to do, is to open up the command bar, which is in ROBLOX Studio.

How do I open Studio, and how do I enable the command bar?
  • Novetus
    1. Open "NovetusBootstrapper", located in the root of your Novetus directory.
    2. Click "PLAY NOVETUS".
    3. If you're editing an existing place, select your place from the place box. Otherwise, ignore this step.
    4. Click the "Build" button.
    5. You should then see this prompt pop up. If you're editing an existing place, click "Yes", otherwise, click no.

  • Enabling the Command Bar
You can enable the command bar by going to: View > Toolbars > Command (if there is no check mark next to it). A text box will appear at the bottom of the software. You can insert code in there and it will execute.

Being specific

When you first create a script, you have to know what it is meant to do at exactly what time and under what conditions. For a script that kills your character it's pretty obvious what it needs to do: it kills you. Scripting is just giving commands to the computer, so you just need a line of code to do something to kill your character.

Remember that scripts can break with just one letter or symbol being wrong.

How do you kill your character? You need to set the Humanoid's health to zero. A Humanoid is one of the types of objects in ROBLOX Lua that controls player's health. There's many ways to set the health to zero, such as removing the character's head or specifically setting the health to zero. For now, we'll just remove the head.

ROBLOX won't remove anything until told, so we need to navigate the tree structure of ROBLOX games to find the character's head and remove it. The structure of a ROBLOX game is like a tree, and the trunk is a DataModel object called game. There is a "branch" (known as a child) called Workspace. Think of all the bricks in your game children on the Workspace children. bricks are organized as more children of the workspace. Your character is a child of the Workspace, and the Workspace is a child of game.

A visual description of the ROBLOX game "family tree"

Note that children of game are known as game services, which provide functionality for your game automatically. When you enter any place, you have a Player object named after you inside the Players game service and a model named after you in the Workspace (called a character). Your character holds your head, torso, limbs and other visual stuff. The player object does other things that won't be covered right now.

ROBLOX Studio has a nice tool that lets you view the family tree visually. It is called the Explorer#The_Explorer_and_Properties_Bar,Explorer window. To open it, click View > Explorer. It is very self explanatory.

Writing Lua code

The ultimate trick to being a scripter is to mastering how to make code that does what you want, when you want it. Since you are a beginner, you will be walked through the steps to making your code do what you want starting from English to Lua code. Do not think of scripting as translating to a language; think of scripting as giving orders on what to do.

Here's our starting command. It's what we want to happen, and it has been written in plain English.

Remove USERNAME's head.

Naturally, ROBLOX will not like that very much because it's in English! You have to figure out how to express what you want to happen in Lua code.

In game, find Workspace, find USERNAME, find his Head, and remove it.

game is the root of all things in your game. We need to "go down" the family tree and find the right brick to remove. To get an object that is a child of another object this, you use a period (.) after the parent object, then the child object's name. Going through the family tree, we get this:

Delete game.Workspace.USERNAME.Head

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.

workspace.USERNAME.Head:Destroy()

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:

workspace.AwesomeSocks.Head:Destroy()

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

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 command bar. Type your one-lined wonder in, and hit enter to run it.

NOTE: You must open build mode or solo mode from the studio, if you open it from the browser, you will not be able to open the command bar.

If your head just disappeared and you heard an "Oughh!" sound because your character just died, then you have succeeded. Your script works.

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

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.

workspace.USERNAME.Humanoid.Health = 0

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.

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.

workspace.USERNAME.Humanoid.Health = 0

Inserting a Script object

To add a new script in ROBLOX Studio, just click Insert > Object... > Script. You'll find a blank script that has been added to the Workspace.

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.

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.

Starting and Stopping your script

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'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

There are 5 topics that will be answered here:

  • Creating the script
  • Storing references to objects
  • Listening to events
  • Functions
  • Modifying objects

NOTE: All work, building and scripting, should be done in Edit Mode. All these lessons will be shown as if you are in Edit Mode. To open Edit Mode, on your desktop screen, hit Start>Programs>ROBLOX>ROBLOX Studio. Then go to your profile, then click "Edit". You can also press CTRL+N or click File>New to get a completely empty place.

Creating the Script

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 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

Assuming the script is still under Workspace, that is where your script will run. Let's say you want a brick turning invisible/visible, back and forth when touched. The script needs to know where that brick is before modifying 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:

local brick = workspace.Brick

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

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.

An event listener watches what's going on, and waits for an event to happen. When it does, it tells the script to do something. This is one important part of the script, otherwise you couldn't really make scripts wait for anything.

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:

brick.Touched:connect(onTouched)

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. Here is a very well-done reference page set up by MrDoomBringer.

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

brick.Touched:connect(onTouched)

a line or two below the variable assignment

local brick = Workspace.Brick

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.

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:

local function onTouched(part)

end

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.

Now, make the lines from first example, except put it two lines under the variable assignment, and one line above the listener.

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.

This is where storing references to objects saves you time. We wanted it to flicker invisible/visible, so here's an example:

brick.Transparency = 1

wait(1)

brick.Transparency = 0

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 "local function onTouched(part)" and above the line "end".

Complete script

local brick = workspace.Brick -- Store a reference to the brick.

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

	wait(1)

	brick.Transparency = 0 
end 

brick.Touched:connect(onTouched) -- The line that connects the function to the event.

Advanced scripting techniques

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 [:])

local function <functionname>(<parameter>)
    <statements>
end

<functionname>(<parameters>)

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 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):

local function <functionname>(<parameters>)
    <statements>

    return <valueobtainedfromstatements>
end

<somevariable> = <functionname>(<args>)

Copy and paste these codes into a script for a better example:

Example 1

local function sayHello(name)
    print("Hello, " .. name .. "!")
end

sayHello("Bob")

Example 2

local function addNumbers(a, b)
    local answer = a + b
    return answer
end

local answer = addNumbers(1, 2)

print(answer) --> Prints in the output 3

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:

-- Define a function called addNumbers with the arguments "a" and "b"
local function addNumbers(a, b)
    -- make a variable called "answer", and set it to the sum of a and b.
    answer = a + b
    -- Return the variable called answer. This ends the function.
    return answer
end

-- Set a variable called "answer" to the return value (answer) of addNumbers, with the arguments 1 and 2.
local answer = addNumbers(1, 2)

print(answer) -- Prints in the output 3

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. There are two main ways to do it in Lua, both involve conditions.

Conditions

A condition is a situation. A simple condition is this:

1 == 2

(Note the "==". Always use that, and not "=".) Of course 1 isn't 2! So that would be false.

1 < 2

That would be true, because 1 is less than 2.

These are all of the conditions that you can use:

== Is equal to
< Less than
> Greater than
<= Less than, or equal to
>= Greater than or equal to
~= Not equal to

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

The if statement does something only if a condition is true. Syntax:

if (<condition>) then
    <statements>
end

Example:

if (2 + 2 == 4) then
    print("All is right in the world")
end

That would always print "All is right in the world", because 2 + 2 is always equal to 4.

There is also an else statement, which executes if the condition is false:

 
if (<condition>) then
    <statements>
else
    <statements>
end

Example:

if (2 + 2 == 4) then
    print("All is right in the world")
else
    print("Warning! Warning! Computer Self-Destruction!")
end

While

while <condition> do
    <statements>
end

This does something over and over until the condition is false, or the break command is executed. People typically don't use this unless they want a never-ending loop, in which case their condition is true, and the loop will not terminate. Here is something very important: If this is an infinite loop, you MUST put a wait() function in your loop! Otherwise your computer/server will take every ounce of it's processing power to execute the code, because right when it's done, it wants to execute again. This WILL crash the server. This will make it wait so it has time to execute other things, and not crash.

Example:

while true do
    print("Lagging up your computer...")

    wait(0.5)
end

See also