为什么设置下划线等于一个函数?

Why set underscores equal to a function?

我在这里和其他地方在线搜索了答案,但所有主题都涉及迭代 table、元 table 或 _,var1 = do_some_stuff() 的迭代次数这里的情况。

这只是一个非现实的功能,但包含我的意思的示例:

function do_some_stuff(data)
    _ = some_function(data)
    some_other_code
    _ = some_other_function(data)
end

这不会被认为与简单输入相同:

function do_some_stuff(data)
    some_function(data)
    some_other_code
    some_other_function(data)
end

我知道如果我像这样创建一个基本的 Lua 程序,两个版本 运行 相同:

function hello(state)
    print("World")
end

function ugh(state)
    _ = hello(state) -- and w/ hello(state) only
end

ugh(state)

我只是想知道是否有必要 _ = some_function() 的时候?

_ = do_some_stuff() 没有任何好处,而使用 do_some_stuff() 更好,更容易被接受。以这种方式使用下划线没有任何好处。

感谢 Etan Reisner 和 Mud 的帮助和澄清。

在你写的例子中,_是没有意义的。通常,如果函数返回多个值,则使用 _,并且您不需要所有返回的内容。一次性变量 _ 可以这么说。

例如:

local lyr, needThis = {}
lyr.test = function()
    local a, b, c;
    --do stuff
    return a, b, c
end

比方说,对于 returns 多个值的函数,我只需要第 3 个值来执行其他操作。相关部分将是:

_, _, needThis = lyr.test()

needThis 的值将是函数 lyr.test() 中返回的 c 的值。