lua怎么产生随机数?

请先 登录 后评论

2 个回答

冷红林
擅长:互联网

attachments-2018-08-N9GFidVo5b83d29e6ec23.png   需要注意的是,只有带FLOAT的LOD才支持该函数

请先 登录 后评论
技术销售Delectate
擅长:IT

有两个方式产生随机数:使用float lod或者使用rtos.tick()

如果开发者使用的是float lod,那么它是支持lua的math库。使用math.random()即可生成随机数;

如果开发者使用的是其他lod,则需要在代码中加入如下函数:


-- 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

调用:

random()

返回随机数。

请先 登录 后评论
  • 2 关注
  • 1 收藏,2868 浏览
  • qin0036 提出于 2018-08-27 18:28

相似问题