'return' is now a valid statement outside of a function

lets us do some cool things later. also the repl can print returned values. eg.

`return "hello world"` will print `<string> "hello world"` to the console
This commit is contained in:
cpunch 2023-12-28 23:41:10 -06:00
parent 43d79a456e
commit e0455902b0
2 changed files with 16 additions and 4 deletions

12
main.c
View File

@ -50,9 +50,21 @@ static bool interpret(CState *state, const char *script, const char *mod)
// cosmoV_compileString pushes the result onto the stack (COBJ_ERROR or COBJ_CLOSURE) // cosmoV_compileString pushes the result onto the stack (COBJ_ERROR or COBJ_CLOSURE)
if (cosmoV_compileString(state, script, mod)) { if (cosmoV_compileString(state, script, mod)) {
if (!cosmoV_pcall(state, 0, 1)) {
cosmoV_printBacktrace(state, cosmoV_readError(*cosmoV_pop(state))); cosmoV_printBacktrace(state, cosmoV_readError(*cosmoV_pop(state)));
return false; return false;
} }
// if the result is nil, we don't print it
if (IS_NIL(*cosmoV_getTop(state, 0))) {
cosmoV_pop(state);
return true;
}
// otherwise, we print the result
cosmoV_printValue(*cosmoV_getTop(state, 0));
printf("\n");
cosmoV_pop(state);
} else { } else {
cosmoV_printBacktrace(state, cosmoV_readError(*cosmoV_pop(state))); cosmoV_printBacktrace(state, cosmoV_readError(*cosmoV_pop(state)));
return false; return false;

View File

@ -1471,10 +1471,10 @@ static void functionDeclaration(CParseState *pstate)
static void returnStatement(CParseState *pstate) static void returnStatement(CParseState *pstate)
{ {
if (pstate->compiler->type != FTYPE_FUNCTION && pstate->compiler->type != FTYPE_METHOD) { // if (pstate->compiler->type != FTYPE_FUNCTION && pstate->compiler->type != FTYPE_METHOD) {
error(pstate, "Expected 'return' in function!"); // error(pstate, "Expected 'return' in function!");
return; // return;
} // }
if (blockFollow(pstate->current)) { // does this return have a value if (blockFollow(pstate->current)) { // does this return have a value
writeu8(pstate, OP_NIL); writeu8(pstate, OP_NIL);