Evaluate code block in a function parameter in lua

anonymous-function, lambda, lua

Solution

You need to wrap the function definition in parentheses and then call it by adding `()` after. Putting this in the Lua interpreter:

> print((function ()
    s=""
    for i=1,10 do
       s=s..tostring(i)
    end
    return s
  end)())

gives the following output

> 12345678910

Problem

I wasn't really sure how to title the question, but consider the following lua code: ``` print(function () s = "" for i = 1, 10 do s = s..tostring(i) end return s end) ``` But this prints only the function address, since function() returns a closure. Is there a way to evaluate the anonymous function? Like in scheme where I can embrace the lambda in additional brackets? ``` ((lambda ()(display "Hello World"))) ``` Of course I know, I could define the function beforehand and call it later, but I was just curious if this is possible in lua. Thanks in advance for all replys.

Original source