local mission1{"Jonny","Player1","Player2"}
How would I give money to everyone in the table?
I know you have to use something like:
for i
but I don’t understand that.
local mission1{"Jonny","Player1","Player2"}
How would I give money to everyone in the table?
I know you have to use something like:
for i
but I don’t understand that.
The for i, v in pairs
loop is a pretty cool loop, as it goes through everything inside a table in addition with 2 helpful variables: The i
& v
The i
would be known as the index, or the order of every object inside the loop
The v
would be considered as the value, or what object you’re looking for inside the loop
For your instance, we can use this loop along with game.Players:GetPlayers()
(Which returns a table of players) & check if the Player has leaderstats
to add Money or not
for i, v in pairs(game.Players:GetPlayers()) do
local leaderstats = v:FindFirstChild("leaderstats") --We should have a leaderstats object already parented inside each player, but we'll check to make sure
if leaderstats then
leaderstats.Money.Value += 10 --Adding money
end
end
You can loop through the table, make sure their in the server, and then increase their cash value.
local Players = game:GetService("Players")
local mission1 = {"Jonny","Player1","Player2"}
for _, name in pairs(mission1) do
if not Players:FindFirstChild(name) then
continue
end
Players[name].Currency.Value += 50
end
table.foreach(mission1, function(i, v)
local player = game.Players[v.Name]
local currentMoney = player:GetAttribute(“Money”)
player:SetAttribute(“Money”, currentMoney + 100)
end)
The i is the index of the table, Johnny is 1, Player1 is two and so on.
The v is the thing that’s next to the index, 1 is Johnny, 2 is Player1.
A for loop goes through every child in the table, let’s say I make a table with three fruits, a apple, orange and a pineapple. It would be called fruits = {“Apple”, “Orange”, “Pineapple”}
Let’s say I want to eat the apple, I would do
for number, name in pairs(fruits) do
if number == 1 then
print("Eating " … name)
end
end)
It would print Eating Apple because Apple is automatically number 1 in the table.
You can name it however you want, for i,v in pairs, for d,c in pairs, it dosen’t matter. You can also switch it to
if name == “Apple” then
print(name … " is " … index “st in the table.”)
It will print Apple is 1st in the table