Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If parameter isn't passed then use default

Tags:

c++

It just gives me "redaclaration of delay". How can I change this so that if delay is not passed to the call of doSay(text), the delay should be 1000, but if it's called as doSay(text, 9000), it should be a delay of 9000?

Here is what I tried, but it didn't work.

uint32_t delay = MINTICKS;
if (parameters > 1) {
    delay = std::max(delay, popNumber(L));
} else {
    uint32_t delay = 1000;
}

The code

int PersonInterface::luaActionSay(lua_State* L)
{
    //doSay(text, <optional> delay)
    int32_t parameters = lua_gettop(L);

    uint32_t delay = MINTICKS;
    if (parameters > 1) {
        delay = std::max(delay, popNumber(L));
    }

    std::string msg(popString(L));

    ScriptEnviroment* env = getScriptEnv();

    Person* person = env->getPerson();
    if(person){
        person->doSay(msg, delay);
    }

    return 0;
}
like image 972
Kaka Avatar asked Feb 16 '23 05:02

Kaka


1 Answers

To pass default parameters to a function, use this syntax in the function declaration:

void foo(int a, int b = 1000);

foo(42);       // calls foo(42, 1000);
foo(42, 9000); 

You can have an arbitrary number of default parameters, but cannot have non-default parameters to the right of a default one, so this is not legal:

void foo(int a, int b = 1000, int c);

but this is

void foo(int a, int b = 1000, int c = 42);

As for your re-declaration error, just don't declare delay again:

} else {
  delay = 1000;
}

or

delay = (parameters > 1) ?
        std::max(delay, popNumber(L)) :
        1000;
like image 94
juanchopanza Avatar answered Feb 18 '23 20:02

juanchopanza