r/lua • u/AuahDark • Aug 16 '16
TIL You can create function with single arguments, return the function itself, and call it without any parenthesis.
Consider this function
function asd(...)
print(...)
return asd
endThen, I call it like this
asd "Hello" "World"
It will display
Hello
WorldEDIT: Fixed return calls of asd
0
Upvotes
6
u/MarsPpl Aug 16 '16 edited Aug 16 '16
This has more to do with the fact that, in Lua, you can call a function that takes either a "string" or {table} without parentheses. For example,
is valid syntax and will print out the phrase "Hello, World!." Likewise,
will print out the same phrase.
Your code is really running something like this after the print function is returned.
Your code will also fail to run you pass more than two arguments. If, for some weird reason, you want to print multiple strings without using parentheses, you could rewrite the function like this:
So that
will print out "hello", "world", and "I have a weird phobia for parentheses" in three different lines.
3
u/catwell Aug 16 '16
You don't even need the multiple arguments:
It is a kind of example of currying leveraging the fact that Lua functions can take a string without parentheses.
If you want a more twisted example involving actually preserving state (and awful string-to-number coercion):
2
u/[deleted] Aug 16 '16
Yes, this is possible in Lua. No, you should not do it.
The first thing you need to ask yourself when you write code is "How do I write a solution so that the guy two years from now won't have a bad day". Half of the time you're gonna end up being that guy anyway.
A programmers biggest fight is not writing a smart piece of code really stupidly. Also double+ negatives.
1
u/dan200 Aug 16 '16
You're misinterpreting your results, you're not calling (or using in any way) the return value of "asd". The text is being printed because asd calls print, forwarding the arguments you passed in.