TextBox = {} TextBox.__index = TextBox function TextBox:new(x, y, width, height, options) local options = options or {} local o = { text = "", x = x, y = y, width = width, height = height, borderColor = options.borderColor or {0, 0, 0}, bgColor = options.bgColor or {.75, .85, .75}, fgColor = options.fgColor or {0, 0, 0}, font = options.font or love.graphics.newFont(24), cursorOnTime = options.cursorOnTime or .35, enabled = true, focused = true, cursorOn = true, cursorTime = 0, } if options.enabled == false then o.enabled = false end if options.focused == false then o.focused = false end if not o.enabled then o.cursorOn = false; o.focused = false end setmetatable(o, TextBox) return o end function TextBox:blink(dt) if not self.focused then return end self.cursorTime = self.cursorTime + dt if self.cursorTime >= self.cursorOnTime then self.cursorTime = self.cursorTime - self.cursorOnTime self.cursorOn = not self.cursorOn end end function TextBox:draw() if not self.enabled then return end love.graphics.setLineWidth(3) love.graphics.setColor(unpack(self.borderColor)) love.graphics.rectangle("line", self.x, self.y, self.width, self.height, 10, 10) love.graphics.setLineWidth(1) love.graphics.setColor(unpack(self.bgColor)) love.graphics.rectangle("fill", self.x, self.y, self.width, self.height, 10, 10) love.graphics.setColor(unpack(self.fgColor)) love.graphics.setFont(self.font) love.graphics.print(self.text, self.x+15, self.y+7) local mx = 15 + self.font:getWidth(self.text) love.graphics.setLineWidth(2) if self.cursorOn then love.graphics.setColor(unpack(self.fgColor)) love.graphics.line(self.x+mx, self.y+7, self.x+mx, self.y+self.height-10) else love.graphics.setColor(unpack(self.bgColor)) love.graphics.line(self.x+mx, self.y+7, self.x+mx, self.y+self.height-10) end end function TextBox:append(t) if not self.focused then return end if self.font:getWidth(self.text..t) < self.width - 30 then self.text = self.text .. t end end function TextBox:delete() if not self.focused then return end if #self.text > 0 then self.text = self.text:sub(1, -2) end end function TextBox:clear() if not self.focused then return end self.text = "" end function TextBox:keypressed(key) if key == "backspace" then self:delete() end end setmetatable(TextBox, {__call=TextBox.new}) return TextBox