Search code examples
luavectorizationapply

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?


Solution

  • 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