Table "to array" and "to lookup" functions.

Here’s a couple of small handy functions to convert a lookup table to an indexed table and indexed table to a lookup.

toarray - takes a table and creates an indexed shallow copy or takes n parameters and creates an indexed table from them.

function toarray(...)
    local new = {}
    local tbl
    if #arg == 1 and type(arg[1]) == "table" then tbl = arg[1]
    else tbl = arg end
    local count = 1
    for i,v in pairs(tbl) do
        new[count] = v
        count = count + 1
    end
    return new
end

tolookup - takes a table and creates a key-value lookup by the string name of the key / id field of the contents or the indexed table of ids/keys (of the same length as the input table).

function tolookup(tbl,id)
    local new ={}
    if type(id) == "string" then
        for i,v in pairs(tbl) do new[v[id]] = v end
    elseif type(id) == "table" then
        local count = 1
        for i,v in pairs(tbl) do
            new[id[count]] = v
            count = count + 1
        end
    end
    return new
end

Nice! Handy functions to have.

One thing I found that might not matter here is counting a table with “#new” in your example, seems quite slow performing. You could have a local variable counter instead as you are building it up rather than using #new each iteration.

You can also use table.insert( new, value ) as well.

I think table.insert is not very useful and not optimize…
Look at this : http://lua-users.org/wiki/OptimisationCodingTips

@HyroVitalyProtego very interesting, thanks for that.

@Simeon Thanks! :smiley: They are indeed I’ve needed them many times and not had them and probably written them several times over in context specific ways and I came to doing the same again yesterday and thought wait why don’t i write them generically :smiley:

@spacemonkey Whoops! Thank you nicely spotted! I did intend to have a local variable counter as thats far more efficient than counting the table every iteration :wink: which of course iterates the table… i must of got sidetracked on that :). Just edited that in now :slight_smile:

@HyroVitalyProtago Very interesting read! My favorite optimisation of all time is, depending on platform, XORing a register against itself to set it to zero is actually cheaper than setting it to zero explicitly :smiley:

@HyroVitalyProtago, great find! Time to go and optimize my projects now, hehe.