Using numericField

Hi, I’m trying to create a game where the player has to correctly guess the number of bats that have entered a cave.
I created the variables ‘purplebatCount’ and ‘greenbatCount’ so they would increase by 1 when a bat of that colour (purple or green in this case) entered the cave. How would I use ‘numericField’ so the player can input the correct number?

function timerDown(event)
  timeLimit = timeLimit - 1

  if timeLimit== 2 then

      print("screenfade")
      transition.to( background, { alpha=0.5  } )
      transition.to( cave, { alpha=0  } )
 end
  if timeLimit == 0 then --When the time reaches 0, a random question will appear
    randomImage = math.random(1,4)
 end
    local purplebatCount -- Number of purple bats that entered the cave
    local greenbatCount -- Number of green bats that entered the cave
   -- How many purple bats entered the cave?
    if randomImage == 1 then
     print("purpleMessage")
      purpleMessage = display.newImageRect( mainGroup, "purpleMessagep.png",  500, 500)
      purpleMessage.x = display.contentCenterX
      purpleMessage.y = display.contentHeight - 200
      numericField = native.newTextField( 155, 255, 90, 30 ) -- Number text box
     numericField.inputType = "number"
      end
--How many green bats entered the cave?
    if randomImage == 2 then
      print("greenMessage")
      greenMessage = display.newImageRect( mainGroup, "greenMessageg.png",  500, 500)
      greenMessage.x = display.contentCenterX
      greenMessage.y = display.contentHeight - 200
      numericField = native.newTextField( 155, 255, 90, 30 ) -- Number text box
      numericField.inputType = "number"
    end

I’m relatively new to using Lua so you’ll need to explain this to me in a way I’ll understand if that’s ok. :+1:
Thanks :grinning:

Expanding the sample code that can be found on documentation to fit your needs. This should do the trick.

local numericField
 
local function checkAnswer()
      -- check submitted answer
end

local function textListener( event )
 
    if ( event.phase == "began" ) then
        -- User begins editing "numericField"
    elseif ( event.phase == "ended" or event.phase == "submitted" ) then
        checkAnswer()
    end
end
 
-- Create text field
numericField = native.newTextField( 150, 150, 180, 30 )
numericField.inputType = "number"
numericField:addEventListener( "userInput", textListener )

Also, do remember that the values of the the textfield is going to be a string, so you’ll need to change it to number via tonumber before comparing it to numeric values.

1 Like