Skip to content

Commit cd92b91

Browse files
committed
Add default argument for string.split
If string.split is called without an argument, set " " as default delimiter. Fixes #31
1 parent 825908f commit cd92b91

File tree

2 files changed

+17
-3
lines changed

2 files changed

+17
-3
lines changed

src/string.c

+12-3
Original file line numberDiff line numberDiff line change
@@ -536,9 +536,9 @@ sl_string_char_at_index(sl_vm_t* vm, SLVAL self, SLVAL index)
536536
SLVAL
537537
sl_string_split(sl_vm_t* vm, SLVAL self, size_t argc, SLVAL* argv)
538538
{
539-
SLVAL substr = argv[0];
539+
SLVAL substr;
540540
sl_string_t* haystack = sl_get_string(vm, self);
541-
sl_string_t* needle = sl_get_string(vm, substr);
541+
sl_string_t* needle;
542542
SLVAL ret = sl_make_array(vm, 0, NULL), piece;
543543
uint8_t* haystack_buff = haystack->buff;
544544
uint8_t* start_ptr = haystack_buff;
@@ -547,6 +547,15 @@ sl_string_split(sl_vm_t* vm, SLVAL self, size_t argc, SLVAL* argv)
547547
size_t buff_len;
548548
uint32_t c;
549549
long limit = 0;
550+
551+
if(argc > 0) {
552+
substr = argv[0];
553+
} else {
554+
substr = sl_make_cstring(vm, " ");
555+
}
556+
557+
needle = sl_get_string(vm, substr);
558+
550559
if(argc > 1) {
551560
limit = sl_get_int(sl_expect(vm, argv[1], vm->lib.Int));
552561
if(limit < 0) {
@@ -764,7 +773,7 @@ sl_init_string(sl_vm_t* vm)
764773
sl_define_method(vm, vm->lib.String, "url_encode", 0, sl_string_url_encode);
765774
sl_define_method(vm, vm->lib.String, "index", 1, sl_string_index);
766775
sl_define_method(vm, vm->lib.String, "[]", 1, sl_string_char_at_index);
767-
sl_define_method(vm, vm->lib.String, "split", -2, sl_string_split);
776+
sl_define_method(vm, vm->lib.String, "split", -1, sl_string_split);
768777
sl_define_method(vm, vm->lib.String, "==", 1, sl_string_eq);
769778
sl_define_method(vm, vm->lib.String, "~", 1, sl_string_is_match);
770779
sl_define_method(vm, vm->lib.String, "<=>", 1, sl_string_spaceship);

test/core/string.sl

+5
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,11 @@ class StringTest extends Test {
138138
assert_equal(["foo", "bar baz"], "foo bar baz".split(" ", 2));
139139
assert_equal(["foo", "bar", "baz"], "foo bar baz".split(" ", 3));
140140
}
141+
142+
def test_split_with_default_argument {
143+
assert_equal(["hello", "world"], "hello world".split);
144+
assert_equal(["a", "b", "c"], "a b c".split);
145+
}
141146
142147
def test_spaceship {
143148
assert_equal(0, "a" <=> "a");

0 commit comments

Comments
 (0)