Operator Lookup

From Xojo Documentation

Global Method

Operator_Lookup(name As String)

Supported for all project types and targets.

Allows the class to handle dot notation references that are not class members.


Global Method

Operator_Lookup(name As String) As Type

Supported for all project types and targets.

Allows the class to handle dot notation references that are not class members and return a value.

Notes

Use Operator_Lookup to define a function that will be called if the called item cannot otherwise be found in the class.

Operator_Lookup overloads a class's lookup operator. The method's first parameter must be a String which will receive the name of the desired member. The method can have any combination of other parameters and can have any return type. The Operator_Lookup operator is called whenever you use the foo.bar syntax to look up a member of an object and the compiler can't find anything named "bar". Before it returns an Undefined Identifier error, the compiler will try to call a lookup operator and pass "bar" as the first parameter. Overloading works for the lookup operator just as it does for any other method.

fa-exclamation-circle-32.png
If you implement Operator_Lookup on a class, you will no longer get compilation errors if you, for example, inadvertently misspell a property name. Instead, the Operator_Lookup method is called at runtime and is passed the name of your incorrectly spelled property.

Sample Code

Gets values entered as dot notation from a Dictionary and returns the value:

// Gets values entered as dot notation from a dictionary
// MyClass.AnyName returns what is in
// ValueDict.Value("AnyName")

Function Operator_Lookup(name As String) As String
If ValueDict.HasKey(name) Then
Return ValueDict.Value(name)
Else
Return ""
End If
End Function

This code defines "SquareLength" in the Vector class (see Operator_Add), a class with two integer properties, x and y.

Function Operator_Lookup(Name As String) As Double
If Name = "SquareLength" Then Return Self.x^2 + Self.y^2
End Function

When you write:

Var myDouble As Double
myDouble = myVector.SquareLength

it will return the result of the calculation. However, you can also write:

myDouble = myVector.UndefinedFunction // does not exist

and it will compile and run, returning zero. This can lead to difficult to track down errors.

See Also

Operator Overloading