1
0
Fork 0
forked from fun/fun

Added to_string() and to_number() functions as built-ins.

This commit is contained in:
Johannes Findeisen 2025-09-15 03:45:26 +02:00
commit 559400a866
11 changed files with 113 additions and 3 deletions

View file

@ -682,6 +682,47 @@ void vm_run(VM *vm, Bytecode *entry) {
break;
}
case OP_TO_NUMBER: {
Value v = pop_value(vm);
if (v.type == VAL_INT) {
/* pass-through */
Value out = make_int(v.i);
free_value(v);
push_value(vm, out);
} else if (v.type == VAL_STRING) {
const char *s = v.s ? v.s : "";
/* trim spaces */
const char *p = s;
while (*p == ' ' || *p == '\t' || *p == '\r' || *p == '\n') p++;
char *endp = NULL;
long long parsed = strtoll(p, &endp, 10);
/* skip trailing spaces */
while (endp && (*endp == ' ' || *endp == '\t' || *endp == '\r' || *endp == '\n')) endp++;
if (endp && *endp != '\0') {
/* non-numeric suffix -> 0 */
push_value(vm, make_int(0));
} else {
push_value(vm, make_int((int64_t)parsed));
}
free_value(v);
} else {
/* nil, array, function -> 0 */
free_value(v);
push_value(vm, make_int(0));
}
break;
}
case OP_TO_STRING: {
Value v = pop_value(vm);
char *s = value_to_string_alloc(&v);
Value out = make_string(s ? s : "");
if (s) free(s);
free_value(v);
push_value(vm, out);
break;
}
case OP_LOAD_GLOBAL: {
int idx = inst.operand;
if (idx < 0 || idx >= VM_MAX_GLOBALS) {