rhaiscript / rhai

Rhai - An embedded scripting language for Rust.
https://crates.io/crates/rhai
Apache License 2.0
3.77k stars 178 forks source link

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

Closed zitsen closed 6 months ago

zitsen commented 7 months ago

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 commented 7 months ago

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 commented 7 months ago

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 commented 6 months ago

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

schungx commented 6 months ago

Will do that tomorrow

schungx commented 6 months ago

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