lua-users home
lua-l archive

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

Jim Pryor <> dixit:

> On Sun, Nov 29, 2009 at 12:26:45PM +0100, spir wrote:
> > Is there a way to let a table item refer to another one:
> >    t = {x=1, y=x+1}
> > or
> >    t = {x=1, y=t.x+1}
> > (at table creation time).
> > Meaning let a table act as a scope/namespace/module.
> If you ignore your parenthetical qualification, yes, you can make a
> table be a namespace.
> function foo()
>     local t = {x=1}
>     setfenv(1, t)   -- now t provides the global namespace inside foo
>     t.y = x         -- now t.y == t.x == 1
>     return t
> end

Thank you. I think this may be a solution, a kind of table factory. Need to dig in this direction.
Probably, for this to work, I would need to use both setfenv(1,t) and getfenv(1), to get & set on the table the proper pairs.

> However, you say you want to do that all at once -- to have later
> entries in the table literal detect the meaning of earlier entries. I
> can't imagine what use case would demand that, but as far as I can tell,
> no that's not possible. Not without hacking the Lua sources.

The use case is to build parsers/grammars as tables of (named) patterns. This seems to me rather an obvious solution in Lua. However, higher-level patterns need to reference lower-level ones, eg integer = OneOrMore(digit).

[In python, I use classes as pseudo namespaces, which works because python class defs actually are executable snippets. They work like modules, in fact.]

> I may be wrong, but I don't think I am.


la vita e estrany