Overload Resolution

Overload resolution is the runtime process of determining which method to call based on the given arguments. Because Lua is a dynamic language, the runtime needs to find which one to call. This is similar to that of C#. Two C# delegates can be registered to the same name in Lua. When the function is invoked in Lua, the arguments are used to determine which overload should be invoked according to C# overload resolution.

Determining Which Method

Overload resolution operates similarly than in C#. When choosing between two methods, the one that requires less conversions is better than one with more. A method with more explicit arguments is better than one with less (through optional arguments or params arrays). Ones without a params array is better than one with. If there is two overloads with the same desirability, then an AmbiguousMatchException is thrown.

Converting Arguments

When an argument is given in Lua code, it may need to be converted to work in C# (e.g. numbers). The value is converted if that method is chosen. A value can be converted if (a) one of the types (the current type or the resulting type) defines a valid cast, (b) if the value is a table and the result is an array, or (c) the value is a number. The converter supports both implicit and explicit casts. All primitive number types are supported.

Specifying an Overload

When there is ambiguity, there is a need to specify which overload you want to call. There are two ways to do this. One is to use the new framework method overload that takes a method and the zero-based index of the overload to invoke. This is suggested for reverse-compatibility. The other option is to use a grave ` character in the name and then add the index. If the method(s) were registered using lua.Register, then the indicies are the order that they were added.

If the overloads are for member methods, then by default the indexing is in the order returned by MethodInfo.GetMethods which is usually in the order they are defined in the source. If you want to specify explicitly which overloads are which in your classes, you can attach an OverloadAttribute to the methods and give the index you want to use as the argument. Any methods that are not marked with the attribute will be given the first index that is not specified by another OverloadAttribute. If there is a conflict in an index, an exception will be thrown.

-- these perform the same action
-- note that overload returns a method object
ret = overload(Func, 2)("Arguments")
ret = Func`2("Arguments")

Last edited May 26, 2013 at 3:51 AM by ModMaker, version 2


No comments yet.