문제

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.

도움이 되었습니까?

해결책

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

다른 팁

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top