| Andreas Rozek |
|
Lua_04 - Tag Methods for Numerical OperatorsWhenever a numerical operator is applied on a non-numeric operand, Lua invokes a related tag method (if defined, otherwise the script is aborted with an error message). "Lua_04" exploits this mechanism and defines a new numerical data type whose instances may be used within arithmetic expressions just like any other value of type "number". Similar to the programming language Python [2,3] any binary operator is represented by two methods - the first one is used if the left operand (or both) is of the object type, the other one handles the situation when only the right operand is of the object type. Like so often, this facility is demonstrated using complex numbers: based on the mechanisms introduced by "Lua_03", "Lua_04" defines a new "class" called "Complex" with methods for basic numeric operations and comparisons. These methods are then registered as tag methods for the corresponding Lua operators. "Lua_04" should be invoked without any command line arguments lua Lua_04.lua and yields the following output: Lua_04 - experiments with tag-methods for numeric operators
complex numbers:
a = 1.0+i*1.0 = 1+i*1
b = 2.0 = 2
c = i*3.0 = 0+i*3
basic operators:
-a = -1-i*1
-c = 0-i*3
a+b = 3+i*1
a+c = 1+i*4
a-b = -1+i*1
a-c = 1-i*2
a*b = 2+i*2
a*c = -3+i*3
a/b = 0.5+i*0.5
a/c = 0.3333333333333333-i*0.3333333333333333
It is recommended to analyze this output along with the source code - this clarifies the proper behaviour of the abovementioned functions and methods. Source CodeThe source code of this example is available for download:
As the functions defined within "Lua_04.lua" will also be used in other programming examples, they may be downloaded separately as a Lua script file:
References
|
| http://www.Andreas-Rozek.de/Lua/Acquainting/Lua_04_en.html | (last Modification: 15.04.2002) |