public void LuaPushNil() { LuaDLL.lua_pushnil(L); }
/* * Pushes the value of a member or a delegate to call it, depending on the type of * the member. Works with static or instance members. * Uses reflection to find members, and stores the reflected MemberInfo object in * a cache (indexed by the type of the object and the name of the member). */ private int getMember(IntPtr luaState, IReflect objType, object obj, string methodName, BindingFlags bindingType) { bool implicitStatic = false; MemberInfo member = null; object cachedMember = checkMemberCache(memberCache, objType, methodName); //object cachedMember=null; if (cachedMember is LuaCSFunction) { translator.pushFunction(luaState, (LuaCSFunction)cachedMember); translator.push(luaState, true); return(2); } else if (cachedMember != null) { member = (MemberInfo)cachedMember; } else { MemberInfo[] members = objType.GetMember(methodName, bindingType | BindingFlags.Public | BindingFlags.NonPublic); if (members.Length > 0) { member = members[0]; } else { // If we can't find any suitable instance members, try to find them as statics - but we only want to allow implicit static // lookups for fields/properties/events -kevinh members = objType.GetMember(methodName, bindingType | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); if (members.Length > 0) { member = members[0]; implicitStatic = true; } } } if (member != null) { if (member.MemberType == MemberTypes.Field) { FieldInfo field = (FieldInfo)member; if (cachedMember == null) { setMemberCache(memberCache, objType, methodName, member); } try { translator.push(luaState, field.GetValue(obj)); } catch { LuaDLL.lua_pushnil(luaState); } } else if (member.MemberType == MemberTypes.Property) { PropertyInfo property = (PropertyInfo)member; if (cachedMember == null) { setMemberCache(memberCache, objType, methodName, member); } try { object val = property.GetValue(obj, null); translator.push(luaState, val); } catch (ArgumentException) { // If we can't find the getter in our class, recurse up to the base class and see // if they can help. if (objType is Type && !(((Type)objType) == typeof(object))) { return(getMember(luaState, ((Type)objType).BaseType, obj, methodName, bindingType)); } else { LuaDLL.lua_pushnil(luaState); } } catch { LuaDLL.lua_pushnil(luaState); } } else if (member.MemberType == MemberTypes.Event) { EventInfo eventInfo = (EventInfo)member; if (cachedMember == null) { setMemberCache(memberCache, objType, methodName, member); } translator.push(luaState, new RegisterEventHandler(translator.pendingEvents, obj, eventInfo)); } else if (!implicitStatic) { if (member.MemberType == MemberTypes.NestedType) { // kevinh - added support for finding nested types // cache us if (cachedMember == null) { setMemberCache(memberCache, objType, methodName, member); } // Find the name of our class string name = member.Name; Type dectype = member.DeclaringType; // Build a new long name and try to find the type by name string longname = dectype.FullName + "+" + name; Type nestedType = translator.FindType(longname); translator.pushType(luaState, nestedType); } else { // Member type must be 'method' LuaCSFunction wrapper = new LuaCSFunction((new LuaMethodWrapper(translator, objType, methodName, bindingType)).call); if (cachedMember == null) { setMemberCache(memberCache, objType, methodName, wrapper); } translator.pushFunction(luaState, wrapper); translator.push(luaState, true); return(2); } } else { // If we reach this point we found a static method, but can't use it in this context because the user passed in an instance translator.throwError(luaState, "can't pass instance to static method " + methodName); LuaDLL.lua_pushnil(luaState); } } else { // kevinh - we want to throw an exception because meerly returning 'nil' in this case // is not sufficient. valid data members may return nil and therefore there must be some // way to know the member just doesn't exist. translator.throwError(luaState, "unknown member name " + methodName); LuaDLL.lua_pushnil(luaState); } // push false because we are NOT returning a function (see luaIndexFunction) translator.push(luaState, false); return(2); }
/* * Calls the method. Receives the arguments from the Lua stack * and returns values in it. */ public int call(IntPtr luaState) { MethodBase methodToCall = _Method; object targetObject = _Target; bool failedCall = true; int nReturnValues = 0; if (!LuaDLL.lua_checkstack(luaState, 5)) { throw new LuaException("Lua stack overflow"); } bool isStatic = (_BindingType & BindingFlags.Static) == BindingFlags.Static; SetPendingException(null); if (methodToCall == null) // Method from name { if (isStatic) { targetObject = null; } else { targetObject = _ExtractTarget(luaState, 1); } //LuaDLL.lua_remove(luaState,1); // Pops the receiver if (_LastCalledMethod.cachedMethod != null) // Cached? { int numStackToSkip = isStatic ? 0 : 1; // If this is an instance invoe we will have an extra arg on the stack for the targetObject int numArgsPassed = LuaDLL.lua_gettop(luaState) - numStackToSkip; MethodBase method = _LastCalledMethod.cachedMethod; if (numArgsPassed == _LastCalledMethod.argTypes.Length) // No. of args match? { if (!LuaDLL.lua_checkstack(luaState, _LastCalledMethod.outList.Length + 6)) { throw new LuaException("Lua stack overflow"); } object[] args = _LastCalledMethod.args; try { for (int i = 0; i < _LastCalledMethod.argTypes.Length; i++) { MethodArgs type = _LastCalledMethod.argTypes[i]; object luaParamValue = type.extractValue(luaState, i + 1 + numStackToSkip); if (_LastCalledMethod.argTypes[i].isParamsArray) { args[type.index] = _Translator.tableToArray(luaParamValue, type.paramsArrayType); } else { args[type.index] = luaParamValue; } if (args[type.index] == null && !LuaDLL.lua_isnil(luaState, i + 1 + numStackToSkip)) { throw new LuaException("argument number " + (i + 1) + " is invalid"); } } if ((_BindingType & BindingFlags.Static) == BindingFlags.Static) { _Translator.push(luaState, method.Invoke(null, args)); } else { if (_LastCalledMethod.cachedMethod.IsConstructor) { _Translator.push(luaState, ((ConstructorInfo)method).Invoke(args)); } else { _Translator.push(luaState, method.Invoke(targetObject, args)); } } failedCall = false; } catch (TargetInvocationException e) { // Failure of method invocation return(SetPendingException(e.GetBaseException())); } catch (Exception e) { if (_Members.Length == 1) // Is the method overloaded? // No, throw error { return(SetPendingException(e)); } } } } // Cache miss if (failedCall) { // System.Diagnostics.Debug.WriteLine("cache miss on " + methodName); // If we are running an instance variable, we can now pop the targetObject from the stack if (!isStatic) { if (targetObject == null) { _Translator.throwError(luaState, String.Format("instance method '{0}' requires a non null target object", _MethodName)); LuaDLL.lua_pushnil(luaState); return(1); } LuaDLL.lua_remove(luaState, 1); // Pops the receiver } bool hasMatch = false; string candidateName = null; foreach (MemberInfo member in _Members) { candidateName = member.ReflectedType.Name + "." + member.Name; MethodBase m = (MethodInfo)member; bool isMethod = _Translator.matchParameters(luaState, m, ref _LastCalledMethod); if (isMethod) { hasMatch = true; break; } } if (!hasMatch) { string msg = (candidateName == null) ? "invalid arguments to method call" : ("invalid arguments to method: " + candidateName); LuaDLL.luaL_error(luaState, msg); LuaDLL.lua_pushnil(luaState); return(1); } } } else // Method from MethodBase instance { if (methodToCall.ContainsGenericParameters) { // bool isMethod = //* not used _Translator.matchParameters(luaState, methodToCall, ref _LastCalledMethod); if (methodToCall.IsGenericMethodDefinition) { //need to make a concrete type of the generic method definition List <Type> typeArgs = new List <Type>(); foreach (object arg in _LastCalledMethod.args) { typeArgs.Add(arg.GetType()); } MethodInfo concreteMethod = (methodToCall as MethodInfo).MakeGenericMethod(typeArgs.ToArray()); _Translator.push(luaState, concreteMethod.Invoke(targetObject, _LastCalledMethod.args)); failedCall = false; } else if (methodToCall.ContainsGenericParameters) { LuaDLL.luaL_error(luaState, "unable to invoke method on generic class as the current method is an open generic method"); LuaDLL.lua_pushnil(luaState); return(1); } } else { if (!methodToCall.IsStatic && !methodToCall.IsConstructor && targetObject == null) { targetObject = _ExtractTarget(luaState, 1); LuaDLL.lua_remove(luaState, 1); // Pops the receiver } if (!_Translator.matchParameters(luaState, methodToCall, ref _LastCalledMethod)) { LuaDLL.luaL_error(luaState, "invalid arguments to method call"); LuaDLL.lua_pushnil(luaState); return(1); } } } if (failedCall) { if (!LuaDLL.lua_checkstack(luaState, _LastCalledMethod.outList.Length + 6)) { throw new LuaException("Lua stack overflow"); } try { if (isStatic) { _Translator.push(luaState, _LastCalledMethod.cachedMethod.Invoke(null, _LastCalledMethod.args)); } else { if (_LastCalledMethod.cachedMethod.IsConstructor) { _Translator.push(luaState, ((ConstructorInfo)_LastCalledMethod.cachedMethod).Invoke(_LastCalledMethod.args)); } else { _Translator.push(luaState, _LastCalledMethod.cachedMethod.Invoke(targetObject, _LastCalledMethod.args)); } } } catch (TargetInvocationException e) { return(SetPendingException(e.GetBaseException())); } catch (Exception e) { return(SetPendingException(e)); } } // Pushes out and ref return values for (int index = 0; index < _LastCalledMethod.outList.Length; index++) { nReturnValues++; _Translator.push(luaState, _LastCalledMethod.args[_LastCalledMethod.outList[index]]); } //by isSingle 2010-09-10 11:26:31 //Desc: // if not return void,we need add 1, // or we will lost the function's return value // when call dotnet function like "int foo(arg1,out arg2,out arg3)" in lua code if (!_LastCalledMethod.IsReturnVoid && nReturnValues > 0) { nReturnValues++; } return(nReturnValues < 1 ? 1 : nReturnValues); }
/*static void PushNull(IntPtr L) * { * LuaDLL.tolua_pushudata(L, 1); * }*/ //PushVarObject public static void Push(IntPtr L, object obj) { if (obj == null) { LuaDLL.lua_pushnil(L); return; } Type t = obj.GetType(); if (t.IsValueType) { if (t == typeof(bool)) { bool b = (bool)obj; LuaDLL.lua_pushboolean(L, b); } else if (t.IsEnum) { Push(L, (System.Enum)obj); } else if (t.IsPrimitive) { double d = LuaMisc.ToDouble(obj); LuaDLL.lua_pushnumber(L, d); } else if (t == typeof(Vector3)) { Push(L, (Vector3)obj); } else if (t == typeof(Quaternion)) { Push(L, (Quaternion)obj); } else if (t == typeof(Vector2)) { Push(L, (Vector2)obj); } else if (t == typeof(Vector4)) { Push(L, (Vector4)obj); } else if (t == typeof(Color)) { Push(L, (Color)obj); } else if (t == typeof(RaycastHit)) { Push(L, (RaycastHit)obj); } else if (t == typeof(Touch)) { Push(L, (Touch)obj); } else if (t == typeof(Ray)) { Push(L, (Ray)obj); } else if (t == typeof(Bounds)) { Push(L, (Bounds)obj); } else if (t == typeof(LayerMask)) { Push(L, (LayerMask)obj); } else { PushValue(L, (ValueType)obj); } } else { if (t.IsArray) { Push(L, (Array)obj); } else if (t == typeof(string)) { LuaDLL.lua_pushstring(L, (string)obj); } else if (t.IsSubclassOf(typeof(LuaBaseRef))) { Push(L, (LuaBaseRef)obj); } else if (t.IsSubclassOf(typeof(UnityEngine.Object))) { Push(L, (UnityEngine.Object)obj); } else if (t.IsSubclassOf(typeof(UnityEngine.TrackedReference))) { Push(L, (UnityEngine.TrackedReference)obj); } else if (t == typeof(LuaByteBuffer)) { LuaByteBuffer lbb = (LuaByteBuffer)obj; LuaDLL.lua_pushlstring(L, lbb.buffer, lbb.buffer.Length); } else if (t.IsSubclassOf(typeof(Delegate))) { Push(L, (Delegate)obj); } else if (obj is System.Collections.IEnumerator) { Push(L, (IEnumerator)obj); } else if (t == typeof(EventObject)) { Push(L, (EventObject)obj); } else if (t == monoType) { Push(L, (Type)obj); } else { PushObject(L, obj); } } }
/* * Called by the __index metafunction of CLR objects in case the * method is not cached or it is a field/property/event. * Receives the object and the member name as arguments and returns * either the value of the member or a delegate to call it. * If the member does not exist returns nil. */ private int getMethod(IntPtr luaState) { object obj = translator.getRawNetObject(luaState, 1); if (obj == null) { translator.throwError(luaState, "trying to index an invalid object reference"); LuaDLL.lua_pushnil(luaState); return(1); } object index = translator.getObject(luaState, 2); Type indexType = index.GetType(); string methodName = index as string; // will be null if not a string arg Type objType = obj.GetType(); // Handle the most common case, looking up the method by name if (methodName != null && isMemberPresent(objType, methodName)) { return(getMember(luaState, objType, obj, methodName, BindingFlags.Instance)); } // Try to access by array if the type is right and index is an int (lua numbers always come across as double) if (obj is Array && index is double) { object[] arr = (object[])obj; translator.push(luaState, arr[(int)((double)index)]); } else { // Try to use get_Item to index into this .net object Type[] argTypes = new Type[1]; argTypes[0] = indexType; MethodInfo getter = objType.GetMethod("get_Item", argTypes); if (index is double) { // For numbers we always prefer to pass ints into our accessor if possible (if the accessor // is really built for doubles it should cast back correctly double d = (double)index; if (d == Math.Round(d)) { bool convertToInt = true; // If we already found a getter, it might be a version expecting an 'object' parameter // in that case we'll want to convert to an int if (getter != null) { ParameterInfo[] actualParms = getter.GetParameters(); convertToInt = actualParms[0].ParameterType != typeof(double); } if (convertToInt) { index = (int)d; // convert the index to a true (but boxed) int } } // If we can't find a double based indexer, fall back to an int based index if (getter == null && index is int) { argTypes[0] = typeof(int); getter = objType.GetMethod("get_Item", argTypes); } } if (getter == null) { translator.throwError(luaState, "method not found (or no indexer): " + index); LuaDLL.lua_pushnil(luaState); } object[] args = new object[1]; // Just call the indexer - if out of bounds an exception will happen args[0] = index; try { object result = getter.Invoke(obj, args); translator.push(luaState, result); } catch (Exception e) { translator.throwError(luaState, "exception while indexing: " + e); LuaDLL.lua_pushnil(luaState); } } LuaDLL.lua_pushboolean(luaState, false); return(2); }
/* * Calls the method. Receives the arguments from the Lua stack * and returns values in it. */ public int call(IntPtr luaState) { MethodBase methodToCall = method; object targetObject = target; bool failedCall = true; int nReturnValues = 0; if (!LuaDLL.lua_checkstack(luaState, 5)) { throw new LuaException("Lua stack overflow"); } bool isStatic = (bindingType & BindingFlags.Static) == BindingFlags.Static; SetPendingException(null); if (methodToCall == null) // Method from name { if (isStatic) { targetObject = null; } else { targetObject = extractTarget(luaState, 1); } //LuaDLL.lua_remove(luaState,1); // Pops the receiver if (lastCalledMethod.cachedMethod != null) // Cached? { int numStackToSkip = isStatic ? 0 : 1; // If this is an instance invoe we will have an extra arg on the stack for the targetObject int numArgsPassed = LuaDLL.lua_gettop(luaState) - numStackToSkip; if (numArgsPassed == lastCalledMethod.argTypes.Length) // No. of args match? { if (!LuaDLL.lua_checkstack(luaState, lastCalledMethod.outList.Length + 6)) { throw new LuaException("Lua stack overflow"); } try { for (int i = 0; i < lastCalledMethod.argTypes.Length; i++) { lastCalledMethod.args[lastCalledMethod.argTypes[i].index] = lastCalledMethod.argTypes[i].extractValue(luaState, i + 1 + numStackToSkip); if (lastCalledMethod.args[lastCalledMethod.argTypes[i].index] == null && !LuaDLL.lua_isnil(luaState, i + 1 + numStackToSkip)) { throw new LuaException("argument number " + (i + 1) + " is invalid"); } } if ((bindingType & BindingFlags.Static) == BindingFlags.Static) { translator.push(luaState, lastCalledMethod.cachedMethod.Invoke(null, lastCalledMethod.args)); } else { if (lastCalledMethod.cachedMethod.IsConstructor) { translator.push(luaState, ((ConstructorInfo)lastCalledMethod.cachedMethod).Invoke(lastCalledMethod.args)); } else { translator.push(luaState, lastCalledMethod.cachedMethod.Invoke(targetObject, lastCalledMethod.args)); } } failedCall = false; } catch (TargetInvocationException e) { // Failure of method invocation return(SetPendingException(e.GetBaseException())); } catch (Exception e) { if (members.Length == 1) // Is the method overloaded? // No, throw error { return(SetPendingException(e)); } } } } // Cache miss if (failedCall) { // System.Diagnostics.Debug.WriteLine("cache miss on " + methodName); // If we are running an instance variable, we can now pop the targetObject from the stack if (!isStatic) { if (targetObject == null) { translator.throwError(luaState, String.Format("instance method '{0}' requires a non null target object", methodName)); LuaDLL.lua_pushnil(luaState); return(1); } LuaDLL.lua_remove(luaState, 1); // Pops the receiver } bool hasMatch = false; string candidateName = null; foreach (MemberInfo member in members) { candidateName = member.ReflectedType.Name + "." + member.Name; MethodBase m = (MethodInfo)member; bool isMethod = translator.matchParameters(luaState, m, ref lastCalledMethod); if (isMethod) { hasMatch = true; break; } } if (!hasMatch) { string msg = (candidateName == null) ? "invalid arguments to method call" : ("invalid arguments to method: " + candidateName); translator.throwError(luaState, msg); LuaDLL.lua_pushnil(luaState); return(1); } } } else // Method from MethodBase instance { if (!methodToCall.IsStatic && !methodToCall.IsConstructor && targetObject == null) { targetObject = extractTarget(luaState, 1); LuaDLL.lua_remove(luaState, 1); // Pops the receiver } if (!translator.matchParameters(luaState, methodToCall, ref lastCalledMethod)) { translator.throwError(luaState, "invalid arguments to method call"); LuaDLL.lua_pushnil(luaState); return(1); } } if (failedCall) { if (!LuaDLL.lua_checkstack(luaState, lastCalledMethod.outList.Length + 6)) { throw new LuaException("Lua stack overflow"); } try { if (isStatic) { translator.push(luaState, lastCalledMethod.cachedMethod.Invoke(null, lastCalledMethod.args)); } else { if (lastCalledMethod.cachedMethod.IsConstructor) { translator.push(luaState, ((ConstructorInfo)lastCalledMethod.cachedMethod).Invoke(lastCalledMethod.args)); } else { translator.push(luaState, lastCalledMethod.cachedMethod.Invoke(targetObject, lastCalledMethod.args)); } } } catch (TargetInvocationException e) { return(SetPendingException(e.GetBaseException())); } catch (Exception e) { return(SetPendingException(e)); } } // Pushes out and ref return values for (int index = 0; index < lastCalledMethod.outList.Length; index++) { nReturnValues++; //for(int i=0;i<lastCalledMethod.outList.Length;i++) translator.push(luaState, lastCalledMethod.args[lastCalledMethod.outList[index]]); } return(nReturnValues < 1 ? 1 : nReturnValues); }
public int pushError(IntPtr luaState, string msg) { LuaDLL.lua_pushnil(luaState); LuaDLL.lua_pushstring(luaState, msg); return(2); }
/* * Called by the __index metafunction of CLR objects in case the * method is not cached or it is a field/property/event. * Receives the object and the member name as arguments and returns * either the value of the member or a delegate to call it. * If the member does not exist returns nil. */ private int getMethod(IntPtr luaState) { object obj = translator.getRawNetObject(luaState, 1); if (obj == null) { translator.throwError(luaState, "trying to index an invalid object reference"); LuaDLL.lua_pushnil(luaState); return(1); } object index = translator.getObject(luaState, 2); Type indexType = index.GetType(); string methodName = index as string; // will be null if not a string arg Type objType = obj.GetType(); // Handle the most common case, looking up the method by name if (methodName != null && isMemberPresent(objType, methodName)) { return(getMember(luaState, objType, obj, methodName, BindingFlags.Instance)); } // Try to access by array if the type is right and index is an int (lua numbers always come across as double) if (objType.IsArray && index is double) { object[] arr = (object[])obj; translator.push(luaState, arr[(int)((double)index)]); } else { // Try to use get_Item to index into this .net object MethodInfo getter = objType.GetMethod("get_Item"); ParameterInfo[] actualParms = (getter != null) ? getter.GetParameters() : null; if (actualParms == null || actualParms.Length != 1) { translator.throwError(luaState, "method not found (or no indexer): " + index); LuaDLL.lua_pushnil(luaState); } else { // Get the index in a form acceptable to the getter index = translator.getAsType(luaState, 2, actualParms[0].ParameterType); object[] args = new object[1]; // Just call the indexer - if out of bounds an exception will happen args[0] = index; try { object result = getter.Invoke(obj, args); translator.push(luaState, result); } catch (TargetInvocationException e) { // Provide a more readable description for the common case of key not found if (e.InnerException is KeyNotFoundException) { translator.throwError(luaState, "key '" + index + "' not found "); } else { translator.throwError(luaState, "exception indexing '" + index + "' " + e.Message); } LuaDLL.lua_pushnil(luaState); } } } LuaDLL.lua_pushboolean(luaState, false); return(2); }
public static int getMethod(IntPtr luaState) { ObjectTranslator translator = ObjectTranslator.FromState(luaState); object obj = translator.getRawNetObject(luaState, 1); if (obj == null) { translator.throwError(luaState, "trying to index an invalid object reference"); LuaDLL.lua_pushnil(luaState); return(1); } object index = translator.getObject(luaState, 2); //Type indexType = index.GetType(); //* not used string methodName = index as string; // will be null if not a string arg Type objType = obj.GetType(); // Handle the most common case, looking up the method by name. // CP: This will fail when using indexers and attempting to get a value with the same name as a property of the object, // ie: xmlelement['item'] <- item is a property of xmlelement try { if (methodName != null && translator.metaFunctions.isMemberPresent(objType, methodName)) { return(translator.metaFunctions.getMember(luaState, objType, obj, methodName, BindingFlags.Instance | BindingFlags.IgnoreCase)); } } catch { } bool failed = true; // Try to access by array if the type is right and index is an int (lua numbers always come across as double) if (objType.IsArray && index is double) { int intIndex = (int)((double)index); Array aa = obj as Array; if (intIndex >= aa.Length) { return(translator.pushError(luaState, "array index out of bounds: " + intIndex + " " + aa.Length)); } object val = aa.GetValue(intIndex); translator.push(luaState, val); failed = false; } else { // Try to use get_Item to index into this .net object //MethodInfo getter = objType.GetMethod("get_Item"); // issue here is that there may be multiple indexers.. MethodInfo[] methods = objType.GetMethods(); foreach (MethodInfo mInfo in methods) { if (mInfo.Name == "get_Item") { //check if the signature matches the input if (mInfo.GetParameters().Length == 1) { MethodInfo getter = mInfo; ParameterInfo[] actualParms = (getter != null) ? getter.GetParameters() : null; if (actualParms == null || actualParms.Length != 1) { return(translator.pushError(luaState, "method not found (or no indexer): " + index)); } else { // Get the index in a form acceptable to the getter index = translator.getAsType(luaState, 2, actualParms[0].ParameterType); // Just call the indexer - if out of bounds an exception will happen try { object result = getter.Invoke(obj, new object[] { index }); translator.push(luaState, result); failed = false; } catch (TargetInvocationException e) { // Provide a more readable description for the common case of key not found if (e.InnerException is KeyNotFoundException) { return(translator.pushError(luaState, "key '" + index + "' not found ")); } else { return(translator.pushError(luaState, "exception indexing '" + index + "' " + e.Message)); } } } } } } } if (failed) { return(translator.pushError(luaState, "cannot find " + index)); } LuaDLL.lua_pushboolean(luaState, false); return(2); }
private int getMember(IntPtr luaState, IReflect objType, object obj, string methodName, BindingFlags bindingType) { bool flag = false; MemberInfo memberInfo = null; object obj2 = this.checkMemberCache(this.memberCache, objType, methodName); if (obj2 is LuaCSFunction) { this.translator.pushFunction(luaState, (LuaCSFunction)obj2); this.translator.push(luaState, true); return(2); } if (obj2 != null) { memberInfo = (MemberInfo)obj2; } else { MemberInfo[] member = objType.GetMember(methodName, bindingType | BindingFlags.Public | BindingFlags.IgnoreCase); if (member.Length > 0) { memberInfo = member[0]; } else { member = objType.GetMember(methodName, bindingType | BindingFlags.Static | BindingFlags.Public | BindingFlags.IgnoreCase); if (member.Length > 0) { memberInfo = member[0]; flag = true; } } } if (memberInfo != null) { if (memberInfo.MemberType == MemberTypes.Field) { FieldInfo fieldInfo = (FieldInfo)memberInfo; if (obj2 == null) { this.setMemberCache(this.memberCache, objType, methodName, memberInfo); } try { this.translator.push(luaState, fieldInfo.GetValue(obj)); } catch { LuaDLL.lua_pushnil(luaState); } } else if (memberInfo.MemberType == MemberTypes.Property) { PropertyInfo propertyInfo = (PropertyInfo)memberInfo; if (obj2 == null) { this.setMemberCache(this.memberCache, objType, methodName, memberInfo); } try { object o = propertyInfo.GetGetMethod().Invoke(obj, null); this.translator.push(luaState, o); } catch (ArgumentException) { if (objType is Type && (Type)objType != typeof(object)) { return(this.getMember(luaState, ((Type)objType).BaseType, obj, methodName, bindingType)); } LuaDLL.lua_pushnil(luaState); } catch (TargetInvocationException e) { this.ThrowError(luaState, e); LuaDLL.lua_pushnil(luaState); } } else if (memberInfo.MemberType == MemberTypes.Event) { EventInfo eventInfo = (EventInfo)memberInfo; if (obj2 == null) { this.setMemberCache(this.memberCache, objType, methodName, memberInfo); } this.translator.push(luaState, new RegisterEventHandler(this.translator.pendingEvents, obj, eventInfo)); } else if (!flag) { if (memberInfo.MemberType != MemberTypes.NestedType) { LuaCSFunction luaCSFunction = new LuaCSFunction(new LuaMethodWrapper(this.translator, objType, methodName, bindingType).call); if (obj2 == null) { this.setMemberCache(this.memberCache, objType, methodName, luaCSFunction); } this.translator.pushFunction(luaState, luaCSFunction); this.translator.push(luaState, true); return(2); } if (obj2 == null) { this.setMemberCache(this.memberCache, objType, methodName, memberInfo); } string name = memberInfo.Name; Type declaringType = memberInfo.DeclaringType; string className = declaringType.FullName + "+" + name; Type t = this.translator.FindType(className); this.translator.pushType(luaState, t); } else { this.translator.throwError(luaState, "can't pass instance to static method " + methodName); LuaDLL.lua_pushnil(luaState); } } else { this.translator.throwError(luaState, "unknown member name " + methodName); LuaDLL.lua_pushnil(luaState); } this.translator.push(luaState, false); return(2); }
public static int getMethod(IntPtr luaState) { ObjectTranslator objectTranslator = ObjectTranslator.FromState(luaState); object rawNetObject = objectTranslator.getRawNetObject(luaState, 1); if (rawNetObject == null) { objectTranslator.throwError(luaState, "trying to index an invalid object reference"); LuaDLL.lua_pushnil(luaState); return(1); } object obj = objectTranslator.getObject(luaState, 2); string text = obj as string; Type type = rawNetObject.GetType(); try { if (text != null && objectTranslator.metaFunctions.isMemberPresent(type, text)) { int result = objectTranslator.metaFunctions.getMember(luaState, type, rawNetObject, text, BindingFlags.IgnoreCase | BindingFlags.Instance); return(result); } } catch { } bool flag = true; if (type.IsArray && obj is double) { int num = (int)((double)obj); Array array = rawNetObject as Array; if (num >= array.Length) { return(objectTranslator.pushError(luaState, string.Concat(new object[] { "array index out of bounds: ", num, " ", array.Length }))); } object value = array.GetValue(num); objectTranslator.push(luaState, value); flag = false; } else { MethodInfo[] methods = type.GetMethods(); MethodInfo[] array2 = methods; for (int i = 0; i < array2.Length; i++) { MethodInfo methodInfo = array2[i]; if (methodInfo.Name == "get_Item" && methodInfo.GetParameters().Length == 1) { MethodInfo methodInfo2 = methodInfo; ParameterInfo[] array3 = (methodInfo2 == null) ? null : methodInfo2.GetParameters(); if (array3 == null || array3.Length != 1) { return(objectTranslator.pushError(luaState, "method not found (or no indexer): " + obj)); } obj = objectTranslator.getAsType(luaState, 2, array3[0].ParameterType); try { object o = methodInfo2.Invoke(rawNetObject, new object[] { obj }); objectTranslator.push(luaState, o); flag = false; } catch (TargetInvocationException ex) { int result; if (ex.InnerException is KeyNotFoundException) { result = objectTranslator.pushError(luaState, "key '" + obj + "' not found "); return(result); } result = objectTranslator.pushError(luaState, string.Concat(new object[] { "exception indexing '", obj, "' ", ex.Message })); return(result); } } } } if (flag) { return(objectTranslator.pushError(luaState, "cannot find " + obj)); } LuaDLL.lua_pushboolean(luaState, false); return(2); }
/* * Called by the __index metafunction of CLR objects in case the * method is not cached or it is a field/property/event. * Receives the object and the member name as arguments and returns * either the value of the member or a delegate to call it. * If the member does not exist returns nil. */ private int getMethod(IntPtr luaState) { object obj = translator.getRawNetObject(luaState, 1); if (obj == null) { translator.throwError(luaState, "trying to index an invalid object reference"); LuaDLL.lua_pushnil(luaState); return(1); } object index = translator.GetStackObject(luaState, 2); Type indexType = index.GetType(); string methodName = index as string; // will be null if not a string arg Type objType = obj.GetType(); // Handle the most common case, looking up the method by name. // CP: This will fail when using indexers and attempting to get a value with the same name as a property of the object, // ie: xmlelement['item'] <- item is a property of xmlelement try { if (methodName != null && isMemberPresent(objType, methodName)) { return(getMember(luaState, objType, obj, methodName, BindingFlags.Instance | BindingFlags.IgnoreCase)); } } catch { } // Try to access by array if the type is right and index is an int (lua numbers always come across as double) if (objType.IsArray && index is double) { int intIndex = (int)((double)index); if (objType.UnderlyingSystemType == typeof(float[])) { float[] arr = ((float[])obj); translator.push(luaState, arr[intIndex]); } else if (objType.UnderlyingSystemType == typeof(double[])) { double[] arr = ((double[])obj); translator.push(luaState, arr[intIndex]); } else if (objType.UnderlyingSystemType == typeof(int[])) { int[] arr = ((int[])obj); translator.push(luaState, arr[intIndex]); } else { object[] arr = (object[])obj; translator.push(luaState, arr[intIndex]); } } else { // Try to use get_Item to index into this .net object //MethodInfo getter = objType.GetMethod("get_Item"); MethodInfo[] methods = objType.GetMethods(); foreach (MethodInfo mInfo in methods) { if (mInfo.Name == "get_Item") { //check if the signature matches the input if (mInfo.GetParameters().Length == 1) { MethodInfo getter = mInfo; ParameterInfo[] actualParms = (getter != null) ? getter.GetParameters() : null; if (actualParms == null || actualParms.Length != 1) { translator.throwError(luaState, "method not found (or no indexer): " + index); LuaDLL.lua_pushnil(luaState); } else { // Get the index in a form acceptable to the getter index = translator.getAsType(luaState, 2, actualParms[0].ParameterType); object[] args = new object[1]; // Just call the indexer - if out of bounds an exception will happen args[0] = index; try { object result = getter.Invoke(obj, args); translator.push(luaState, result); } catch (TargetInvocationException e) { // Provide a more readable description for the common case of key not found if (e.InnerException is KeyNotFoundException) { translator.throwError(luaState, "key '" + index + "' not found "); } else { translator.throwError(luaState, "exception indexing '" + index + "' " + e.Message); } LuaDLL.lua_pushnil(luaState); } } } } } } LuaDLL.lua_pushboolean(luaState, false); return(2); }
public int call(IntPtr luaState) { MethodBase method = this._Method; object obj = this._Target; bool flag = true; int num = 0; if (!LuaDLL.lua_checkstack(luaState, 5)) { throw new LuaException("Lua stack overflow"); } bool flag2 = (this._BindingType & BindingFlags.Static) == BindingFlags.Static; this.SetPendingException(null); if (method == null) { if (flag2) { obj = null; } else { obj = this._ExtractTarget(luaState, 1); } if (this._LastCalledMethod.cachedMethod != null) { int num2 = (!flag2) ? 1 : 0; int num3 = LuaDLL.lua_gettop(luaState) - num2; MethodBase cachedMethod = this._LastCalledMethod.cachedMethod; if (num3 == this._LastCalledMethod.argTypes.Length) { if (!LuaDLL.lua_checkstack(luaState, this._LastCalledMethod.outList.Length + 6)) { throw new LuaException("Lua stack overflow"); } object[] args = this._LastCalledMethod.args; try { for (int i = 0; i < this._LastCalledMethod.argTypes.Length; i++) { MethodArgs methodArgs = this._LastCalledMethod.argTypes[i]; object obj2 = methodArgs.extractValue(luaState, i + 1 + num2); if (this._LastCalledMethod.argTypes[i].isParamsArray) { args[methodArgs.index] = this._Translator.tableToArray(obj2, methodArgs.paramsArrayType); } else { args[methodArgs.index] = obj2; } if (args[methodArgs.index] == null && !LuaDLL.lua_isnil(luaState, i + 1 + num2)) { throw new LuaException("argument number " + (i + 1) + " is invalid"); } } if ((this._BindingType & BindingFlags.Static) == BindingFlags.Static) { this._Translator.push(luaState, cachedMethod.Invoke(null, args)); } else if (this._LastCalledMethod.cachedMethod.IsConstructor) { this._Translator.push(luaState, ((ConstructorInfo)cachedMethod).Invoke(args)); } else { this._Translator.push(luaState, cachedMethod.Invoke(obj, args)); } flag = false; } catch (TargetInvocationException ex) { int result = this.SetPendingException(ex.GetBaseException()); return(result); } catch (Exception pendingException) { if (this._Members.Length == 1) { int result = this.SetPendingException(pendingException); return(result); } } } } if (flag) { if (!flag2) { if (obj == null) { this._Translator.throwError(luaState, string.Format("instance method '{0}' requires a non null target object", this._MethodName)); LuaDLL.lua_pushnil(luaState); return(1); } LuaDLL.lua_remove(luaState, 1); } bool flag3 = false; string text = null; MemberInfo[] members = this._Members; for (int j = 0; j < members.Length; j++) { MemberInfo memberInfo = members[j]; text = memberInfo.ReflectedType.Name + "." + memberInfo.Name; MethodBase method2 = (MethodInfo)memberInfo; bool flag4 = this._Translator.matchParameters(luaState, method2, ref this._LastCalledMethod); if (flag4) { flag3 = true; break; } } if (!flag3) { string message = (text != null) ? ("invalid arguments to method: " + text) : "invalid arguments to method call"; LuaDLL.luaL_error(luaState, message); LuaDLL.lua_pushnil(luaState); this.ClearCachedArgs(); return(1); } } } else if (method.ContainsGenericParameters) { this._Translator.matchParameters(luaState, method, ref this._LastCalledMethod); if (method.IsGenericMethodDefinition) { List <Type> list = new List <Type>(); object[] args2 = this._LastCalledMethod.args; for (int k = 0; k < args2.Length; k++) { object obj3 = args2[k]; list.Add(obj3.GetType()); } MethodInfo methodInfo = (method as MethodInfo).MakeGenericMethod(list.ToArray()); this._Translator.push(luaState, methodInfo.Invoke(obj, this._LastCalledMethod.args)); flag = false; } else if (method.ContainsGenericParameters) { LuaDLL.luaL_error(luaState, "unable to invoke method on generic class as the current method is an open generic method"); LuaDLL.lua_pushnil(luaState); this.ClearCachedArgs(); return(1); } } else { if (!method.IsStatic && !method.IsConstructor && obj == null) { obj = this._ExtractTarget(luaState, 1); LuaDLL.lua_remove(luaState, 1); } if (!this._Translator.matchParameters(luaState, method, ref this._LastCalledMethod)) { LuaDLL.luaL_error(luaState, "invalid arguments to method call"); LuaDLL.lua_pushnil(luaState); this.ClearCachedArgs(); return(1); } } if (flag) { if (!LuaDLL.lua_checkstack(luaState, this._LastCalledMethod.outList.Length + 6)) { this.ClearCachedArgs(); throw new LuaException("Lua stack overflow"); } try { if (flag2) { this._Translator.push(luaState, this._LastCalledMethod.cachedMethod.Invoke(null, this._LastCalledMethod.args)); } else if (this._LastCalledMethod.cachedMethod.IsConstructor) { this._Translator.push(luaState, ((ConstructorInfo)this._LastCalledMethod.cachedMethod).Invoke(this._LastCalledMethod.args)); } else { this._Translator.push(luaState, this._LastCalledMethod.cachedMethod.Invoke(obj, this._LastCalledMethod.args)); } } catch (TargetInvocationException ex2) { this.ClearCachedArgs(); int result = this.SetPendingException(ex2.GetBaseException()); return(result); } catch (Exception pendingException2) { this.ClearCachedArgs(); int result = this.SetPendingException(pendingException2); return(result); } } for (int l = 0; l < this._LastCalledMethod.outList.Length; l++) { num++; this._Translator.push(luaState, this._LastCalledMethod.args[this._LastCalledMethod.outList[l]]); } if (!this._LastCalledMethod.IsReturnVoid && num > 0) { num++; } this.ClearCachedArgs(); return((num >= 1) ? num : 1); }
public static void Push(IntPtr L, object obj) { if (obj == null) { LuaDLL.lua_pushnil(L); return; } Type type = obj.GetType(); if (type.get_IsValueType()) { if (type == typeof(bool)) { bool value = (bool)obj; LuaDLL.lua_pushboolean(L, value); } else if (type.get_IsEnum()) { ToLua.Push(L, (Enum)obj); } else if (type.get_IsPrimitive()) { double number = LuaMisc.ToDouble(obj); LuaDLL.lua_pushnumber(L, number); } else if (type == typeof(Vector3)) { ToLua.Push(L, (Vector3)obj); } else if (type == typeof(Quaternion)) { ToLua.Push(L, (Quaternion)obj); } else if (type == typeof(Vector2)) { ToLua.Push(L, (Vector2)obj); } else if (type == typeof(Vector4)) { ToLua.Push(L, (Vector4)obj); } else if (type == typeof(Color)) { ToLua.Push(L, (Color)obj); } else if (type == typeof(RaycastHit)) { ToLua.Push(L, (RaycastHit)obj); } else if (type == typeof(Touch)) { ToLua.Push(L, (Touch)obj); } else if (type == typeof(Ray)) { ToLua.Push(L, (Ray)obj); } else if (type == typeof(Bounds)) { ToLua.Push(L, (Bounds)obj); } else if (type == typeof(LayerMask)) { ToLua.PushLayerMask(L, (LayerMask)obj); } else { ToLua.PushValue(L, (ValueType)obj); } } else if (type.get_IsArray()) { ToLua.Push(L, (Array)obj); } else if (type == typeof(string)) { LuaDLL.lua_pushstring(L, (string)obj); } else if (type.IsSubclassOf(typeof(LuaBaseRef))) { ToLua.Push(L, (LuaBaseRef)obj); } else if (type.IsSubclassOf(typeof(Object))) { ToLua.Push(L, (Object)obj); } else if (type.IsSubclassOf(typeof(TrackedReference))) { ToLua.Push(L, (TrackedReference)obj); } else if (type == typeof(LuaByteBuffer)) { LuaByteBuffer luaByteBuffer = (LuaByteBuffer)obj; LuaDLL.lua_pushlstring(L, luaByteBuffer.buffer, luaByteBuffer.buffer.Length); } else if (type.IsSubclassOf(typeof(Delegate))) { ToLua.Push(L, (Delegate)obj); } else if (obj is IEnumerator) { ToLua.Push(L, (IEnumerator)obj); } else if (type == typeof(EventObject)) { ToLua.Push(L, (EventObject)obj); } else if (type == ToLua.monoType) { ToLua.Push(L, (Type)obj); } else { ToLua.PushObject(L, obj); } }