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

help plz

Started by craton, 17 October 2012 - 09:52 PM
craton #1
Posted 17 October 2012 - 11:52 PM
i have 2 quetions?
how can you save things to a disk like a log all in the same file?

and what code can i use to run multiple programs at once?
Kingdaro #2
Posted 18 October 2012 - 12:35 AM
For your first question, you could save a table of your vars and load them later using serializing.


-- declare variables
var1 = 5
var2 = 'a string'

-- path/name of your file
local filepath = 'savedvars'

-- function for saving variables to a file
local function saveVars(vars)
  -- convert the variables table to a string
  local writestring = textutils.serialize(vars)

  -- write the string to a file
  local file = fs.open(filepath, 'w')
  file:write(writestring)
  file:close()
end

-- function for loading the variables
local function loadVars()
  -- return a "re converted" version of our saved table
  local file = fs.open(filepath, 'r')
  local data

  -- make sure the file exists
  -- and actually contains something
  if file then
    data = file.readAll()
  end

  -- if the file doesn't exist, it'll just return nil.
  return data
end

-- to save our variables we can just do:
saveVars {var1=var1, var2=var2}

-- and then reload our variables later on.
local vars = loadVars()

-- here we access them.
print(vars.var1)
print(vars.var2)

--> 5
--> a string

Your second question is much easier. You can use the parallel API to run multiple programs at once. Say you wanted to run programs "foo" and "bar" at the same time.

local function foo()
shell.run('foo')
end

local function bar()
shell.run('bar')
end

parallel.waitForAll(foo, bar)
ChunLing #3
Posted 18 October 2012 - 06:17 AM
The append option (fs.open(filepath, "a") ) is ideal for keeping a log file. If you want to save program data (particularly tables), then using textutils.un/serialize and saving using write into a file opened with the "w" option is better. The wiki has a page devoted to the various uses of the fs.open command.