gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 00:26:01 27 4
gpt4 key购买 nike

我在这里和其他地方在线搜索了答案,但所有主题都涉及迭代表、元表或 _,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() 的时间?

最佳答案

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

例如:

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

比方说,对于这样一个返回多个值的函数,我只需要第三个值来做其他事情。相关部分是:

_, _, needThis = lyr.test()

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

关于variables - 为什么设置下划线等于一个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30604868/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com