Updating a value in a table

I have a remote event that when fired does some other things but its also supposed to add to a value in a players inventory (a table with the players table within a serverdata table).

Inventory = {
 ex = 0,
 ex2 = 0
}

That is what their inventory table looks like. Whenever the remote event is fired passed with it is the player and the item that they are trying to pick up. In the onserverevent script I have it updating the value.

pickupItem.OnServerEvent:Connect(function(player, item)
	local Inventory = ServerData[player].Inventory
	Inventory.item.Value = Inventory.item.Value + 1
end)

But I always get this error.

attempt to index nil with 'Value'

2 Likes

You should be doing Inventory[item].

When you do Inventory.item it looks for the key named item inside Inventory. When you use Inventory[item] it uses the value of the variable item to index Inventory

image

Also if you’re using number types NOT NumberValues for elements in your table you might want to do Inventory[item] = Inventory[item] + 1 (In your example you used number types)

4 Likes

when is use this:

Inventory[item] = Inventory[item] + 1

it gives me this error:

attempt to perform arithmetic (add) on nil and number

Because Inventory[item] == nil, you haven’t assigned anything to it.

I gave the number types in inventory the value of 0. Does that count as nil?

I don’t understand what you mean. However the #help-and-feedback:scripting-support category is not created to teach you Lua, only to solve problems with your code. You seem to lack basic knowledge and I recommend to watch or read tutorials on Lua tables and related things.

The use of tables has already been documented in the Internet and there’s no need to post such questions on the DevForum.

Check this out: Programming in Lua : 2.5

I figured it out. When I was sending the item name I was using mouse.target for other things in a function to pick it up and when did FireServer I wasn’t sending the name of the item. (was using mouse.Target rather than mouse.Target.Name)

1 Like

That is why you should always attach the code that is firing the event because very often it is the cause of the problem.

1 Like