Lua: Skip variable declaration

lua

Solution

First of all, variables are not garbage collected, objects are. In this case, there's nothing to garbage collect.

However, let's say that `TestFunc` was creating objects (say, tables):

function TestFunc()
   return {1}, {2}
end

function SecondFunction()
   local nodeclare, var = TestFunc()
end

Now `nodeclare` is referencing a table returned by `TestFunc`. That's an object, allocated on the heap, that we don't want hanging around forever.

That object will eventually be collected if there is nothing left referring to it. In your case, as soon as `SecondFunction` returns, the local `nodeclare` goes out of scope and goes away. As long as there's nothing else referencing that table, the table will be collected (during next collection cycle).

You can avoid declaring `nodeclare` entirely by skipping the first return value of `TestFunc` like this:

local var = select(2, TestFunc())

However, when you're talking about a temporary local variable, as in your example, you normally just create the temporary variable then ignore it. This avoids the overhead of the call to `select`. Sometimes you use a variable name that indicates it's trash:

local _, var = TestFunc()

If say I was doing a pairs loop over 100 values, would that even have a signifigant impact?

None whatsoever. You're just continually overwriting the value of a local variable.

Problem

I am trying to "Skip" a variable, by either never declaring it or just having it garbage collected immediately, but I don't know if it's possible. Example: ``` function TestFunc() return 1, 2 end function SecondFunction() local nodeclare, var = TestFunc() end ``` Basically what I wanted was for "nodeclare" to not even exist. So if I did print(nodeclare, var) it would do nil, 2. The same thing would be if I was doing a pairs loop and I didn't need to use the keyvalue. Is there some special thing I can put as the variable name for this to happen? If say I was doing a pairs loop over 100 values, would that even have a signifigant impact?

Original source