Luatable equivalent in C#? -
i've been looking way make table thing in c# (3.5), still have come empty. want this
var myclassvar = new myclass(); myclassvar["hello"]["world"] = "hello world"; myclassvar["hello"][0] = "swapped"; myclassvar[0][0] = "test"; myclassvar["hello"]["to"]["the"]["world"] = "again"; myclassvar[0][1][0][0] = "same above sorta";
i'm trying create type of class parse file format i've created storing data. know of this?
public class luatable { private dictionary<object, dynamic> properties = new dictionary<object, dynamic>(); public dynamic this[object property] { { if (properties.containskey(property)) return properties[property]; luatable table = new luatable(); properties.add(property, table); return table; } set { if (!properties.containskey(property)) properties.add(property, value); else properties[property] = value; } } }
you can use how want to:
var myclassvar = new luatable(); myclassvar["hello"]["world"] = "hello world"; myclassvar["hello"][0] = "swapped"; myclassvar[0][0] = "test"; myclassvar["hello"]["to"]["the"]["world"] = "again"; myclassvar[0][1][0][0] = "same above sorta"; string s1 = myclassvar["hello"]["world"]; // = "hello world" string s2 = myclassvar["hello"][0]; // = "swapped" string s3 = myclassvar[0][0]; // = "test" string s4 = myclassvar["hello"]["to"]["the"]["world"]; // = "again" string s5 = myclassvar[0][1][0][0]; // = "same above sorta"
edit: realized c# 3.5 doesn't have dynamic
, here's version uses generics. hope fine (since have have of child properties of table of same type (in case, string
):
public class luatable<t> t : class { private bool isvalue; private t value = null; private dictionary<object, luatable<t>> properties = new dictionary<object, luatable<t>>(); public static implicit operator luatable<t>(t val) { if (val luatable<t>) return (luatable<t>)val; return new luatable<t>() { isvalue = true, value = val }; } public static implicit operator t(luatable<t> table) { if (table.isvalue) return table.value; return table; } public luatable<t> this[object property] { { if (isvalue) return null; if (properties.containskey(property)) return properties[property]; luatable<t> table = new luatable<t>(); properties.add(property, table); return table; } set { if (!properties.containskey(property)) properties.add(property, value); else properties[property] = value; } } }
to use it, it's same above. change first line:
var myclassvar = new luatable<string>();
Comments
Post a Comment