Skip to content
This repository was archived by the owner on Jan 19, 2021. It is now read-only.

Commit b36a11a

Browse files
committed
Fixed math.randomseed() can't handle double values
- math.randomseed(os.time()) was seeding like math.randomseed(0) - added unit tests
1 parent 154530a commit b36a11a

File tree

3 files changed

+23
-5
lines changed

3 files changed

+23
-5
lines changed

Diff for: KopiLua/src/lmathlib.cs

+10-2
Original file line numberDiff line numberDiff line change
@@ -205,8 +205,16 @@ private static int MathRandom (LuaState L) {
205205

206206

207207
private static int MathRandomSeed (LuaState L) {
208-
//srand(luaL_checkint(L, 1));
209-
rng = new Random(LuaLCheckInt(L, 1));
208+
// math.randomseed() can take a double number but Random expects an integer seed.
209+
// we use modulus to bring back the double to the allowed integer interval.
210+
LuaNumberType seed = Math.Abs(LuaLCheckNumber(L, 1));
211+
LuaNumberType max = (LuaNumberType)int.MaxValue;
212+
while (seed > max)
213+
{
214+
seed = fmod(seed, max);
215+
}
216+
217+
rng = new Random((int)seed);
210218
return 0;
211219
}
212220

Diff for: KopiLua/src/luaconf.cs

+1-2
Original file line numberDiff line numberDiff line change
@@ -1137,8 +1137,7 @@ public static int strlen(CharPtr str)
11371137

11381138
public static lua_Number fmod(lua_Number a, lua_Number b)
11391139
{
1140-
float quotient = (int)Math.Floor(a / b);
1141-
return a - quotient * b;
1140+
return a - Math.Floor(a / b) * b;
11421141
}
11431142

11441143
public static lua_Number modf(lua_Number a, out lua_Number b)

Diff for: tests/core.cs

+12-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@
22
using System;
33
using NUnit.Framework;
44
using System.IO;
5-
using KopiLua;
5+
using KopiLua;
6+
using System.Text;
67

78
namespace Tests.iOS
89
{
@@ -184,6 +185,16 @@ public void OSLib()
184185

185186
// Test for os.difftime giving result in seconds.
186187
AssertString(st1 + "\n" + st2 + "\nassert(os.difftime(t2, t1) == 30)");
188+
}
189+
190+
[Test]
191+
public void MathLib()
192+
{
193+
// Test for math.random() giving different values after init with math.randomseed(os.time()).
194+
AssertString("local s1 = os.time({year=2015, month=5, day=28, hour=15, min=50, sec=48})\nlocal s2 = s1 + 1\nmath.randomseed(s1)\nmath.random()\nmath.random()\nlocal n1 = math.random()\nmath.randomseed(s2)\nmath.random()\nmath.random()\nlocal n2 = math.random()\nprint(tostring(n1) .. ',' .. tostring(n2))\nassert(n1 ~= n2)");
195+
196+
// Test for math.random() giving same values for math.randomseed(42).
197+
AssertString("math.randomseed(42)\nmath.random()\nmath.random()\nlocal n1 = math.random()\nmath.randomseed(42)\nmath.random()\nmath.random()\nlocal n2 = math.random()\nprint(tostring(n1) .. ',' .. tostring(n2))\nassert(n1 == n2)");
187198
}
188199
}
189200
}

0 commit comments

Comments
 (0)