Can functions and operators be overloaded?

Functions cannot be overloaded, at least not at compile time.

However, you can 'overload' based on the types of the arguments you receive. Say we need a function which can operate on one or many numbers:

function overload(num)
 if type(num) == 'table' then
 for i,v in ipairs(num) do
 overload(v)
 end
 elseif type(num) == 'number' then
 dosomethingwith(num)
 end end

The usual operators can be overloaded using metamethods. If an object (either a Lua table or C userdata) has a metatable then we can control the meaning of the arithmetic operators (like + - * / ^), concatenation .., calling () and comparison operators == ~= < >.

Overriding () allows for 'function objects' or functors, which can be used wherever Lua expects something that is callable.

Note a restriction on overloading operators like ==: both arguments must be of the same type. You cannot create your own SuperNumber class and get sn == 0 to work, unfortunately. You would have to create an instance of SuperNumber called Zero and use that in your comparisons.

You can control the meaning of a[i] but this is not strictly speaking overloading the [] operator. __index fires when Lua cannot find a key inside a table. __index can be set to either a table or to a function; objects are often implemented by setting __index to be the metatable itself, and by putting the methods in the metatable. Since a.fun is equivalent to a['fun'], there is no way to distinguish between looking up using explicit indexing and using a dot. A naive Set class would put some methods in the metatable and store the elements of the set as keys in the object itself. But if Set a method 'set', then s['set'] would always be true, even though 'set' would not be a member of the set.

The size operator and action when garbage-collected can be overridden by C extensions, not by plain Lua 5.1. This is restriction has been removed for Lua 5.2.



Back