Search code examples
lualua-table

Converting indexed table to keyed table in Lua


I'm a newbie in Lua.

I wonder how to convert indexed table to a key-based table.

For example, Let's say I have the following table.

t = {5, 6, 7, 8}

Now, I understand t[1] is 5, t[2] is 6, t[3] is 7, and t[4] is 8.

What should I do to convert the table t to the following key-based style? (without re-constructing the table again)

t = {x=5, y=6, z=7, w=8}

What would be the most simplest and performant solution to do this?


Solution

  • Try this code:

    t = {5, 6, 7, 8}
    f = {"x", "y", "z", "w"}
    
    for k=1,#t do
        t[f[k]]=t[k]
        t[k]=nil
    end
    
    for k,v in pairs(t) do
        print(k,v)
    end