added input() to repl

This commit is contained in:
CPunch 2020-11-12 20:06:38 -06:00
parent 279714f3e0
commit 40ae495aaf
2 changed files with 21 additions and 4 deletions

View File

@ -33,11 +33,11 @@ typedef struct CValueArray {
CValue *values; CValue *values;
} CValueArray; } CValueArray;
COSMO_API void initValArray(CState *state, CValueArray *val, size_t startCapacity); void initValArray(CState *state, CValueArray *val, size_t startCapacity);
COSMO_API void cleanValArray(CState *state, CValueArray *array); // cleans array void cleanValArray(CState *state, CValueArray *array); // cleans array
COSMO_API void appendValArray(CState *state, CValueArray *array, CValue val); void appendValArray(CState *state, CValueArray *array, CValue val);
COSMO_API void printValue(CValue val); void printValue(CValue val);
COSMO_API bool cosmoV_equal(CValue valA, CValue valB); COSMO_API bool cosmoV_equal(CValue valA, CValue valB);
COSMO_API CObjString *cosmoV_toString(CState *state, CValue val); COSMO_API CObjString *cosmoV_toString(CState *state, CValue val);

View File

@ -15,6 +15,20 @@ CValue cosmoB_quitRepl(CState *state, int nargs, CValue *args) {
return cosmoV_newNil(); // we don't return anything return cosmoV_newNil(); // we don't return anything
} }
CValue cosmoB_input(CState *state, int nargs, CValue *args) {
// input() accepts the same params as print()!
for (int i = 0; i < nargs; i++) {
CObjString *str = cosmoV_toString(state, args[i]);
printf("%s", cosmoO_readCString(str));
}
// but, we return user input instead!
char line[1024];
fgets(line, sizeof(line), stdin);
return cosmoV_newObj(cosmoO_copyString(state, line, strlen(line)-1)); // -1 for the \n
}
static void interpret(CState *state, const char* script) { static void interpret(CState *state, const char* script) {
// cosmoP_compileString pushes the result onto the stack (NIL or COBJ_FUNCTION) // cosmoP_compileString pushes the result onto the stack (NIL or COBJ_FUNCTION)
@ -38,6 +52,7 @@ static void repl() {
// TODO: there's gotta be a better way to do this // TODO: there's gotta be a better way to do this
cosmoV_register(state, "quit", cosmoV_newObj(cosmoO_newCFunction(state, cosmoB_quitRepl))); cosmoV_register(state, "quit", cosmoV_newObj(cosmoO_newCFunction(state, cosmoB_quitRepl)));
cosmoV_register(state, "input", cosmoV_newObj(cosmoO_newCFunction(state, cosmoB_input)));
while (_ACTIVE) { while (_ACTIVE) {
printf("> "); printf("> ");
@ -90,6 +105,8 @@ static void runFile(const char* fileName) {
CState *state = cosmoV_newState(); CState *state = cosmoV_newState();
cosmoB_loadlibrary(state); cosmoB_loadlibrary(state);
cosmoV_register(state, "input", cosmoV_newObj(cosmoO_newCFunction(state, cosmoB_input)));
interpret(state, script); interpret(state, script);
cosmoV_freeState(state); cosmoV_freeState(state);