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

Writing Tables to Files

Started by cdel, 25 September 2014 - 08:25 AM
cdel #1
Posted 25 September 2014 - 10:25 AM
I am a bit confused on how I would write a table to a file.

An example code setup:


table = { "Hello", "World", "!" }

local file = fs.open("hai", "w")
file.write(table)
file.close()

'hai' file:


{3.0=!, 2.0=World, 1.0=Hello}

How do I make it look like a 'normal' table as it would in another program.
Edited on 25 September 2014 - 08:27 AM
Bomb Bloke #2
Posted 25 September 2014 - 11:11 AM
In your example, you create a table and store the pointer that leads to it in your "table" variable. Then you attempt to write that pointer to disk.

Take a look at textutils.serialize() / textutils.unserialize().

Edit:

Hang on, you're saying fs.write() produced "{3.0=!, 2.0=World, 1.0=Hello}" without a specific serialisation call? I honestly wouldn't've expected it to do even that much… In any case, you should get better results with the textutils API.
Edited on 25 September 2014 - 09:16 AM
oeed #3
Posted 25 September 2014 - 11:14 AM
Edit: Ninja'd….

You're looking for textutils.serialise, or unserialise if you want to read a table.

Note that serialise (UK spelling) is valid, but only since 1.6. It's up to you whether to use the UK spelling or the US spelling.


local _table = { "Hello", "World", "!" }
local file = fs.open("hai", "w")
file.write(textutils.serialise(_table))
file.close()

Also you shouldn't use table a variable name, it's used for the actual table API/object/whatever you want to call it.
Edited on 25 September 2014 - 09:15 AM
cdel #4
Posted 25 September 2014 - 11:19 AM
In your example, you create a table and store the pointer that leads to it in your "table" variable. Then you attempt to write that pointer to disk.

Take a look at textutils.serialize() / textutils.unserialize().

Edit:

Hang on, you're saying fs.write() produced "{3.0=!, 2.0=World, 1.0=Hello}" without a specific serialisation call? I honestly wouldn't've expected it to do even that much… In any case, you should get better results with the textutils API.

I didn't expect it either. :unsure:/>

Edit: Ninja'd….

You're looking for textutils.serialise, or unserialise if you want to read a table.

Note that serialise (UK spelling) is valid, but only since 1.6. It's up to you whether to use the UK spelling or the US spelling.


local _table = { "Hello", "World", "!" }
local file = fs.open("hai", "w")
file.write(textutils.serialise(_table))
file.close()

Also you shouldn't use table a variable name, it's used for the actual table API/object/whatever you want to call it.

I knew about serialising tables and such, just didn't know if it was different for some reason when writing to files. thanks :)/>