# Table suddenly becomes nil

Hi!
I’m messing around with metatables and for some reason T2 for the first iteration of the ipairs loop is fine, but then turns into nil.

``````local t1 = {5,3}
local t2 = {0,0}

local mt = {__add = function(t, value)
print("Adding " .. value .. " to table")
t[math.random(1, 2)] += value
end,}

setmetatable(t2, mt)

for i,v in ipairs(t1) do
if typeof(v) == "number" then
print("T1: ", t1)
print("T2: ", t2)
print("V: ", v)
t2 += v
end
end

print(t2)
``````

Thanks!

I think it’s because you forgot to return the table at the end, try this out

``````local t1 = {5,3}
local t2 = {0,0}

local mt = {__add = function(t, value)
print("Adding " .. value .. " to table")
t[math.random(1, 2)] += value
return t
end,}

setmetatable(t2, mt)

for i,v in ipairs(t1) do
if typeof(v) == "number" then
print("T1: ", t1)
print("T2: ", t2)
print("V: ", v)
t2 += v
end
end

print(t2)
``````
2 Likes

That worked, thanks! I didn’t know you had to return the table, that’s weird.

1 Like

I thought something was up as in the official dev wiki article for metatables, it returned something but in your code, you didn’t return anything, so it assumed it had to make it `nil`, but at least you got the solution!

If you have anymore issues don’t be afraid to make another post!

2 Likes