Godot: [Suggestion] Add a limit parameter for .replace

Created on 14 Jun 2017  路  9Comments  路  Source: godotengine/godot

Operating system or device - Godot version:
2.1.3

I'm creating a chatbox where I am converting text like :joy: -> to [img]res://joy.png[/img]

However, looking over the docs I was trying to limit the amount of smileys a player can use. While looking at the GDScript's String class, the .replace method has no limit parameter

Example:

String replace( String what, String forwhat )
Replace occurrences of a substring for different ones inside the string.

Proposed feature:

String replace( String what, String forwhat, int limit=-1)
Replace occurrences of a substring for different ones inside the string.

This might have been suggested before but couldn't find anything. thanks for reading!

e: -1 would be default, to replace all ofc or whatever. i think you guys get my idea :P

archived discussion core

Most helpful comment

I would say, go with the API Python 3 uses, to respect the principle of least surprise.

All 9 comments

This sounds quite specific for such a general purpose method. How about counting them before (using find) and process the string accordingly by doing a substring?

Well, the parameter is present with the python replace聽function (here) or the php preg_replace function (here). I do not see for what reason it should not be added.

A complex treatment as @Zylann suggest is also very inefficient, while implementing a counter on the replace function should really have a low impact on the replace function performances.

I agree with OP, in my humble opinion it should be implemented. :)

Note also that the replace_first function should allow you to do what you want, but it seems available on master version (not 2.*). However that is still less efficient that having a limit parameter.

Depends how much text you want to process, in case of a chat it's not significant and then manual method would work already (not saying to check every char, composing existing methods would work). But if you want to do this on a huge text then yes.

Sure, but I guess a core functionality should adapt to any case (including huge texts) :)

Well, given the ease of just doing this, and the fact that it would not break compatibility in any way, I think we shouldn't make it much of a problem.

Also, mind that we might like a rreplace function, for replacing the last N matches.

and consequently a rreplacen function, for the case insensitive :)

I would say, go with the API Python 3 uses, to respect the principle of least surprise.

Bug triage note: The original issue reporter closed all their issues before deleting their account. If you are affected by a similar issue/want a similar feature, please file a new ticket (referencing this one if it contains useful information) so that it can be further looked at and eventually resolved.

Was this page helpful?
0 / 5 - 0 ratings