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

Saving A Table On A Disk, Then Using It In A Script.

Started by NomNuggetNom, 12 September 2013 - 02:42 PM
NomNuggetNom #1
Posted 12 September 2013 - 04:42 PM
Hey folks! Here's the gist of my program: I can request an item to be crafted by saying "$$craft <amount> <item_name>". I can also manipulate the items in a similar manner. In order to be able to say something like "$$craft 5 glass", I've created a table of some item IDs like so:

itemIndex = {}
itemIndex["glass"] = 20
itemIndex["chest"] = 54

Now, that's all good and working fine. I also have an add command to manually index the values ingame using this: "$$add <item_name> <ID>". I have no problems with that command, it works just fine. The problem arises when I need to make changes to the script, and those values are gone. One method I thought might work is saving the table to a disk, then loading it on the program's startup. How would I do something like this while retaining the ability to manually add values? Or is there another method I should be pursuing? Thanks!
Vilsol #2
Posted 12 September 2013 - 04:56 PM
You can serialize and unserialize an array with textutils.
http://computercraft.info/wiki/Textutils_(API)
Hydra #3
Posted 12 September 2013 - 05:45 PM
By heart, to save a table:


local tab = {"one", "two","three"} -- your data
local str = textutils.serialize(tab) -- string version
local handle = fs.open("data.txt", "w") -- open a file handle for writing, returns nil if it can't
handle.write(str) -- write the data
handle.close() -- close the file

To read:

local handle = fs.open("data.txt", "r") -- open file for reading
local str = handle.readAll() -- read the data
handle.close() -- close the file
local tab = textutils.unserialize(str) --get the table from the string
NomNuggetNom #4
Posted 12 September 2013 - 08:04 PM
Thanks for your replies guys. Instead of converting the table, I just have the following:
    Which works perfectly. Except with metadata.. Because the string.find is looking for a strand of letters, then an equals, than a strand of numbers, a ':' will throw it off. Unfortunately I can't find the pattern for ':'.
immibis #5
Posted 13 September 2013 - 03:49 AM
The pattern for ':' is probably ':'