Unverified Commit 5e9a190a authored by Vinicius Jarina's avatar Vinicius Jarina Committed by GitHub
Browse files

WIP cleanup (#275)

* WIP cleanup

* Trying fixing iPhoneSimTests.

* More cleanups

* Minified initLua loadCLRpackage
parent 66947423
...@@ -22,31 +22,34 @@ namespace NLua.Method ...@@ -22,31 +22,34 @@ namespace NLua.Method
*/ */
class LuaMethodWrapper class LuaMethodWrapper
{ {
internal LuaNativeFunction invokeFunction; internal LuaNativeFunction InvokeFunction;
ObjectTranslator _Translator;
MethodBase _Method; readonly ObjectTranslator _translator;
MethodCache _LastCalledMethod = new MethodCache(); readonly MethodBase _method;
string _MethodName;
MemberInfo[] _Members; readonly ExtractValue _extractTarget;
ExtractValue _ExtractTarget; readonly object _target;
object _Target; readonly bool _isStatic;
bool _IsStatic;
readonly string _methodName;
readonly MethodInfo[] _members;
MethodCache _lastCalledMethod;
/* /*
* Constructs the wrapper for a known MethodBase instance * Constructs the wrapper for a known MethodBase instance
*/ */
public LuaMethodWrapper(ObjectTranslator translator, object target, ProxyType targetType, MethodBase method) public LuaMethodWrapper(ObjectTranslator translator, object target, ProxyType targetType, MethodBase method)
{ {
invokeFunction = Call; InvokeFunction = Call;
_Translator = translator; _translator = translator;
_Target = target; _target = target;
_extractTarget = translator.typeChecker.GetExtractor(targetType);
if (targetType != null)
_ExtractTarget = translator.typeChecker.GetExtractor(targetType); _method = method;
_methodName = method.Name;
_Method = method; _isStatic = method.IsStatic;
_MethodName = method.Name;
_IsStatic = method.IsStatic;
} }
/* /*
...@@ -54,16 +57,16 @@ namespace NLua.Method ...@@ -54,16 +57,16 @@ namespace NLua.Method
*/ */
public LuaMethodWrapper(ObjectTranslator translator, ProxyType targetType, string methodName, BindingFlags bindingType) public LuaMethodWrapper(ObjectTranslator translator, ProxyType targetType, string methodName, BindingFlags bindingType)
{ {
invokeFunction = Call; InvokeFunction = Call;
_Translator = translator;
_MethodName = methodName;
if (targetType != null) _translator = translator;
_ExtractTarget = translator.typeChecker.GetExtractor(targetType); _methodName = methodName;
_extractTarget = translator.typeChecker.GetExtractor(targetType);
_IsStatic = (bindingType & BindingFlags.Static) == BindingFlags.Static; _isStatic = (bindingType & BindingFlags.Static) == BindingFlags.Static;
_Members = GetMethodsRecursively(targetType.UnderlyingSystemType, methodName, bindingType | BindingFlags.Public); _members = GetMethodsRecursively(targetType.UnderlyingSystemType,
methodName,
bindingType | BindingFlags.Public);
} }
MethodInfo[] GetMethodsRecursively(Type type, string methodName, BindingFlags bindingType) MethodInfo[] GetMethodsRecursively(Type type, string methodName, BindingFlags bindingType)
...@@ -84,7 +87,7 @@ namespace NLua.Method ...@@ -84,7 +87,7 @@ namespace NLua.Method
/// <param name="e">null for no pending exception</param> /// <param name="e">null for no pending exception</param>
int SetPendingException(Exception e) int SetPendingException(Exception e)
{ {
return _Translator.interpreter.SetPendingException(e); return _translator.interpreter.SetPendingException(e);
} }
/* /*
...@@ -94,15 +97,17 @@ namespace NLua.Method ...@@ -94,15 +97,17 @@ namespace NLua.Method
int Call(IntPtr state) int Call(IntPtr state)
{ {
var luaState = LuaState.FromIntPtr(state); var luaState = LuaState.FromIntPtr(state);
var methodToCall = _Method;
object targetObject = _Target; MethodBase methodToCall = _method;
object targetObject = _target;
bool failedCall = true; bool failedCall = true;
int nReturnValues = 0; int nReturnValues = 0;
if (!luaState.CheckStack(5)) if (!luaState.CheckStack(5))
throw new LuaException("Lua stack overflow"); throw new LuaException("Lua stack overflow");
bool isStatic = _IsStatic; bool isStatic = _isStatic;
SetPendingException(null); SetPendingException(null);
if (methodToCall == null) if (methodToCall == null)
...@@ -110,57 +115,54 @@ namespace NLua.Method ...@@ -110,57 +115,54 @@ namespace NLua.Method
if (isStatic) if (isStatic)
targetObject = null; targetObject = null;
else else
targetObject = _ExtractTarget(luaState, 1); targetObject = _extractTarget(luaState, 1);
if (_LastCalledMethod.cachedMethod != null) if (_lastCalledMethod.cachedMethod != null)
{ // Cached? { // 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 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; int numArgsPassed = luaState.GetTop() - numStackToSkip;
MethodBase method = _LastCalledMethod.cachedMethod; MethodBase method = _lastCalledMethod.cachedMethod;
if (numArgsPassed == _LastCalledMethod.argTypes.Length) if (numArgsPassed == _lastCalledMethod.argTypes.Length)
{ // No. of args match? { // No. of args match?
if (!luaState.CheckStack(_LastCalledMethod.outList.Length + 6)) if (!luaState.CheckStack(_lastCalledMethod.outList.Length + 6))
throw new LuaException("Lua stack overflow"); throw new LuaException("Lua stack overflow");
object[] args = _LastCalledMethod.args; object[] args = _lastCalledMethod.args;
try try
{ {
for (int i = 0; i < _LastCalledMethod.argTypes.Length; i++) for (int i = 0; i < _lastCalledMethod.argTypes.Length; i++)
{ {
MethodArgs type = _LastCalledMethod.argTypes[i]; MethodArgs type = _lastCalledMethod.argTypes[i];
int index = i + 1 + numStackToSkip; int index = i + 1 + numStackToSkip;
Func<int, object> valueExtractor = currentParam => {
return type.extractValue(luaState, currentParam);
};
if (_LastCalledMethod.argTypes[i].isParamsArray) if (_lastCalledMethod.argTypes[i].IsParamsArray)
{ {
int count = _LastCalledMethod.argTypes.Length - i; int count = _lastCalledMethod.argTypes.Length - i;
Array paramArray = _Translator.TableToArray(valueExtractor, type.paramsArrayType, index, count); Array paramArray = _translator.TableToArray(luaState, type.ExtractValue, type.ParamsArrayType, index, count);
args[_LastCalledMethod.argTypes[i].index] = paramArray; args[_lastCalledMethod.argTypes[i].Index] = paramArray;
} }
else else
{ {
args[type.index] = valueExtractor(index); args[type.Index] = type.ExtractValue(luaState, index);
} }
if (_LastCalledMethod.args[_LastCalledMethod.argTypes[i].index] == null && if (_lastCalledMethod.args[_lastCalledMethod.argTypes[i].Index] == null &&
!luaState.IsNil(i + 1 + numStackToSkip)) !luaState.IsNil(i + 1 + numStackToSkip))
throw new LuaException(string.Format("Argument number {0} is invalid", (i + 1))); throw new LuaException(string.Format("Argument number {0} is invalid", (i + 1)));
} }
if (_IsStatic) if (_isStatic)
_Translator.Push(luaState, method.Invoke(null, _LastCalledMethod.args)); _translator.Push(luaState, method.Invoke(null, _lastCalledMethod.args));
else else
{ {
if (method.IsConstructor) if (method.IsConstructor)
_Translator.Push(luaState, ((ConstructorInfo)method).Invoke(_LastCalledMethod.args)); _translator.Push(luaState, ((ConstructorInfo)method).Invoke(_lastCalledMethod.args));
else else
_Translator.Push(luaState, method.Invoke(targetObject, _LastCalledMethod.args)); _translator.Push(luaState, method.Invoke(targetObject, _lastCalledMethod.args));
} }
failedCall = false; failedCall = false;
...@@ -168,12 +170,12 @@ namespace NLua.Method ...@@ -168,12 +170,12 @@ namespace NLua.Method
catch (TargetInvocationException e) catch (TargetInvocationException e)
{ {
// Failure of method invocation // Failure of method invocation
if (_Translator.interpreter.UseTraceback) e.GetBaseException().Data["Traceback"] = _Translator.interpreter.GetDebugTraceback(); if (_translator.interpreter.UseTraceback) e.GetBaseException().Data["Traceback"] = _translator.interpreter.GetDebugTraceback();
return SetPendingException(e.GetBaseException()); return SetPendingException(e.GetBaseException());
} }
catch (Exception e) catch (Exception e)
{ {
if (_Members.Length == 1) // Is the method overloaded? if (_members.Length == 1) // Is the method overloaded?
// No, throw error // No, throw error
return SetPendingException(e); return SetPendingException(e);
} }
...@@ -189,7 +191,7 @@ namespace NLua.Method ...@@ -189,7 +191,7 @@ namespace NLua.Method
{ {
if (targetObject == null) if (targetObject == null)
{ {
_Translator.ThrowError(luaState, string.Format("instance method '{0}' requires a non null target object", _MethodName)); _translator.ThrowError(luaState, string.Format("instance method '{0}' requires a non null target object", _methodName));
luaState.PushNil(); luaState.PushNil();
return 1; return 1;
} }
...@@ -200,11 +202,11 @@ namespace NLua.Method ...@@ -200,11 +202,11 @@ namespace NLua.Method
bool hasMatch = false; bool hasMatch = false;
string candidateName = null; string candidateName = null;
foreach (var member in _Members) foreach (var member in _members)
{ {
candidateName = member.ReflectedType.Name + "." + member.Name; candidateName = member.ReflectedType.Name + "." + member.Name;
var m = (MethodInfo)member; var m = (MethodInfo)member;
bool isMethod = _Translator.MatchParameters(luaState, m, ref _LastCalledMethod); bool isMethod = _translator.MatchParameters(luaState, m, ref _lastCalledMethod);
if (isMethod) if (isMethod)
{ {
...@@ -216,7 +218,7 @@ namespace NLua.Method ...@@ -216,7 +218,7 @@ namespace NLua.Method
if (!hasMatch) if (!hasMatch)
{ {
string msg = (candidateName == null) ? "Invalid arguments to method call" : ("Invalid arguments to method: " + candidateName); string msg = (candidateName == null) ? "Invalid arguments to method call" : ("Invalid arguments to method: " + candidateName);
_Translator.ThrowError(luaState, msg); _translator.ThrowError(luaState, msg);
luaState.PushNil(); luaState.PushNil();
return 1; return 1;
} }
...@@ -226,23 +228,23 @@ namespace NLua.Method ...@@ -226,23 +228,23 @@ namespace NLua.Method
{ // Method from MethodBase instance { // Method from MethodBase instance
if (methodToCall.ContainsGenericParameters) if (methodToCall.ContainsGenericParameters)
{ {
_Translator.MatchParameters(luaState, methodToCall, ref _LastCalledMethod); _translator.MatchParameters(luaState, methodToCall, ref _lastCalledMethod);
if (methodToCall.IsGenericMethodDefinition) if (methodToCall.IsGenericMethodDefinition)
{ {
//need to make a concrete type of the generic method definition //need to make a concrete type of the generic method definition
var typeArgs = new List<Type>(); var typeArgs = new List<Type>();
foreach (object arg in _LastCalledMethod.args) foreach (object arg in _lastCalledMethod.args)
typeArgs.Add(arg.GetType()); typeArgs.Add(arg.GetType());
var concreteMethod = ((MethodInfo)methodToCall).MakeGenericMethod(typeArgs.ToArray()); var concreteMethod = ((MethodInfo)methodToCall).MakeGenericMethod(typeArgs.ToArray());
_Translator.Push(luaState, concreteMethod.Invoke(targetObject, _LastCalledMethod.args)); _translator.Push(luaState, concreteMethod.Invoke(targetObject, _lastCalledMethod.args));
failedCall = false; failedCall = false;
} }
else if (methodToCall.ContainsGenericParameters) else if (methodToCall.ContainsGenericParameters)
{ {
_Translator.ThrowError(luaState, "Unable to invoke method on generic class as the current method is an open generic method"); _translator.ThrowError(luaState, "Unable to invoke method on generic class as the current method is an open generic method");
luaState.PushNil(); luaState.PushNil();
return 1; return 1;
} }
...@@ -251,13 +253,13 @@ namespace NLua.Method ...@@ -251,13 +253,13 @@ namespace NLua.Method
{ {
if (!methodToCall.IsStatic && !methodToCall.IsConstructor && targetObject == null) if (!methodToCall.IsStatic && !methodToCall.IsConstructor && targetObject == null)
{ {
targetObject = _ExtractTarget(luaState, 1); targetObject = _extractTarget(luaState, 1);
luaState.Remove(1); // Pops the receiver luaState.Remove(1); // Pops the receiver
} }
if (!_Translator.MatchParameters(luaState, methodToCall, ref _LastCalledMethod)) if (!_translator.MatchParameters(luaState, methodToCall, ref _lastCalledMethod))
{ {
_Translator.ThrowError(luaState, "Invalid arguments to method call"); _translator.ThrowError(luaState, "Invalid arguments to method call");
luaState.PushNil(); luaState.PushNil();
return 1; return 1;
} }
...@@ -266,24 +268,24 @@ namespace NLua.Method ...@@ -266,24 +268,24 @@ namespace NLua.Method
if (failedCall) if (failedCall)
{ {
if (!luaState.CheckStack(_LastCalledMethod.outList.Length + 6)) if (!luaState.CheckStack(_lastCalledMethod.outList.Length + 6))
throw new LuaException("Lua stack overflow"); throw new LuaException("Lua stack overflow");
try try
{ {
if (isStatic) if (isStatic)
_Translator.Push(luaState, _LastCalledMethod.cachedMethod.Invoke(null, _LastCalledMethod.args)); _translator.Push(luaState, _lastCalledMethod.cachedMethod.Invoke(null, _lastCalledMethod.args));
else else
{ {
if (_LastCalledMethod.cachedMethod.IsConstructor) if (_lastCalledMethod.cachedMethod.IsConstructor)
_Translator.Push(luaState, ((ConstructorInfo)_LastCalledMethod.cachedMethod).Invoke(_LastCalledMethod.args)); _translator.Push(luaState, ((ConstructorInfo)_lastCalledMethod.cachedMethod).Invoke(_lastCalledMethod.args));
else else
_Translator.Push(luaState, _LastCalledMethod.cachedMethod.Invoke(targetObject, _LastCalledMethod.args)); _translator.Push(luaState, _lastCalledMethod.cachedMethod.Invoke(targetObject, _lastCalledMethod.args));
} }
} }
catch (TargetInvocationException e) catch (TargetInvocationException e)
{ {
if (_Translator.interpreter.UseTraceback) e.GetBaseException().Data["Traceback"] = _Translator.interpreter.GetDebugTraceback(); if (_translator.interpreter.UseTraceback) e.GetBaseException().Data["Traceback"] = _translator.interpreter.GetDebugTraceback();
return SetPendingException(e.GetBaseException()); return SetPendingException(e.GetBaseException());
} }
catch (Exception e) catch (Exception e)
...@@ -293,17 +295,17 @@ namespace NLua.Method ...@@ -293,17 +295,17 @@ namespace NLua.Method
} }
// Pushes out and ref return values // Pushes out and ref return values
for (int index = 0; index < _LastCalledMethod.outList.Length; index++) for (int index = 0; index < _lastCalledMethod.outList.Length; index++)
{ {
nReturnValues++; nReturnValues++;
_Translator.Push(luaState, _LastCalledMethod.args[_LastCalledMethod.outList[index]]); _translator.Push(luaState, _lastCalledMethod.args[_lastCalledMethod.outList[index]]);
} }
// If not return void,we need add 1, // If not return void,we need add 1,
// or we will lost the function's return value // or we will lost the function's return value
// when call dotnet function like "int foo(arg1,out arg2,out arg3)" in Lua code // when call dotnet function like "int foo(arg1,out arg2,out arg3)" in Lua code
if (!_LastCalledMethod.IsReturnVoid && nReturnValues > 0) if (!_lastCalledMethod.IsReturnVoid && nReturnValues > 0)
nReturnValues++; nReturnValues++;
return nReturnValues < 1 ? 1 : nReturnValues; return nReturnValues < 1 ? 1 : nReturnValues;
......
...@@ -8,10 +8,10 @@ namespace NLua.Method ...@@ -8,10 +8,10 @@ namespace NLua.Method
struct MethodArgs struct MethodArgs
{ {
// Position of parameter // Position of parameter
public int index; public int Index;
// Type-conversion function // Type-conversion function
public ExtractValue extractValue; public ExtractValue ExtractValue;
public bool isParamsArray; public bool IsParamsArray;
public Type paramsArrayType; public Type ParamsArrayType;
} }
} }
\ No newline at end of file
...@@ -5,15 +5,15 @@ namespace NLua.Method ...@@ -5,15 +5,15 @@ namespace NLua.Method
{ {
class RegisterEventHandler class RegisterEventHandler
{ {
private EventHandlerContainer pendingEvents; private readonly EventHandlerContainer _pendingEvents;
private EventInfo eventInfo; private readonly EventInfo _eventInfo;
private object target; private readonly object _target;
public RegisterEventHandler(EventHandlerContainer pendingEvents, object target, EventInfo eventInfo) public RegisterEventHandler(EventHandlerContainer pendingEvents, object target, EventInfo eventInfo)
{ {
this.target = target; _target = target;
this.eventInfo = eventInfo; _eventInfo = eventInfo;
this.pendingEvents = pendingEvents; _pendingEvents = pendingEvents;
} }
/* /*
...@@ -23,9 +23,9 @@ namespace NLua.Method ...@@ -23,9 +23,9 @@ namespace NLua.Method
{ {
//CP: Fix by Ben Bryant for event handling with one parameter //CP: Fix by Ben Bryant for event handling with one parameter
//link: http://luaforge.net/forum/message.php?msg_id=9266 //link: http://luaforge.net/forum/message.php?msg_id=9266
Delegate handlerDelegate = CodeGeneration.Instance.GetDelegate(eventInfo.EventHandlerType, function); Delegate handlerDelegate = CodeGeneration.Instance.GetDelegate(_eventInfo.EventHandlerType, function);
eventInfo.AddEventHandler(target, handlerDelegate); _eventInfo.AddEventHandler(_target, handlerDelegate);
pendingEvents.Add(handlerDelegate, this); _pendingEvents.Add(handlerDelegate, this);
return handlerDelegate; return handlerDelegate;
} }
...@@ -36,7 +36,7 @@ namespace NLua.Method ...@@ -36,7 +36,7 @@ namespace NLua.Method
public void Remove(Delegate handlerDelegate) public void Remove(Delegate handlerDelegate)
{ {
RemovePending(handlerDelegate); RemovePending(handlerDelegate);
pendingEvents.Remove(handlerDelegate); _pendingEvents.Remove(handlerDelegate);
} }
/* /*
...@@ -44,7 +44,7 @@ namespace NLua.Method ...@@ -44,7 +44,7 @@ namespace NLua.Method
*/ */
internal void RemovePending(Delegate handlerDelegate) internal void RemovePending(Delegate handlerDelegate)
{ {
eventInfo.RemoveEventHandler(target, handlerDelegate); _eventInfo.RemoveEventHandler(_target, handlerDelegate);
} }
} }
} }
\ No newline at end of file
...@@ -14,8 +14,9 @@ ...@@ -14,8 +14,9 @@
<Compile Include="$(MSBuildThisFileDirectory)Event\HookExceptionEventArgs.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Event\HookExceptionEventArgs.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Exceptions\LuaException.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Exceptions\LuaException.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Exceptions\LuaScriptException.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Exceptions\LuaScriptException.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\GeneralExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\StringExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\LuaExtensions.cs" /> <Compile Include="$(MSBuildThisFileDirectory)Extensions\LuaExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\TypeExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)GenerateEventAssembly\ClassGenerator.cs" /> <Compile Include="$(MSBuildThisFileDirectory)GenerateEventAssembly\ClassGenerator.cs" />
<Compile Include="$(MSBuildThisFileDirectory)GenerateEventAssembly\CodeGeneration.cs" /> <Compile Include="$(MSBuildThisFileDirectory)GenerateEventAssembly\CodeGeneration.cs" />
<Compile Include="$(MSBuildThisFileDirectory)GenerateEventAssembly\DelegateGenerator.cs" /> <Compile Include="$(MSBuildThisFileDirectory)GenerateEventAssembly\DelegateGenerator.cs" />
......
...@@ -36,20 +36,20 @@ namespace NLua ...@@ -36,20 +36,20 @@ namespace NLua
} }
} }
readonly LuaNativeFunction registerTableFunction; readonly LuaNativeFunction _registerTableFunction;
readonly LuaNativeFunction unregisterTableFunction; readonly LuaNativeFunction _unregisterTableFunction;
readonly LuaNativeFunction getMethodSigFunction; readonly LuaNativeFunction _getMethodSigFunction;
readonly LuaNativeFunction getConstructorSigFunction; readonly LuaNativeFunction _getConstructorSigFunction;
readonly LuaNativeFunction importTypeFunction; readonly LuaNativeFunction _importTypeFunction;
readonly LuaNativeFunction loadAssemblyFunction; readonly LuaNativeFunction _loadAssemblyFunction;
readonly LuaNativeFunction ctypeFunction; readonly LuaNativeFunction _ctypeFunction;
readonly LuaNativeFunction enumFromIntFunction; readonly LuaNativeFunction _enumFromIntFunction;
// object to object # // object to object #
readonly Dictionary<object, int> objectsBackMap = new Dictionary<object, int>(new ReferenceComparer()); readonly Dictionary<object, int> _objectsBackMap = new Dictionary<object, int>(new ReferenceComparer());
// object # to object (FIXME - it should be possible to get object address as an object #) // object # to object (FIXME - it should be possible to get object address as an object #)
readonly Dictionary<int, object> objects = new Dictionary<int, object>(); readonly Dictionary<int, object> _objects = new Dictionary<int, object>();
internal EventHandlerContainer pendingEvents = new EventHandlerContainer(); internal EventHandlerContainer PendingEvents = new EventHandlerContainer();
MetaFunctions metaFunctions; MetaFunctions metaFunctions;
List<Assembly> assemblies; List<Assembly> assemblies;
internal CheckType typeChecker; internal CheckType typeChecker;
...@@ -73,14 +73,14 @@ namespace NLua ...@@ -73,14 +73,14 @@ namespace NLua
metaFunctions = new MetaFunctions(this); metaFunctions = new MetaFunctions(this);
assemblies = new List<Assembly>(); assemblies = new List<Assembly>();
importTypeFunction = ImportType; _importTypeFunction = ImportType;
loadAssemblyFunction = LoadAssembly; _loadAssemblyFunction = LoadAssembly;
registerTableFunction = RegisterTable; _registerTableFunction = RegisterTable;
unregisterTableFunction = UnregisterTable; _unregisterTableFunction = UnregisterTable;
getMethodSigFunction = GetMethodSignature; _getMethodSigFunction = GetMethodSignature;
getConstructorSigFunction = GetConstructorSignature; _getConstructorSigFunction = GetConstructorSignature;
ctypeFunction = CType; _ctypeFunction = CType;
enumFromIntFunction = EnumFromInt; _enumFromIntFunction = EnumFromInt;
CreateLuaObjectList(luaState); CreateLuaObjectList(luaState);
CreateIndexingMetaFunction(luaState); CreateIndexingMetaFunction(luaState);
...@@ -114,7 +114,7 @@ namespace NLua ...@@ -114,7 +114,7 @@ namespace NLua
{ {
luaState.PushString("luaNet_indexfunction"); luaState.PushString("luaNet_indexfunction");
luaState.DoString(MetaFunctions.LuaIndexFunction); luaState.DoString(MetaFunctions.LuaIndexFunction);
luaState.RawSet((int)LuaRegistry.Index); luaState.RawSet(LuaRegistry.Index);
} }
/* /*
...@@ -170,21 +170,21 @@ namespace NLua ...@@ -170,21 +170,21 @@ namespace NLua
{ {
luaState.PushCFunction(metaFunctions.IndexFunction); luaState.PushCFunction(metaFunctions.IndexFunction);
luaState.SetGlobal("get_object_member"); luaState.SetGlobal("get_object_member");
luaState.PushCFunction(importTypeFunction); luaState.PushCFunction(_importTypeFunction);
luaState.SetGlobal("import_type"); luaState.SetGlobal("import_type");
luaState.PushCFunction(loadAssemblyFunction); luaState.PushCFunction(_loadAssemblyFunction);
luaState.SetGlobal("load_assembly"); luaState.SetGlobal("load_assembly");
luaState.PushCFunction(registerTableFunction); luaState.PushCFunction(_registerTableFunction);
luaState.SetGlobal("make_object"); luaState.SetGlobal("make_object");
luaState.PushCFunction(unregisterTableFunction); luaState.PushCFunction(_unregisterTableFunction);
luaState.SetGlobal("free_object"); luaState.SetGlobal("free_object");
luaState.PushCFunction(getMethodSigFunction); luaState.PushCFunction(_getMethodSigFunction);
luaState.SetGlobal("get_method_bysig"); luaState.SetGlobal("get_method_bysig");
luaState.PushCFunction(getConstructorSigFunction); luaState.PushCFunction(_getConstructorSigFunction);
luaState.SetGlobal("get_constructor_bysig"); luaState.SetGlobal("get_constructor_bysig");
luaState.PushCFunction(ctypeFunction); luaState.PushCFunction(_ctypeFunction);
luaState.SetGlobal("ctype"); luaState.SetGlobal("ctype");
luaState.PushCFunction(enumFromIntFunction); luaState.PushCFunction(_enumFromIntFunction);
luaState.SetGlobal("enum"); luaState.SetGlobal("enum");
} }
...@@ -227,7 +227,8 @@ namespace NLua ...@@ -227,7 +227,8 @@ namespace NLua
if (message != null) if (message != null)
{ {
// Wrap Lua error (just a string) and store the error location // Wrap Lua error (just a string) and store the error location
if (interpreter.UseTraceback) message += Environment.NewLine + interpreter.GetDebugTraceback(); if (interpreter.UseTraceback)
message += Environment.NewLine + interpreter.GetDebugTraceback();
e = new LuaScriptException(message, errLocation); e = new LuaScriptException(message, errLocation);
} }
else else
...@@ -384,45 +385,48 @@ namespace NLua ...@@ -384,45 +385,48 @@ namespace NLua
private int RegisterTableInternal(LuaState luaState) private int RegisterTableInternal(LuaState luaState)
{ {
if (luaState.Type(1) == LuaType.Table) if (luaState.Type(1) != LuaType.Table)
{ {
var luaTable = GetTable(luaState, 1); ThrowError(luaState, "register_table: first arg is not a table");
string superclassName = luaState.ToString(2).ToString(); return 0;
}
if (superclassName != null) LuaTable luaTable = GetTable(luaState, 1);
{ string superclassName = luaState.ToString(2);
var klass = FindType(superclassName);
if (klass != null) if (string.IsNullOrEmpty(superclassName))
{ {
// Creates and pushes the object in the stack, setting ThrowError(luaState, "register_table: superclass name can not be null");
// it as the metatable of the first argument return 0;
object obj = CodeGeneration.Instance.GetClassInstance(klass, luaTable);
PushObject(luaState, obj, "luaNet_metatable");
luaState.NewTable();
luaState.PushString("__index");
luaState.PushCopy(-3);;
luaState.SetTable(-3);
luaState.PushString("__newindex");
luaState.PushCopy(-3);
luaState.SetTable(-3);
luaState.SetMetaTable(1);
// Pushes the object again, this time as the base field
// of the table and with the luaNet_searchbase metatable
luaState.PushString("base");
int index = AddObject(obj);
PushNewObject(luaState, obj, index, "luaNet_searchbase");
luaState.RawSet(1);
}
else
ThrowError(luaState, "register_table: can not find superclass '" + superclassName + "'");
}
else
ThrowError(luaState, "register_table: superclass name can not be null");
} }
else
ThrowError(luaState, "register_table: first arg is not a table"); var klass = FindType(superclassName);
if (klass == null)
{
ThrowError(luaState, "register_table: can not find superclass '" + superclassName + "'");
return 0;
}
// Creates and pushes the object in the stack, setting
// it as the metatable of the first argument
object obj = CodeGeneration.Instance.GetClassInstance(klass, luaTable);
PushObject(luaState, obj, "luaNet_metatable");
luaState.NewTable();
luaState.PushString("__index");
luaState.PushCopy(-3);;
luaState.SetTable(-3);
luaState.PushString("__newindex");
luaState.PushCopy(-3);
luaState.SetTable(-3);
luaState.SetMetaTable(1);
// Pushes the object again, this time as the base field
// of the table and with the luaNet_searchbase metatable
luaState.PushString("base");
int index = AddObject(obj);
PushNewObject(luaState, obj, index, "luaNet_searchbase");
luaState.RawSet(1);
return 0; return 0;
} }
...@@ -443,36 +447,32 @@ namespace NLua ...@@ -443,36 +447,32 @@ namespace NLua
private int UnregisterTableInternal(LuaState luaState) private int UnregisterTableInternal(LuaState luaState)
{ {
try
if (!luaState.GetMetaTable(1))
{ {
if (luaState.GetMetaTable(1)) ThrowError(luaState, "unregister_table: arg is not valid table");
{ return 0;
luaState.PushString("__index"); }
luaState.GetTable(-2);
object obj = GetRawNetObject(luaState, -1);
if (obj == null) luaState.PushString("__index");
ThrowError(luaState, "unregister_table: arg is not valid table"); luaState.GetTable(-2);
object obj = GetRawNetObject(luaState, -1);
var luaTableField = obj.GetType().GetField("__luaInterface_luaTable"); if (obj == null)
ThrowError(luaState, "unregister_table: arg is not valid table");
if (luaTableField == null) var luaTableField = obj.GetType().GetField("__luaInterface_luaTable");
ThrowError(luaState, "unregister_table: arg is not valid table");
luaTableField.SetValue(obj, null); if (luaTableField == null)
luaState.PushNil(); ThrowError(luaState, "unregister_table: arg is not valid table");
luaState.SetMetaTable(1);
luaState.PushString("base"); // ReSharper disable once PossibleNullReferenceException
luaState.PushNil(); luaTableField.SetValue(obj, null);
luaState.SetTable(1); luaState.PushNil();
} luaState.SetMetaTable(1);
else luaState.PushString("base");
ThrowError(luaState, "unregister_table: arg is not valid table"); luaState.PushNil();
} luaState.SetTable(1);
catch (Exception e)
{
ThrowError(luaState, e.Message);
}
return 0; return 0;
} }
...@@ -499,7 +499,7 @@ namespace NLua ...@@ -499,7 +499,7 @@ namespace NLua
if (udata != -1) if (udata != -1)
{ {
klass = (ProxyType)objects[udata]; klass = (ProxyType)_objects[udata];
target = null; target = null;
} }
else else
...@@ -527,7 +527,7 @@ namespace NLua ...@@ -527,7 +527,7 @@ namespace NLua
var method = klass.GetMethod(methodName, BindingFlags.Public | BindingFlags.Static | var method = klass.GetMethod(methodName, BindingFlags.Public | BindingFlags.Static |
BindingFlags.Instance, signature); BindingFlags.Instance, signature);
var wrapper = new LuaMethodWrapper(this, target, klass, method); var wrapper = new LuaMethodWrapper(this, target, klass, method);
LuaNativeFunction invokeDelegate = wrapper.invokeFunction; LuaNativeFunction invokeDelegate = wrapper.InvokeFunction;
PushFunction(luaState, invokeDelegate); PushFunction(luaState, invokeDelegate);
} }
catch (Exception e) catch (Exception e)
...@@ -559,7 +559,7 @@ namespace NLua ...@@ -559,7 +559,7 @@ namespace NLua
int udata = luaState.CheckUObject(1, "luaNet_class"); int udata = luaState.CheckUObject(1, "luaNet_class");
if (udata != -1) if (udata != -1)
klass = (ProxyType)objects[udata]; klass = (ProxyType)_objects[udata];
if (klass == null) if (klass == null)
ThrowError(luaState, "get_constructor_bysig: first arg is invalid type reference"); ThrowError(luaState, "get_constructor_bysig: first arg is invalid type reference");
...@@ -573,7 +573,7 @@ namespace NLua ...@@ -573,7 +573,7 @@ namespace NLua
{ {
ConstructorInfo constructor = klass.UnderlyingSystemType.GetConstructor(signature); ConstructorInfo constructor = klass.UnderlyingSystemType.GetConstructor(signature);
var wrapper = new LuaMethodWrapper(this, null, klass, constructor); var wrapper = new LuaMethodWrapper(this, null, klass, constructor);
var invokeDelegate = wrapper.invokeFunction; var invokeDelegate = wrapper.InvokeFunction;
PushFunction(luaState, invokeDelegate); PushFunction(luaState, invokeDelegate);
} }
catch (Exception e) catch (Exception e)
...@@ -617,7 +617,7 @@ namespace NLua ...@@ -617,7 +617,7 @@ namespace NLua
} }
// Object already in the list of Lua objects? Push the stored reference. // Object already in the list of Lua objects? Push the stored reference.
bool found = (!o.GetType().IsValueType || o.GetType().IsEnum) && objectsBackMap.TryGetValue(o, out index); bool found = (!o.GetType().IsValueType || o.GetType().IsEnum) && _objectsBackMap.TryGetValue(o, out index);
if (found) if (found)
{ {
...@@ -785,7 +785,7 @@ namespace NLua ...@@ -785,7 +785,7 @@ namespace NLua
internal void CollectObject(int udata) internal void CollectObject(int udata)
{ {
object o; object o;
bool found = objects.TryGetValue(udata, out o); bool found = _objects.TryGetValue(udata, out o);
// The other variant of collectObject might have gotten here first, in that case we will silently ignore the missing entry // The other variant of collectObject might have gotten here first, in that case we will silently ignore the missing entry
if (found) if (found)
...@@ -795,26 +795,23 @@ namespace NLua ...@@ -795,26 +795,23 @@ namespace NLua
/// <summary> /// <summary>
/// Given an object reference, remove it from our maps /// Given an object reference, remove it from our maps
/// </summary> /// </summary>
/// <param name = "o"></param>
/// <param name = "udata"></param> /// <param name = "udata"></param>
private void CollectObject(object o, int udata) private void CollectObject(object o, int udata)
{ {
objects.Remove(udata); _objects.Remove(udata);
#if NETFX_CORE
if (!o.GetType ().GetTypeInfo ().IsValueType || o.GetType().GetTypeInfo().IsEnum)
#else
if (!o.GetType().IsValueType || o.GetType().IsEnum) if (!o.GetType().IsValueType || o.GetType().IsEnum)
#endif _objectsBackMap.Remove(o);
objectsBackMap.Remove(o);
} }
private int AddObject(object obj) private int AddObject(object obj)
{ {
// New object: inserts it in the list // New object: inserts it in the list
int index = nextObj++; int index = nextObj++;
objects[index] = obj; _objects[index] = obj;
if (!obj.GetType().IsValueType || obj.GetType().IsEnum) if (!obj.GetType().IsValueType || obj.GetType().IsEnum)
objectsBackMap[obj] = index; _objectsBackMap[obj] = index;
return index; return index;
} }
...@@ -829,32 +826,22 @@ namespace NLua ...@@ -829,32 +826,22 @@ namespace NLua
switch (type) switch (type)
{ {
case LuaType.Number: case LuaType.Number:
{
return luaState.ToNumber(index); return luaState.ToNumber(index);
}
case LuaType.String: case LuaType.String:
{
return luaState.ToString(index); return luaState.ToString(index);
}
case LuaType.Boolean: case LuaType.Boolean:
{
return luaState.ToBoolean(index); return luaState.ToBoolean(index);
}
case LuaType.Table: case LuaType.Table:
{
return GetTable(luaState, index); return GetTable(luaState, index);
}
case LuaType.Function: case LuaType.Function:
{
return GetFunction(luaState, index); return GetFunction(luaState, index);
}
case LuaType.UserData: case LuaType.UserData:
{ {
int udata = luaState.ToNetObject(index, Tag); int udata = luaState.ToNetObject(index, Tag);
return udata != -1 ? objects[udata] : GetUserData(luaState, index); return udata != -1 ? _objects[udata] : GetUserData(luaState, index);
} }
default: default:
return null; return null;
} }
} }
...@@ -888,7 +875,6 @@ namespace NLua ...@@ -888,7 +875,6 @@ namespace NLua
internal LuaFunction GetFunction(LuaState luaState, int index) internal LuaFunction GetFunction(LuaState luaState, int index)
{ {
luaState.PushCopy(index); luaState.PushCopy(index);
var x = luaState.Type(1);
int reference = luaState.Ref(LuaRegistry.Index); int reference = luaState.Ref(LuaRegistry.Index);
if (reference == -1) if (reference == -1)
return null; return null;
...@@ -902,7 +888,7 @@ namespace NLua ...@@ -902,7 +888,7 @@ namespace NLua
internal object GetNetObject(LuaState luaState, int index) internal object GetNetObject(LuaState luaState, int index)
{ {
int idx = luaState.ToNetObject(index, Tag); int idx = luaState.ToNetObject(index, Tag);
return idx != -1 ? objects[idx] : null; return idx != -1 ? _objects[idx] : null;
} }
/* /*
...@@ -912,7 +898,7 @@ namespace NLua ...@@ -912,7 +898,7 @@ namespace NLua
internal object GetRawNetObject(LuaState luaState, int index) internal object GetRawNetObject(LuaState luaState, int index)
{ {
int udata = luaState.RawNetObj(index); int udata = luaState.RawNetObj(index);
return udata != -1 ? objects[udata] : null; return udata != -1 ? _objects[udata] : null;
} }
...@@ -926,15 +912,13 @@ namespace NLua ...@@ -926,15 +912,13 @@ namespace NLua
if (oldTop == newTop) if (oldTop == newTop)
return null; return null;
else
{
var returnValues = new List<object>();
for (int i = oldTop + 1; i <= newTop; i++)
returnValues.Add(GetObject(luaState, i));
luaState.SetTop(oldTop); var returnValues = new List<object>();
return returnValues.ToArray(); for (int i = oldTop + 1; i <= newTop; i++)
} returnValues.Add(GetObject(luaState, i));
luaState.SetTop(oldTop);
return returnValues.ToArray();
} }
/* /*
...@@ -1030,9 +1014,9 @@ namespace NLua ...@@ -1030,9 +1014,9 @@ namespace NLua
return metaFunctions.MatchParameters(luaState, method, ref methodCache); return metaFunctions.MatchParameters(luaState, method, ref methodCache);
} }
internal Array TableToArray(Func<int, object> luaParamValue, Type paramArrayType, int startIndex, int count) internal Array TableToArray(LuaState luaState, ExtractValue extractValue, Type paramArrayType, int startIndex, int count)
{ {
return metaFunctions.TableToArray(luaParamValue, paramArrayType, startIndex, count); return metaFunctions.TableToArray(luaState, extractValue, paramArrayType, ref startIndex, count);
} }
private Type TypeOf(LuaState luaState, int idx) private Type TypeOf(LuaState luaState, int idx)
...@@ -1041,7 +1025,7 @@ namespace NLua ...@@ -1041,7 +1025,7 @@ namespace NLua
if (udata == -1) if (udata == -1)
return null; return null;
var pt = (ProxyType)objects[udata]; var pt = (ProxyType)_objects[udata];
return pt.UnderlyingSystemType; return pt.UnderlyingSystemType;
} }
......
using System; using System;
using System.Collections.Concurrent; using System.Collections.Concurrent;
using System.Diagnostics;
using LuaState = KeraLua.Lua; using LuaState = KeraLua.Lua;
namespace NLua namespace NLua
{ {
internal class ObjectTranslatorPool internal class ObjectTranslatorPool
{ {
private static volatile ObjectTranslatorPool instance = new ObjectTranslatorPool(); private static volatile ObjectTranslatorPool _instance = new ObjectTranslatorPool();
private ConcurrentDictionary<LuaState, ObjectTranslator> translators = new ConcurrentDictionary<LuaState, ObjectTranslator>(); private ConcurrentDictionary<LuaState, ObjectTranslator> translators = new ConcurrentDictionary<LuaState, ObjectTranslator>();
public static ObjectTranslatorPool Instance { public static ObjectTranslatorPool Instance => _instance;
get
{
return instance;
}
}
public ObjectTranslatorPool()
{
}
public void Add(LuaState luaState, ObjectTranslator translator) public void Add(LuaState luaState, ObjectTranslator translator)
{ {
......
...@@ -8,11 +8,11 @@ namespace NLua ...@@ -8,11 +8,11 @@ namespace NLua
/// </summary> /// </summary>
public class ProxyType public class ProxyType
{ {
private Type proxy; private readonly Type _proxy;
public ProxyType(Type proxy) public ProxyType(Type proxy)
{ {
this.proxy = proxy; _proxy = proxy;
} }
/// <summary> /// <summary>
...@@ -24,36 +24,30 @@ namespace NLua ...@@ -24,36 +24,30 @@ namespace NLua
return "ProxyType(" + UnderlyingSystemType + ")"; return "ProxyType(" + UnderlyingSystemType + ")";
} }
public Type UnderlyingSystemType { public Type UnderlyingSystemType => _proxy;
get { return proxy; }
}
public override bool Equals(object obj) public override bool Equals(object obj)
{ {
if (obj is Type) if (obj is Type)
return proxy.Equals((Type)obj); return _proxy == (Type)obj;
if (obj is ProxyType) if (obj is ProxyType)
return proxy.Equals(((ProxyType)obj).UnderlyingSystemType); return _proxy == ((ProxyType)obj).UnderlyingSystemType;
return proxy.Equals(obj); return _proxy.Equals(obj);
} }
public override int GetHashCode() public override int GetHashCode()
{ {
return proxy.GetHashCode(); return _proxy.GetHashCode();
} }
public MemberInfo[] GetMember(string name, BindingFlags bindingAttr) public MemberInfo[] GetMember(string name, BindingFlags bindingAttr)
{ {
return proxy.GetMember(name, bindingAttr); return _proxy.GetMember(name, bindingAttr);
} }
public MethodInfo GetMethod(string name, BindingFlags bindingAttr, Type[] signature) public MethodInfo GetMethod(string name, BindingFlags bindingAttr, Type[] signature)
{ {
#if NETFX_CORE return _proxy.GetMethod(name, bindingAttr, null, signature, null);
return proxy.GetMethod (name, bindingAttr, signature);
#else
return proxy.GetMethod(name, bindingAttr, null, signature, null);
#endif
} }
} }
} }
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment