Skip to content

Commit f2c8dc1

Browse files
committed
join can now operate on strings.
added vstrcat, but never used.
1 parent f74035f commit f2c8dc1

File tree

3 files changed

+60
-9
lines changed

3 files changed

+60
-9
lines changed

functions.c

+30-7
Original file line numberDiff line numberDiff line change
@@ -258,17 +258,40 @@ lval* builtin_eval(lenv* env, lval* val){
258258
}
259259
lval* builtin_join(lenv* env, lval* val){
260260
LASSERT_MIN_ARG_COUNT("join", val, val, 1);
261+
262+
BOOL string = TRUE;
263+
size_t totalStringLength = 0;
261264
for(int i = 0; i < val->cell_count; i++) {
262-
LASSERT_TYPE("join", val, val->cell_list[i], LVAL_Q_EXPR);
265+
if (val->cell_list[i]->type != LVAL_STR) {
266+
string = FALSE;
267+
break;
268+
} else {
269+
totalStringLength += strlen(val->cell_list[i]->data.str);
270+
}
263271
}
264272

265-
lval* x = lval_pop(val,0);
266-
267-
while(val->cell_count > 0) {
268-
x = lval_join(x, lval_pop(val, 0));
273+
if (string) {
274+
char* newStr = calloc(totalStringLength+1, sizeof(char));
275+
for(int i = 0; i < val->cell_count; i++) {
276+
strcat(newStr, val->cell_list[i]->data.str);
277+
}
278+
279+
lval* newVal = lval_str(newStr);
280+
lval_delete(val);
281+
return newVal;
282+
} else { //Not string, join lists
283+
for(int i = 0; i < val->cell_count; i++) {
284+
LASSERT_TYPE("join", val, val->cell_list[i], LVAL_Q_EXPR);
285+
}
286+
287+
lval* x = lval_pop(val,0);
288+
289+
while(val->cell_count > 0) {
290+
x = lval_join(x, lval_pop(val, 0));
291+
}
292+
293+
return x;
269294
}
270-
271-
return x;
272295
}
273296
lval* builtin_head(lenv* env, lval* val){
274297
LASSERT_ARG_COUNT("head", val, val, 1);

util.c

+28-1
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,39 @@
11
#include <string.h>
22
#include <stdlib.h>
3+
#include <stdarg.h>
34

45
#include "util.h"
56

6-
char * strdup(char* s) {
7+
char * strdup(const char* s) {
78
if (s == NULL) return NULL;
89
char *d = calloc(strlen (s) + 1, sizeof(char));
910
if (d == NULL) return NULL;
1011
strcpy (d,s);
1112
return d;
1213
}
14+
15+
char* vstrcat(int n, ...) {
16+
va_list va;
17+
18+
char** strings = calloc(n, sizeof(char*));
19+
size_t stringLength = 0;
20+
21+
va_start(va, n);
22+
23+
for(int i = 0; i<n; i++) {
24+
strings[i] = va_arg(va, char*);
25+
stringLength += strlen(strings[i]);
26+
}
27+
28+
va_end(va);
29+
30+
char* newStr = calloc(stringLength+1, sizeof(char));
31+
32+
for(int i = 0; i<n; i++) {
33+
strcat(newStr, strings[i]);
34+
}
35+
36+
free(strings);
37+
38+
return newStr;
39+
}

util.h

+2-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,8 @@
1212
extern "C" {
1313
#endif
1414

15-
char * strdup(char* s);
15+
char* strdup(const char* s);
16+
char* vstrcat(int n, ...);
1617

1718
#ifdef __cplusplus
1819
}

0 commit comments

Comments
 (0)