/// <summary>[-0, +2, e] /// 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. /// </summary> int getMethod(lua.State L) { Debug.Assert(interpreter.IsSameLua(L) && luanet.infunction(L)); object obj = luaclr.checkref(L, 1); object index = translator.getObject(L, 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 if (methodName != null && isMemberPresent(objType, methodName)) { return(getMember(L, objType, obj, methodName, BindingFlags.Instance)); } 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) { object val; try { val = ((Array)obj).GetValue((int)(double)index); } catch (Exception ex) { return(translator.throwError(L, ex)); } translator.push(L, val); failed = false; } else { try { // 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.. foreach (MethodInfo mInfo in objType.GetMethods()) { if (mInfo.Name == "get_Item") { ParameterInfo[] actualParms = mInfo.GetParameters(); if (actualParms.Length != 1) //check if the signature matches the input { continue; } if (!translator.memberIsAllowed(mInfo)) { continue; } // Get the index in a form acceptable to the getter index = translator.getAsType(L, 2, actualParms[0].ParameterType); // Just call the indexer - if out of bounds an exception will happen object o = mInfo.Invoke(obj, new[] { index }); failed = false; translator.push(L, o); break; } } } catch (TargetInvocationException ex) { return(translator.throwError(L, luaclr.verifyex(ex.InnerException))); } catch (LuaInternalException) { throw; } catch (Exception ex) { return(luaL.error(L, "unable to index {0}: {1}", objType, ex.Message)); } } if (failed) { return(luaL.error(L, "cannot find " + index)); } lua.pushboolean(L, false); return(2); }
/// <summary>Calls the method. Receives the arguments from the Lua stack and returns values in it.</summary> public int call(lua.State L) { using (luanet.entercfunction(L, _Translator.interpreter)) { MethodBase methodToCall = _Method; object targetObject = _Target; bool failedCall = true; int nReturnValues = 0; luaL.checkstack(L, 5, "MethodWrapper.call"); bool isStatic = (_BindingType & BindingFlags.Static) == BindingFlags.Static; if (methodToCall == null) // Method from name { targetObject = isStatic ? null : _ExtractTarget(L, 1); //lua.remove(L,1); // Pops the receiver if (_LastCalledMethod.cachedMethod != null && _Translator.memberIsAllowed(_LastCalledMethod.cachedMethod)) // 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 = lua.gettop(L) - numStackToSkip; MethodBase method = _LastCalledMethod.cachedMethod; if (numArgsPassed == _LastCalledMethod.argTypes.Length) // No. of args match? { luaL.checkstack(L, _LastCalledMethod.outList.Length + 6, "MethodWrapper.call"); object[] args = _LastCalledMethod.args; try { for (int i = 0; i < _LastCalledMethod.argTypes.Length; i++) { MethodArgs type = _LastCalledMethod.argTypes[i]; object luaParamValue = type.extractValue(L, i + 1 + numStackToSkip); args[type.index] = _LastCalledMethod.argTypes[i].isParamsArray ? ObjectTranslator.TableToArray(luaParamValue, type.paramsArrayType) : luaParamValue; if (args[type.index] == null && !lua.isnil(L, i + 1 + numStackToSkip)) { throw new LuaException("argument number " + (i + 1) + " is invalid"); } } _Translator.pushReturnValue(L, method.IsConstructor ? ((ConstructorInfo)method).Invoke(args) : method.Invoke(targetObject, args)); failedCall = false; } catch (TargetInvocationException ex) { return(_Translator.throwError(L, luaclr.verifyex(ex.InnerException))); } catch (LuaInternalException) { throw; } catch (Exception ex) { if (_Members.Length == 1) // Is the method overloaded? { return(luaL.error(L, "method call failed ({0})", ex.Message)); // No, throw error } } } } // 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) { return(luaL.error(L, String.Format("instance method '{0}' requires a non null target object", _MethodName))); } lua.remove(L, 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(L, m, ref _LastCalledMethod); if (isMethod) { if (_Translator.memberIsAllowed(member)) { hasMatch = true; break; } if (_Members.Length == 1) { return(luaL.error(L, "method call failed (access denied)")); } } } if (!hasMatch) { return(luaL.error(L, (candidateName == null) ? "invalid arguments to method call" : "invalid arguments to method: " + candidateName)); } } } else // Method from MethodBase instance { if (!_Translator.memberIsAllowed(methodToCall)) { return(luaL.error(L, "method call failed (access denied)")); } if (methodToCall.ContainsGenericParameters) { // bool isMethod = //* not used _Translator.matchParameters(L, methodToCall, ref _LastCalledMethod); if (methodToCall.IsGenericMethodDefinition) { //need to make a concrete type of the generic method definition var args = _LastCalledMethod.args; var typeArgs = new Type[args.Length]; for (int i = 0; i < args.Length; ++i) { typeArgs[i] = args[i].GetType(); } MethodInfo concreteMethod = ((MethodInfo)methodToCall).MakeGenericMethod(typeArgs); _Translator.pushReturnValue(L, concreteMethod.Invoke(targetObject, args)); failedCall = false; } else if (methodToCall.ContainsGenericParameters) { return(luaL.error(L, "unable to invoke method on generic class as the current method is an open generic method")); } } else { if (!methodToCall.IsStatic && !methodToCall.IsConstructor && targetObject == null) { targetObject = _ExtractTarget(L, 1); lua.remove(L, 1); // Pops the receiver } if (!_Translator.matchParameters(L, methodToCall, ref _LastCalledMethod)) { return(luaL.error(L, "invalid arguments to method call")); } } } if (failedCall) { if (!_Translator.memberIsAllowed(_LastCalledMethod.cachedMethod)) { return(luaL.error(L, "method call failed (access denied)")); } luaL.checkstack(L, _LastCalledMethod.outList.Length + 6, "MethodWrapper.call"); try { _Translator.pushReturnValue(L, _LastCalledMethod.cachedMethod.IsConstructor ? ((ConstructorInfo)_LastCalledMethod.cachedMethod).Invoke(_LastCalledMethod.args) : _LastCalledMethod.cachedMethod.Invoke(isStatic ? null : targetObject, _LastCalledMethod.args)); } catch (TargetInvocationException ex) { return(_Translator.throwError(L, luaclr.verifyex(ex.InnerException))); } catch (LuaInternalException) { throw; } catch (Exception ex) { return(luaL.error(L, "method call failed ({0})", ex.Message)); } } // Pushes out and ref return values foreach (int arg in _LastCalledMethod.outList) { nReturnValues++; _Translator.pushReturnValue(L, _LastCalledMethod.args[arg]); } //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); } }