A function with no arguments can be called with them?

Posted by Cadari on Wed 29 Aug 2007 06:03 PM — 6 posts, 25,022 views.

#0
Hello. A very basic question.

function balance_equilibrium_notify()
    ...
end

balance_equilibrium_notify(gained_balance_eq)

A function with no parameters is called with a one? Is that a trick of Lua of some kind? :) gained_balance_eq is boolean if it's of any importance.
USA #1
I'm not quite sure what exactly the question is here... Yes, you can call a function that does not take any parameters with a parameter in it... It just doesn't do particularly much of anything.

Lua 5.1.2  Copyright (C) 1994-2007 Lua.org, PUC-Rio
> function test()
>> print( "whee!" )
>> end
> test( true )
whee!
> test( "foo" )
whee!
>
#2
I don't know a single thing about Lua, so was wandering, if it is some kind of work-around or something alike. Like not calling the mentioned function if the parameter is nil.

Thank you!
USA #3

Lua 5.1.2  Copyright (C) 1994-2007 Lua.org, PUC-Rio
> function test( foo, bar )
>> print( foo, bar )
>> end
> test( 1, 2 )
1       2
> test( 1 )
1       nil
> test()
nil     nil
>

Is this what you mean? You can check to see if a parameter has been passed before running the function.

Personally, with the example you gave, I would just test before calling the function.

if gained_balance_eq ~= nil then
  balance_equilibrium_notify(gained_balance_eq)
end
#4
No, sorry, I'm not that good with explaining my thoughts in English.

The code I posted is not mine. I just stumbled upon it and thought there are two possibilities:

1. It's just a minor mistake, nothing to worry about if Lua allows it.

2. It's an extremely complex Lua-only trick and this code works in some completely unexpected way :)

Now, as you told me it's just #1, I have no questions. Thanks, again.
Amended on Wed 29 Aug 2007 09:17 PM by Cadari
Australia Forum Administrator #5
Quote:

A function with no parameters is called with a one? Is that a trick of Lua of some kind?


The Lua manual clearly illustrates that functions can be called with more or less arguments than they "expect". If you supply too many arguments, they are ignored. If you supply "too few" then the extra ones are set to nil.

I cannot see a huge amount of point in writing code like your example, as calling that function with an argument, which it will not handle, seems redundant and is probably a simple coding error. However it is not a Lua syntax error.

Functions can also return multiple results, a "trick" which is used quite often.