Currently, registering a printf/format
-like function in AngelScript is bothering. A workaround is using function overloads with parameters from less to more. I tried to modify the source code to implement variadic function support. This is the current version:
As you can see, the function is registered using int sumi(int …)
. The script can use sumi(100, 10, 1)
to invoke it, getting the result 111
(shown by the debugger). Once this is complete, maybe developer can register a format
function in declaration like format(const string&in fmt, ?&in …)
.
My current solution is adding a new flag IsVariadic
for function. Function with this flag will treat the last parameters as a special one, allowing any number of arguments of this type passed to the target function. The argument count is pushed to stack as the hidden first argument using PshC4
. This will be handled by a sightly modified asCGeneric
. The user code can use gen->GetArgCount()
and other interfaces to retrieve arguments.
For example, this is the C++ code of sumi_generic
in the above screenshot:
void sumi_generic(asIScriptGeneric* gen)
{
int result = 0;
int count = gen->GetArgCount();
for (int i = 0; i < count; ++i)
{
int val = (int)gen->GetArgDWord(i);
result += val;
}
gen->SetReturnDWord(result);
}
However, it seems that it needs some further consideration when playing with named arguments. Should allow that special parameter to have a name? Thus, given a function int func(int a, int b, int… args)
, we can probably write int result = func(args:1, args:2, args:3, a:0xA, b:0xB);
.