If the parameter is not passed, use the default value

It just gives me a โ€œfix delayโ€. How can I change this so that if the delay was not passed to the doSay(text) call, the delay should be 1000, but if it is called doSay(text, 9000) , it should be a 9000 delay?

Here is what I tried, but it did not work.

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

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; } 
+4
source share
1 answer

To pass default parameters to a function, use this syntax in a 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 they cannot have non-default parameters to the right of the default value, so this is not legal:

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

but this

 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; 
+8
source

Source: https://habr.com/ru/post/1486168/


All Articles