First Lua Coding

Scripting is important for Roblox games. Roblox uses Lua, a programming language that has been popular for creating games. It’s first important to understand how we place programs in the game.

DON’T JUST READ THIS. OPEN STUDIO AND TRY EACH STEP.

Parent and Child Relationships

All the objects inside of your game are listed in the Explorer. If you drop an object on another object, the dropped object will go underneath and to the right a bit. This makes the object above the parent, or the one that is in charge. Add two Parts and drop one on top.

You’ll see that if you move Part 1 that Part 2 moves as well. Part 2 is the Child, doing what the Parent says. Part 1 is the child of the Workspace. Anything with a “V” next to it is a parent.

Placing a Script

Delete the child Part. Then right click the remaining Part. Add an Object called a Script. It looks like a piece of paper. A screen with some code will pop up. The code says to display the words “Hello world!” 

Press Play and see the phrase in the Output. This happened because the Part used the Script to say the words. You can change the words to whatever you want. Try it!

 

Variables

Variables are words or numbers that can store other words or numbers. You can change variables with your code. For example, a NumberOfSwords variable in a game can hold the number 2. Then when you sell it, NumberOfSwords is changed to one. Think of it kind of like the memory of your brain.

There are 3 main types of variables: Numbers, Strings, and Booleans.

Numbers are… numbers! Strings are words and must have these ” around them. Booleans is simply True and False. Make this code in your game.

Press play. What did it print out? Did it print the word spoons, word and fun? No, it printed what the variables stored!

Ok, so lets make a variable called swords and potions. Set swords =4 and potions = 3.

Then use the command:

print (“I have ” .. (swords + potions) .. ” items in my inventory.”)

Press Play and find out how many items you have. See how variables can be useful for things like inventory or counting coins or calculating health?

Creating an Object with Code

Code can do anything, even create objects. You can write code to make an object without putting it in the Explorer yourself.

Put this in the code:

newObject = Instance.new(“Part”)
newObject.Parent = Workspace
newObject.Name = “Oof”

Press play and open the Explorer. Your code created a Part named Oof!

newObject = Instance.new(“Part”)
newObject.Parent = Workspace
newObject.Name = “Oof”

Instance.new is a command to create which you then tell it the name of the type of object you want to create. To place it in the game and inside the explorer, you use the name of the newObject to access data about it, like .Parent or .Name to assign what these are going to be. You’ll notice this newObject part only exists when the game runs. That’s because the code creates it!

QuizzesStatus