5

Suppose I am inserting a string into a table as follows:

table.insert(tbl, mystring)

and that mystring is generated by replacing all occurrences of "a" with "b" in input:

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

The obvious way to combine the two into one statement doesn't work, because gsub returns two results:

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

which, I suppose, is the price paid for supporting multiple return values. The question is, is there a standard, built-in way to select just the first return value? When I found select I thought that was exactly what it did, but alas, it actually selects all results from N onwards, and so doesn't help in this scenario.

Now I know I can define my own select as follows:

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

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

but this doesn't look right, since I'd expect a built-in way of doing this.

So, am I missing some built-in construct? If not, do Lua developers tend to use a separate variable to extract the correct argument or write their own select1 functions?

4

3 回答 3

12

您可以用括号将表达式括起来:

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

这将只选择第一个结果。

要获得第 n 个结果,您可以使用select并用括号括起来:

func1( (select(n, func2())) )
于 2010-04-24T14:30:06.830 回答
5

将表达式放入括号中,如下所示:

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

将强制一个返回值。或者你可以像这样抓住它们:

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

甚至更好的是, dummy 抓住它来保存变量:

str,_ = string.gsub(input, "a", "b")
table.insert(tbl, str)
于 2010-04-24T14:31:16.033 回答
5

在一行中:({ funct(args) })[n]将返回第 n 个结果而不声明任何命名变量。

于 2013-09-15T14:14:10.597 回答