Question

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.

Était-ce utile?

La solution

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

Autres conseils

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

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top