Lua随机选取表中元素&处理

本文介绍了在 Lua 编程中如何随机选取表中的元素,包括使用 math.randomseed 和 table库的方法,讨论了随机选取单个元素以及批量随机选取的实现方式,帮助开发者更好地理解和应用 Lua 的随机处理功能。
摘要由CSDN通过智能技术生成
mapmonsters{
  {
  mapid = 150404,
  monsters = {
  
   {monsterId = 100402, weight = 147},
   {monsterId = 100403, weight = 147},
   {monsterId = 100404, weight = 147},
   {monsterId = 100406, weight = 147},
   {monsterId = 100405, weight = 147},
   {monsterId = 100502, weight = 5},
   {monsterId = 100503, weight = 5},
   {monsterId = 100504, weight = 5},
   
  }
 },
}

math.randomseed(tostring(os.time()):reverse():sub(1, 6)) -- 随机种子


function offline_random_monster(x)
 totalWeight = 0
 tempRate = {}
 bingo = 0


 -- 处理权重
 for i=1, table.getn(mapmonsters) do
  if mapmonsters[i].mapid == x then -- 找到了地图
   bingo = i;
   for j = 1, table.getn(mapmonsters[i].monsters) do
    totalWeight = totalWeight + mapmonsters[i].monsters[j].weight
    table.insert(tempRate, totalWeight)
   end
  end
 end


 keynum = math.random(totalWeight) -- 保存
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值