If only one value needed from a set of the returned values by a function what is the best approach?
For example, you need the third return value of a function, you can do like this:
a,b,c,d = Manyvalues()
Debugprint(c)
a,b,d = Nil
Not an elegant solution to use three needless variables.
A creative method could be used liked this:
c = Pack ( Manyvalues() )[2]
Debugprint(c)
Don't know which one is more optimal by speed and memory, but the latter looks better for the eye
Is there any other solution? Maybe something from the Lua syntax?
Drop some results
Re: Drop some results
Why do you set a,b,d to NIL if they are not needed?
-
- Posts: 475
- Joined: Fri May 15, 2015 5:15 pm
- Location: Waterville, Minnesota USA
Re: Drop some results
Interesting problem. I actually encounter that same problem every now and then, but so far it havent been speed critical, and I have only had usually 2 max 3 values coming, so I have simply used local a,b to store the values, in which case Hollywood will itself take care of removing the a (and b as well).
But indeed, it might not be a bad idea to have some exact and fast way to access only one of the coming values.
But indeed, it might not be a bad idea to have some exact and fast way to access only one of the coming values.
Re: Drop some results
I wonder why you assign the values at all if you don't need them ?
This will work:
This, too:
This will work:
Code: Select all
myfunc=Function()
Return(1,2,3,4)
EndFunction
a,b,c=myfunc()
DebugPrint(a)
DebugPrint(b)
DebugPrint(c)
DebugPrint(d)
Code: Select all
myfunc=Function()
Return(1,2,3,4)
EndFunction
a,b,c,d,e=myfunc()
DebugPrint(a)
DebugPrint(b)
DebugPrint(c)
DebugPrint(d)
DebugPrint(e)
Re: Drop some results
I usually just create local variables, and this kind of stuff is usually used in some code block/function, so they're deleted automatically then.lazi wrote: ↑Sun Nov 10, 2019 2:23 pm If only one value needed from a set of the returned values by a function what is the best approach?
For example, you need the third return value of a function, you can do like this:
a,b,c,d = Manyvalues()
Debugprint(c)
a,b,d = Nil
Not an elegant solution to use three needless variables.
Code: Select all
local a,b,c,d = Manyvalues()
Debugprint(c)
Re: Drop some results
This seems to be the best way, but it can be optimized a bit further:lazi wrote: ↑Sun Nov 10, 2019 2:23 pmCode: Select all
a,b,c,d = Manyvalues() Debugprint(c) a,b,d = Nil
Code: Select all
a, a, c, a = Manyvalues()
Debugprint(c)
a = Nil
(http://www.lua.org/manual/5.1/manual.html#pdf-select)