How do i add numbers to arrays?

I want to add numbers to a array
Example: “table.insert(table[array], 1)”
then make it print “table[array] = 1”

is it possible?

something like this?

tab = {["Hi"] = 5}
tab["Goodbye"] = 4
print(tab.Hi, tab.Goodbye)

kinda, i want to add new values as well like

table['Hello'] = 4
table['Hello'] += 1
print(table.Hello) -- 5


from my knowledge that should work, although i don’t do a lot of math stuff with tables. If it doesn’t work try just doing the longer method

tab["Hello"] = 4
tab.Hello = tab.Hello+1
print(tab.Hello)

but += should also work

Nope, i tried and it didnt worked :confused:

replace ipairs with pairs or just remove it completely, I don’t know how ipairs work exactly but once I tried to use it and it didn’t work at all. So add a print() to check if it even gets to that point because I doubt it does

You can also do this without the name label …
Just need to know the table locations you’re working with.

a = {1, 2, 5}
print(a[1])
print(a[1] + a[3])

that’s not what i was asking for…

i don’t see any difference using pairs

Oh, looked like you were adding array values. Sorry about that. Is this what you were asking?

playerItems = {}

table.insert(playerItems, "Potion")
table.insert(playerItems, "Bread")
table.insert(playerItems, "Sleeping bag")

for index = 1, #playerItems do
  local itemString = playerItems[index]
  print("Index " .. index .. ": " .. itemString)
end

Making Changes to Arrays

pairs can loop through dictionaries but ipairs cant, and using [“string”] = 5 instead of [1] = 5 makes the table a dictionary. So you have to use pairs or it won’t work at all

kinda, i just want to add a new value to the array like this:

table['Hello'] = 4
table['Hello'] += 1
print(table.Hello) -- 5

I think you could do that by doing your calculations then just changing the array value, or the other way around …

a = {1, 2, 5}
print(a[1] + a[3]) this  = 6

a[1] = 5
print(a[1] + a[3]) this  = 10

ItemsQuanitity is a dictionary, not an array. You would check if a key existed with ItemsQuantity[Item.Name] instead of table.find.

ipairs is also correct here, because you’re iterating through the array returned from GetChildren and its faster to numerically traverse it.

1 Like

Wow, i don’t know how but it actually worked! Thanks a lot!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.