[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: RFE: table ctor syntax enhancement for many-to-one mappings
- From: HyperHacker <hyperhacker@...>
- Date: Thu, 18 Aug 2011 16:39:25 -0600
On Thu, Aug 18, 2011 at 16:37, Lorenzo Donati
<lorenzodonatibz@interfree.it> wrote:
> Thanks for the reply
>
> On 18/08/2011 23.40, HyperHacker wrote:
>>
>> On Thu, Aug 18, 2011 at 14:46, Lorenzo Donati
>> <lorenzodonatibz@interfree.it> wrote:
>>>
>>> Hi all!
>
> [...]
>
>>> In other words I propose to enhance the table constructor syntax to allow
>>> not just one expression inside "[]", but an expression list, so that:
>>>
>>> [exp1,exp2,exp3,...] = val
>>>
>>> would be expanded as
>>>
>>> [exp1] = val, [exp2] = val, [exp3] = val, ...
>>>
> [...]
>
>>>
>>>
>>
>> This seems not too far from the typical multiple assignments:
>> a, b, c = 1, 2, 3
>> I often wondered why that can't be done in tables. I'm guessing the
>> answer is ambiguity: does a, b, c = 1, 2 mean [1]=a, ['b']=1, ['c']=2
>> or ['a']=1, ['b']=2, [1]=c or ['a']=1, ['b']=2, ['c']=nil? This might
>> be resolvable with some kind of syntax extension such as (a,b,c) =
>> (1,2,3) and just requiring equal number of values on left/right sides,
>> since you can't store nil in a table anyway (so a,b,c = 1,2 doesn't
>> really make sense).
>
> My proposal is far less ambitious. It would only add new semantics, not
> modify the existing one: it will only affect the ctor in the cases where the
> square brackets are used, and would allow only one value on the RHS:
>
> so
>
> { a, b, c = 1, 2 }
>
> will have the usual meaning, whereas:
> (<=> means "equivalent" for short)
>
>
> { ["a", "b", "c"] = 1, 2 } <=>
> { ["a"] = 1, ["b"] = 1, ["c"] = 1, 2 } <=>
> { a = 1, b = 1, c = 1, 2 }
>
> and
>
> { [a, b, c] = 1, 2 } <=>
> { [a] = 1, [b] = 1, [c] = 1, 2 }
>
>
>
> [...]
>
>>
>> Something similar to your idea could be done with a 'rep' function: a,
>> b, c = rep(3, true) --returns true, true, true. That would let you do
>> similar to my snippet above without needing the local aliases, which
>> might look a little nicer.
>
> nope, it won't work with current implementation:
>
> -- example rep
> function rep( n, what )
> if n == 0 then return end
> return what, rep( n - 1, what )
> end
>
> t = { a, b, c = rep(3, true) } --> { c = true }
> -------------------------------
>
> since:
>
> { a, b, c = rep(3, true) } <=>
> { a = nil, b = nil, c = true } <=> { c = true }
>
> since in this case the return values of rep are adjusted to 1 - the manual
> says [1]:
>
> "If the *last field* in the list has the form *exp* and the expression is a
> function call or a vararg expression, then all values returned by this
> expression enter the list consecutively (see §2.5.8). "
>
>
> [1] http://www.lua.org/manual/5.1/manual.html#2.5.7
>
>
> -- Lorenzo
>
>
>
>
>
>
I meant doing it outside the table constructor, e.g.:
t = {}
t.a, t.b, t.c = rep(3, true)
--
Sent from my toaster.