Posted 22 February 2013 - 06:49 PM
Say something… Hm…
Many have asked how to store variables in a file. And this is a basic tutorial about that. (You couldn't have been much more straightforward LBP, could you?)
This tutorial requires a basic knowledge of tables.
Step 1: Set up your variables inside a table
Step 2: Convert the table to a string
Step 3: Save the string to a file
We're done!
Now try to load that table.
Step 4: Read the serialized table
Step 5: Convert the string to a table
YAY! Now you can store variables in a file.
NOTE: You cannot store functions or "threads" (ok, coroutines) in files, because textutils doesn't like them. Of course, you could store a function dump, but I'm not sure what would happen to textutils then.
Many have asked how to store variables in a file. And this is a basic tutorial about that. (You couldn't have been much more straightforward LBP, could you?)
This tutorial requires a basic knowledge of tables.
Step 1: Set up your variables inside a table
local health = 4
local hunger = 8
local armor = 3
local name = "Steve"
local target = {} -- this is a table
target.health = health
target.hunger = hunger
target.armor = armor
target.name = name
Step 2: Convert the table to a string
local output = textutils.serialize(target)
Step 3: Save the string to a file
local handle = assert(fs.open("vars", "w"), "Couldn't save vars") -- this will give you an error if something's gone wrong
handle.write(output) -- this is where the magic happens, we're storing the entire "target" table
handle.close()
We're done!
Now try to load that table.
Step 4: Read the serialized table
local handle = assert(fs.open("vars", "r"), "Couldn't load vars") -- this file is opened in read mode
local input = handle.readAll() -- input is now the serialized table
handle.close()
Step 5: Convert the string to a table
local destination = textutils.unserialize(input) -- this will decode our table
print(destination.health) -- prints 4
print(destination.hunger) -- prints 8
print(destination.armor) -- prints 3
print(destination.name) -- prints Steve
YAY! Now you can store variables in a file.
NOTE: You cannot store functions or "threads" (ok, coroutines) in files, because textutils doesn't like them. Of course, you could store a function dump, but I'm not sure what would happen to textutils then.