Blackhardd wrote:I know it's more related question for LUA then for Love2D but i'm asking for help. I had just two simple lua scipts.
First is "buttons.lua"
and "main.lua"
I'm trying to create function that creates and draw buttons and i am totally don't understand why it doesn't works. I'll be glad if you tell me where is the problem. I am newbie at programming.
Regards Blackhardd.
The problem you're having isn't with functions -- it's with how variables work.
First, let's look here.
Code: Select all
function createBtn( imgPath, btnName )
btnName = love.graphics.newImage(imgPath)
end
In the top part, btnName is defined as a
local variable representing what the second argument is, as a
value. What you're doing here is instead overwriting that local variable, NOT the variable named in the second argument.
Code: Select all
function createBtn( imgPath, btnName ) -- Here, a local variable is created called btnName, and it has a value of whatever the second argument is when the function is called.
btnName = love.graphics.newImage(imgPath) -- But here, the variable btnName's value changes from being the second argument to the ID of the image.
end -- The "end" statement marks the end of the code block, and all local variables in the code block it ends are forgotten by Lua.
It gets worse. Here, there's an even bigger problem with calling the function:
Code: Select all
require("buttons")
function love.load()
createBtn("Sprites/Menu/exit.png", exit_btn) -- exit_btn is entered as a variable, not a string. And since exit_btn has nothing assigned to it, the second argument is passed as nil, or "nothing".
end
Finally, it would be ten times as efficient if you just assigned it directly, since all you're doing here is literally this:
Code: Select all
function love.load()
exit_btn = love.graphics.newImage("Sprites/Menu/exit.png")
end
function love.update(dt)
end
function love.draw()
love.graphics.draw(exit_btn, 200, 200)
end