godotengine / godot

Godot Engine – Multi-platform 2D and 3D game engine
https://godotengine.org
MIT License
91.15k stars 21.19k forks source link

GDScript: String.substr returns more text than specified #47243

Closed ephreal closed 3 years ago

ephreal commented 3 years ago

Godot version: 3.2.3

OS/device including version: Archlinux with Linux x86_64 kernel 5.11.7

Issue description: When using GDScript's substr method on a string, the result is often incorrect. Substring appears to work correctly near the start of the string, but fails to return to correct result towards the middle and end of the string.

In all instances exhibiting the problem that I tested, substr returns far more text than should be expected. For example, in the steps to reproduce, the third substring call should return 5 characters, but returns 17 instead.

Steps to reproduce: Place the following code inside of a gdscript file and attempt to run it.

func _ready():

    # string.substr(start, end) appears to function incorrectly. Some parts
    # work as expected, but some places in the string do not. Here is some text
    # from the poem "The Jabberwocky".
    var jabber = "twas brillig and the slithey toves, did gyre and gimble in the wabe."

    # Should (and does) print out "twas "
    print("substr(0, 5)")
    print(jabber.substr(0,5))
    print()

    # Should (and does) print out "twas brillig and the slithey toves"
    print("substr(0, 35)")
    print(jabber.substr(0,35))
    print()

    # Should print out " and ", but instead prints out " and the slithey "
    print("substr(12, 17)")
    print(jabber.substr(12,17))
    print()

    # Attempt to print out the "did gyre and gimble".
    # Prints out "did gyre and gimble in the wabe." instead.
    print("substr(36, 54)")
    print(jabber.substr(36,54))
    print()

When running the code, the output should be similar to this if the same issue is being seen: snip

Minimal reproduction project: String.substr Issue.zip

EDIT: As soon as I submitted this, something clicked. I believe I have misread the documentation about 15 times in a row. The second part is the length of the string to get, not the index to stop at. Coming from a python background, I completely missed that every time I read it. Sounds like rubber duck debugging at it's finest!

ephreal commented 3 years ago

As soon as I submitted this, something clicked. I believe I have misread the documentation about 15 times in a row. The second part is the length of the string to get, not the index to stop at. Coming from a python background, I completely missed that every time I read it. Sounds like rubber duck debugging at it's finest!

If it makes sense for the development side of things to add in a .slice(start_index, end_index) method to gdscript, I'm sure other might appreciate it as well. If not, then sorry for tho noise on this one.