Added to_string() and to_number() functions as built-ins.
This commit is contained in:
parent
d67c541824
commit
559400a866
11 changed files with 113 additions and 3 deletions
41
src/vm.c
41
src/vm.c
|
|
@ -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) {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue