# Table Value Increment

I’m trying to increment a value that is in the 5th index of a table I have, inside of a function I made called Increment Table and I’m not sure why it’s not working.

``````local function IncrementTable(num, increment)
num = num + increment
print(num)
end
if tbls[5] == 0 then
IncrementTable(tbls[5], 1)
elseif tbls[5] == 1 then
IncrementTable(tbls[5], 1)
elseif tbls[5] == 2 then
IncrementTable(tbls[5], 1)
elseif tbls[5] == 3 then
IncrementTable(tbls[5], 1)
end
``````
1 Like

Try making sure both the table and specified index exist, are there any errors in the output?

``````local function incrementNum(num, inc)
num += inc
print(num)
end

local t = {nil, nil, nil, nil, 1}
print(incrementNum(t[5], 1)) -- 2
``````

Edit: Your function also works when tested, perhaps you didn’t specify a variable called ‘tbls’ referencing a table with the fifth index being a number.

``````local tbls = {"value for first index", 2, 3, 4, 1}
local function IncrementTable(num, increment)
num = num + increment
print(num)
end
if tbls[5] == 0 then
IncrementTable(tbls[5], 1)
elseif tbls[5] == 1 then
IncrementTable(tbls[5], 1)
elseif tbls[5] == 2 then
IncrementTable(tbls[5], 1)
elseif tbls[5] == 3 then
IncrementTable(tbls[5], 1)
end

--> prints 2
``````

I tried your method and it didnt work, the way I did it before was

``````tbls[5] = tbls[5] + 1
``````

But that was inefficient and I didnt wanna write it over and over so I just made a function, in the output it increments it by 1 then it stops working using both my method and yours

How you wrote the function and implied the functionality, that’s exactly what the code’s supposed to do.

Did you mean you wanted to linearly increment the number and print it to output?

Just use iteration

``````for n = 1, 5 do
print(n)
end
``````

Your current code actually just checked once only whether the number was a certain value, if it wasn’t then then through the `elseif` block it did that again, in the end if no evaluation returned true through the convulated method, it would just stop.
Also not sure how you made it increment the number with all these `elseif` s since you definitely need a loop to avoid unnecessary code as well.