Is there a lua equivalent of Scala's map or C#'s Select function?

Viewed 13811

I'm looking for a nice way to do a map / select on a Lua table.

eg. I have a table :

myTable = {
  pig = farmyard.pig,
  cow = farmyard.bigCow,
  sheep = farmyard.whiteSheep,
}

How do I write myTable.map(function(f) f.getName)? [Assuming all farmyard animals have names]

ie. apply the function to all elements in the table.

5 Answers

An elegant solution using metatables:

map = function (old_t, f)
    return setmetatable({}, {
        __index = function (new_t, k)
            new_t[k] = f(old_t[k])
            return new_t[k]
        end
    })
end

The resulting table calculates each entry only when it is necessarily, essentially being a lazy table.

This means that it will also work on infinite lazy lists and tables, but there is a caveat - namely that if f doesn't always return the same result for the same input, then as the function calls are delayed then the resulting table might act differently depending on how differently f behaves when the table is created, and when each key is first indexed.

Well, all the other answers provide a slow map function. You will be able to see the performance difference when you have more than just a few elements in table.

This is the fastest map() function in pure lua -

function map(f, t)
    local t1 = {}
    local t_len = #t
    for i = 1, t_len do
        t1[i] = f(t[i])
    end
    return t1
end

It doesn't use the # operator in loop for comparison nor does it do t1[#t1+1]. both of which are slow.

PS: This code was taken from this article

This is an example of a map function in lua -

function(f, t)
    local o = {}
    for i = 1, #t do
        o[#o + 1] = f(t[i])
    end
    return o
end

Please Note: the above implementation is unoptimized. It should work for your purpose. However if you want one of the fastest implementation of the map() function in lua you can check this out - Lua Map Function It contains code and explanation.

Related