add string at func, fix string split

This commit is contained in:
Neemek 2025-09-16 20:01:29 +02:00
parent 16e756bd4e
commit 14d7a5ce73
2 changed files with 26 additions and 8 deletions

View file

@ -3,9 +3,9 @@ package core
import (
"errors"
"fmt"
"math"
"reflect"
"strconv"
"strings"
)
type ValueType int
@ -326,17 +326,19 @@ var StringPrototype = map[string]*BuiltinFunctionValue{
str := this.(*StringValue).String()
sep := v[0].(*StringValue).String()
prev := 0
var out []Value
tmp := strings.Builder{}
for i := 0; i < len(str)-len(sep); i++ {
tmp.WriteRune([]rune(str)[i])
for i := 1; i < len(str)-len(sep); i++ {
if str[i:i+len(sep)] == sep {
out = append(out, &StringValue{tmp.String()})
tmp.Reset()
out = append(out, &StringValue{str[prev:i]})
prev = i + len(sep)
}
}
if prev != len(str) {
out = append(out, &StringValue{str[prev:len(str)]})
}
return &ListValue{out}, nil
},
nil,
@ -352,6 +354,22 @@ var StringPrototype = map[string]*BuiltinFunctionValue{
return GoToValue(len(this.(*StringValue).Text)), nil
},
},
"at": {
Name: "at",
Signature: &FunctionSignature{
[]TypeSignature{&NumberSignature{}},
&StringSignature{},
},
F: func(vm *VM, this Value, args []Value) (Value, error) {
i := int(math.Floor(args[0].(*NumberValue).Number))
if i < 0 || i >= len(this.(*StringValue).Text) {
return nil, errors.New("index is out of range")
}
return GoToValue(string(this.(*StringValue).Text[i])), nil
},
},
}
func (v *StringValue) Get(key string) (Value, error) {