How to flatten a table in Lua 5.3+
Page 1 of 1 • Share
How to flatten a table in Lua 5.3+
This is a code I used for our game. It flattens a table and returns an associative table that maps a string key to its value.
Kita mo yung resources sa log ng Counter Strike? Parang ganun.
So eto na siya:
Tell me kung may ganitong function na or optimal method. I made it in a few minutes and honestly hindi pa na u-unit test. However no bugs have been discovered yet that came from this function so far xD
- Example:
- For example, for this table
- Code:
local assets = {
images = {
guilty_kiss = 'res/images/gk01.png';
nico = 'res/images/nico_yazawa.png';
};
shaders = {
vert = {
simple = 'res/shaders/simple.vert.glsl';
};
frag = {
simple = 'res/shaders/simple.frag.glsl';
}
};
}
You'll get something as if you did the following:- Code:
local flattened_table = {
assets.images.guilty_kiss = 'res/images/gk01.png';
assets.images.nico = 'res/images/nico_yazawa.png';
assets.shaders.vert.simple = 'res/shaders/simple.vert.glsl';
assets.shaders.frag.simple = 'res/shaders/simple.frag.glsl';
}
Kita mo yung resources sa log ng Counter Strike? Parang ganun.
So eto na siya:
- Code:
local flatten
do
local function _flatten(r, pr, ks, it, t, k, v)
if v == nil then
-- we're done
if #ks == 0 then return r end
-- unpack saved state (for ver 5.3 below just 'unpack')
it, t, k, v = table.unpack(ks[#ks])
ks[#ks] = nil
pr[#pr] = nil
else
-- push the key as a prefix
pr[#pr+1] = k
if type(v) ~= 'table' then
-- if it isnt a table, add to our results
r[table.concat(pr, '.')] = tostring(v)
pr[#pr] = nil
else
-- otherwise if it's a table save state
ks[#ks + 1] = {it, t, k, v}
it, t, k = pairs(v)
end
end
return _flatten(r, pr, ks, it, t, it(t, k))
end
flatten = function(root)
local it, t, v = pairs(root)
return _flatten({}, {}, {}, it, t, it(t, v))
end
end
Tell me kung may ganitong function na or optimal method. I made it in a few minutes and honestly hindi pa na u-unit test. However no bugs have been discovered yet that came from this function so far xD
- J e F F
- New Member
- Posts : 12
Trophy : 41
Join date : 2017-09-05
Age : 29
Location : Mexico
Re: How to flatten a table in Lua 5.3+
keep it up (3)
- Sherlock-
- Banned
- Posts : 42
Trophy : 52
Join date : 2017-09-02
Location : 221B Baker Street
Re: How to flatten a table in Lua 5.3+
keep it right
- AhoGrill
- Journeyman
- Posts : 50
Trophy : 112
Join date : 2017-09-02
Age : 19
Location : I'm Aho so I don't know
Re: How to flatten a table in Lua 5.3+
Nice on up
- Fubu-chan
- Honorary Poster
- Posts : 163
Trophy : 237
Join date : 2017-09-02
Age : 24
Location : bikini bottom
Page 1 of 1
Permissions in this forum:
You cannot reply to topics in this forum