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

read table in file?

Started by Goof, 07 July 2013 - 11:34 PM
Goof #1
Posted 08 July 2013 - 01:34 AM
Hi :P/>

I'm trying to make a settings file with tables which looks like this atm:

desktop = {
  ["user"] = { username = "";
    ["Color"] = {
      ["BackgroundColor"] = colors.gray;
    };
    ["Icons"] = {
      ["Programs"] = {
        ["xMin"] = 2;
        ["yMin"] = 1;
        ["xMax"] = 10;
        ["yMax"] = 3;
        ["text"] = "Programs";
        ["Text_Color"] = colors.white;
        ["Background_Color"] = colors.black;
      };  
    };
  };
};


is it possible to read this file as a table?


-Thanks

-Mikk809h
Grim Reaper #2
Posted 08 July 2013 - 02:44 AM
Instead of trying to create a script which will write tables as strings from a file and read them back in the same manner, just use the textutils.serialize and textutils.unserialize functions available in CC.

For example, the following code writes a table to a file and reads it right back exactly as it was.

-- Our table with multiple levels.
local _table = {
    ["field0"] = 1,
    ["field1"] = {
            ["field0"] = true
        }
}

-- Write the table to a file as a string.
local fileHandle = fs.open ("file", 'w')
fileHandle.write (textutils.serialize (_table))
fileHandle.close()

-- Read the contents of the file back as a string and unserialize it into a table format.
local fileHandle   = fs.open ("file", 'r')
_table             = textutils.unserialize (fileHandle.readAll())
fileHandle.close()
Kingdaro #3
Posted 08 July 2013 - 05:00 AM
For the record, this is also valid, is much less typing, and looks a little neater (in my opinion):

desktop = {
  user = { username = "";
    Color = {
      BackgroundColor = colors.gray;
    };
    Icons = {
      Programs = {
        xMin = 2;
        yMin = 1;
        xMax = 10;
        yMax = 3;
        text = "Programs";
        Text_Color = colors.white;
        Background_Color = colors.black;
      };  
    };
  };
};
Goof #4
Posted 09 July 2013 - 07:48 PM
Sorry for the late answer.. (i've been busy…)

Oh.. Thanks for thoose answers. now i know what to do. xD


gonna continue coding… :P/>

Thanks