Any way to make textbox inputs?
Posted: Tue Apr 10, 2012 12:28 am
Is there a way to make a textbox input in love?
I don't have experience with this, But i can think of a way to do it..So you'd probably have a variable assigned to the text in the textbox. Then on love.keypressed() you'd add whichever key was pressed to that string..something like this:CDCosma wrote:Is there a way to make a textbox input in love?
Code: Select all
function love.load()
str = ""
end
function love.draw()
love.graphics.print(str, 10, 10)
end
function love.keypressed(key)
str = str..key
end
Code: Select all
Textbox = {}
Textbox.__index = Textbox
function Textbox.create(x, y, max)
local temp = {}
setmetatable(temp, Textbox)
temp.hover = false
temp.selected = false
temp.text = ""
temp.max = max
temp.width = font["default"]:getWidth("a") * 16
temp.height = font["default"]:getHeight()
temp.color = color["text"]
temp.x = x
temp.y = y
return temp
end
Code: Select all
function Textbox:draw()
love.graphics.setColor(self.color)
if self.selected then
love.graphics.setColor(unpack(color["hover"]))
end
love.graphics.quad("line", self.x, self.y, self.x + self.width, self.y, self.x + self.width, self.y + self.height, self.x, self.y + self.height)
love.graphics.setFont(font["default"])
love.graphics.setColor(self.color)
love.graphics.print(self.text, self.x, self.y)
end
Code: Select all
function Textbox:update(dt)
local x = love.mouse.getX()
local y = love.mouse.getY()
if x > self.x
and x < self.x + self.width
and y < self.y + self.height
and y > self.y then
self.hover = true
else
self.hover = false
end
end
Code: Select all
function Textbox:mousepressed(x, y, button)
if self.hover then
self.selected = true
else
self.selected = false
end
end
function Textbox:keypressed(key)
if string.len(self:getText()) < self.max then
if self.selected then
if key == "backspace" then
local str = self:getText()
self:setText(string.sub(str, 1, string.len(str) - 1))
elseif key:match("[A-Za-z0-9]") and not in_table(key_disable, key) then
local str = self:getText()
local newKey = key
if love.keyboard.isDown("shift") then newKey = string.upper(key) end
str = str .. newKey
self:setText(str)
end
end
end
end
Code: Select all
key_disable = {
"up","down","left","right","home","end","pageup","pagedown", --Navigation keys
"insert","tab","clear","delete", --Editing keys
"f1","f2","f3","f4","f5","f6","f7","f8","f9","f10","f11","f12","f13","f14","f15", --Function keys
"numlock","scrollock","ralt","lalt","rmeta","lmeta","lsuper","rsuper","mode","compose", "lshift", "rshift", "lctrl", "rctrl", "capslock", --Modifier keys
"pause","escape","help","print","sysreq","break","menu","power","euro","undo" --Miscellaneous keys
}