<aside> 💡 How can you manipulate a lua table?

</aside>

local table = table

--Copy everything in 't' to a new table.
---@param t table
---@return table
function table.copy(t)
  local nt = {}
  for k, v in pairs(t) do
    if type(v) == 'table' then
      nt[k] = table.copy(v)
    else
      nt[k] = v
    end
  end
  return nt
end

-- Add a new element at the end of table 't'.
---@param t table
---@param element any
function table.add(t, element)
  t[#t + 1] = element
end

-- Get element count of table 't'.
---@param t table
---@return number
function table.count(t)
  local count = 0
  for _ in pairs(t) do
    count = count + 1
  end
  return count
end

function table.tostring(tbl, key, lines)
  key = key and key..':' or ''
  lines = lines or {}
  lines[#lines + 1] = key .. '{'
  for k, v in pairs(tbl) do
    if type(v) == 'table' then
      table.tostring(v, k, lines)
    else
      lines[#lines + 1] = tostring(k) .. ':' .. tostring(v)
    end
  end
  lines[#lines + 1] = '}'
  return table.concat(lines, ' ')
end

---@param map table<number, any>
---@return any[]
function table.map_to_list(map)
  local list = {}
  for k, v in pairs(map) do
    list[#list + 1] = v
  end
  return list
end

---@param list any[] @value array
---@param key any[] @key array
---@return table<number, any>
function table.list_to_map(list, key)
  local map = {}
  for k, v in pairs(list) do
    map[v[key] or k] = v
  end
  return map
end
function math.get_list_random_order(list, length)
  local size = length and math.min(length, #list) or #list
  local count = 1
  local old_list = { table.unpack(list) }
  local new_list = {}
  while count <= size do
    local index = math.random(1, #old_list)
    new_list[count] = old_list[index]
    table.remove(old_list, index)
    count = count + 1
  end
  return new_list
end

给出一组概率,获得一个基于此组概率值的 index


---@param list number[] list of probability
---@return number index of list, error if zero
function math.get_random_index_with_probability(list)
  local total_value = 0
  for _, v in ipairs(list) do
    total_value = total_value + v
  end

  if total_value == 0 then return 0 end
  local random_value = math.random(total_value)

  for index, v in ipairs(list) do
    if random_value <= v then
      return index
    end
    random_value = random_value - v
  end

  return 0
end