The best way to return structures
#1

The most common structure you use in SA-MP is a position (or a vector) Float:X, Float:Y, Float:Z. Now, all functions like SetPlayerPos and GetPlayerPos use the parameter way of accepting and returning (via by-ref parameters) this structure, but is there a better way?

It's occured to me during the writing of i_quat that I needed a function to return a quaternion (consisting of 4 Float numbers). Now I had multiple methods of returning this:

Code:
stock ReturnQuat(&Float:w, &Float:x, &Float:y, &Float:z)
stock ReturnQuat(Float:quat[4]) quat[0] = w, quat[1] = x //etc.
stock ReturnQuat() { Float:quat[4]; ... return quat; }
Which of these three methods you think is the best? The first method has the advantage of choosing a destination you wish for all returned values, be it a quadruple of variables or an array indices, but it's too long if you use it regularly. The second method is shorter and faster to use, but you have to remember which index means what (e.g. if it's WXYZ or XYZW). The third one can be used to easily pass its return to another function, but if you already have an array allocated for the return, it does another needless allocation. And you still cannot use the return like new Float:quat[4] = ReturnQuat();, because the expression has to be constant.

Which of these ways is the best one? I want my script to use standardized and most useful conventions for handling this.
Reply
#2

I'd say go with first one, if someone wants an array (like me), they'll do it themselves. Also it's consistent with samp API
Reply
#3

First one because you have a option to choose from. Lets say i just need Z coordinate, so i can:
pawn Code:
new Float:z;
GetPlayerPos(playerid, z, z, z);
(no more than one allocation)
Reply
#4

Gammix, there is no guarantee that the z coordinate will be set last. It could change in future releases or other functions.
Reply
#5

Quote:
Originally Posted by Macluawn
View Post
Gammix, there is no guarantee that the z coordinate will be set last. It could change in future releases or other functions.
This really. That example is bad practice and (imo) leads to confusing code.
Reply
#6

I believe the first one is the fastest.
Reply
#7

I am not that sure because each time you return something pawn will allocate it into the heap (if it is bigger than one cell)
The best way would be to use a third parameter for the output
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)