Add a value to table fields (lua)

Viewed 170

guys!

Can you help me, please!

I want to add a number to a table, and I want to have it like this:

A={1,2,3}
B=A+5
--- now B is {6,7,8}

I don't want to create any classes, additional modules. May be some kind of extension to global table?

I think it can be done via global __add overrides.. Any thoughts?

2 Answers
A = setmetatable({1,2,3},
  {
    __add = function (t, add)
      assert(type(add) == "number", "invalid addend! number expected")
      local result = {}
      for i,v in ipairs(t) do
        result[i] = v + add
      end
      return result
    end
  })

B = A + 5    
print(table.concat(B, ","))
C = A + "f"

You can do this by iterating through the table with ipairs and setting each element of B to the sum of the number and the corresponding element of A

For example

local B = {};
local numberToAdd = 5;
for i, v in ipairs(A) do
    B[i] = v + numberToAdd;
end

A metatable can also be used to have the syntax B = A + 5. You would use the same code as the example, but you would need to use setmetatable on A then set the __add function of the metatable to the example code.

Related