blockgame/mods/bg_api/util_table.lua
trans_soup 5a3d81787c add several utility functions related to tables.
create api functions `any`, `every`, and `underride`.

`any` and `every` checks if a condition is true for any and every item
in a table, respectively.
`underride` returns a table that defaults to a provided table, for
items that aren't specified in the other provided table.
2023-10-17 11:19:55 +02:00

51 lines
1 KiB
Lua

function blockgame.get_keys (tab)
local keyset = {}
local n = 0
for key, value in pairs(tab) do
n = n + 1
keyset[n] = key
end
return keyset
end
function blockgame.shallow_copy_table (tab)
local result = {}
for key, value in pairs(tab) do
result[key] = value
end
return result
end
function blockgame.shuffle (tab)
local keys = blockgame.get_keys(tab)
local result = {}
while #keys > 0 do
local index = math.random(1, #keys)
local key = table.remove(keys, index)
table.insert(result, tab[key])
end
return result
end
function blockgame.any (tab, check)
for key, value in pairs(tab) do
if check(value, key, tab) then return true end
end
return false
end
function blockgame.every (tab, check)
for key, value in pairs(tab) do
if not check(value, key, tab) then return false end
end
return true
end
function blockgame.underride (tab, template)
local tab = tab or {}
local result = blockgame.shallow_copy_table(template)
for key, value in pairs(tab) do
result[key] = value
end
return result
end