diff options
author | daurnimator <quae@daurnimator.com> | 2018-02-04 15:10:25 -0800 |
---|---|---|
committer | daurnimator <quae@daurnimator.com> | 2018-02-04 15:15:18 -0800 |
commit | 794db77dc24902dd0928514f26b8f05220bc1758 (patch) | |
tree | 997a288397d9b77681978b7f404268f802b0735e | |
parent | d6891e1e0ab0eccd8df0cc316118696270703758 (diff) | |
download | fengari-794db77dc24902dd0928514f26b8f05220bc1758.tar.gz fengari-794db77dc24902dd0928514f26b8f05220bc1758.tar.bz2 fengari-794db77dc24902dd0928514f26b8f05220bc1758.zip |
src/lmathlib.js: Implement math.randomseed via a simple LCG
Closes #78
-rw-r--r-- | README.md | 1 | ||||
-rw-r--r-- | src/lmathlib.js | 22 |
2 files changed, 21 insertions, 2 deletions
@@ -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, |