FICHEKK
FICHEKK

Reputation: 819

Changing variable in function

I want to make it when I press a button, a bunch of variables change.

function BuyItem(price, quantity, pps, text, quantitytext)
    if(PixoosQuantity >= price) then
        PixoosQuantity = PixoosQuantity - price
        price = price * 1.1

        quantity = quantity + 1

        PixoosPerSecond = PixoosPerSecond + pps
        PixoosPerSecondDisplay.text = "PPS: " .. string.format("%.3f", PixoosPerSecond)
        PixoosQuantityDisplay.text = "Pixoos: " .. string.format("%.3f", PixoosQuantity)

        text.text = "Deck of playing cards\nPrice: " .. string.format("%.3f", price) .. " Pixoos"
        quantitytext.text = quantity
    end
end

This is a function which gets called upon button press:

function ButtonAction(event)
    if event.target.name == "DeckOfPlayingCards" then
        BuyItem(DeckOfPlayingCardsPrice, DeckOfPlayingCardsQuantity, DeckOfPlayingCardsPPS, DeckOfPlayingCardsText, DeckOfPlayingCardsQuantityText)
    end
end

My question is, why don't the variables change? I tried putting return price and such, but it still doesn't work...

Upvotes: 1

Views: 82

Answers (1)

Jakuje
Jakuje

Reputation: 25956

You pass the variable price by value and not by reference. This construct does not exists in Lua, so you need to workaround it, for example by using the return value:

DeckOfPlayingCardsPrice, DeckOfPlayingCardsText, DeckOfPlayingCardsQuantityText = BuyItem(DeckOfPlayingCardsPrice, [...], DeckOfPlayingCardsText, DeckOfPlayingCardsQuantityText)

and return the expected value properly:

function BuyItem(price, quantity, pps, text, quantitytext)
    if(PixoosQuantity >= price) then
        [...]
    end
    return price, quantity, quantitytext
end

In Lua you can return multiple results.

Upvotes: 1

Related Questions