love.keypressed

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
XF3DeX
Prole
Posts: 2
Joined: Fri Dec 28, 2012 3:55 pm

love.keypressed

Post 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
User avatar
mickeyjm
Party member
Posts: 237
Joined: Thu Dec 29, 2011 11:41 am

Re: love.keypressed

Post 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
Your screen is very zoomed in...
User avatar
Lafolie
Inner party member
Posts: 809
Joined: Tue Apr 05, 2011 2:59 pm
Location: SR388
Contact:

Re: love.keypressed

Post 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.
Do you recognise when the world won't stop for you? Or when the days don't care what you've got to do? When the weight's too tough to lift up, what do you? Don't let them choose for you, that's on you.
XF3DeX
Prole
Posts: 2
Joined: Fri Dec 28, 2012 3:55 pm

Re: love.keypressed

Post by XF3DeX »

Thanks guys
Post Reply

Who is online

Users browsing this forum: Ahrefs [Bot], Bing [Bot] and 9 guests