join can now operate on strings.

added vstrcat, but never used.
This commit is contained in:
2014-06-21 22:48:47 +01:00
parent f74035fcce
commit f2c8dc167c
3 changed files with 60 additions and 9 deletions

View File

@@ -258,17 +258,40 @@ lval* builtin_eval(lenv* env, lval* val){
} }
lval* builtin_join(lenv* env, lval* val){ lval* builtin_join(lenv* env, lval* val){
LASSERT_MIN_ARG_COUNT("join", val, val, 1); LASSERT_MIN_ARG_COUNT("join", val, val, 1);
BOOL string = TRUE;
size_t totalStringLength = 0;
for(int i = 0; i < val->cell_count; i++) { for(int i = 0; i < val->cell_count; i++) {
LASSERT_TYPE("join", val, val->cell_list[i], LVAL_Q_EXPR); if (val->cell_list[i]->type != LVAL_STR) {
string = FALSE;
break;
} else {
totalStringLength += strlen(val->cell_list[i]->data.str);
}
} }
lval* x = lval_pop(val,0); if (string) {
char* newStr = calloc(totalStringLength+1, sizeof(char));
while(val->cell_count > 0) { for(int i = 0; i < val->cell_count; i++) {
x = lval_join(x, lval_pop(val, 0)); strcat(newStr, val->cell_list[i]->data.str);
}
lval* newVal = lval_str(newStr);
lval_delete(val);
return newVal;
} else { //Not string, join lists
for(int i = 0; i < val->cell_count; i++) {
LASSERT_TYPE("join", val, val->cell_list[i], LVAL_Q_EXPR);
}
lval* x = lval_pop(val,0);
while(val->cell_count > 0) {
x = lval_join(x, lval_pop(val, 0));
}
return x;
} }
return x;
} }
lval* builtin_head(lenv* env, lval* val){ lval* builtin_head(lenv* env, lval* val){
LASSERT_ARG_COUNT("head", val, val, 1); LASSERT_ARG_COUNT("head", val, val, 1);

29
util.c
View File

@@ -1,12 +1,39 @@
#include <string.h> #include <string.h>
#include <stdlib.h> #include <stdlib.h>
#include <stdarg.h>
#include "util.h" #include "util.h"
char * strdup(char* s) { char * strdup(const char* s) {
if (s == NULL) return NULL; if (s == NULL) return NULL;
char *d = calloc(strlen (s) + 1, sizeof(char)); char *d = calloc(strlen (s) + 1, sizeof(char));
if (d == NULL) return NULL; if (d == NULL) return NULL;
strcpy (d,s); strcpy (d,s);
return d; return d;
} }
char* vstrcat(int n, ...) {
va_list va;
char** strings = calloc(n, sizeof(char*));
size_t stringLength = 0;
va_start(va, n);
for(int i = 0; i<n; i++) {
strings[i] = va_arg(va, char*);
stringLength += strlen(strings[i]);
}
va_end(va);
char* newStr = calloc(stringLength+1, sizeof(char));
for(int i = 0; i<n; i++) {
strcat(newStr, strings[i]);
}
free(strings);
return newStr;
}

3
util.h
View File

@@ -12,7 +12,8 @@
extern "C" { extern "C" {
#endif #endif
char * strdup(char* s); char* strdup(const char* s);
char* vstrcat(int n, ...);
#ifdef __cplusplus #ifdef __cplusplus
} }