• 欢迎大家分享资料!前往留言板评论即可!

【Lua】如何生成随机数

合宙 模组资料网 2年前 (2021-05-15) 334次浏览 0个评论 扫描二维码

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

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

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

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


调用方法:

print(random())

转载请注明原文链接:【Lua】如何生成随机数
喜欢 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址