Page 1 of 1

love.keypressed

Posted: Thu Jan 03, 2013 10:22 am
by XF3DeX
Hello. I have a question about LÖVE/Lua.

I'm not sure I understand how functions work in Lua.
Let me explain more:

In my main.lua file I have

Code: Select all

function love.update(dt) end
function love.draw() end
function love.keypressed(k,u) end
There is another file "Card.lua" where I have:

Code: Select all

function Card:draw() end
function Card:update(dt) 
   if bla-bla then
      bla-bla
   end
   function love.keypressed(k,u)
      if (bla) then bla end
   end
end
I defined the function love.keypressed inside another function in another file. How does that work?
Why does this function overwrites the same function at "main.lua"

Thanks

Re: love.keypressed

Posted: Thu Jan 03, 2013 11:22 am
by mickeyjm
by redefining love.keypressed() in cards.lua you overwrite the old one because otherwise when it is called LOVE wouldn't know which function to run. If you want to do an action in cards.lua when a key is pressed something like this would be best:


In main.lua:

Code: Select all

function love.keypressed(k,u)
    Card:keypressed(k,u) --Pass the function on
end
In cards.lua:

Code: Select all

function Card:keypressed(k,u)
    if (bla) then bla end
end
Just make sure Card is global and it should work

If you want he function to fire all the time the key is down do this:

Code: Select all

function Card:update(dt)
    if love.keyboard.isDown(bla) then
         bla
    end
end
And be sure to call Card:update(dt) in love.update in main.lua like I did with love.keypressed

Re: love.keypressed

Posted: Thu Jan 03, 2013 12:07 pm
by Lafolie
Pretty sure you shouldn't be defining functions like that. A fun and effective way to use the callbacks is with states and objects (or tables). Your states can be objects or just tables themselves.

Code: Select all

tbl = {"Obey"}
tbl.func = function(self) print(self[1]) end

tbl:func()
--Obey
tbl.func(tbl)
--Obey
tbl.func()
--Probably errors
There's more than one way to assign a function too:

Code: Select all

f = function() end
function f() end
I prefer to use the former because I like to think of it as assigning a value like you would with any other data type.

Re: love.keypressed

Posted: Thu Jan 03, 2013 11:22 pm
by XF3DeX
Thanks guys