[LUA] 制作一个随机歌曲选择器

一直在试着通过水果占位符获取随机歌曲,但总是返回橙子,我似乎无法弄清楚为什么。

math.randomseed(os.time())
local songLists = {"Apple", "Orange", "Pineapple"}
local songValue = math.random(#songLists)
local songSelected = songLists[songValue]

print(tostring(songSelected))
点赞
用户12918181
用户12918181

Lua 使用 PRNG(伪随机数生成器)来计算随机数。

math.randomseed(os.time()) 用某种当前时间的数据初始化公式(不是最佳决策)。 os.time() 给出精度为1秒的当前时间,这意味着如果您在一秒钟内的循环内执行此代码,则会得到相同的种子号码(如果时钟未更改)。 最佳实践是在应用程序启动时使用更好的随机数据(如进程 ID、os.clock())来初始化随机 math.randomseed(...)

很可能你的问题是在这段代码或者应用程序的另一部分中多次执行 math.randomseed(...) 时使用了相同的种子数据。

2020-03-01 16:31:08