1
votes

I am making a bank on Minecraft.

I am having trouble with saving a variable after addition or subtraction has been done to it.

For example, if x="balance", x=15, say I want to withdraw from my balance:

x = 15 - y(withdrawn money)

The variable is not saved when the program is run again.

2
Your question is not clear. What is x? A variable which holds your balance? What is y? - John Smith
x is a person's balance y is money that is taken out of the account - Kevin McGinley
modify your question to make it more clear instead of adding comments - Tim Tisdall

2 Answers

3
votes

If you want data persistence between program runs, you need to store the data in files. For example, you could save the variable x to a file like this:

h = fs.open("filename","w")
h.writeLine(x)
h.close()

And you could load it like this:

h = fs.open("filename","r")
x = tonumber(h.readLine())
h.close()

Here is the documentation. http://computercraft.info/wiki/Fs.open

0
votes

Here is a first stab at it. I suppose the account balance is stored in x. Then the following function will withdraw and return money from x.

-- wa is amount to withdraw
-- this function withdraws the maximum allowable
function withdraw(wa) 
    if wa>0 then
        wt=math.min(x,wa)
        if wa <= x then
            x=x-wt
            return wt
        end
    end
    return 0
end

A far more sophisticated way to keep accounts is available in the PiL book: http://www.lua.org/pil/16.html