void FillMethodArguments(LuaState luaState, int numStackToSkip) { object[] args = _lastCalledMethod.args; for (int i = 0; i < _lastCalledMethod.argTypes.Length; i++) { MethodArgs type = _lastCalledMethod.argTypes[i]; int index = i + 1 + numStackToSkip; if (_lastCalledMethod.argTypes[i].IsParamsArray) { int count = _lastCalledMethod.argTypes.Length - i; Array paramArray = _translator.TableToArray(luaState, type.ExtractValue, type.ParameterType, index, count); args[_lastCalledMethod.argTypes[i].Index] = paramArray; } else { args[type.Index] = type.ExtractValue(luaState, index); } if (_lastCalledMethod.args[_lastCalledMethod.argTypes[i].Index] == null && !luaState.IsNil(i + 1 + numStackToSkip)) { throw new LuaException(string.Format("Argument number {0} is invalid", (i + 1))); } } }
/* * Matches a method against its arguments in the Lua stack. Returns * if the match was successful. It it was also returns the information * necessary to invoke the method. */ internal bool MatchParameters (LuaState luaState, MethodBase method, ref MethodCache methodCache) { ExtractValue extractValue; bool isMethod = true; var paramInfo = method.GetParameters (); int currentLuaParam = 1; int nLuaParams = LuaLib.LuaGetTop (luaState); var paramList = new List<object> (); var outList = new List<int> (); var argTypes = new List<MethodArgs> (); foreach (var currentNetParam in paramInfo) { #if !SILVERLIGHT if (!currentNetParam.IsIn && currentNetParam.IsOut) // Skips out params #else if (currentNetParam.IsOut) // Skips out params #endif { paramList.Add (null); outList.Add (paramList.LastIndexOf (null)); } else if (IsTypeCorrect (luaState, currentLuaParam, currentNetParam, out extractValue)) { // Type checking var value = extractValue (luaState, currentLuaParam); paramList.Add (value); int index = paramList.LastIndexOf (value); var methodArg = new MethodArgs (); methodArg.index = index; methodArg.extractValue = extractValue; argTypes.Add (methodArg); if (currentNetParam.ParameterType.IsByRef) outList.Add (index); currentLuaParam++; } // Type does not match, ignore if the parameter is optional else if (IsParamsArray (luaState, currentLuaParam, currentNetParam, out extractValue)) { var paramArrayType = currentNetParam.ParameterType.GetElementType (); Func<int, object> extractDelegate = (currentParam) => { currentLuaParam ++; return extractValue (luaState, currentParam); }; int count = (nLuaParams - currentLuaParam) + 1; Array paramArray = TableToArray (extractDelegate, paramArrayType, currentLuaParam, count); paramList.Add (paramArray); int index = paramList.LastIndexOf (paramArray); var methodArg = new MethodArgs (); methodArg.index = index; methodArg.extractValue = extractValue; methodArg.isParamsArray = true; methodArg.paramsArrayType = paramArrayType; argTypes.Add (methodArg); } else if (currentLuaParam > nLuaParams) { // Adds optional parameters if (currentNetParam.IsOptional) paramList.Add (currentNetParam.DefaultValue); else { isMethod = false; break; } } else if (currentNetParam.IsOptional) paramList.Add (currentNetParam.DefaultValue); else { // No match isMethod = false; break; } } if (currentLuaParam != nLuaParams + 1) // Number of parameters does not match isMethod = false; if (isMethod) { methodCache.args = paramList.ToArray (); methodCache.cachedMethod = method; methodCache.outList = outList.ToArray (); methodCache.argTypes = argTypes.ToArray (); } return isMethod; }
/* * Calls the method. Receives the arguments from the Lua stack * and returns values in it. */ int call(LuaCore.lua_State luaState) { var methodToCall = _Method; object targetObject = _Target; bool failedCall = true; int nReturnValues = 0; if (!LuaLib.lua_checkstack(luaState, 5)) { throw new LuaException("Lua stack overflow"); } bool isStatic = (_BindingType & BindingFlags.Static) == BindingFlags.Static; SetPendingException(null); if (methodToCall.IsNull()) // Method from name { if (isStatic) { targetObject = null; } else { targetObject = _ExtractTarget(luaState, 1); } //LuaLib.lua_remove(luaState,1); // Pops the receiver if (!_LastCalledMethod.cachedMethod.IsNull()) // 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 = LuaLib.lua_gettop(luaState) - numStackToSkip; MethodBase method = _LastCalledMethod.cachedMethod; if (numArgsPassed == _LastCalledMethod.argTypes.Length) // No. of args match? { if (!LuaLib.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) { Array paramArray = _Translator.tableToArray(luaParamValue, type.paramsArrayType); args [_LastCalledMethod.argTypes [i].index] = paramArray; } else { args [type.index] = luaParamValue; } if (_LastCalledMethod.args [_LastCalledMethod.argTypes [i].index] == null && !LuaLib.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.IsNull()) { _Translator.throwError(luaState, String.Format("instance method '{0}' requires a non null target object", _MethodName)); LuaLib.lua_pushnil(luaState); return(1); } LuaLib.lua_remove(luaState, 1); // Pops the receiver } bool hasMatch = false; string candidateName = null; foreach (var member in _Members) { candidateName = member.ReflectedType.Name + "." + member.Name; var 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); LuaLib.lua_pushnil(luaState); return(1); } } } else // Method from MethodBase instance { if (methodToCall.ContainsGenericParameters) { _Translator.matchParameters(luaState, methodToCall, ref _LastCalledMethod); if (methodToCall.IsGenericMethodDefinition) { //need to make a concrete type of the generic method definition var typeArgs = new List <Type> (); foreach (object arg in _LastCalledMethod.args) { typeArgs.Add(arg.GetType()); } var concreteMethod = (methodToCall as MethodInfo).MakeGenericMethod(typeArgs.ToArray()); _Translator.push(luaState, concreteMethod.Invoke(targetObject, _LastCalledMethod.args)); failedCall = false; } else if (methodToCall.ContainsGenericParameters) { _Translator.throwError(luaState, "unable to invoke method on generic class as the current method is an open generic method"); LuaLib.lua_pushnil(luaState); return(1); } } else { if (!methodToCall.IsStatic && !methodToCall.IsConstructor && targetObject == null) { targetObject = _ExtractTarget(luaState, 1); LuaLib.lua_remove(luaState, 1); // Pops the receiver } if (!_Translator.matchParameters(luaState, methodToCall, ref _LastCalledMethod)) { _Translator.throwError(luaState, "invalid arguments to method call"); LuaLib.lua_pushnil(luaState); return(1); } } } if (failedCall) { if (!LuaLib.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); }
/* * Calls the method. Receives the arguments from the Lua stack * and returns values in it. */ int Call(IntPtr state) { var luaState = LuaState.FromIntPtr(state); MethodBase methodToCall = _method; object targetObject = _target; bool failedCall = true; int nReturnValues = 0; if (!luaState.CheckStack(5)) { throw new LuaException("Lua stack overflow"); } bool isStatic = _isStatic; SetPendingException(null); if (methodToCall == null) { // Method from name if (isStatic) { targetObject = null; } else { targetObject = _extractTarget(luaState, 1); } 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 = luaState.GetTop() - numStackToSkip; MethodBase method = _lastCalledMethod.cachedMethod; if (numArgsPassed == _lastCalledMethod.argTypes.Length) { // No. of args match? if (!luaState.CheckStack(_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]; int index = i + 1 + numStackToSkip; if (_lastCalledMethod.argTypes[i].IsParamsArray) { int count = _lastCalledMethod.argTypes.Length - i; Array paramArray = _translator.TableToArray(luaState, type.ExtractValue, type.ParamsArrayType, index, count); args[_lastCalledMethod.argTypes[i].Index] = paramArray; } else { args[type.Index] = type.ExtractValue(luaState, index); } if (_lastCalledMethod.args[_lastCalledMethod.argTypes[i].Index] == null && !luaState.IsNil(i + 1 + numStackToSkip)) { throw new LuaException(string.Format("Argument number {0} is invalid", (i + 1))); } } if (_isStatic) { _translator.Push(luaState, method.Invoke(null, _lastCalledMethod.args)); } else { if (method.IsConstructor) { _translator.Push(luaState, ((ConstructorInfo)method).Invoke(_lastCalledMethod.args)); } else { _translator.Push(luaState, method.Invoke(targetObject, _lastCalledMethod.args)); } } failedCall = false; } catch (TargetInvocationException e) { // Failure of method invocation if (_translator.interpreter.UseTraceback) { e.GetBaseException().Data["Traceback"] = _translator.interpreter.GetDebugTraceback(); } 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)); luaState.PushNil(); return(1); } luaState.Remove(1); // Pops the receiver } bool hasMatch = false; string candidateName = null; foreach (var member in _members) { candidateName = member.ReflectedType.Name + "." + member.Name; bool isMethod = _translator.MatchParameters(luaState, member, 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); luaState.PushNil(); return(1); } } } else { // Method from MethodBase instance if (methodToCall.ContainsGenericParameters) { _translator.MatchParameters(luaState, methodToCall, ref _lastCalledMethod); if (methodToCall.IsGenericMethodDefinition) { //need to make a concrete type of the generic method definition var typeArgs = new List <Type>(); foreach (object arg in _lastCalledMethod.args) { typeArgs.Add(arg.GetType()); } var concreteMethod = ((MethodInfo)methodToCall).MakeGenericMethod(typeArgs.ToArray()); _translator.Push(luaState, concreteMethod.Invoke(targetObject, _lastCalledMethod.args)); failedCall = false; } else if (methodToCall.ContainsGenericParameters) { _translator.ThrowError(luaState, "Unable to invoke method on generic class as the current method is an open generic method"); luaState.PushNil(); return(1); } } else { if (!methodToCall.IsStatic && !methodToCall.IsConstructor && targetObject == null) { targetObject = _extractTarget(luaState, 1); luaState.Remove(1); // Pops the receiver } if (!_translator.MatchParameters(luaState, methodToCall, ref _lastCalledMethod)) { _translator.ThrowError(luaState, "Invalid arguments to method call"); luaState.PushNil(); return(1); } } } if (failedCall) { if (!luaState.CheckStack(_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) { if (_translator.interpreter.UseTraceback) { e.GetBaseException().Data["Traceback"] = _translator.interpreter.GetDebugTraceback(); } 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]]); } // 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); }
/* * Matches a method against its arguments in the Lua stack. Returns * if the match was succesful. It it was also returns the information * necessary to invoke the method. */ internal bool matchParameters (LuaCore.lua_State luaState, MethodBase method, ref MethodCache methodCache) { ExtractValue extractValue; bool isMethod = true; var paramInfo = method.GetParameters (); int currentLuaParam = 1; int nLuaParams = LuaLib.lua_gettop (luaState); var paramList = new ArrayList (); var outList = new List<int> (); var argTypes = new List<MethodArgs> (); foreach (var currentNetParam in paramInfo) { if (!currentNetParam.IsIn && currentNetParam.IsOut) // Skips out params outList.Add (paramList.Add (null)); else if (currentLuaParam > nLuaParams) { // Adds optional parameters if (currentNetParam.IsOptional) paramList.Add (currentNetParam.DefaultValue); else { isMethod = false; break; } } else if (_IsTypeCorrect (luaState, currentLuaParam, currentNetParam, out extractValue)) { // Type checking int index = paramList.Add (extractValue (luaState, currentLuaParam)); var methodArg = new MethodArgs (); methodArg.index = index; methodArg.extractValue = extractValue; argTypes.Add (methodArg); if (currentNetParam.ParameterType.IsByRef) outList.Add (index); currentLuaParam++; } // Type does not match, ignore if the parameter is optional else if (_IsParamsArray (luaState, currentLuaParam, currentNetParam, out extractValue)) { object luaParamValue = extractValue (luaState, currentLuaParam); var paramArrayType = currentNetParam.ParameterType.GetElementType (); Array paramArray; if (luaParamValue is LuaTable) { var table = (LuaTable)luaParamValue; var tableEnumerator = table.GetEnumerator (); paramArray = Array.CreateInstance (paramArrayType, table.Values.Count); tableEnumerator.Reset (); int paramArrayIndex = 0; while (tableEnumerator.MoveNext()) { paramArray.SetValue (Convert.ChangeType (tableEnumerator.Value, currentNetParam.ParameterType.GetElementType ()), paramArrayIndex); paramArrayIndex++; } } else { paramArray = Array.CreateInstance (paramArrayType, 1); paramArray.SetValue (luaParamValue, 0); } int index = paramList.Add (paramArray); var methodArg = new MethodArgs (); methodArg.index = index; methodArg.extractValue = extractValue; methodArg.isParamsArray = true; methodArg.paramsArrayType = paramArrayType; argTypes.Add (methodArg); currentLuaParam++; } else if (currentNetParam.IsOptional) paramList.Add (currentNetParam.DefaultValue); else { // No match isMethod = false; break; } } if (currentLuaParam != nLuaParams + 1) // Number of parameters does not match isMethod = false; if (isMethod) { methodCache.args = paramList.ToArray (); methodCache.cachedMethod = method; methodCache.outList = outList.ToArray (); methodCache.argTypes = argTypes.ToArray (); } return isMethod; }
public MethodCache() { args = new object[0]; argTypes = new MethodArgs[0]; outList = new int[0]; }