Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluate code block in a function parameter in lua

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.

like image 754
Moe Avatar asked Apr 16 '12 13:04

Moe


2 Answers

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
like image 188
ddk Avatar answered Oct 23 '22 16:10

ddk


If this is a global behaviour you want, the simplest solution would be to hook print so that it evaluates any functions passed to it. That way you can simply leave the call sites as lambdas.

like image 4
Puppy Avatar answered Oct 23 '22 17:10

Puppy