lua-users home
lua-l archive

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


on 3/25/04 8:45 AM, Jay Carlson at nop@nop.com wrote:

> The reason to use [0] and [1] is they take advantage of the "small integer
> keys are stored in an array" optimization in Lua 5.0.  For clarity you could
> use .car and .cdr instead.  Note that all strings in Lua are interned, so
> the performance penalty is not that great.

Do you want to use 0 and 1 or 1 and 2?

One other thing to try is doing these as function closures.

    function cons( a, b )
        return function( key )
            if key == "car" then
                return a
            elseif key == "cdr" then
                return b
            end
        end
    end

    function car( a )
        return a( "car" )
    end

    function cdr( a )
        return a( "cdr" )
    end

    etc.

> On the other hand, it might be a fun exercise to implement this as a C
> extension.  The car would be stored as a ref, which is something the
> reference manual doesn't emphasize enough.  (Somebody might wanna write a
> tutorial for the wiki on references).  If you allow improper lists, you'll
> have to store the cdr as a ref as well.

Beware of what amount to reference-counting cycles when creating refs. It's
actually a bit of a pain to get userdata to refer safely to other Lua data
objects and seems to require the use of per-object metatables rather than
sharing the metatables across a type.

Mark