Skip to content

Instantly share code, notes, and snippets.

@bofm
Created June 10, 2019 17:26
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bofm/70766566ecd4edee76f8f17ffa7362c9 to your computer and use it in GitHub Desktop.
Save bofm/70766566ecd4edee76f8f17ffa7362c9 to your computer and use it in GitHub Desktop.
lua flatten table
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
@JlnWntr
Copy link

JlnWntr commented Mar 27, 2024

This is not working (with lua 5.4)?
I tried:

local test1 = {{1}, 2, {3, {4}}}
local test2 = flatten(test1)

for i=1, #test2 do --Test
    print(test2[i])
end

The returned table is empty.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment