Jump to content




Add / subtract numbers in a file?


  • You cannot reply to this topic
4 replies to this topic

#1 ry00000

  • Members
  • 244 posts
  • LocationComputer, Base, SwitchCraft, Cube-earth, Blockiverse, Computer

Posted 12 October 2015 - 02: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?

#2 Lyqyd

    Lua Liquidator

  • Moderators
  • 8,465 posts

Posted 12 October 2015 - 02:31 PM

Please post your current code.

#3 Creator

    Mad Dash Victor

  • Members
  • 2,168 posts
  • LocationYou will never find me, muhahahahahaha

Posted 12 October 2015 - 02: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


#4 H4X0RZ

  • Members
  • 1,315 posts
  • LocationGermany

Posted 12 October 2015 - 03: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.

#5 YoYoYonnY

  • Members
  • 49 posts

Posted 12 October 2015 - 09: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 by YoYoYonnY, 12 October 2015 - 09:05 PM.






1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users