Page 1 of 1

"local _ _, x, y = ..."

Posted: Tue Oct 22, 2013 1:49 pm
by Doctornull
What does this syntax mean?

Note the lack of a comma between the first _ and the 2nd _, that's what I'm talking about.

Re: "local _ _, x, y = ..."

Posted: Tue Oct 22, 2013 4:41 pm
by Castler
From playing around on repl.it, it looks like it's another way of saying

Code: Select all

local _
_, x, y = ...
In other words, it's probably a bug, and it likely makes x and y global.

Some sample code demonstrating this:

Code: Select all

function ret4() return 1, 2, 3, 4 end
function test() 
  local _ _, x, y = ret4() 
  print(_) 
  print(x) 
  print(y) 
end

test()   -- prints 1, 2, 3; 4th return value is discarded

print(_) -- prints "nil"
print(x) -- prints "2"; i.e., x is global
print(y) -- prints "3"; i.e., y is global

Re: "local _ _, x, y = ..."

Posted: Tue Oct 22, 2013 5:48 pm
by darkgod
Yup, and it's not a bug :)
I use it this way because x and y already exist

Re: "local _ _, x, y = ..."

Posted: Tue Oct 22, 2013 5:59 pm
by Castler
darkgod wrote:Yup, and it's not a bug :)
I use it this way because x and y already exist
Ah, I see. So, Doctornull, to answer your question, the intent is something like "declare _ as a local variable, then assign to _ and the preexisting local variables x and y" (or, really, "throw away the first return value by storing it to new local variable _, then store the second and third return values to preexisting local variables x and y").

Thanks for the explanation and correction.

Re: "local _ _, x, y = ..."

Posted: Tue Oct 22, 2013 7:42 pm
by Doctornull
Interesting, thanks for the explanation.

I'm a bit curious why it's desirable to have global x and y but not a global "garbage" variable _.

Re: "local _ _, x, y = ..."

Posted: Wed Oct 23, 2013 2:14 am
by Castler
Doctornull wrote:I'm a bit curious why it's desirable to have global x and y but not a global "garbage" variable _.
x and y aren't globals; they're locals that are declared earlier in the function (so there's no need to declare them again).

Global variables are almost never desirable; using globals means that functions' behavior can affect and be affected by arbitrary global variables in addition to the functions' own inputs and outputs, and that simply makes code too hard to understand and maintain.

Re: "local _ _, x, y = ..."

Posted: Wed Oct 23, 2013 2:59 am
by Doctornull
Castler wrote:x and y aren't globals; they're locals that are declared earlier
Ah, yes, I'd missed that. Thanks!
Castler wrote:Global variables are almost never desirable
Indeed, thus my question.

Cheers!