[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Colon notation in object-oriented programming
- From: Dirk Laurie <dirk.laurie@...>
- Date: Sun, 5 Mar 2017 13:32:44 +0200
2017-03-04 8:32 GMT+02:00 Petri Häkkinen <email@example.com>:
> 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.
I and others replied to the above in the thread "Lua and composition",
but maybe it deserves a thread of its own.
Let me take an example from the only userdata objects supplied with
Lua, namely files.
One can write:
Without colon notation, how far can we get?
local outfile = io.open("results.txt","w")
Now what next? Remember, outfile:write() is not available.
And io.write does not allow you to specify a file.
local filemeta = getmetatable(outfile).__index
Faster? Really? Clearer? Not on your nelly.
Now you can argue that the programmer is under no obligation
to hide the methods of a file object that well, but the point is that
you can't easily, by accident, call the write or close methods without
a valid file argument in place. This makes code safer and cleaner.