I think I've found a bug in math.clamp(). While documenting it, I found that it behaves very weirdly. Looking at the source code, it looks like the algorithm (lines 126-127) has some typos/mixups which make the output weird. The solution would be to change the code to the following:
- Code: Select all
static naRef f_clamp(naContext c, naRef me, int argc, naRef* args)
{
naRef min = naNumValue(argc > 0 ? args[0] : naNil());
naRef max = naNumValue(argc > 1 ? args[1] : naNil());
naRef x = naNumValue(argc > 2 ? args[2] : naNil());
if(naIsNil(min) || naIsNil(max) || naIsNil(x))
naRuntimeError(c, "non numeric arguments to clamp()");
if (x.num < min.num)
x.num = min.num;
else if (x.num > max.num)
x.num = max.num;
return VALIDATE(x);
}
This fixes the algorithm and renames variables a and b to min and max to make it clearer.
Reagrds,
Red Leader
P.S. If someone could forward this to the mailing list, it would be greatly appreciated.