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

Changing variables from one file to another

Started by RaiderOfLife, 21 August 2014 - 08:30 PM
RaiderOfLife #1
Posted 21 August 2014 - 10:30 PM
I am trying to make a very big stock exchange program and it runs threw multiple files. one file I call "stock-buy-1", when activated adds 1 to a variable on a file called "stock-userAmmount" this is what I have.

stock-buy-1
h = fs.open("stock-userAmmount", "a")
h.writeLine("x = 0+1")
h.close()

stock-userAmmount
x = 0
print( x )

so basicly I want stock-buy-1 to open stock-userAmmount and add one to x = 0 so when it prints it
will go up 1 number each time I run stock-buy-1, how would I fix this?
Bomb Bloke #2
Posted 22 August 2014 - 01:23 AM
You can't inject a line partway into a file. You can add lines to the end, or overwrite the entire thing - those are the two options.

So, you've got a choice: Either overwrite the entire "stock-userAmmount" script, or write to a third file and have the "stock-userAmmount" script read from that. That latter option is the easiest, and it'd go something like this:

stock-buy-1:
local myTable
if fs.exists("stock-data") then
  -- If the data file already exists, read what's in it:
  local myFile = fs.open("stock-data","r")
  myTable = textutils.unserialize(myFile.readAll())
  myFile.close()
else
  -- Otherwise build a new table:
  myTable = {["x"] = -1}
end

-- Add one to x:
myTable.x = myTable.x + 1

-- Write the data file with the updated data:
local myFile = fs.open("stock-data","w")
myFile.write(textutils.serialize(myTable))
myFile.close()

stock-userAmmount:
local myFile = fs.open("stock-data","r")
local myTable = textutils.unserialize(myFile.readAll())
myFile.close()

print(myTable.x)

You could do much the same thing without the table, but using one makes it much, much easier to store multiple values if you later have need to do so.
RaiderOfLife #3
Posted 22 August 2014 - 02:10 AM
I tried this, it didn't work