改变函数中的变量
Changing variable in function
我想做的是按下一个按钮,一堆变量发生变化。
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
这是一个在按下按钮时调用的函数:
function ButtonAction(event)
if event.target.name == "DeckOfPlayingCards" then
BuyItem(DeckOfPlayingCardsPrice, DeckOfPlayingCardsQuantity, DeckOfPlayingCardsPPS, DeckOfPlayingCardsText, DeckOfPlayingCardsQuantityText)
end
end
我的问题是,为什么变量不改变?我试着把 return price
之类的,但它仍然不起作用...
您按值而不是 by reference 传递了变量 price
。此构造在 Lua 中不存在,因此您需要解决它,例如使用 return 值:
DeckOfPlayingCardsPrice, DeckOfPlayingCardsText, DeckOfPlayingCardsQuantityText = BuyItem(DeckOfPlayingCardsPrice, [...], DeckOfPlayingCardsText, DeckOfPlayingCardsQuantityText)
和return正确的期望值:
function BuyItem(price, quantity, pps, text, quantitytext)
if(PixoosQuantity >= price) then
[...]
end
return price, quantity, quantitytext
end
在 Lua 你可以 return multiple results.
我想做的是按下一个按钮,一堆变量发生变化。
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
这是一个在按下按钮时调用的函数:
function ButtonAction(event)
if event.target.name == "DeckOfPlayingCards" then
BuyItem(DeckOfPlayingCardsPrice, DeckOfPlayingCardsQuantity, DeckOfPlayingCardsPPS, DeckOfPlayingCardsText, DeckOfPlayingCardsQuantityText)
end
end
我的问题是,为什么变量不改变?我试着把 return price
之类的,但它仍然不起作用...
您按值而不是 by reference 传递了变量 price
。此构造在 Lua 中不存在,因此您需要解决它,例如使用 return 值:
DeckOfPlayingCardsPrice, DeckOfPlayingCardsText, DeckOfPlayingCardsQuantityText = BuyItem(DeckOfPlayingCardsPrice, [...], DeckOfPlayingCardsText, DeckOfPlayingCardsQuantityText)
和return正确的期望值:
function BuyItem(price, quantity, pps, text, quantitytext)
if(PixoosQuantity >= price) then
[...]
end
return price, quantity, quantitytext
end
在 Lua 你可以 return multiple results.