Reposted from here (http://www.computercraft.info/forums2/index.php?/topic/20602-autosaving-tables/)
If you have ever tried to write a script that saves a lot of things, say a bank server, you've had to repeatedly save tables whenever they are modified. I have the solution! After a day or two of tinkering around with metatables & serializing, I've created a method that makes a table save every time it is edited. I got the idea from locked tables, where people where using __newindex to detect when it was being modified, and prevent it. Here I've modified that method to additionally save the table after modification.
pastebin get h0eW3iEA (http://www.pastebin.com/h0eW3iEA)
How to use
Simple: Paste the code into the top of your program and write this:
makeAutoSaving( YOUR_TABLE, FILE_NAME )Alternatively, you can use it as a seperate file and load it as an api, in which case you can use this
api.makeAutoSaving( YOUR_TABLE, FILE_NAME )Also, this method DOES prevent the use of pairs and ipairs, and the # operator is broken. I tried adding __len, but it doesn't want to work (although, that could be the emulator). Because of this, I modify the metatable in such a way that doing
getmetatable( t ).originwill get you the actual table, however setting variables to this table bypasses my code entirely. It is mainly there to get the length of, although you can iterate through it if necessary. Here's an example of good iteration:
for k, v in pairs( getmetatable( t ).origin ) do
if v == "some random thingy" then
t[ k ] = "r" --#modify the variable holding the modified table
As always, constructive criticism is appreciated.
Edit: Fixed bug with restoring previous tables!