🐐 String indexing and slicing
This commit is contained in:
@@ -833,6 +833,17 @@ class ArrayIndex(Node):
|
||||
if k not in d:
|
||||
raise CentvrionError(f"Key not found in dict")
|
||||
return vtable, d[k]
|
||||
if isinstance(array, ValStr):
|
||||
if isinstance(index, ValInt):
|
||||
i = index.value()
|
||||
elif isinstance(index, ValFrac) and index.value().denominator == 1:
|
||||
i = index.value().numerator
|
||||
else:
|
||||
raise CentvrionError("String index must be a number")
|
||||
s = array.value()
|
||||
if i < 1 or i > len(s):
|
||||
raise CentvrionError(f"Index {i} out of range for string of length {len(s)}")
|
||||
return vtable, ValStr(s[i - 1])
|
||||
if not isinstance(array, ValList):
|
||||
raise CentvrionError("Cannot index a non-array value")
|
||||
if isinstance(index, ValInt):
|
||||
@@ -877,6 +888,16 @@ class ArraySlice(Node):
|
||||
vtable, array = self.array.eval(vtable)
|
||||
vtable, from_val = self.from_index.eval(vtable)
|
||||
vtable, to_val = self.to_index.eval(vtable)
|
||||
if isinstance(array, ValStr):
|
||||
from_int = _to_index_int(from_val)
|
||||
to_int = _to_index_int(to_val)
|
||||
s = array.value()
|
||||
if from_int < 1 or to_int > len(s) or from_int > to_int:
|
||||
raise CentvrionError(
|
||||
f"Slice [{from_int} VSQVE {to_int}] out of range"
|
||||
f" for string of length {len(s)}"
|
||||
)
|
||||
return vtable, ValStr(s[from_int - 1 : to_int])
|
||||
if not isinstance(array, ValList):
|
||||
raise CentvrionError("Cannot slice a non-array value")
|
||||
from_int = _to_index_int(from_val)
|
||||
|
||||
Reference in New Issue
Block a user