In Lua, can I easily select the Nth result without custom functions?

Suppose I insert a row into a table as follows:

table.insert(tbl, mystring)

and that mystringis created by replacing all occurrences of "a" with "b" in input:

mystring = string.gsub(input, "a", "b")

The obvious way to combine two into one statement does not work, because it gsubreturns two results:

table.insert(tbl, string.gsub(input, "a", "b"))  -- error!
-- (second result of gsub is passed into table.insert)

which, I believe, is the price paid to support multiple return values. The question is, is there a standard built-in way to select only the first return value? When I found select, I thought that this is exactly what he did, but, alas, he actually selects all the results from N and onwards, so this does not help.

, select :

function select1(n, ...)
  return arg[n]
end

table.insert(tbl, select1(1, string.gsub(input, "a", "b")))

, .

, - ? , Lua select1 ?

+5
3

:

table.insert(tbl, (string.gsub(input, "a", "b")))

.

n- , select :

func1( (select(n, func2())) )
+11

, :

table.insert(tbl, (string.gsub(input, "a", "b")))

. :

str,cnt = string.gsub(input, "a", "b")
table.insert(tbl, str)

, , :

str,_ = string.gsub(input, "a", "b")
table.insert(tbl, str)
+5

On one line: ({ funct(args) })[n]will return the nth result without declaring any named variables.

+5
source

All Articles