Lua hierarchy string to table -
is there way can convert hierarchy string table form?
suppose input a.b.c.d
ouput should table traverses above input: a = {}
a.b = {}
a.b.c = {}
a.b.c.d = {}
thanks.
the obvious solution parse string , construct hierarchy table that. more clever solution let lua you. bit of metamagic , function environment manipulation can done:
dump = require 'pl.pretty'.dump -- convenient table dumper penlight function createtable(str) local env_mt = {} env_mt.__index = function(t, k) rawset(t, k, setmetatable({}, env_mt)) return rawget(t, k) end local env = setmetatable({}, env_mt) local f = loadstring("return "..str) setfenv(f, env) f() return env end dump( createtable "a.b.c.d" )
this outputs:
{ = { b = { c = { d = { } } } } }
Comments
Post a Comment