Implementing an integral type

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

Implementing an integral type

Reuben Thomas-3
I am thinking about adding integer support to Lua, without giving up
floating point numbers as the basic number type. The obvious way to do this
seems to be to add a new userdata type, and provide suitable tag methods for
all the operations that can act on numbers.

However, I'm a bit worried by the description of lua_pushusertag. This says
that it first searches for a userdata with the same value and tag. The
natural way to store ints is "unboxed", i.e. to cast them to void *, but
this means that each time a C program wants to push an integer, the Lua
runtime will search to see if that integer is already in use.

So everything will work fine, but rather slowly.

I can imagine that implementing other types that take up little storage,
such as complex numbers, could give similar efficiency losses, even if the
value used as a userdata really is a pointer: it might be nice to be able to
tell Lua whether a given tag type should be shared where possible (as at
present) or copied every time (as I imagine would be better for integers).

So in the end I seem to be raising two issues:

1. How best to implement separate integer support? (Or is it just not worth
it?)

2. Is it worth allowing tag types *not* to be shared, but copied each time a
new value is created?

-- 
http://sc3d.org/rrt/
L'art des vers est de transformer en beautés les faiblesses (Aragon)


Reply | Threaded
Open this post in threaded view
|

Re: Implementing an integral type

Roberto Ierusalimschy
> However, I'm a bit worried by the description of lua_pushusertag. This says
> that it first searches for a userdata with the same value and tag. The
> natural way to store ints is "unboxed", i.e. to cast them to void *, but
> this means that each time a C program wants to push an integer, the Lua
> runtime will search to see if that integer is already in use.

This search uses a hash table, and so it is not so slow. I guess the 
overhead of this search is comparable with the basic overhead of function
calls through the API (which you cannot avoid). 


> 1. How best to implement separate integer support? (Or is it just not worth
> it?)

Integers implemented through the official API will for sure be much slower 
than the native number type. Only the time for a function call (to run the 
tag method) is much larger than the time for an arithmetic opcode. What I 
think it is worth is to implement a library for "big integers". Those are
naturally unboxed, do not fit into a double, and pay for the performance.

-- Roberto