lua-users home
lua-l archive

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



Could the comma be used even outside of tables as a "just one, please" operator?

One thing I never learn to like about Lua syntax is the use of () to cut out a tail. In my opinion, it looks way too innocent, and use of paranthesis should not change data contents at all.

Personally, I wouldn't mind forcing people to use, say "first()" instead of just "()".


Lua 5.1.1  Copyright (C) 1994-2006 Lua.org, PUC-Rio
a= {1,2}
print(unpack(a))
1       2
print((unpack(a)))
1
print(unpack(a),)
stdin:1: unexpected symbol near ')'
first= function(a) return a end
print(first(unpack(a)))
1





On Tue, 14 Nov 2006 13:35:53 -0000 (GMT)
 "Rici Lake" <lua@ricilake.net> wrote:
Mark Hamburg wrote:
When using Lua for more or less data description tasks, I'm frequently finding myself wishing for a splice operator that would allow one to use
all
of the results of a function when building a table.

<snip>

Where the $ means that we take all of the results from the function rather than just the first. (And if it has no results, we also reflect that.) I
would also be quite open to other syntaxes.

Mark

Daniel Silverstone and I implemented this as part of the table comprehensions patch (now part of Aranha, so I might be able to backport it to Lua sometime). The syntax we chose, in order to avoid any new lexemes, was to allow multiple returns (including no returns) if the function call was followed by a ';' or at the end of the table constructor -- in other words, a following ',' causes normalization to one value:

 { f(); g(), h() }

==>

f() and h() are fully expanded, g() is normalized to a single value

The implementation is quite straight-forward. The new table vm opcode is modified to use two temporaries: the first is the table itself, and the second is the current insertion index (so newtable itself always initializes that slot to 1). The setlist opcode then updates this slot to
the next index.

This slightly simplifies the implementation of the setlist opcode; the opcode itself does not need to store the starting index, only the number of things to be added to the table, and there is no longer a need to coerce an integer to an Instruction for large starting indices. The benchmarking I did showed that the change was usually slightly faster on Intel x86, with an additional speedup on a G4 Mac; apparently, the simpler opcode decoding compensates for the cost of using an extra stack slot.

I can attempt to isolate this patch if anyone would like to see it.