HI DEVS,
first sorry if the tittle sucks couldn’t think of a better one also this is my first tutorial so have mercy also in this tutorial i will tell you things very little coders know about.
1. continue
do you know what breaks are right they break the loop. well continue almost does the same thing except instead of breaking the loop it skips an iteration for example:
for i, v in pairs({1,2,3,4,5,6,7,8,9,0}) do
if v == 7 then
continue -- skips iteration
end
print(v)-- prints v or value of table
end
--the output would look like:
1
2
3
4
5
6-- as you can see it skips six to 8
8
9
0
note. that continue does not have parentheses
or ()
.
2. next
we all know what for
loops
are but did you know you could write them in a different way? here is the more used version:
for i, v in pairs({"lol", true}) do
end
here’s the less used version:
for i,v next, {"give","me","feed","back"}, nil do-- after the `next,` you put your table
-- your stuff here
end
note that next
does not need parentheses
or ()
also the nil is not needed.
3.and & or
yes i know you probably know what and
& or
are but did you know you could put them in variables. you probably seen it but probably never understood it. here’s an example on what a variable looks like with ors
& ands
:
local randomBool = math.random(1, 2) == 2 and true or false
the random bool will be equal true
if math.random(1, 2) == 2
that’s why there’s an and
. if you wanted randomBool
to be false
when math.random(1, 2) == 2
, you would add false after the and
.
But wait… how about the or
what’s that for well if math.random(1, 2) == 1
we need randomBool
to be equal to something that’s wen or
comes in, if the first part isn’t true then randomBool
will be equal what ever value comes after the or
.
4. shared
ever heard sharing is caring well we aren’t learning about that were learning about shared. here is what shared does that I didn’t steal from the devhub
.
A table that is shared across all scripts that share This serves the exact same purpose as _G .
here is an example how you would use it:
-- some script
shared.RandomTable = {"i", "have",-1,"brain","cell"}-- very random table i made
-- some other script
for i, v in next, shared.RandomTable, nil do
print(v)-- i have -1 brain cell
end
note. use module scripts please
5 too long…
Have you ever have that long if statement for example:
if player.team.name=="Green" or player.team.name=="Blue" or player.team.name=="Red" or player.team.name=="Pink" or player.team.name=="black" then
-- see how long it is
end
local onlyTeams = {
["Green"] = true,
["Blue"] = true,
["Red"] = true,
["Pink"] = true,
["black"] = true
}
if onlyTeam[player.Team.name] then
see how short it is
end
if not (player.Team.name == "white") do
-- you can do this too
end
-- note this is just an example