随机数

基本类型 / 数字 / 整型

-- Both ends included
local rand = math.random(0, 2)
local rand_ok = rand >= 0 and rand <= 2
-- rand_ok = true

-- One argument n means 1..n
local rand2 = math.random(3)
local rand2_ok = rand2 >= 1 and rand2 <= 3
-- rand2_ok = true

-- A random element: an index in 1..#list
local list = {"red", "green", "blue"}
local rand3 = list[math.random(#list)]
local rand3_ok = rand3 ~= nil
-- rand3_ok = true

-- The same seed gives the same numbers
math.randomseed(42)
local first = math.random(100)
math.randomseed(42)
local second = math.random(100)
local same = first == second
-- same = true

print("rand_ok = " .. tostring(rand_ok))
print("rand2_ok = " .. tostring(rand2_ok))
print("rand3_ok = " .. tostring(rand3_ok))
print("same = " .. tostring(same))

-- An empty interval is an error
local ok, err = pcall(math.random, 3, 1)
-- ok = false
-- err = bad argument #1 to 'math.random'
-- (interval is empty)
print("ok = " .. tostring(ok))
print("err = " .. err)