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

@ -260,6 +260,7 @@ func (p *Parser) factor() (Node, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
return &ListNode{ return &ListNode{
[]Node{}, []Node{},
s, s,
@ -277,7 +278,6 @@ func (p *Parser) factor() (Node, error) {
} }
value, err := p.condition() value, err := p.condition()
if err != nil { if err != nil {
return nil, err return nil, err
} }

View file

@ -3,9 +3,9 @@ package core
import ( import (
"errors" "errors"
"fmt" "fmt"
"math"
"reflect" "reflect"
"strconv" "strconv"
"strings"
) )
type ValueType int type ValueType int
@ -326,17 +326,19 @@ var StringPrototype = map[string]*BuiltinFunctionValue{
str := this.(*StringValue).String() str := this.(*StringValue).String()
sep := v[0].(*StringValue).String() sep := v[0].(*StringValue).String()
prev := 0
var out []Value var out []Value
tmp := strings.Builder{} for i := 1; i < len(str)-len(sep); i++ {
for i := 0; i < len(str)-len(sep); i++ {
tmp.WriteRune([]rune(str)[i])
if str[i:i+len(sep)] == sep { if str[i:i+len(sep)] == sep {
out = append(out, &StringValue{tmp.String()}) out = append(out, &StringValue{str[prev:i]})
tmp.Reset() prev = i + len(sep)
} }
} }
if prev != len(str) {
out = append(out, &StringValue{str[prev:len(str)]})
}
return &ListValue{out}, nil return &ListValue{out}, nil
}, },
nil, nil,
@ -352,6 +354,22 @@ var StringPrototype = map[string]*BuiltinFunctionValue{
return GoToValue(len(this.(*StringValue).Text)), nil 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) { func (v *StringValue) Get(key string) (Value, error) {