/// <summary> /// Registers methods with [LuaBind] attributes in Lua. /// </summary> private void RegisterLuaMethods(object obj) { const BindingFlags flags = BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; foreach (var method in obj.GetType().GetMethods(flags)) { var attr = method.GetCustomAttributes(typeof(BindLuaAttribute), inherit: false).FirstOrDefault() as BindLuaAttribute; if (attr == null) { continue; } var wrapper = new LuaRuntime.MethodWrapper(this, method); var fn = luaRuntime.CreateFunctionFromMethodWrapper(wrapper); var name = string.IsNullOrEmpty(attr.Name) ? method.Name : attr.Name; luaRuntime.Globals[name] = fn; } }
public LuaValue this [LuaRuntime runtime, LuaValue keyValue] { get { var members = GetMembers(keyValue); if (members.Count == 1) { var method = members [0] as MethodInfo; if (method != null) { return(runtime.CreateFunctionFromMethodWrapper(new LuaRuntime.MethodWrapper(type, method, @static: true))); } var property = members [0] as PropertyInfo; if (property != null) { var getter = property.GetGetMethod(); if (getter == null) { throw new LuaException("Property is write-only."); } if (getter.GetParameters().Length != 0) { throw new LuaException("Cannot get an indexer."); } var ret = property.GetValue(type, null); return(clrObject.Binder.ObjectToLuaValue(ret, clrObject, runtime)); } var field = members [0] as FieldInfo; if (field != null) { return(clrObject.Binder.ObjectToLuaValue(field.GetValue(type), clrObject, runtime)); } } return(LuaNil.Instance); } set { var members = GetMembers(keyValue); if (members.Count == 1) { var property = members [0] as PropertyInfo; if (property != null) { var setter = property.GetSetMethod(); if (setter == null) { throw new LuaException("Property is read-only."); } if (setter.GetParameters().Length != 1) { throw new LuaException("Cannot set an indexer."); } object v; try { v = value.ToClrType(property.PropertyType); } catch { throw new LuaException("Value is incompatible with this property."); } property.SetValue(null, v, null); return; } var field = members [0] as FieldInfo; if (field != null) { object v; try { v = value.ToClrType(field.FieldType); } catch { throw new LuaException("Value is incompatible with this property."); } field.SetValue(null, v); return; } } throw new LuaException("Property/field not found: " + keyValue.ToString()); } }