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
{ {
...@@ -64,9 +64,9 @@ namespace LuaInterface ...@@ -64,9 +64,9 @@ namespace LuaInterface
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();
...@@ -81,55 +81,74 @@ namespace LuaInterface ...@@ -81,55 +81,74 @@ namespace LuaInterface
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
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 (LuaDLL.lua_isnumber(luaState, stackPos))
return extractValues[runtimeHandleValue]; return extractValues[runtimeHandleValue];
if (paramType == typeof(bool)) if (paramType == typeof(bool))
{ {
if (KopiLua.Lua.lua_isboolean(luaState, stackPos)) 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;
} }
...@@ -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
......
...@@ -4,10 +4,11 @@ namespace LuaInterface ...@@ -4,10 +4,11 @@ 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)
* */ * */
[CLSCompliant(true)]
public class Lua : IDisposable 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,10 +65,10 @@ namespace LuaInterface ...@@ -62,10 +65,10 @@ 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
...@@ -74,59 +77,67 @@ namespace LuaInterface ...@@ -74,59 +77,67 @@ namespace LuaInterface
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! * CAUTION: LuaInterface.Lua instances can't share the same lua state!
*/ */
public Lua(KopiLua.Lua.lua_State luaState) public Lua(Int64 luaState)
{
IntPtr lState = new IntPtr(luaState);
LuaDLL.lua_pushstring(lState, "LUAINTERFACE LOADED");
LuaDLL.lua_gettable(lState, (int)LuaIndexes.LUA_REGISTRYINDEX);
if(LuaDLL.lua_toboolean(lState,-1))
{ {
//IntPtr lState = new IntPtr(luaState); LuaDLL.lua_settop(lState,-2);
KopiLua.Lua.lua_pushstring(luaState, "LUAINTERFACE LOADED");
KopiLua.Lua.lua_gettable(luaState, (int)PseudoIndex.Registry);
if(KopiLua.Lua.lua_toboolean(luaState,-1).ToBoolean()) {
KopiLua.Lua.lua_settop(luaState,-2);
throw new LuaException("There is already a LuaInterface.Lua instance associated with this Lua state"); throw new LuaException("There is already a LuaInterface.Lua instance associated with this Lua state");
} else { }
KopiLua.Lua.lua_settop(luaState,-2); else
KopiLua.Lua.lua_pushstring(luaState, "LUAINTERFACE LOADED"); {
KopiLua.Lua.lua_pushboolean(luaState, 1); LuaDLL.lua_settop(lState,-2);
KopiLua.Lua.lua_settable(luaState, (int)PseudoIndex.Registry); LuaDLL.lua_pushstring(lState, "LUAINTERFACE LOADED");
this.luaState=luaState; LuaDLL.lua_pushboolean(lState, true);
KopiLua.Lua.lua_pushvalue(luaState, (int)PseudoIndex.Globals); LuaDLL.lua_settable(lState, (int)LuaIndexes.LUA_REGISTRYINDEX);
KopiLua.Lua.lua_getglobal(luaState, "luanet"); this.luaState=lState;
KopiLua.Lua.lua_pushstring(luaState, "getmetatable"); LuaDLL.lua_pushvalue(lState, (int)LuaIndexes.LUA_GLOBALSINDEX);
KopiLua.Lua.lua_getglobal(luaState, "getmetatable"); LuaDLL.lua_getglobal(lState, "luanet");
KopiLua.Lua.lua_settable(luaState, -3); LuaDLL.lua_pushstring(lState, "getmetatable");
KopiLua.Lua.lua_replace(luaState, (int)PseudoIndex.Globals); LuaDLL.lua_getglobal(lState, "getmetatable");
LuaDLL.lua_settable(lState, -3);
LuaDLL.lua_replace(lState, (int)LuaIndexes.LUA_GLOBALSINDEX);
translator=new ObjectTranslator(this, this.luaState); translator=new ObjectTranslator(this, this.luaState);
KopiLua.Lua.lua_replace(luaState, (int)PseudoIndex.Globals); LuaDLL.lua_replace(lState, (int)LuaIndexes.LUA_GLOBALSINDEX);
LuaLib.luaL_dostring(luaState, Lua.init_luanet); // steffenj: lua_dostring renamed to luaL_dostring LuaDLL.luaL_dostring(lState, Lua.init_luanet); // steffenj: lua_dostring renamed to luaL_dostring
} }
_StatePassed = true;
} }
/// <summary> /// <summary>
...@@ -134,7 +145,7 @@ namespace LuaInterface ...@@ -134,7 +145,7 @@ namespace LuaInterface
/// </summary> /// </summary>
/// <param name="luaState"></param> /// <param name="luaState"></param>
/// Not yet used /// Not yet used
int LockCallback(KopiLua.Lua.lua_State luaState) int LockCallback(IntPtr luaState)
{ {
// Monitor.Enter(luaLock); // Monitor.Enter(luaLock);
...@@ -146,17 +157,27 @@ namespace LuaInterface ...@@ -146,17 +157,27 @@ namespace LuaInterface
/// </summary> /// </summary>
/// <param name="luaState"></param> /// <param name="luaState"></param>
/// Not yet used /// Not yet used
int UnlockCallback(KopiLua.Lua.lua_State luaState) int UnlockCallback(IntPtr luaState)
{ {
// Monitor.Exit(luaLock); // Monitor.Exit(luaLock);
return 0; return 0;
} }
static int PanicCallback(KopiLua.Lua.lua_State luaState) public void Close()
{
if (_StatePassed)
return;
if (luaState != IntPtr.Zero)
LuaDLL.lua_close(luaState);
//luaState = IntPtr.Zero; <- suggested by Christopher Cebulski http://luaforge.net/forum/forum.php?thread_id=44593&forum_id=146
}
static int PanicCallback(IntPtr luaState)
{ {
// string desc = KopiLua.Lua.lua_tostring(luaState, 1); // string desc = LuaDLL.lua_tostring(luaState, 1);
string reason = String.Format("unprotected error in call to Lua API ({0})", KopiLua.Lua.lua_tostring(luaState, -1)); string reason = String.Format("unprotected error in call to Lua API ({0})", LuaDLL.lua_tostring(luaState, -1));
// lua_tostring(L, -1); // lua_tostring(L, -1);
...@@ -168,24 +189,19 @@ namespace LuaInterface ...@@ -168,24 +189,19 @@ namespace LuaInterface
/// <summary> /// <summary>
/// Assuming we have a Lua error string sitting on the stack, throw a C# exception out to the user's app /// Assuming we have a Lua error string sitting on the stack, throw a C# exception out to the user's app
/// </summary> /// </summary>
/// <exception cref="LuaScriptException">Thrown if the script caused an exception</exception>
void ThrowExceptionFromError(int oldTop) void ThrowExceptionFromError(int oldTop)
{ {
object err = translator.getObject(luaState, -1); object err = translator.getObject(luaState, -1);
KopiLua.Lua.lua_settop(luaState, oldTop); LuaDLL.lua_settop(luaState, oldTop);
// If the 'error' on the stack is an actual C# exception, just rethrow it. Otherwise the value must have started
// as a true Lua error and is best interpreted as a string - wrap it in a LuaException and rethrow.
Exception thrown = err as Exception;
if (thrown == null)
{
if (err == null)
err = "Unknown Lua Error";
thrown = new LuaException(err.ToString()); // A pre-wrapped exception - just rethrow it (stack trace of InnerException will be preserved)
} LuaScriptException luaEx = err as LuaScriptException;
if (luaEx != null) throw luaEx;
throw thrown; // A non-wrapped Lua error (best interpreted as a string) - wrap it and throw it
if (err == null) err = "Unknown Lua Error";
throw new LuaScriptException(err.ToString(), "");
} }
...@@ -202,7 +218,7 @@ namespace LuaInterface ...@@ -202,7 +218,7 @@ namespace LuaInterface
if (caughtExcept != null) if (caughtExcept != null)
{ {
translator.throwError(luaState, caughtExcept); translator.throwError(luaState, caughtExcept);
KopiLua.Lua.lua_pushnil(luaState); LuaDLL.lua_pushnil(luaState);
return 1; return 1;
} }
...@@ -210,6 +226,54 @@ namespace LuaInterface ...@@ -210,6 +226,54 @@ namespace LuaInterface
return 0; 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;
}
/* /*
* Excutes a Lua chunk and returns all the chunk's return * Excutes a Lua chunk and returns all the chunk's return
...@@ -217,33 +281,71 @@ namespace LuaInterface ...@@ -217,33 +281,71 @@ 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)
{
executing = true;
try
{ {
if (KopiLua.Lua.lua_pcall(luaState, 0, -1, 0) == 0) if (LuaDLL.lua_pcall(luaState, 0, -1, 0) == 0)
return translator.popValues(luaState, oldTop); return translator.popValues(luaState, oldTop);
else else
ThrowExceptionFromError(oldTop); 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
} }
/// <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)
{
executing = true;
try
{ {
if (KopiLua.Lua.lua_pcall(luaState, 0, -1, 0) == 0) if (LuaDLL.lua_pcall(luaState, 0, -1, 0) == 0)
return translator.popValues(luaState, oldTop); return translator.popValues(luaState, oldTop);
else else
ThrowExceptionFromError(oldTop); ThrowExceptionFromError(oldTop);
} }
finally { executing = false; }
}
else else
ThrowExceptionFromError(oldTop); ThrowExceptionFromError(oldTop);
...@@ -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,8 +519,8 @@ namespace LuaInterface ...@@ -303,8 +519,8 @@ 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;
} }
...@@ -345,8 +561,7 @@ namespace LuaInterface ...@@ -345,8 +561,7 @@ 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
...@@ -374,8 +589,8 @@ namespace LuaInterface ...@@ -374,8 +589,8 @@ 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)
...@@ -386,9 +601,14 @@ namespace LuaInterface ...@@ -386,9 +601,14 @@ 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
{
int error = LuaDLL.lua_pcall(luaState, nArgs, -1, 0);
if (error != 0)
ThrowExceptionFromError(oldTop); ThrowExceptionFromError(oldTop);
}
finally { executing = false; }
if(returnTypes != null) if(returnTypes != null)
return translator.popValues(luaState,oldTop,returnTypes); return translator.popValues(luaState,oldTop,returnTypes);
...@@ -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,30 +975,31 @@ namespace LuaInterface ...@@ -519,30 +975,31 @@ 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,15 +1009,15 @@ namespace LuaInterface ...@@ -552,15 +1009,15 @@ 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);
} }
...@@ -572,10 +1029,10 @@ namespace LuaInterface ...@@ -572,10 +1029,10 @@ namespace LuaInterface
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();
} }
...@@ -583,262 +1040,97 @@ namespace LuaInterface ...@@ -583,262 +1040,97 @@ namespace LuaInterface
#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;
public LuaTable(int reference, Lua interpreter)
{
this.reference=reference;
this.interpreter=interpreter;
}
~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.IEnumerator GetEnumerator()
{
return interpreter.GetTableDict(this).GetEnumerator();
}
public ICollection Keys
{ {
get { return interpreter.GetTableDict(this).Keys; } LUA_HOOKCALL = 0,
LUA_HOOKRET = 1,
LUA_HOOKLINE = 2,
LUA_HOOKCOUNT = 3,
LUA_HOOKTAILRET = 4,
} }
public ICollection Values /// <summary>
/// Event masks for lua hook callback
/// </summary>
/// <remarks>
/// Do not change any of the values because they must match the lua values
/// </remarks>
/// <author>Reinhard Ostermeier</author>
[Flags]
public enum EventMasks
{ {
get { return interpreter.GetTableDict(this).Values; } LUA_MASKCALL = (1 << EventCodes.LUA_HOOKCALL),
LUA_MASKRET = (1 << EventCodes.LUA_HOOKRET),
LUA_MASKLINE = (1 << EventCodes.LUA_HOOKLINE),
LUA_MASKCOUNT = (1 << EventCodes.LUA_HOOKCOUNT),
LUA_MASKALL = Int32.MaxValue,
} }
/* /// <summary>
* Gets an string fields of a table ignoring its metatable, /// Structure for lua debug information
* if it exists /// </summary>
*/ /// <remarks>
internal object rawget(string field) /// Do not change this struct because it must match the lua structure lua_debug
{ /// </remarks>
return interpreter.rawGetObject(reference,field); /// <author>Reinhard Ostermeier</author>
[System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)]
public struct LuaDebug
{
public EventCodes eventCode;
[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 String what;
[System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPStr)]
public String source;
public int currentline;
public int nups;
public int linedefined;
public int lastlinedefined;
[System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst = 60/*LUA_IDSIZE*/)]
public String shortsrc;
public int i_ci;
} }
internal object rawgetFunction(string field) /// <summary>
/// Event args for hook callback event
/// </summary>
/// <author>Reinhard Ostermeier</author>
public class DebugHookEventArgs : EventArgs
{ {
object obj=interpreter.rawGetObject(reference,field); private readonly LuaDebug luaDebug;
if(obj is KopiLua.Lua.lua_CFunction) public DebugHookEventArgs(LuaDebug luaDebug)
return new LuaFunction((KopiLua.Lua.lua_CFunction)obj,interpreter);
else
return obj;
}
/*
* Pushes this table into the Lua stack
*/
internal void push(KopiLua.Lua.lua_State luaState)
{ {
LuaLib.lua_getref(luaState,reference); this.luaDebug = luaDebug;
}
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,this.reference);
} else return false;
}
public override int GetHashCode()
{
return reference;
}
} }
public class LuaFunction public LuaDebug LuaDebug
{ {
private Lua interpreter; get { return luaDebug; }
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() public class HookExceptionEventArgs : EventArgs
{
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); private readonly Exception m_Exception;
} public Exception Exception
/*
* 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) get { return m_Exception; }
return reference;
else
return function.GetHashCode();
}
} }
public class LuaUserData public HookExceptionEventArgs(Exception ex)
{
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; m_Exception = ex;
} }
} }
} }
\ 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;
//}
}
}
...@@ -6,7 +6,7 @@ namespace LuaInterface ...@@ -6,7 +6,7 @@ namespace LuaInterface
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;
/* /*
...@@ -39,39 +39,39 @@ namespace LuaInterface ...@@ -39,39 +39,39 @@ namespace LuaInterface
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);
...@@ -85,34 +85,35 @@ namespace LuaInterface ...@@ -85,34 +85,35 @@ namespace LuaInterface
/* /*
* __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> /// <summary>
/// Debug tool to dump the lua stack /// Debug tool to dump the lua stack
/// </summary> /// </summary>
/// FIXME, move somewhere else /// FIXME, move somewhere else
public static void dumpStack(ObjectTranslator translator, KopiLua.Lua.lua_State luaState) 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); Debug.WriteLine("lua stack depth: " + depth);
for (int i = 1; i <= depth; i++) for (int i = 1; i <= depth; i++)
{ {
LuaType type = KopiLua.Lua.lua_type(luaState, i).ToLuaType(); LuaTypes type = LuaDLL.lua_type(luaState, i);
// we dump stacks when deep in calls, calling typename while the stack is in flux can fail sometimes, so manually check for key types // 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 == LuaType.Table) ? "table" : KopiLua.Lua.lua_typename(luaState, Convert.ToInt32(type)).ToString(); string typestr = (type == LuaTypes.LUA_TTABLE) ? "table" : LuaDLL.lua_typename(luaState, type);
string strrep = KopiLua.Lua.lua_tostring(luaState, i).ToString(); string strrep = LuaDLL.lua_tostring(luaState, i);
if (type == LuaType.UserData) if (type == LuaTypes.LUA_TUSERDATA)
{ {
object obj = translator.getRawNetObject(luaState, i); object obj = translator.getRawNetObject(luaState, i);
strrep = obj.ToString(); strrep = obj.ToString();
...@@ -122,6 +123,7 @@ namespace LuaInterface ...@@ -122,6 +123,7 @@ namespace LuaInterface
} }
} }
/* /*
* Called by the __index metafunction of CLR objects in case the * Called by the __index metafunction of CLR objects in case the
* method is not cached or it is a field/property/event. * method is not cached or it is a field/property/event.
...@@ -129,44 +131,80 @@ namespace LuaInterface ...@@ -129,44 +131,80 @@ namespace LuaInterface
* either the value of the member or a delegate to call it. * either the value of the member or a delegate to call it.
* If the member does not exist returns nil. * If the member does not exist returns nil.
*/ */
private int getMethod(KopiLua.Lua.lua_State luaState) private int getMethod(IntPtr luaState)
{ {
object obj = translator.getRawNetObject(luaState, 1); object obj = translator.getRawNetObject(luaState, 1);
if (obj == null) if (obj == null)
{ {
translator.throwError(luaState, "trying to index an invalid object reference"); translator.throwError(luaState, "trying to index an invalid object reference");
KopiLua.Lua.lua_pushnil(luaState); LuaDLL.lua_pushnil(luaState);
return 1; return 1;
} }
object index = translator.getObject(luaState, 2); object index = translator.getObject(luaState, 2);
//Type indexType = index.GetType(); Type indexType = index.GetType();
string methodName = index as string; // will be null if not a string arg string methodName = index as string; // will be null if not a string arg
Type objType = obj.GetType(); Type objType = obj.GetType();
// Handle the most common case, looking up the method by name // Handle the most common case, looking up the method by name.
// CP: This will fail when using indexers and attempting to get a value with the same name as a property of the object,
// ie: xmlelement['item'] <- item is a property of xmlelement
try
{
if (methodName != null && isMemberPresent(objType, methodName)) if (methodName != null && isMemberPresent(objType, methodName))
return getMember(luaState, objType, obj, methodName, BindingFlags.Instance); return getMember(luaState, objType, obj, methodName, BindingFlags.Instance | BindingFlags.IgnoreCase);
}
catch { }
// Try to access by array if the type is right and index is an int (lua numbers always come across as double) // Try to access by array if the type is right and index is an int (lua numbers always come across as double)
if (objType.IsArray && index is double) if (objType.IsArray && index is double)
{ {
object[] arr = (object[])obj; int intIndex = (int)((double)index);
translator.push(luaState, arr[(int)((double)index)]); if (objType.UnderlyingSystemType == typeof(float[]))
{
float[] arr = ((float[])obj);
translator.push(luaState, arr[intIndex]);
}
else if (objType.UnderlyingSystemType == typeof(double[]))
{
double[] arr = ((double[])obj);
translator.push(luaState, arr[intIndex]);
}
else if (objType.UnderlyingSystemType == typeof(int[]))
{
int[] arr = ((int[])obj);
translator.push(luaState, arr[intIndex]);
}
else
{
object[] arr = (object[])obj;
translator.push(luaState, arr[intIndex]);
}
} }
else else
{ {
// Try to use get_Item to index into this .net object // Try to use get_Item to index into this .net object
MethodInfo getter = objType.GetMethod("get_Item"); //MethodInfo getter = objType.GetMethod("get_Item");
MethodInfo[] methods = objType.GetMethods();
foreach (MethodInfo mInfo in methods)
{
if (mInfo.Name == "get_Item")
{
//check if the signature matches the input
if (mInfo.GetParameters().Length == 1)
{
MethodInfo getter = mInfo;
ParameterInfo[] actualParms = (getter != null) ? getter.GetParameters() : null; ParameterInfo[] actualParms = (getter != null) ? getter.GetParameters() : null;
if (actualParms == null || actualParms.Length != 1) if (actualParms == null || actualParms.Length != 1)
{ {
translator.throwError(luaState, "method not found (or no indexer): " + index); translator.throwError(luaState, "method not found (or no indexer): " + index);
KopiLua.Lua.lua_pushnil(luaState); LuaDLL.lua_pushnil(luaState);
} }
else else
{ {
...@@ -185,17 +223,22 @@ namespace LuaInterface ...@@ -185,17 +223,22 @@ namespace LuaInterface
catch (TargetInvocationException e) catch (TargetInvocationException e)
{ {
// Provide a more readable description for the common case of key not found // Provide a more readable description for the common case of key not found
if(e.InnerException is KeyNotFoundException) if (e.InnerException is KeyNotFoundException)
translator.throwError(luaState, "key '" + index + "' not found "); translator.throwError(luaState, "key '" + index + "' not found ");
else else
translator.throwError(luaState, "exception indexing '" + index + "' " + e.Message); translator.throwError(luaState, "exception indexing '" + index + "' " + e.Message);
KopiLua.Lua.lua_pushnil(luaState); LuaDLL.lua_pushnil(luaState);
}
}
} }
} }
} }
KopiLua.Lua.lua_pushboolean(luaState, 0);
}
LuaDLL.lua_pushboolean(luaState, false);
return 2; return 2;
} }
...@@ -204,31 +247,31 @@ namespace LuaInterface ...@@ -204,31 +247,31 @@ namespace LuaInterface
* __index metafunction of base classes (the base field of Lua tables). * __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. * Adds a prefix to the method name to call the base version of the method.
*/ */
private int getBaseMethod(KopiLua.Lua.lua_State luaState) private int getBaseMethod(IntPtr luaState)
{ {
object obj = translator.getRawNetObject(luaState, 1); object obj = translator.getRawNetObject(luaState, 1);
if (obj == null) if (obj == null)
{ {
translator.throwError(luaState, "trying to index an invalid object reference"); translator.throwError(luaState, "trying to index an invalid object reference");
KopiLua.Lua.lua_pushnil(luaState); LuaDLL.lua_pushnil(luaState);
KopiLua.Lua.lua_pushboolean(luaState, 0); LuaDLL.lua_pushboolean(luaState, false);
return 2; return 2;
} }
string methodName = KopiLua.Lua.lua_tostring(luaState, 2).ToString(); string methodName = LuaDLL.lua_tostring(luaState, 2);
if (methodName == null) if (methodName == null)
{ {
KopiLua.Lua.lua_pushnil(luaState); LuaDLL.lua_pushnil(luaState);
KopiLua.Lua.lua_pushboolean(luaState, 0); LuaDLL.lua_pushboolean(luaState, false);
return 2; return 2;
} }
getMember(luaState, obj.GetType(), obj, "__luaInterface_base_" + methodName, BindingFlags.Instance); getMember(luaState, obj.GetType(), obj, "__luaInterface_base_" + methodName, BindingFlags.Instance | BindingFlags.IgnoreCase);
KopiLua.Lua.lua_settop(luaState, -2); LuaDLL.lua_settop(luaState, -2);
if (KopiLua.Lua.lua_type(luaState, -1).ToLuaType() == LuaType.Nil) if (LuaDLL.lua_type(luaState, -1) == LuaTypes.LUA_TNIL)
{ {
KopiLua.Lua.lua_settop(luaState, -2); LuaDLL.lua_settop(luaState, -2);
return getMember(luaState, obj.GetType(), obj, methodName, BindingFlags.Instance); return getMember(luaState, obj.GetType(), obj, methodName, BindingFlags.Instance | BindingFlags.IgnoreCase);
} }
KopiLua.Lua.lua_pushboolean(luaState, 0); LuaDLL.lua_pushboolean(luaState, false);
return 2; return 2;
} }
...@@ -246,7 +289,8 @@ namespace LuaInterface ...@@ -246,7 +289,8 @@ namespace LuaInterface
if (cachedMember != null) if (cachedMember != null)
return true; return true;
MemberInfo[] members = objType.GetMember(methodName, BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); //CP: Removed NonPublic binding search
MemberInfo[] members = objType.GetMember(methodName, BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase/* | BindingFlags.NonPublic*/);
return (members.Length > 0); return (members.Length > 0);
} }
...@@ -256,15 +300,15 @@ namespace LuaInterface ...@@ -256,15 +300,15 @@ namespace LuaInterface
* Uses reflection to find members, and stores the reflected MemberInfo object in * Uses reflection to find members, and stores the reflected MemberInfo object in
* a cache (indexed by the type of the object and the name of the member). * a cache (indexed by the type of the object and the name of the member).
*/ */
private int getMember(KopiLua.Lua.lua_State luaState, IReflect objType, object obj, string methodName, BindingFlags bindingType) private int getMember(IntPtr luaState, IReflect objType, object obj, string methodName, BindingFlags bindingType)
{ {
bool implicitStatic = false; bool implicitStatic = false;
MemberInfo member = null; MemberInfo member = null;
object cachedMember = checkMemberCache(memberCache, objType, methodName); object cachedMember = checkMemberCache(memberCache, objType, methodName);
//object cachedMember=null; //object cachedMember=null;
if (cachedMember is KopiLua.Lua.lua_CFunction) if (cachedMember is LuaCSFunction)
{ {
translator.pushFunction(luaState, (KopiLua.Lua.lua_CFunction)cachedMember); translator.pushFunction(luaState, (LuaCSFunction)cachedMember);
translator.push(luaState, true); translator.push(luaState, true);
return 2; return 2;
} }
...@@ -274,14 +318,16 @@ namespace LuaInterface ...@@ -274,14 +318,16 @@ namespace LuaInterface
} }
else else
{ {
MemberInfo[] members = objType.GetMember(methodName, bindingType | BindingFlags.Public | BindingFlags.NonPublic); //CP: Removed NonPublic binding search
MemberInfo[] members = objType.GetMember(methodName, bindingType | BindingFlags.Public | BindingFlags.IgnoreCase/*| BindingFlags.NonPublic*/);
if (members.Length > 0) if (members.Length > 0)
member = members[0]; member = members[0];
else else
{ {
// If we can't find any suitable instance members, try to find them as statics - but we only want to allow implicit static // If we can't find any suitable instance members, try to find them as statics - but we only want to allow implicit static
// lookups for fields/properties/events -kevinh // lookups for fields/properties/events -kevinh
members = objType.GetMember(methodName, bindingType | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); //CP: Removed NonPublic binding search and made case insensitive
members = objType.GetMember(methodName, bindingType | BindingFlags.Static | BindingFlags.Public | BindingFlags.IgnoreCase/*| BindingFlags.NonPublic*/);
if (members.Length > 0) if (members.Length > 0)
{ {
...@@ -302,7 +348,7 @@ namespace LuaInterface ...@@ -302,7 +348,7 @@ namespace LuaInterface
} }
catch catch
{ {
KopiLua.Lua.lua_pushnil(luaState); LuaDLL.lua_pushnil(luaState);
} }
} }
else if (member.MemberType == MemberTypes.Property) else if (member.MemberType == MemberTypes.Property)
...@@ -323,12 +369,12 @@ namespace LuaInterface ...@@ -323,12 +369,12 @@ namespace LuaInterface
if (objType is Type && !(((Type)objType) == typeof(object))) if (objType is Type && !(((Type)objType) == typeof(object)))
return getMember(luaState, ((Type)objType).BaseType, obj, methodName, bindingType); return getMember(luaState, ((Type)objType).BaseType, obj, methodName, bindingType);
else else
KopiLua.Lua.lua_pushnil(luaState); LuaDLL.lua_pushnil(luaState);
} }
catch(TargetInvocationException e) // Convert this exception into a Lua error catch (TargetInvocationException e) // Convert this exception into a Lua error
{ {
ThrowError(luaState, e); ThrowError(luaState, e);
KopiLua.Lua.lua_pushnil(luaState); LuaDLL.lua_pushnil(luaState);
} }
} }
else if (member.MemberType == MemberTypes.Event) else if (member.MemberType == MemberTypes.Event)
...@@ -337,7 +383,7 @@ namespace LuaInterface ...@@ -337,7 +383,7 @@ namespace LuaInterface
if (cachedMember == null) setMemberCache(memberCache, objType, methodName, member); if (cachedMember == null) setMemberCache(memberCache, objType, methodName, member);
translator.push(luaState, new RegisterEventHandler(translator.pendingEvents, obj, eventInfo)); translator.push(luaState, new RegisterEventHandler(translator.pendingEvents, obj, eventInfo));
} }
else if(!implicitStatic) else if (!implicitStatic)
{ {
if (member.MemberType == MemberTypes.NestedType) if (member.MemberType == MemberTypes.NestedType)
{ {
...@@ -359,7 +405,8 @@ namespace LuaInterface ...@@ -359,7 +405,8 @@ namespace LuaInterface
else else
{ {
// Member type must be 'method' // Member type must be 'method'
KopiLua.Lua.lua_CFunction wrapper = new KopiLua.Lua.lua_CFunction((new LuaMethodWrapper(translator, objType, methodName, bindingType)).call); LuaCSFunction wrapper = new LuaCSFunction((new LuaMethodWrapper(translator, objType, methodName, bindingType)).call);
if (cachedMember == null) setMemberCache(memberCache, objType, methodName, wrapper); if (cachedMember == null) setMemberCache(memberCache, objType, methodName, wrapper);
translator.pushFunction(luaState, wrapper); translator.pushFunction(luaState, wrapper);
translator.push(luaState, true); translator.push(luaState, true);
...@@ -371,7 +418,7 @@ namespace LuaInterface ...@@ -371,7 +418,7 @@ namespace LuaInterface
// 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 // 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
translator.throwError(luaState, "can't pass instance to static method " + methodName); translator.throwError(luaState, "can't pass instance to static method " + methodName);
KopiLua.Lua.lua_pushnil(luaState); LuaDLL.lua_pushnil(luaState);
} }
} }
else else
...@@ -382,7 +429,7 @@ namespace LuaInterface ...@@ -382,7 +429,7 @@ namespace LuaInterface
translator.throwError(luaState, "unknown member name " + methodName); translator.throwError(luaState, "unknown member name " + methodName);
KopiLua.Lua.lua_pushnil(luaState); LuaDLL.lua_pushnil(luaState);
} }
// push false because we are NOT returning a function (see luaIndexFunction) // push false because we are NOT returning a function (see luaIndexFunction)
...@@ -418,7 +465,7 @@ namespace LuaInterface ...@@ -418,7 +465,7 @@ namespace LuaInterface
* the member name and the value to be stored as arguments. Throws * the member name and the value to be stored as arguments. Throws
* and error if the assignment is invalid. * and error if the assignment is invalid.
*/ */
private int setFieldOrProperty(KopiLua.Lua.lua_State luaState) private int setFieldOrProperty(IntPtr luaState)
{ {
object target = translator.getRawNetObject(luaState, 1); object target = translator.getRawNetObject(luaState, 1);
if (target == null) if (target == null)
...@@ -430,7 +477,7 @@ namespace LuaInterface ...@@ -430,7 +477,7 @@ namespace LuaInterface
// First try to look up the parameter as a property name // First try to look up the parameter as a property name
string detailMessage; string detailMessage;
bool didMember = trySetMember(luaState, type, target, BindingFlags.Instance, out detailMessage); bool didMember = trySetMember(luaState, type, target, BindingFlags.Instance | BindingFlags.IgnoreCase, out detailMessage);
if (didMember) if (didMember)
return 0; // Must have found the property name return 0; // Must have found the property name
...@@ -438,9 +485,9 @@ namespace LuaInterface ...@@ -438,9 +485,9 @@ namespace LuaInterface
// We didn't find a property name, now see if we can use a [] style this accessor to set array contents // We didn't find a property name, now see if we can use a [] style this accessor to set array contents
try try
{ {
if (type.IsArray && KopiLua.Lua.lua_isnumber(luaState, 2).ToBoolean()) if (type.IsArray && LuaDLL.lua_isnumber(luaState, 2))
{ {
int index = (int)KopiLua.Lua.lua_tonumber(luaState, 2); int index = (int)LuaDLL.lua_tonumber(luaState, 2);
Array arr = (Array)target; Array arr = (Array)target;
object val = translator.getAsType(luaState, 3, arr.GetType().GetElementType()); object val = translator.getAsType(luaState, 3, arr.GetType().GetElementType());
...@@ -495,7 +542,7 @@ namespace LuaInterface ...@@ -495,7 +542,7 @@ namespace LuaInterface
/// <param name="target"></param> /// <param name="target"></param>
/// <param name="bindingType"></param> /// <param name="bindingType"></param>
/// <returns>false if unable to find the named member, true for success</returns> /// <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) private bool trySetMember(IntPtr luaState, IReflect targetType, object target, BindingFlags bindingType, out string detailMessage)
{ {
detailMessage = null; // No error yet detailMessage = null; // No error yet
...@@ -503,14 +550,14 @@ namespace LuaInterface ...@@ -503,14 +550,14 @@ namespace LuaInterface
// changing the lua typecode to string // changing the lua typecode to string
// Note: We don't use isstring because the standard lua C isstring considers either strings or numbers to // Note: We don't use isstring because the standard lua C isstring considers either strings or numbers to
// be true for isstring. // be true for isstring.
if (KopiLua.Lua.lua_type(luaState, 2).ToLuaType() != LuaType.String) if (LuaDLL.lua_type(luaState, 2) != LuaTypes.LUA_TSTRING)
{ {
detailMessage = "property names must be strings"; detailMessage = "property names must be strings";
return false; return false;
} }
// We only look up property names by string // We only look up property names by string
string fieldName = KopiLua.Lua.lua_tostring(luaState, 2).ToString(); string fieldName = LuaDLL.lua_tostring(luaState, 2);
if (fieldName == null || fieldName.Length < 1 || !(char.IsLetter(fieldName[0]) || fieldName[0] == '_')) if (fieldName == null || fieldName.Length < 1 || !(char.IsLetter(fieldName[0]) || fieldName[0] == '_'))
{ {
detailMessage = "invalid property name"; detailMessage = "invalid property name";
...@@ -521,7 +568,8 @@ namespace LuaInterface ...@@ -521,7 +568,8 @@ namespace LuaInterface
MemberInfo member = (MemberInfo)checkMemberCache(memberCache, targetType, fieldName); MemberInfo member = (MemberInfo)checkMemberCache(memberCache, targetType, fieldName);
if (member == null) if (member == null)
{ {
MemberInfo[] members = targetType.GetMember(fieldName, bindingType | BindingFlags.Public | BindingFlags.NonPublic); //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) if (members.Length > 0)
{ {
member = members[0]; member = members[0];
...@@ -574,12 +622,12 @@ namespace LuaInterface ...@@ -574,12 +622,12 @@ namespace LuaInterface
* Writes to fields or properties, either static or instance. Throws an error * Writes to fields or properties, either static or instance. Throws an error
* if the operation is invalid. * if the operation is invalid.
*/ */
private int setMember(KopiLua.Lua.lua_State luaState, IReflect targetType, object target, BindingFlags bindingType) private int setMember(IntPtr luaState, IReflect targetType, object target, BindingFlags bindingType)
{ {
string detail; string detail;
bool success = trySetMember(luaState, targetType, target, bindingType, out detail); bool success = trySetMember(luaState, targetType, target, bindingType, out detail);
if(!success) if (!success)
translator.throwError(luaState, detail); translator.throwError(luaState, detail);
return 0; return 0;
...@@ -590,7 +638,7 @@ namespace LuaInterface ...@@ -590,7 +638,7 @@ namespace LuaInterface
/// </summary> /// </summary>
/// <param name="e"></param> /// <param name="e"></param>
/// We try to look into the exception to give the most meaningful description /// We try to look into the exception to give the most meaningful description
void ThrowError(KopiLua.Lua.lua_State luaState, Exception e) void ThrowError(IntPtr luaState, Exception e)
{ {
// If we got inside a reflection show what really happened // If we got inside a reflection show what really happened
TargetInvocationException te = e as TargetInvocationException; TargetInvocationException te = e as TargetInvocationException;
...@@ -604,38 +652,38 @@ namespace LuaInterface ...@@ -604,38 +652,38 @@ namespace LuaInterface
/* /*
* __index metafunction of type references, works on static members. * __index metafunction of type references, works on static members.
*/ */
private int getClassMethod(KopiLua.Lua.lua_State luaState) private int getClassMethod(IntPtr luaState)
{ {
IReflect klass; IReflect klass;
object obj = translator.getRawNetObject(luaState, 1); object obj = translator.getRawNetObject(luaState, 1);
if (obj == null || !(obj is IReflect)) if (obj == null || !(obj is IReflect))
{ {
translator.throwError(luaState, "trying to index an invalid type reference"); translator.throwError(luaState, "trying to index an invalid type reference");
KopiLua.Lua.lua_pushnil(luaState); LuaDLL.lua_pushnil(luaState);
return 1; return 1;
} }
else klass = (IReflect)obj; else klass = (IReflect)obj;
if (KopiLua.Lua.lua_isnumber(luaState, 2).ToBoolean()) if (LuaDLL.lua_isnumber(luaState, 2))
{ {
int size = (int)KopiLua.Lua.lua_tonumber(luaState, 2); int size = (int)LuaDLL.lua_tonumber(luaState, 2);
translator.push(luaState, Array.CreateInstance(klass.UnderlyingSystemType, size)); translator.push(luaState, Array.CreateInstance(klass.UnderlyingSystemType, size));
return 1; return 1;
} }
else else
{ {
string methodName = KopiLua.Lua.lua_tostring(luaState, 2).ToString(); string methodName = LuaDLL.lua_tostring(luaState, 2);
if (methodName == null) if (methodName == null)
{ {
KopiLua.Lua.lua_pushnil(luaState); LuaDLL.lua_pushnil(luaState);
return 1; return 1;
} } //CP: Ignore case
else return getMember(luaState, klass, null, methodName, BindingFlags.FlattenHierarchy | BindingFlags.Static); else return getMember(luaState, klass, null, methodName, BindingFlags.FlattenHierarchy | BindingFlags.Static | BindingFlags.IgnoreCase);
} }
} }
/* /*
* __newindex function of type references, works on static members. * __newindex function of type references, works on static members.
*/ */
private int setClassFieldOrProperty(KopiLua.Lua.lua_State luaState) private int setClassFieldOrProperty(IntPtr luaState)
{ {
IReflect target; IReflect target;
object obj = translator.getRawNetObject(luaState, 1); object obj = translator.getRawNetObject(luaState, 1);
...@@ -645,7 +693,7 @@ namespace LuaInterface ...@@ -645,7 +693,7 @@ namespace LuaInterface
return 0; return 0;
} }
else target = (IReflect)obj; else target = (IReflect)obj;
return setMember(luaState, target, null, BindingFlags.FlattenHierarchy | BindingFlags.Static); return setMember(luaState, target, null, BindingFlags.FlattenHierarchy | BindingFlags.Static | BindingFlags.IgnoreCase);
} }
/* /*
* __call metafunction of type references. Searches for and calls * __call metafunction of type references. Searches for and calls
...@@ -653,7 +701,7 @@ namespace LuaInterface ...@@ -653,7 +701,7 @@ namespace LuaInterface
* found or if the arguments are invalid. Throws an error if the constructor * found or if the arguments are invalid. Throws an error if the constructor
* generates an exception. * generates an exception.
*/ */
private int callConstructor(KopiLua.Lua.lua_State luaState) private int callConstructor(IntPtr luaState)
{ {
MethodCache validConstructor = new MethodCache(); MethodCache validConstructor = new MethodCache();
IReflect klass; IReflect klass;
...@@ -661,11 +709,11 @@ namespace LuaInterface ...@@ -661,11 +709,11 @@ namespace LuaInterface
if (obj == null || !(obj is IReflect)) if (obj == null || !(obj is IReflect))
{ {
translator.throwError(luaState, "trying to call constructor on an invalid type reference"); translator.throwError(luaState, "trying to call constructor on an invalid type reference");
KopiLua.Lua.lua_pushnil(luaState); LuaDLL.lua_pushnil(luaState);
return 1; return 1;
} }
else klass = (IReflect)obj; else klass = (IReflect)obj;
KopiLua.Lua.lua_remove(luaState, 1); LuaDLL.lua_remove(luaState, 1);
ConstructorInfo[] constructors = klass.UnderlyingSystemType.GetConstructors(); ConstructorInfo[] constructors = klass.UnderlyingSystemType.GetConstructors();
foreach (ConstructorInfo constructor in constructors) foreach (ConstructorInfo constructor in constructors)
{ {
...@@ -679,11 +727,11 @@ namespace LuaInterface ...@@ -679,11 +727,11 @@ namespace LuaInterface
catch (TargetInvocationException e) catch (TargetInvocationException e)
{ {
ThrowError(luaState, e); ThrowError(luaState, e);
KopiLua.Lua.lua_pushnil(luaState); LuaDLL.lua_pushnil(luaState);
} }
catch catch
{ {
KopiLua.Lua.lua_pushnil(luaState); LuaDLL.lua_pushnil(luaState);
} }
return 1; return 1;
} }
...@@ -694,7 +742,7 @@ namespace LuaInterface ...@@ -694,7 +742,7 @@ namespace LuaInterface
translator.throwError(luaState, String.Format("{0} does not contain constructor({1}) argument match", translator.throwError(luaState, String.Format("{0} does not contain constructor({1}) argument match",
klass.UnderlyingSystemType, klass.UnderlyingSystemType,
constructorName)); constructorName));
KopiLua.Lua.lua_pushnil(luaState); LuaDLL.lua_pushnil(luaState);
return 1; return 1;
} }
/* /*
...@@ -702,13 +750,13 @@ namespace LuaInterface ...@@ -702,13 +750,13 @@ namespace LuaInterface
* if the match was succesful. It it was also returns the information * if the match was succesful. It it was also returns the information
* necessary to invoke the method. * necessary to invoke the method.
*/ */
internal bool matchParameters(KopiLua.Lua.lua_State luaState, MethodBase method, ref MethodCache methodCache) internal bool matchParameters(IntPtr luaState, MethodBase method, ref MethodCache methodCache)
{ {
ExtractValue extractValue; ExtractValue extractValue;
bool isMethod = true; bool isMethod = true;
ParameterInfo[] paramInfo = method.GetParameters(); ParameterInfo[] paramInfo = method.GetParameters();
int currentLuaParam = 1; int currentLuaParam = 1;
int nLuaParams = KopiLua.Lua.lua_gettop(luaState); int nLuaParams = LuaDLL.lua_gettop(luaState);
ArrayList paramList = new ArrayList(); ArrayList paramList = new ArrayList();
List<int> outList = new List<int>(); List<int> outList = new List<int>();
List<MethodArgs> argTypes = new List<MethodArgs>(); List<MethodArgs> argTypes = new List<MethodArgs>();
...@@ -730,17 +778,61 @@ namespace LuaInterface ...@@ -730,17 +778,61 @@ namespace LuaInterface
break; break;
} }
} }
else if ((extractValue = translator.typeChecker.checkType(luaState, currentLuaParam, currentNetParam.ParameterType)) != null) // Type checking else if (_IsTypeCorrect(luaState, currentLuaParam, currentNetParam, out extractValue)) // Type checking
{ {
int index = paramList.Add(extractValue(luaState, currentLuaParam)); int index = paramList.Add(extractValue(luaState, currentLuaParam));
MethodArgs methodArg = new MethodArgs(); MethodArgs methodArg = new MethodArgs();
methodArg.index = index; methodArg.index = index;
methodArg.extractValue = extractValue; methodArg.extractValue = extractValue;
argTypes.Add(methodArg); argTypes.Add(methodArg);
if (currentNetParam.ParameterType.IsByRef) if (currentNetParam.ParameterType.IsByRef)
outList.Add(index); outList.Add(index);
currentLuaParam++; currentLuaParam++;
} // Type does not match, ignore if the parameter is optional } // 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) else if (currentNetParam.IsOptional)
{ {
paramList.Add(currentNetParam.DefaultValue); paramList.Add(currentNetParam.DefaultValue);
...@@ -762,5 +854,89 @@ namespace LuaInterface ...@@ -762,5 +854,89 @@ namespace LuaInterface
} }
return isMethod; 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
...@@ -6,14 +6,34 @@ namespace LuaInterface ...@@ -6,14 +6,34 @@ namespace LuaInterface
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;
public MethodBase cachedMethod
{
get
{
return _cachedMethod;
}
set
{
_cachedMethod = value;
MethodInfo mi = value as MethodInfo;
if (mi != null)
{
IsReturnVoid = string.Compare(mi.ReturnType.Name, "System.Void", true) == 0;
}
}
}
public bool IsReturnVoid;
// List or arguments // List or arguments
public object[] args; public object[] args;
// Positions of out parameters // Positions of out parameters
...@@ -31,12 +51,16 @@ namespace LuaInterface ...@@ -31,12 +51,16 @@ namespace LuaInterface
public int index; public int index;
// Type-conversion function // Type-conversion function
public ExtractValue extractValue; public ExtractValue extractValue;
public bool isParamsArray;
public Type paramsArrayType;
} }
/* /*
* Argument extraction with type-conversion function * Argument extraction with type-conversion function
*/ */
delegate object ExtractValue(KopiLua.Lua.lua_State luaState, int stackPos); delegate object ExtractValue(IntPtr luaState, int stackPos);
/* /*
* Wrapper class for methods/constructors accessed from Lua. * Wrapper class for methods/constructors accessed from Lua.
...@@ -46,42 +70,50 @@ namespace LuaInterface ...@@ -46,42 +70,50 @@ namespace LuaInterface
*/ */
class LuaMethodWrapper class LuaMethodWrapper
{ {
ObjectTranslator translator; private ObjectTranslator _Translator;
MethodBase method; private MethodBase _Method;
MethodCache lastCalledMethod=new MethodCache(); private MethodCache _LastCalledMethod = new MethodCache();
string methodName; private string _MethodName;
MemberInfo[] members; private MemberInfo[] _Members;
IReflect targetType; private IReflect _TargetType;
ExtractValue extractTarget; private ExtractValue _ExtractTarget;
object target; private object _Target;
BindingFlags bindingType; private BindingFlags _BindingType;
/* /*
* Constructs the wrapper for a known MethodBase instance * Constructs the wrapper for a known MethodBase instance
*/ */
public LuaMethodWrapper(ObjectTranslator translator, object target, IReflect targetType, MethodBase method) public LuaMethodWrapper(ObjectTranslator translator, object target, IReflect targetType, MethodBase method)
{ {
this.translator=translator; _Translator = translator;
this.target=target; _Target = target;
this.targetType=targetType; _TargetType = targetType;
if(targetType!=null) if (targetType != null)
extractTarget=translator.typeChecker.getExtractor(targetType); _ExtractTarget = translator.typeChecker.getExtractor(targetType);
this.method=method; _Method = method;
this.methodName=method.Name; _MethodName = method.Name;
if(method.IsStatic) { bindingType=BindingFlags.Static; }
else { bindingType=BindingFlags.Instance; } if (method.IsStatic)
{ _BindingType = BindingFlags.Static; }
else
{ _BindingType = BindingFlags.Instance; }
} }
/* /*
* Constructs the wrapper for a known method name * Constructs the wrapper for a known method name
*/ */
public LuaMethodWrapper(ObjectTranslator translator, IReflect targetType, string methodName, BindingFlags bindingType) public LuaMethodWrapper(ObjectTranslator translator, IReflect targetType, string methodName, BindingFlags bindingType)
{ {
this.translator=translator; _Translator = translator;
this.methodName=methodName; _MethodName = methodName;
this.targetType=targetType; _TargetType = targetType;
if(targetType!=null)
extractTarget=translator.typeChecker.getExtractor(targetType); if (targetType != null)
this.bindingType=bindingType; _ExtractTarget = translator.typeChecker.getExtractor(targetType);
members=targetType.UnderlyingSystemType.GetMember(methodName,MemberTypes.Method,bindingType|BindingFlags.Public|BindingFlags.NonPublic);
_BindingType = bindingType;
//CP: Removed NonPublic binding search and added IgnoreCase
_Members = targetType.UnderlyingSystemType.GetMember(methodName, MemberTypes.Method, bindingType | BindingFlags.Public | BindingFlags.IgnoreCase/*|BindingFlags.NonPublic*/);
} }
...@@ -92,7 +124,7 @@ namespace LuaInterface ...@@ -92,7 +124,7 @@ namespace LuaInterface
/// <param name="e">null for no pending exception</param> /// <param name="e">null for no pending exception</param>
int SetPendingException(Exception e) int SetPendingException(Exception e)
{ {
return translator.interpreter.SetPendingException(e); return _Translator.interpreter.SetPendingException(e);
} }
...@@ -100,78 +132,102 @@ namespace LuaInterface ...@@ -100,78 +132,102 @@ namespace LuaInterface
* Calls the method. Receives the arguments from the Lua stack * Calls the method. Receives the arguments from the Lua stack
* and returns values in it. * and returns values in it.
*/ */
public int call(KopiLua.Lua.lua_State luaState) public int call(IntPtr luaState)
{ {
MethodBase methodToCall=method; MethodBase methodToCall = _Method;
object targetObject=target; object targetObject = _Target;
bool failedCall=true; bool failedCall = true;
int nReturnValues=0; int nReturnValues = 0;
Console.WriteLine("asyyyyyyyyyyyyyy");
if(!KopiLua.Lua.lua_checkstack(luaState,5).ToBoolean()) if (!LuaDLL.lua_checkstack(luaState, 5))
throw new LuaException("Lua stack overflow"); throw new LuaException("Lua stack overflow");
Console.WriteLine("asyyyyyyyyyyyyyy1");
bool isStatic = (bindingType & BindingFlags.Static) == BindingFlags.Static; bool isStatic = (_BindingType & BindingFlags.Static) == BindingFlags.Static;
Console.WriteLine("asyyyyyyyyyyyyyy2");
SetPendingException(null); SetPendingException(null);
Console.WriteLine("asyyyyyyyyyyyyyy3");
Console.WriteLine(methodToCall==null); if (methodToCall == null) // Method from name
if(methodToCall==null) // Method from name
{ {
if (isStatic) if (isStatic)
targetObject=null; targetObject = null;
else else
targetObject=extractTarget(luaState,1); targetObject = _ExtractTarget(luaState, 1);
//KopiLua.Lua.lua_remove(luaState,1); // Pops the receiver
Console.WriteLine("asdxxxxxx"); //LuaDLL.lua_remove(luaState,1); // Pops the receiver
Console.WriteLine(lastCalledMethod.cachedMethod); if (_LastCalledMethod.cachedMethod != null) // Cached?
Console.WriteLine(lastCalledMethod.cachedMethod!=null);
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 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; int numArgsPassed = LuaDLL.lua_gettop(luaState) - numStackToSkip;
if(numArgsPassed == lastCalledMethod.argTypes.Length) // No. of args match? if (numArgsPassed == _LastCalledMethod.argTypes.Length) // No. of args match?
{ {
if(!KopiLua.Lua.lua_checkstack(luaState,lastCalledMethod.outList.Length+6).ToBoolean()) if (!LuaDLL.lua_checkstack(luaState, _LastCalledMethod.outList.Length + 6))
throw new LuaException("Lua stack overflow"); throw new LuaException("Lua stack overflow");
try try
{ {
Console.WriteLine("0"); for (int i = 0; i < _LastCalledMethod.argTypes.Length; i++)
Console.WriteLine(lastCalledMethod.argTypes.Length); {
for(int i=0;i<lastCalledMethod.argTypes.Length;i++) if (_LastCalledMethod.argTypes[i].isParamsArray)
{
object luaParamValue = _LastCalledMethod.argTypes[i].extractValue(luaState, i + 1 + numStackToSkip);
Type paramArrayType = _LastCalledMethod.argTypes[i].paramsArrayType;
Array paramArray;
if (luaParamValue is LuaTable)
{
LuaTable table = (LuaTable)luaParamValue;
paramArray = Array.CreateInstance(paramArrayType, table.Values.Count);
for (int x = 1; x <= table.Values.Count; x++)
{
paramArray.SetValue(Convert.ChangeType(table[x], paramArrayType), x - 1);
}
}
else
{
paramArray = Array.CreateInstance(paramArrayType, 1);
paramArray.SetValue(luaParamValue, 0);
}
_LastCalledMethod.args[_LastCalledMethod.argTypes[i].index] = paramArray;
}
else
{ {
lastCalledMethod.args[lastCalledMethod.argTypes[i].index]= _LastCalledMethod.args[_LastCalledMethod.argTypes[i].index] =
lastCalledMethod.argTypes[i].extractValue(luaState, i + 1 + numStackToSkip); _LastCalledMethod.argTypes[i].extractValue(luaState, i + 1 + numStackToSkip);
}
if(lastCalledMethod.args[lastCalledMethod.argTypes[i].index]==null && if (_LastCalledMethod.args[_LastCalledMethod.argTypes[i].index] == null &&
!KopiLua.Lua.lua_isnil(luaState, i + 1 + numStackToSkip)) !LuaDLL.lua_isnil(luaState, i + 1 + numStackToSkip))
{ {
throw new LuaException("argument number "+(i+1)+" is invalid"); throw new LuaException("argument number " + (i + 1) + " is invalid");
} }
} }
Console.WriteLine("asd"); if ((_BindingType & BindingFlags.Static) == BindingFlags.Static)
if((bindingType & BindingFlags.Static)==BindingFlags.Static)
{ {
translator.push(luaState,lastCalledMethod.cachedMethod.Invoke(null,lastCalledMethod.args)); _Translator.push(luaState, _LastCalledMethod.cachedMethod.Invoke(null, _LastCalledMethod.args));
} }
else else
{ {
Console.WriteLine("asd2"); if (_LastCalledMethod.cachedMethod.IsConstructor)
if(lastCalledMethod.cachedMethod.IsConstructor) _Translator.push(luaState, ((ConstructorInfo)_LastCalledMethod.cachedMethod).Invoke(_LastCalledMethod.args));
translator.push(luaState,((ConstructorInfo)lastCalledMethod.cachedMethod).Invoke(lastCalledMethod.args));
else else
translator.push(luaState,lastCalledMethod.cachedMethod.Invoke(targetObject,lastCalledMethod.args)); _Translator.push(luaState, _LastCalledMethod.cachedMethod.Invoke(targetObject, _LastCalledMethod.args));
} }
failedCall=false; failedCall = false;
} }
catch(TargetInvocationException e) catch (TargetInvocationException e)
{ {
// Failure of method invocation // Failure of method invocation
return SetPendingException(e.GetBaseException()); return SetPendingException(e.GetBaseException());
} }
catch(Exception e) catch (Exception e)
{ {
if(members.Length==1) // Is the method overloaded? if (_Members.Length == 1) // Is the method overloaded?
// No, throw error // No, throw error
return SetPendingException(e); return SetPendingException(e);
} }
...@@ -179,7 +235,7 @@ Console.WriteLine("asyyyyyyyyyyyyyy3"); ...@@ -179,7 +235,7 @@ Console.WriteLine("asyyyyyyyyyyyyyy3");
} }
// Cache miss // Cache miss
if(failedCall) if (failedCall)
{ {
// System.Diagnostics.Debug.WriteLine("cache miss on " + methodName); // System.Diagnostics.Debug.WriteLine("cache miss on " + methodName);
...@@ -188,92 +244,131 @@ Console.WriteLine("asyyyyyyyyyyyyyy3"); ...@@ -188,92 +244,131 @@ Console.WriteLine("asyyyyyyyyyyyyyy3");
{ {
if (targetObject == null) if (targetObject == null)
{ {
translator.throwError(luaState, String.Format("instance method '{0}' requires a non null target object", methodName)); _Translator.throwError(luaState, String.Format("instance method '{0}' requires a non null target object", _MethodName));
KopiLua.Lua.lua_pushnil(luaState); LuaDLL.lua_pushnil(luaState);
return 1; return 1;
} }
KopiLua.Lua.lua_remove(luaState, 1); // Pops the receiver LuaDLL.lua_remove(luaState, 1); // Pops the receiver
} }
bool hasMatch=false; bool hasMatch = false;
string candidateName = null; string candidateName = null;
foreach(MemberInfo member in members) foreach (MemberInfo member in _Members)
{ {
candidateName = member.ReflectedType.Name + "." + member.Name; candidateName = member.ReflectedType.Name + "." + member.Name;
MethodBase m=(MethodInfo)member; MethodBase m = (MethodInfo)member;
bool isMethod=translator.matchParameters(luaState,m,ref lastCalledMethod); bool isMethod = _Translator.matchParameters(luaState, m, ref _LastCalledMethod);
if(isMethod) if (isMethod)
{ {
hasMatch=true; hasMatch = true;
break; break;
} }
} }
if(!hasMatch) if (!hasMatch)
{ {
string msg = (candidateName == null) string msg = (candidateName == null)
? "invalid arguments to method call" ? "invalid arguments to method call"
: ("invalid arguments to method: " + candidateName); : ("invalid arguments to method: " + candidateName);
translator.throwError(luaState, msg); _Translator.throwError(luaState, msg);
KopiLua.Lua.lua_pushnil(luaState); LuaDLL.lua_pushnil(luaState);
return 1; return 1;
} }
} }
} }
else // Method from MethodBase instance else // Method from MethodBase instance
{ {
if(!methodToCall.IsStatic && !methodToCall.IsConstructor && targetObject==null) if (methodToCall.ContainsGenericParameters)
{
bool isMethod = _Translator.matchParameters(luaState, methodToCall, ref _LastCalledMethod);
if (methodToCall.IsGenericMethodDefinition)
{ {
targetObject=extractTarget(luaState,1); //need to make a concrete type of the generic method definition
KopiLua.Lua.lua_remove(luaState,1); // Pops the receiver List<Type> typeArgs = new List<Type>();
foreach (object arg in _LastCalledMethod.args)
typeArgs.Add(arg.GetType());
MethodInfo concreteMethod = (methodToCall as MethodInfo).MakeGenericMethod(typeArgs.ToArray());
_Translator.push(luaState, concreteMethod.Invoke(targetObject, _LastCalledMethod.args));
failedCall = false;
} }
if(!translator.matchParameters(luaState,methodToCall,ref lastCalledMethod)) else if (methodToCall.ContainsGenericParameters)
{ {
translator.throwError(luaState,"invalid arguments to method call"); _Translator.throwError(luaState, "unable to invoke method on generic class as the current method is an open generic method");
KopiLua.Lua.lua_pushnil(luaState); LuaDLL.lua_pushnil(luaState);
return 1; return 1;
} }
} }
else
{
if (!methodToCall.IsStatic && !methodToCall.IsConstructor && targetObject == null)
{
targetObject = _ExtractTarget(luaState, 1);
LuaDLL.lua_remove(luaState, 1); // Pops the receiver
}
if(failedCall) if (!_Translator.matchParameters(luaState, methodToCall, ref _LastCalledMethod))
{ {
if(!KopiLua.Lua.lua_checkstack(luaState,lastCalledMethod.outList.Length+6).ToBoolean()) _Translator.throwError(luaState, "invalid arguments to method call");
LuaDLL.lua_pushnil(luaState);
return 1;
}
}
}
if (failedCall)
{
if (!LuaDLL.lua_checkstack(luaState, _LastCalledMethod.outList.Length + 6))
throw new LuaException("Lua stack overflow"); throw new LuaException("Lua stack overflow");
try try
{ {
if (isStatic) if (isStatic)
{ {
translator.push(luaState,lastCalledMethod.cachedMethod.Invoke(null,lastCalledMethod.args)); _Translator.push(luaState, _LastCalledMethod.cachedMethod.Invoke(null, _LastCalledMethod.args));
} }
else else
{ {
if(lastCalledMethod.cachedMethod.IsConstructor) if (_LastCalledMethod.cachedMethod.IsConstructor)
translator.push(luaState,((ConstructorInfo)lastCalledMethod.cachedMethod).Invoke(lastCalledMethod.args)); _Translator.push(luaState, ((ConstructorInfo)_LastCalledMethod.cachedMethod).Invoke(_LastCalledMethod.args));
else else
translator.push(luaState,lastCalledMethod.cachedMethod.Invoke(targetObject,lastCalledMethod.args)); _Translator.push(luaState, _LastCalledMethod.cachedMethod.Invoke(targetObject, _LastCalledMethod.args));
} }
} }
catch(TargetInvocationException e) catch (TargetInvocationException e)
{ {
return SetPendingException(e.GetBaseException()); return SetPendingException(e.GetBaseException());
} }
catch(Exception e) catch (Exception e)
{ {
return SetPendingException(e); return SetPendingException(e);
} }
} }
// Pushes out and ref return values // Pushes out and ref return values
for(int index=0;index<lastCalledMethod.outList.Length;index++) for (int index = 0; index < _LastCalledMethod.outList.Length; index++)
{ {
nReturnValues++; nReturnValues++;
//for(int i=0;i<lastCalledMethod.outList.Length;i++) //for(int i=0;i<lastCalledMethod.outList.Length;i++)
translator.push(luaState,lastCalledMethod.args[lastCalledMethod.outList[index]]); _Translator.push(luaState, _LastCalledMethod.args[_LastCalledMethod.outList[index]]);
} }
//by isSingle 2010-09-10 11:26:31
//Desc:
// if not return void,we need add 1,
// or we will lost the function's return value
// when call dotnet function like "int foo(arg1,out arg2,out arg3)" in lua code
if (!_LastCalledMethod.IsReturnVoid && nReturnValues > 0)
{
nReturnValues++;
}
return nReturnValues < 1 ? 1 : nReturnValues; return nReturnValues < 1 ? 1 : nReturnValues;
} }
} }
...@@ -329,8 +424,8 @@ Console.WriteLine("asyyyyyyyyyyyyyy3"); ...@@ -329,8 +424,8 @@ Console.WriteLine("asyyyyyyyyyyyyyy3");
public RegisterEventHandler(EventHandlerContainer pendingEvents, object target, EventInfo eventInfo) public RegisterEventHandler(EventHandlerContainer pendingEvents, object target, EventInfo eventInfo)
{ {
this.target=target; this.target = target;
this.eventInfo=eventInfo; this.eventInfo = eventInfo;
this.pendingEvents = pendingEvents; this.pendingEvents = pendingEvents;
} }
...@@ -340,15 +435,24 @@ Console.WriteLine("asyyyyyyyyyyyyyy3"); ...@@ -340,15 +435,24 @@ Console.WriteLine("asyyyyyyyyyyyyyy3");
*/ */
public Delegate Add(LuaFunction function) public Delegate Add(LuaFunction function)
{ {
MethodInfo mi = eventInfo.EventHandlerType.GetMethod("Invoke"); //CP: Fix by Ben Bryant for event handling with one parameter
ParameterInfo[] pi = mi.GetParameters(); //link: http://luaforge.net/forum/message.php?msg_id=9266
LuaEventHandler handler=CodeGeneration.Instance.GetEvent(pi[1].ParameterType,function); Delegate handlerDelegate = CodeGeneration.Instance.GetDelegate(eventInfo.EventHandlerType, function);
eventInfo.AddEventHandler(target, handlerDelegate);
Delegate handlerDelegate=Delegate.CreateDelegate(eventInfo.EventHandlerType,handler,"HandleEvent");
eventInfo.AddEventHandler(target,handlerDelegate);
pendingEvents.Add(handlerDelegate, this); pendingEvents.Add(handlerDelegate, this);
return handlerDelegate; return handlerDelegate;
//MethodInfo mi = eventInfo.EventHandlerType.GetMethod("Invoke");
//ParameterInfo[] pi = mi.GetParameters();
//LuaEventHandler handler=CodeGeneration.Instance.GetEvent(pi[1].ParameterType,function);
//Delegate handlerDelegate=Delegate.CreateDelegate(eventInfo.EventHandlerType,handler,"HandleEvent");
//eventInfo.AddEventHandler(target,handlerDelegate);
//pendingEvents.Add(handlerDelegate, this);
//return handlerDelegate;
} }
/* /*
...@@ -381,10 +485,16 @@ Console.WriteLine("asyyyyyyyyyyyyyy3"); ...@@ -381,10 +485,16 @@ Console.WriteLine("asyyyyyyyyyyyyyy3");
{ {
public LuaFunction handler = null; public LuaFunction handler = null;
public void handleEvent(object sender,object data) // 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(new object[] { sender,data },new Type[0]); handler.Call(args);
} }
//public void handleEvent(object sender,object data)
//{
// handler.call(new object[] { sender,data },new Type[0]);
//}
} }
/* /*
...@@ -401,32 +511,32 @@ Console.WriteLine("asyyyyyyyyyyyyyy3"); ...@@ -401,32 +511,32 @@ Console.WriteLine("asyyyyyyyyyyyyyy3");
public LuaFunction function; public LuaFunction function;
public LuaDelegate() public LuaDelegate()
{ {
function=null; function = null;
returnTypes=null; returnTypes = null;
} }
public object callFunction(object[] args,object[] inArgs,int[] outArgs) public object callFunction(object[] args, object[] inArgs, int[] outArgs)
{ {
// args is the return array of arguments, inArgs is the actual array // args is the return array of arguments, inArgs is the actual array
// of arguments passed to the function (with in parameters only), outArgs // of arguments passed to the function (with in parameters only), outArgs
// has the positions of out parameters // has the positions of out parameters
object returnValue; object returnValue;
int iRefArgs; int iRefArgs;
object[] returnValues=function.call(inArgs,returnTypes); object[] returnValues = function.call(inArgs, returnTypes);
if(returnTypes[0] == typeof(void)) if (returnTypes[0] == typeof(void))
{ {
returnValue=null; returnValue = null;
iRefArgs=0; iRefArgs = 0;
} }
else else
{ {
returnValue=returnValues[0]; returnValue = returnValues[0];
iRefArgs=1; iRefArgs = 1;
} }
// Sets the value of out and ref parameters (from // Sets the value of out and ref parameters (from
// the values returned by the Lua function). // the values returned by the Lua function).
for(int i=0;i<outArgs.Length;i++) for (int i = 0; i < outArgs.Length; i++)
{ {
args[outArgs[i]]=returnValues[iRefArgs]; args[outArgs[i]] = returnValues[iRefArgs];
iRefArgs++; iRefArgs++;
} }
return returnValue; return returnValue;
...@@ -445,10 +555,10 @@ Console.WriteLine("asyyyyyyyyyyyyyy3"); ...@@ -445,10 +555,10 @@ Console.WriteLine("asyyyyyyyyyyyyyy3");
* Gets the function called name from the provided table, * Gets the function called name from the provided table,
* returning null if it does not exist * returning null if it does not exist
*/ */
public static LuaFunction getTableFunction(LuaTable luaTable,string name) public static LuaFunction getTableFunction(LuaTable luaTable, string name)
{ {
object funcObj=luaTable.rawget(name); object funcObj = luaTable.rawget(name);
if(funcObj is LuaFunction) if (funcObj is LuaFunction)
return (LuaFunction)funcObj; return (LuaFunction)funcObj;
else else
return null; return null;
...@@ -456,27 +566,27 @@ Console.WriteLine("asyyyyyyyyyyyyyy3"); ...@@ -456,27 +566,27 @@ Console.WriteLine("asyyyyyyyyyyyyyy3");
/* /*
* Calls the provided function with the provided parameters * Calls the provided function with the provided parameters
*/ */
public static object callFunction(LuaFunction function,object[] args,Type[] returnTypes,object[] inArgs,int[] outArgs) 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 // args is the return array of arguments, inArgs is the actual array
// of arguments passed to the function (with in parameters only), outArgs // of arguments passed to the function (with in parameters only), outArgs
// has the positions of out parameters // has the positions of out parameters
object returnValue; object returnValue;
int iRefArgs; int iRefArgs;
object[] returnValues=function.call(inArgs,returnTypes); object[] returnValues = function.call(inArgs, returnTypes);
if(returnTypes[0] == typeof(void)) if (returnTypes[0] == typeof(void))
{ {
returnValue=null; returnValue = null;
iRefArgs=0; iRefArgs = 0;
} }
else else
{ {
returnValue=returnValues[0]; returnValue = returnValues[0];
iRefArgs=1; iRefArgs = 1;
} }
for(int i=0;i<outArgs.Length;i++) for (int i = 0; i < outArgs.Length; i++)
{ {
args[outArgs[i]]=returnValues[iRefArgs]; args[outArgs[i]] = returnValues[iRefArgs];
iRefArgs++; iRefArgs++;
} }
return returnValue; return returnValue;
......
...@@ -6,7 +6,7 @@ namespace LuaInterface ...@@ -6,7 +6,7 @@ namespace LuaInterface
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
...@@ -25,24 +25,24 @@ namespace LuaInterface ...@@ -25,24 +25,24 @@ namespace LuaInterface
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,159 +55,179 @@ namespace LuaInterface ...@@ -55,159 +55,179 @@ 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)
if (e is string)
{ {
// We use this to remove anything pushed by luaL_where // We use this to remove anything pushed by luaL_where
int oldTop = KopiLua.Lua.lua_gettop(luaState); int oldTop = LuaDLL.lua_gettop(luaState);
// Stack frame #1 is our C# wrapper, so not very interesting to the user // Stack frame #1 is our C# wrapper, so not very interesting to the user
// Stack frame #2 must be the lua code that called us, so that's what we want to use // 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); LuaDLL.luaL_where(luaState, 1);
object[] curlev = popValues(luaState, oldTop); object[] curlev = popValues(luaState, oldTop);
// Debug.WriteLine(curlev);
// Determine the position in the script where the exception was triggered
string errLocation = "";
if (curlev.Length > 0) if (curlev.Length > 0)
e = curlev[0].ToString() + e; errLocation = curlev[0].ToString();
string message = e as string;
if (message != null)
{
// Wrap Lua error (just a string) and store the error location
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); push(luaState, e);
KopiLua.Lua.lua_error(luaState); 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
{ {
Assembly assembly=Assembly.LoadWithPartialName(assemblyName); string assemblyName=LuaDLL.lua_tostring(luaState,1);
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 assembly = Assembly.LoadWithPartialName(assemblyName);
if (assembly == null) }
assembly = Assembly.Load(AssemblyName.GetAssemblyName(assemblyName)); catch (BadImageFormatException)
{
// The assemblyName was invalid. It is most likely a path.
} }
catch (Exception)
if (assembly == null)
{ {
// ignore - it might not even be a filename assembly = Assembly.Load(AssemblyName.GetAssemblyName(assemblyName));
} }
if(assembly!=null && !assemblies.Contains(assembly)) if (assembly != null && !assemblies.Contains(assembly))
{
assemblies.Add(assembly); assemblies.Add(assembly);
}
} }
catch(Exception e) catch(Exception e)
{ {
throwError(luaState,e); throwError(luaState,e);
} }
return 0; return 0;
} }
...@@ -228,14 +248,14 @@ namespace LuaInterface ...@@ -228,14 +248,14 @@ namespace LuaInterface
* 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;
} }
/* /*
...@@ -243,12 +263,12 @@ namespace LuaInterface ...@@ -243,12 +263,12 @@ namespace LuaInterface
* 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);
...@@ -258,21 +278,20 @@ namespace LuaInterface ...@@ -258,21 +278,20 @@ namespace LuaInterface
// 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 + "'");
...@@ -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,13 +424,13 @@ namespace LuaInterface ...@@ -404,13 +424,13 @@ 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;
} }
...@@ -418,31 +438,30 @@ namespace LuaInterface ...@@ -418,31 +438,30 @@ namespace LuaInterface
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);
...@@ -560,7 +573,7 @@ namespace LuaInterface ...@@ -560,7 +573,7 @@ namespace LuaInterface
// 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;
...@@ -568,57 +581,42 @@ namespace LuaInterface ...@@ -568,57 +581,42 @@ namespace LuaInterface
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,7 +735,7 @@ namespace LuaInterface ...@@ -737,7 +735,7 @@ 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();
} }
} }
...@@ -750,6 +748,7 @@ namespace LuaInterface ...@@ -750,6 +748,7 @@ namespace LuaInterface
{ {
// 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 else
...@@ -759,34 +758,33 @@ namespace LuaInterface ...@@ -759,34 +758,33 @@ namespace LuaInterface
/* /*
* 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)
......
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