summaryrefslogtreecommitdiff
path: root/src/rng.moon
blob: 2c995f2a46ac3f7682e2a6814a5a426ef7a2c888 (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
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
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