Array, And Foreach Function

Started by FarisDon, Sep 29, 2015, 05:39 AM

Previous topic - Next topic

FarisDon

players <- []; // That's a Array as you guys know!
foreach(a,val in players) // But what is that ??? I found it often! in scripts
{
Basically i just want to know the function of players/anyname <-[] this array plus Foreach(a, val in players ) May you just explain me these 2 things, so i'll really appreciate you!( What does they do, and how)
P.s: Sorry, for my bad english, and it's a request to  you S.L.C If you are gonna explain, so in easy words please!

Thijn

It's actually pretty straightforward.
When you have, let's say, 2 elements in that array. You can loop through it using the foreach statement. Which like it's name suggests, does something for each element.
The syntax is basically foreach( index, value in array ).
In our case, the array has 2 elements. Let's say:
players[0] = "Test 1";
players[1] = "Test 2";

When you do a foreach like this:
foreach( index, value in players ) {
print("Index: " + index + ", value: " + value);
}
It will print:
QuoteIndex 0, value: Test 1
Index 1, value: Test 2

Debian

#2
'foreach' '(' [index_id','] value_id 'in' exp ')' stat
Foreach is a loop executes a statement for every element contained in an array, table, class, string or generator.

local a=[10,23,33,41,589,56]
foreach(idx,val in a){
    print("index="+idx+" value="+val+"\n");
}
or
foreach(val in a){
    print("value="+val+"\n");
}

He made his script complex this makes it easy to understand

foreach(val in players){
    print("value="+val+"\n");
}

If you look closely there will be a players.push( players.id ) and players.remove( player.id ) which will add player id to array when he joins and remove player id when he leaves.

Murdock

Quote from: Debian on Sep 29, 2015, 03:09 PM'foreach' '(' [index_id','] value_id 'in' exp ')' stat
Foreach is a loop executes a statement for every element contained in an array, table, class, string or generator.

You said exactly the same as @Thijn already said...

Thijn

Quote from: Debian on Sep 29, 2015, 03:09 PM'foreach' '(' [index_id','] value_id 'in' exp ')' stat
Foreach is a loop executes a statement for every element contained in an array, table, class, string or generator.
...
It's nice you take the time to explain something but:
1. Don't do it when it's already been explained.
2. Say the same thing.
3. Try to give an easier example and then fail to actually tell what it does.