Skip to content

Why does this fail and then succeed if i simply pull the expression out into a variable? #3674

Answered by asmagill
unphased asked this question in Q&A
Discussion options

You must be logged in to vote

This is one of those subtle lua quirks that crops up and bites everyone at least once... it has to do with functions that return multiple values and their position in an argument list.

gsub returns two values -- the changed string and the number of changes made. If a function returns multiple values and is at the end of an argument list, all of the return values are appended to the list:

a = "1, 2, 3, 4"
print(a:gsub(", ", "-"))

1-2-3-4	3

But, if the same function is not the final argument in the argument list, then only the first return value is used:

print(a:gsub(", ", "-"), "is new")

1-2-3-4	is new

The fix is to either capture the result you want into a local variable and use that, o…

Replies: 2 comments 1 reply

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
1 reply
@unphased
Comment options

Answer selected by unphased
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants