Godot: String.insert() not working correctly

Created on 8 Jul 2019  路  4Comments  路  Source: godotengine/godot

Godot version:

3.1.1-stable

OS/device including version:

Windows 10, latest

Issue description:

Inserting in a string only seems to be working with a string directly instead of declaring a var first and then inserting in this var.

For example this is working:

var a = "12345".insert(2,"x")
print(a)

However, the piece of code below does not work.

Steps to reproduce:
This should be enough to reproduce the issue:

var a = "12345"
a.insert(2,"x")
print(a)

Minimal reproduction project:

archived bug documentation

Most helpful comment

I'd say that documentation could be improved here. Now that I look at String docs, some methods say that they return a value and some just say about modifying string. It should be more consistent. But that's another issue probably.

All 4 comments

This is probably intended, but documentation doesn't clarify it properly. The method returns the resulting String, so the original one doesn't get modified.

More than just a documentation question, I think this issue raises a more global programming design question.

The design choice for String is: all methods that modify the input string return a new String and do not actually modify the input. If you want to replace the input with output value, you'll need to do a = a.insert(2, "x").

On the contrary, Spatial.rotate() does modify the input object and returns nothing.

The "return new value" policy is sometimes considered as bad practice, or more likely a old-fashioned way. But it is really subject to personal tastes.

Maybe it also simply depends on the usages. See this post (about C#, but on a similar topic)

However, such design change will bring backwards incompatibility, so it may not happen (soon).

Thanks @KoBeWi, looks like I missed the return type here. Like @StraToN and you mentioned, the documentation is quite confusing IMHO.

On one hand you have functions like String insert that return a new string, on the other there is e.g. void erase that just returns nothing while doing it's job.

Anyways, I'm going to close this issue as it's only been a misunderstanding on my part, thanks!

I'd say that documentation could be improved here. Now that I look at String docs, some methods say that they return a value and some just say about modifying string. It should be more consistent. But that's another issue probably.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Zylann picture Zylann  路  3Comments

blurymind picture blurymind  路  3Comments

testman42 picture testman42  路  3Comments

EdwardAngeles picture EdwardAngeles  路  3Comments

Spooner picture Spooner  路  3Comments