lua-users home
lua-l archive

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



On Feb 12, 2004, at 12:45, andrew cooke wrote:


Hi,

As far as I can tell, Lua evaluates arguments to functions eagerly.  Is
there any way of treating blocks of code lazily?

For example, if I want to add a "case" statement to Lua that looks
something like:

case x
of   1 do ... end
of   2 do ... end
else   do ... end

would I be able to?  My initial idea was to define case as a vararg
function, but if arguments are evaluated eagerly then this won't work (I
believe).

The syntax in the example above isn't important - what I'm looking for is
a way of handling sections of code as first class objects, and for them
not to be evaluated when passed as arguments, I think.

Well, functions are sections of code and they are first class objects.

This function calls one of its arguments according to the value of the first argument:

function select(x, ...) return arg[x]() end

And here it is being used. Notice that arguments 2 and 3 are anonymous functions.

> select(2, function () print "apple" end, function () print "banana" end)
banana

It's almost not worth writing the select function. You can use a table of functions instead:

a = {
  function () print "apple" end,
  function () print "banana" end,
}

> a[1]()
apple

Hope that helps.

Tuomo Valkonen's suggestion, which I picked up whilst I was writing this reply, is similar.

David Jones