Skip to content

Commit 3e3d208

Browse files
committed
Fixed 4984: (Lua math.randomseed() gets stuck with large numbers)
Signed-off-by: ccw808 <ccw808@googlemail.com>
1 parent 60dc246 commit 3e3d208

File tree

3 files changed

+22
-2
lines changed

3 files changed

+22
-2
lines changed

src/lapi.c

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -334,6 +334,21 @@ LUA_API lua_Integer lua_tointeger (lua_State *L, int idx) {
334334
}
335335

336336

337+
LUA_API lua_Integer lua_tointegerW (lua_State *L, int idx) {
338+
TValue n;
339+
const TValue *o = index2adr(L, idx);
340+
if (tonumber(o, &n)) {
341+
lua_Integer res;
342+
lua_Number num = nvalue(o);
343+
num = fmod( num, 0x7fffffff ); // Wrap the number between -2,147,483,647 and 2,147,483,647
344+
lua_number2integer(res, num);
345+
return res;
346+
}
347+
else
348+
return 0;
349+
}
350+
351+
337352
LUA_API int lua_toboolean (lua_State *L, int idx) {
338353
const TValue *o = index2adr(L, idx);
339354
return !l_isfalse(o);

src/lmathlib.c

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -206,8 +206,12 @@ static int math_random (lua_State *L) {
206206

207207

208208
static int math_randomseed (lua_State *L) {
209-
srand(luaL_checkint(L, 1));
210-
return 0;
209+
// lua_tointegerW wraps out of range numbers (luaL_checkint clips values below -1^32 and above 1^32)
210+
srand(lua_tointegerW(L, 1));
211+
// Do some rands here, as the first few results bear a close relationship to the seed number
212+
rand();
213+
rand();
214+
return 0;
211215
}
212216

213217

src/lua.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,7 @@ LUA_API int (lua_lessthan) (lua_State *L, int idx1, int idx2);
153153

154154
LUA_API lua_Number (lua_tonumber) (lua_State *L, int idx);
155155
LUA_API lua_Integer (lua_tointeger) (lua_State *L, int idx);
156+
LUA_API lua_Integer (lua_tointegerW) (lua_State *L, int idx);
156157
LUA_API int (lua_toboolean) (lua_State *L, int idx);
157158
LUA_API const char *(lua_tolstring) (lua_State *L, int idx, size_t *len);
158159
LUA_API size_t (lua_objlen) (lua_State *L, int idx);

0 commit comments

Comments
 (0)