From 794db77dc24902dd0928514f26b8f05220bc1758 Mon Sep 17 00:00:00 2001 From: daurnimator Date: Sun, 4 Feb 2018 15:10:25 -0800 Subject: src/lmathlib.js: Implement math.randomseed via a simple LCG Closes #78 --- README.md | 1 - src/lmathlib.js | 22 +++++++++++++++++++++- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index a70caf5..458269a 100644 --- a/README.md +++ b/README.md @@ -117,7 +117,6 @@ p(L); ## NYI -- `math.randomseed()` - `io.input()`: partially implemented - `io.lines()` - `io.open()` diff --git a/src/lmathlib.js b/src/lmathlib.js index 301aa02..665fbc4 100644 --- a/src/lmathlib.js +++ b/src/lmathlib.js @@ -36,9 +36,22 @@ const { } = require('./luaconf.js'); const { to_luastring } = require("./fengaricore.js"); +let rand_state; +/* use same parameters as glibc LCG */ +const l_rand = function() { + rand_state = (1103515245 * rand_state + 12345) & 0x7fffffff; + return rand_state; +}; +const l_srand = function(x) { + rand_state = x|0; + if (rand_state === 0) + rand_state = 1; +}; + const math_random = function(L) { let low, up; - let r = Math.random(); + /* use Math.random until randomseed is called */ + let r = (rand_state === void 0)?Math.random():(l_rand() / 0x80000000); switch (lua_gettop(L)) { /* check number of arguments */ case 0: lua_pushnumber(L, r); /* Number between 0 and 1 */ @@ -66,6 +79,12 @@ const math_random = function(L) { return 1; }; +const math_randomseed = function(L) { + l_srand(luaL_checknumber(L, 1)); + l_rand(); /* discard first value to avoid undesirable correlations */ + return 0; +}; + const math_abs = function(L) { if (lua_isinteger(L, 1)) { let n = lua_tointeger(L, 1); @@ -274,6 +293,7 @@ const mathlib = { "modf": math_modf, "rad": math_rad, "random": math_random, + "randomseed": math_randomseed, "sin": math_sin, "sqrt": math_sqrt, "tan": math_tan, -- cgit v1.2.3-70-g09d2