Skip to content

Instantly share code, notes, and snippets.

@lazydao
Last active May 20, 2022 03:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lazydao/ac7c1a8d6f20cf894154e8b93893cb4c to your computer and use it in GitHub Desktop.
Save lazydao/ac7c1a8d6f20cf894154e8b93893cb4c to your computer and use it in GitHub Desktop.
Lua集子
local function pick(rules, count, random_func)
random_func = random_func or math.random
count = count or 1
local ret = {}
local total_weight = 0
for _, v in ipairs(rules) do
local weight = v.weight
total_weight = total_weight + weight
end
if total_weight <= 0 then
return
end
local index
for i=1, count do
local rd = random_func(total_weight)
for k, rule in ipairs(rules) do
local weight = rule.weight
if rd <= weight then
table.insert(ret, rule)
index = k
break
else
rd = rd - weight
end
end
end
return ret, index
end
local rules = {
{
id=1,
weight=6000
},
{
id=2,
weight=3000
},
{
id=3,
weight=1000
}
}
pick(rules, 1)
  • next(t) 可以用来检查一个table是否为空
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment