Created
June 10, 2019 17:26
-
-
Save bofm/70766566ecd4edee76f8f17ffa7362c9 to your computer and use it in GitHub Desktop.
lua flatten table
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local function noop(...) | |
return ... | |
end | |
-- convert a nested table to a flat table | |
local function flatten(t, sep, key_modifier, res) | |
if type(t) ~= 'table' then | |
return t | |
end | |
if sep == nil then | |
sep = '.' | |
end | |
if res == nil then | |
res = {} | |
end | |
if key_modifier == nil then | |
key_modifier = noop | |
end | |
for k, v in pairs(t) do | |
if type(v) == 'table' then | |
local v = flatten(v, sep, key_modifier, {}) | |
for k2, v2 in pairs(v) do | |
res[key_modifier(k) .. sep .. key_modifier(k2)] = v2 | |
end | |
else | |
res[key_modifier(k)] = v | |
end | |
end | |
return res | |
end | |
return flatten |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is not working (with lua 5.4)?
I tried:
The returned table is empty.