lua-users home
lua-l archive

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


> nice :-)
>
> It's a shame so many places seem to explicitly check the type of
> things...
>
>    table.foreach ({1,2 , 5, 9}, "|x|x+1")
>    stdin:1: bad argument #2 to 'foreach' (function expected, got string)
>
> blargh...

You've just made every string callable -- both lambda strings and
ordinary strings. How would you ensure type-safety now?
For example:

  function call_callback(fn)
    assert(type(fn) == "function" or type(getmetatable(fn).__call) ==
"function")
    fn(42)
  end

  call_callback(print) -- OK
  call_callback("|x| print(x)") -- OK
  call_callback("|x| My checkbox") -- Not OK

  local my_variable = print
  local my_variable = "Hello?!"
  call_callback(my_variable) -- Well, you get the point.

On the other hand, it is not absolutely necessary to use __call()
metamethod -- implicit conversion is almost as good.

  print( fun("|x,y| x+y")(2,3) )

You may want to omit braces:

  print( fun"|x,y| x+y" (20, 30))

Where fun may be basically the same as the __call() metamethod above.

Alexander.