Merge: Srand by default
authorJean Privat <jean@pryen.org>
Mon, 17 Nov 2014 22:55:32 +0000 (17:55 -0500)
committerJean Privat <jean@pryen.org>
Mon, 17 Nov 2014 22:55:32 +0000 (17:55 -0500)
Some people found that it is not KISS nor POLA to have `rand` that is not random by default.

So let's just call `srand` during the init of Sys.

Pull-Request: #916
Reviewed-by: Lucas Bajolet <r4pass@hotmail.com>
Reviewed-by: Alexis Laferrière <alexis.laf@xymus.net>

examples/shoot/src/shoot_logic.nit
lib/mnit/mnit_injected_input.nit
lib/standard/math.nit
src/interpreter/naive_interpreter.nit

index 838c78b..824af57 100644 (file)
@@ -1052,6 +1052,7 @@ end
 
 fun headless_run
 do
+       srand_from 0
        print "Headless run"
        # Only run the playscene
        var scene = new PlayScene(80000,60000)
index 4ed9664..a72b34d 100644 (file)
@@ -78,6 +78,8 @@ redef class App
                var env = "MNIT_SRAND".environ
                if env != "" then
                        srand_from(env.to_i)
+               else
+                       srand_from(0)
                end
 
                var input = "MNIT_READ_INPUT".environ
index 5a980aa..2bbb6aa 100644 (file)
@@ -178,7 +178,31 @@ redef class Collection[ E ]
        end
 end
 
+redef class Sys
+       init
+       do
+               srand
+       end
+end
+
 fun atan2(x: Float, y: Float): Float is extern "kernel_Any_Any_atan2_2"
 fun pi: Float is extern "kernel_Any_Any_pi_0"
+
+# Initialize the pseudo-random generator with the given seed.
+# The pseudo-random generator is used by the method `rand` and other to generate sequence of numbers.
+# These sequences are repeatable by calling `srand_from` with a same seed value.
+#
+# ~~~~
+# srand_from(0)
+# var a = 10.rand
+# var b = 100.rand
+# srand_from(0)
+# assert 10.rand == a
+# assert 100.rand == b
+# ~~~~
 fun srand_from(x: Int) is extern "kernel_Any_Any_srand_from_1"
+
+# Reinitialize the pseudo-random generator used by the method `rand` and other.
+# This method is automatically invoked at the begin of the program, so usually, there is no need to manually invoke it.
+# The only exception is in conjunction with `srand_from` to reset the pseudo-random generator.
 fun srand is extern "kernel_Any_Any_srand_0"
index 86bba5f..2879ac9 100644 (file)
@@ -1046,6 +1046,9 @@ redef class AMethPropdef
                        return v.native_string_instance(txt)
                else if pname == "get_time" then
                        return v.int_instance(get_time)
+               else if pname == "srand" then
+                       srand
+                       return null
                else if pname == "srand_from" then
                        srand_from(args[1].to_i)
                        return null