339 posts
Location
Computer, Base, SwitchCraft, Cube-earth, Blockiverse, Computer
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?
8543 posts
Posted 12 October 2015 - 03:31 PM
Please post your current code.
2679 posts
Location
You will never find me, muhahahahahaha
Posted 12 October 2015 - 03:59 PM
In order to work with number in a file, you have to follow several steps:
- Open the file
- Read the file
- Convert the content to a number
- Do the math
- Convert the result to a string
- Write to file
1583 posts
Location
Germany
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-mathYou should look at the source and learn from it, instead of (just) copying it.
51 posts
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