Interesting little tidbit- math.random
Posted: 23 Aug 2009, 08:15
Just a little bit of random programmer lore I thought I'd share with folks, so that maybe they can avoid the newbie trap I hit yesterday:
Math.Random using a low range of floats can cause an error in synced code. I.E., math.random(-0.3,0.3) will result in an error, where Lua reports an "empty interval" and ends the program.
This is due to Spring's handling of math.random, which is as follows:
Anyhow, it appears that math.random can only return integers, so if you need a fairly wide range of numbers between -1.0 and 1.0, you can avoid it with simple math like this:
Which, given Lua's un-typed handling of variables, will by default return a float value between 1.000000 and -1.000000.
So, if you've been doing anything on the assumption that math.random's results are a float, such as using max, min or floor... there isn't a need, apparently, unless you're performing operations on it afterwards and need it to become an integer or something.
Just thought I'd throw that out there for folks, feel free to correct my terminology, etc., if I didn't write a sufficiently-clear explanation of what's going on programmatically.
Math.Random using a low range of floats can cause an error in synced code. I.E., math.random(-0.3,0.3) will result in an error, where Lua reports an "empty interval" and ends the program.
This is due to Spring's handling of math.random, which is as follows:
Code: Select all
else if ((args == 2) && lua_isnumber(L, 1) && lua_isnumber(L, 2)) {
const int lower = (int)lua_tonumber(L, 1);
const int upper = (int)lua_tonumber(L, 2);
if (lower >= upper) {
luaL_error(L, "Empty interval in math.random() {synced}");
}
const float diff = (upper - lower);
const float r = gs->randFloat(); // [0,1], not [0,1) ?
int value = lower + (int)(r * (diff + 1));
value = max(lower, min(upper, value));
lua_pushnumber(L, value);
}
Code: Select all
local myVariable = math.random(-100,100)
myVariable = myVariable / 100
So, if you've been doing anything on the assumption that math.random's results are a float, such as using max, min or floor... there isn't a need, apparently, unless you're performing operations on it afterwards and need it to become an integer or something.
Just thought I'd throw that out there for folks, feel free to correct my terminology, etc., if I didn't write a sufficiently-clear explanation of what's going on programmatically.