变量名和逗号后面的下划线有什么作用? [英] What is the purpose of the underscore after variable name and comma?

查看:63
本文介绍了变量名和逗号后面的下划线有什么作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找到了这个 Lua 代码:

I found this Lua code:

function displayName(name)
  name, _ = name:gsub("{", "\\{")
  return name
end

又一次:

function parsePath(path)
  if type(path) == "string" then path, _ = path:gsub("\\", "/") end
  return path
end

我明白代码的作用..我不明白的是,变量名和赋值部分(=)之间的 , _(逗号下划线).. 所以这个 name, _ = name:gsub("{", "\\{") 和这个 ..then path, _ = path:gsub("\\", "/")

I understand what the code does.. what I don't understand is that , _ (comma underscore) between the variable name and the assignation part (=).. so this one name, _ = name:gsub("{", "\\{") and this one ..then path, _ = path:gsub("\\", "/")

谁能给我解释一下那东西的意思?

Can someone explain to me the meaning of that thing ?

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

那么为什么脚本是这样写的?

So why the script is written this way ?

推荐答案

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

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.

这篇关于变量名和逗号后面的下划线有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆