Exemplo n.º 1
0
        internal static void _PushObject(LuaState luaState, object result)
        {
            try {
                if (null == result)
                {
                    LuaLib.LuaPushNil(luaState);
                }
                else if (result is LuaBase)             // LuaFunction or LuaTable
                {
                    LuaLib.LuaGetRef(luaState, (result as LuaBase).Reference);
                }
                else if (result is LuaString)           // LuaString
                {
                    var bytes = (result as LuaString).ToBytes();
                    LuaLib.LuaPushLString(luaState, bytes, bytes.Length);
                }
                else
                {
                    var t = result.GetType();
                    if (t.IsValueType)
                    {
                        if (t == typeof(bool))          // bool
                        {
                            LuaLib.LuaPushBoolean(luaState, (bool)result);
                        }
                        else if (t.IsPrimitive)         // number
                        {
                            LuaLib.LuaPushNumber(luaState, _ConvertToDouble(result));
                        }
                        else if (t.IsEnum)              // enum

                        {
                        }
                        else                            // structure
                        {
                            var size  = Marshal.SizeOf(result);
                            var bytes = new byte[size];
                            var ptr   = Marshal.AllocHGlobal(size);
                            Marshal.StructureToPtr(result, ptr, false);
                            Marshal.Copy(ptr, bytes, 0, size);
                            Marshal.FreeHGlobal(ptr);
                            LuaLib.LuaPushLString(luaState, bytes, size);
                        }
                    }
                    else if (t == typeof(string))       // string
                    {
                        LuaLib.LuaPushString(luaState, (string)result);
                    }
                    else if (t.IsArray)
                    {
                        if ("Byte[]" == t.Name)         // byte[] will be transferred through lstring
                        {
                            var bytes = result as byte[];
                            LuaLib.LuaPushLString(luaState, bytes, bytes.Length);
                        }
                        else                            // other array type
                        {
                            LuaLib.LuaNewTable(luaState);
                            var arr = result as Array;
                            for (var i = 0; i < arr.Length; ++i)
                            {
                                LuaLib.LuaPushNumber(luaState, i + 1);
                                _PushObject(luaState, arr.GetValue(i));
                                LuaLib.LuaSetTable(luaState, -3);
                            }
                        }
                    }
                    else if (result is IDictionary)     // KeyPair<TKey, TValue> related
                    {
                        LuaLib.LuaNewTable(luaState);
                        var dict = result as IDictionary;
                        var keys = dict.Keys;
                        foreach (var key in keys)
                        {
                            _PushObject(luaState, key);
                            _PushObject(luaState, dict[key]);
                            LuaLib.LuaSetTable(luaState, -3);
                        }
                    }
                    else if (result is IEnumerable)     // Array related
                    {
                        LuaLib.LuaNewTable(luaState);
                        var enumerable = result as IEnumerable;
                        var index      = 0;
                        foreach (var v in enumerable)
                        {
                            LuaLib.LuaPushNumber(luaState, index);
                            _PushObject(luaState, v);
                            LuaLib.LuaSetTable(luaState, -3);
                            ++index;
                        }
                    }
                    else                                // user data
                    {
                        int allocId = -1;
                        if (!LuaExecuter.objects.TryGetValue(result, out allocId))
                        {
                            allocId = (++LuaExecuter.objectAllocId);
                            LuaExecuter.objects.Add(result, allocId);
                            LuaExecuter.objectRefs.Add(result, 1);
                            LuaExecuter.backObjects.Add(allocId, result);
                        }
                        else
                        {
                            LuaExecuter.objectRefs[result] += 1;
                        }

                        LuaLib.LuaNetNewUData(luaState, allocId);
                        LuaLib.LuaLGetMetatable(luaState, "luaruntime");
                        LuaLib.LuaSetMetatable(luaState, -2);
                    }
                }
            } catch (Exception e) {
                Logger <ILuaRuntime> .X(e);
            }
        }
        /*
         * Calls the method. Receives the arguments from the Lua stack
         * and returns values in it.
         */
        int Call(LuaState luaState)
        {
            var    methodToCall  = _Method;
            object targetObject  = _Target;
            bool   failedCall    = true;
            int    nReturnValues = 0;

            if (!LuaLib.LuaCheckStack(luaState, 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 (targetObject == null || targetObject.Equals(null))
                    {
                        _Translator.ThrowError(luaState, String.Format("instance method '{0}' requires a non null target object", _MethodName));
                        LuaLib.LuaPushNil(luaState);
                        return(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  = LuaLib.LuaGetTop(luaState) - numStackToSkip;
                    MethodBase method         = _LastCalledMethod.cachedMethod;

                    if (numArgsPassed == _LastCalledMethod.argTypes.Length)                       // No. of args match?
                    {
                        if (!LuaLib.LuaCheckStack(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];

                                int index = i + 1 + numStackToSkip;

                                Func <int, object> valueExtractor = (currentParam) => {
                                    return(type.extractValue(luaState, currentParam));
                                };

                                if (_LastCalledMethod.argTypes [i].isParamsArray)
                                {
                                    int   count      = index - _LastCalledMethod.argTypes.Length;
                                    Array paramArray = _Translator.TableToArray(valueExtractor, type.paramsArrayType, index, count);
                                    args [_LastCalledMethod.argTypes [i].index] = paramArray;
                                }
                                else
                                {
                                    args [type.index] = valueExtractor(index);
                                }

                                if (_LastCalledMethod.args [_LastCalledMethod.argTypes [i].index] == null &&
                                    !LuaLib.LuaIsNil(luaState, 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
                            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)
                    {
                        LuaLib.LuaRemove(luaState, 1);                          // Pops the receiver
                    }

                    bool   hasMatch      = false;
                    string candidateName = null;

                    foreach (var member in _Members)
                    {
#if NETFX_CORE
                        candidateName = member.DeclaringType.Name + "." + member.Name;
#else
                        candidateName = member.ReflectedType.Name + "." + member.Name;
#endif
                        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.LuaPushNil(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.LuaPushNil(luaState);
                        return(1);
                    }
                }
                else
                {
                    if (!methodToCall.IsStatic && !methodToCall.IsConstructor && targetObject == null)
                    {
                        targetObject = _ExtractTarget(luaState, 1);
                        if (targetObject == null || targetObject.Equals(null))
                        {
                            _Translator.ThrowError(luaState, String.Format("instance method '{0}' requires a non null target object", _MethodName));
                            LuaLib.LuaPushNil(luaState);
                            return(1);
                        }
                        LuaLib.LuaRemove(luaState, 1);                          // Pops the receiver
                    }

                    if (!_Translator.MatchParameters(luaState, methodToCall, ref _LastCalledMethod))
                    {
                        _Translator.ThrowError(luaState, "invalid arguments to method call");
                        LuaLib.LuaPushNil(luaState);
                        return(1);
                    }
                }
            }

            if (failedCall)
            {
                if (!LuaLib.LuaCheckStack(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);
        }
Exemplo n.º 3
0
        public static void Push(IntPtr state, object o)
        {
            // nil == null
            if (o == null)
            {
                LuaLib.lua_pushnil(state);
                return;
            }

            // First do a switch lookup. Switch is incredibly fast.
            IConvertible iConvertible = o as IConvertible;

            if (iConvertible != null)
            {
                switch (iConvertible.GetTypeCode())
                {
                case TypeCode.Char:
                case TypeCode.String:
                    LuaLib.lua_pushstring(state, o.ToString(  ));
                    return;

                case TypeCode.Boolean:
                    LuaLib.lua_pushboolean(state, (bool)o);
                    return;

                case TypeCode.Byte:
                case TypeCode.SByte:
                case TypeCode.Decimal:
                case TypeCode.Single:
                case TypeCode.Double:
                case TypeCode.Int16:
                case TypeCode.Int32:
                case TypeCode.Int64:
                case TypeCode.UInt16:
                case TypeCode.UInt32:
                case TypeCode.UInt64:
                    LuaLib.lua_pushnumber(state, iConvertible.ToDouble(CultureInfo.InvariantCulture));
                    return;
                }
            }

            // Now handle the sealed classes. We can use RuntimeTypeHandle
            // because of the lack of inheritance.
            // RTH is fast because it's incredibly easy for the CLR to
            // lookup in memory.
            RuntimeTypeHandle       rth = Type.GetTypeHandle(o);
            Action <IntPtr, object> pusher;

            if (pushers.TryGetValue(rth, out pusher))
            {
                pusher(state, o);
            }
            else
            {
                // Now handle cases where inheritance can happen.
                ClrFunction clrFunction = o as ClrFunction;
                if (clrFunction != null)
                {
                    LuaLib.lua_pushcfunction(state, clrFunction.callback);
                }
                else
                {
                    throw new NotImplementedException("Passing of exotic datatypes is not yet handled");
                }
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// Called when lua requests that the function is invoked.
        /// </summary>
        /// <param name='lua'>
        /// The lua state.
        /// </param>
        internal virtual int Invoke(IntPtr s)
        {
            if (disposed == 1)
            {
                Helpers.Throw(s, "function '{0}' has been disposed", name);
                return(0);
            }

            Lua lua;

            if (!LookupTable <IntPtr, Lua> .Retrieve(s, out lua))
            {
                try
                {
                    LuaLib.lua_close(s);                       // This somehow didn't get called.
                }
                catch { }
                return(0);
            }

            int argc = LuaLib.lua_gettop(s);

            object[] args;
            if (argc == 0)
            {
                args = emptyObjects;
            }
            else
            {
                args = new object[argc];
                for (int i = 0; i < argc; i++)
                {
                    object argv = Helpers.GetObject(s, i + 1);
                    args[i] = argv;
                }
            }

            try
            {
                args = OnInvoke(lua, args) ?? emptyObjects;
            }
            catch (Exception ex)
            {
                Helpers.Throw(s, "exception calling function '{0}' - {1}", name, ex.Message);
                return(0);
            }

            if (args.Length > 0 && !LuaLib.lua_checkstack(s, args.Length))
            {
                Helpers.Throw(s, "not enough space for return values of function '{0}'", name);
                return(0);
            }

            var lastValue = 0;

            try
            {
                for (int i = 0; i < args.Length; lastValue = i++)
                {
                    Helpers.Push(s, args[i]);
                }
                return(args.Length);
            }
            catch (Exception ex)
            {
                Helpers.Throw(s, "failed to allocate return value for function '{0}','{1}' - {2}", name, lastValue, ex.Message);
                return(0);
            }
        }
Exemplo n.º 5
0
        /*
         * Calls the method. Receives the arguments from the Lua stack
         * and returns values in it.
         */
        public 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;

                    if (numArgsPassed == _LastCalledMethod.argTypes.Length)                    // No. of args match?
                    {
                        if (!LuaLib.lua_checkstack(luaState, _LastCalledMethod.outList.Length + 6))
                        {
                            throw new LuaException("Lua stack overflow");
                        }

                        try
                        {
                            for (int i = 0; i < _LastCalledMethod.argTypes.Length; i++)
                            {
                                if (_LastCalledMethod.argTypes[i].isParamsArray)
                                {
                                    object luaParamValue  = _LastCalledMethod.argTypes[i].extractValue(luaState, i + 1 + numStackToSkip);
                                    var    paramArrayType = _LastCalledMethod.argTypes[i].paramsArrayType;
                                    Array  paramArray;

                                    if (luaParamValue is LuaTable)
                                    {
                                        var table = (LuaTable)luaParamValue;
                                        paramArray = Array.CreateInstance(paramArrayType, table.Values.Count);

                                        for (int x = 1; x <= table.Values.Count; x++)
                                        {
                                            paramArray.SetValue(Convert.ChangeType(table[x], paramArrayType), x - 1);
                                        }
                                    }
                                    else
                                    {
                                        paramArray = Array.CreateInstance(paramArrayType, 1);
                                        paramArray.SetValue(luaParamValue, 0);
                                    }

                                    _LastCalledMethod.args[_LastCalledMethod.argTypes[i].index] = paramArray;
                                }
                                else
                                {
                                    _LastCalledMethod.args[_LastCalledMethod.argTypes[i].index] =
                                        _LastCalledMethod.argTypes[i].extractValue(luaState, i + 1 + numStackToSkip);
                                }

                                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)
                {
                    /*bool isMethod = */ _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++;
                //for(int i=0;i<lastCalledMethod.outList.Length;i++)
                _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);
        }
Exemplo n.º 6
0
 /// <summary>
 /// Creates a LuaFunction for the object on the top of the stack, and pops it.
 /// </summary>
 /// <param name="s">
 /// A Lua State
 /// </param>
 internal LuaFunction(IntPtr s)
 {
     state     = s;
     reference = LuaLib.luaL_ref(state, (int)PseudoIndex.Registry);
 }