Vice City: Multiplayer

Server Development => Scripting and Server Management => Topic started by: KAKAN on Sep 30, 2015, 06:21 PM

Title: random error
Post by: KAKAN on Sep 30, 2015, 06:21 PM
Heya,
So this is the random function:-
function random(min, max)
{
    return min + ((max - min + 1) * rand() / 32767).tointeger();
}

And here's the TextUpdater function:-
function TextUpdater()
{
                     local idx = random_msg[ random(0, random_msg.len() ) ];
                     ClientMessageToAll( idx[0], idx[1], idx[2], idx[3] );
}

Her's the random_msg
random_msg <- [
["Hey",255,255,255],
["Heya",255,255,255]
];

So the problem is with this line:-
                     local idx = random_msg[ random(0, random_msg.len() ) ];And the error is:-
the index 2 doesn't existWhen i change that line to:-
                     local idx = random_msg[ random(0, random_msg.len() - 1 ) ];It fixes the error, why?
And what was the problem before?
And why do we use -1 there?
Title: Re: random error
Post by: Thijn on Sep 30, 2015, 06:33 PM
An arrays index start with 0. So the first element will be given index 0.
When you get the length of that array (with one element: the first) it will return 1.
That's why you'd always have to use array.len() - 1 in order to get the latest element.
Title: Re: random error
Post by: KAKAN on Oct 01, 2015, 08:45 AM
That means it wouldn't affect my messages?
Title: Re: random error
Post by: Thijn on Oct 01, 2015, 04:52 PM
Quote from: KAKAN on Oct 01, 2015, 08:45 AMThat means it wouldn't affect my messages?
Nope.
Title: Re: random error
Post by: KAKAN on Oct 02, 2015, 05:59 AM
Okay! Thanks, solved, locked