[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Lua and composition
- From: Petri Häkkinen <petrih3@...>
- Date: Sat, 4 Mar 2017 09:32:20 +0200
On Mar 4, 2017, at 8:48 AM, Dirk Laurie <dirk.laurie@gmail.com> wrote:
>> Why all the trouble? I mean, you could just use free functions:
>> object_system_func(a, b, c)
>>
>> This is faster (no need for nested dynamic table look ups) and there is no need for "self" parameter that is magically more important than the others. Also you don't need to artificially invent new classes just because you want to add a function that does not naturally fit into your existing class hierarchy.
>
> I agree with all you say — but since 5.2 Lua actually has a VM instruction
> for object-oriented access, and it does make some kinds of code look
> cleaner, especially when the object is a userdata but all the other
> parameters are simple scalars.
>
I'm trying to come up with an example where the OOP style is more cleaner (could you give an example?)..
e.g. in my mind the syntactic difference between the two styles in the following case is irrelevant in practice:
obj:draw_rectangle(x, y, w, h)
vs.
canvas_draw_rectangle(obj, x, y, w, h)
On the other hand when functions take multiple objects as parameters the implicit self starts to feel like an oddball. A classical example:
ray:intersect(box) -- huh? should the intersect method be in ray or box class? or maybe some sort of intersection_calculator class ;-D
vs.
intersect_ray_box(ray, box)
Another advantage of the imperative style:
-- OOP
for i=1,#objs do
objs[i]:do_something()
end
function myclass:do_something()
-- code here
end
vs.
-- imperative
do_something(objs)
function do_something(objs)
for i=1,#objs do
-- code here
end
end
The latter can be much faster when the number of objs is large (no metamethod look ups and function calls per obj). Of course you could do this with OOP too, but you tend not to because you mind is so distracted by all those classes :)