User:Merlin11188/Sandbox: Difference between revisions

From Legacy Roblox Wiki
Jump to navigationJump to search
>JulienDethurens
→‎Terminology: Used a definition list to list them. Revert if you prefer the old one, even though this one is the standard way to do it.
m Text replacement - "</SyntaxHighlight>" to "</syntaxhighlight>"
Tags: mobile web edit mobile edit
 
(6 intermediate revisions by 3 users not shown)
Line 1: Line 1:
{| style="{{border-radius|4px}}; background-color: #ffdddd; border: dashed 2px #aa0000; border-top-color: #ff0000; border-left-color: #ff0000; margin: auto 10px; padding: 2px; display: block"
{{User:Merlin11188/Templates/NoEdit}}
|{{ImageLink|image=ArrowSquare.png|link=User:Tomtomn00/Sandbox/NoEditTemplate}}
|<big>'''Do not edit!'''</big><br><small>The creator of this subpage does not want it to be edited without permission.</small>
|}
 
==Hello World==
==Hello World==


Line 28: Line 24:
===Terminology===
===Terminology===


There are three terms I want you to know before we continue:
There are four terms I want you to know before we continue:
<dl title="Terminology">
<dl title="Terminology">
<dt>code
<dt>code
Line 44: Line 40:
Before I start explaining the stuff you can do in Lua to you, there is something I need to explain to you that I'm going to use a lot in this tutorial: ''Commenting''. Comments are things that are '''not''' executed by Lua. A comment can contain any characters because it doesn't need to be read.  
Before I start explaining the stuff you can do in Lua to you, there is something I need to explain to you that I'm going to use a lot in this tutorial: ''Commenting''. Comments are things that are '''not''' executed by Lua. A comment can contain any characters because it doesn't need to be read.  


====[[Comments_(Scripting)#Single-line_Comments|One-Line Comments]]====
====[[Comments_(Scripting)#Single-line_Comments|Short Comments]]====


A one-line comment is made with {{`|--}}. It lasts for the rest of the line. Here are some examples:
A one-line comment is made with {{`|--}}. It lasts for the rest of the line. Here are some examples:
Line 54: Line 50:
|fit=output}}}}
|fit=output}}}}


====[[Comments_(Scripting)#Block_Comments|Multi-Line Comments]]====
====[[Comments_(Scripting)#Block_Comments|Long Comments]]====


A multi-line comment starts with {{`|<nowiki>--[[</nowiki>}} and ends with {{`|<nowiki>]]</nowiki>}}. Everything between the opening and the closing is treated as a comment, even if the comment is only in the middle of the line.  
A multi-line comment starts with {{`|<nowiki>--[[</nowiki>}} and ends with {{`|<nowiki>]]</nowiki>}}. Everything between the opening and the closing is treated as a comment, even if the comment is only in the middle of the line.  
Line 81: Line 77:
A [[Variable|variable]] is just a container. It holds a value. For a good understanding, please read the [[Variable|page on variables]] from sections [[Variable#Assignment|1]] to [[Variable#Swapping|3.1]], ignoring the section on Scope. We'll get to that later. Here are just some examples of variables:
A [[Variable|variable]] is just a container. It holds a value. For a good understanding, please read the [[Variable|page on variables]] from sections [[Variable#Assignment|1]] to [[Variable#Swapping|3.1]], ignoring the section on Scope. We'll get to that later. Here are just some examples of variables:


{{Example|<code lua>
{{Example|<syntaxhighlight lang="lua">
x = 3
x = 3
y = 4
y = 4
aVariable = 6
aVariable = 6
iHave134141NumbersInMyNameAndABooleanValue = true
iHave134141NumbersInMyNameAndABooleanValue = true
</code>}}
</syntaxhighlight>}}


Remember that saying {{`|<nowiki>variable = someValue</nowiki>}} is called ''declaring a variable''.
Remember that saying {{`|<nowiki>variable = someValue</nowiki>}} is called ''declaring a variable''.
Line 441: Line 437:


The most basic type of control structure is an {{`|if then}} statement. It's fairly self-explanatory: If the condition is true, then do stuff. If it isn't, then skip around. Here is the basic syntax for an {{`|if then}} statement:
The most basic type of control structure is an {{`|if then}} statement. It's fairly self-explanatory: If the condition is true, then do stuff. If it isn't, then skip around. Here is the basic syntax for an {{`|if then}} statement:
<code lua>
<syntaxhighlight lang="lua">
if condition then -- Create a new code block
if condition then -- Create a new code block
print("Hi")
print("Hi")
Line 447: Line 443:
-- Do other stuff
-- Do other stuff
end -- End the new code block. If condition is not truthy, then whatever is after this end is run.
end -- End the new code block. If condition is not truthy, then whatever is after this end is run.
</code>
</syntaxhighlight>


In the above, if {{`|condition}} is a ''truthy'' value (neither nil nor false), then what is in the code block is run. Else, whatever is after the end is run (in this case, nothing). Now, let's make condition an actual value and throw in some more stuff:
In the above, if {{`|condition}} is a ''truthy'' value (neither nil nor false), then what is in the code block is run. Else, whatever is after the end is run (in this case, nothing). Now, let's make condition an actual value and throw in some more stuff:

Latest revision as of 06:12, 27 April 2023

Do not edit!
The creator of this subpage does not want it to be edited without permission. Please discuss any changes that you think are relevant on the talk page.

Hello World

The language I'm teaching you is called Lua. A tradition of programming languages is to start off the learner with a Hello World program. So what is a Hello World program? It is a program that writes the words "Hello World" to the output. Here it is in Lua:

Example
Hello World
print("Hello World")


Ta-da! For now and the rest of the tutorial, that box on the right is the output. Keep that in mind. Print is our function for writing to the output. When we want to print string literals (words, like Hello World) to the output, we must put them in quotes. Here's another example:

Example
Hi Newcomer!
print("Hi Newcomer!")



Beginning

Terminology

There are four terms I want you to know before we continue:

code
Anything written in Lua.
chunk
One line of code in Lua.
script
Multiple chunks that accomplish a specific task in Lua.
character
Any of the ASCII values (numbers, letters, spaces, enter key, down arrow, etc).

Comments

Before I start explaining the stuff you can do in Lua to you, there is something I need to explain to you that I'm going to use a lot in this tutorial: Commenting. Comments are things that are not executed by Lua. A comment can contain any characters because it doesn't need to be read.

Short Comments

A one-line comment is made with --. It lasts for the rest of the line. Here are some examples:

Example
Hello world
print("Hello world") -- This will print Hello world to the output!
-- I'm invisible! print("Hi"). Hi won't be printed to the output!


Long Comments

A multi-line comment starts with --[[ and ends with ]]. Everything between the opening and the closing is treated as a comment, even if the comment is only in the middle of the line.

Example
Hello World
print("Hello World")--[[
I'm a very long comment.
In fact, I last multiple lines.
Should I be discovered, I must… but that won't happen.
]]


A multi-line comment cannot be placed inside of a string literal (inside of quotation marks)! You must put it elsewhere. Here are more examples:

Example
print("Hello M--[[I'll never be found!]]y Friend!")
--[[They'll never catch me!]]print("HI")

Hello M--I'll never be found!y Friend!

HI


There are also leveled comments, but I won't go into those. They're just like multi-line comments, except they have different levels. I never use them.

Variables

A variable is just a container. It holds a value. For a good understanding, please read the page on variables from sections 1 to 3.1, ignoring the section on Scope. We'll get to that later. Here are just some examples of variables:

Example
x = 3
y = 4
aVariable = 6
iHave134141NumbersInMyNameAndABooleanValue = true


Remember that saying variable = someValue is called declaring a variable.

Types and Values

Nil

For our intents and purposes, nil means nothing. If you really want an in-depth guide, read the page on nil. Here are some examples:

Example
nil
x1 = nil
x2 = nil
x3 = nil
x4 = nil
-- Yeah. Boring =P
print(x4) -- Want to print the value of a variable? print(VARIABLE NAME HERE)


Booleans

A boolean is a simple data type. It is either true or false—always. There are no exceptions. Here are some examples:

Example

true

false
bool = true
thisGuideIsntAwesome = false
thisGuideRocks = true
print(thisGuideRocks)
print(thisGuideIsntAwesome)


Numbers

A number is a data type that can hold a number. In Lua, unlike other languages, a number can transfer between any of the following types of numbers without any special functions:

  • Integer (no decimal point: 32
  • Floating-point (have a decimal point: 32.4
  • Hexadecimal (I wouldn't recommend using that if you don't know what it does. Example: 0xFFA3

Here are some examples:

Example

9123 1234122.1234

44978
num1 = 9123
num2 = 1234122.1234
num3 = 0xAFB2
print(num1)
print(num2)
print(num3)


Strings

A string is a data type that holds any {{`|characters}], with one exception: a single-line quote. Before we begin, a string literal is any string placed inside of what I will refer to as string marks in the following sections. When declaring a variable as a string, you will most likely declare it as a string literal.

One-Line Strings

The string marks for a one-line string are quotation marks (" " or ' '. Please use the double quotes, not the single quotes for strings. Here are some examples:

Example

Merlin11188 1/22/2012

Hi! How are you?
name = "Merlin11188"
dateWhenWritten = "1/22/2012"
greeting = "Hi! How are you?"
print(name)
print(dateWhenWritten)
print(greeting)


Multi-Line Strings

The string marks for a multi-line string are brackets ([[<--start. end -->]]). They can contain any and all characters. Please ignore the syntax highlighting (color of the text) in the following example; it's inaccurate.

Example

I'm a very long string that has multiple lines and takes up a lot of space.

I'm multiple lines,

but still relatively short!
longString = [[I'm a very
long string that
has multiple
lines and takes up
a lot of
space.
]]
otherLongString = [[I'm multiple lines,
but still relatively short!]]
print(longString)
print(otherLongString)


Much like leveled comments, you may also have leveled strings. They work in the exact same way, except they don't start with --.

Objects

Objects are more advanced data types, such as:

  • Tables
  • Functions
  • Threads
  • Userdatas

I'll go into those later.

Expressions

An expression is a chunk in Lua that manipulations a value through the use of operators.

Operators

An operator allows you to manipulate the value of a variable. Some examples of manipulation are addition, subtraction, and combining two strings. Yay! Useful things!

Arithmetic

The mathematical operators are:

  • +; to add two numbers
  • -; to subtract two numbers (or to get the opposite of a number)
  • *; to multiply two numbers
  • /; to divide two numbers
  • ^; to raise a number to an exponent
  • %; for the modulus of one number by another number

The modulus operator returns the remainder of division. So, 7 % 3 equals 1 because 7/3 = 2 r1. Here are some examples:

Example

8 14 12 4 16 1

0.5
x = 4
x = x*2
print(x)
x = x + 6
print(x)
x = x - 2
print(x)
x = x/3
print(x)
x = x^2
print(x)
x = x%5
print(x)
x = x/2
print(x)


Relational

Relational operators always return a boolean, true or false. There are six relational operators:

  • >; greater than
  • <; less than
  • >=; greater than or equal to
  • <=; less than or equal to
  • ==; equal to
  • ~=; not equal to

Remember from math class what those things do? No? Fine, then. Here are examples:

Example

false true false true false

false
w, x, y, z = 3, 4, 5, 3
print(w > x)
print(x < y)
print(y <= z)
print(w >= z)
print(w == x)
print(w ~= z)


Logical

All logical operators consider false and nil as false and anything else as true. There are three logical operators in Lua:

And

The and operator checks its first operand (the thing that comes before it); if its first operand is false or nil, and returns that operand's value. If its first operand is not false nor nil, then it returns the second operand's value (the value of the thing that comes after it). Here are some examples:

Example

true Hi false false

Hi
a, b, c, d = 1, true, false, "Hi"
print(a and b)
print(a and d)
print(b and c)
print(c and a)
print(b and d)


Or

The or operator checks if its first operand is not nil nor false; if it's not nil nor false then it returns that operand's value. Otherwise, it returns the second operand's value. Here are some examples:

Example

1 1 1 true true Hi 1 Hi

false
a, b, c, d = 1, true, false, "Hi"
print(a or b)
print(a or c)
print(a or d)
print(b or c)
print(b or d)
print(c or d)
print(c or a)
print(d or c)
print(c or c)


Not

The not operator, unlike the other logical operators always returns a boolean, true or false. if its only operand is nil or false, then true is returned. If its only operand is not nil nor false, then false is returned. Here are some examples:

Example

false false true

false
a, b, c, d = 1, true, false, "Hi"
print(not a)
print(not b)
print(not c)
print(not d)


Concatenation

The concatenation operator (..) appends one string onto another. In the case of one of the operands being a number, converts it to a string first. Here are some examples:

Example

Hello Hethere. llo He He who is happy is rich. there. he is! there.35

3535
x, y, z = "He", "llo ", "there."
print(x .. y)
print(x .. z)
print(y .. x)
print(x .. " who is happy is rich.")
print(z .. " he is!")
print(z .. 35)
print(35 .. 35)


Precedence

Precedence refers to the order in which operators are executed. When you have a math equation, like this:

3*4 + 2*9 - 7/9 % 3 + 4 * 5

what order does Lua do that in? Does it work it from right to left? (Hint: The result is 49.222222222222.) No. Lua doesn't. That's where precedence comes into play. Which one is evaluated first? Why, the operators are evaluated in the order from top to bottom of this chart:

^
not  - (unary)
*   /   %
+   -
..
<   >   <=  >=  ~=  ==
and
or

Note: Things inside of parentheses are evaluated first. (7 + 3)*2 will be 20, whereas 7 + 3*2 will be 13. Operators with the same precedence are evaluated from left to right. So, in the above equation, the first things to be evaluated is the 3*4, then the 2*9, then the 7/9, then the (7/9)%3, then the 4*5, and so on. As with all operators, you can put strings of operators together. Here are some examples:

Example
print(3*4 + 9/3 - 6%2^3/3 + 9 - 8 .. " is a number.")
print(6^3*3-48 .. " is a multiple of 100 and is equal to " .. 3 .. "*" .. 4 .. "*" .. 50 .. ".")

14 is a number.

600 is a multiple of 100 and is equal to 3*4*50.


Statements

In Lua, statements include assigning a value to a variable, control structures (which are talked about in this section), and function calls.

Variables, Scope, and Blocks

If you remember that section on variable scopes I told you not to read from earlier, you may recognize that the scopes page is that section. I think it does an excellent job of explaining, particularly the pictures. See the actual scope page for a more in-depth guide.


You should almost always use local variables. They are faster for more efficiency and it's easier to see where people are declaring them. Unless I have a good reason not to (I want a variable to be in the global scope), I will use local variables for the rest of this guide/reference. Here are some examples with scope:

Example

3 7 12 3 7 nil 3 nil

nil
-- Code block level 0
local a = 3 -- Visible to level 0 and higher
do -- Code block level 1
	local b = 7 -- Visible to level 1 and higher
	do -- Code block level 2
		local c = 12 -- Visible to level 2 and higher
		print(a)
		print(b)
		print(c)
	end -- Back to level 1
	print(a)
	print(b)
	print(c)
end -- Back to level 0
print(a)
print(b)
print(c)


Control Structures

Control structures are pieces of code that tell Lua what to do next. Normally, it goes from top to bottom, but that's what these are: they allow for the order to change. There are four basic types of control structures and one keyword:

if <condition> then statements

The most basic type of control structure is an if then statement. It's fairly self-explanatory: If the condition is true, then do stuff. If it isn't, then skip around. Here is the basic syntax for an if then statement:

if condition then -- Create a new code block
	print("Hi")
	print("Condition is truthy!")
	-- Do other stuff
end -- End the new code block. If condition is not truthy, then whatever is after this end is run.

In the above, if condition is a truthy value (neither nil nor false), then what is in the code block is run. Else, whatever is after the end is run (in this case, nothing). Now, let's make condition an actual value and throw in some more stuff:

Example

5 > 3

Hi!
local y, x = 5, 3

if y > x then
	print(y .. " > " .. x)
end
print("Hi!")


Remember that the relational operators always return a boolean? Saying if y > x then is the same as saying if 5 > 3 then, which evaluates to be true. But what if y is not greater than x? Then we have this scenario:

Example

--Nothing because 3 is not greater than 5.

Hi!
local y, x = 3, 5

if y > x then
	print(y .. " > " .. x)
end
print("Hi!")


Because 3 is not greater than 5, the code that said print(y .. " > " .. x) was never run. It was skipped right over, as was everything all the way down to the end.

Else statement

Note: You do not need an end for an else statement. You need it only for the if <condition> then statement.
The else statement is an add-on to the if <condition> then statement. The else statement specifies what happens when <condition> in if <condition> then statements is false. If an else is present, and the condition evaluates to be false, then, rather than skip down to the end, the if then statement skips to the else. Here is an example, using similar code to the above::

Example

3 < 5

Hi!
local y, x = 3, 5

if y > x then
	print(y .. " > " .. x)
else
	print(y .. " < " .. x)
	-- Do some other stuff
end
print("Hi!")


y is 3 and x is 5; therefore, if 3 > 5 then evaluates to be false, and it runs the code after the else up until the end.

elesif <condition> then statements

An elseif statement is exactly what it sounds like: a combination of the if then statement and else statement. It is a statement that is evaluated if the original if statement evaluates to false. Like the else statement, it does not need an end; however, unlike the else statement, you attach a condition to it. Here is an example:

Example

5 == 5

Hi!
local z, y, x = 5, 3, 5

if y > x then
	print(y .. " > " .. x)
elseif z == x then
	print(z .. " == " .. x)
elseif y < x then
	print(y .. " < " .. x)
else
	print("y must be greater than, equal to, or less than x, since it's a number...")
end
print("Hi!")


Notice how only the {{{1}}} got printed, not the 3 < 5. That's because once an if … elseif … else statement has found a condition that evaluates to be true (in this case, does 5 == 5), it stops evaluating and just jumps straight down to the end. The elseif y < x then statement wasn't even evaluated.

Loops