diff --git a/builtin/io.wren b/builtin/io.wren index 8ac4bead..c3be2db7 100644 --- a/builtin/io.wren +++ b/builtin/io.wren @@ -78,4 +78,9 @@ class IO { IO.writeString_(obj.toString) return obj } + + static read(prompt) { + IO.write(prompt) + return IO.read + } } diff --git a/src/wren_io.c b/src/wren_io.c index f0dbde33..17ffad90 100644 --- a/src/wren_io.c +++ b/src/wren_io.c @@ -3,8 +3,12 @@ #if WREN_USE_LIB_IO #include +#include #include +// TODO: this is a somewhat arbitrary limit, do something smarter? +#define MAX_READ_LEN 1024 + // This string literal is generated automatically from io.wren. Do not edit. static const char* libSource = "class IO {\n" @@ -87,6 +91,11 @@ static const char* libSource = " IO.writeString_(obj.toString)\n" " return obj\n" " }\n" +"\n" +" static read(prompt) {\n" +" IO.write(prompt)\n" +" return IO.read\n" +" }\n" "}\n"; static void ioWriteString(WrenVM* vm) @@ -96,6 +105,18 @@ static void ioWriteString(WrenVM* vm) printf("%s", s); } +static void ioRead(WrenVM* vm) +{ + char buffer[MAX_READ_LEN]; + char* result = fgets(buffer, MAX_READ_LEN, stdin); + + if (result == NULL) { + // TODO: handle error here + } + + wrenReturnString(vm, buffer, strlen(buffer)); +} + static void ioClock(WrenVM* vm) { wrenReturnDouble(vm, (double)clock() / CLOCKS_PER_SEC); @@ -106,6 +127,7 @@ void wrenLoadIOLibrary(WrenVM* vm) wrenInterpret(vm, "Wren IO library", libSource); wrenDefineStaticMethod(vm, "IO", "writeString_", 1, ioWriteString); wrenDefineStaticMethod(vm, "IO", "clock", 0, ioClock); + wrenDefineStaticMethod(vm, "IO", "read", 0, ioRead); } #endif