summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authordaurnimator <quae@daurnimator.com>2018-02-04 15:10:25 -0800
committerdaurnimator <quae@daurnimator.com>2018-02-04 15:15:18 -0800
commit794db77dc24902dd0928514f26b8f05220bc1758 (patch)
tree997a288397d9b77681978b7f404268f802b0735e
parentd6891e1e0ab0eccd8df0cc316118696270703758 (diff)
downloadfengari-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.md1
-rw-r--r--src/lmathlib.js22
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,