mirror of
https://github.com/appgurueu/modlib.git
synced 2024-11-26 01:03:46 +01:00
Add table.deepset; alias table.nilget to deepget
This commit is contained in:
parent
530360474a
commit
494d109833
30
table.lua
30
table.lua
@ -1,5 +1,6 @@
|
|||||||
-- Localize globals
|
-- Localize globals
|
||||||
local assert, ipairs, math, next, pairs, rawget, rawset, setmetatable, string, table, type = assert, ipairs, math, next, pairs, rawget, rawset, setmetatable, string, table, type
|
local assert, ipairs, math, next, pairs, rawget, rawset, setmetatable, select, string, table, type
|
||||||
|
= assert, ipairs, math, next, pairs, rawget, rawset, setmetatable, select, string, table, type
|
||||||
|
|
||||||
-- Set environment
|
-- Set environment
|
||||||
local _ENV = {}
|
local _ENV = {}
|
||||||
@ -43,11 +44,30 @@ function set_case_insensitive_index(table)
|
|||||||
end
|
end
|
||||||
|
|
||||||
--+ nilget(a, "b", "c") == a?.b?.c
|
--+ nilget(a, "b", "c") == a?.b?.c
|
||||||
function nilget(value, key, ...)
|
function nilget(value, ...)
|
||||||
if value == nil or key == nil then
|
local n = select("#", ...)
|
||||||
return value
|
for i = 1, n do
|
||||||
|
if value == nil then return nil end
|
||||||
|
value = value[select(i, ...)]
|
||||||
end
|
end
|
||||||
return nilget(value[key], ...)
|
return value
|
||||||
|
end
|
||||||
|
|
||||||
|
deepget = nilget
|
||||||
|
|
||||||
|
--+ `deepset(a, "b", "c", d)` is the same as `a.b = a.b ?? {}; a.b.c = d`
|
||||||
|
function deepset(table, ...)
|
||||||
|
local n = select("#", ...)
|
||||||
|
for i = 1, n - 2 do
|
||||||
|
local key = select(i, ...)
|
||||||
|
local parent = table
|
||||||
|
table = parent[key]
|
||||||
|
if table == nil then
|
||||||
|
table = {}
|
||||||
|
parent[key] = table
|
||||||
|
end
|
||||||
|
end
|
||||||
|
table[select(n - 1, ...)] = select(n, ...)
|
||||||
end
|
end
|
||||||
|
|
||||||
-- Fisher-Yates
|
-- Fisher-Yates
|
||||||
|
Loading…
Reference in New Issue
Block a user