RandomUtil = {} --根据权重随机词条数量 function RandomUtil.random_weighted(weight_str, count) local result = {} if count <= 0 then return result end local num = string.split(weight_str, "|") local weight_total = 0 for _, value in pairs(num) do local sum = string.split(value, "#") weight_total = weight_total + tonumber(sum[2]) end local random_weight = math.random(1, weight_total) local cumulative_weight = 0 for _, value in pairs(num) do local sum = string.split(value, "#") local weight = tonumber(sum[2]) cumulative_weight = cumulative_weight + weight if cumulative_weight >= random_weight then table.insert(result, tonumber(sum[1])) if table.count(result) == count then return result end end end end -- 示例:"1#80|2#10|3#10" -- 80%的概率选中1 -- 10%的概率选中2 -- 80%的概率选中3 function RandomUtil.selectKey(configStr) local results = RandomUtil.random_weighted(configStr, 1) local num = results[1] return num; end