Exemple #1
0
        internal static object TryRun(LuaRuntime runtime, long token, object target, object[] args, out bool returned)
        {
            _Logger.Debug($"Trying to run method hook (token {token})");
            returned = false;

            object return_value = null;

            LuaFunction fun;

            if (_Hooks.TryGetValue(token, out fun))
            {
                _Logger.Debug($"Hook found");
                // target == null --> static

                var objs_offs = 1;
                if (target == null)
                {
                    objs_offs = 0;
                }

                var objs = new LuaValue[args.Length + objs_offs];
                if (target != null)
                {
                    objs[0] = runtime.AsLuaValue(target);
                }
                for (int i = 0; i < args.Length; i++)
                {
                    objs[i + objs_offs] = runtime.AsLuaValue(args[i]);
                }

                var result = fun.Call(args: objs);

                Type return_type;
                if (_HookReturns.TryGetValue(token, out return_type))
                {
                    if (result.Count > 1)
                    {
                        for (int i = 1; i < result.Count; i++)
                        {
                            result[i].Dispose();
                        }
                    }

                    if (result.Count > 0)
                    {
                        returned     = true;
                        return_value = runtime.ToClrObject(result[0], return_type);

                        if (return_value != result[0])
                        {
                            result[0].Dispose();
                        }
                    }
                }
                else
                {
                    result.Dispose();
                }

                for (int i = 0; i < objs.Length; i++)
                {
                    objs[i]?.Dispose();
                }
            }
            else
            {
                _Logger.Debug($"Hook not found");
            }

            return(return_value);
        }