【Lua】如何生成随机数

众所周知,为了性能考虑,模块的默认底层是不支持float的,那么如果此时希望使用math库生成随机数怎么办呢?

#使用Float LOD
只有float lod才支持math库,所以开发者可以使用带Float字样的lod,或者带8955F字样的lod(202F/268F);
但是请注意,这个lod可能带来某种程度的性能下降;

#使用rtos.tick()生成伪随机数
废话不多说,上代码:

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
-- luat math lib

require "bit"
module(..., package.seeall)

local seed = tonumber(tostring(os.time()):reverse():sub(1, 7)) + rtos.tick()

function randomseed(val)
seed = val
end

function random()
local next = seed
next = next * 1103515245
next = next + 12345
local result = (next / 65536) % 2048

next = next * 1103515245
next = next + 12345
result = result * 2 ^ 10
result = bit.bxor(result, (next / 65536) % 1024)

next = next * 1103515245
next = next + 12345
result = result * 2 ^ 10
result = bit.bxor(result, (next / 65536) % 1024)

seed = next
return result
end


调用方法:

1
print(random())

上次更新 2021-01-28