Last active
August 25, 2025 06:59
-
-
Save lazydao/ac7c1a8d6f20cf894154e8b93893cb4c to your computer and use it in GitHub Desktop.
Lua
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| -- 检查一个table是否为空 | |
| next(t) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment