lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

[Peter Odding]
Should the Lua API be extended to (transparently) treat callable objects as functions in the appropriate contexts?

It's called OO - objects responding to method calls / messages :)

The metatable is the method table, with a few entries special-cased to go through a fast vtable-like dispatch vector.

For numbers, strings, functions, the methods are treated as class methods (there is only one method table).

For tables and userdata, the methods are instance methods. So Lua's internal type tag is really mostly needed for numbers, strings, etc - to locate the proper metatable, whereas with tables and userdata it's all metatable dispatch as in any other pure OO implementation.

And so on... I'm not saying anything new here.

A notation of the form "foo(...)" is a method call using the "__call" method. This doesn't work for all lexical token types, i.e "1(...)", though that may be rewritten as "(1)(...)". IOW, there are some syntactical restrictions.

As for semantics, it seems to me that Lua is already close to treating any type as an object which is indeed callable (if it has a __call).

The "table.sort" case which Petite Abeille (little bee?) started this thread with appears to be an anomaly, in that the C code does not behave in the same way as Lua scripts. Perhaps there is another less important anomaly with functions not having a __call entry in their metatable yet by definition still being callable (I haven't looked into the source code).

If you look at in in general, syntax is just a vehicle to express a sequence of method calls. Good ol' BCPL was a language which used only syntax to distinguish methods, everything had the same data type (a word). It had a single metatable to speak in Lua terms, so "1(2)" would happily call the function at (word-) address 1 with argument 2 - which in turn could well be a function pointer, if the proper value was stored at address 2.

I agree with Miles and Steve (the next response) that it could be really useful if the Lua API and standard libraries were to make more use of Lua's metamethods (eating one's own dog food so to speak).

Assuming all the important metamethods use fast-track tricks internally to avoid slowing down the common cases, I think it would indeed make Lua "purer" (fewer concepts, fewer exceptional cases).