Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua: string.rep nested inside string.gsub?

I would like to be able to take a string and repeat every substring following a number that amount of times while removing the number. For example "5 north, 3 west" --> "north north north north north, west west west". This is what I tried:

test = "5 north, 3 west"
test = test:gsub("(%d) (%w+)", string.rep("%2 ", tonumber("%1")) )
Note(test)

But I just get an error like "number expected got Nil."

like image 817
Eli Bell Avatar asked Jul 27 '26 13:07

Eli Bell


1 Answers

You need to use a function as the second parameter to gsub:

test = "5 north, 3 west"
test = test:gsub("(%d) (%w+)",
  function(s1, s2) return string.rep(s2.." ", tonumber(s1)) end)
print(test)

This prints north north north north north , west west west.

like image 130
Paul Kulchenko Avatar answered Jul 30 '26 09:07

Paul Kulchenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!