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

Permanent Variable

Started by lieudusty, 09 September 2012 - 05:18 PM
lieudusty #1
Posted 09 September 2012 - 07:18 PM
Hi everyone! =D

This might be a noob question but, I'm wondering how I would make a permanent variable that stays there even after the computer restart. Can someone please help? Thanks! =D
cant_delete_account #2
Posted 09 September 2012 - 07:31 PM
To save variables through reboot, try this:

local function saveVar(tVar, tVarContent, tReplace)
if not tReplace then
if not fs.exists("/.vars/"..tVar..".var") then
local tFile = fs.open("/.vars/"..tVar..".var", "w")
if tFile then
tFile.write(tVarContent)
tFile.close()
end
else
error("Variable "..tVar.." already exists!")
end
else
fs.delete("/.vars/"..tVar..".var")
local tFile = fs.open("/.vars/"..tVar..".var", "w")
if tFile then
tFile.write(tVarContent)
tFile.close()
end
end
end
local function readVar(tVar)
if fs.exists("/.vars/"..tVar..".var") then
local tFile = fs.open("/.vars/"..tVar..".var", "r")
else
error("Variable "..tVar.." doesn't exist!")
end
if tFile then
return tFile.readLine()
tFile.close()
end
end
Then use:
saveVar("name you want variable to be", "what variable contains this only works with strings right now", if you want to replace variable boolean true/false) – saves variable
readVar("variable name") – returns contents of variable entered
Of course, if I was releasing this I would polish it up, but this is just an example.
(never tested ^)
Lyqyd #3
Posted 09 September 2012 - 07:44 PM
You'll want to write your variables to a file, then read them again out of that file. Look into the fs and io APIs (you'll only need to use one or the other; io has a couple nice features that fs doesn't), and glance through the code posted above if it's not incomprehensible to you.