Page 1 of 1

Function not running?

Posted: Sun Apr 29, 2012 2:54 pm
by Neon
So, I'm making a small little lib to make it easier to make graphics. I'm giving each button a function to run, if they are clicked.

Code: Select all

function love.mousepressed(x, y, button)
	for k, obj in pairs(Objects) do
		if obj.objtype == "Button" and x > obj.xpos and x < obj.xpos + obj.width and y > obj.ypos and y < obj.ypos + obj.height and button == 1 then
			obj[click]()
		end
	end
end
It registers when the object is clicked fine, but it won't run the function stored in the click variable.

The function is added like so.

Code: Select all

function Lib.addFunc(objname, functype, func)
	Objects[objname][functype] = func
end
Example of calling it.

Code: Select all

Lib.addFunc("MyButton", "click", function()
Lib.edit("MyLabel", "words", "BUTTON WORKED")
end)
The above function adds a function that changes the text of the "MyLabel" object when "MyButton" is clicked (because when it's click, it should run it's clicked function).

So, when the button is clicked, it should run it's click function stored in the click variable, but it doesn't change the text when clicked, and doesn't run the function. If anyone understood, can they help?

By the way, if anyone needs so the the createButton function, here.

Code: Select all

Lib = {}
Objects = {}

function Lib.createButton(objname, x, y, h, w, stat, r, g, b)
	Objects[objname] = {objtype = "Button", xpos = x, ypos = y, height = h, width = w, status = stat, red = r, green = g, blue = b, click = nil} --click is set to nil because it's added later with the Lib.addFunc function.
end

Re: Function not running?

Posted: Sun Apr 29, 2012 3:05 pm
by kikito
There are several problems.

The first one is that the "button" paramter in love.mousepressed is never a "1". It's always one of the MouseConstants: "l", "m", "r", "wd", "wu", "x1" or "x2".

The second problem that you will have is that the click variable is nil, so this code will fail:

Code: Select all

obj[click]()
Instead, try this:

Code: Select all

obj:click()
There is also a bit of an issue with code cleanup. I'd move the "is this point inside the object" function to your objects. This way, the mousepressed function can look like this:

Code: Select all

function love.mousepressed(x, y, button)
  if button ~= "l" then return end
  for _,obj in pairs(Objects) do
    if obj:contains(x,y) then
      obj:click()
    end
  end
end
And then implement "contains" on all the buttons, etc that you have (probably using metatables and __index, so you don't have to store the same function again and again in all objects).

Re: Function not running?

Posted: Sun Apr 29, 2012 3:43 pm
by Neon
Thanks! It worked.

Re: Function not running?

Posted: Thu May 03, 2012 10:19 am
by sweetyang2012
I ever face the same problem and i can't slove it .At last,i change a my computer ,all is ok then.