Example #1
0
        /// <summary>
        /// Convert C# exceptions into Lua errors
        /// </summary>
        /// <returns>num of things on stack</returns>
        /// <param name="e">null for no pending exception</param>
        internal int SetPendingException(Exception e)
        {
            Exception caughtExcept = e;

            if (caughtExcept != null)
            {
                translator.throwError(luaState, caughtExcept);
                LuaDLL.lua_pushnil(luaState);

                return(1);
            }
            else
            {
                return(0);
            }
        }
        /*
         * 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);
        }
Example #3
0
        /*
         * 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.

            // 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)
            {
                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");
                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);
        }