tlang-interperter-cs/tlanglib/TDictionary.cs

122 lines
3.3 KiB
C#
Raw Permalink Normal View History

2023-06-08 18:14:35 +00:00
using System;
2023-03-10 10:12:36 +00:00
using System.Collections.Generic;
2023-06-08 18:14:35 +00:00
using System.Text;
using Newtonsoft.Json.Linq;
2023-03-10 10:12:36 +00:00
2023-03-09 19:40:14 +00:00
namespace tlang
{
2023-03-10 04:33:58 +00:00
public class TRootDict : TDictionary
{
2023-06-08 18:14:35 +00:00
2023-03-10 04:33:58 +00:00
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);
}
}
2023-03-09 19:40:14 +00:00
public class TDictionary : TObject
{
2023-06-08 18:14:35 +00:00
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;
}
2023-03-09 23:57:16 +00:00
public override bool AsBoolean {get =>true;}
2023-03-09 19:40:14 +00:00
public TDictionary()
{
}
Dictionary<string,TObject> items {get;set;}=new Dictionary<string, TObject>();
2023-03-10 04:33:58 +00:00
public virtual TObject GetMember(string name)
2023-03-09 19:40:14 +00:00
{
if(items.ContainsKey(name))
{
return items[name];
}else{
return TObject.Uninit;
}
}
2023-03-10 04:33:58 +00:00
public virtual void SetMember(string name, TObject obj)
2023-03-09 19:40:14 +00:00
{
if(items.ContainsKey(name))
{
items[name] = obj;
}
else
{
items.Add(name,obj);
}
}
2023-06-08 18:14:35 +00:00
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();
}
2023-03-10 04:33:58 +00:00
public virtual bool MemberExists(string name)
2023-03-09 19:40:14 +00:00
{
return items.ContainsKey(name);
}
2023-06-08 18:14:35 +00:00
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;
}
}
2023-03-09 19:40:14 +00:00
public TObject this[string variable] { get => GetMember(variable); set => SetMember(variable,value); }
}
}