Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 15 additions & 5 deletions libs/table.lua
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,7 @@ end
---at.
---@param tbl table
---@param value any
---@return any|nil
---@return any
function ext_table.search(tbl, value)
for k, v in pairs(tbl) do
if v == value then
Expand Down Expand Up @@ -313,29 +313,39 @@ function ext_table.shuffle(tbl)
return tbl
end

---Returns a random key, value index from an array.
---Returns a random (key, value) pair selected from the sequence portion of a table, or `nil` on an empty array.
---
---This function only works on the sequence portion of the table. Its behavior is undefined if the table has holes.
---@param tbl table
---@return any, any
function ext_table.randomipair(tbl)
if #tbl == 0 then
return
end
local i = math.random(#tbl)
return i, tbl[i]
end

---Returns a random key, value index from an array.
---Returns a random value selected from a table, or `nil` on an empty table.
---@param tbl table
---@return any, any
function ext_table.randomvalue(tbl)
local values = ext_table.values(tbl)
if #values == 0 then
return
end
return values[math.random(#values)]
end

---Returns a random key, value index from a table.
---Returns a random (key, value) pair selected from a table, or `nil` on an empty table.
---@param tbl table
---@return any, any
function ext_table.randompair(tbl)
local rand = math.random(ext_table.count(tbl))
local count = ext_table.count(tbl)
if count == 0 then
return
end
local rand = math.random(count)
local n = 0
for k, v in pairs(tbl) do
n = n + 1
Expand Down