Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Yet more bikeshedding, this time in Lua!

This first approach doesn't use an internal lambda but is idiomatic - (do/end does not create a block in Lua - it creates a scope):

At the Lua repl:

  > function which_answer_is_correct (...)
  >> for index, answer in ipairs {...} do
  >>   if tostring(answer) == '42' then return index end
  >> end
  >> return 'none of the above'
  >> end
  > =which_answer_is_correct('black', 'white', 42, 'symbolic_logic')
  3
The next approach duplicates the semantics of the Ruby code you posted, if Ruby blocks were actually lambdas:

  > -- first a bit of magic to make Tables act more like in Ruby
  > mt = { __index = table }
  > function Table (t)
  >>     return setmetatable(t or {}, mt)
  >> end
  > 
  > function table:each_with_index (block)
  >>     for index, value in ipairs(self) do
  >>         block(value, index)
  >>     end
  >> end

  > -- now actually write our function:
  > function which_answer_is_correct (...)
  >>     local answers = Table {...}
  >>     answers:each_with_index (function (answer, index)
  >>         if tostring(answer) == '42' then return index end
  >>     end)
  >>     return 'none of the above'
  >> end
  >
  > =which_answer_is_correct('black', 'white', 42, 'symbolic_logic')
  none of the above
Now, if you want the nonlocal return properties of Ruby blocks in Lua, you need to be a bit more clever than I feel at the moment. There's probably a trick available via coroutines, because coroutine.yield() yields to the caller of the currently running coroutine, rather than to the caller of the currently running function.

Making anonymous function creation less verbose is a popular topic on the Lua mailing list. "function (args) return args end" is more verbose than "do |args| args end". There are several implementations via community-developed macro extensions. I wouldn't be surprised to see something appear in the Lua 5.2 RC candidate later this year.

In the real world, I'd probably write something like this in Lua:

  function which_answer_is_correct (...)
      return table.find({...}, function (value) return tostring(value) == 42 end)
  end
Implementation of table:find(cond) is left as an exercise for the reader.


Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: