-2

How can I make a text box to be able to enter numbers using them to calculate in love2d ?

ad absurdum
  • 19,498
  • 5
  • 37
  • 60

1 Answers1

0

steps:

  • (optional) capture mouse / touch location
  • store input, in a string variable
  • sanitize input, make sure there aren't unexpected chars
  • calculate results, use load(str) then execute that ()
  • print results

Capturing mouse is optional, only required if your app has more than one function. If it's a single-use app that only calculates what you type in, there's no need for that first step. However, if there are other selectable locations on the screen, you'll need a way to determine that the user desires that input area. There are a few GUI libs that help with this, or you can simply test if it's within the expected screen x,y region.

function love.load()
    fontsize = 16
    fontname = "font.ttf"
    font = love.graphics.newFont( fontname, fontsize )

    input_x_min = 20
    input_x_max = 400

    input_y_min = 20
    input_y_max = input_y_min +fontsize *2

    allowed_chars = "1234567890()+-*/"
    love.keyboard.setTextInput( false )
    input_text = "result="  --  for storing input
    result = nil  --  empty placeholder for now

    output_x = 20
    output_y = 40
    output_limit = 400
end


function love.update(dt)
    local x, y = love.mouse.getPosition()
    -- could also capture mouseclicks here, and/or get touch events

    if x >= input_x_min and x <= input_x_max
    and y >= input_y_min and y <= input_y_max then
        love.keyboard.setTextInput( true )
    else
        love.keyboard.setTextInput( false )
        input_text = "result=" -- no longer selected, reset input
    end
end


function love.textinput(t)
    for i = 1, #allowed_chars do -- sanitize input
        if allowed_chars :sub(i,i) == t then -- if char is allowed
            input_text = input_text ..t -- append what was typed

            generate_result, err = load( input_text ) -- "result=3+(2*2)"
            if err then print( err )
            else generate_result() -- function() return result=3+(2*2) end
            end
        end
    end
end


function love.draw()
    love.graphics.printf( input_text, output_x, output_y, input_limit )
    love.graphics.printf( result, output_x, output_y, output_limit )
end
Doyousketch2
  • 2,060
  • 1
  • 11
  • 11
  • 1
    If you don't want to have it in a global variable, you can get rid of the `"result="` bit and use `load('return ' .. input_text)`. You can then get the return value with `generate_result()`. – Jasmijn Feb 19 '21 at 12:33