OOP shenanigan

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
User avatar
Notsure
Prole
Posts: 7
Joined: Fri Mar 03, 2017 11:35 pm

OOP shenanigan

Post by Notsure »

Not really a question, but more something intriguing and useful for anyone who wants to use it; and to see who else has used this.

I've created an Object-esque table for a ball, and I wanted to have that object associated with it's own box2D body, shape, and fixture, for easy referencing in the future. Much pain and metatables later, I arrive at this solution:

Code: Select all

function ball.mt.__call(self,index,...)
--It's a series of look-ups. Nothing special,really.
	if(type(ball[index])=='function') then --ball class
		return ball[index](self,...);
	elseif(type(self.fixture[index])=='function') then --love.physics.fixture
		return self.fixture[index](self.fixture,...);
	elseif(type(self.fixture:getBody()[index])=='function') then --love.physics.body
		return self.fixture:getBody()[index](self.fixture:getBody(),...)
	elseif(type(self.fixture:getShape()[index])=='function') then --love.physics.shape
		return self.fixture:getShape()[index](self.fixture:getShape(),...)
	end
end	
This produces an intresting syntax when calling functions of associated userdata/tables:

Code: Select all

ball_obj("Function_Index",Argument1,Argument2)
If anyone has used this solution before, is there anything simpler or any major problems with it?
:crazy: kek :crazy:
User avatar
ivan
Party member
Posts: 1911
Joined: Fri Mar 07, 2008 1:39 pm
Contact:

Re: OOP shenanigan

Post by ivan »

My first reaction is that it doesn't look clear.
You're basically re-routing function calls (which is unnecessary) and results in weird looking syntax.
I mean, sure, it might work but I don't see any advantage over calling the functions directly.
Also, one body may have several fixtures, and complex game objects may have multiple bodies connected with joints.
Lastly, the point of OO programming is encapsulation, so when you provide access to the internal stuff (like self.fixture) then the rest of your code becomes closely coupled with the "object" and in this case, Box2D.
If you're going to use OO programming, you might as well wrap the object so that it provides some sort of "higher level" API.
If anyone has used this solution before
What exactly is the problem you are trying to solve?
Post Reply

Who is online

Users browsing this forum: Google [Bot] and 96 guests