Attempt to perform arithmetic (sub) on number and nil

so im making a tower defense game, i have everything working, but when i upgrade, i get the error

attempt to perform arithmetic (sub) on number and nil

and it comes from:

 player.stats.Cash.Value -= towercosts.Data[tower.Parent.Name][level]

the towercosts is a module that contains what the towers level cost and how much it costs to place it, the level is the towers current level
and the tower is the tower model

towercosts.Data[tower.Parent.Name][level] is nil. Before subtracting the cash try printing towercosts.Data to see if tower.Parent.Name is in fact a key in the table. You can then also check if level is within that table.

it just prints

{...}

thats all that prints

then how else am i supposed to use modules to store data?

Try to separate the table so you find out what index is nil.

print(towercosts.Data)
print(towercosts.Data[tower.Parent.Name])
print(towercosts.Data[tower.Parent.Name][level])

If any one of those are nil, then you can look inside the last [brackets] to see what is missing.
Also, you can open {…} to see what values are inside.

the last one was nil, is that why?

Next, try this:

print(towercosts.Data[tower.Parent.Name], level)

Open the table that gets printed and see if you can find the 2nd print level anywhere in the table. If not, then your level variable is incorrect.

it prints 1 which is the level the tower is getting upgraded to

What does the table look like when it is opened? It could be possible that your level variable is a string. consider using tonumber(level) or tostring(level)

it looks like this:

                    ["1"] = 50,
                    ["2"] = 100,
                    ["Cost"] = 250

I’m guessing level is a number then. You have to do towercosts.Data[tower.Parent.Name][tostring(level)]. Types matter!

1 Like

ive never heard of tostring, but ill try!

ok so it works, thanks for telling me