如何在ROBLOX Lua中制作加权RNG? (如CS:GO案例)

时间:2014-11-10 23:48:43

标签: lua roblox

说我有一张像这样的表:

skins = {desert_camouflage = 10, forest_camouflage = 20}

“desert_camouflage”的加权比“forest_camouflage”稀少。

我正在搜索一个Rbx.Lua RNG函数,它会打印出它的结果。

2 个答案:

答案 0 :(得分:1)

我不这么认为,但自己写得很容易:

function(weights)
  local sum = 0
  for _, v in next, weights do
    if v < 0 or math.floor(v) ~= v then
      error "Weights must be non-negative integers"
    end
    sum = sum + v
  end
  sum = math.random(sum)
  for k, v in next, weights do
    sum = sum - v
    if sum <= 0 then
      return k
    end
  end
  error "Should not happen."
end

答案 1 :(得分:0)

试试我的解决方案:

function weighted_random (weights)
    local summ = 0
    for i, weight in pairs (weights) do
        summ = summ + weight
    end
    if summ == 0 then return end
    local value = math.random (summ)
    summ = 0
    for i, weight in pairs (weights) do
        summ = summ + weight
        if value <= summ then
            return i, weight
        end
    end
end