random error

Started by KAKAN, Sep 30, 2015, 06:21 PM

Previous topic - Next topic

KAKAN

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?
oh no

Thijn

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.

KAKAN

That means it wouldn't affect my messages?
oh no

Thijn

Quote from: KAKAN on Oct 01, 2015, 08:45 AMThat means it wouldn't affect my messages?
Nope.

KAKAN

Okay! Thanks, solved, locked
oh no