I've searched for an answer here and elsewhere online, but all topics deal with either iterating a table, metatables, or times when _,var1 = do_some_stuff() which are not the case here.
This is just a non-realistic function, but containing examples of what I mean:
function do_some_stuff(data)
_ = some_function(data)
some_other_code
_ = some_other_function(data)
end
Wouldn't this be considered the same as simply entering:
function do_some_stuff(data)
some_function(data)
some_other_code
some_other_function(data)
end
I know that if I create a basic Lua program like this both versions run the same:
function hello(state)
print("World")
end
function ugh(state)
_ = hello(state) -- and w/ hello(state) only
end
ugh(state)
I just would like to know if there can be a time where this _ = some_function() is necessary?
In the example you wrote, _ is meaningless. In general, _ is used if a function is returning multiple values, and you don't need all of the returned stuff. A throw-away variable _ is, so to speak.
For example:
local lyr, needThis = {}
lyr.test = function()
local a, b, c;
--do stuff
return a, b, c
end
Lets say, for such a function that returns multiple values, I only need the 3rd value to do something else. The relevant part would be:
_, _, needThis = lyr.test()
The value of needThis will be the value of c returned in the function lyr.test().
There is no benefit to _ = do_some_stuff(), rather using do_some_stuff() is fine and more accepted. The underscore provides no benefit when used in this way.
Thanks Etan Reisner and Mud for the help and clarification.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With