122 lines
3.3 KiB
C#
122 lines
3.3 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Text;
|
|
using Newtonsoft.Json.Linq;
|
|
|
|
namespace tlang
|
|
{
|
|
public class TRootDict : TDictionary
|
|
{
|
|
|
|
IScopeEnvironment env;
|
|
public TRootDict(IScopeEnvironment env)
|
|
{
|
|
this.env=env;
|
|
}
|
|
public override TObject GetMember(string name)
|
|
{
|
|
return env.GetVariable(name);
|
|
}
|
|
public override void SetMember(string name, TObject obj)
|
|
{
|
|
env.SetVariable(name,obj);
|
|
}
|
|
public override bool MemberExists(string name)
|
|
{
|
|
return env.VariableExists(name);
|
|
}
|
|
}
|
|
public class TDictionary : TObject
|
|
{
|
|
public override JToken AsToken()
|
|
{
|
|
if(this.TryGetTimeSpan(out var ts))
|
|
{
|
|
return JValue.FromObject(ts);
|
|
}
|
|
JObject obj=new JObject();
|
|
foreach(var item in this.items)
|
|
{
|
|
obj.Add(item.Key,item.Value.AsToken());
|
|
}
|
|
return obj;
|
|
}
|
|
public override bool AsBoolean {get =>true;}
|
|
public TDictionary()
|
|
{
|
|
|
|
}
|
|
|
|
Dictionary<string,TObject> items {get;set;}=new Dictionary<string, TObject>();
|
|
|
|
public virtual TObject GetMember(string name)
|
|
{
|
|
if(items.ContainsKey(name))
|
|
{
|
|
return items[name];
|
|
}else{
|
|
return TObject.Uninit;
|
|
}
|
|
}
|
|
|
|
public virtual void SetMember(string name, TObject obj)
|
|
{
|
|
if(items.ContainsKey(name))
|
|
{
|
|
items[name] = obj;
|
|
}
|
|
else
|
|
{
|
|
items.Add(name,obj);
|
|
}
|
|
}
|
|
public override string ToString()
|
|
{
|
|
if(items.ContainsKey("toString"))
|
|
{
|
|
var tostr = items["toString"] as ICallable;
|
|
if(tostr != null)
|
|
{
|
|
var res= tostr.Call().ToString();
|
|
return res;
|
|
}
|
|
}
|
|
StringBuilder b = new StringBuilder();
|
|
b.AppendLine("Dictionary Items:");
|
|
foreach(var item in items)
|
|
{
|
|
b.AppendLine($"{item.Key}={item.Value.ToString()}");
|
|
}
|
|
return b.ToString();
|
|
}
|
|
public virtual bool MemberExists(string name)
|
|
{
|
|
return items.ContainsKey(name);
|
|
}
|
|
|
|
internal IEnumerable<TDictionary> GetMembers()
|
|
{
|
|
foreach(var item in items)
|
|
{
|
|
TDictionary dict = TObject.Dictionary();
|
|
dict["getname"] = new TExternalMethod(()=>{
|
|
return TObject.String(item.Key);
|
|
});
|
|
dict["getvalue"] = new TExternalMethod(()=>{
|
|
return item.Value;
|
|
});
|
|
dict["setvalue"] = new TExternalMethod((args)=>{
|
|
if(args.Length == 1)
|
|
{
|
|
items[item.Key] = args[0];
|
|
}
|
|
});
|
|
yield return dict;
|
|
}
|
|
}
|
|
|
|
public TObject this[string variable] { get => GetMember(variable); set => SetMember(variable,value); }
|
|
|
|
|
|
}
|
|
} |