aboutsummaryrefslogtreecommitdiff
path: root/src/rng.moon
blob: d7606f91e0e1f47a7e424be2d63fe35b9b44ddec (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
-- Contains pseudo-random number generators, and some helper functions

rng = {}
totally_random_seed = tonumber(os.date("%Y%H%M%S"))
math.randomseed(totally_random_seed)

-- same syntax as math.random, if m and n are passed, they are lower and upper bounds
-- if only m is passed, it is the upper bound
-- if neither is passed, between 0 and 1
-- Example:
--      local rng = require("rng")
--      local generator1 = rng.generator()
--      local random1 = generator1()
--      local generator2 = rng.generator()
--      local random2 = generator2()
--      assert(random1, random2)
rng.generator = (seed, m, n) ->
	seed = seed or tonumber(os.date("%Y%S"))
	co = coroutine.wrap(() ->
		while true
			math.randomseed(seed)
			if m and n
				seed = math.random(m,n)
			elseif m
				seed = math.random(m)
			else
				seed = math.random()
			coroutine.yield(seed)
	)
	co, seed

rng.randomstring = (charset, length) ->
	t = {}
	charset_len = #charset
	for i = 1, length
		char = math.random(charset_len)
		t[i] = charset\sub(char,char)
	table.concat(t)

rng.hexstring = (length) ->
	rng.randomstring("0123456789ABCDEF", length)

rng.numstring = (length) ->
	rng.randomstring("0123456789", length)

rng