lua-users home
lua-l archive

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



On Sat, Jan 18, 2014 at 10:38 AM, Philipp Janda <siffiejoe@gmx.net> wrote:
Am 18.01.2014 15:04 schröbte Antonio Vieiro:

I would like to build a small s-_expression_ ([1]) library in Lua (5.1),
so I need to design cons-cells ([2]) first.

I would appreciate some advice in the design of the cons-cells. I am
thinking of two approaches:

A) Design cons-cells as Lua tables, in plain Lua, with a "car" and a
"cdr" being other Lua objects (possibly other cons-cells).
B) Design cons-cells as a C structure (Lua allocated and garbage
collected with a __gc metamethod), that keeps references to other Lua
objects using luaL_ref and luaL_unref (possibly with references to other
cons-cells).

C) Use closures for cons-cells. See [3].
D) Similar to A, but use the keys `1` and `2` (i.e. the array part of the table) for head and tail.

`cons`, `car`, `cdr`, `setcar`, and `setcdr` are the only functions that need to know the difference, so you can even change the implementation later ...

I have a set of example modules I created for the course I taught in my university's Fall semester (late August to mid-December) on my website at 
http://www.cs.olemiss.edu/~hcc/csci658/notes/658lectureNotes.html#cellList

However, I intentionally did not include anything like a setcar or setcdr, instead forcing creation or a new Cons cell. I wanted immutability of the cells.

My item 15(a) is more or less approach A above.  My item 15(e) is more or less approach C (which I implemented after a similar suggestion by Phillipp Janda to a post to this list).  ... My item 15(b) was an attempt to enforce immutability of the cells.

Approach D would be a relatively straightforward mod to my 15(a).

The core of the module are six primitives: constructors Nil and Cons, field accessors head and tail, and query functions isNil and isList.  These functions "hide" the implementation of the Cons cell from the rest of the module's functions and from outside.

My item 15(c) and 15(d) are attempts to provide "lazy" lists -- requiring a bit of macro processing in the code that uses the module.

- Conrad Cunningham