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

Add / subtract numbers in a file?

Started by ry00000, 12 October 2015 - 01:04 PM
ry00000 #1
Posted 12 October 2015 - 03:04 PM
Please help! I'm trying to add/subtract the amount of money, but it doesn't do it!
Could you give me a snippet of code to learn from?
Lyqyd #2
Posted 12 October 2015 - 03:31 PM
Please post your current code.
Creator #3
Posted 12 October 2015 - 03:59 PM
In order to work with number in a file, you have to follow several steps:
  1. Open the file
  2. Read the file
  3. Convert the content to a number
  4. Do the math
  5. Convert the result to a string
  6. Write to file
H4X0RZ #4
Posted 12 October 2015 - 04:34 PM
(Sorry if this is spoon-feeding)

Here is a small API I quickly wrote which shows you how to do simple math with a file. I assume that the file only contains a number, and nothing else. http://backspace.cf/snippet/file-math
You should look at the source and learn from it, instead of (just) copying it.
YoYoYonnY #5
Posted 12 October 2015 - 10:04 PM
This example looks alot like H4X0RZs, but I feel like he did too much for you. If you are up for a challenge and think you can understand the following then be my guest:

local path = "file.txt" -- The file to save the data to
function save(data) -- Save the data
	local handle = fs.open(path, "w")
	handle.write(data)
	handle.close()
end
function load() -- Load the data
	local data
	local handle = fs.open(path)
	data = handle.readAll()
	handle.close()
	return data
end
function parseMoney(data) -- Parse the data (Convert it to something usefull, in this case a number, but might be a string, table or anything else. If we had a file storing a account with name, password, id, balance etc. then writing your own parse function would be necessairy.)
	return tonumber(data)
end
function serializeMoney(data) -- Serialize the data (Convert it to a string)
	return tostring(data)
end
function saveMoney(money) -- Some shortcuts
	save(serializeMoney(money))
end
function loadMoney()
	return parseMoney(load())
end
-- Lets test our code:
local money
function init() -- Before we will start our test we will make sure that we saved 100 money
	money = 100
	saveMoney(money)
end
function main()
	init() -- We have to make sure our file is saved before it is loaded
	money = loadMoney() -- We had 100 money...
	money = money + 100 -- We add 100 (=200 total)
	saveMoney(money) -- We save our money (We now have 200)
end
main() -- Lets run our test
Note: This also follows Creators algorithm.
Edited on 12 October 2015 - 08:05 PM