Search code examples
variableslua

What is the purpose of the underscore after variable name and comma?


I found this Lua code:

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

and again:

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

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 ?

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

So why the script is written this way ?


Solution

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

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

    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.

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

    In your examples this is actually not necessary.

    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.

    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.