private void isVariable(ref string stmt) // checks if user want to print a variable. Or function call results.
{
int frstopenbrkt = -2, secopenbrkt = -2, closingbrkt = -2, arowassignidx = -2, eqassignidx, assignidx = -2;
bool beginswithprint = stmt.StartsWith("print(") || stmt.StartsWith("(");
if (beginswithprint)
{
frstopenbrkt = stmt.IndexOf("(");
secopenbrkt = stmt.IndexOf("(", frstopenbrkt + 1);
}
else
{
secopenbrkt = stmt.IndexOf("(");
}
closingbrkt = stmt.IndexOf(")", secopenbrkt + 1);
bool hasassignmentoperator = (stmt.Contains("=") || stmt.Contains("<-"));
if (hasassignmentoperator && secopenbrkt > 0)
{
eqassignidx = stmt.IndexOf("=");
arowassignidx = stmt.IndexOf("<-");
if (eqassignidx > 0 && arowassignidx > 0) // both assignment oprator exists. say: a<-func(q=TRUE)
{
assignidx = eqassignidx < arowassignidx ? eqassignidx : arowassignidx; // whichever has less idx
}
else if (eqassignidx > 0) // only '=' exists
{
assignidx = eqassignidx;
}
else if (arowassignidx > 0)//only "<-" exists
{
assignidx = arowassignidx;
}
//its not assignment of type 'aa = something'. Rather its assignment in parameters like 'somfunc(isgood=TRUE)'
if (assignidx > secopenbrkt && closingbrkt > assignidx)//if closing to secopenbrkt closes after assignment'='
hasassignmentoperator = false;
}
bool beginswithcat = stmt.StartsWith("cat(");
if (beginswithprint && hasassignmentoperator) // for print(a<-c('msg')
{
int indexofopeningprintparenthesis = stmt.IndexOf('(');// first (
int indexofclosingprintparenthesis = stmt.LastIndexOf(')');// last )
int indexofassignmentopr = stmt.IndexOf("<-") > 0 ? stmt.IndexOf("<-") : stmt.IndexOf('=');
string varname = stmt.Substring(indexofopeningprintparenthesis + 1, (indexofassignmentopr - indexofopeningprintparenthesis - 1));// a
stmt = stmt.Remove(indexofclosingprintparenthesis).Replace("print(", "") + "; print(" + varname + ");";// a<-c('msg'); print(a);
}
if (!beginswithprint && !hasassignmentoperator && !beginswithcat)// for a & a+ a+a+a*2 & help(...) & ?...
{
stmt = "print(" + stmt + ")";
}
}