|
On 2 December 2013 05:21, Marc Lepage <mlepage@antimeta.com> wrote: > Hi, > > I would like to have a factory function node(t) which returns an object (a > table is fine). I would like these to be able to nest. If node just returns > t, this works: > > A = node { } > B = node { node {} } > > In this case, A is a node with no children, and B is a node with one child. > > Now, I want to be able to make these in modules. Supposing I expect to find > a tree root in mod.tree, then this is fine: > > ----- BEGIN MODULE ----- > return { > tree = node { node {}, node { node {} } } > } > ----- END MODULE ----- > > And if I configure a table and environment (like the module function), I can > omit the table creation: > > ----- BEGIN MODULE ----- > tree = node { node {}, node { node {} } } > ----- END MODULE ----- > > So far so good, that is semantically what I want. But I'd like to make the > syntax simpler, something like: > > ----- BEGIN MODULE ----- > node {} > node { node {} } > ----- END MODULE ----- > > where the root level mod.tree node is implicitly made, and the top level > nodes in the module implicitly add themselves as children to the root level > node. > > In other words, previous two modules produce the same result, just differ in > syntax. > > This means, in the above syntax, that the two top level nodes have to add > themselves to the implicit tree root node, but the child node must not do > that. > > So, any suggestion as to techniques to accomplish something like this? > > Thanks, > Marc > I've written a `node` function that can create a tree implicitly with the first call and add non-child nodes to it, but I don't think there's any way to add that tree to the module's environment unless you explicitly assign it like in your second example or you call an initialisation function in each module and pass it the environment table as an argument. There may or may not be a way around this using the debug library. I've attached my implementation of the `node` function and a small script to test its functionality. Regards, Choonster
Attachment:
nodes.lua
Description: Binary data
Attachment:
nodes_test.lua
Description: Binary data