Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature: syntax str[range] support like rust string indexing by range #841

Closed
zitsen opened this issue Mar 1, 2024 · 5 comments · Fixed by #845
Closed

Feature: syntax str[range] support like rust string indexing by range #841

zitsen opened this issue Mar 1, 2024 · 5 comments · Fixed by #845

Comments

@zitsen
Copy link
Contributor

zitsen commented Mar 1, 2024

Expect:

let s = "abcd";
let n = s[1..3];

Now it reports:

2: let n = s[1..3];
             ^ Data type incorrect: core::ops::range::Range<i64> (expecting i64)

Would this feature could be supported? Maybe I can contribute if you don't mind to add this, and give me some help to start.

@schungx
Copy link
Collaborator

schungx commented Mar 1, 2024

Well, there is sub_string that does something similar...

The actual implementation may be quite involved, since indexer for strings cannot be overridden. It is built-in. Internally it uses mutable references to do its magic. For example, if we implement this correctly for strings, you can do this:

let s = "abcdefg";
s[1..3] = "xyz";    // you can even modify a sub-range inside a string!
print(s);    // prints `axyzdefg`

When Rhai was first developed, ranges were not in, so this feature was left uncoded.

It should be similar to how indexing into a string to get at a single character would work:

let s = "abcdefg";
s[1] = 'x';
print(s);    // prints `axcdefg`

@schungx
Copy link
Collaborator

schungx commented Mar 1, 2024

You may look into the Target type to see how character indexing is done, and then adapt it to ranges if you want a shot at it?

zitsen added a commit to zitsen/rhai that referenced this issue Mar 18, 2024
Now we support range indexing on strings, including ref/mut impls.

For example, you can use range indexing intead of sub_of_string() method
like bellow:

```rust
let s1 = "abcde";
let s2 = s1[1..4]; // "bcd"
s1[1..4] = "f"; // s1: "afe", s2: "bcd"
```

Close rhaiscript#841
@zitsen
Copy link
Contributor Author

zitsen commented Mar 18, 2024

May you have time to review the pr: #845 ?

@schungx
Copy link
Collaborator

schungx commented Mar 18, 2024

Will do that tomorrow

@schungx
Copy link
Collaborator

schungx commented Mar 19, 2024

There are a few odds and ends that you missed, which I'll fix and update with a new drop.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants