January
January

Reputation: 17100

How do you efficiently apply a numeric operation to an array in lua?

Say, I have an array

a = { 1, 2, 10, 15 }

I would like to divide each element by 3 and store the result in a new array. Is there a more efficient / elegant way of doing that than this:

b = { }
for i,x in pairs(a) do
  b[i] = x / 3
end

In R, I would simply do b <- a/3. Is there anything like that in lua, or maybe a way of applying a function to each element of a table?

Upvotes: 1

Views: 259

Answers (2)

January
January

Reputation: 17100

In addition to the answer by shingo, I found in the meanwhile that writing an R-style mapping function is very easy in lua:

function map(x, f)
  local ret = { }
  for k, v in pairs(x) do
    ret[k] = f(v)
  end
  return ret
end

This makes some operations easy, for example

a = { 1, 2, 3, 5, 10 }
map(a, function(x) return x * 2 end)

Upvotes: 0

shingo
shingo

Reputation: 27154

Lua is lightweight, so there is no ready-made functions, but you can create a similar function with metatable.

local mt_vectorization = {
    __div = function (dividend, divisor)
        local b = {}
        for i,x in pairs(dividend) do
            b[i] = x / divisor
        end
        return b
    end
}

a = setmetatable({ 1, 2, 10, 15 }, mt_vectorization)

b = a / 3

Upvotes: 2

Related Questions