简体   繁体   中英

Update object's text in Solar2D (ex-CoronaSDK)

I want to display a text with a number and to update the number when pressing a button. Here is what I got right now:

local oxyPar = 10
--the oxyPar is just a number

local oxyOpt =
{
   text = "Oxygen: ".. tostring( oxyPar )
   --all other text parameters
  }

local oxygen = display.newText( oxyOpt )
--display a text calling oxyOpt table for the parameters

local timeOpt =
{
   --all the button parameters
   onRelease = timeOn
   --call timeOn function on the button release
}

local timeBtn = widget.newButton( timeOpt )
--a button that calls timeOpt table for the parameters

local function timeOn( listener )
   oxyPar = oxyPar + 1
end

After pressing the button the oxyPar (the number) should grow by one, but the text still shows up Oxygen: 10 instead of Oxygen: 11 . Is there a way to update the text so it shows the new number?

changing oxyPar does not affect your display object oxygen .

A number value is copied by value so

local oxyPar = 10
local oxyOpt = {text = tostring(oxyPar)}
local oxygen = display.newText( oxyOpt )

is equivalent to

local oxyOpt = {text = "10"}
local oxygen = display.newText( oxyOpt )

There is no relation between oxyPar and oxyOpt as you simply copied the return value of tostring(10) into oxyOpt.text which is a different variable.

Change ogygen.text instead

Please refer to the Solar2d reference manual.

https://docs.coronalabs.com/api/library/display/newText.html

Updating Text Post-Creation

local myText = display.newText( "hello", 100, 200, native.systemFont, 12 ) myText:setFillColor( 1, 0, 0.5 ) -- Change the displayed text myText.text = "Hello World!"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM