lua-users home
lua-l archive

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


Wouldn't it be easier to just make a helper function to create sets,
as it seems like the only time you want special syntax is in the
construction phase. Here's

do
  local function addset(t, k, ...)
    if k then t[k] = true; return addset(t, ...); end
    return t
  end
  function set(...) return addset({}, ...) end
end

-- test
myset = set("mercury", "venus", "earth")

using the planet = {[mercury], [venus], [earth]} syntax would be
confusing, since [x] generally means "the variable x as a key" but in
this case it would mean "the string x as a key".


On Sun, Feb 24, 2008 at 1:24 PM, John Hind <john.hind@zen.co.uk> wrote:
> About a year ago, Peter Jacobi suggested a syntactic sugar for sets:
>
>  planet = {["mercury"], ["venus"], ["earth"]} -- In Lua 5.1, Gives Error '='
>  expected
>
>  Would be compiled as:
>
>  planet = {["mercury"]=true, ["venus"]=true, ["earth"]=true}
>
>  http://lua-users.org/lists/lua-l/2007-03/msg00767.html
>
>  Of course, Peter's syntax could be further simplified to:
>
>  planet = {[mercury], [venus], [earth]} -- In Lua 5.1, Gives Error '='
>  expected
>
>  Then you could write:
>
>  local input = "pluto"
>
>  if planet[input] then
>         print(input, " is a planet")
>  else
>         print(input, " is not a planet")
>  end
>
>  I think this is a really nice idiom and entirely within the spirit of Lua.
>  It expresses sets using the standard table mechanism + syntax sugar in
>  exactly the same spirit that arrays and objects are implemented in Lua.
>
>  Of course, responses focussed on pointing out that you can already do this
>  and various ways of expressing it within the existing language. But that's
>  not the point. Having it in the basic language definition makes Lua better
>  and more expressive at negligible cost. It also allows mixed idioms in data
>  description that are difficult to implement generically using factory
>  functions:
>
>  local mark = {name="Mark Jones", age=34, [male]}
>
>  I definitely vote this excellent suggestion be seriously considered for a
>  future version of Lua!
>
>  - John Hind
>
>