lua-users home
lua-l archive

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


If you really want cons cells for lua, this wouldn't be too bad (although
totally untested):

consmt = {}
function cons(a, b) return setmetatable({[0]=a, [1]=b}, consmt) end
function car(a) return a[0] end
function cdr(a) return a[1] end
function setcar(a, v) a[0]=v end
function setcdr(a, v) a[1]=v end
function isnull(a) return a == nil end
function iscons(a)
    if type(a) ~= "table" then return false end
    return getmetatable(a) == consmt
end
function islist(a)
  return isnull(a) or iscons(a)
end

Feel free to add fascist __newindex and __index methods to consmt to keep
people from messing with the internals of your cons cells.

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.

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.

Jay