Chainable affine transforms

This is just a minor QoL request, but it would be nice if affineTransforms which mutate the caller returned self to enable chaining. Consider something like this:

-- create a transform
local t = geom.affineTransform.new()

-- apply a series of transformations
t:rotate(90)
t:translate(10, 10)
t:scale(2)

-- use the transform
local v2 = t * v1

Which could be written more succinctly as:

local v2 = t:rotate(90):translate(10, 10):scale(2) * v1

Note that this is already possible for non-mutating variants, since by definition they return a copy:

local t2 = t:rotatedBy(90):translatedBy(10, 10):scaledBy(2)

You could reassign the result to t instead of t2, of course, but that's inefficient.

One could argue that the unchained version is better for clarity, but supporting chaining would leave that choice to the developer without impacting current usage. The proposed change would also mean that the two variants behave more similarly.

2 Likes

Do these methods not return values? I haven't used the Lua API personally, and the Inside Playdate documentation doesn't mention anything about return values (which I guess means there are none).

I've always thought of void as a sort of "only as necessary" return type. If there's some meaningful thing that could be returned from a function, it should be returned rather than just using void. My personal pain point in this regard is sorting operations: neither Java's sort() methods (Arrays, Collections) nor .NET's List<T>.Sort() return anything and it makes them somewhat inconvenient to use. (I do get a lot of mileage out of Enumerable.OrderBy(), though).

+1 on having these methods return self. I don't see how that could break any existing code.

yeah, this seems legit. The only possible issue I can think of is it's not clear that you're changing t here

local v2 = t:rotate(90):translate(10, 10):scale(2) * v1

because you're also using the return value of the chain in a separate operation, but I'm all for making functions more flexible. I'll file it!

1 Like

Whoops, hit the wrong button. I had a post about how looking ahead about five feet can save a person a lot of grief.