diff --git a/minproto.leg b/minproto.leg index 006c917..f980578 100644 --- a/minproto.leg +++ b/minproto.leg @@ -4010,10 +4010,21 @@ oop prim_String_pop(oop func, oop self, oop args, oop env) } oop prim_String_asInteger(oop func, oop self, oop args, oop env) -{ assert(is(String, self)); +{ assert(is(Object, args)); + int argc = _get(args, Object,isize); assert(is(String, self)); + if (argc > 1) fatal("String.asInteger: expected either 0 or 1 arguments, got %d\n", argc); + char *str = String_content(self); // ensure nul terminator char *end = 0; - long value = strtol(str, &end, 0); + long value; + + if (argc == 1) { + oop base = _get(args, Object,indexed)[0]; + value = strtol(str, &end, integerValue(base, "String.asInteger")); + } else { + value = strtol(str, &end, 0); + } + if (*end) return nil; return newInteger(value); } diff --git a/test.txt b/test.txt index 0255044..48bf644 100644 --- a/test.txt +++ b/test.txt @@ -378,6 +378,12 @@ ast = (`6 * @myNode;); // user-defined node in AST print("AST eval => ", eval(ast), "\n"); +print("String to int conversion\n"); +print("11111111".asInteger(2), "\n"); +print("377".asInteger(8), "\n"); +print("255".asInteger(), "\n"); +print("FF".asInteger(16), "\n"); + for (i from 0 to 10) print(i, " "); print("\n"); for (i from 10 to 0) print(i, " "); print("\n"); for (i in 10) print(i, " "); print("\n");