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
3
u/catwell Aug 16 '16
You don't even need the multiple arguments:
function asd(x)
print(x)
return asd
endIt 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):
Lua 5.3.3 Copyright (C) 1994-2016 Lua.org, PUC-Rio
> function summer(x)
>> return function(y)
>> return summer(x+y), x+y
>> end
>> end
> sum = summer(0)
> select(2, sum "1" "2" "3" "4")
10.02
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.
2
u/whoopdedo Aug 16 '16
No, you should not do it.
I'd never tell anyone that. At least not for a language feature that is clearly documented and isn't likely to be changed anytime soon.
The no-parenthesis shortcut is somewhat divisive but looks good when using Lua as a DSL. Particularly with tables to call functions with named parameters.
Function chaining is extremely useful and I wish more libraries took advantage of it.
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.
5
u/Erendir Aug 16 '16
according to this https://www.lua.org/manual/5.3/manual.html#3.4.10 You are wrong. "A call of the form f'string' (or f"string" or f[[string]]) is syntactic sugar for f('string'); that is, the argument list is a single literal string."
5
u/dan200 Aug 16 '16
Ooooh. My bad, I understand now. So the posted code is equivalent to:
(asd("Hello"))("World")Extra brackets added for clarity. Another reason to avoid this syntax!
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.