tlang-interperter-cs/tlanglib/EachLoop.cs

102 lines
3.0 KiB
C#
Raw Permalink Normal View History

2023-03-10 10:12:36 +00:00
using System.Collections.Generic;
2023-03-09 23:57:16 +00:00
namespace tlang
{
public class EachLoop : Node
{
public GetVariableValue Name {get;set;}
public Node List {get;set;}
public Node Body {get;set;}
public EachLoop(GetVariableValue name, Node ls,Node body)
{
Name = name;
List = ls;
Body=body;
}
private IEnumerable<TObject> CreateItterator(IScopeEnvironment env,TObject ls)
{
var dict = ls as TDictionary;
var str = ls as TString;
var array = ls as TArray;
if(dict!= null)
{
var gIttrVar = dict["ittr"] as TDictionary;
2023-06-08 18:14:35 +00:00
var gIttrProp = dict["getittr"] as ICallable;
var myObj = gIttrVar;
2023-03-09 23:57:16 +00:00
if(gIttrProp != null)
{
2023-06-08 18:14:35 +00:00
var _myObj= gIttrProp.Call() as TDictionary;
if(_myObj != null)
{
myObj = _myObj;
}
}
if(myObj != null)
2023-03-09 23:57:16 +00:00
{
var reset = myObj["reset"] as ICallable;
var moveNext = myObj["movenext"] as ICallable;
2023-06-08 18:14:35 +00:00
var getCurrent = myObj["getcurrent"] as ICallable;
2023-03-09 23:57:16 +00:00
if(reset != null) reset.Call();
if(moveNext != null)
while(moveNext.Call().AsBoolean)
{
if(getCurrent != null)
{
yield return getCurrent.Call();
}
else
{
var current = myObj["current"];
yield return current;
}
}
}
2023-06-08 18:14:35 +00:00
2023-03-09 23:57:16 +00:00
}
else if(array != null)
{
foreach(var item in array.Items)
{
yield return item;
}
}
else if(str != null)
{
foreach(var c in str.Value)
{
2023-06-08 18:14:35 +00:00
yield return TObject.Char(c);
2023-03-09 23:57:16 +00:00
}
}
}
public override TObject Execute(IScopeEnvironment nodeEnv)
{
var env = nodeEnv.SubEnv;
var ls = List.Execute(env);
bool isRunning=true;
env["last_ittr"]= new TExternalMethod((args)=>{
2023-06-08 18:14:35 +00:00
2023-03-09 23:57:16 +00:00
isRunning=false;
2023-06-08 18:14:35 +00:00
return TObject.True;
2023-03-09 23:57:16 +00:00
});
TObject last = TObject.Uninit;
var enumerator=CreateItterator(env,ls).GetEnumerator();
while(isRunning && enumerator.MoveNext())
{
Name.SetValue(env,enumerator.Current);
Body.Execute(env);
}
return last;
}
}
}