1
0
mirror of https://github.com/godotengine/godot.git synced 2025-11-05 12:10:55 +00:00

Ternary operator in GDScript (a if x else b)

Fixes #1961
This commit is contained in:
Bojidar Marinov
2016-08-25 21:18:35 +03:00
committed by Pedro J. Estébanez
parent c0743f898a
commit 6ad84850ab
3 changed files with 125 additions and 14 deletions

View File

@@ -661,6 +661,46 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre
codegen.opcodes.push_back(p_stack_level|GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS);
return p_stack_level|GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS;
} break;
// ternary operators
case GDParser::OperatorNode::OP_TERNARY_IF: {
// x IF a ELSE y operator with early out on failure
int res = _parse_expression(codegen,on->arguments[0],p_stack_level);
if (res<0)
return res;
codegen.opcodes.push_back(GDFunction::OPCODE_JUMP_IF_NOT);
codegen.opcodes.push_back(res);
int jump_fail_pos=codegen.opcodes.size();
codegen.opcodes.push_back(0);
res = _parse_expression(codegen,on->arguments[1],p_stack_level);
if (res<0)
return res;
codegen.alloc_stack(p_stack_level); //it will be used..
codegen.opcodes.push_back(GDFunction::OPCODE_ASSIGN);
codegen.opcodes.push_back(p_stack_level|GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS);
codegen.opcodes.push_back(res);
codegen.opcodes.push_back(GDFunction::OPCODE_JUMP);
int jump_past_pos=codegen.opcodes.size();
codegen.opcodes.push_back(0);
codegen.opcodes[jump_fail_pos]=codegen.opcodes.size();
res = _parse_expression(codegen,on->arguments[2],p_stack_level);
if (res<0)
return res;
codegen.opcodes.push_back(GDFunction::OPCODE_ASSIGN);
codegen.opcodes.push_back(p_stack_level|GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS);
codegen.opcodes.push_back(res);
codegen.opcodes[jump_past_pos]=codegen.opcodes.size();
return p_stack_level|GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS;
} break;
//unary operators
case GDParser::OperatorNode::OP_NEG: { if (!_create_unary_operator(codegen,on,Variant::OP_NEGATE,p_stack_level)) return -1;} break;