Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua string.gsub without printing match count

Tags:

lua

Frustratingly, any my previous Lua tries went in extensive Google searching of more/less same Lua resources, and then resulted in some multi-line code to get basic things, which i.e. I get from Python with simple command.

Same again, I want to replace substring from string, and use i.e.:

string.gsub("My string", "str", "th")

which results in:

My thing 1

I imagine replacement count can be useful, but who would expect it by default, and without option to suppress it, but maybe I miss something?

How to print just string result, without counter?

like image 541
theta Avatar asked Mar 12 '12 00:03

theta


2 Answers

Enclose in parentheses: (string.gsub("My string", "str", "th")).

like image 155
lhf Avatar answered Nov 15 '22 10:11

lhf


The results are only a problem because you are using print, which takes multiple parameters. Lua allows multiple assignments, so normally the code would look like

newstr, n = string.gsub("My string", "str", "th")

but the count is only provided if there is a place to put it, so

newstr = string.gsub("My string", "str", "th")

is also fine, and causes the count to be discarded. If you are using print directly (the same applies to return) then you should enclose the call in parentheses to discard all but the first result.

like image 32
Borodin Avatar answered Nov 15 '22 12:11

Borodin