Need help with tables

Heya, everyone.

So I need some help here with some tables. I’ve been trying really hard to solve this but right now, I just wanna give up… But instead of giving up, I wanna try asking ya about this. So, I have this script:

local myTable = {

	["My Item"] = {
		["Price"] = 100,
		["My Value"] = 23
	},

}

for i, v in pairs(myTable) do
	print(i)
end

table.insert(myTable, {

	["My Other Item"] = {
		["Price"] = 140,
		["My Value"] = 15
	},
	
})

for i, v in pairs(myTable) do
	print(i)
end

As you can see, first there is a table that has some values and indexes. Secondly, there is a for loop that loops through the table and return the index. In this case, it returns “My Items”. So this works perfectly. However, when inserting into the table with an index as you see, and then printing the index, it prints “1”. I do not want that, because this script is a breakdown of a larger script that I am working on (so I didn’t have to show you 500 lines of code).

It is for an inventory system so “My Item” would be the name of the item the player have, therefore I need to include the index, and when inserting into the table and printing the index, it should not print the count, but the index string. Any solutions to this would be hiiighly appreciated! :smile:

Thank you in advance.

I am not sure what you are asking? table.insert inserts an element to the array part. So don’t use it?

True, but when I am inserting an element into the table, the index gets corrupt.

Instead of using table.insert you should use:

myTable["My Other Item"] = {
	["Price"] = 140,
	["My Value"] = 15
}
1 Like

Could you define “corrupt” in this context??

As long as the index is not an integer, it should print the exact index value (string/object value etc.). Also, index doesn’t print the total amount of values in an array/table unless you add a hashtag (#) in front of it - and even then, the indexes would need to be integers.

From my assumption, the table looks like this:

{

	["My Item"] = {
		["Price"] = 100,
		["My Value"] = 23
	},{
        ["Price"] = 140,
		["My Value"] = 15
      }

}

After inserting the element, and not including the index at all

Yes that is how it looks like. The second table is at index 1. You basically have a mixed table.

How would I change the script in other for the table to look like this after inserting?

{

	["My Item"] = {
		["Price"] = 100,
		["My Value"] = 23
	},
    ["My Other Item"] = {
        ["Price"] = 140,
		["My Value"] = 15
    }

}

This reply from five minutes ago might be useful.

The second argument for table.insert() is the position in the table (a number value).

You should be fine by just doing

myTable["My Other Item"] = {
		["Price"] = 140,
		["My Value"] = 15
	}

Ohh yes, it works! Thanks man :smile:

The position argument in table.insert isn’t actually required. If left out it defaults to #array + 1

local x = {1}
for i = 2, 4 do
	table.insert(x, i)
end
print(table.unpack(x)) -- 1 2 3 4
1 Like