Commit 19e9e632 authored by Megax's avatar Megax
Browse files

* Tudomasom szerinti legutolso LuaInterfacekerul feltoltesre majd atalakitasra.

parent 00eddcac
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Reflection; using System.Reflection;
using LuaWrap; using Lua511;
namespace LuaInterface namespace LuaInterface
{ {
...@@ -20,130 +20,149 @@ namespace LuaInterface ...@@ -20,130 +20,149 @@ namespace LuaInterface
public CheckType(ObjectTranslator translator) public CheckType(ObjectTranslator translator)
{ {
this.translator = translator; this.translator = translator;
extractValues.Add(typeof(object).TypeHandle.Value.ToInt64(), new ExtractValue(getAsObject)); extractValues.Add(typeof(object).TypeHandle.Value.ToInt64(), new ExtractValue(getAsObject));
extractValues.Add(typeof(sbyte).TypeHandle.Value.ToInt64(), new ExtractValue(getAsSbyte)); extractValues.Add(typeof(sbyte).TypeHandle.Value.ToInt64(), new ExtractValue(getAsSbyte));
extractValues.Add(typeof(byte).TypeHandle.Value.ToInt64(), new ExtractValue(getAsByte)); extractValues.Add(typeof(byte).TypeHandle.Value.ToInt64(), new ExtractValue(getAsByte));
extractValues.Add(typeof(short).TypeHandle.Value.ToInt64(), new ExtractValue(getAsShort)); extractValues.Add(typeof(short).TypeHandle.Value.ToInt64(), new ExtractValue(getAsShort));
extractValues.Add(typeof(ushort).TypeHandle.Value.ToInt64(), new ExtractValue(getAsUshort)); extractValues.Add(typeof(ushort).TypeHandle.Value.ToInt64(), new ExtractValue(getAsUshort));
extractValues.Add(typeof(int).TypeHandle.Value.ToInt64(), new ExtractValue(getAsInt)); extractValues.Add(typeof(int).TypeHandle.Value.ToInt64(), new ExtractValue(getAsInt));
extractValues.Add(typeof(uint).TypeHandle.Value.ToInt64(), new ExtractValue(getAsUint)); extractValues.Add(typeof(uint).TypeHandle.Value.ToInt64(), new ExtractValue(getAsUint));
extractValues.Add(typeof(long).TypeHandle.Value.ToInt64(), new ExtractValue(getAsLong)); extractValues.Add(typeof(long).TypeHandle.Value.ToInt64(), new ExtractValue(getAsLong));
extractValues.Add(typeof(ulong).TypeHandle.Value.ToInt64(), new ExtractValue(getAsUlong)); extractValues.Add(typeof(ulong).TypeHandle.Value.ToInt64(), new ExtractValue(getAsUlong));
extractValues.Add(typeof(double).TypeHandle.Value.ToInt64(), new ExtractValue(getAsDouble)); extractValues.Add(typeof(double).TypeHandle.Value.ToInt64(), new ExtractValue(getAsDouble));
extractValues.Add(typeof(char).TypeHandle.Value.ToInt64(), new ExtractValue(getAsChar)); extractValues.Add(typeof(char).TypeHandle.Value.ToInt64(), new ExtractValue(getAsChar));
extractValues.Add(typeof(float).TypeHandle.Value.ToInt64(), new ExtractValue(getAsFloat)); extractValues.Add(typeof(float).TypeHandle.Value.ToInt64(), new ExtractValue(getAsFloat));
extractValues.Add(typeof(decimal).TypeHandle.Value.ToInt64(), new ExtractValue(getAsDecimal)); extractValues.Add(typeof(decimal).TypeHandle.Value.ToInt64(), new ExtractValue(getAsDecimal));
extractValues.Add(typeof(bool).TypeHandle.Value.ToInt64(), new ExtractValue(getAsBoolean)); extractValues.Add(typeof(bool).TypeHandle.Value.ToInt64(), new ExtractValue(getAsBoolean));
extractValues.Add(typeof(string).TypeHandle.Value.ToInt64(), new ExtractValue(getAsString)); extractValues.Add(typeof(string).TypeHandle.Value.ToInt64(), new ExtractValue(getAsString));
extractValues.Add(typeof(LuaFunction).TypeHandle.Value.ToInt64(), new ExtractValue(getAsFunction)); extractValues.Add(typeof(LuaFunction).TypeHandle.Value.ToInt64(), new ExtractValue(getAsFunction));
extractValues.Add(typeof(LuaTable).TypeHandle.Value.ToInt64(), new ExtractValue(getAsTable)); extractValues.Add(typeof(LuaTable).TypeHandle.Value.ToInt64(), new ExtractValue(getAsTable));
extractValues.Add(typeof(LuaUserData).TypeHandle.Value.ToInt64(), new ExtractValue(getAsUserdata)); extractValues.Add(typeof(LuaUserData).TypeHandle.Value.ToInt64(), new ExtractValue(getAsUserdata));
extractNetObject = new ExtractValue(getAsNetObject); extractNetObject = new ExtractValue(getAsNetObject);
} }
/* /*
* Checks if the value at Lua stack index stackPos matches paramType, * Checks if the value at Lua stack index stackPos matches paramType,
* returning a conversion function if it does and null otherwise. * returning a conversion function if it does and null otherwise.
*/ */
internal ExtractValue getExtractor(IReflect paramType) internal ExtractValue getExtractor(IReflect paramType)
{ {
return getExtractor(paramType.UnderlyingSystemType); return getExtractor(paramType.UnderlyingSystemType);
} }
internal ExtractValue getExtractor(Type paramType) internal ExtractValue getExtractor(Type paramType)
{ {
if(paramType.IsByRef) paramType=paramType.GetElementType(); if(paramType.IsByRef) paramType=paramType.GetElementType();
long runtimeHandleValue = paramType.TypeHandle.Value.ToInt64(); long runtimeHandleValue = paramType.TypeHandle.Value.ToInt64();
if(extractValues.ContainsKey(runtimeHandleValue)) if(extractValues.ContainsKey(runtimeHandleValue))
return extractValues[runtimeHandleValue]; return extractValues[runtimeHandleValue];
else else
return extractNetObject; return extractNetObject;
} }
internal ExtractValue checkType(KopiLua.Lua.lua_State luaState,int stackPos,Type paramType) internal ExtractValue checkType(IntPtr luaState,int stackPos,Type paramType)
{ {
LuaType luatype = KopiLua.Lua.lua_type(luaState, stackPos).ToLuaType(); LuaTypes luatype = LuaDLL.lua_type(luaState, stackPos);
if(paramType.IsByRef) paramType=paramType.GetElementType(); if(paramType.IsByRef) paramType=paramType.GetElementType();
Type underlyingType = Nullable.GetUnderlyingType(paramType); Type underlyingType = Nullable.GetUnderlyingType(paramType);
if (underlyingType != null) if (underlyingType != null)
{ {
paramType = underlyingType; // Silently convert nullable types to their non null requics paramType = underlyingType; // Silently convert nullable types to their non null requics
} }
long runtimeHandleValue = paramType.TypeHandle.Value.ToInt64(); long runtimeHandleValue = paramType.TypeHandle.Value.ToInt64();
if (paramType.Equals(typeof(object))) if (paramType.Equals(typeof(object)))
return extractValues[runtimeHandleValue]; return extractValues[runtimeHandleValue];
if (KopiLua.Lua.lua_isnumber(luaState, stackPos).ToBoolean()) //CP: Added support for generic parameters
return extractValues[runtimeHandleValue]; if (paramType.IsGenericParameter)
{
if (luatype == LuaTypes.LUA_TBOOLEAN)
return extractValues[typeof(bool).TypeHandle.Value.ToInt64()];
else if (luatype == LuaTypes.LUA_TSTRING)
return extractValues[typeof(string).TypeHandle.Value.ToInt64()];
else if (luatype == LuaTypes.LUA_TTABLE)
return extractValues[typeof(LuaTable).TypeHandle.Value.ToInt64()];
else if (luatype == LuaTypes.LUA_TUSERDATA)
return extractValues[typeof(object).TypeHandle.Value.ToInt64()];
else if (luatype == LuaTypes.LUA_TFUNCTION)
return extractValues[typeof(LuaFunction).TypeHandle.Value.ToInt64()];
else if (luatype == LuaTypes.LUA_TNUMBER)
return extractValues[typeof(double).TypeHandle.Value.ToInt64()];
else
;//an unsupported type was encountered
}
if (paramType == typeof(bool)) if (LuaDLL.lua_isnumber(luaState, stackPos))
{ return extractValues[runtimeHandleValue];
if (KopiLua.Lua.lua_isboolean(luaState, stackPos))
if (paramType == typeof(bool))
{
if (LuaDLL.lua_isboolean(luaState, stackPos))
return extractValues[runtimeHandleValue]; return extractValues[runtimeHandleValue];
} }
else if (paramType == typeof(string)) else if (paramType == typeof(string))
{ {
if (KopiLua.Lua.lua_isstring(luaState, stackPos).ToBoolean()) if (LuaDLL.lua_isstring(luaState, stackPos))
return extractValues[runtimeHandleValue]; return extractValues[runtimeHandleValue];
else if (luatype == LuaType.Nil) else if (luatype == LuaTypes.LUA_TNIL)
return extractNetObject; // kevinh - silently convert nil to a null string pointer return extractNetObject; // kevinh - silently convert nil to a null string pointer
} }
else if (paramType == typeof(LuaTable)) else if (paramType == typeof(LuaTable))
{ {
if (luatype == LuaType.Table) if (luatype == LuaTypes.LUA_TTABLE)
return extractValues[runtimeHandleValue]; return extractValues[runtimeHandleValue];
} }
else if (paramType == typeof(LuaUserData)) else if (paramType == typeof(LuaUserData))
{ {
if (luatype == LuaType.UserData) if (luatype == LuaTypes.LUA_TUSERDATA)
return extractValues[runtimeHandleValue]; return extractValues[runtimeHandleValue];
} }
else if (paramType == typeof(LuaFunction)) else if (paramType == typeof(LuaFunction))
{ {
if (luatype == LuaType.Function) if (luatype == LuaTypes.LUA_TFUNCTION)
return extractValues[runtimeHandleValue]; return extractValues[runtimeHandleValue];
} }
else if (typeof(Delegate).IsAssignableFrom(paramType) && luatype == LuaType.Function) else if (typeof(Delegate).IsAssignableFrom(paramType) && luatype == LuaTypes.LUA_TFUNCTION)
{ {
return new ExtractValue(new DelegateGenerator(translator, paramType).extractGenerated); return new ExtractValue(new DelegateGenerator(translator, paramType).extractGenerated);
} }
else if (paramType.IsInterface && luatype == LuaType.Table) else if (paramType.IsInterface && luatype == LuaTypes.LUA_TTABLE)
{ {
return new ExtractValue(new ClassGenerator(translator, paramType).extractGenerated); return new ExtractValue(new ClassGenerator(translator, paramType).extractGenerated);
} }
else if ((paramType.IsInterface || paramType.IsClass) && luatype == LuaType.Nil) else if ((paramType.IsInterface || paramType.IsClass) && luatype == LuaTypes.LUA_TNIL)
{ {
// kevinh - allow nil to be silently converted to null - extractNetObject will return null when the item ain't found // kevinh - allow nil to be silently converted to null - extractNetObject will return null when the item ain't found
return extractNetObject; return extractNetObject;
} }
else if (KopiLua.Lua.lua_type(luaState, stackPos).ToLuaType() == LuaType.Table) else if (LuaDLL.lua_type(luaState, stackPos) == LuaTypes.LUA_TTABLE)
{ {
if (KopiLua.Lua.luaL_getmetafield(luaState, stackPos, "__index").ToBoolean()) if (LuaDLL.luaL_getmetafield(luaState, stackPos, "__index"))
{ {
object obj = translator.getNetObject(luaState, -1); object obj = translator.getNetObject(luaState, -1);
KopiLua.Lua.lua_settop(luaState, -2); LuaDLL.lua_settop(luaState, -2);
if (obj != null && paramType.IsAssignableFrom(obj.GetType())) if (obj != null && paramType.IsAssignableFrom(obj.GetType()))
return extractNetObject; return extractNetObject;
} }
else else
return null; return null;
} }
else else
{ {
object obj = translator.getNetObject(luaState, stackPos); object obj = translator.getNetObject(luaState, stackPos);
if (obj != null && paramType.IsAssignableFrom(obj.GetType())) if (obj != null && paramType.IsAssignableFrom(obj.GetType()))
return extractNetObject; return extractNetObject;
} }
return null; return null;
} }
/* /*
...@@ -151,136 +170,136 @@ namespace LuaInterface ...@@ -151,136 +170,136 @@ namespace LuaInterface
* index stackPos as the desired type if it can, or null * index stackPos as the desired type if it can, or null
* otherwise. * otherwise.
*/ */
private object getAsSbyte(KopiLua.Lua.lua_State luaState,int stackPos) private object getAsSbyte(IntPtr luaState,int stackPos)
{ {
sbyte retVal=(sbyte)KopiLua.Lua.lua_tonumber(luaState,stackPos); sbyte retVal=(sbyte)LuaDLL.lua_tonumber(luaState,stackPos);
if(retVal==0 && !KopiLua.Lua.lua_isnumber(luaState,stackPos).ToBoolean()) return null; if(retVal==0 && !LuaDLL.lua_isnumber(luaState,stackPos)) return null;
return retVal; return retVal;
} }
private object getAsByte(KopiLua.Lua.lua_State luaState,int stackPos) private object getAsByte(IntPtr luaState,int stackPos)
{ {
byte retVal=(byte)KopiLua.Lua.lua_tonumber(luaState,stackPos); byte retVal=(byte)LuaDLL.lua_tonumber(luaState,stackPos);
if(retVal==0 && !KopiLua.Lua.lua_isnumber(luaState,stackPos).ToBoolean()) return null; if(retVal==0 && !LuaDLL.lua_isnumber(luaState,stackPos)) return null;
return retVal; return retVal;
} }
private object getAsShort(KopiLua.Lua.lua_State luaState,int stackPos) private object getAsShort(IntPtr luaState,int stackPos)
{ {
short retVal=(short)KopiLua.Lua.lua_tonumber(luaState,stackPos); short retVal=(short)LuaDLL.lua_tonumber(luaState,stackPos);
if(retVal==0 && !KopiLua.Lua.lua_isnumber(luaState,stackPos).ToBoolean()) return null; if(retVal==0 && !LuaDLL.lua_isnumber(luaState,stackPos)) return null;
return retVal; return retVal;
} }
private object getAsUshort(KopiLua.Lua.lua_State luaState,int stackPos) private object getAsUshort(IntPtr luaState,int stackPos)
{ {
ushort retVal=(ushort)KopiLua.Lua.lua_tonumber(luaState,stackPos); ushort retVal=(ushort)LuaDLL.lua_tonumber(luaState,stackPos);
if(retVal==0 && !KopiLua.Lua.lua_isnumber(luaState,stackPos).ToBoolean()) return null; if(retVal==0 && !LuaDLL.lua_isnumber(luaState,stackPos)) return null;
return retVal; return retVal;
} }
private object getAsInt(KopiLua.Lua.lua_State luaState,int stackPos) private object getAsInt(IntPtr luaState,int stackPos)
{ {
int retVal=(int)KopiLua.Lua.lua_tonumber(luaState,stackPos); int retVal=(int)LuaDLL.lua_tonumber(luaState,stackPos);
if(retVal==0 && !KopiLua.Lua.lua_isnumber(luaState,stackPos).ToBoolean()) return null; if(retVal==0 && !LuaDLL.lua_isnumber(luaState,stackPos)) return null;
return retVal; return retVal;
} }
private object getAsUint(KopiLua.Lua.lua_State luaState,int stackPos) private object getAsUint(IntPtr luaState,int stackPos)
{ {
uint retVal=(uint)KopiLua.Lua.lua_tonumber(luaState,stackPos); uint retVal=(uint)LuaDLL.lua_tonumber(luaState,stackPos);
if(retVal==0 && !KopiLua.Lua.lua_isnumber(luaState,stackPos).ToBoolean()) return null; if(retVal==0 && !LuaDLL.lua_isnumber(luaState,stackPos)) return null;
return retVal; return retVal;
} }
private object getAsLong(KopiLua.Lua.lua_State luaState,int stackPos) private object getAsLong(IntPtr luaState,int stackPos)
{ {
long retVal=(long)KopiLua.Lua.lua_tonumber(luaState,stackPos); long retVal=(long)LuaDLL.lua_tonumber(luaState,stackPos);
if(retVal==0 && !KopiLua.Lua.lua_isnumber(luaState,stackPos).ToBoolean()) return null; if(retVal==0 && !LuaDLL.lua_isnumber(luaState,stackPos)) return null;
return retVal; return retVal;
} }
private object getAsUlong(KopiLua.Lua.lua_State luaState,int stackPos) private object getAsUlong(IntPtr luaState,int stackPos)
{ {
ulong retVal=(ulong)KopiLua.Lua.lua_tonumber(luaState,stackPos); ulong retVal=(ulong)LuaDLL.lua_tonumber(luaState,stackPos);
if(retVal==0 && !KopiLua.Lua.lua_isnumber(luaState,stackPos).ToBoolean()) return null; if(retVal==0 && !LuaDLL.lua_isnumber(luaState,stackPos)) return null;
return retVal; return retVal;
} }
private object getAsDouble(KopiLua.Lua.lua_State luaState,int stackPos) private object getAsDouble(IntPtr luaState,int stackPos)
{ {
double retVal=KopiLua.Lua.lua_tonumber(luaState,stackPos); double retVal=LuaDLL.lua_tonumber(luaState,stackPos);
if(retVal==0 && !KopiLua.Lua.lua_isnumber(luaState,stackPos).ToBoolean()) return null; if(retVal==0 && !LuaDLL.lua_isnumber(luaState,stackPos)) return null;
return retVal; return retVal;
} }
private object getAsChar(KopiLua.Lua.lua_State luaState,int stackPos) private object getAsChar(IntPtr luaState,int stackPos)
{ {
char retVal=(char)KopiLua.Lua.lua_tonumber(luaState,stackPos); char retVal=(char)LuaDLL.lua_tonumber(luaState,stackPos);
if(retVal==0 && !KopiLua.Lua.lua_isnumber(luaState,stackPos).ToBoolean()) return null; if(retVal==0 && !LuaDLL.lua_isnumber(luaState,stackPos)) return null;
return retVal; return retVal;
} }
private object getAsFloat(KopiLua.Lua.lua_State luaState,int stackPos) private object getAsFloat(IntPtr luaState,int stackPos)
{ {
float retVal=(float)KopiLua.Lua.lua_tonumber(luaState,stackPos); float retVal=(float)LuaDLL.lua_tonumber(luaState,stackPos);
if(retVal==0 && !KopiLua.Lua.lua_isnumber(luaState,stackPos).ToBoolean()) return null; if(retVal==0 && !LuaDLL.lua_isnumber(luaState,stackPos)) return null;
return retVal; return retVal;
} }
private object getAsDecimal(KopiLua.Lua.lua_State luaState,int stackPos) private object getAsDecimal(IntPtr luaState,int stackPos)
{ {
decimal retVal=(decimal)KopiLua.Lua.lua_tonumber(luaState,stackPos); decimal retVal=(decimal)LuaDLL.lua_tonumber(luaState,stackPos);
if(retVal==0 && !KopiLua.Lua.lua_isnumber(luaState,stackPos).ToBoolean()) return null; if(retVal==0 && !LuaDLL.lua_isnumber(luaState,stackPos)) return null;
return retVal; return retVal;
} }
private object getAsBoolean(KopiLua.Lua.lua_State luaState,int stackPos) private object getAsBoolean(IntPtr luaState,int stackPos)
{ {
return KopiLua.Lua.lua_toboolean(luaState,stackPos); return LuaDLL.lua_toboolean(luaState,stackPos);
} }
private object getAsString(KopiLua.Lua.lua_State luaState,int stackPos) private object getAsString(IntPtr luaState,int stackPos)
{ {
string retVal=KopiLua.Lua.lua_tostring(luaState,stackPos).ToString(); string retVal=LuaDLL.lua_tostring(luaState,stackPos);
if(retVal==string.Empty && !KopiLua.Lua.lua_isstring(luaState,stackPos).ToBoolean()) return null; if(retVal=="" && !LuaDLL.lua_isstring(luaState,stackPos)) return null;
return retVal; return retVal;
} }
private object getAsTable(KopiLua.Lua.lua_State luaState,int stackPos) private object getAsTable(IntPtr luaState,int stackPos)
{ {
return translator.getTable(luaState,stackPos); return translator.getTable(luaState,stackPos);
} }
private object getAsFunction(KopiLua.Lua.lua_State luaState,int stackPos) private object getAsFunction(IntPtr luaState,int stackPos)
{ {
return translator.getFunction(luaState,stackPos); return translator.getFunction(luaState,stackPos);
} }
private object getAsUserdata(KopiLua.Lua.lua_State luaState,int stackPos) private object getAsUserdata(IntPtr luaState,int stackPos)
{ {
return translator.getUserData(luaState,stackPos); return translator.getUserData(luaState,stackPos);
} }
public object getAsObject(KopiLua.Lua.lua_State luaState,int stackPos) public object getAsObject(IntPtr luaState,int stackPos)
{ {
if(KopiLua.Lua.lua_type(luaState,stackPos).ToLuaType()==LuaType.Table) if(LuaDLL.lua_type(luaState,stackPos)==LuaTypes.LUA_TTABLE)
{ {
if(KopiLua.Lua.luaL_getmetafield(luaState,stackPos,"__index").ToBoolean()) if(LuaDLL.luaL_getmetafield(luaState,stackPos,"__index"))
{ {
if(LuaLib.luaL_checkmetatable(luaState,-1)) if(LuaDLL.luaL_checkmetatable(luaState,-1))
{ {
KopiLua.Lua.lua_insert(luaState,stackPos); LuaDLL.lua_insert(luaState,stackPos);
KopiLua.Lua.lua_remove(luaState,stackPos+1); LuaDLL.lua_remove(luaState,stackPos+1);
} }
else else
{ {
KopiLua.Lua.lua_settop(luaState,-2); LuaDLL.lua_settop(luaState,-2);
} }
} }
} }
object obj=translator.getObject(luaState,stackPos); object obj=translator.getObject(luaState,stackPos);
return obj; return obj;
} }
public object getAsNetObject(KopiLua.Lua.lua_State luaState,int stackPos) public object getAsNetObject(IntPtr luaState,int stackPos)
{ {
object obj=translator.getNetObject(luaState,stackPos); object obj=translator.getNetObject(luaState,stackPos);
if(obj==null && KopiLua.Lua.lua_type(luaState,stackPos).ToLuaType()==LuaType.Table) if(obj==null && LuaDLL.lua_type(luaState,stackPos)==LuaTypes.LUA_TTABLE)
{ {
if(KopiLua.Lua.luaL_getmetafield(luaState,stackPos,"__index").ToBoolean()) if(LuaDLL.luaL_getmetafield(luaState,stackPos,"__index"))
{ {
if(LuaLib.luaL_checkmetatable(luaState,-1)) if(LuaDLL.luaL_checkmetatable(luaState,-1))
{ {
KopiLua.Lua.lua_insert(luaState,stackPos); LuaDLL.lua_insert(luaState,stackPos);
KopiLua.Lua.lua_remove(luaState,stackPos+1); LuaDLL.lua_remove(luaState,stackPos+1);
obj=translator.getNetObject(luaState,stackPos); obj=translator.getNetObject(luaState,stackPos);
} }
else else
{ {
KopiLua.Lua.lua_settop(luaState,-2); LuaDLL.lua_settop(luaState,-2);
} }
} }
} }
......
...@@ -44,7 +44,7 @@ namespace LuaInterface ...@@ -44,7 +44,7 @@ namespace LuaInterface
this.translator=translator; this.translator=translator;
this.delegateType=delegateType; this.delegateType=delegateType;
} }
public object extractGenerated(KopiLua.Lua.lua_State luaState,int stackPos) public object extractGenerated(IntPtr luaState,int stackPos)
{ {
return CodeGeneration.Instance.GetDelegate(delegateType,translator.getFunction(luaState,stackPos)); return CodeGeneration.Instance.GetDelegate(delegateType,translator.getFunction(luaState,stackPos));
} }
...@@ -67,7 +67,7 @@ namespace LuaInterface ...@@ -67,7 +67,7 @@ namespace LuaInterface
this.translator=translator; this.translator=translator;
this.klass=klass; this.klass=klass;
} }
public object extractGenerated(KopiLua.Lua.lua_State luaState,int stackPos) public object extractGenerated(IntPtr luaState,int stackPos)
{ {
return CodeGeneration.Instance.GetClassInstance(klass,translator.getTable(luaState,stackPos)); return CodeGeneration.Instance.GetClassInstance(klass,translator.getTable(luaState,stackPos));
} }
...@@ -105,10 +105,11 @@ namespace LuaInterface ...@@ -105,10 +105,11 @@ namespace LuaInterface
private CodeGeneration() private CodeGeneration()
{ {
// Create an assembly name // Create an assembly name
assemblyName=new AssemblyName(); assemblyName=new AssemblyName( );
assemblyName.Name="LuaInterface_generatedcode"; assemblyName.Name="LuaInterface_generatedcode";
// Create a new assembly with one module. // Create a new assembly with one module.
newAssembly=Thread.GetDomain().DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run); newAssembly=Thread.GetDomain().DefineDynamicAssembly(
assemblyName, AssemblyBuilderAccess.Run);
newModule=newAssembly.DefineDynamicModule("LuaInterface_generatedcode"); newModule=newAssembly.DefineDynamicModule("LuaInterface_generatedcode");
} }
...@@ -148,7 +149,7 @@ namespace LuaInterface ...@@ -148,7 +149,7 @@ namespace LuaInterface
// Emits the IL for the method. It loads the arguments // Emits the IL for the method. It loads the arguments
// and calls the handleEvent method of the base class // and calls the handleEvent method of the base class
ILGenerator generator=handleMethod.GetILGenerator(); ILGenerator generator=handleMethod.GetILGenerator( );
generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Ldarg_0);
generator.Emit(OpCodes.Ldarg_1); generator.Emit(OpCodes.Ldarg_1);
generator.Emit(OpCodes.Ldarg_2); generator.Emit(OpCodes.Ldarg_2);
...@@ -201,7 +202,7 @@ namespace LuaInterface ...@@ -201,7 +202,7 @@ namespace LuaInterface
returnType,paramTypes); returnType,paramTypes);
// Generates the IL for the method // Generates the IL for the method
ILGenerator generator=delegateMethod.GetILGenerator(); ILGenerator generator=delegateMethod.GetILGenerator( );
generator.DeclareLocal(typeof(object[])); // original arguments generator.DeclareLocal(typeof(object[])); // original arguments
generator.DeclareLocal(typeof(object[])); // with out-only arguments removed generator.DeclareLocal(typeof(object[])); // with out-only arguments removed
...@@ -451,7 +452,7 @@ namespace LuaInterface ...@@ -451,7 +452,7 @@ namespace LuaInterface
if(myType.BaseType.Equals(typeof(object))) if(myType.BaseType.Equals(typeof(object)))
myType.DefineMethodOverride(methodImpl,method); myType.DefineMethodOverride(methodImpl,method);
ILGenerator generator=methodImpl.GetILGenerator(); ILGenerator generator=methodImpl.GetILGenerator( );
generator.DeclareLocal(typeof(object[])); // original arguments generator.DeclareLocal(typeof(object[])); // original arguments
generator.DeclareLocal(typeof(object[])); // with out-only arguments removed generator.DeclareLocal(typeof(object[])); // with out-only arguments removed
......
namespace LuaInterface namespace LuaInterface
{ {
using System; using System;
using System.IO; using System.IO;
using System.Collections; using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized; using System.Collections.Specialized;
using System.Reflection; using System.Reflection;
using System.Threading; using System.Threading;
using LuaWrap; using Lua511;
/* /*
* Main class of LuaInterface * Main class of LuaInterface
...@@ -20,8 +21,10 @@ namespace LuaInterface ...@@ -20,8 +21,10 @@ namespace LuaInterface
* - removed all Open*Lib() functions * - removed all Open*Lib() functions
* - all libs automatically open in the Lua class constructor (just assign nil to unwanted libs) * - all libs automatically open in the Lua class constructor (just assign nil to unwanted libs)
* */ * */
public class Lua : IDisposable [CLSCompliant(true)]
public class Lua : IDisposable
{ {
static string init_luanet = static string init_luanet =
"local metatable = {} \n"+ "local metatable = {} \n"+
"local import_type = luanet.import_type \n"+ "local import_type = luanet.import_type \n"+
...@@ -62,153 +65,214 @@ namespace LuaInterface ...@@ -62,153 +65,214 @@ namespace LuaInterface
"-- Preload the mscorlib assembly \n"+ "-- Preload the mscorlib assembly \n"+
"luanet.load_assembly(\"mscorlib\") \n"; "luanet.load_assembly(\"mscorlib\") \n";
readonly KopiLua.Lua.lua_State luaState; /*readonly */ IntPtr luaState;
ObjectTranslator translator; ObjectTranslator translator;
KopiLua.Lua.lua_CFunction panicCallback/*, lockCallback, unlockCallback*/; LuaCSFunction panicCallback, lockCallback, unlockCallback;
/// <summary> /// <summary>
/// Used to ensure multiple .net threads all get serialized by this single lock for access to the lua stack/objects /// Used to ensure multiple .net threads all get serialized by this single lock for access to the lua stack/objects
/// </summary> /// </summary>
object luaLock = new object(); object luaLock = new object();
public Lua() public Lua()
{ {
luaState = KopiLua.Lua.luaL_newstate(); // steffenj: Lua 5.1.1 API change (lua_open is gone) luaState = LuaDLL.luaL_newstate(); // steffenj: Lua 5.1.1 API change (lua_open is gone)
//KopiLua.Lua.luaopen_base(luaState); // steffenj: luaopen_* no longer used //LuaDLL.luaopen_base(luaState); // steffenj: luaopen_* no longer used
KopiLua.Lua.luaL_openlibs(luaState); // steffenj: Lua 5.1.1 API change (luaopen_base is gone, just open all libs right here) LuaDLL.luaL_openlibs(luaState); // steffenj: Lua 5.1.1 API change (luaopen_base is gone, just open all libs right here)
KopiLua.Lua.lua_pushstring(luaState, "LUAINTERFACE LOADED"); LuaDLL.lua_pushstring(luaState, "LUAINTERFACE LOADED");
KopiLua.Lua.lua_pushboolean(luaState, 1); LuaDLL.lua_pushboolean(luaState, true);
KopiLua.Lua.lua_settable(luaState, (int) PseudoIndex.Registry); LuaDLL.lua_settable(luaState, (int) LuaIndexes.LUA_REGISTRYINDEX);
KopiLua.Lua.lua_newtable(luaState); LuaDLL.lua_newtable(luaState);
KopiLua.Lua.lua_setglobal(luaState, "luanet"); LuaDLL.lua_setglobal(luaState, "luanet");
KopiLua.Lua.lua_pushvalue(luaState, (int)PseudoIndex.Globals); LuaDLL.lua_pushvalue(luaState, (int)LuaIndexes.LUA_GLOBALSINDEX);
KopiLua.Lua.lua_getglobal(luaState, "luanet"); LuaDLL.lua_getglobal(luaState, "luanet");
KopiLua.Lua.lua_pushstring(luaState, "getmetatable"); LuaDLL.lua_pushstring(luaState, "getmetatable");
KopiLua.Lua.lua_getglobal(luaState, "getmetatable"); LuaDLL.lua_getglobal(luaState, "getmetatable");
KopiLua.Lua.lua_settable(luaState, -3); LuaDLL.lua_settable(luaState, -3);
KopiLua.Lua.lua_replace(luaState, (int)PseudoIndex.Globals); LuaDLL.lua_replace(luaState, (int)LuaIndexes.LUA_GLOBALSINDEX);
translator=new ObjectTranslator(this,luaState); translator=new ObjectTranslator(this,luaState);
KopiLua.Lua.lua_replace(luaState, (int)PseudoIndex.Globals); LuaDLL.lua_replace(luaState, (int)LuaIndexes.LUA_GLOBALSINDEX);
LuaLib.luaL_dostring(luaState, Lua.init_luanet); // steffenj: lua_dostring renamed to luaL_dostring LuaDLL.luaL_dostring(luaState, Lua.init_luanet); // steffenj: lua_dostring renamed to luaL_dostring
// We need to keep this in a managed reference so the delegate doesn't get garbage collected // We need to keep this in a managed reference so the delegate doesn't get garbage collected
panicCallback = new KopiLua.Lua.lua_CFunction(PanicCallback); panicCallback = new LuaCSFunction(PanicCallback);
KopiLua.Lua.lua_atpanic(luaState, panicCallback); LuaDLL.lua_atpanic(luaState, panicCallback);
// KopiLua.Lua.lua_atlock(luaState, lockCallback = new CallbackFunction(LockCallback)); //LuaDLL.lua_atlock(luaState, lockCallback = new LuaCSFunction(LockCallback));
// KopiLua.Lua.lua_atunlock(luaState, unlockCallback = new CallbackFunction(UnlockCallback)); //LuaDLL.lua_atunlock(luaState, unlockCallback = new LuaCSFunction(UnlockCallback));
} }
/* private bool _StatePassed;
* CAUTION: LuaInterface.Lua instances can't share the same lua state!
*/ /*
public Lua(KopiLua.Lua.lua_State luaState) * CAUTION: LuaInterface.Lua instances can't share the same lua state!
{ */
//IntPtr lState = new IntPtr(luaState); public Lua(Int64 luaState)
KopiLua.Lua.lua_pushstring(luaState, "LUAINTERFACE LOADED"); {
KopiLua.Lua.lua_gettable(luaState, (int)PseudoIndex.Registry); IntPtr lState = new IntPtr(luaState);
if(KopiLua.Lua.lua_toboolean(luaState,-1).ToBoolean()) { LuaDLL.lua_pushstring(lState, "LUAINTERFACE LOADED");
KopiLua.Lua.lua_settop(luaState,-2); LuaDLL.lua_gettable(lState, (int)LuaIndexes.LUA_REGISTRYINDEX);
throw new LuaException("There is already a LuaInterface.Lua instance associated with this Lua state");
} else { if(LuaDLL.lua_toboolean(lState,-1))
KopiLua.Lua.lua_settop(luaState,-2); {
KopiLua.Lua.lua_pushstring(luaState, "LUAINTERFACE LOADED"); LuaDLL.lua_settop(lState,-2);
KopiLua.Lua.lua_pushboolean(luaState, 1); throw new LuaException("There is already a LuaInterface.Lua instance associated with this Lua state");
KopiLua.Lua.lua_settable(luaState, (int)PseudoIndex.Registry); }
this.luaState=luaState; else
KopiLua.Lua.lua_pushvalue(luaState, (int)PseudoIndex.Globals); {
KopiLua.Lua.lua_getglobal(luaState, "luanet"); LuaDLL.lua_settop(lState,-2);
KopiLua.Lua.lua_pushstring(luaState, "getmetatable"); LuaDLL.lua_pushstring(lState, "LUAINTERFACE LOADED");
KopiLua.Lua.lua_getglobal(luaState, "getmetatable"); LuaDLL.lua_pushboolean(lState, true);
KopiLua.Lua.lua_settable(luaState, -3); LuaDLL.lua_settable(lState, (int)LuaIndexes.LUA_REGISTRYINDEX);
KopiLua.Lua.lua_replace(luaState, (int)PseudoIndex.Globals); this.luaState=lState;
translator=new ObjectTranslator(this, this.luaState); LuaDLL.lua_pushvalue(lState, (int)LuaIndexes.LUA_GLOBALSINDEX);
KopiLua.Lua.lua_replace(luaState, (int)PseudoIndex.Globals); LuaDLL.lua_getglobal(lState, "luanet");
LuaLib.luaL_dostring(luaState, Lua.init_luanet); // steffenj: lua_dostring renamed to luaL_dostring LuaDLL.lua_pushstring(lState, "getmetatable");
} LuaDLL.lua_getglobal(lState, "getmetatable");
} LuaDLL.lua_settable(lState, -3);
LuaDLL.lua_replace(lState, (int)LuaIndexes.LUA_GLOBALSINDEX);
/// <summary> translator=new ObjectTranslator(this, this.luaState);
/// Called for each lua_lock call LuaDLL.lua_replace(lState, (int)LuaIndexes.LUA_GLOBALSINDEX);
/// </summary> LuaDLL.luaL_dostring(lState, Lua.init_luanet); // steffenj: lua_dostring renamed to luaL_dostring
/// <param name="luaState"></param> }
/// Not yet used
int LockCallback(KopiLua.Lua.lua_State luaState) _StatePassed = true;
{ }
// Monitor.Enter(luaLock);
/// <summary>
return 0; /// Called for each lua_lock call
} /// </summary>
/// <param name="luaState"></param>
/// <summary> /// Not yet used
/// Called for each lua_unlock call int LockCallback(IntPtr luaState)
/// </summary> {
/// <param name="luaState"></param> // Monitor.Enter(luaLock);
/// Not yet used
int UnlockCallback(KopiLua.Lua.lua_State luaState) return 0;
{ }
// Monitor.Exit(luaLock);
/// <summary>
return 0; /// Called for each lua_unlock call
} /// </summary>
/// <param name="luaState"></param>
static int PanicCallback(KopiLua.Lua.lua_State luaState) /// Not yet used
{ int UnlockCallback(IntPtr luaState)
// string desc = KopiLua.Lua.lua_tostring(luaState, 1); {
string reason = String.Format("unprotected error in call to Lua API ({0})", KopiLua.Lua.lua_tostring(luaState, -1)); // Monitor.Exit(luaLock);
// lua_tostring(L, -1); return 0;
}
throw new LuaException(reason);
} public void Close()
{
if (_StatePassed)
return;
/// <summary>
/// Assuming we have a Lua error string sitting on the stack, throw a C# exception out to the user's app if (luaState != IntPtr.Zero)
/// </summary> LuaDLL.lua_close(luaState);
void ThrowExceptionFromError(int oldTop) //luaState = IntPtr.Zero; <- suggested by Christopher Cebulski http://luaforge.net/forum/forum.php?thread_id=44593&forum_id=146
{ }
object err = translator.getObject(luaState, -1);
KopiLua.Lua.lua_settop(luaState, oldTop); static int PanicCallback(IntPtr luaState)
{
// If the 'error' on the stack is an actual C# exception, just rethrow it. Otherwise the value must have started // string desc = LuaDLL.lua_tostring(luaState, 1);
// as a true Lua error and is best interpreted as a string - wrap it in a LuaException and rethrow. string reason = String.Format("unprotected error in call to Lua API ({0})", LuaDLL.lua_tostring(luaState, -1));
Exception thrown = err as Exception;
// lua_tostring(L, -1);
if (thrown == null)
{ throw new LuaException(reason);
if (err == null) }
err = "Unknown Lua Error";
thrown = new LuaException(err.ToString());
} /// <summary>
/// Assuming we have a Lua error string sitting on the stack, throw a C# exception out to the user's app
throw thrown; /// </summary>
} /// <exception cref="LuaScriptException">Thrown if the script caused an exception</exception>
void ThrowExceptionFromError(int oldTop)
{
object err = translator.getObject(luaState, -1);
/// <summary> LuaDLL.lua_settop(luaState, oldTop);
/// Convert C# exceptions into Lua errors
/// </summary> // A pre-wrapped exception - just rethrow it (stack trace of InnerException will be preserved)
/// <returns>num of things on stack</returns> LuaScriptException luaEx = err as LuaScriptException;
/// <param name="e">null for no pending exception</param> if (luaEx != null) throw luaEx;
internal int SetPendingException(Exception e)
{ // A non-wrapped Lua error (best interpreted as a string) - wrap it and throw it
Exception caughtExcept = e; if (err == null) err = "Unknown Lua Error";
throw new LuaScriptException(err.ToString(), "");
if (caughtExcept != null) }
{
translator.throwError(luaState, caughtExcept);
KopiLua.Lua.lua_pushnil(luaState);
/// <summary>
return 1; /// Convert C# exceptions into Lua errors
} /// </summary>
else /// <returns>num of things on stack</returns>
return 0; /// <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;
}
private bool executing;
/// <summary>
/// True while a script is being executed
/// </summary>
public bool IsExecuting { get { return executing; } }
/// <summary>
///
/// </summary>
/// <param name="chunk"></param>
/// <param name="name"></param>
/// <returns></returns>
public LuaFunction LoadString(string chunk, string name)
{
int oldTop = LuaDLL.lua_gettop(luaState);
executing = true;
try
{
if (LuaDLL.luaL_loadbuffer(luaState, chunk, name) != 0)
ThrowExceptionFromError(oldTop);
}
finally { executing = false; }
LuaFunction result = translator.getFunction(luaState, -1);
translator.popValues(luaState, oldTop);
return result;
}
/// <summary>
///
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
public LuaFunction LoadFile(string fileName)
{
int oldTop = LuaDLL.lua_gettop(luaState);
if (LuaDLL.luaL_loadfile(luaState, fileName) != 0)
ThrowExceptionFromError(oldTop);
LuaFunction result = translator.getFunction(luaState, -1);
translator.popValues(luaState, oldTop);
return result;
}
/* /*
...@@ -217,37 +281,75 @@ namespace LuaInterface ...@@ -217,37 +281,75 @@ namespace LuaInterface
*/ */
public object[] DoString(string chunk) public object[] DoString(string chunk)
{ {
int oldTop=KopiLua.Lua.lua_gettop(luaState); int oldTop=LuaDLL.lua_gettop(luaState);
if(LuaLib.luaL_loadbuffer(luaState,chunk,"chunk")== LuaEnum.Ok) if (LuaDLL.luaL_loadbuffer(luaState, chunk, "chunk") == 0)
{ {
if (KopiLua.Lua.lua_pcall(luaState, 0, -1, 0) == 0) executing = true;
return translator.popValues(luaState, oldTop); try
else {
ThrowExceptionFromError(oldTop); if (LuaDLL.lua_pcall(luaState, 0, -1, 0) == 0)
} return translator.popValues(luaState, oldTop);
else else
ThrowExceptionFromError(oldTop); ThrowExceptionFromError(oldTop);
}
return null; // Never reached - keeps compiler happy finally { executing = false; }
}
else
ThrowExceptionFromError(oldTop);
return null; // Never reached - keeps compiler happy
} }
/// <summary>
/// Executes a Lua chnk and returns all the chunk's return values in an array.
/// </summary>
/// <param name="chunk">Chunk to execute</param>
/// <param name="chunkName">Name to associate with the chunk</param>
/// <returns></returns>
public object[] DoString(string chunk, string chunkName)
{
int oldTop = LuaDLL.lua_gettop(luaState);
executing = true;
if (LuaDLL.luaL_loadbuffer(luaState, chunk, chunkName) == 0)
{
try
{
if (LuaDLL.lua_pcall(luaState, 0, -1, 0) == 0)
return translator.popValues(luaState, oldTop);
else
ThrowExceptionFromError(oldTop);
}
finally { executing = false; }
}
else
ThrowExceptionFromError(oldTop);
return null; // Never reached - keeps compiler happy
}
/* /*
* Excutes a Lua file and returns all the chunk's return * Excutes a Lua file and returns all the chunk's return
* values in an array * values in an array
*/ */
public object[] DoFile(string fileName) public object[] DoFile(string fileName)
{ {
int oldTop=KopiLua.Lua.lua_gettop(luaState); int oldTop=LuaDLL.lua_gettop(luaState);
if(KopiLua.Lua.luaL_loadfile(luaState,fileName)==0) if(LuaDLL.luaL_loadfile(luaState,fileName)==0)
{ {
if (KopiLua.Lua.lua_pcall(luaState, 0, -1, 0) == 0) executing = true;
return translator.popValues(luaState, oldTop); try
else {
ThrowExceptionFromError(oldTop); if (LuaDLL.lua_pcall(luaState, 0, -1, 0) == 0)
return translator.popValues(luaState, oldTop);
else
ThrowExceptionFromError(oldTop);
}
finally { executing = false; }
} }
else else
ThrowExceptionFromError(oldTop); ThrowExceptionFromError(oldTop);
return null; // Never reached - keeps compiler happy return null; // Never reached - keeps compiler happy
} }
...@@ -260,9 +362,9 @@ namespace LuaInterface ...@@ -260,9 +362,9 @@ namespace LuaInterface
get get
{ {
object returnValue=null; object returnValue=null;
int oldTop=KopiLua.Lua.lua_gettop(luaState); int oldTop=LuaDLL.lua_gettop(luaState);
string[] path=fullPath.Split(new char[] { '.' }); string[] path=fullPath.Split(new char[] { '.' });
KopiLua.Lua.lua_getglobal(luaState,path[0]); LuaDLL.lua_getglobal(luaState,path[0]);
returnValue=translator.getObject(luaState,-1); returnValue=translator.getObject(luaState,-1);
if(path.Length>1) if(path.Length>1)
{ {
...@@ -270,30 +372,144 @@ namespace LuaInterface ...@@ -270,30 +372,144 @@ namespace LuaInterface
Array.Copy(path,1,remainingPath,0,path.Length-1); Array.Copy(path,1,remainingPath,0,path.Length-1);
returnValue=getObject(remainingPath); returnValue=getObject(remainingPath);
} }
KopiLua.Lua.lua_settop(luaState,oldTop); LuaDLL.lua_settop(luaState,oldTop);
//Console.WriteLine("get: {0}", returnValue);
return returnValue; return returnValue;
} }
set set
{ {
int oldTop=KopiLua.Lua.lua_gettop(luaState); int oldTop=LuaDLL.lua_gettop(luaState);
string[] path=fullPath.Split(new char[] { '.' }); string[] path=fullPath.Split(new char[] { '.' });
//Console.WriteLine("set: {0}", path.Length);
if(path.Length==1) if(path.Length==1)
{ {
translator.push(luaState,value); translator.push(luaState,value);
KopiLua.Lua.lua_setglobal(luaState,fullPath); LuaDLL.lua_setglobal(luaState,fullPath);
} }
else else
{ {
KopiLua.Lua.lua_getglobal(luaState,path[0]); LuaDLL.lua_getglobal(luaState,path[0]);
string[] remainingPath=new string[path.Length-1]; string[] remainingPath=new string[path.Length-1];
Array.Copy(path,1,remainingPath,0,path.Length-1); Array.Copy(path,1,remainingPath,0,path.Length-1);
setObject(remainingPath,value); setObject(remainingPath,value);
} }
KopiLua.Lua.lua_settop(luaState,oldTop); LuaDLL.lua_settop(luaState,oldTop);
}
// Globals auto-complete
if (value == null)
{
// Remove now obsolete entries
globals.Remove(fullPath);
}
else
{
// Add new entries
if (!globals.Contains(fullPath))
registerGlobal(fullPath, value.GetType(), 0);
}
}
} }
#region Globals auto-complete
private readonly List<string> globals = new List<string>();
private bool globalsSorted;
/// <summary>
/// An alphabetically sorted list of all globals (objects, methods, etc.) externally added to this Lua instance
/// </summary>
/// <remarks>Members of globals are also listed. The formatting is optimized for text input auto-completion.</remarks>
public IEnumerable<string> Globals
{
get
{
// Only sort list when necessary
if (!globalsSorted)
{
globals.Sort();
globalsSorted = true;
}
return globals;
}
}
/// <summary>
/// Adds an entry to <see cref="globals"/> (recursivley handles 2 levels of members)
/// </summary>
/// <param name="path">The index accessor path ot the entry</param>
/// <param name="type">The type of the entry</param>
/// <param name="recursionCounter">How deep have we gone with recursion?</param>
private void registerGlobal(string path, Type type, int recursionCounter)
{
// If the type is a global method, list it directly
if (type == typeof(LuaCSFunction))
{
// Format for easy method invocation
globals.Add(path + "(");
}
// If the type is a class or an interface and recursion hasn't been running too long, list the members
else if ((type.IsClass || type.IsInterface) && type != typeof(string) && recursionCounter < 2)
{
#region Methods
foreach (MethodInfo method in type.GetMethods(BindingFlags.Public | BindingFlags.Instance))
{
if (
// Check that the LuaHideAttribute and LuaGlobalAttribute were not applied
(method.GetCustomAttributes(typeof(LuaHideAttribute), false).Length == 0) &&
(method.GetCustomAttributes(typeof(LuaGlobalAttribute), false).Length == 0) &&
// Exclude some generic .NET methods that wouldn't be very usefull in Lua
method.Name != "GetType" && method.Name != "GetHashCode" && method.Name != "Equals" &&
method.Name != "ToString" && method.Name != "Clone" && method.Name != "Dispose" &&
method.Name != "GetEnumerator" && method.Name != "CopyTo" &&
!method.Name.StartsWith("get_", StringComparison.Ordinal) &&
!method.Name.StartsWith("set_", StringComparison.Ordinal) &&
!method.Name.StartsWith("add_", StringComparison.Ordinal) &&
!method.Name.StartsWith("remove_", StringComparison.Ordinal))
{
// Format for easy method invocation
string command = path + ":" + method.Name + "(";
if (method.GetParameters().Length == 0) command += ")";
globals.Add(command);
}
}
#endregion
#region Fields
foreach (FieldInfo field in type.GetFields(BindingFlags.Public | BindingFlags.Instance))
{
if (
// Check that the LuaHideAttribute and LuaGlobalAttribute were not applied
(field.GetCustomAttributes(typeof(LuaHideAttribute), false).Length == 0) &&
(field.GetCustomAttributes(typeof(LuaGlobalAttribute), false).Length == 0))
{
// Go into recursion for members
registerGlobal(path + "." + field.Name, field.FieldType, recursionCounter + 1);
}
}
#endregion
#region Properties
foreach (PropertyInfo property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
if (
// Check that the LuaHideAttribute and LuaGlobalAttribute were not applied
(property.GetCustomAttributes(typeof(LuaHideAttribute), false).Length == 0) &&
(property.GetCustomAttributes(typeof(LuaGlobalAttribute), false).Length == 0)
// Exclude some generic .NET properties that wouldn't be very usefull in Lua
&& property.Name != "Item")
{
// Go into recursion for members
registerGlobal(path + "." + property.Name, property.PropertyType, recursionCounter + 1);
}
}
#endregion
}
// Otherwise simply add the element to the list
else globals.Add(path);
// List will need to be sorted on next access
globalsSorted = false;
}
#endregion
/* /*
* Navigates a table in the top of the stack, returning * Navigates a table in the top of the stack, returning
* the value of the specified field * the value of the specified field
...@@ -303,12 +519,12 @@ namespace LuaInterface ...@@ -303,12 +519,12 @@ namespace LuaInterface
object returnValue=null; object returnValue=null;
for(int i=0;i<remainingPath.Length;i++) for(int i=0;i<remainingPath.Length;i++)
{ {
KopiLua.Lua.lua_pushstring(luaState,remainingPath[i]); LuaDLL.lua_pushstring(luaState,remainingPath[i]);
KopiLua.Lua.lua_gettable(luaState,-2); LuaDLL.lua_gettable(luaState,-2);
returnValue=translator.getObject(luaState,-1); returnValue=translator.getObject(luaState,-1);
if(returnValue==null) break; if(returnValue==null) break;
} }
return returnValue; return returnValue;
} }
/* /*
* Gets a numeric global variable * Gets a numeric global variable
...@@ -344,9 +560,8 @@ namespace LuaInterface ...@@ -344,9 +560,8 @@ namespace LuaInterface
*/ */
public LuaFunction GetFunction(string fullPath) public LuaFunction GetFunction(string fullPath)
{ {
object obj=this[fullPath]; object obj=this[fullPath];
//return (obj is KopiLua.Lua.lua_CFunction ? new LuaFunction((KopiLua.Lua.lua_CFunction)obj,this) : (LuaFunction)obj); return (obj is LuaCSFunction ? new LuaFunction((LuaCSFunction)obj,this) : (LuaFunction)obj);
return (obj is KopiLua.Lua.lua_CFunction ? new LuaFunction((KopiLua.Lua.lua_CFunction)obj,this) : /*(LuaFunction)*/new LuaFunction(obj.GetHashCode(), this));
} }
/* /*
* Gets a function global variable as a delegate of * Gets a function global variable as a delegate of
...@@ -362,7 +577,7 @@ namespace LuaInterface ...@@ -362,7 +577,7 @@ namespace LuaInterface
*/ */
internal object[] callFunction(object function,object[] args) internal object[] callFunction(object function,object[] args)
{ {
return callFunction(function, args, null); return callFunction(function, args, null);
} }
...@@ -374,9 +589,9 @@ namespace LuaInterface ...@@ -374,9 +589,9 @@ namespace LuaInterface
internal object[] callFunction(object function,object[] args,Type[] returnTypes) internal object[] callFunction(object function,object[] args,Type[] returnTypes)
{ {
int nArgs=0; int nArgs=0;
int oldTop=KopiLua.Lua.lua_gettop(luaState); int oldTop=LuaDLL.lua_gettop(luaState);
if(!KopiLua.Lua.lua_checkstack(luaState,args.Length+6).ToBoolean()) if(!LuaDLL.lua_checkstack(luaState,args.Length+6))
throw new LuaException("Lua stack overflow"); throw new LuaException("Lua stack overflow");
translator.push(luaState,function); translator.push(luaState,function);
if(args!=null) if(args!=null)
{ {
...@@ -385,15 +600,20 @@ namespace LuaInterface ...@@ -385,15 +600,20 @@ namespace LuaInterface
{ {
translator.push(luaState,args[i]); translator.push(luaState,args[i]);
} }
} }
LuaEnum error = KopiLua.Lua.lua_pcall(luaState, nArgs, -1, 0).ToLuaEnum(); executing = true;
if (error != LuaEnum.Ok) try
ThrowExceptionFromError(oldTop); {
int error = LuaDLL.lua_pcall(luaState, nArgs, -1, 0);
if(returnTypes != null) if (error != 0)
return translator.popValues(luaState,oldTop,returnTypes); ThrowExceptionFromError(oldTop);
else }
return translator.popValues(luaState, oldTop); finally { executing = false; }
if(returnTypes != null)
return translator.popValues(luaState,oldTop,returnTypes);
else
return translator.popValues(luaState, oldTop);
} }
/* /*
* Navigates a table to set the value of one of its fields * Navigates a table to set the value of one of its fields
...@@ -402,12 +622,12 @@ namespace LuaInterface ...@@ -402,12 +622,12 @@ namespace LuaInterface
{ {
for(int i=0; i<remainingPath.Length-1;i++) for(int i=0; i<remainingPath.Length-1;i++)
{ {
KopiLua.Lua.lua_pushstring(luaState,remainingPath[i]); LuaDLL.lua_pushstring(luaState,remainingPath[i]);
KopiLua.Lua.lua_gettable(luaState,-2); LuaDLL.lua_gettable(luaState,-2);
} }
KopiLua.Lua.lua_pushstring(luaState,remainingPath[remainingPath.Length-1]); LuaDLL.lua_pushstring(luaState,remainingPath[remainingPath.Length-1]);
translator.push(luaState,val); translator.push(luaState,val);
KopiLua.Lua.lua_settable(luaState,-3); LuaDLL.lua_settable(luaState,-3);
} }
/* /*
* Creates a new table as a global variable or as a field * Creates a new table as a global variable or as a field
...@@ -416,42 +636,40 @@ namespace LuaInterface ...@@ -416,42 +636,40 @@ namespace LuaInterface
public void NewTable(string fullPath) public void NewTable(string fullPath)
{ {
string[] path=fullPath.Split(new char[] { '.' }); string[] path=fullPath.Split(new char[] { '.' });
int oldTop=KopiLua.Lua.lua_gettop(luaState); int oldTop=LuaDLL.lua_gettop(luaState);
if(path.Length==1) if(path.Length==1)
{ {
KopiLua.Lua.lua_newtable(luaState); LuaDLL.lua_newtable(luaState);
KopiLua.Lua.lua_setglobal(luaState,fullPath); LuaDLL.lua_setglobal(luaState,fullPath);
} }
else else
{ {
KopiLua.Lua.lua_getglobal(luaState,path[0]); LuaDLL.lua_getglobal(luaState,path[0]);
for(int i=1; i<path.Length-1;i++) for(int i=1; i<path.Length-1;i++)
{ {
KopiLua.Lua.lua_pushstring(luaState,path[i]); LuaDLL.lua_pushstring(luaState,path[i]);
KopiLua.Lua.lua_gettable(luaState,-2); LuaDLL.lua_gettable(luaState,-2);
} }
KopiLua.Lua.lua_pushstring(luaState,path[path.Length-1]); LuaDLL.lua_pushstring(luaState,path[path.Length-1]);
KopiLua.Lua.lua_newtable(luaState); LuaDLL.lua_newtable(luaState);
KopiLua.Lua.lua_settable(luaState,-3); LuaDLL.lua_settable(luaState,-3);
} }
KopiLua.Lua.lua_settop(luaState,oldTop); LuaDLL.lua_settop(luaState,oldTop);
} }
public ListDictionary GetTableDict(LuaTable table) public ListDictionary GetTableDict(LuaTable table)
{ {
ListDictionary dict = new ListDictionary(); ListDictionary dict = new ListDictionary();
int oldTop = KopiLua.Lua.lua_gettop(luaState); int oldTop = LuaDLL.lua_gettop(luaState);
translator.push(luaState, table); translator.push(luaState, table);
KopiLua.Lua.lua_pushnil(luaState); LuaDLL.lua_pushnil(luaState);
// nem biztos hogy jóóóó while (LuaDLL.lua_next(luaState, -2) != 0)
//while (KopiLua.Lua.lua_next(luaState, -2) != 0)
while (!KopiLua.Lua.lua_next(luaState, -2).ToBoolean())
{ {
dict[translator.getObject(luaState, -2)] = translator.getObject(luaState, -1); dict[translator.getObject(luaState, -2)] = translator.getObject(luaState, -1);
KopiLua.Lua.lua_settop(luaState, -2); LuaDLL.lua_settop(luaState, -2);
} }
KopiLua.Lua.lua_settop(luaState, oldTop); LuaDLL.lua_settop(luaState, oldTop);
return dict; return dict;
} }
...@@ -460,9 +678,247 @@ namespace LuaInterface ...@@ -460,9 +678,247 @@ namespace LuaInterface
* Lets go of a previously allocated reference to a table, function * Lets go of a previously allocated reference to a table, function
* or userdata * or userdata
*/ */
#region lua debug functions
/// <summary>
/// lua hook calback delegate
/// </summary>
/// <author>Reinhard Ostermeier</author>
private LuaHookFunction hookCallback = null;
/// <summary>
/// Activates the debug hook
/// </summary>
/// <param name="mask">Mask</param>
/// <param name="count">Count</param>
/// <returns>see lua docs. -1 if hook is already set</returns>
/// <author>Reinhard Ostermeier</author>
public int SetDebugHook(EventMasks mask, int count)
{
if (hookCallback == null)
{
hookCallback = new LuaHookFunction(DebugHookCallback);
return LuaDLL.lua_sethook(luaState, hookCallback, (int)mask, count);
}
return -1;
}
/// <summary>
/// Removes the debug hook
/// </summary>
/// <returns>see lua docs</returns>
/// <author>Reinhard Ostermeier</author>
public int RemoveDebugHook()
{
hookCallback = null;
return LuaDLL.lua_sethook(luaState, null, 0, 0);
}
/// <summary>
/// Gets the hook mask.
/// </summary>
/// <returns>hook mask</returns>
/// <author>Reinhard Ostermeier</author>
public EventMasks GetHookMask()
{
return (EventMasks)LuaDLL.lua_gethookmask(luaState);
}
/// <summary>
/// Gets the hook count
/// </summary>
/// <returns>see lua docs</returns>
/// <author>Reinhard Ostermeier</author>
public int GetHookCount()
{
return LuaDLL.lua_gethookcount(luaState);
}
/// <summary>
/// Gets the stack entry on a given level
/// </summary>
/// <param name="level">level</param>
/// <param name="luaDebug">lua debug structure</param>
/// <returns>Returns true if level was allowed, false if level was invalid.</returns>
/// <author>Reinhard Ostermeier</author>
public bool GetStack(int level, out LuaDebug luaDebug)
{
luaDebug = new LuaDebug();
IntPtr ld = System.Runtime.InteropServices.Marshal.AllocHGlobal(System.Runtime.InteropServices.Marshal.SizeOf(luaDebug));
System.Runtime.InteropServices.Marshal.StructureToPtr(luaDebug, ld, false);
try
{
return LuaDLL.lua_getstack(luaState, level, ld) != 0;
}
finally
{
luaDebug = (LuaDebug)System.Runtime.InteropServices.Marshal.PtrToStructure(ld, typeof(LuaDebug));
System.Runtime.InteropServices.Marshal.FreeHGlobal(ld);
}
}
/// <summary>
/// Gets info (see lua docs)
/// </summary>
/// <param name="what">what (see lua docs)</param>
/// <param name="luaDebug">lua debug structure</param>
/// <returns>see lua docs</returns>
/// <author>Reinhard Ostermeier</author>
public int GetInfo(String what, ref LuaDebug luaDebug)
{
IntPtr ld = System.Runtime.InteropServices.Marshal.AllocHGlobal(System.Runtime.InteropServices.Marshal.SizeOf(luaDebug));
System.Runtime.InteropServices.Marshal.StructureToPtr(luaDebug, ld, false);
try
{
return LuaDLL.lua_getinfo(luaState, what, ld);
}
finally
{
luaDebug = (LuaDebug)System.Runtime.InteropServices.Marshal.PtrToStructure(ld, typeof(LuaDebug));
System.Runtime.InteropServices.Marshal.FreeHGlobal(ld);
}
}
/// <summary>
/// Gets local (see lua docs)
/// </summary>
/// <param name="luaDebug">lua debug structure</param>
/// <param name="n">see lua docs</param>
/// <returns>see lua docs</returns>
/// <author>Reinhard Ostermeier</author>
public String GetLocal(LuaDebug luaDebug, int n)
{
IntPtr ld = System.Runtime.InteropServices.Marshal.AllocHGlobal(System.Runtime.InteropServices.Marshal.SizeOf(luaDebug));
System.Runtime.InteropServices.Marshal.StructureToPtr(luaDebug, ld, false);
try
{
return LuaDLL.lua_getlocal(luaState, ld, n);
}
finally
{
System.Runtime.InteropServices.Marshal.FreeHGlobal(ld);
}
}
/// <summary>
/// Sets local (see lua docs)
/// </summary>
/// <param name="luaDebug">lua debug structure</param>
/// <param name="n">see lua docs</param>
/// <returns>see lua docs</returns>
/// <author>Reinhard Ostermeier</author>
public String SetLocal(LuaDebug luaDebug, int n)
{
IntPtr ld = System.Runtime.InteropServices.Marshal.AllocHGlobal(System.Runtime.InteropServices.Marshal.SizeOf(luaDebug));
System.Runtime.InteropServices.Marshal.StructureToPtr(luaDebug, ld, false);
try
{
return LuaDLL.lua_setlocal(luaState, ld, n);
}
finally
{
System.Runtime.InteropServices.Marshal.FreeHGlobal(ld);
}
}
/// <summary>
/// Gets up value (see lua docs)
/// </summary>
/// <param name="funcindex">see lua docs</param>
/// <param name="n">see lua docs</param>
/// <returns>see lua docs</returns>
/// <author>Reinhard Ostermeier</author>
public String GetUpValue(int funcindex, int n)
{
return LuaDLL.lua_getupvalue(luaState, funcindex, n);
}
/// <summary>
/// Sets up value (see lua docs)
/// </summary>
/// <param name="funcindex">see lua docs</param>
/// <param name="n">see lua docs</param>
/// <returns>see lua docs</returns>
/// <author>Reinhard Ostermeier</author>
public String SetUpValue(int funcindex, int n)
{
return LuaDLL.lua_setupvalue(luaState, funcindex, n);
}
/// <summary>
/// Delegate that is called on lua hook callback
/// </summary>
/// <param name="luaState">lua state</param>
/// <param name="luaDebug">Pointer to LuaDebug (lua_debug) structure</param>
/// <author>Reinhard Ostermeier</author>
private void DebugHookCallback(IntPtr luaState, IntPtr luaDebug)
{
try
{
LuaDebug ld = (LuaDebug)System.Runtime.InteropServices.Marshal.PtrToStructure(luaDebug, typeof(LuaDebug));
EventHandler<DebugHookEventArgs> temp = DebugHook;
if (temp != null)
{
temp(this, new DebugHookEventArgs(ld));
}
}
catch (Exception ex)
{
OnHookException(new HookExceptionEventArgs(ex));
}
}
/// <summary>
/// Event that is raised when an exception occures during a hook call.
/// </summary>
/// <author>Reinhard Ostermeier</author>
public event EventHandler<HookExceptionEventArgs> HookException;
private void OnHookException(HookExceptionEventArgs e)
{
EventHandler<HookExceptionEventArgs> temp = HookException;
if (temp != null)
{
temp(this, e);
}
}
/// <summary>
/// Event when lua hook callback is called
/// </summary>
/// <remarks>
/// Is only raised if SetDebugHook is called before.
/// </remarks>
/// <author>Reinhard Ostermeier</author>
public event EventHandler<DebugHookEventArgs> DebugHook;
/// <summary>
/// Pops a value from the lua stack.
/// </summary>
/// <returns>Returns the top value from the lua stack.</returns>
/// <author>Reinhard Ostermeier</author>
public object Pop()
{
int top = Lua511.LuaDLL.lua_gettop(luaState);
return translator.popValues(luaState, top - 1)[0];
}
/// <summary>
/// Pushes a value onto the lua stack.
/// </summary>
/// <param name="value">Value to push.</param>
/// <author>Reinhard Ostermeier</author>
public void Push(object value)
{
translator.push(luaState, value);
}
#endregion
internal void dispose(int reference) internal void dispose(int reference)
{ {
LuaLib.lua_unref(luaState,reference); if (luaState != IntPtr.Zero) //Fix submitted by Qingrui Li
LuaDLL.lua_unref(luaState,reference);
} }
/* /*
* Gets a field of the table corresponding to the provided reference * Gets a field of the table corresponding to the provided reference
...@@ -470,12 +926,12 @@ namespace LuaInterface ...@@ -470,12 +926,12 @@ namespace LuaInterface
*/ */
internal object rawGetObject(int reference,string field) internal object rawGetObject(int reference,string field)
{ {
int oldTop=KopiLua.Lua.lua_gettop(luaState); int oldTop=LuaDLL.lua_gettop(luaState);
LuaLib.lua_getref(luaState,reference); LuaDLL.lua_getref(luaState,reference);
KopiLua.Lua.lua_pushstring(luaState,field); LuaDLL.lua_pushstring(luaState,field);
KopiLua.Lua.lua_rawget(luaState,-2); LuaDLL.lua_rawget(luaState,-2);
object obj=translator.getObject(luaState,-1); object obj=translator.getObject(luaState,-1);
KopiLua.Lua.lua_settop(luaState,oldTop); LuaDLL.lua_settop(luaState,oldTop);
return obj; return obj;
} }
/* /*
...@@ -483,10 +939,10 @@ namespace LuaInterface ...@@ -483,10 +939,10 @@ namespace LuaInterface
*/ */
internal object getObject(int reference,string field) internal object getObject(int reference,string field)
{ {
int oldTop=KopiLua.Lua.lua_gettop(luaState); int oldTop=LuaDLL.lua_gettop(luaState);
LuaLib.lua_getref(luaState,reference); LuaDLL.lua_getref(luaState,reference);
object returnValue=getObject(field.Split(new char[] {'.'})); object returnValue=getObject(field.Split(new char[] {'.'}));
KopiLua.Lua.lua_settop(luaState,oldTop); LuaDLL.lua_settop(luaState,oldTop);
return returnValue; return returnValue;
} }
/* /*
...@@ -494,12 +950,12 @@ namespace LuaInterface ...@@ -494,12 +950,12 @@ namespace LuaInterface
*/ */
internal object getObject(int reference,object field) internal object getObject(int reference,object field)
{ {
int oldTop=KopiLua.Lua.lua_gettop(luaState); int oldTop=LuaDLL.lua_gettop(luaState);
LuaLib.lua_getref(luaState,reference); LuaDLL.lua_getref(luaState,reference);
translator.push(luaState,field); translator.push(luaState,field);
KopiLua.Lua.lua_gettable(luaState,-2); LuaDLL.lua_gettable(luaState,-2);
object returnValue=translator.getObject(luaState,-1); object returnValue=translator.getObject(luaState,-1);
KopiLua.Lua.lua_settop(luaState,oldTop); LuaDLL.lua_settop(luaState,oldTop);
return returnValue; return returnValue;
} }
/* /*
...@@ -508,10 +964,10 @@ namespace LuaInterface ...@@ -508,10 +964,10 @@ namespace LuaInterface
*/ */
internal void setObject(int reference, string field, object val) internal void setObject(int reference, string field, object val)
{ {
int oldTop=KopiLua.Lua.lua_gettop(luaState); int oldTop=LuaDLL.lua_gettop(luaState);
LuaLib.lua_getref(luaState,reference); LuaDLL.lua_getref(luaState,reference);
setObject(field.Split(new char[] {'.'}),val); setObject(field.Split(new char[] {'.'}),val);
KopiLua.Lua.lua_settop(luaState,oldTop); LuaDLL.lua_settop(luaState,oldTop);
} }
/* /*
* Sets a numeric field of the table or userdata corresponding the the provided reference * Sets a numeric field of the table or userdata corresponding the the provided reference
...@@ -519,31 +975,32 @@ namespace LuaInterface ...@@ -519,31 +975,32 @@ namespace LuaInterface
*/ */
internal void setObject(int reference, object field, object val) internal void setObject(int reference, object field, object val)
{ {
int oldTop=KopiLua.Lua.lua_gettop(luaState); int oldTop=LuaDLL.lua_gettop(luaState);
LuaLib.lua_getref(luaState,reference); LuaDLL.lua_getref(luaState,reference);
translator.push(luaState,field); translator.push(luaState,field);
translator.push(luaState,val); translator.push(luaState,val);
KopiLua.Lua.lua_settable(luaState,-3); LuaDLL.lua_settable(luaState,-3);
KopiLua.Lua.lua_settop(luaState,oldTop); LuaDLL.lua_settop(luaState,oldTop);
} }
/* /*
* Registers an object's method as a Lua function (global or table field) * Registers an object's method as a Lua function (global or table field)
* The method may have any signature * The method may have any signature
*/ */
public LuaFunction RegisterFunction(string path, object target,MethodInfo function) public LuaFunction RegisterFunction(string path, object target, MethodBase function /*MethodInfo function*/) //CP: Fix for struct constructor by Alexander Kappner (link: http://luaforge.net/forum/forum.php?thread_id=2859&forum_id=145)
{ {
// We leave nothing on the stack when we are done // We leave nothing on the stack when we are done
int oldTop = KopiLua.Lua.lua_gettop(luaState); int oldTop = LuaDLL.lua_gettop(luaState);
LuaMethodWrapper wrapper=new LuaMethodWrapper(translator,target,function.DeclaringType,function); LuaMethodWrapper wrapper=new LuaMethodWrapper(translator,target,function.DeclaringType,function);
translator.push(luaState,new KopiLua.Lua.lua_CFunction(wrapper.call)); translator.push(luaState,new LuaCSFunction(wrapper.call));
this[path]=translator.getObject(luaState,-1); this[path]=translator.getObject(luaState,-1);
LuaFunction f = GetFunction(path); LuaFunction f = GetFunction(path);
KopiLua.Lua.lua_settop(luaState, oldTop); LuaDLL.lua_settop(luaState, oldTop);
return f;
return f;
} }
...@@ -552,293 +1009,128 @@ namespace LuaInterface ...@@ -552,293 +1009,128 @@ namespace LuaInterface
*/ */
internal bool compareRef(int ref1, int ref2) internal bool compareRef(int ref1, int ref2)
{ {
int top=KopiLua.Lua.lua_gettop(luaState); int top=LuaDLL.lua_gettop(luaState);
LuaLib.lua_getref(luaState,ref1); LuaDLL.lua_getref(luaState,ref1);
LuaLib.lua_getref(luaState,ref2); LuaDLL.lua_getref(luaState,ref2);
int equal=KopiLua.Lua.lua_equal(luaState,-1,-2); int equal=LuaDLL.lua_equal(luaState,-1,-2);
KopiLua.Lua.lua_settop(luaState,top); LuaDLL.lua_settop(luaState,top);
return (equal!=0); return (equal!=0);
} }
internal void pushCSFunction(KopiLua.Lua.lua_CFunction function) internal void pushCSFunction(LuaCSFunction function)
{ {
translator.pushFunction(luaState,function); translator.pushFunction(luaState,function);
} }
#region IDisposable Members #region IDisposable Members
public virtual void Dispose() public virtual void Dispose()
{ {
if (translator != null) if (translator != null)
{ {
translator.pendingEvents.Dispose(); translator.pendingEvents.Dispose();
translator = null;
translator = null; }
}
this.Close();
System.GC.Collect(); System.GC.Collect();
System.GC.WaitForPendingFinalizers(); System.GC.WaitForPendingFinalizers();
} }
#endregion #endregion
} }
/* /// <summary>
* Wrapper class for Lua tables /// Event codes for lua hook function
* /// </summary>
* Author: Fabio Mascarenhas /// <remarks>
* Version: 1.0 /// Do not change any of the values because they must match the lua values
*/ /// </remarks>
public class LuaTable /// <author>Reinhard Ostermeier</author>
{ public enum EventCodes
internal int reference; {
private Lua interpreter; LUA_HOOKCALL = 0,
public LuaTable(int reference, Lua interpreter) LUA_HOOKRET = 1,
{ LUA_HOOKLINE = 2,
this.reference=reference; LUA_HOOKCOUNT = 3,
this.interpreter=interpreter; LUA_HOOKTAILRET = 4,
} }
~LuaTable()
{ /// <summary>
interpreter.dispose(reference); /// Event masks for lua hook callback
} /// </summary>
/* /// <remarks>
* Indexer for string fields of the table /// Do not change any of the values because they must match the lua values
*/ /// </remarks>
public object this[string field] /// <author>Reinhard Ostermeier</author>
{ [Flags]
get public enum EventMasks
{ {
return interpreter.getObject(reference,field); LUA_MASKCALL = (1 << EventCodes.LUA_HOOKCALL),
} LUA_MASKRET = (1 << EventCodes.LUA_HOOKRET),
set LUA_MASKLINE = (1 << EventCodes.LUA_HOOKLINE),
{ LUA_MASKCOUNT = (1 << EventCodes.LUA_HOOKCOUNT),
interpreter.setObject(reference,field,value); LUA_MASKALL = Int32.MaxValue,
} }
}
/* /// <summary>
* Indexer for numeric fields of the table /// Structure for lua debug information
*/ /// </summary>
public object this[object field] /// <remarks>
{ /// Do not change this struct because it must match the lua structure lua_debug
get /// </remarks>
{ /// <author>Reinhard Ostermeier</author>
return interpreter.getObject(reference,field); [System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)]
} public struct LuaDebug
set {
{ public EventCodes eventCode;
interpreter.setObject(reference,field,value); [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPStr)]
} public String name;
} [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPStr)]
public String namewhat;
[System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPStr)]
public System.Collections.IEnumerator GetEnumerator() public String what;
{ [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPStr)]
return interpreter.GetTableDict(this).GetEnumerator(); public String source;
} public int currentline;
public int nups;
public ICollection Keys public int linedefined;
{ public int lastlinedefined;
get { return interpreter.GetTableDict(this).Keys; } [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst = 60/*LUA_IDSIZE*/)]
} public String shortsrc;
public int i_ci;
public ICollection Values }
{
get { return interpreter.GetTableDict(this).Values; } /// <summary>
} /// Event args for hook callback event
/// </summary>
/* /// <author>Reinhard Ostermeier</author>
* Gets an string fields of a table ignoring its metatable, public class DebugHookEventArgs : EventArgs
* if it exists {
*/ private readonly LuaDebug luaDebug;
internal object rawget(string field)
{ public DebugHookEventArgs(LuaDebug luaDebug)
return interpreter.rawGetObject(reference,field); {
} this.luaDebug = luaDebug;
}
internal object rawgetFunction(string field)
{ public LuaDebug LuaDebug
object obj=interpreter.rawGetObject(reference,field); {
get { return luaDebug; }
if(obj is KopiLua.Lua.lua_CFunction) }
return new LuaFunction((KopiLua.Lua.lua_CFunction)obj,interpreter); }
else
return obj; public class HookExceptionEventArgs : EventArgs
} {
private readonly Exception m_Exception;
/* public Exception Exception
* Pushes this table into the Lua stack {
*/ get { return m_Exception; }
internal void push(KopiLua.Lua.lua_State luaState) }
{
LuaLib.lua_getref(luaState,reference); public HookExceptionEventArgs(Exception ex)
} {
public override string ToString() m_Exception = ex;
{ }
return "table"; }
}
public override bool Equals(object o)
{
if(o is LuaTable)
{
LuaTable l=(LuaTable)o;
return interpreter.compareRef(l.reference,this.reference);
} else return false;
}
public override int GetHashCode()
{
return reference;
}
}
public class LuaFunction
{
private Lua interpreter;
internal KopiLua.Lua.lua_CFunction function;
internal int reference;
public LuaFunction(int reference, Lua interpreter)
{
this.reference=reference;
this.function=null;
this.interpreter=interpreter;
}
public LuaFunction(KopiLua.Lua.lua_CFunction function, Lua interpreter)
{
this.reference=0;
this.function=function;
this.interpreter=interpreter;
}
~LuaFunction()
{
if(reference!=0)
interpreter.dispose(reference);
}
/*
* Calls the function casting return values to the types
* in returnTypes
*/
internal object[] call(object[] args, Type[] returnTypes)
{
return interpreter.callFunction(this,args,returnTypes);
}
/*
* Calls the function and returns its return values inside
* an array
*/
public object[] Call(params object[] args)
{
return interpreter.callFunction(this,args);
}
/*
* Pushes the function into the Lua stack
*/
internal void push(KopiLua.Lua.lua_State luaState)
{
if(reference!=0)
LuaLib.lua_getref(luaState,reference);
else
interpreter.pushCSFunction(function);
}
public override string ToString()
{
return "function";
}
public override bool Equals(object o)
{
if(o is LuaFunction)
{
LuaFunction l=(LuaFunction)o;
if(this.reference!=0 && l.reference!=0)
return interpreter.compareRef(l.reference,this.reference);
else
return this.function==l.function;
}
else return false;
}
public override int GetHashCode()
{
if(reference!=0)
return reference;
else
return function.GetHashCode();
}
}
public class LuaUserData
{
internal int reference;
private Lua interpreter;
public LuaUserData(int reference, Lua interpreter)
{
this.reference=reference;
this.interpreter=interpreter;
}
~LuaUserData()
{
interpreter.dispose(reference);
}
/*
* Indexer for string fields of the userdata
*/
public object this[string field]
{
get
{
return interpreter.getObject(reference,field);
}
set
{
interpreter.setObject(reference,field,value);
}
}
/*
* Indexer for numeric fields of the userdata
*/
public object this[object field]
{
get
{
return interpreter.getObject(reference,field);
}
set
{
interpreter.setObject(reference,field,value);
}
}
/*
* Calls the userdata and returns its return values inside
* an array
*/
public object[] Call(params object[] args)
{
return interpreter.callFunction(this,args);
}
/*
* Pushes the userdata into the Lua stack
*/
internal void push(KopiLua.Lua.lua_State luaState)
{
LuaLib.lua_getref(luaState,reference);
}
public override string ToString()
{
return "userdata";
}
public override bool Equals(object o)
{
if(o is LuaUserData)
{
LuaUserData l=(LuaUserData)o;
return interpreter.compareRef(l.reference,this.reference);
}
else return false;
}
public override int GetHashCode()
{
return reference;
}
}
} }
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.Text;
namespace LuaInterface
{
/// <summary>
/// Base class to provide consistent disposal flow across lua objects. Uses code provided by Yves Duhoux and suggestions by Hans Schmeidenbacher and Qingrui Li
/// </summary>
public abstract class LuaBase : IDisposable
{
private bool _Disposed;
protected int _Reference;
protected Lua _Interpreter;
~LuaBase()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public virtual void Dispose(bool disposeManagedResources)
{
if (!_Disposed)
{
if (disposeManagedResources)
{
if (_Reference != 0)
_Interpreter.dispose(_Reference);
}
_Interpreter = null;
_Disposed = true;
}
}
public override bool Equals(object o)
{
if (o is LuaBase)
{
LuaBase l = (LuaBase)o;
return _Interpreter.compareRef(l._Reference, _Reference);
}
else return false;
}
public override int GetHashCode()
{
return _Reference;
}
}
}
using System; using System;
using System.Collections.Generic; using System.Runtime.Serialization;
using System.Text;
namespace LuaInterface namespace LuaInterface
{ {
/// <summary> /// <summary>
/// Add a specific type for Lua exceptions (kevinh) /// Exceptions thrown by the Lua runtime
/// </summary> /// </summary>
public class LuaException : ApplicationException [Serializable]
{ public class LuaException : Exception
public LuaException(string reason) : base(reason) {
{ public LuaException()
} {}
}
} public LuaException(string message) : base(message)
{}
public LuaException(string message, Exception innerException) : base(message, innerException)
{}
protected LuaException(SerializationInfo info, StreamingContext context) : base(info, context)
{}
}
}
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.Text;
using Lua511;
namespace LuaInterface
{
public class LuaFunction : LuaBase
{
//private Lua interpreter;
internal LuaCSFunction function;
//internal int reference;
public LuaFunction(int reference, Lua interpreter)
{
_Reference = reference;
this.function = null;
_Interpreter = interpreter;
}
public LuaFunction(LuaCSFunction function, Lua interpreter)
{
_Reference = 0;
this.function = function;
_Interpreter = interpreter;
}
//~LuaFunction()
//{
// if (reference != 0)
// interpreter.dispose(reference);
//}
//bool disposed = false;
//~LuaFunction()
//{
// Dispose(false);
//}
//public void Dispose()
//{
// Dispose(true);
// GC.SuppressFinalize(this);
//}
//public virtual void Dispose(bool disposeManagedResources)
//{
// if (!this.disposed)
// {
// if (disposeManagedResources)
// {
// if (_Reference != 0)
// _Interpreter.dispose(_Reference);
// }
// disposed = true;
// }
//}
/*
* Calls the function casting return values to the types
* in returnTypes
*/
internal object[] call(object[] args, Type[] returnTypes)
{
return _Interpreter.callFunction(this, args, returnTypes);
}
/*
* Calls the function and returns its return values inside
* an array
*/
public object[] Call(params object[] args)
{
return _Interpreter.callFunction(this, args);
}
/*
* Pushes the function into the Lua stack
*/
internal void push(IntPtr luaState)
{
if (_Reference != 0)
LuaDLL.lua_getref(luaState, _Reference);
else
_Interpreter.pushCSFunction(function);
}
public override string ToString()
{
return "function";
}
public override bool Equals(object o)
{
if (o is LuaFunction)
{
LuaFunction l = (LuaFunction)o;
if (this._Reference != 0 && l._Reference != 0)
return _Interpreter.compareRef(l._Reference, this._Reference);
else
return this.function == l.function;
}
else return false;
}
public override int GetHashCode()
{
if (_Reference != 0)
return _Reference;
else
return function.GetHashCode();
}
}
}
using System;
namespace LuaInterface
{
/// <summary>
/// Marks a method for global usage in Lua scripts
/// </summary>
/// <see cref="LuaRegistrationHelper.TaggedInstanceMethods"/>
/// <see cref="LuaRegistrationHelper.TaggedStaticMethods"/>
[AttributeUsage(AttributeTargets.Method)]
public sealed class LuaGlobalAttribute : Attribute
{
/// <summary>
/// An alternative name to use for calling the function in Lua - leave empty for CLR name
/// </summary>
public string Name { get; set; }
/// <summary>
/// A description of the function
/// </summary>
public string Description { get; set; }
}
}
using System;
namespace LuaInterface
{
/// <summary>
/// Marks a method, field or property to be hidden from Lua auto-completion
/// </summary>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Field | AttributeTargets.Property)]
public sealed class LuaHideAttribute : Attribute
{}
}
...@@ -45,6 +45,14 @@ ...@@ -45,6 +45,14 @@
<Compile Include="ProxyType.cs" /> <Compile Include="ProxyType.cs" />
<Compile Include="LuaLib\LuaLib.cs" /> <Compile Include="LuaLib\LuaLib.cs" />
<Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="LuaBase.cs" />
<Compile Include="LuaFunction.cs" />
<Compile Include="LuaGlobalAttribute.cs" />
<Compile Include="LuaHideAttribute.cs" />
<Compile Include="LuaRegistrationHelper.cs" />
<Compile Include="LuaScriptException.cs" />
<Compile Include="LuaTable.cs" />
<Compile Include="LuaUserData.cs" />
</ItemGroup> </ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it. <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
......
using System;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
namespace LuaInterface
{
public static class LuaRegistrationHelper
{
#region Tagged instance methods
/// <summary>
/// Registers all public instance methods in an object tagged with <see cref="LuaGlobalAttribute"/> as Lua global functions
/// </summary>
/// <param name="lua">The Lua VM to add the methods to</param>
/// <param name="o">The object to get the methods from</param>
public static void TaggedInstanceMethods(Lua lua, object o)
{
#region Sanity checks
if (lua == null) throw new ArgumentNullException("lua");
if (o == null) throw new ArgumentNullException("o");
#endregion
foreach (MethodInfo method in o.GetType().GetMethods(BindingFlags.Instance | BindingFlags.Public))
{
foreach (LuaGlobalAttribute attribute in method.GetCustomAttributes(typeof(LuaGlobalAttribute), true))
{
if (string.IsNullOrEmpty(attribute.Name))
lua.RegisterFunction(method.Name, o, method); // CLR name
else
lua.RegisterFunction(attribute.Name, o, method); // Custom name
}
}
}
#endregion
#region Tagged static methods
/// <summary>
/// Registers all public static methods in a class tagged with <see cref="LuaGlobalAttribute"/> as Lua global functions
/// </summary>
/// <param name="lua">The Lua VM to add the methods to</param>
/// <param name="type">The class type to get the methods from</param>
public static void TaggedStaticMethods(Lua lua, Type type)
{
#region Sanity checks
if (lua == null) throw new ArgumentNullException("lua");
if (type == null) throw new ArgumentNullException("type");
if (!type.IsClass) throw new ArgumentException("The type must be a class!", "type");
#endregion
foreach (MethodInfo method in type.GetMethods(BindingFlags.Static | BindingFlags.Public))
{
foreach (LuaGlobalAttribute attribute in method.GetCustomAttributes(typeof(LuaGlobalAttribute), false))
{
if (string.IsNullOrEmpty(attribute.Name))
lua.RegisterFunction(method.Name, null, method); // CLR name
else
lua.RegisterFunction(attribute.Name, null, method); // Custom name
}
}
}
#endregion
#region Enumeration
/// <summary>
/// Registers an enumeration's values for usage as a Lua variable table
/// </summary>
/// <typeparam name="T">The enum type to register</typeparam>
/// <param name="lua">The Lua VM to add the enum to</param>
[SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter", Justification = "The type parameter is used to select an enum type")]
public static void Enumeration<T>(Lua lua)
{
#region Sanity checks
if (lua == null) throw new ArgumentNullException("lua");
#endregion
Type type = typeof(T);
if (!type.IsEnum) throw new ArgumentException("The type must be an enumeration!");
string[] names = Enum.GetNames(type);
var values = (T[])Enum.GetValues(type);
lua.NewTable(type.Name);
for (int i = 0; i < names.Length; i++)
{
string path = type.Name + "." + names[i];
lua[path] = values[i];
}
}
#endregion
}
}
using System;
namespace LuaInterface
{
/// <summary>
/// Exceptions thrown by the Lua runtime because of errors in the script
/// </summary>
public class LuaScriptException : LuaException
{
/// <summary>
/// Returns true if the exception has occured as the result of a .NET exception in user code
/// </summary>
public bool IsNetException { get; private set; }
private readonly string source;
/// <summary>
/// The position in the script where the exception was triggered.
/// </summary>
public override string Source { get { return source; } }
/// <summary>
/// Creates a new Lua-only exception.
/// </summary>
/// <param name="message">The message that describes the error.</param>
/// <param name="source">The position in the script where the exception was triggered.</param>
public LuaScriptException(string message, string source) : base(message)
{
this.source = source;
}
/// <summary>
/// Creates a new .NET wrapping exception.
/// </summary>
/// <param name="innerException">The .NET exception triggered by user-code.</param>
/// <param name="source">The position in the script where the exception was triggered.</param>
public LuaScriptException(Exception innerException, string source)
: base("A .NET exception occured in user-code", innerException)
{
this.source = source;
this.IsNetException = true;
}
public override string ToString()
{
// Prepend the error source
return GetType().FullName + ": " + source + Message;
}
}
}
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.Text;
using Lua511;
using System.Collections;
namespace LuaInterface
{
/*
* Wrapper class for Lua tables
*
* Author: Fabio Mascarenhas
* Version: 1.0
*/
public class LuaTable : LuaBase
{
//internal int _Reference;
//private Lua _Interpreter;
public LuaTable(int reference, Lua interpreter)
{
_Reference = reference;
_Interpreter = interpreter;
}
//bool disposed = false;
//~LuaTable()
//{
// Dispose(false);
//}
//public void Dispose()
//{
// Dispose(true);
// GC.SuppressFinalize(this);
//}
//public virtual void Dispose(bool disposeManagedResources)
//{
// if (!this.disposed)
// {
// if (disposeManagedResources)
// {
// if (_Reference != 0)
// _Interpreter.dispose(_Reference);
// }
// disposed = true;
// }
//}
//~LuaTable()
//{
// _Interpreter.dispose(_Reference);
//}
/*
* Indexer for string fields of the table
*/
public object this[string field]
{
get
{
return _Interpreter.getObject(_Reference, field);
}
set
{
_Interpreter.setObject(_Reference, field, value);
}
}
/*
* Indexer for numeric fields of the table
*/
public object this[object field]
{
get
{
return _Interpreter.getObject(_Reference, field);
}
set
{
_Interpreter.setObject(_Reference, field, value);
}
}
public System.Collections.IDictionaryEnumerator GetEnumerator()
{
return _Interpreter.GetTableDict(this).GetEnumerator();
}
public ICollection Keys
{
get { return _Interpreter.GetTableDict(this).Keys; }
}
public ICollection Values
{
get { return _Interpreter.GetTableDict(this).Values; }
}
/*
* Gets an string fields of a table ignoring its metatable,
* if it exists
*/
internal object rawget(string field)
{
return _Interpreter.rawGetObject(_Reference, field);
}
internal object rawgetFunction(string field)
{
object obj = _Interpreter.rawGetObject(_Reference, field);
if (obj is LuaCSFunction)
return new LuaFunction((LuaCSFunction)obj, _Interpreter);
else
return obj;
}
/*
* Pushes this table into the Lua stack
*/
internal void push(IntPtr luaState)
{
LuaDLL.lua_getref(luaState, _Reference);
}
public override string ToString()
{
return "table";
}
//public override bool Equals(object o)
//{
// if (o is LuaTable)
// {
// LuaTable l = (LuaTable)o;
// return _Interpreter.compareRef(l._Reference, _Reference);
// }
// else return false;
//}
//public override int GetHashCode()
//{
// return _Reference;
//}
}
}
using System;
using System.Collections.Generic;
using System.Text;
using Lua511;
namespace LuaInterface
{
public class LuaUserData : LuaBase
{
//internal int _Reference;
//private Lua _Interpreter;
public LuaUserData(int reference, Lua interpreter)
{
_Reference = reference;
_Interpreter = interpreter;
}
//~LuaUserData()
//{
// if (_Reference != 0)
// _Interpreter.dispose(_Reference);
//}
/*
* Indexer for string fields of the userdata
*/
public object this[string field]
{
get
{
return _Interpreter.getObject(_Reference, field);
}
set
{
_Interpreter.setObject(_Reference, field, value);
}
}
/*
* Indexer for numeric fields of the userdata
*/
public object this[object field]
{
get
{
return _Interpreter.getObject(_Reference, field);
}
set
{
_Interpreter.setObject(_Reference, field, value);
}
}
/*
* Calls the userdata and returns its return values inside
* an array
*/
public object[] Call(params object[] args)
{
return _Interpreter.callFunction(this, args);
}
/*
* Pushes the userdata into the Lua stack
*/
internal void push(IntPtr luaState)
{
LuaDLL.lua_getref(luaState, _Reference);
}
public override string ToString()
{
return "userdata";
}
//public override bool Equals(object o)
//{
// if (o is LuaUserData)
// {
// LuaUserData l = (LuaUserData)o;
// return _Interpreter.compareRef(l._Reference, _Reference);
// }
// else return false;
//}
//public override int GetHashCode()
//{
// return _Reference;
//}
}
}
namespace LuaInterface namespace LuaInterface
{ {
using System; using System;
using System.IO; using System.IO;
using System.Collections; using System.Collections;
using System.Reflection; using System.Reflection;
using System.Diagnostics; using System.Diagnostics;
using System.Collections.Generic; using System.Collections.Generic;
using LuaWrap; using Lua511;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
/* /*
* Functions used in the metatables of userdata representing * Functions used in the metatables of userdata representing
* CLR objects * CLR objects
* *
* Author: Fabio Mascarenhas * Author: Fabio Mascarenhas
* Version: 1.0 * Version: 1.0
*/ */
class MetaFunctions class MetaFunctions
{ {
/* /*
* __index metafunction for CLR objects. Implemented in Lua. * __index metafunction for CLR objects. Implemented in Lua.
*/ */
internal static string luaIndexFunction = internal static string luaIndexFunction =
"local function index(obj,name)\n" + "local function index(obj,name)\n" +
" local meta=getmetatable(obj)\n" + " local meta=getmetatable(obj)\n" +
" local cached=meta.cache[name]\n" + " local cached=meta.cache[name]\n" +
" if cached~=nil then\n" + " if cached~=nil then\n" +
" return cached\n" + " return cached\n" +
" else\n" + " else\n" +
" local value,isFunc=get_object_member(obj,name)\n" + " local value,isFunc=get_object_member(obj,name)\n" +
" if isFunc then\n" + " if isFunc then\n" +
" meta.cache[name]=value\n" + " meta.cache[name]=value\n" +
" end\n" + " end\n" +
" return value\n" + " return value\n" +
" end\n" + " end\n" +
"end\n" + "end\n" +
"return index"; "return index";
private ObjectTranslator translator; private ObjectTranslator translator;
private Hashtable memberCache = new Hashtable(); private Hashtable memberCache = new Hashtable();
internal KopiLua.Lua.lua_CFunction gcFunction, indexFunction, newindexFunction, internal LuaCSFunction gcFunction, indexFunction, newindexFunction,
baseIndexFunction, classIndexFunction, classNewindexFunction, baseIndexFunction, classIndexFunction, classNewindexFunction,
execDelegateFunction, callConstructorFunction, toStringFunction; execDelegateFunction, callConstructorFunction, toStringFunction;
public MetaFunctions(ObjectTranslator translator) public MetaFunctions(ObjectTranslator translator)
{ {
this.translator = translator; this.translator = translator;
gcFunction = new KopiLua.Lua.lua_CFunction(this.collectObject); gcFunction = new LuaCSFunction(this.collectObject);
toStringFunction = new KopiLua.Lua.lua_CFunction(this.toString); toStringFunction = new LuaCSFunction(this.toString);
indexFunction = new KopiLua.Lua.lua_CFunction(this.getMethod); indexFunction = new LuaCSFunction(this.getMethod);
newindexFunction = new KopiLua.Lua.lua_CFunction(this.setFieldOrProperty); newindexFunction = new LuaCSFunction(this.setFieldOrProperty);
baseIndexFunction = new KopiLua.Lua.lua_CFunction(this.getBaseMethod); baseIndexFunction = new LuaCSFunction(this.getBaseMethod);
callConstructorFunction = new KopiLua.Lua.lua_CFunction(this.callConstructor); callConstructorFunction = new LuaCSFunction(this.callConstructor);
classIndexFunction = new KopiLua.Lua.lua_CFunction(this.getClassMethod); classIndexFunction = new LuaCSFunction(this.getClassMethod);
classNewindexFunction = new KopiLua.Lua.lua_CFunction(this.setClassFieldOrProperty); classNewindexFunction = new LuaCSFunction(this.setClassFieldOrProperty);
execDelegateFunction = new KopiLua.Lua.lua_CFunction(this.runFunctionDelegate); execDelegateFunction = new LuaCSFunction(this.runFunctionDelegate);
} }
/* /*
* __call metafunction of CLR delegates, retrieves and calls the delegate. * __call metafunction of CLR delegates, retrieves and calls the delegate.
*/ */
private int runFunctionDelegate(KopiLua.Lua.lua_State luaState) private int runFunctionDelegate(IntPtr luaState)
{ {
KopiLua.Lua.lua_CFunction func = (KopiLua.Lua.lua_CFunction)translator.getRawNetObject(luaState, 1); LuaCSFunction func = (LuaCSFunction)translator.getRawNetObject(luaState, 1);
KopiLua.Lua.lua_remove(luaState, 1); LuaDLL.lua_remove(luaState, 1);
return func(luaState); return func(luaState);
} }
/* /*
* __gc metafunction of CLR objects. * __gc metafunction of CLR objects.
*/ */
private int collectObject(KopiLua.Lua.lua_State luaState) private int collectObject(IntPtr luaState)
{ {
int udata = LuaLib.luanet_rawnetobj(luaState, 1); int udata = LuaDLL.luanet_rawnetobj(luaState, 1);
if (udata != -1) if (udata != -1)
{ {
translator.collectObject(udata); translator.collectObject(udata);
} }
else else
{ {
// Debug.WriteLine("not found: " + udata); // Debug.WriteLine("not found: " + udata);
} }
return 0; return 0;
} }
/* /*
* __tostring metafunction of CLR objects. * __tostring metafunction of CLR objects.
*/ */
private int toString(KopiLua.Lua.lua_State luaState) private int toString(IntPtr luaState)
{ {
object obj = translator.getRawNetObject(luaState, 1); object obj = translator.getRawNetObject(luaState, 1);
if (obj != null) if (obj != null)
{ {
translator.push(luaState, obj.ToString() + ": " + obj.GetHashCode()); translator.push(luaState, obj.ToString() + ": " + obj.GetHashCode());
} }
else KopiLua.Lua.lua_pushnil(luaState); else LuaDLL.lua_pushnil(luaState);
return 1; return 1;
} }
/// <summary>
/// Debug tool to dump the lua stack /// <summary>
/// </summary> /// Debug tool to dump the lua stack
/// FIXME, move somewhere else /// </summary>
public static void dumpStack(ObjectTranslator translator, KopiLua.Lua.lua_State luaState) /// FIXME, move somewhere else
{ public static void dumpStack(ObjectTranslator translator, IntPtr luaState)
int depth = KopiLua.Lua.lua_gettop(luaState); {
int depth = LuaDLL.lua_gettop(luaState);
Debug.WriteLine("lua stack depth: " + depth);
for (int i = 1; i <= depth; i++) Debug.WriteLine("lua stack depth: " + depth);
{ for (int i = 1; i <= depth; i++)
LuaType type = KopiLua.Lua.lua_type(luaState, i).ToLuaType(); {
// we dump stacks when deep in calls, calling typename while the stack is in flux can fail sometimes, so manually check for key types LuaTypes type = LuaDLL.lua_type(luaState, i);
string typestr = (type == LuaType.Table) ? "table" : KopiLua.Lua.lua_typename(luaState, Convert.ToInt32(type)).ToString(); // we dump stacks when deep in calls, calling typename while the stack is in flux can fail sometimes, so manually check for key types
string typestr = (type == LuaTypes.LUA_TTABLE) ? "table" : LuaDLL.lua_typename(luaState, type);
string strrep = KopiLua.Lua.lua_tostring(luaState, i).ToString();
if (type == LuaType.UserData) string strrep = LuaDLL.lua_tostring(luaState, i);
{ if (type == LuaTypes.LUA_TUSERDATA)
object obj = translator.getRawNetObject(luaState, i); {
strrep = obj.ToString(); object obj = translator.getRawNetObject(luaState, i);
} strrep = obj.ToString();
}
Debug.Print("{0}: ({1}) {2}", i, typestr, strrep);
} Debug.Print("{0}: ({1}) {2}", i, typestr, strrep);
} }
}
/*
* 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 * Called by the __index metafunction of CLR objects in case the
* either the value of the member or a delegate to call it. * method is not cached or it is a field/property/event.
* If the member does not exist returns nil. * Receives the object and the member name as arguments and returns
*/ * either the value of the member or a delegate to call it.
private int getMethod(KopiLua.Lua.lua_State luaState) * If the member does not exist returns nil.
{ */
object obj = translator.getRawNetObject(luaState, 1); private int getMethod(IntPtr luaState)
if (obj == null) {
{ object obj = translator.getRawNetObject(luaState, 1);
translator.throwError(luaState, "trying to index an invalid object reference"); if (obj == null)
KopiLua.Lua.lua_pushnil(luaState); {
return 1; 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();
object index = translator.getObject(luaState, 2);
string methodName = index as string; // will be null if not a string arg Type indexType = index.GetType();
Type objType = obj.GetType();
string methodName = index as string; // will be null if not a string arg
// Handle the most common case, looking up the method by name Type objType = obj.GetType();
if (methodName != null && isMemberPresent(objType, methodName))
return getMember(luaState, objType, obj, methodName, BindingFlags.Instance); // Handle the most common case, looking up the method by name.
// Try to access by array if the type is right and index is an int (lua numbers always come across as double) // CP: This will fail when using indexers and attempting to get a value with the same name as a property of the object,
if (objType.IsArray && index is double) // ie: xmlelement['item'] <- item is a property of xmlelement
{ try
object[] arr = (object[])obj; {
if (methodName != null && isMemberPresent(objType, methodName))
translator.push(luaState, arr[(int)((double)index)]); return getMember(luaState, objType, obj, methodName, BindingFlags.Instance | BindingFlags.IgnoreCase);
} }
else catch { }
{
// Try to use get_Item to index into this .net object // Try to access by array if the type is right and index is an int (lua numbers always come across as double)
MethodInfo getter = objType.GetMethod("get_Item"); if (objType.IsArray && index is double)
ParameterInfo[] actualParms = (getter != null) ? getter.GetParameters() : null; {
int intIndex = (int)((double)index);
if (actualParms == null || actualParms.Length != 1)
{ if (objType.UnderlyingSystemType == typeof(float[]))
translator.throwError(luaState, "method not found (or no indexer): " + index); {
float[] arr = ((float[])obj);
KopiLua.Lua.lua_pushnil(luaState); translator.push(luaState, arr[intIndex]);
} }
else else if (objType.UnderlyingSystemType == typeof(double[]))
{ {
// Get the index in a form acceptable to the getter double[] arr = ((double[])obj);
index = translator.getAsType(luaState, 2, actualParms[0].ParameterType); translator.push(luaState, arr[intIndex]);
}
object[] args = new object[1]; else if (objType.UnderlyingSystemType == typeof(int[]))
{
// Just call the indexer - if out of bounds an exception will happen int[] arr = ((int[])obj);
args[0] = index; translator.push(luaState, arr[intIndex]);
try }
{ else
object result = getter.Invoke(obj, args); {
translator.push(luaState, result); object[] arr = (object[])obj;
} translator.push(luaState, arr[intIndex]);
catch (TargetInvocationException e) }
{ }
// Provide a more readable description for the common case of key not found else
if(e.InnerException is KeyNotFoundException) {
translator.throwError(luaState, "key '" + index + "' not found "); // Try to use get_Item to index into this .net object
else //MethodInfo getter = objType.GetMethod("get_Item");
translator.throwError(luaState, "exception indexing '" + index + "' " + e.Message); MethodInfo[] methods = objType.GetMethods();
KopiLua.Lua.lua_pushnil(luaState); foreach (MethodInfo mInfo in methods)
} {
} if (mInfo.Name == "get_Item")
} {
//check if the signature matches the input
KopiLua.Lua.lua_pushboolean(luaState, 0); if (mInfo.GetParameters().Length == 1)
return 2; {
} MethodInfo getter = mInfo;
ParameterInfo[] actualParms = (getter != null) ? getter.GetParameters() : null;
/* if (actualParms == null || actualParms.Length != 1)
* __index metafunction of base classes (the base field of Lua tables). {
* Adds a prefix to the method name to call the base version of the method. translator.throwError(luaState, "method not found (or no indexer): " + index);
*/
private int getBaseMethod(KopiLua.Lua.lua_State luaState) LuaDLL.lua_pushnil(luaState);
{ }
object obj = translator.getRawNetObject(luaState, 1); else
if (obj == null) {
{ // Get the index in a form acceptable to the getter
translator.throwError(luaState, "trying to index an invalid object reference"); index = translator.getAsType(luaState, 2, actualParms[0].ParameterType);
KopiLua.Lua.lua_pushnil(luaState);
KopiLua.Lua.lua_pushboolean(luaState, 0); object[] args = new object[1];
return 2;
} // Just call the indexer - if out of bounds an exception will happen
string methodName = KopiLua.Lua.lua_tostring(luaState, 2).ToString(); args[0] = index;
if (methodName == null) try
{ {
KopiLua.Lua.lua_pushnil(luaState); object result = getter.Invoke(obj, args);
KopiLua.Lua.lua_pushboolean(luaState, 0); translator.push(luaState, result);
return 2; }
} catch (TargetInvocationException e)
getMember(luaState, obj.GetType(), obj, "__luaInterface_base_" + methodName, BindingFlags.Instance); {
KopiLua.Lua.lua_settop(luaState, -2); // Provide a more readable description for the common case of key not found
if (KopiLua.Lua.lua_type(luaState, -1).ToLuaType() == LuaType.Nil) if (e.InnerException is KeyNotFoundException)
{ translator.throwError(luaState, "key '" + index + "' not found ");
KopiLua.Lua.lua_settop(luaState, -2); else
return getMember(luaState, obj.GetType(), obj, methodName, BindingFlags.Instance); translator.throwError(luaState, "exception indexing '" + index + "' " + e.Message);
}
KopiLua.Lua.lua_pushboolean(luaState, 0); LuaDLL.lua_pushnil(luaState);
return 2; }
} }
}
}
/// <summary> }
/// Does this method exist as either an instance or static?
/// </summary>
/// <param name="objType"></param> }
/// <param name="methodName"></param>
/// <returns></returns> LuaDLL.lua_pushboolean(luaState, false);
bool isMemberPresent(IReflect objType, string methodName) return 2;
{ }
object cachedMember = checkMemberCache(memberCache, objType, methodName);
if (cachedMember != null) /*
return true; * __index metafunction of base classes (the base field of Lua tables).
* Adds a prefix to the method name to call the base version of the method.
MemberInfo[] members = objType.GetMember(methodName, BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); */
return (members.Length > 0); private int getBaseMethod(IntPtr luaState)
} {
object obj = translator.getRawNetObject(luaState, 1);
/* if (obj == null)
* Pushes the value of a member or a delegate to call it, depending on the type of {
* the member. Works with static or instance members. translator.throwError(luaState, "trying to index an invalid object reference");
* Uses reflection to find members, and stores the reflected MemberInfo object in LuaDLL.lua_pushnil(luaState);
* a cache (indexed by the type of the object and the name of the member). LuaDLL.lua_pushboolean(luaState, false);
*/ return 2;
private int getMember(KopiLua.Lua.lua_State luaState, IReflect objType, object obj, string methodName, BindingFlags bindingType) }
{ string methodName = LuaDLL.lua_tostring(luaState, 2);
bool implicitStatic = false; if (methodName == null)
MemberInfo member = null; {
object cachedMember = checkMemberCache(memberCache, objType, methodName); LuaDLL.lua_pushnil(luaState);
//object cachedMember=null; LuaDLL.lua_pushboolean(luaState, false);
if (cachedMember is KopiLua.Lua.lua_CFunction) return 2;
{ }
translator.pushFunction(luaState, (KopiLua.Lua.lua_CFunction)cachedMember); getMember(luaState, obj.GetType(), obj, "__luaInterface_base_" + methodName, BindingFlags.Instance | BindingFlags.IgnoreCase);
translator.push(luaState, true); LuaDLL.lua_settop(luaState, -2);
return 2; if (LuaDLL.lua_type(luaState, -1) == LuaTypes.LUA_TNIL)
} {
else if (cachedMember != null) LuaDLL.lua_settop(luaState, -2);
{ return getMember(luaState, obj.GetType(), obj, methodName, BindingFlags.Instance | BindingFlags.IgnoreCase);
member = (MemberInfo)cachedMember; }
} LuaDLL.lua_pushboolean(luaState, false);
else return 2;
{ }
MemberInfo[] members = objType.GetMember(methodName, bindingType | BindingFlags.Public | BindingFlags.NonPublic);
if (members.Length > 0)
member = members[0]; /// <summary>
else /// Does this method exist as either an instance or static?
{ /// </summary>
// If we can't find any suitable instance members, try to find them as statics - but we only want to allow implicit static /// <param name="objType"></param>
// lookups for fields/properties/events -kevinh /// <param name="methodName"></param>
members = objType.GetMember(methodName, bindingType | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); /// <returns></returns>
bool isMemberPresent(IReflect objType, string methodName)
if (members.Length > 0) {
{ object cachedMember = checkMemberCache(memberCache, objType, methodName);
member = members[0];
implicitStatic = true; if (cachedMember != null)
} return true;
}
} //CP: Removed NonPublic binding search
if (member != null) MemberInfo[] members = objType.GetMember(methodName, BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase/* | BindingFlags.NonPublic*/);
{ return (members.Length > 0);
if (member.MemberType == MemberTypes.Field) }
{
FieldInfo field = (FieldInfo)member; /*
if (cachedMember == null) setMemberCache(memberCache, objType, methodName, member); * Pushes the value of a member or a delegate to call it, depending on the type of
try * the member. Works with static or instance members.
{ * Uses reflection to find members, and stores the reflected MemberInfo object in
translator.push(luaState, field.GetValue(obj)); * a cache (indexed by the type of the object and the name of the member).
} */
catch private int getMember(IntPtr luaState, IReflect objType, object obj, string methodName, BindingFlags bindingType)
{ {
KopiLua.Lua.lua_pushnil(luaState); bool implicitStatic = false;
} MemberInfo member = null;
} object cachedMember = checkMemberCache(memberCache, objType, methodName);
else if (member.MemberType == MemberTypes.Property) //object cachedMember=null;
{ if (cachedMember is LuaCSFunction)
PropertyInfo property = (PropertyInfo)member; {
if (cachedMember == null) setMemberCache(memberCache, objType, methodName, member); translator.pushFunction(luaState, (LuaCSFunction)cachedMember);
try translator.push(luaState, true);
{ return 2;
object val = property.GetValue(obj, null); }
else if (cachedMember != null)
translator.push(luaState, val); {
} member = (MemberInfo)cachedMember;
catch (ArgumentException) }
{ else
// If we can't find the getter in our class, recurse up to the base class and see {
// if they can help. //CP: Removed NonPublic binding search
MemberInfo[] members = objType.GetMember(methodName, bindingType | BindingFlags.Public | BindingFlags.IgnoreCase/*| BindingFlags.NonPublic*/);
if (objType is Type && !(((Type)objType) == typeof(object))) if (members.Length > 0)
return getMember(luaState, ((Type)objType).BaseType, obj, methodName, bindingType); member = members[0];
else else
KopiLua.Lua.lua_pushnil(luaState); {
} // If we can't find any suitable instance members, try to find them as statics - but we only want to allow implicit static
catch(TargetInvocationException e) // Convert this exception into a Lua error // lookups for fields/properties/events -kevinh
{ //CP: Removed NonPublic binding search and made case insensitive
ThrowError(luaState, e); members = objType.GetMember(methodName, bindingType | BindingFlags.Static | BindingFlags.Public | BindingFlags.IgnoreCase/*| BindingFlags.NonPublic*/);
KopiLua.Lua.lua_pushnil(luaState);
} if (members.Length > 0)
} {
else if (member.MemberType == MemberTypes.Event) member = members[0];
{ implicitStatic = true;
EventInfo eventInfo = (EventInfo)member; }
if (cachedMember == null) setMemberCache(memberCache, objType, methodName, member); }
translator.push(luaState, new RegisterEventHandler(translator.pendingEvents, obj, eventInfo)); }
} if (member != null)
else if(!implicitStatic) {
{ if (member.MemberType == MemberTypes.Field)
if (member.MemberType == MemberTypes.NestedType) {
{ FieldInfo field = (FieldInfo)member;
// kevinh - added support for finding nested types if (cachedMember == null) setMemberCache(memberCache, objType, methodName, member);
try
// cache us {
if (cachedMember == null) setMemberCache(memberCache, objType, methodName, member); translator.push(luaState, field.GetValue(obj));
}
// Find the name of our class catch
string name = member.Name; {
Type dectype = member.DeclaringType; LuaDLL.lua_pushnil(luaState);
}
// Build a new long name and try to find the type by name }
string longname = dectype.FullName + "+" + name; else if (member.MemberType == MemberTypes.Property)
Type nestedType = translator.FindType(longname); {
PropertyInfo property = (PropertyInfo)member;
translator.pushType(luaState, nestedType); if (cachedMember == null) setMemberCache(memberCache, objType, methodName, member);
} try
else {
{ object val = property.GetValue(obj, null);
// Member type must be 'method'
KopiLua.Lua.lua_CFunction wrapper = new KopiLua.Lua.lua_CFunction((new LuaMethodWrapper(translator, objType, methodName, bindingType)).call); translator.push(luaState, val);
if (cachedMember == null) setMemberCache(memberCache, objType, methodName, wrapper); }
translator.pushFunction(luaState, wrapper); catch (ArgumentException)
translator.push(luaState, true); {
return 2; // If we can't find the getter in our class, recurse up to the base class and see
} // if they can help.
}
else if (objType is Type && !(((Type)objType) == typeof(object)))
{ return getMember(luaState, ((Type)objType).BaseType, obj, methodName, bindingType);
// If we reach this point we found a static method, but can't use it in this context because the user passed in an instance else
translator.throwError(luaState, "can't pass instance to static method " + methodName); LuaDLL.lua_pushnil(luaState);
}
KopiLua.Lua.lua_pushnil(luaState); catch (TargetInvocationException e) // Convert this exception into a Lua error
} {
} ThrowError(luaState, e);
else LuaDLL.lua_pushnil(luaState);
{ }
// kevinh - we want to throw an exception because meerly returning 'nil' in this case }
// is not sufficient. valid data members may return nil and therefore there must be some else if (member.MemberType == MemberTypes.Event)
// way to know the member just doesn't exist. {
EventInfo eventInfo = (EventInfo)member;
translator.throwError(luaState, "unknown member name " + methodName); if (cachedMember == null) setMemberCache(memberCache, objType, methodName, member);
translator.push(luaState, new RegisterEventHandler(translator.pendingEvents, obj, eventInfo));
KopiLua.Lua.lua_pushnil(luaState); }
} else if (!implicitStatic)
{
// push false because we are NOT returning a function (see luaIndexFunction) if (member.MemberType == MemberTypes.NestedType)
translator.push(luaState, false); {
return 2; // kevinh - added support for finding nested types
}
/* // cache us
* Checks if a MemberInfo object is cached, returning it or null. if (cachedMember == null) setMemberCache(memberCache, objType, methodName, member);
*/
private object checkMemberCache(Hashtable memberCache, IReflect objType, string memberName) // Find the name of our class
{ string name = member.Name;
Hashtable members = (Hashtable)memberCache[objType]; Type dectype = member.DeclaringType;
if (members != null)
return members[memberName]; // Build a new long name and try to find the type by name
else string longname = dectype.FullName + "+" + name;
return null; Type nestedType = translator.FindType(longname);
}
/* translator.pushType(luaState, nestedType);
* Stores a MemberInfo object in the member cache. }
*/ else
private void setMemberCache(Hashtable memberCache, IReflect objType, string memberName, object member) {
{ // Member type must be 'method'
Hashtable members = (Hashtable)memberCache[objType]; LuaCSFunction wrapper = new LuaCSFunction((new LuaMethodWrapper(translator, objType, methodName, bindingType)).call);
if (members == null)
{ if (cachedMember == null) setMemberCache(memberCache, objType, methodName, wrapper);
members = new Hashtable(); translator.pushFunction(luaState, wrapper);
memberCache[objType] = members; translator.push(luaState, true);
} return 2;
members[memberName] = member; }
} }
/* else
* __newindex metafunction of CLR objects. Receives the object, {
* the member name and the value to be stored as arguments. Throws // If we reach this point we found a static method, but can't use it in this context because the user passed in an instance
* and error if the assignment is invalid. translator.throwError(luaState, "can't pass instance to static method " + methodName);
*/
private int setFieldOrProperty(KopiLua.Lua.lua_State luaState) LuaDLL.lua_pushnil(luaState);
{ }
object target = translator.getRawNetObject(luaState, 1); }
if (target == null) else
{ {
translator.throwError(luaState, "trying to index and invalid object reference"); // kevinh - we want to throw an exception because meerly returning 'nil' in this case
return 0; // is not sufficient. valid data members may return nil and therefore there must be some
} // way to know the member just doesn't exist.
Type type = target.GetType();
translator.throwError(luaState, "unknown member name " + methodName);
// First try to look up the parameter as a property name
string detailMessage; LuaDLL.lua_pushnil(luaState);
bool didMember = trySetMember(luaState, type, target, BindingFlags.Instance, out detailMessage); }
if (didMember) // push false because we are NOT returning a function (see luaIndexFunction)
return 0; // Must have found the property name translator.push(luaState, false);
return 2;
// We didn't find a property name, now see if we can use a [] style this accessor to set array contents }
try /*
{ * Checks if a MemberInfo object is cached, returning it or null.
if (type.IsArray && KopiLua.Lua.lua_isnumber(luaState, 2).ToBoolean()) */
{ private object checkMemberCache(Hashtable memberCache, IReflect objType, string memberName)
int index = (int)KopiLua.Lua.lua_tonumber(luaState, 2); {
Hashtable members = (Hashtable)memberCache[objType];
Array arr = (Array)target; if (members != null)
object val = translator.getAsType(luaState, 3, arr.GetType().GetElementType()); return members[memberName];
arr.SetValue(val, index); else
} return null;
else }
{ /*
// Try to see if we have a this[] accessor * Stores a MemberInfo object in the member cache.
MethodInfo setter = type.GetMethod("set_Item"); */
if (setter != null) private void setMemberCache(Hashtable memberCache, IReflect objType, string memberName, object member)
{ {
ParameterInfo[] args = setter.GetParameters(); Hashtable members = (Hashtable)memberCache[objType];
Type valueType = args[1].ParameterType; if (members == null)
{
// The new val ue the user specified members = new Hashtable();
object val = translator.getAsType(luaState, 3, valueType); memberCache[objType] = members;
}
Type indexType = args[0].ParameterType; members[memberName] = member;
object index = translator.getAsType(luaState, 2, indexType); }
/*
object[] methodArgs = new object[2]; * __newindex metafunction of CLR objects. Receives the object,
* the member name and the value to be stored as arguments. Throws
// Just call the indexer - if out of bounds an exception will happen * and error if the assignment is invalid.
methodArgs[0] = index; */
methodArgs[1] = val; private int setFieldOrProperty(IntPtr luaState)
{
setter.Invoke(target, methodArgs); object target = translator.getRawNetObject(luaState, 1);
} if (target == null)
else {
{ translator.throwError(luaState, "trying to index and invalid object reference");
translator.throwError(luaState, detailMessage); // Pass the original message from trySetMember because it is probably best return 0;
} }
} Type type = target.GetType();
}
catch (SEHException) // First try to look up the parameter as a property name
{ string detailMessage;
// If we are seeing a C++ exception - this must actually be for Lua's private use. Let it handle it bool didMember = trySetMember(luaState, type, target, BindingFlags.Instance | BindingFlags.IgnoreCase, out detailMessage);
throw;
} if (didMember)
catch (Exception e) return 0; // Must have found the property name
{
ThrowError(luaState, e); // We didn't find a property name, now see if we can use a [] style this accessor to set array contents
} try
return 0; {
} if (type.IsArray && LuaDLL.lua_isnumber(luaState, 2))
{
/// <summary> int index = (int)LuaDLL.lua_tonumber(luaState, 2);
/// Tries to set a named property or field
/// </summary> Array arr = (Array)target;
/// <param name="luaState"></param> object val = translator.getAsType(luaState, 3, arr.GetType().GetElementType());
/// <param name="targetType"></param> arr.SetValue(val, index);
/// <param name="target"></param> }
/// <param name="bindingType"></param> else
/// <returns>false if unable to find the named member, true for success</returns> {
private bool trySetMember(KopiLua.Lua.lua_State luaState, IReflect targetType, object target, BindingFlags bindingType, out string detailMessage) // Try to see if we have a this[] accessor
{ MethodInfo setter = type.GetMethod("set_Item");
detailMessage = null; // No error yet if (setter != null)
{
// If not already a string just return - we don't want to call tostring - which has the side effect of ParameterInfo[] args = setter.GetParameters();
// changing the lua typecode to string Type valueType = args[1].ParameterType;
// Note: We don't use isstring because the standard lua C isstring considers either strings or numbers to
// be true for isstring. // The new val ue the user specified
if (KopiLua.Lua.lua_type(luaState, 2).ToLuaType() != LuaType.String) object val = translator.getAsType(luaState, 3, valueType);
{
detailMessage = "property names must be strings"; Type indexType = args[0].ParameterType;
return false; object index = translator.getAsType(luaState, 2, indexType);
}
object[] methodArgs = new object[2];
// We only look up property names by string
string fieldName = KopiLua.Lua.lua_tostring(luaState, 2).ToString(); // Just call the indexer - if out of bounds an exception will happen
if (fieldName == null || fieldName.Length < 1 || !(char.IsLetter(fieldName[0]) || fieldName[0] == '_')) methodArgs[0] = index;
{ methodArgs[1] = val;
detailMessage = "invalid property name";
return false; setter.Invoke(target, methodArgs);
} }
else
// Find our member via reflection or the cache {
MemberInfo member = (MemberInfo)checkMemberCache(memberCache, targetType, fieldName); translator.throwError(luaState, detailMessage); // Pass the original message from trySetMember because it is probably best
if (member == null) }
{ }
MemberInfo[] members = targetType.GetMember(fieldName, bindingType | BindingFlags.Public | BindingFlags.NonPublic); }
if (members.Length > 0) catch (SEHException)
{ {
member = members[0]; // If we are seeing a C++ exception - this must actually be for Lua's private use. Let it handle it
setMemberCache(memberCache, targetType, fieldName, member); throw;
} }
else catch (Exception e)
{ {
detailMessage = "field or property '" + fieldName + "' does not exist"; ThrowError(luaState, e);
return false; }
} return 0;
} }
if (member.MemberType == MemberTypes.Field) /// <summary>
{ /// Tries to set a named property or field
FieldInfo field = (FieldInfo)member; /// </summary>
object val = translator.getAsType(luaState, 3, field.FieldType); /// <param name="luaState"></param>
try /// <param name="targetType"></param>
{ /// <param name="target"></param>
field.SetValue(target, val); /// <param name="bindingType"></param>
} /// <returns>false if unable to find the named member, true for success</returns>
catch (Exception e) private bool trySetMember(IntPtr luaState, IReflect targetType, object target, BindingFlags bindingType, out string detailMessage)
{ {
ThrowError(luaState, e); detailMessage = null; // No error yet
}
// We did a call // If not already a string just return - we don't want to call tostring - which has the side effect of
return true; // changing the lua typecode to string
} // Note: We don't use isstring because the standard lua C isstring considers either strings or numbers to
else if (member.MemberType == MemberTypes.Property) // be true for isstring.
{ if (LuaDLL.lua_type(luaState, 2) != LuaTypes.LUA_TSTRING)
PropertyInfo property = (PropertyInfo)member; {
object val = translator.getAsType(luaState, 3, property.PropertyType); detailMessage = "property names must be strings";
try return false;
{ }
property.SetValue(target, val, null);
} // We only look up property names by string
catch (Exception e) string fieldName = LuaDLL.lua_tostring(luaState, 2);
{ if (fieldName == null || fieldName.Length < 1 || !(char.IsLetter(fieldName[0]) || fieldName[0] == '_'))
ThrowError(luaState, e); {
} detailMessage = "invalid property name";
// We did a call return false;
return true; }
}
// Find our member via reflection or the cache
detailMessage = "'" + fieldName + "' is not a .net field or property"; MemberInfo member = (MemberInfo)checkMemberCache(memberCache, targetType, fieldName);
return false; if (member == null)
} {
//CP: Removed NonPublic binding search and made case insensitive
MemberInfo[] members = targetType.GetMember(fieldName, bindingType | BindingFlags.Public | BindingFlags.IgnoreCase/*| BindingFlags.NonPublic*/);
/* if (members.Length > 0)
* Writes to fields or properties, either static or instance. Throws an error {
* if the operation is invalid. member = members[0];
*/ setMemberCache(memberCache, targetType, fieldName, member);
private int setMember(KopiLua.Lua.lua_State luaState, IReflect targetType, object target, BindingFlags bindingType) }
{ else
string detail; {
bool success = trySetMember(luaState, targetType, target, bindingType, out detail); detailMessage = "field or property '" + fieldName + "' does not exist";
return false;
if(!success) }
translator.throwError(luaState, detail); }
return 0; if (member.MemberType == MemberTypes.Field)
} {
FieldInfo field = (FieldInfo)member;
/// <summary> object val = translator.getAsType(luaState, 3, field.FieldType);
/// Convert a C# exception into a Lua error try
/// </summary> {
/// <param name="e"></param> field.SetValue(target, val);
/// We try to look into the exception to give the most meaningful description }
void ThrowError(KopiLua.Lua.lua_State luaState, Exception e) catch (Exception e)
{ {
// If we got inside a reflection show what really happened ThrowError(luaState, e);
TargetInvocationException te = e as TargetInvocationException; }
// We did a call
if (te != null) return true;
e = te.InnerException; }
else if (member.MemberType == MemberTypes.Property)
translator.throwError(luaState, e); {
} PropertyInfo property = (PropertyInfo)member;
object val = translator.getAsType(luaState, 3, property.PropertyType);
/* try
* __index metafunction of type references, works on static members. {
*/ property.SetValue(target, val, null);
private int getClassMethod(KopiLua.Lua.lua_State luaState) }
{ catch (Exception e)
IReflect klass; {
object obj = translator.getRawNetObject(luaState, 1); ThrowError(luaState, e);
if (obj == null || !(obj is IReflect)) }
{ // We did a call
translator.throwError(luaState, "trying to index an invalid type reference"); return true;
KopiLua.Lua.lua_pushnil(luaState); }
return 1;
} detailMessage = "'" + fieldName + "' is not a .net field or property";
else klass = (IReflect)obj; return false;
if (KopiLua.Lua.lua_isnumber(luaState, 2).ToBoolean()) }
{
int size = (int)KopiLua.Lua.lua_tonumber(luaState, 2);
translator.push(luaState, Array.CreateInstance(klass.UnderlyingSystemType, size)); /*
return 1; * Writes to fields or properties, either static or instance. Throws an error
} * if the operation is invalid.
else */
{ private int setMember(IntPtr luaState, IReflect targetType, object target, BindingFlags bindingType)
string methodName = KopiLua.Lua.lua_tostring(luaState, 2).ToString(); {
if (methodName == null) string detail;
{ bool success = trySetMember(luaState, targetType, target, bindingType, out detail);
KopiLua.Lua.lua_pushnil(luaState);
return 1; if (!success)
} translator.throwError(luaState, detail);
else return getMember(luaState, klass, null, methodName, BindingFlags.FlattenHierarchy | BindingFlags.Static);
} return 0;
} }
/*
* __newindex function of type references, works on static members. /// <summary>
*/ /// Convert a C# exception into a Lua error
private int setClassFieldOrProperty(KopiLua.Lua.lua_State luaState) /// </summary>
{ /// <param name="e"></param>
IReflect target; /// We try to look into the exception to give the most meaningful description
object obj = translator.getRawNetObject(luaState, 1); void ThrowError(IntPtr luaState, Exception e)
if (obj == null || !(obj is IReflect)) {
{ // If we got inside a reflection show what really happened
translator.throwError(luaState, "trying to index an invalid type reference"); TargetInvocationException te = e as TargetInvocationException;
return 0;
} if (te != null)
else target = (IReflect)obj; e = te.InnerException;
return setMember(luaState, target, null, BindingFlags.FlattenHierarchy | BindingFlags.Static);
} translator.throwError(luaState, e);
/* }
* __call metafunction of type references. Searches for and calls
* a constructor for the type. Returns nil if the constructor is not /*
* found or if the arguments are invalid. Throws an error if the constructor * __index metafunction of type references, works on static members.
* generates an exception. */
*/ private int getClassMethod(IntPtr luaState)
private int callConstructor(KopiLua.Lua.lua_State luaState) {
{ IReflect klass;
MethodCache validConstructor = new MethodCache(); object obj = translator.getRawNetObject(luaState, 1);
IReflect klass; if (obj == null || !(obj is IReflect))
object obj = translator.getRawNetObject(luaState, 1); {
if (obj == null || !(obj is IReflect)) translator.throwError(luaState, "trying to index an invalid type reference");
{ LuaDLL.lua_pushnil(luaState);
translator.throwError(luaState, "trying to call constructor on an invalid type reference"); return 1;
KopiLua.Lua.lua_pushnil(luaState); }
return 1; else klass = (IReflect)obj;
} if (LuaDLL.lua_isnumber(luaState, 2))
else klass = (IReflect)obj; {
KopiLua.Lua.lua_remove(luaState, 1); int size = (int)LuaDLL.lua_tonumber(luaState, 2);
ConstructorInfo[] constructors = klass.UnderlyingSystemType.GetConstructors(); translator.push(luaState, Array.CreateInstance(klass.UnderlyingSystemType, size));
foreach (ConstructorInfo constructor in constructors) return 1;
{ }
bool isConstructor = matchParameters(luaState, constructor, ref validConstructor); else
if (isConstructor) {
{ string methodName = LuaDLL.lua_tostring(luaState, 2);
try if (methodName == null)
{ {
translator.push(luaState, constructor.Invoke(validConstructor.args)); LuaDLL.lua_pushnil(luaState);
} return 1;
catch (TargetInvocationException e) } //CP: Ignore case
{ else return getMember(luaState, klass, null, methodName, BindingFlags.FlattenHierarchy | BindingFlags.Static | BindingFlags.IgnoreCase);
ThrowError(luaState, e); }
KopiLua.Lua.lua_pushnil(luaState); }
} /*
catch * __newindex function of type references, works on static members.
{ */
KopiLua.Lua.lua_pushnil(luaState); private int setClassFieldOrProperty(IntPtr luaState)
} {
return 1; IReflect target;
} object obj = translator.getRawNetObject(luaState, 1);
} if (obj == null || !(obj is IReflect))
{
string constructorName = (constructors.Length == 0) ? "unknown" : constructors[0].Name; translator.throwError(luaState, "trying to index an invalid type reference");
return 0;
translator.throwError(luaState, String.Format("{0} does not contain constructor({1}) argument match", }
klass.UnderlyingSystemType, else target = (IReflect)obj;
constructorName)); return setMember(luaState, target, null, BindingFlags.FlattenHierarchy | BindingFlags.Static | BindingFlags.IgnoreCase);
KopiLua.Lua.lua_pushnil(luaState); }
return 1; /*
} * __call metafunction of type references. Searches for and calls
/* * a constructor for the type. Returns nil if the constructor is not
* Matches a method against its arguments in the Lua stack. Returns * found or if the arguments are invalid. Throws an error if the constructor
* if the match was succesful. It it was also returns the information * generates an exception.
* necessary to invoke the method. */
*/ private int callConstructor(IntPtr luaState)
internal bool matchParameters(KopiLua.Lua.lua_State luaState, MethodBase method, ref MethodCache methodCache) {
{ MethodCache validConstructor = new MethodCache();
ExtractValue extractValue; IReflect klass;
bool isMethod = true; object obj = translator.getRawNetObject(luaState, 1);
ParameterInfo[] paramInfo = method.GetParameters(); if (obj == null || !(obj is IReflect))
int currentLuaParam = 1; {
int nLuaParams = KopiLua.Lua.lua_gettop(luaState); translator.throwError(luaState, "trying to call constructor on an invalid type reference");
ArrayList paramList = new ArrayList(); LuaDLL.lua_pushnil(luaState);
List<int> outList = new List<int>(); return 1;
List<MethodArgs> argTypes = new List<MethodArgs>(); }
foreach (ParameterInfo currentNetParam in paramInfo) else klass = (IReflect)obj;
{ LuaDLL.lua_remove(luaState, 1);
if (!currentNetParam.IsIn && currentNetParam.IsOut) // Skips out params ConstructorInfo[] constructors = klass.UnderlyingSystemType.GetConstructors();
{ foreach (ConstructorInfo constructor in constructors)
outList.Add(paramList.Add(null)); {
} bool isConstructor = matchParameters(luaState, constructor, ref validConstructor);
else if (currentLuaParam > nLuaParams) // Adds optional parameters if (isConstructor)
{ {
if (currentNetParam.IsOptional) try
{ {
paramList.Add(currentNetParam.DefaultValue); translator.push(luaState, constructor.Invoke(validConstructor.args));
} }
else catch (TargetInvocationException e)
{ {
isMethod = false; ThrowError(luaState, e);
break; LuaDLL.lua_pushnil(luaState);
} }
} catch
else if ((extractValue = translator.typeChecker.checkType(luaState, currentLuaParam, currentNetParam.ParameterType)) != null) // Type checking {
{ LuaDLL.lua_pushnil(luaState);
int index = paramList.Add(extractValue(luaState, currentLuaParam)); }
MethodArgs methodArg = new MethodArgs(); return 1;
methodArg.index = index; }
methodArg.extractValue = extractValue; }
argTypes.Add(methodArg);
if (currentNetParam.ParameterType.IsByRef) string constructorName = (constructors.Length == 0) ? "unknown" : constructors[0].Name;
outList.Add(index);
currentLuaParam++; translator.throwError(luaState, String.Format("{0} does not contain constructor({1}) argument match",
} // Type does not match, ignore if the parameter is optional klass.UnderlyingSystemType,
else if (currentNetParam.IsOptional) constructorName));
{ LuaDLL.lua_pushnil(luaState);
paramList.Add(currentNetParam.DefaultValue); return 1;
} }
else // No match /*
{ * Matches a method against its arguments in the Lua stack. Returns
isMethod = false; * if the match was succesful. It it was also returns the information
break; * necessary to invoke the method.
} */
} internal bool matchParameters(IntPtr luaState, MethodBase method, ref MethodCache methodCache)
if (currentLuaParam != nLuaParams + 1) // Number of parameters does not match {
isMethod = false; ExtractValue extractValue;
if (isMethod) bool isMethod = true;
{ ParameterInfo[] paramInfo = method.GetParameters();
methodCache.args = paramList.ToArray(); int currentLuaParam = 1;
methodCache.cachedMethod = method; int nLuaParams = LuaDLL.lua_gettop(luaState);
methodCache.outList = outList.ToArray(); ArrayList paramList = new ArrayList();
methodCache.argTypes = argTypes.ToArray(); List<int> outList = new List<int>();
} List<MethodArgs> argTypes = new List<MethodArgs>();
return isMethod; foreach (ParameterInfo 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));
MethodArgs 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);
Type paramArrayType = currentNetParam.ParameterType.GetElementType();
Array paramArray;
if (luaParamValue is LuaTable)
{
LuaTable table = (LuaTable)luaParamValue;
IDictionaryEnumerator 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);
MethodArgs 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;
}
/// <summary>
/// CP: Fix for operator overloading failure
/// Returns true if the type is set and assigns the extract value
/// </summary>
/// <param name="luaState"></param>
/// <param name="currentLuaParam"></param>
/// <param name="currentNetParam"></param>
/// <param name="extractValue"></param>
/// <returns></returns>
private bool _IsTypeCorrect(IntPtr luaState, int currentLuaParam, ParameterInfo currentNetParam, out ExtractValue extractValue)
{
try
{
return (extractValue = translator.typeChecker.checkType(luaState, currentLuaParam, currentNetParam.ParameterType)) != null;
}
catch
{
extractValue = null;
Debug.WriteLine("Type wasn't correct");
return false;
}
}
private bool _IsParamsArray(IntPtr luaState, int currentLuaParam, ParameterInfo currentNetParam, out ExtractValue extractValue)
{
extractValue = null;
if (currentNetParam.GetCustomAttributes(typeof(ParamArrayAttribute), false).Length > 0)
{
LuaTypes luaType;
try
{
luaType = LuaDLL.lua_type(luaState, currentLuaParam);
}
catch (Exception ex)
{
Debug.WriteLine("Could not retrieve lua type while attempting to determine params Array Status.");
Debug.WriteLine(ex.Message);
extractValue = null;
return false;
}
if (luaType == LuaTypes.LUA_TTABLE)
{
try
{
extractValue = translator.typeChecker.getExtractor(typeof(LuaTable));
}
catch (Exception ex)
{
Debug.WriteLine("An error occurred during an attempt to retrieve a LuaTable extractor while checking for params array status.");
}
if (extractValue != null)
{
return true;
}
}
else
{
Type paramElementType = currentNetParam.ParameterType.GetElementType();
try
{
extractValue = translator.typeChecker.checkType(luaState, currentLuaParam, paramElementType);
}
catch (Exception ex)
{
Debug.WriteLine(string.Format("An error occurred during an attempt to retrieve an extractor ({0}) while checking for params array status.", paramElementType.FullName));
}
if (extractValue != null)
{
return true;
}
}
}
Debug.WriteLine("Type wasn't Params object.");
return false;
}
}
} }
\ No newline at end of file
namespace LuaInterface namespace LuaInterface
{ {
using System; using System;
using System.IO; using System.IO;
using System.Collections; using System.Collections;
using System.Reflection; using System.Reflection;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using LuaWrap; using Lua511;
/* /*
* Cached method * Cached method
*/ */
struct MethodCache struct MethodCache
{ {
public MethodBase cachedMethod; private MethodBase _cachedMethod;
// List or arguments
public object[] args; public MethodBase cachedMethod
// Positions of out parameters {
public int[] outList; get
// Types of parameters {
public MethodArgs[] argTypes; return _cachedMethod;
} }
set
/* {
* Parameter information _cachedMethod = value;
*/ MethodInfo mi = value as MethodInfo;
struct MethodArgs if (mi != null)
{ {
// Position of parameter IsReturnVoid = string.Compare(mi.ReturnType.Name, "System.Void", true) == 0;
public int index; }
// Type-conversion function }
public ExtractValue extractValue; }
}
public bool IsReturnVoid;
/*
* Argument extraction with type-conversion function // List or arguments
*/ public object[] args;
delegate object ExtractValue(KopiLua.Lua.lua_State luaState, int stackPos); // Positions of out parameters
public int[] outList;
/* // Types of parameters
* Wrapper class for methods/constructors accessed from Lua. public MethodArgs[] argTypes;
* }
* Author: Fabio Mascarenhas
* Version: 1.0 /*
*/ * Parameter information
class LuaMethodWrapper */
{ struct MethodArgs
ObjectTranslator translator; {
MethodBase method; // Position of parameter
MethodCache lastCalledMethod=new MethodCache(); public int index;
string methodName; // Type-conversion function
MemberInfo[] members; public ExtractValue extractValue;
IReflect targetType;
ExtractValue extractTarget; public bool isParamsArray;
object target;
BindingFlags bindingType; public Type paramsArrayType;
/* }
* Constructs the wrapper for a known MethodBase instance
*/ /*
public LuaMethodWrapper(ObjectTranslator translator, object target, IReflect targetType, MethodBase method) * Argument extraction with type-conversion function
{ */
this.translator=translator; delegate object ExtractValue(IntPtr luaState, int stackPos);
this.target=target;
this.targetType=targetType; /*
if(targetType!=null) * Wrapper class for methods/constructors accessed from Lua.
extractTarget=translator.typeChecker.getExtractor(targetType); *
this.method=method; * Author: Fabio Mascarenhas
this.methodName=method.Name; * Version: 1.0
if(method.IsStatic) { bindingType=BindingFlags.Static; } */
else { bindingType=BindingFlags.Instance; } class LuaMethodWrapper
} {
/* private ObjectTranslator _Translator;
* Constructs the wrapper for a known method name private MethodBase _Method;
*/ private MethodCache _LastCalledMethod = new MethodCache();
public LuaMethodWrapper(ObjectTranslator translator, IReflect targetType, string methodName, BindingFlags bindingType) private string _MethodName;
{ private MemberInfo[] _Members;
this.translator=translator; private IReflect _TargetType;
this.methodName=methodName; private ExtractValue _ExtractTarget;
this.targetType=targetType; private object _Target;
if(targetType!=null) private BindingFlags _BindingType;
extractTarget=translator.typeChecker.getExtractor(targetType);
this.bindingType=bindingType; /*
members=targetType.UnderlyingSystemType.GetMember(methodName,MemberTypes.Method,bindingType|BindingFlags.Public|BindingFlags.NonPublic); * Constructs the wrapper for a known MethodBase instance
} */
public LuaMethodWrapper(ObjectTranslator translator, object target, IReflect targetType, MethodBase method)
{
/// <summary> _Translator = translator;
/// Convert C# exceptions into Lua errors _Target = target;
/// </summary> _TargetType = targetType;
/// <returns>num of things on stack</returns> if (targetType != null)
/// <param name="e">null for no pending exception</param> _ExtractTarget = translator.typeChecker.getExtractor(targetType);
int SetPendingException(Exception e) _Method = method;
{ _MethodName = method.Name;
return translator.interpreter.SetPendingException(e);
} if (method.IsStatic)
{ _BindingType = BindingFlags.Static; }
else
/* { _BindingType = BindingFlags.Instance; }
* Calls the method. Receives the arguments from the Lua stack }
* and returns values in it. /*
*/ * Constructs the wrapper for a known method name
public int call(KopiLua.Lua.lua_State luaState) */
{ public LuaMethodWrapper(ObjectTranslator translator, IReflect targetType, string methodName, BindingFlags bindingType)
MethodBase methodToCall=method; {
object targetObject=target; _Translator = translator;
bool failedCall=true; _MethodName = methodName;
int nReturnValues=0; _TargetType = targetType;
Console.WriteLine("asyyyyyyyyyyyyyy");
if(!KopiLua.Lua.lua_checkstack(luaState,5).ToBoolean()) if (targetType != null)
throw new LuaException("Lua stack overflow"); _ExtractTarget = translator.typeChecker.getExtractor(targetType);
Console.WriteLine("asyyyyyyyyyyyyyy1");
bool isStatic = (bindingType & BindingFlags.Static) == BindingFlags.Static; _BindingType = bindingType;
Console.WriteLine("asyyyyyyyyyyyyyy2");
SetPendingException(null); //CP: Removed NonPublic binding search and added IgnoreCase
Console.WriteLine("asyyyyyyyyyyyyyy3"); _Members = targetType.UnderlyingSystemType.GetMember(methodName, MemberTypes.Method, bindingType | BindingFlags.Public | BindingFlags.IgnoreCase/*|BindingFlags.NonPublic*/);
Console.WriteLine(methodToCall==null); }
if(methodToCall==null) // Method from name
{
if (isStatic) /// <summary>
targetObject=null; /// Convert C# exceptions into Lua errors
else /// </summary>
targetObject=extractTarget(luaState,1); /// <returns>num of things on stack</returns>
//KopiLua.Lua.lua_remove(luaState,1); // Pops the receiver /// <param name="e">null for no pending exception</param>
Console.WriteLine("asdxxxxxx"); int SetPendingException(Exception e)
Console.WriteLine(lastCalledMethod.cachedMethod); {
Console.WriteLine(lastCalledMethod.cachedMethod!=null); return _Translator.interpreter.SetPendingException(e);
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 = KopiLua.Lua.lua_gettop(luaState) - numStackToSkip; /*
* Calls the method. Receives the arguments from the Lua stack
if(numArgsPassed == lastCalledMethod.argTypes.Length) // No. of args match? * and returns values in it.
{ */
if(!KopiLua.Lua.lua_checkstack(luaState,lastCalledMethod.outList.Length+6).ToBoolean()) public int call(IntPtr luaState)
throw new LuaException("Lua stack overflow"); {
try MethodBase methodToCall = _Method;
{ object targetObject = _Target;
Console.WriteLine("0"); bool failedCall = true;
Console.WriteLine(lastCalledMethod.argTypes.Length); int nReturnValues = 0;
for(int i=0;i<lastCalledMethod.argTypes.Length;i++)
{ if (!LuaDLL.lua_checkstack(luaState, 5))
lastCalledMethod.args[lastCalledMethod.argTypes[i].index]= throw new LuaException("Lua stack overflow");
lastCalledMethod.argTypes[i].extractValue(luaState, i + 1 + numStackToSkip);
bool isStatic = (_BindingType & BindingFlags.Static) == BindingFlags.Static;
if(lastCalledMethod.args[lastCalledMethod.argTypes[i].index]==null &&
!KopiLua.Lua.lua_isnil(luaState, i + 1 + numStackToSkip)) SetPendingException(null);
{
throw new LuaException("argument number "+(i+1)+" is invalid"); if (methodToCall == null) // Method from name
} {
} if (isStatic)
Console.WriteLine("asd"); targetObject = null;
if((bindingType & BindingFlags.Static)==BindingFlags.Static) else
{ targetObject = _ExtractTarget(luaState, 1);
translator.push(luaState,lastCalledMethod.cachedMethod.Invoke(null,lastCalledMethod.args));
} //LuaDLL.lua_remove(luaState,1); // Pops the receiver
else if (_LastCalledMethod.cachedMethod != null) // Cached?
{ {
Console.WriteLine("asd2"); int numStackToSkip = isStatic ? 0 : 1; // If this is an instance invoe we will have an extra arg on the stack for the targetObject
if(lastCalledMethod.cachedMethod.IsConstructor) int numArgsPassed = LuaDLL.lua_gettop(luaState) - numStackToSkip;
translator.push(luaState,((ConstructorInfo)lastCalledMethod.cachedMethod).Invoke(lastCalledMethod.args));
else if (numArgsPassed == _LastCalledMethod.argTypes.Length) // No. of args match?
translator.push(luaState,lastCalledMethod.cachedMethod.Invoke(targetObject,lastCalledMethod.args)); {
} if (!LuaDLL.lua_checkstack(luaState, _LastCalledMethod.outList.Length + 6))
failedCall=false; throw new LuaException("Lua stack overflow");
}
catch(TargetInvocationException e) try
{ {
// Failure of method invocation for (int i = 0; i < _LastCalledMethod.argTypes.Length; i++)
return SetPendingException(e.GetBaseException()); {
} if (_LastCalledMethod.argTypes[i].isParamsArray)
catch(Exception e) {
{ object luaParamValue = _LastCalledMethod.argTypes[i].extractValue(luaState, i + 1 + numStackToSkip);
if(members.Length==1) // Is the method overloaded?
// No, throw error Type paramArrayType = _LastCalledMethod.argTypes[i].paramsArrayType;
return SetPendingException(e);
} Array paramArray;
}
} if (luaParamValue is LuaTable)
{
// Cache miss LuaTable table = (LuaTable)luaParamValue;
if(failedCall)
{ paramArray = Array.CreateInstance(paramArrayType, table.Values.Count);
// System.Diagnostics.Debug.WriteLine("cache miss on " + methodName);
for (int x = 1; x <= table.Values.Count; x++)
// If we are running an instance variable, we can now pop the targetObject from the stack {
if (!isStatic) paramArray.SetValue(Convert.ChangeType(table[x], paramArrayType), x - 1);
{ }
if (targetObject == null) }
{ else
translator.throwError(luaState, String.Format("instance method '{0}' requires a non null target object", methodName)); {
KopiLua.Lua.lua_pushnil(luaState); paramArray = Array.CreateInstance(paramArrayType, 1);
return 1; paramArray.SetValue(luaParamValue, 0);
} }
KopiLua.Lua.lua_remove(luaState, 1); // Pops the receiver _LastCalledMethod.args[_LastCalledMethod.argTypes[i].index] = paramArray;
} }
else
bool hasMatch=false; {
string candidateName = null; _LastCalledMethod.args[_LastCalledMethod.argTypes[i].index] =
_LastCalledMethod.argTypes[i].extractValue(luaState, i + 1 + numStackToSkip);
foreach(MemberInfo member in members) }
{
candidateName = member.ReflectedType.Name + "." + member.Name; if (_LastCalledMethod.args[_LastCalledMethod.argTypes[i].index] == null &&
!LuaDLL.lua_isnil(luaState, i + 1 + numStackToSkip))
MethodBase m=(MethodInfo)member; {
throw new LuaException("argument number " + (i + 1) + " is invalid");
bool isMethod=translator.matchParameters(luaState,m,ref lastCalledMethod); }
if(isMethod) }
{ if ((_BindingType & BindingFlags.Static) == BindingFlags.Static)
hasMatch=true; {
break; _Translator.push(luaState, _LastCalledMethod.cachedMethod.Invoke(null, _LastCalledMethod.args));
} }
} else
if(!hasMatch) {
{ if (_LastCalledMethod.cachedMethod.IsConstructor)
string msg = (candidateName == null) _Translator.push(luaState, ((ConstructorInfo)_LastCalledMethod.cachedMethod).Invoke(_LastCalledMethod.args));
? "invalid arguments to method call" else
: ("invalid arguments to method: " + candidateName); _Translator.push(luaState, _LastCalledMethod.cachedMethod.Invoke(targetObject, _LastCalledMethod.args));
}
translator.throwError(luaState, msg); failedCall = false;
KopiLua.Lua.lua_pushnil(luaState); }
return 1; catch (TargetInvocationException e)
} {
} // Failure of method invocation
} return SetPendingException(e.GetBaseException());
else // Method from MethodBase instance }
{ catch (Exception e)
if(!methodToCall.IsStatic && !methodToCall.IsConstructor && targetObject==null) {
{ if (_Members.Length == 1) // Is the method overloaded?
targetObject=extractTarget(luaState,1); // No, throw error
KopiLua.Lua.lua_remove(luaState,1); // Pops the receiver return SetPendingException(e);
} }
if(!translator.matchParameters(luaState,methodToCall,ref lastCalledMethod)) }
{ }
translator.throwError(luaState,"invalid arguments to method call");
KopiLua.Lua.lua_pushnil(luaState); // Cache miss
return 1; if (failedCall)
} {
} // System.Diagnostics.Debug.WriteLine("cache miss on " + methodName);
if(failedCall) // If we are running an instance variable, we can now pop the targetObject from the stack
{ if (!isStatic)
if(!KopiLua.Lua.lua_checkstack(luaState,lastCalledMethod.outList.Length+6).ToBoolean()) {
throw new LuaException("Lua stack overflow"); if (targetObject == null)
try {
{ _Translator.throwError(luaState, String.Format("instance method '{0}' requires a non null target object", _MethodName));
if (isStatic) LuaDLL.lua_pushnil(luaState);
{ return 1;
translator.push(luaState,lastCalledMethod.cachedMethod.Invoke(null,lastCalledMethod.args)); }
}
else LuaDLL.lua_remove(luaState, 1); // Pops the receiver
{ }
if(lastCalledMethod.cachedMethod.IsConstructor)
translator.push(luaState,((ConstructorInfo)lastCalledMethod.cachedMethod).Invoke(lastCalledMethod.args)); bool hasMatch = false;
else string candidateName = null;
translator.push(luaState,lastCalledMethod.cachedMethod.Invoke(targetObject,lastCalledMethod.args));
} foreach (MemberInfo member in _Members)
} {
catch(TargetInvocationException e) candidateName = member.ReflectedType.Name + "." + member.Name;
{
return SetPendingException(e.GetBaseException()); MethodBase m = (MethodInfo)member;
}
catch(Exception e) bool isMethod = _Translator.matchParameters(luaState, m, ref _LastCalledMethod);
{ if (isMethod)
return SetPendingException(e); {
} hasMatch = true;
} break;
}
// Pushes out and ref return values }
for(int index=0;index<lastCalledMethod.outList.Length;index++) if (!hasMatch)
{ {
nReturnValues++; string msg = (candidateName == null)
//for(int i=0;i<lastCalledMethod.outList.Length;i++) ? "invalid arguments to method call"
translator.push(luaState,lastCalledMethod.args[lastCalledMethod.outList[index]]); : ("invalid arguments to method: " + candidateName);
}
return nReturnValues < 1 ? 1 : nReturnValues; _Translator.throwError(luaState, msg);
} LuaDLL.lua_pushnil(luaState);
} return 1;
}
}
}
else // Method from MethodBase instance
/// <summary> {
/// We keep track of what delegates we have auto attached to an event - to allow us to cleanly exit a LuaInterface session if (methodToCall.ContainsGenericParameters)
/// </summary> {
class EventHandlerContainer : IDisposable bool isMethod = _Translator.matchParameters(luaState, methodToCall, ref _LastCalledMethod);
{
Dictionary<Delegate, RegisterEventHandler> dict = new Dictionary<Delegate, RegisterEventHandler>(); if (methodToCall.IsGenericMethodDefinition)
{
public void Add(Delegate handler, RegisterEventHandler eventInfo) //need to make a concrete type of the generic method definition
{ List<Type> typeArgs = new List<Type>();
dict.Add(handler, eventInfo);
} foreach (object arg in _LastCalledMethod.args)
typeArgs.Add(arg.GetType());
public void Remove(Delegate handler)
{ MethodInfo concreteMethod = (methodToCall as MethodInfo).MakeGenericMethod(typeArgs.ToArray());
bool found = dict.Remove(handler);
Debug.Assert(found); _Translator.push(luaState, concreteMethod.Invoke(targetObject, _LastCalledMethod.args));
} failedCall = false;
}
/// <summary> else if (methodToCall.ContainsGenericParameters)
/// Remove any still registered handlers {
/// </summary> _Translator.throwError(luaState, "unable to invoke method on generic class as the current method is an open generic method");
public void Dispose() LuaDLL.lua_pushnil(luaState);
{ return 1;
foreach (KeyValuePair<Delegate, RegisterEventHandler> pair in dict) }
{ }
pair.Value.RemovePending(pair.Key); else
} {
if (!methodToCall.IsStatic && !methodToCall.IsConstructor && targetObject == null)
dict.Clear(); {
} targetObject = _ExtractTarget(luaState, 1);
} LuaDLL.lua_remove(luaState, 1); // Pops the receiver
}
/* if (!_Translator.matchParameters(luaState, methodToCall, ref _LastCalledMethod))
* Wrapper class for events that does registration/deregistration {
* of event handlers. _Translator.throwError(luaState, "invalid arguments to method call");
* LuaDLL.lua_pushnil(luaState);
* Author: Fabio Mascarenhas return 1;
* Version: 1.0 }
*/ }
class RegisterEventHandler }
{
object target; if (failedCall)
EventInfo eventInfo; {
EventHandlerContainer pendingEvents; if (!LuaDLL.lua_checkstack(luaState, _LastCalledMethod.outList.Length + 6))
throw new LuaException("Lua stack overflow");
public RegisterEventHandler(EventHandlerContainer pendingEvents, object target, EventInfo eventInfo) try
{ {
this.target=target; if (isStatic)
this.eventInfo=eventInfo; {
this.pendingEvents = pendingEvents; _Translator.push(luaState, _LastCalledMethod.cachedMethod.Invoke(null, _LastCalledMethod.args));
} }
else
{
/* if (_LastCalledMethod.cachedMethod.IsConstructor)
* Adds a new event handler _Translator.push(luaState, ((ConstructorInfo)_LastCalledMethod.cachedMethod).Invoke(_LastCalledMethod.args));
*/ else
public Delegate Add(LuaFunction function) _Translator.push(luaState, _LastCalledMethod.cachedMethod.Invoke(targetObject, _LastCalledMethod.args));
{ }
MethodInfo mi = eventInfo.EventHandlerType.GetMethod("Invoke"); }
ParameterInfo[] pi = mi.GetParameters(); catch (TargetInvocationException e)
LuaEventHandler handler=CodeGeneration.Instance.GetEvent(pi[1].ParameterType,function); {
return SetPendingException(e.GetBaseException());
Delegate handlerDelegate=Delegate.CreateDelegate(eventInfo.EventHandlerType,handler,"HandleEvent"); }
eventInfo.AddEventHandler(target,handlerDelegate); catch (Exception e)
pendingEvents.Add(handlerDelegate, this); {
return SetPendingException(e);
return handlerDelegate; }
} }
/* // Pushes out and ref return values
* Removes an existing event handler for (int index = 0; index < _LastCalledMethod.outList.Length; index++)
*/ {
public void Remove(Delegate handlerDelegate) nReturnValues++;
{ //for(int i=0;i<lastCalledMethod.outList.Length;i++)
RemovePending(handlerDelegate); _Translator.push(luaState, _LastCalledMethod.args[_LastCalledMethod.outList[index]]);
pendingEvents.Remove(handlerDelegate); }
}
//by isSingle 2010-09-10 11:26:31
/* //Desc:
* Removes an existing event handler (without updating the pending handlers list) // if not return void,we need add 1,
*/ // or we will lost the function's return value
internal void RemovePending(Delegate handlerDelegate) // when call dotnet function like "int foo(arg1,out arg2,out arg3)" in lua code
{ if (!_LastCalledMethod.IsReturnVoid && nReturnValues > 0)
eventInfo.RemoveEventHandler(target, handlerDelegate); {
} nReturnValues++;
} }
/* return nReturnValues < 1 ? 1 : nReturnValues;
* Base wrapper class for Lua function event handlers. }
* Subclasses that do actual event handling are created }
* at runtime.
*
* Author: Fabio Mascarenhas
* Version: 1.0
*/ /// <summary>
public class LuaEventHandler /// We keep track of what delegates we have auto attached to an event - to allow us to cleanly exit a LuaInterface session
{ /// </summary>
public LuaFunction handler = null; class EventHandlerContainer : IDisposable
{
public void handleEvent(object sender,object data) Dictionary<Delegate, RegisterEventHandler> dict = new Dictionary<Delegate, RegisterEventHandler>();
{
handler.call(new object[] { sender,data },new Type[0]); public void Add(Delegate handler, RegisterEventHandler eventInfo)
} {
} dict.Add(handler, eventInfo);
}
/*
* Wrapper class for Lua functions as delegates public void Remove(Delegate handler)
* Subclasses with correct signatures are created {
* at runtime. bool found = dict.Remove(handler);
* Debug.Assert(found);
* Author: Fabio Mascarenhas }
* Version: 1.0
*/ /// <summary>
public class LuaDelegate /// Remove any still registered handlers
{ /// </summary>
public Type[] returnTypes; public void Dispose()
public LuaFunction function; {
public LuaDelegate() foreach (KeyValuePair<Delegate, RegisterEventHandler> pair in dict)
{ {
function=null; pair.Value.RemovePending(pair.Key);
returnTypes=null; }
}
public object callFunction(object[] args,object[] inArgs,int[] outArgs) dict.Clear();
{ }
// args is the return array of arguments, inArgs is the actual array }
// of arguments passed to the function (with in parameters only), outArgs
// has the positions of out parameters
object returnValue; /*
int iRefArgs; * Wrapper class for events that does registration/deregistration
object[] returnValues=function.call(inArgs,returnTypes); * of event handlers.
if(returnTypes[0] == typeof(void)) *
{ * Author: Fabio Mascarenhas
returnValue=null; * Version: 1.0
iRefArgs=0; */
} class RegisterEventHandler
else {
{ object target;
returnValue=returnValues[0]; EventInfo eventInfo;
iRefArgs=1; EventHandlerContainer pendingEvents;
}
// Sets the value of out and ref parameters (from public RegisterEventHandler(EventHandlerContainer pendingEvents, object target, EventInfo eventInfo)
// the values returned by the Lua function). {
for(int i=0;i<outArgs.Length;i++) this.target = target;
{ this.eventInfo = eventInfo;
args[outArgs[i]]=returnValues[iRefArgs]; this.pendingEvents = pendingEvents;
iRefArgs++; }
}
return returnValue;
} /*
} * Adds a new event handler
*/
/* public Delegate Add(LuaFunction function)
* Static helper methods for Lua tables acting as CLR objects. {
* //CP: Fix by Ben Bryant for event handling with one parameter
* Author: Fabio Mascarenhas //link: http://luaforge.net/forum/message.php?msg_id=9266
* Version: 1.0 Delegate handlerDelegate = CodeGeneration.Instance.GetDelegate(eventInfo.EventHandlerType, function);
*/ eventInfo.AddEventHandler(target, handlerDelegate);
public class LuaClassHelper pendingEvents.Add(handlerDelegate, this);
{
/* return handlerDelegate;
* Gets the function called name from the provided table,
* returning null if it does not exist
*/ //MethodInfo mi = eventInfo.EventHandlerType.GetMethod("Invoke");
public static LuaFunction getTableFunction(LuaTable luaTable,string name) //ParameterInfo[] pi = mi.GetParameters();
{ //LuaEventHandler handler=CodeGeneration.Instance.GetEvent(pi[1].ParameterType,function);
object funcObj=luaTable.rawget(name);
if(funcObj is LuaFunction) //Delegate handlerDelegate=Delegate.CreateDelegate(eventInfo.EventHandlerType,handler,"HandleEvent");
return (LuaFunction)funcObj; //eventInfo.AddEventHandler(target,handlerDelegate);
else //pendingEvents.Add(handlerDelegate, this);
return null;
} //return handlerDelegate;
/* }
* Calls the provided function with the provided parameters
*/ /*
public static object callFunction(LuaFunction function,object[] args,Type[] returnTypes,object[] inArgs,int[] outArgs) * Removes an existing event handler
{ */
// args is the return array of arguments, inArgs is the actual array public void Remove(Delegate handlerDelegate)
// of arguments passed to the function (with in parameters only), outArgs {
// has the positions of out parameters RemovePending(handlerDelegate);
object returnValue; pendingEvents.Remove(handlerDelegate);
int iRefArgs; }
object[] returnValues=function.call(inArgs,returnTypes);
if(returnTypes[0] == typeof(void)) /*
{ * Removes an existing event handler (without updating the pending handlers list)
returnValue=null; */
iRefArgs=0; internal void RemovePending(Delegate handlerDelegate)
} {
else eventInfo.RemoveEventHandler(target, handlerDelegate);
{ }
returnValue=returnValues[0]; }
iRefArgs=1;
} /*
for(int i=0;i<outArgs.Length;i++) * Base wrapper class for Lua function event handlers.
{ * Subclasses that do actual event handling are created
args[outArgs[i]]=returnValues[iRefArgs]; * at runtime.
iRefArgs++; *
} * Author: Fabio Mascarenhas
return returnValue; * Version: 1.0
} */
} public class LuaEventHandler
{
public LuaFunction handler = null;
// CP: Fix provided by Ben Bryant for delegates with one param
// link: http://luaforge.net/forum/message.php?msg_id=9318
public void handleEvent(object[] args)
{
handler.Call(args);
}
//public void handleEvent(object sender,object data)
//{
// handler.call(new object[] { sender,data },new Type[0]);
//}
}
/*
* Wrapper class for Lua functions as delegates
* Subclasses with correct signatures are created
* at runtime.
*
* Author: Fabio Mascarenhas
* Version: 1.0
*/
public class LuaDelegate
{
public Type[] returnTypes;
public LuaFunction function;
public LuaDelegate()
{
function = null;
returnTypes = null;
}
public object callFunction(object[] args, object[] inArgs, int[] outArgs)
{
// args is the return array of arguments, inArgs is the actual array
// of arguments passed to the function (with in parameters only), outArgs
// has the positions of out parameters
object returnValue;
int iRefArgs;
object[] returnValues = function.call(inArgs, returnTypes);
if (returnTypes[0] == typeof(void))
{
returnValue = null;
iRefArgs = 0;
}
else
{
returnValue = returnValues[0];
iRefArgs = 1;
}
// Sets the value of out and ref parameters (from
// the values returned by the Lua function).
for (int i = 0; i < outArgs.Length; i++)
{
args[outArgs[i]] = returnValues[iRefArgs];
iRefArgs++;
}
return returnValue;
}
}
/*
* Static helper methods for Lua tables acting as CLR objects.
*
* Author: Fabio Mascarenhas
* Version: 1.0
*/
public class LuaClassHelper
{
/*
* Gets the function called name from the provided table,
* returning null if it does not exist
*/
public static LuaFunction getTableFunction(LuaTable luaTable, string name)
{
object funcObj = luaTable.rawget(name);
if (funcObj is LuaFunction)
return (LuaFunction)funcObj;
else
return null;
}
/*
* Calls the provided function with the provided parameters
*/
public static object callFunction(LuaFunction function, object[] args, Type[] returnTypes, object[] inArgs, int[] outArgs)
{
// args is the return array of arguments, inArgs is the actual array
// of arguments passed to the function (with in parameters only), outArgs
// has the positions of out parameters
object returnValue;
int iRefArgs;
object[] returnValues = function.call(inArgs, returnTypes);
if (returnTypes[0] == typeof(void))
{
returnValue = null;
iRefArgs = 0;
}
else
{
returnValue = returnValues[0];
iRefArgs = 1;
}
for (int i = 0; i < outArgs.Length; i++)
{
args[outArgs[i]] = returnValues[iRefArgs];
iRefArgs++;
}
return returnValue;
}
}
} }
...@@ -4,9 +4,9 @@ namespace LuaInterface ...@@ -4,9 +4,9 @@ namespace LuaInterface
using System.IO; using System.IO;
using System.Collections; using System.Collections;
using System.Reflection; using System.Reflection;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using LuaWrap; using Lua511;
/* /*
* Passes objects from the CLR to Lua and vice-versa * Passes objects from the CLR to Lua and vice-versa
...@@ -18,31 +18,31 @@ namespace LuaInterface ...@@ -18,31 +18,31 @@ namespace LuaInterface
{ {
internal CheckType typeChecker; internal CheckType typeChecker;
// 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 #)
public readonly Dictionary<int, object> objects = new Dictionary<int, object>(); public readonly Dictionary<int, object> objects = new Dictionary<int, object>();
// object to object # // object to object #
public readonly Dictionary<object, int> objectsBackMap = new Dictionary<object, int>(); public readonly Dictionary<object, int> objectsBackMap = new Dictionary<object, int>();
internal Lua interpreter; internal Lua interpreter;
private MetaFunctions metaFunctions; private MetaFunctions metaFunctions;
private List<Assembly> assemblies; private List<Assembly> assemblies;
private KopiLua.Lua.lua_CFunction registerTableFunction,unregisterTableFunction,getMethodSigFunction, private LuaCSFunction registerTableFunction,unregisterTableFunction,getMethodSigFunction,
getConstructorSigFunction,importTypeFunction,loadAssemblyFunction; getConstructorSigFunction,importTypeFunction,loadAssemblyFunction;
internal EventHandlerContainer pendingEvents = new EventHandlerContainer(); internal EventHandlerContainer pendingEvents = new EventHandlerContainer();
public ObjectTranslator(Lua interpreter,KopiLua.Lua.lua_State luaState) public ObjectTranslator(Lua interpreter,IntPtr luaState)
{ {
this.interpreter=interpreter; this.interpreter=interpreter;
typeChecker=new CheckType(this); typeChecker=new CheckType(this);
metaFunctions=new MetaFunctions(this); metaFunctions=new MetaFunctions(this);
assemblies=new List<Assembly>(); assemblies=new List<Assembly>();
importTypeFunction=new KopiLua.Lua.lua_CFunction(this.importType); importTypeFunction=new LuaCSFunction(this.importType);
loadAssemblyFunction=new KopiLua.Lua.lua_CFunction(this.loadAssembly); loadAssemblyFunction=new LuaCSFunction(this.loadAssembly);
registerTableFunction=new KopiLua.Lua.lua_CFunction(this.registerTable); registerTableFunction=new LuaCSFunction(this.registerTable);
unregisterTableFunction=new KopiLua.Lua.lua_CFunction(this.unregisterTable); unregisterTableFunction=new LuaCSFunction(this.unregisterTable);
getMethodSigFunction=new KopiLua.Lua.lua_CFunction(this.getMethodSignature); getMethodSigFunction=new LuaCSFunction(this.getMethodSignature);
getConstructorSigFunction=new KopiLua.Lua.lua_CFunction(this.getConstructorSignature); getConstructorSigFunction=new LuaCSFunction(this.getConstructorSignature);
createLuaObjectList(luaState); createLuaObjectList(luaState);
createIndexingMetaFunction(luaState); createIndexingMetaFunction(luaState);
...@@ -55,164 +55,184 @@ namespace LuaInterface ...@@ -55,164 +55,184 @@ namespace LuaInterface
/* /*
* Sets up the list of objects in the Lua side * Sets up the list of objects in the Lua side
*/ */
private void createLuaObjectList(KopiLua.Lua.lua_State luaState) private void createLuaObjectList(IntPtr luaState)
{ {
KopiLua.Lua.lua_pushstring(luaState,"luaNet_objects"); LuaDLL.lua_pushstring(luaState,"luaNet_objects");
KopiLua.Lua.lua_newtable(luaState); LuaDLL.lua_newtable(luaState);
KopiLua.Lua.lua_newtable(luaState); LuaDLL.lua_newtable(luaState);
KopiLua.Lua.lua_pushstring(luaState,"__mode"); LuaDLL.lua_pushstring(luaState,"__mode");
KopiLua.Lua.lua_pushstring(luaState,"v"); LuaDLL.lua_pushstring(luaState,"v");
KopiLua.Lua.lua_settable(luaState,-3); LuaDLL.lua_settable(luaState,-3);
KopiLua.Lua.lua_setmetatable(luaState,-2); LuaDLL.lua_setmetatable(luaState,-2);
KopiLua.Lua.lua_settable(luaState, (int) PseudoIndex.Registry); LuaDLL.lua_settable(luaState, (int) LuaIndexes.LUA_REGISTRYINDEX);
} }
/* /*
* Registers the indexing function of CLR objects * Registers the indexing function of CLR objects
* passed to Lua * passed to Lua
*/ */
private void createIndexingMetaFunction(KopiLua.Lua.lua_State luaState) private void createIndexingMetaFunction(IntPtr luaState)
{ {
KopiLua.Lua.lua_pushstring(luaState,"luaNet_indexfunction"); LuaDLL.lua_pushstring(luaState,"luaNet_indexfunction");
LuaLib.luaL_dostring(luaState,MetaFunctions.luaIndexFunction); // steffenj: lua_dostring renamed to luaL_dostring LuaDLL.luaL_dostring(luaState,MetaFunctions.luaIndexFunction); // steffenj: lua_dostring renamed to luaL_dostring
//LuaLib.lua_pushstdcallcfunction(luaState,indexFunction); //LuaDLL.lua_pushstdcallcfunction(luaState,indexFunction);
KopiLua.Lua.lua_rawset(luaState, (int) PseudoIndex.Registry); LuaDLL.lua_rawset(luaState, (int) LuaIndexes.LUA_REGISTRYINDEX);
} }
/* /*
* Creates the metatable for superclasses (the base * Creates the metatable for superclasses (the base
* field of registered tables) * field of registered tables)
*/ */
private void createBaseClassMetatable(KopiLua.Lua.lua_State luaState) private void createBaseClassMetatable(IntPtr luaState)
{ {
KopiLua.Lua.luaL_newmetatable(luaState,"luaNet_searchbase"); LuaDLL.luaL_newmetatable(luaState,"luaNet_searchbase");
KopiLua.Lua.lua_pushstring(luaState,"__gc"); LuaDLL.lua_pushstring(luaState,"__gc");
LuaLib.lua_pushstdcallcfunction(luaState,metaFunctions.gcFunction); LuaDLL.lua_pushstdcallcfunction(luaState,metaFunctions.gcFunction);
KopiLua.Lua.lua_settable(luaState,-3); LuaDLL.lua_settable(luaState,-3);
KopiLua.Lua.lua_pushstring(luaState,"__tostring"); LuaDLL.lua_pushstring(luaState,"__tostring");
LuaLib.lua_pushstdcallcfunction(luaState,metaFunctions.toStringFunction); LuaDLL.lua_pushstdcallcfunction(luaState,metaFunctions.toStringFunction);
KopiLua.Lua.lua_settable(luaState,-3); LuaDLL.lua_settable(luaState,-3);
KopiLua.Lua.lua_pushstring(luaState,"__index"); LuaDLL.lua_pushstring(luaState,"__index");
LuaLib.lua_pushstdcallcfunction(luaState,metaFunctions.baseIndexFunction); LuaDLL.lua_pushstdcallcfunction(luaState,metaFunctions.baseIndexFunction);
KopiLua.Lua.lua_settable(luaState,-3); LuaDLL.lua_settable(luaState,-3);
KopiLua.Lua.lua_pushstring(luaState,"__newindex"); LuaDLL.lua_pushstring(luaState,"__newindex");
LuaLib.lua_pushstdcallcfunction(luaState,metaFunctions.newindexFunction); LuaDLL.lua_pushstdcallcfunction(luaState,metaFunctions.newindexFunction);
KopiLua.Lua.lua_settable(luaState,-3); LuaDLL.lua_settable(luaState,-3);
KopiLua.Lua.lua_settop(luaState,-2); LuaDLL.lua_settop(luaState,-2);
} }
/* /*
* Creates the metatable for type references * Creates the metatable for type references
*/ */
private void createClassMetatable(KopiLua.Lua.lua_State luaState) private void createClassMetatable(IntPtr luaState)
{ {
KopiLua.Lua.luaL_newmetatable(luaState,"luaNet_class"); LuaDLL.luaL_newmetatable(luaState,"luaNet_class");
KopiLua.Lua.lua_pushstring(luaState,"__gc"); LuaDLL.lua_pushstring(luaState,"__gc");
LuaLib.lua_pushstdcallcfunction(luaState,metaFunctions.gcFunction); LuaDLL.lua_pushstdcallcfunction(luaState,metaFunctions.gcFunction);
KopiLua.Lua.lua_settable(luaState,-3); LuaDLL.lua_settable(luaState,-3);
KopiLua.Lua.lua_pushstring(luaState,"__tostring"); LuaDLL.lua_pushstring(luaState,"__tostring");
LuaLib.lua_pushstdcallcfunction(luaState,metaFunctions.toStringFunction); LuaDLL.lua_pushstdcallcfunction(luaState,metaFunctions.toStringFunction);
KopiLua.Lua.lua_settable(luaState,-3); LuaDLL.lua_settable(luaState,-3);
KopiLua.Lua.lua_pushstring(luaState,"__index"); LuaDLL.lua_pushstring(luaState,"__index");
LuaLib.lua_pushstdcallcfunction(luaState,metaFunctions.classIndexFunction); LuaDLL.lua_pushstdcallcfunction(luaState,metaFunctions.classIndexFunction);
KopiLua.Lua.lua_settable(luaState,-3); LuaDLL.lua_settable(luaState,-3);
KopiLua.Lua.lua_pushstring(luaState,"__newindex"); LuaDLL.lua_pushstring(luaState,"__newindex");
LuaLib.lua_pushstdcallcfunction(luaState,metaFunctions.classNewindexFunction); LuaDLL.lua_pushstdcallcfunction(luaState,metaFunctions.classNewindexFunction);
KopiLua.Lua.lua_settable(luaState,-3); LuaDLL.lua_settable(luaState,-3);
KopiLua.Lua.lua_pushstring(luaState,"__call"); LuaDLL.lua_pushstring(luaState,"__call");
LuaLib.lua_pushstdcallcfunction(luaState,metaFunctions.callConstructorFunction); LuaDLL.lua_pushstdcallcfunction(luaState,metaFunctions.callConstructorFunction);
KopiLua.Lua.lua_settable(luaState,-3); LuaDLL.lua_settable(luaState,-3);
KopiLua.Lua.lua_settop(luaState,-2); LuaDLL.lua_settop(luaState,-2);
} }
/* /*
* Registers the global functions used by LuaInterface * Registers the global functions used by LuaInterface
*/ */
private void setGlobalFunctions(KopiLua.Lua.lua_State luaState) private void setGlobalFunctions(IntPtr luaState)
{ {
LuaLib.lua_pushstdcallcfunction(luaState,metaFunctions.indexFunction); LuaDLL.lua_pushstdcallcfunction(luaState,metaFunctions.indexFunction);
KopiLua.Lua.lua_setglobal(luaState,"get_object_member"); LuaDLL.lua_setglobal(luaState,"get_object_member");
LuaLib.lua_pushstdcallcfunction(luaState,importTypeFunction); LuaDLL.lua_pushstdcallcfunction(luaState,importTypeFunction);
KopiLua.Lua.lua_setglobal(luaState,"import_type"); LuaDLL.lua_setglobal(luaState,"import_type");
LuaLib.lua_pushstdcallcfunction(luaState,loadAssemblyFunction); LuaDLL.lua_pushstdcallcfunction(luaState,loadAssemblyFunction);
KopiLua.Lua.lua_setglobal(luaState,"load_assembly"); LuaDLL.lua_setglobal(luaState,"load_assembly");
LuaLib.lua_pushstdcallcfunction(luaState,registerTableFunction); LuaDLL.lua_pushstdcallcfunction(luaState,registerTableFunction);
KopiLua.Lua.lua_setglobal(luaState,"make_object"); LuaDLL.lua_setglobal(luaState,"make_object");
LuaLib.lua_pushstdcallcfunction(luaState,unregisterTableFunction); LuaDLL.lua_pushstdcallcfunction(luaState,unregisterTableFunction);
KopiLua.Lua.lua_setglobal(luaState,"free_object"); LuaDLL.lua_setglobal(luaState,"free_object");
LuaLib.lua_pushstdcallcfunction(luaState,getMethodSigFunction); LuaDLL.lua_pushstdcallcfunction(luaState,getMethodSigFunction);
KopiLua.Lua.lua_setglobal(luaState,"get_method_bysig"); LuaDLL.lua_setglobal(luaState,"get_method_bysig");
LuaLib.lua_pushstdcallcfunction(luaState,getConstructorSigFunction); LuaDLL.lua_pushstdcallcfunction(luaState,getConstructorSigFunction);
KopiLua.Lua.lua_setglobal(luaState,"get_constructor_bysig"); LuaDLL.lua_setglobal(luaState,"get_constructor_bysig");
} }
/* /*
* Creates the metatable for delegates * Creates the metatable for delegates
*/ */
private void createFunctionMetatable(KopiLua.Lua.lua_State luaState) private void createFunctionMetatable(IntPtr luaState)
{ {
KopiLua.Lua.luaL_newmetatable(luaState,"luaNet_function"); LuaDLL.luaL_newmetatable(luaState,"luaNet_function");
KopiLua.Lua.lua_pushstring(luaState,"__gc"); LuaDLL.lua_pushstring(luaState,"__gc");
LuaLib.lua_pushstdcallcfunction(luaState,metaFunctions.gcFunction); LuaDLL.lua_pushstdcallcfunction(luaState,metaFunctions.gcFunction);
KopiLua.Lua.lua_settable(luaState,-3); LuaDLL.lua_settable(luaState,-3);
KopiLua.Lua.lua_pushstring(luaState,"__call"); LuaDLL.lua_pushstring(luaState,"__call");
LuaLib.lua_pushstdcallcfunction(luaState,metaFunctions.execDelegateFunction); LuaDLL.lua_pushstdcallcfunction(luaState,metaFunctions.execDelegateFunction);
KopiLua.Lua.lua_settable(luaState,-3); LuaDLL.lua_settable(luaState,-3);
KopiLua.Lua.lua_settop(luaState,-2); LuaDLL.lua_settop(luaState,-2);
} }
/* /*
* Passes errors (argument e) to the Lua interpreter * Passes errors (argument e) to the Lua interpreter
*/ */
internal void throwError(KopiLua.Lua.lua_State luaState,object e) internal void throwError(IntPtr luaState, object e)
{ {
// If the argument is a mere string, we are free to add extra info to it (as opposed to some private C# exception object or somesuch, which we just pass up) // We use this to remove anything pushed by luaL_where
if (e is string) int oldTop = LuaDLL.lua_gettop(luaState);
{
// We use this to remove anything pushed by luaL_where // Stack frame #1 is our C# wrapper, so not very interesting to the user
int oldTop = KopiLua.Lua.lua_gettop(luaState); // Stack frame #2 must be the lua code that called us, so that's what we want to use
LuaDLL.luaL_where(luaState, 1);
// Stack frame #1 is our C# wrapper, so not very interesting to the user object[] curlev = popValues(luaState, oldTop);
// Stack frame #2 must be the lua code that called us, so that's what we want to use
KopiLua.Lua.luaL_where(luaState, 2); // Determine the position in the script where the exception was triggered
object[] curlev = popValues(luaState, oldTop); string errLocation = "";
// Debug.WriteLine(curlev); if (curlev.Length > 0)
errLocation = curlev[0].ToString();
if (curlev.Length > 0)
e = curlev[0].ToString() + e; string message = e as string;
} if (message != null)
{
push(luaState,e); // Wrap Lua error (just a string) and store the error location
KopiLua.Lua.lua_error(luaState); e = new LuaScriptException(message, errLocation);
} }
else
{
Exception ex = e as Exception;
if (ex != null)
{
// Wrap generic .NET exception as an InnerException and store the error location
e = new LuaScriptException(ex, errLocation);
}
}
push(luaState, e);
LuaDLL.lua_error(luaState);
}
/* /*
* Implementation of load_assembly. Throws an error * Implementation of load_assembly. Throws an error
* if the assembly is not found. * if the assembly is not found.
*/ */
private int loadAssembly(KopiLua.Lua.lua_State luaState) private int loadAssembly(IntPtr luaState)
{ {
string assemblyName=KopiLua.Lua.lua_tostring(luaState,1).ToString(); try
try {
{ string assemblyName=LuaDLL.lua_tostring(luaState,1);
Assembly assembly=Assembly.LoadWithPartialName(assemblyName);
Assembly assembly = null;
try
{ try
// If we couldn't find it based on a name, see if we can use it as a filename and find it {
if (assembly == null) assembly = Assembly.LoadWithPartialName(assemblyName);
assembly = Assembly.Load(AssemblyName.GetAssemblyName(assemblyName)); }
} catch (BadImageFormatException)
catch (Exception) {
{ // The assemblyName was invalid. It is most likely a path.
// ignore - it might not even be a filename }
}
if (assembly == null)
if(assembly!=null && !assemblies.Contains(assembly)) {
assemblies.Add(assembly); assembly = Assembly.Load(AssemblyName.GetAssemblyName(assemblyName));
} }
if (assembly != null && !assemblies.Contains(assembly))
{
assemblies.Add(assembly);
}
}
catch(Exception e) catch(Exception e)
{ {
throwError(luaState,e); throwError(luaState,e);
} }
return 0; return 0;
} }
internal Type FindType(string className) internal Type FindType(string className)
{ {
foreach(Assembly assembly in assemblies) foreach(Assembly assembly in assemblies)
{ {
Type klass=assembly.GetType(className); Type klass=assembly.GetType(className);
...@@ -221,64 +241,63 @@ namespace LuaInterface ...@@ -221,64 +241,63 @@ namespace LuaInterface
return klass; return klass;
} }
} }
return null; return null;
} }
/* /*
* Implementation of import_type. Returns nil if the * Implementation of import_type. Returns nil if the
* type is not found. * type is not found.
*/ */
private int importType(KopiLua.Lua.lua_State luaState) private int importType(IntPtr luaState)
{ {
string className=KopiLua.Lua.lua_tostring(luaState,1).ToString(); string className=LuaDLL.lua_tostring(luaState,1);
Type klass=FindType(className); Type klass=FindType(className);
if(klass!=null) if(klass!=null)
pushType(luaState,klass); pushType(luaState,klass);
else else
KopiLua.Lua.lua_pushnil(luaState); LuaDLL.lua_pushnil(luaState);
return 1; return 1;
} }
/* /*
* Implementation of make_object. Registers a table (first * Implementation of make_object. Registers a table (first
* argument in the stack) as an object subclassing the * argument in the stack) as an object subclassing the
* type passed as second argument in the stack. * type passed as second argument in the stack.
*/ */
private int registerTable(KopiLua.Lua.lua_State luaState) private int registerTable(IntPtr luaState)
{ {
if(KopiLua.Lua.lua_type(luaState,1).ToLuaType()==LuaType.Table) if(LuaDLL.lua_type(luaState,1)==LuaTypes.LUA_TTABLE)
{ {
LuaTable luaTable=getTable(luaState,1); LuaTable luaTable=getTable(luaState,1);
string superclassName = KopiLua.Lua.lua_tostring(luaState, 2).ToString(); string superclassName = LuaDLL.lua_tostring(luaState, 2);
if (superclassName != null) if (superclassName != null)
{ {
Type klass = FindType(superclassName); Type klass = FindType(superclassName);
if (klass != null) if (klass != null)
{ {
// Creates and pushes the object in the stack, setting // Creates and pushes the object in the stack, setting
// it as the metatable of the first argument // it as the metatable of the first argument
object obj = CodeGeneration.Instance.GetClassInstance(klass, luaTable); object obj = CodeGeneration.Instance.GetClassInstance(klass, luaTable);
pushObject(luaState, obj, "luaNet_metatable"); pushObject(luaState, obj, "luaNet_metatable");
KopiLua.Lua.lua_newtable(luaState); LuaDLL.lua_newtable(luaState);
KopiLua.Lua.lua_pushstring(luaState, "__index"); LuaDLL.lua_pushstring(luaState, "__index");
KopiLua.Lua.lua_pushvalue(luaState, -3); LuaDLL.lua_pushvalue(luaState, -3);
KopiLua.Lua.lua_settable(luaState, -3); LuaDLL.lua_settable(luaState, -3);
KopiLua.Lua.lua_pushstring(luaState, "__newindex"); LuaDLL.lua_pushstring(luaState, "__newindex");
KopiLua.Lua.lua_pushvalue(luaState, -3); LuaDLL.lua_pushvalue(luaState, -3);
KopiLua.Lua.lua_settable(luaState, -3); LuaDLL.lua_settable(luaState, -3);
KopiLua.Lua.lua_setmetatable(luaState, 1); LuaDLL.lua_setmetatable(luaState, 1);
// Pushes the object again, this time as the base field // Pushes the object again, this time as the base field
// of the table and with the luaNet_searchbase metatable // of the table and with the luaNet_searchbase metatable
KopiLua.Lua.lua_pushstring(luaState, "base"); LuaDLL.lua_pushstring(luaState, "base");
//int index = addObject(obj); int index = addObject(obj);
//pushNewObject(luaState, obj, index, "luaNet_searchbase"); pushNewObject(luaState, obj, index, "luaNet_searchbase");
pushNewObject(luaState, obj, 0, "luaNet_searchbase"); LuaDLL.lua_rawset(luaState, 1);
KopiLua.Lua.lua_rawset(luaState, 1); }
} else
else throwError(luaState, "register_table: can not find superclass '" + superclassName + "'");
throwError(luaState, "register_table: can not find superclass '" + superclassName + "'"); }
} else
else throwError(luaState, "register_table: superclass name can not be null");
throwError(luaState, "register_table: superclass name can not be null");
} }
else throwError(luaState,"register_table: first arg is not a table"); else throwError(luaState,"register_table: first arg is not a table");
return 0; return 0;
...@@ -287,24 +306,24 @@ namespace LuaInterface ...@@ -287,24 +306,24 @@ namespace LuaInterface
* Implementation of free_object. Clears the metatable and the * Implementation of free_object. Clears the metatable and the
* base field, freeing the created object for garbage-collection * base field, freeing the created object for garbage-collection
*/ */
private int unregisterTable(KopiLua.Lua.lua_State luaState) private int unregisterTable(IntPtr luaState)
{ {
try try
{ {
if(KopiLua.Lua.lua_getmetatable(luaState,1)!=0) if(LuaDLL.lua_getmetatable(luaState,1)!=0)
{ {
KopiLua.Lua.lua_pushstring(luaState,"__index"); LuaDLL.lua_pushstring(luaState,"__index");
KopiLua.Lua.lua_gettable(luaState,-2); LuaDLL.lua_gettable(luaState,-2);
object obj=getRawNetObject(luaState,-1); object obj=getRawNetObject(luaState,-1);
if(obj==null) throwError(luaState,"unregister_table: arg is not valid table"); if(obj==null) throwError(luaState,"unregister_table: arg is not valid table");
FieldInfo luaTableField=obj.GetType().GetField("__luaInterface_luaTable"); FieldInfo luaTableField=obj.GetType().GetField("__luaInterface_luaTable");
if(luaTableField==null) throwError(luaState,"unregister_table: arg is not valid table"); if(luaTableField==null) throwError(luaState,"unregister_table: arg is not valid table");
luaTableField.SetValue(obj,null); luaTableField.SetValue(obj,null);
KopiLua.Lua.lua_pushnil(luaState); LuaDLL.lua_pushnil(luaState);
KopiLua.Lua.lua_setmetatable(luaState,1); LuaDLL.lua_setmetatable(luaState,1);
KopiLua.Lua.lua_pushstring(luaState,"base"); LuaDLL.lua_pushstring(luaState,"base");
KopiLua.Lua.lua_pushnil(luaState); LuaDLL.lua_pushnil(luaState);
KopiLua.Lua.lua_settable(luaState,1); LuaDLL.lua_settable(luaState,1);
} }
else throwError(luaState,"unregister_table: arg is not valid table"); else throwError(luaState,"unregister_table: arg is not valid table");
} }
...@@ -318,10 +337,10 @@ namespace LuaInterface ...@@ -318,10 +337,10 @@ namespace LuaInterface
* Implementation of get_method_bysig. Returns nil * Implementation of get_method_bysig. Returns nil
* if no matching method is not found. * if no matching method is not found.
*/ */
private int getMethodSignature(KopiLua.Lua.lua_State luaState) private int getMethodSignature(IntPtr luaState)
{ {
IReflect klass; object target; IReflect klass; object target;
int udata=LuaLib.luanet_checkudata(luaState,1,"luaNet_class"); int udata=LuaDLL.luanet_checkudata(luaState,1,"luaNet_class");
if(udata!=-1) if(udata!=-1)
{ {
klass=(IReflect)objects[udata]; klass=(IReflect)objects[udata];
...@@ -333,25 +352,26 @@ namespace LuaInterface ...@@ -333,25 +352,26 @@ namespace LuaInterface
if(target==null) if(target==null)
{ {
throwError(luaState,"get_method_bysig: first arg is not type or object reference"); throwError(luaState,"get_method_bysig: first arg is not type or object reference");
KopiLua.Lua.lua_pushnil(luaState); LuaDLL.lua_pushnil(luaState);
return 1; return 1;
} }
klass=target.GetType(); klass=target.GetType();
} }
string methodName=KopiLua.Lua.lua_tostring(luaState,2).ToString(); string methodName=LuaDLL.lua_tostring(luaState,2);
Type[] signature=new Type[KopiLua.Lua.lua_gettop(luaState)-2]; Type[] signature=new Type[LuaDLL.lua_gettop(luaState)-2];
for(int i=0;i<signature.Length;i++) for(int i=0;i<signature.Length;i++)
signature[i]=FindType(KopiLua.Lua.lua_tostring(luaState,i+3).ToString()); signature[i]=FindType(LuaDLL.lua_tostring(luaState,i+3));
try try
{ {
//CP: Added ignore case
MethodInfo method=klass.GetMethod(methodName,BindingFlags.Public | BindingFlags.Static | MethodInfo method=klass.GetMethod(methodName,BindingFlags.Public | BindingFlags.Static |
BindingFlags.Instance | BindingFlags.FlattenHierarchy,null,signature,null); BindingFlags.Instance | BindingFlags.FlattenHierarchy | BindingFlags.IgnoreCase, null, signature, null);
pushFunction(luaState,new KopiLua.Lua.lua_CFunction((new LuaMethodWrapper(this,target,klass,method)).call)); pushFunction(luaState,new LuaCSFunction((new LuaMethodWrapper(this,target,klass,method)).call));
} }
catch(Exception e) catch(Exception e)
{ {
throwError(luaState,e); throwError(luaState,e);
KopiLua.Lua.lua_pushnil(luaState); LuaDLL.lua_pushnil(luaState);
} }
return 1; return 1;
} }
...@@ -359,10 +379,10 @@ namespace LuaInterface ...@@ -359,10 +379,10 @@ namespace LuaInterface
* Implementation of get_constructor_bysig. Returns nil * Implementation of get_constructor_bysig. Returns nil
* if no matching constructor is found. * if no matching constructor is found.
*/ */
private int getConstructorSignature(KopiLua.Lua.lua_State luaState) private int getConstructorSignature(IntPtr luaState)
{ {
IReflect klass=null; IReflect klass=null;
int udata=LuaLib.luanet_checkudata(luaState,1,"luaNet_class"); int udata=LuaDLL.luanet_checkudata(luaState,1,"luaNet_class");
if(udata!=-1) if(udata!=-1)
{ {
klass=(IReflect)objects[udata]; klass=(IReflect)objects[udata];
...@@ -371,32 +391,32 @@ namespace LuaInterface ...@@ -371,32 +391,32 @@ namespace LuaInterface
{ {
throwError(luaState,"get_constructor_bysig: first arg is invalid type reference"); throwError(luaState,"get_constructor_bysig: first arg is invalid type reference");
} }
Type[] signature=new Type[KopiLua.Lua.lua_gettop(luaState)-1]; Type[] signature=new Type[LuaDLL.lua_gettop(luaState)-1];
for(int i=0;i<signature.Length;i++) for(int i=0;i<signature.Length;i++)
signature[i]=FindType(KopiLua.Lua.lua_tostring(luaState,i+2).ToString()); signature[i]=FindType(LuaDLL.lua_tostring(luaState,i+2));
try try
{ {
ConstructorInfo constructor=klass.UnderlyingSystemType.GetConstructor(signature); ConstructorInfo constructor=klass.UnderlyingSystemType.GetConstructor(signature);
pushFunction(luaState,new KopiLua.Lua.lua_CFunction((new LuaMethodWrapper(this,null,klass,constructor)).call)); pushFunction(luaState,new LuaCSFunction((new LuaMethodWrapper(this,null,klass,constructor)).call));
} }
catch(Exception e) catch(Exception e)
{ {
throwError(luaState,e); throwError(luaState,e);
KopiLua.Lua.lua_pushnil(luaState); LuaDLL.lua_pushnil(luaState);
} }
return 1; return 1;
} }
/* /*
* Pushes a type reference into the stack * Pushes a type reference into the stack
*/ */
internal void pushType(KopiLua.Lua.lua_State luaState, Type t) internal void pushType(IntPtr luaState, Type t)
{ {
pushObject(luaState,new ProxyType(t),"luaNet_class"); pushObject(luaState,new ProxyType(t),"luaNet_class");
} }
/* /*
* Pushes a delegate into the stack * Pushes a delegate into the stack
*/ */
internal void pushFunction(KopiLua.Lua.lua_State luaState, KopiLua.Lua.lua_CFunction func) internal void pushFunction(IntPtr luaState, LuaCSFunction func)
{ {
pushObject(luaState,func,"luaNet_function"); pushObject(luaState,func,"luaNet_function");
} }
...@@ -404,45 +424,44 @@ namespace LuaInterface ...@@ -404,45 +424,44 @@ namespace LuaInterface
* Pushes a CLR object into the Lua stack as an userdata * Pushes a CLR object into the Lua stack as an userdata
* with the provided metatable * with the provided metatable
*/ */
internal void pushObject(KopiLua.Lua.lua_State luaState, object o, string metatable) internal void pushObject(IntPtr luaState, object o, string metatable)
{ {
int index = -1; int index = -1;
// Pushes nil // Pushes nil
if(o==null) if(o==null)
{ {
KopiLua.Lua.lua_pushnil(luaState); LuaDLL.lua_pushnil(luaState);
return; return;
} }
// 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 = objectsBackMap.TryGetValue(o, out index); bool found = objectsBackMap.TryGetValue(o, out index);
if(found) if(found)
{ {
KopiLua.Lua.luaL_getmetatable(luaState,"luaNet_objects"); LuaDLL.luaL_getmetatable(luaState,"luaNet_objects");
KopiLua.Lua.lua_rawgeti(luaState,-1,index); LuaDLL.lua_rawgeti(luaState,-1,index);
// Note: starting with lua5.1 the garbage collector may remove weak reference items (such as our luaNet_objects values) when the initial GC sweep // Note: starting with lua5.1 the garbage collector may remove weak reference items (such as our luaNet_objects values) when the initial GC sweep
// occurs, but the actual call of the __gc finalizer for that object may not happen until a little while later. During that window we might call // occurs, but the actual call of the __gc finalizer for that object may not happen until a little while later. During that window we might call
// this routine and find the element missing from luaNet_objects, but collectObject() has not yet been called. In that case, we go ahead and call collect // this routine and find the element missing from luaNet_objects, but collectObject() has not yet been called. In that case, we go ahead and call collect
// object here // object here
// did we find a non nil object in our table? if not, we need to call collect object // did we find a non nil object in our table? if not, we need to call collect object
LuaType type = KopiLua.Lua.lua_type(luaState, -1).ToLuaType(); LuaTypes type = LuaDLL.lua_type(luaState, -1);
if (type != LuaType.Nil) if (type != LuaTypes.LUA_TNIL)
{ {
KopiLua.Lua.lua_remove(luaState, -2); // drop the metatable - we're going to leave our object on the stack LuaDLL.lua_remove(luaState, -2); // drop the metatable - we're going to leave our object on the stack
return; return;
} }
// MetaFunctions.dumpStack(this, luaState); // MetaFunctions.dumpStack(this, luaState);
KopiLua.Lua.lua_remove(luaState, -1); // remove the nil object value LuaDLL.lua_remove(luaState, -1); // remove the nil object value
KopiLua.Lua.lua_remove(luaState, -1); // remove the metatable LuaDLL.lua_remove(luaState, -1); // remove the metatable
collectObject(o, index); // Remove from both our tables and fall out to get a new ID collectObject(o, index); // Remove from both our tables and fall out to get a new ID
} }
index = addObject(o); index = addObject(o);
//Console.WriteLine("pushObject: {0}", index);
//pushNewObject(luaState,o,0,metatable);
pushNewObject(luaState,o,index,metatable); pushNewObject(luaState,o,index,metatable);
} }
...@@ -451,65 +470,59 @@ namespace LuaInterface ...@@ -451,65 +470,59 @@ namespace LuaInterface
* Pushes a new object into the Lua stack with the provided * Pushes a new object into the Lua stack with the provided
* metatable * metatable
*/ */
private void pushNewObject(KopiLua.Lua.lua_State luaState,object o,int index,string metatable) private void pushNewObject(IntPtr luaState,object o,int index,string metatable)
{ {
if(metatable=="luaNet_metatable") if(metatable=="luaNet_metatable")
{ {
// Gets or creates the metatable for the object's type // Gets or creates the metatable for the object's type
KopiLua.Lua.luaL_getmetatable(luaState,o.GetType().AssemblyQualifiedName); LuaDLL.luaL_getmetatable(luaState,o.GetType().AssemblyQualifiedName);
if(KopiLua.Lua.lua_isnil(luaState,-1)) if(LuaDLL.lua_isnil(luaState,-1))
{ {
KopiLua.Lua.lua_settop(luaState,-2); LuaDLL.lua_settop(luaState,-2);
KopiLua.Lua.luaL_newmetatable(luaState,o.GetType().AssemblyQualifiedName); LuaDLL.luaL_newmetatable(luaState,o.GetType().AssemblyQualifiedName);
KopiLua.Lua.lua_pushstring(luaState,"cache"); LuaDLL.lua_pushstring(luaState,"cache");
KopiLua.Lua.lua_newtable(luaState); LuaDLL.lua_newtable(luaState);
KopiLua.Lua.lua_rawset(luaState,-3); LuaDLL.lua_rawset(luaState,-3);
KopiLua.Lua.lua_pushlightuserdata(luaState,LuaLib.luanet_gettag()); LuaDLL.lua_pushlightuserdata(luaState,LuaDLL.luanet_gettag());
KopiLua.Lua.lua_pushnumber(luaState,1); LuaDLL.lua_pushnumber(luaState,1);
KopiLua.Lua.lua_rawset(luaState,-3); LuaDLL.lua_rawset(luaState,-3);
KopiLua.Lua.lua_pushstring(luaState,"__index"); LuaDLL.lua_pushstring(luaState,"__index");
KopiLua.Lua.lua_pushstring(luaState,"luaNet_indexfunction"); LuaDLL.lua_pushstring(luaState,"luaNet_indexfunction");
KopiLua.Lua.lua_rawget(luaState, (int) PseudoIndex.Registry); LuaDLL.lua_rawget(luaState, (int) LuaIndexes.LUA_REGISTRYINDEX);
KopiLua.Lua.lua_rawset(luaState,-3); LuaDLL.lua_rawset(luaState,-3);
KopiLua.Lua.lua_pushstring(luaState,"__gc"); LuaDLL.lua_pushstring(luaState,"__gc");
LuaLib.lua_pushstdcallcfunction(luaState,metaFunctions.gcFunction); LuaDLL.lua_pushstdcallcfunction(luaState,metaFunctions.gcFunction);
KopiLua.Lua.lua_rawset(luaState,-3); LuaDLL.lua_rawset(luaState,-3);
KopiLua.Lua.lua_pushstring(luaState,"__tostring"); LuaDLL.lua_pushstring(luaState,"__tostring");
LuaLib.lua_pushstdcallcfunction(luaState,metaFunctions.toStringFunction); LuaDLL.lua_pushstdcallcfunction(luaState,metaFunctions.toStringFunction);
KopiLua.Lua.lua_rawset(luaState,-3); LuaDLL.lua_rawset(luaState,-3);
KopiLua.Lua.lua_pushstring(luaState,"__newindex"); LuaDLL.lua_pushstring(luaState,"__newindex");
LuaLib.lua_pushstdcallcfunction(luaState,metaFunctions.newindexFunction); LuaDLL.lua_pushstdcallcfunction(luaState,metaFunctions.newindexFunction);
KopiLua.Lua.lua_rawset(luaState,-3); LuaDLL.lua_rawset(luaState,-3);
} }
} }
else else
{ {
KopiLua.Lua.luaL_getmetatable(luaState,metatable); LuaDLL.luaL_getmetatable(luaState,metatable);
} }
// Stores the object index in the Lua list and pushes the // Stores the object index in the Lua list and pushes the
// index into the Lua stack // index into the Lua stack
KopiLua.Lua.luaL_getmetatable(luaState,"luaNet_objects"); LuaDLL.luaL_getmetatable(luaState,"luaNet_objects");
//Console.WriteLine("luaState2:" + luaState); LuaDLL.luanet_newudata(luaState,index);
//nextObj++; LuaDLL.lua_pushvalue(luaState,-3);
//index = (int)KopiLua.Lua.lua_newuserdata2(luaState, (uint)nextObj); LuaDLL.lua_remove(luaState,-4);
//Console.WriteLine(index); LuaDLL.lua_setmetatable(luaState,-2);
//addObject(o, index); LuaDLL.lua_pushvalue(luaState,-1);
LuaLib.luanet_newudata(luaState,index); LuaDLL.lua_rawseti(luaState,-3,index);
//Console.WriteLine("index:"+index); LuaDLL.lua_remove(luaState,-2);
KopiLua.Lua.lua_pushvalue(luaState,-3);
KopiLua.Lua.lua_remove(luaState,-4);
KopiLua.Lua.lua_setmetatable(luaState,-2);
KopiLua.Lua.lua_pushvalue(luaState,-1);
KopiLua.Lua.lua_rawseti(luaState,-3,index);
KopiLua.Lua.lua_remove(luaState,-2);
} }
/* /*
* Gets an object from the Lua stack with the desired type, if it matches, otherwise * Gets an object from the Lua stack with the desired type, if it matches, otherwise
* returns null. * returns null.
*/ */
internal object getAsType(KopiLua.Lua.lua_State luaState,int stackPos,Type paramType) internal object getAsType(IntPtr luaState,int stackPos,Type paramType)
{ {
ExtractValue extractor=typeChecker.checkType(luaState,stackPos,paramType); ExtractValue extractor=typeChecker.checkType(luaState,stackPos,paramType);
if(extractor!=null) return extractor(luaState,stackPos); if(extractor!=null) return extractor(luaState,stackPos);
...@@ -517,108 +530,93 @@ namespace LuaInterface ...@@ -517,108 +530,93 @@ namespace LuaInterface
} }
/// <summary> /// <summary>
/// Given the Lua int ID for an object remove it from our maps /// Given the Lua int ID for an object remove it from our maps
/// </summary> /// </summary>
/// <param name="udata"></param> /// <param name="udata"></param>
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)
{ {
// Debug.WriteLine("Removing " + o.ToString() + " @ " + udata); // Debug.WriteLine("Removing " + o.ToString() + " @ " + udata);
objects.Remove(udata); objects.Remove(udata);
objectsBackMap.Remove(o); objectsBackMap.Remove(o);
} }
} }
/// <summary> /// <summary>
/// Given an object reference, remove it from our maps /// Given an object reference, remove it from our maps
/// </summary> /// </summary>
/// <param name="udata"></param> /// <param name="udata"></param>
void collectObject(object o, int udata) void collectObject(object o, int udata)
{ {
// Debug.WriteLine("Removing " + o.ToString() + " @ " + udata); // Debug.WriteLine("Removing " + o.ToString() + " @ " + udata);
objects.Remove(udata); objects.Remove(udata);
objectsBackMap.Remove(o); objectsBackMap.Remove(o);
} }
/// <summary> /// <summary>
/// We want to ensure that objects always have a unique ID /// We want to ensure that objects always have a unique ID
/// </summary> /// </summary>
int nextObj = 0; int nextObj = 0;
int addObject(object obj) int addObject(object obj)
{ {
// New object: inserts it in the list // New object: inserts it in the list
int index = nextObj++; int index = nextObj++;
//Console.WriteLine("Adding " + obj.ToString() + " @ " + index); // Debug.WriteLine("Adding " + obj.ToString() + " @ " + index);
objects[index] = obj; objects[index] = obj;
objectsBackMap[obj] = index; objectsBackMap[obj] = index;
return index; return index;
} }
int addObject(object obj, int index)
{
// New object: inserts it in the list
//int index = nextObj++;
//Console.WriteLine("Adding " + obj.ToString() + " @ " + index);
objects[index] = obj;
objectsBackMap[obj] = index;
return index;
}
/* /*
* Gets an object from the Lua stack according to its Lua type. * Gets an object from the Lua stack according to its Lua type.
*/ */
internal object getObject(KopiLua.Lua.lua_State luaState,int index) internal object getObject(IntPtr luaState,int index)
{ {
LuaType type=KopiLua.Lua.lua_type(luaState,index).ToLuaType(); LuaTypes type=LuaDLL.lua_type(luaState,index);
switch(type) switch(type)
{ {
case LuaType.Number: case LuaTypes.LUA_TNUMBER:
{ {
return KopiLua.Lua.lua_tonumber(luaState,index); return LuaDLL.lua_tonumber(luaState,index);
} }
case LuaType.String: case LuaTypes.LUA_TSTRING:
{ {
return KopiLua.Lua.lua_tostring(luaState,index); return LuaDLL.lua_tostring(luaState,index);
} }
case LuaType.Boolean: case LuaTypes.LUA_TBOOLEAN:
{ {
return KopiLua.Lua.lua_toboolean(luaState,index); return LuaDLL.lua_toboolean(luaState,index);
} }
case LuaType.Table: case LuaTypes.LUA_TTABLE:
{ {
return getTable(luaState,index); return getTable(luaState,index);
} }
case LuaType.Function: case LuaTypes.LUA_TFUNCTION:
{ {
return getFunction(luaState,index); return getFunction(luaState,index);
} }
case LuaType.UserData: case LuaTypes.LUA_TUSERDATA:
{ {
int udata=LuaLib.luanet_tonetobject(luaState,index); int udata=LuaDLL.luanet_tonetobject(luaState,index);
Console.WriteLine("udata: {0}", udata);
if(udata!=-1) if(udata!=-1)
return objects[udata]; return objects[udata];
else else
//return null;
return getUserData(luaState,index); return getUserData(luaState,index);
} }
default: default:
...@@ -628,34 +626,34 @@ namespace LuaInterface ...@@ -628,34 +626,34 @@ namespace LuaInterface
/* /*
* Gets the table in the index positon of the Lua stack. * Gets the table in the index positon of the Lua stack.
*/ */
internal LuaTable getTable(KopiLua.Lua.lua_State luaState,int index) internal LuaTable getTable(IntPtr luaState,int index)
{ {
KopiLua.Lua.lua_pushvalue(luaState,index); LuaDLL.lua_pushvalue(luaState,index);
return new LuaTable(LuaLib.lua_ref(luaState,1),interpreter); return new LuaTable(LuaDLL.lua_ref(luaState,1),interpreter);
} }
/* /*
* Gets the userdata in the index positon of the Lua stack. * Gets the userdata in the index positon of the Lua stack.
*/ */
internal LuaUserData getUserData(KopiLua.Lua.lua_State luaState,int index) internal LuaUserData getUserData(IntPtr luaState,int index)
{ {
KopiLua.Lua.lua_pushvalue(luaState,index); LuaDLL.lua_pushvalue(luaState,index);
return new LuaUserData(LuaLib.lua_ref(luaState,1),interpreter); return new LuaUserData(LuaDLL.lua_ref(luaState,1),interpreter);
} }
/* /*
* Gets the function in the index positon of the Lua stack. * Gets the function in the index positon of the Lua stack.
*/ */
internal LuaFunction getFunction(KopiLua.Lua.lua_State luaState,int index) internal LuaFunction getFunction(IntPtr luaState,int index)
{ {
KopiLua.Lua.lua_pushvalue(luaState,index); LuaDLL.lua_pushvalue(luaState,index);
return new LuaFunction(LuaLib.lua_ref(luaState,1),interpreter); return new LuaFunction(LuaDLL.lua_ref(luaState,1),interpreter);
} }
/* /*
* Gets the CLR object in the index positon of the Lua stack. Returns * Gets the CLR object in the index positon of the Lua stack. Returns
* delegates as Lua functions. * delegates as Lua functions.
*/ */
internal object getNetObject(KopiLua.Lua.lua_State luaState,int index) internal object getNetObject(IntPtr luaState,int index)
{ {
int idx=LuaLib.luanet_tonetobject(luaState,index); int idx=LuaDLL.luanet_tonetobject(luaState,index);
if(idx!=-1) if(idx!=-1)
return objects[idx]; return objects[idx];
else else
...@@ -665,9 +663,9 @@ namespace LuaInterface ...@@ -665,9 +663,9 @@ namespace LuaInterface
* Gets the CLR object in the index positon of the Lua stack. Returns * Gets the CLR object in the index positon of the Lua stack. Returns
* delegates as is. * delegates as is.
*/ */
internal object getRawNetObject(KopiLua.Lua.lua_State luaState,int index) internal object getRawNetObject(IntPtr luaState,int index)
{ {
int udata=LuaLib.luanet_rawnetobj(luaState,index); int udata=LuaDLL.luanet_rawnetobj(luaState,index);
if(udata!=-1) if(udata!=-1)
{ {
return objects[udata]; return objects[udata];
...@@ -678,9 +676,9 @@ namespace LuaInterface ...@@ -678,9 +676,9 @@ namespace LuaInterface
* Pushes the entire array into the Lua stack and returns the number * Pushes the entire array into the Lua stack and returns the number
* of elements pushed. * of elements pushed.
*/ */
internal int returnValues(KopiLua.Lua.lua_State luaState, object[] returnValues) internal int returnValues(IntPtr luaState, object[] returnValues)
{ {
if(KopiLua.Lua.lua_checkstack(luaState,returnValues.Length+5).ToBoolean()) if(LuaDLL.lua_checkstack(luaState,returnValues.Length+5))
{ {
for(int i=0;i<returnValues.Length;i++) for(int i=0;i<returnValues.Length;i++)
{ {
...@@ -694,9 +692,9 @@ namespace LuaInterface ...@@ -694,9 +692,9 @@ namespace LuaInterface
* Gets the values from the provided index to * Gets the values from the provided index to
* the top of the stack and returns them in an array. * the top of the stack and returns them in an array.
*/ */
internal object[] popValues(KopiLua.Lua.lua_State luaState,int oldTop) internal object[] popValues(IntPtr luaState,int oldTop)
{ {
int newTop=KopiLua.Lua.lua_gettop(luaState); int newTop=LuaDLL.lua_gettop(luaState);
if(oldTop==newTop) if(oldTop==newTop)
{ {
return null; return null;
...@@ -708,7 +706,7 @@ namespace LuaInterface ...@@ -708,7 +706,7 @@ namespace LuaInterface
{ {
returnValues.Add(getObject(luaState,i)); returnValues.Add(getObject(luaState,i));
} }
KopiLua.Lua.lua_settop(luaState,oldTop); LuaDLL.lua_settop(luaState,oldTop);
return returnValues.ToArray(); return returnValues.ToArray();
} }
} }
...@@ -717,9 +715,9 @@ namespace LuaInterface ...@@ -717,9 +715,9 @@ namespace LuaInterface
* the top of the stack and returns them in an array, casting * the top of the stack and returns them in an array, casting
* them to the provided types. * them to the provided types.
*/ */
internal object[] popValues(KopiLua.Lua.lua_State luaState,int oldTop,Type[] popTypes) internal object[] popValues(IntPtr luaState,int oldTop,Type[] popTypes)
{ {
int newTop=KopiLua.Lua.lua_gettop(luaState); int newTop=LuaDLL.lua_gettop(luaState);
if(oldTop==newTop) if(oldTop==newTop)
{ {
return null; return null;
...@@ -737,56 +735,56 @@ namespace LuaInterface ...@@ -737,56 +735,56 @@ namespace LuaInterface
returnValues.Add(getAsType(luaState,i,popTypes[iTypes])); returnValues.Add(getAsType(luaState,i,popTypes[iTypes]));
iTypes++; iTypes++;
} }
KopiLua.Lua.lua_settop(luaState,oldTop); LuaDLL.lua_settop(luaState,oldTop);
return returnValues.ToArray(); return returnValues.ToArray();
} }
} }
// kevinh - the following line doesn't work for remoting proxies - they always return a match for 'is' // kevinh - the following line doesn't work for remoting proxies - they always return a match for 'is'
// else if(o is ILuaGeneratedType) // else if(o is ILuaGeneratedType)
static bool IsILua(object o) static bool IsILua(object o)
{ {
if(o is ILuaGeneratedType) if(o is ILuaGeneratedType)
{ {
// Make sure we are _really_ ILuaGenerated // Make sure we are _really_ ILuaGenerated
Type typ = o.GetType(); Type typ = o.GetType();
return (typ.GetInterface("ILuaGeneratedType") != null);
} return (typ.GetInterface("ILuaGeneratedType") != null);
else }
return false; else
} return false;
}
/* /*
* Pushes the object into the Lua stack according to its type. * Pushes the object into the Lua stack according to its type.
*/ */
internal void push(KopiLua.Lua.lua_State luaState, object o) internal void push(IntPtr luaState, object o)
{ {
//Console.WriteLine("push: {0}, {1}", o, luaState);
if(o==null) if(o==null)
{ {
KopiLua.Lua.lua_pushnil(luaState); LuaDLL.lua_pushnil(luaState);
} }
else if(o is sbyte || o is byte || o is short || o is ushort || else if(o is sbyte || o is byte || o is short || o is ushort ||
o is int || o is uint || o is long || o is float || o is int || o is uint || o is long || o is float ||
o is ulong || o is decimal || o is double) o is ulong || o is decimal || o is double)
{ {
double d=Convert.ToDouble(o); double d=Convert.ToDouble(o);
KopiLua.Lua.lua_pushnumber(luaState,d); LuaDLL.lua_pushnumber(luaState,d);
} }
else if(o is char) else if(o is char)
{ {
double d = (char)o; double d = (char)o;
KopiLua.Lua.lua_pushnumber(luaState,d); LuaDLL.lua_pushnumber(luaState,d);
} }
else if(o is string) else if(o is string)
{ {
string str=(string)o; string str=(string)o;
KopiLua.Lua.lua_pushstring(luaState,str); LuaDLL.lua_pushstring(luaState,str);
} }
else if(o is bool) else if(o is bool)
{ {
bool b=(bool)o; bool b=(bool)o;
KopiLua.Lua.lua_pushboolean(luaState,(b == true) ? 1 : 0); LuaDLL.lua_pushboolean(luaState,b);
} }
else if(IsILua(o)) else if(IsILua(o))
{ {
...@@ -796,9 +794,9 @@ namespace LuaInterface ...@@ -796,9 +794,9 @@ namespace LuaInterface
{ {
((LuaTable)o).push(luaState); ((LuaTable)o).push(luaState);
} }
else if(o is KopiLua.Lua.lua_CFunction) else if(o is LuaCSFunction)
{ {
pushFunction(luaState,(KopiLua.Lua.lua_CFunction)o); pushFunction(luaState,(LuaCSFunction)o);
} }
else if(o is LuaFunction) else if(o is LuaFunction)
{ {
...@@ -813,7 +811,7 @@ namespace LuaInterface ...@@ -813,7 +811,7 @@ namespace LuaInterface
* Checks if the method matches the arguments in the Lua stack, getting * Checks if the method matches the arguments in the Lua stack, getting
* the arguments if it does. * the arguments if it does.
*/ */
internal bool matchParameters(KopiLua.Lua.lua_State luaState,MethodBase method,ref MethodCache methodCache) internal bool matchParameters(IntPtr luaState,MethodBase method,ref MethodCache methodCache)
{ {
return metaFunctions.matchParameters(luaState,method,ref methodCache); return metaFunctions.matchParameters(luaState,method,ref methodCache);
} }
......
...@@ -22,7 +22,7 @@ using System.Security.Permissions; ...@@ -22,7 +22,7 @@ using System.Security.Permissions;
// You can specify all the values or you can default the Revision and Build Numbers // You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below: // by using the '*' as shown below:
[assembly: AssemblyVersion("2.0.1.*")] [assembly: AssemblyVersion("2.0.4.*")]
// //
// In order to sign your assembly you must specify a key to use. Refer to the // In order to sign your assembly you must specify a key to use. Refer to the
......
...@@ -9,6 +9,7 @@ namespace LuaInterface ...@@ -9,6 +9,7 @@ namespace LuaInterface
/// </summary> /// </summary>
public class ProxyType : IReflect public class ProxyType : IReflect
{ {
Type proxy; Type proxy;
public ProxyType(Type proxy) public ProxyType(Type proxy)
...@@ -16,14 +17,14 @@ namespace LuaInterface ...@@ -16,14 +17,14 @@ namespace LuaInterface
this.proxy = proxy; this.proxy = proxy;
} }
/// <summary> /// <summary>
/// Provide human readable short hand for this proxy object /// Provide human readable short hand for this proxy object
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
public override string ToString() public override string ToString()
{ {
return "ProxyType(" + UnderlyingSystemType + ")"; return "ProxyType(" + UnderlyingSystemType + ")";
} }
public Type UnderlyingSystemType public Type UnderlyingSystemType
...@@ -90,4 +91,4 @@ namespace LuaInterface ...@@ -90,4 +91,4 @@ namespace LuaInterface
} }
} }
} }
\ 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