This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
Stekeblad's profile picture

table that never change a rows index on its own

Started by Stekeblad, 11 January 2016 - 10:52 PM
Stekeblad #1
Posted 11 January 2016 - 11:52 PM
Hi, I planned making my first post for the program I am working on, but now I need a little help…

I have a table with data that I want to save and load, I want to change its data from inside the program (adding, editing, removing), but, then I add a new row I want the data added to have the index it was given then it was added until the row or entire table is deleted and not to be affected by other changes in the table.

Lets take the two first rows in the table:


SeedTable[1] = {name = "Iron", needed = 16}
SeedTable[2] = {name = "Gold", needed = 20}

If I am not careful then deleting SeedTable[1] then row two will have it's index changed to one and that is what I don't want to happen! If index 1 turns into
{name = "Gold", needed = 20}
then the program will not work as intended.

the index is set to be the damage value of the item
name is a shorter( or random/funny) name for the item and
needed is how many of the item with damage value index is needed to do the thing I am trying to do.

Do anyone have an idea of how to work with a table like this that allows all this? Saving table, loading table, adding rows, removing rows and editing rows WITHOUT rows getting their index changed, without making it too complicated, a little complicated may be necessary :)/>

Maybe saving the ID together with name and needed but then do I not have to work with multiple table copying everything or searching after ID's all the time instead of just jumping to index?
Bomb Bloke #2
Posted 12 January 2016 - 12:51 AM
One method is to simply not use table.remove(). Say you wanted to delete index three, you'd simply do:

SeedTable[3] = nil

Hey presto, it's gone, and all the other indexes stay in place. Note that after doing this, table.maxn(SeedTable) will still return the highest index in the table, whereas #SeedTable would return 2.

Another method is to index the table by names, rather than numbers. Eg:

SeedTable["Iron"] = {needed = 16}
SeedTable["Gold"] = {needed = 20}

This way, it doesn't matter what happens to Iron… Gold is still found under "Gold".
Stekeblad #3
Posted 13 January 2016 - 04:25 PM
It was that easy?! It seems to work. Thanks!