lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Dirk Feytons wrote:
On Mon, Apr 14, 2008 at 9:53 PM, Ralph Hempel
<rhempel@hempeldesigngroup.com> wrote:

 I would suggest having a look at creating your own userata for
 high precision monetary values, and implementing a metatable
 with overrides for the basic Lua operations.

 You may also end up having to add functions to create instances
 of the type etc. See the C API and userdata secions in the Blue PiL
 for details.

I recently discovered one disadvantage of such an approach: relational
operators are only possible on operands of the same type. In other
words, you can't compare such a userdata object with a regular number
since it is by definition false. This might or might not be a problem,
depending on your specific needs but it's certainly something to keep
in mind.

These can be implemented in the metatable as well. The Lua VM
determines that one side or the other of the comparison is a
userdata and then calls the operator in the metatable for that
userdata.

It is up to the C implementation of the userdata to either
issue an error message or make an attempt to cast the other
side of the operator if necessary.

It's probably best in this application to have a completely
separate userdata that is incompatible with "regular" Lua numbers.

At least you'll get decent error messages if you do mix up
the operands :-)

Ralph