Andreas Rozek Hints for Reading List of Recent Changes Guestbook Entry Contact the Author  Deutsche Version  HomePage Previous Topic Next Topic  First Page of Current Topic Next Page Previous Page

Lua_04 - Tag Methods for Numerical Operators

Whenever 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 Code

The 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

[1] Roberto Ierusalimschy, Luiz Henrique de Figueiredo, Waldemar Celes
Reference Manual of the Programming Language Lua 4.0
(see http://www.lua.org/manual)
the official reference manual contains any relevatn information about the language itself, the set of standard libraries and its interface to the run-time environment;
[2] Python Language Website
(see http://www.python.org)
the given web site is a good starting point for further investigations on "Python"
[3] Python 2.2.1 Documentation
(see http://www.python.org/doc/current)
you may either download the actual Python documentation or browse it online at the given address

Disclaimer

Please, consider also the author's Disclaimer!

http://www.Andreas-Rozek.de/Lua/Acquainting/Lua_04_en.html    (last Modification: 15.04.2002)