Return
This commit is contained in:
@@ -15,6 +15,7 @@ InstructionType strToInstructionType(std::string in) {
|
||||
else if (in == "while") return InstructionType::While;
|
||||
else if (in == "compare") return InstructionType::Compare;
|
||||
else if (in == "input") return InstructionType::Input;
|
||||
else if (in == "return") return InstructionType::Return;
|
||||
else return InstructionType::Variable;
|
||||
}
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
|
||||
enum class InstructionType {
|
||||
None, Print, Println, Math, Let, Variable, Exit, If, While, Input, Compare, Function
|
||||
None, Print, Println, Math, Let, Variable, Exit, If, While, Input, Compare, Function, Return
|
||||
};
|
||||
|
||||
enum class ValueType {
|
||||
@@ -33,6 +33,7 @@ struct Value {
|
||||
std::unique_ptr<Instruction> processed;
|
||||
std::string real = "";
|
||||
InstructionGroup instructionGroup;
|
||||
bool is_return = false;
|
||||
std::string toString() const;
|
||||
Varname varName = Varname();
|
||||
Value(std::string stringval);
|
||||
|
||||
@@ -89,10 +89,14 @@ Value execute(Instruction inst) {
|
||||
Value return_val;
|
||||
for (const auto& body_inst : func.body) {
|
||||
return_val = execute(body_inst);
|
||||
if (return_val.is_return) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
data::popScope();
|
||||
|
||||
return_val.is_return = false;
|
||||
return return_val;
|
||||
}
|
||||
}
|
||||
@@ -104,6 +108,16 @@ Value execute(Instruction inst) {
|
||||
}
|
||||
break;
|
||||
}
|
||||
case InstructionType::Return: {
|
||||
if (inst.args.empty()) {
|
||||
Value val;
|
||||
val.is_return = true;
|
||||
return val;
|
||||
}
|
||||
Value return_val = inst.args[0];
|
||||
return_val.is_return = true;
|
||||
return return_val;
|
||||
}
|
||||
default:
|
||||
// Note: 'If' and 'Let' are already handled.
|
||||
error("Unknown instruction");
|
||||
|
||||
@@ -30,12 +30,18 @@ Value modules::ifs(std::vector<Value> args) {
|
||||
if (is_true) {
|
||||
for (const auto& inst : args[1].instructionGroup) {
|
||||
return_val = execute(inst);
|
||||
if (return_val.is_return) {
|
||||
return return_val;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (args.size() > 2) {
|
||||
if (args[2].valtype == ValueType::InstructionGroup) {
|
||||
for (const auto& inst : args[2].instructionGroup) {
|
||||
return_val = execute(inst);
|
||||
if (return_val.is_return) {
|
||||
return return_val;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
error("Syntax error: 'else' body must be an instruction group");
|
||||
|
||||
@@ -30,6 +30,9 @@ Value modules::whiles(std::vector<Value> args) {
|
||||
while (is_true) {
|
||||
for (const auto& inst : args[1].instructionGroup) {
|
||||
return_val = execute(inst);
|
||||
if (return_val.is_return) {
|
||||
return return_val;
|
||||
}
|
||||
}
|
||||
condition_result = execute(*args[0].processed);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user