lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Mon, Jul 05, 2004 at 05:37:28PM +0200, Markus Huber wrote:
> How can be a nested table created from strings/data pairs like this?
> 
>    <Strings> def. the table should be filled with <Data>
> 
>    "Colour."                 "black"
>    "Colour.Markus."          "blue"
>    "Colour.Markus."          "yellow"
>    "Colour.Thomas"           "green"   -- note: without the last point
>    "Colour.Group.Heinz."     "red"
> 
> So the result should be a table:
> 
>    print(Colour[1])             --> "black"
>    print(Colour.Markus[1])      --> "blue"
>    print(Colour.Markus[2])      --> "yellow"
>    print(Colour.Thomas)         --> "green"
>    print(Colour.Group.Heinz[1]  --> "red"
> 
> Any solutions without using dostring()? I think a recursive function
> call does the work and I will programm this later this day but possible
> someone has an already running solution or any other good ideas.

I haven't tried this, but:

function insert(loc, val)
    local last = 0
	local tbl = _G
    for match, _, pos in string.gfind(loc, "(.-)(%.)()") do
        last = pos
		if not tbl[match] then tbl[match] = {} end
        tbl = tbl[match]
    end
    local match = string.sub(loc, last)
    if match == "" then
        tbl[table.getn(tbl)+1] = val
	else
        tbl[match] = val
    end
end

-- Jamie Webb