This is my first time using lua and the first thing I have made with it, this is not my first programming language however and I want to know how I can improve my lua code.
I have wrote this, it just makes "LOL?" Fade and enlarge where you click but after a few clicks the program really starts to lag, why could this be? Is it my code or is it Love?
I realise that a few things can be done (making things else if, but I wasn't sure how to do that in lua) but I doubt they'd hinder the performance
function load()
love.graphics.setFont(love.graphics.newFont(love.default_font, 20))
text = "LOL?"
alpha = 255
size = 20
love.mouse.setVisible(false)
X = love.mouse.getX()
Y = love.mouse.getY()
end
function update(dt)
temp = angle
if alpha >= 0 then
alpha = alpha - 15
end
if alpha < 0 then
click = false
alpha = 255
end
if alpha % 10 then
size = size + 1
end
if click == false then
alpha = 255
size = 20
end
X = love.mouse.getX()
Y = love.mouse.getY()
end
function draw()
love.graphics.setColor(255, 255, 255, 255)
love.graphics.setFont(love.graphics.newFont(love.default_font, 20))
love.graphics.draw(text, X, Y)
if click then
love.graphics.setColor(255, 255, 255, alpha)
love.graphics.setFont(love.graphics.newFont(love.default_font, size))
love.graphics.draw(text, tempX, tempY)
end
end
function mousepressed(x, y, button)
if button == love.mouse_left then
click = true
tempX = x
tempY = y
end
end
font_cache = {}
function setfont(s)
if not font_cache[s] then
font_cache[s] = love.graphics.newFont(love.default_font, s)
end
love.graphics.setFont(font_cache[s])
end
function load()
setfont(20)
text = "LOL II?"
alpha = 255
size = 20
love.mouse.setVisible(false)
X = love.mouse.getX()
Y = love.mouse.getY()
end
function update(dt)
temp = angle
if alpha >= 0 then
alpha = alpha - 15
end
if alpha < 0 then
click = false
alpha = 255
end
if alpha % 10 then
size = size + 1
end
if click == false then
alpha = 255
size = 20
end
X = love.mouse.getX()
Y = love.mouse.getY()
end
function draw()
love.graphics.setColor(255, 255, 255, 255)
setfont(20)
love.graphics.draw(text, X, Y)
if click then
love.graphics.setColor(255, 255, 255, alpha)
setfont(size)
love.graphics.draw(text, tempX, tempY)
end
end
function mousepressed(x, y, button)
if button == love.mouse_left then
click = true
tempX = x
tempY = y
end
end
The problem is that love.graphics.newFont rasterizes all letters via FreeType and then creates OpenGL textures of each and every letter. Doing this each frame is really one of the things that will kill performance.
The version above will still lag the first "click", because the fonts are created between frames, but that can easily be fixed by preloading the fonts in load().