且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

变量名和逗号后面的下划线有什么作用?

更新时间:2023-02-14 22:53:08

在许多编程语言中,_ 用于表示未使用的变量.

In many programming languages _ is used to denote unused variables.

这也适用于 Lua.这是纯粹的风格约定.您在 Lua 手册中找不到任何相关内容.

This is also applicable to Lua. It is pure style convention. You won't find anything about it in the Lua manual.

luackeck 是 Lua 最常用的静态代码分析器,当你的代码中有未使用的变量时,它会给你警告.在这方面,它将忽略名为 _ 的变量.

luackeck, the most common static code analyzer for Lua will give you warnings for having unused variables in your code. It will ignore variables named _ in that regard.

不会是 name = name:gsub(....) 或 ..then path = path:gsub(...)一样吗?

Wouldn't be name = name:gsub(....) or ..then path = path:gsub(...) the same ?

在您的示例中,这实际上不是必需的.

In your examples this is actually not necessary.

name, _ = name:gsub("{", "\\{") 中包含 _ 的唯一原因是提示此函数实际上返回两个值.通常你会把 _ 放在一边.

The only reason to have _ in name, _ = name:gsub("{", "\\{") would be to give a hint that this function actually returns two values. Usually you would leave the _ away.

_, numReplaced = name:gsub("{", "\\{") 如果您只对第二个返回值感兴趣,那么它是有意义的.如果不添加第一个未使用的变量,您将无法获得它.

Whereas _, numReplaced = name:gsub("{", "\\{") would make sense if you're only interested in the second return value. You cannot get that without adding the first unused variable.