Commit d7bb0c93 authored by Megax's avatar Megax
Browse files

* Mar csak egy falj nincs atalakitva. Ha az is meglesz (vagy kozben) akkor a...

* Mar csak egy falj nincs atalakitva. Ha az is meglesz (vagy kozben) akkor a fajlok kimeneti helyet is modositom + hozzadom azokat az exeket amik a luainterface-hez voltak.
parent bbf63a7e
...@@ -26,10 +26,13 @@ ...@@ -26,10 +26,13 @@
using System; using System;
using System.Reflection; using System.Reflection;
using System.Collections.Generic; using System.Collections.Generic;
using LuaInterface.Method;
using LuaInterface.Extensions; using LuaInterface.Extensions;
namespace LuaInterface namespace LuaInterface
{ {
using LuaCore = KopiLua.Lua;
/* /*
* Type checking and conversion functions. * Type checking and conversion functions.
* *
...@@ -84,9 +87,9 @@ namespace LuaInterface ...@@ -84,9 +87,9 @@ namespace LuaInterface
return extractValues.ContainsKey(runtimeHandleValue) ? extractValues[runtimeHandleValue] : extractNetObject; return extractValues.ContainsKey(runtimeHandleValue) ? extractValues[runtimeHandleValue] : extractNetObject;
} }
internal ExtractValue checkType(KopiLua.Lua.lua_State luaState, int stackPos, Type paramType) internal ExtractValue checkType(LuaCore.lua_State luaState, int stackPos, Type paramType)
{ {
var luatype = KopiLua.Lua.lua_type(luaState, stackPos).ToLuaTypes(); var luatype = LuaCore.lua_type(luaState, stackPos).ToLuaTypes();
if(paramType.IsByRef) if(paramType.IsByRef)
paramType = paramType.GetElementType(); paramType = paramType.GetElementType();
...@@ -120,17 +123,17 @@ namespace LuaInterface ...@@ -120,17 +123,17 @@ namespace LuaInterface
//;//an unsupported type was encountered //;//an unsupported type was encountered
} }
if(KopiLua.Lua.lua_isnumber(luaState, stackPos).ToBoolean()) if(LuaCore.lua_isnumber(luaState, stackPos).ToBoolean())
return extractValues[runtimeHandleValue]; return extractValues[runtimeHandleValue];
if(paramType == typeof(bool)) if(paramType == typeof(bool))
{ {
if(KopiLua.Lua.lua_isboolean(luaState, stackPos)) if(LuaCore.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(LuaCore.lua_isstring(luaState, stackPos).ToBoolean())
return extractValues[runtimeHandleValue]; return extractValues[runtimeHandleValue];
else if(luatype == LuaTypes.Nil) else if(luatype == LuaTypes.Nil)
return extractNetObject; // kevinh - silently convert nil to a null string pointer return extractNetObject; // kevinh - silently convert nil to a null string pointer
...@@ -159,12 +162,12 @@ namespace LuaInterface ...@@ -159,12 +162,12 @@ namespace LuaInterface
// 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).ToLuaTypes() == LuaTypes.Table) else if(LuaCore.lua_type(luaState, stackPos).ToLuaTypes() == LuaTypes.Table)
{ {
if(KopiLua.Lua.luaL_getmetafield(luaState, stackPos, "__index").ToBoolean()) if(LuaCore.luaL_getmetafield(luaState, stackPos, "__index").ToBoolean())
{ {
object obj = translator.getNetObject(luaState, -1); object obj = translator.getNetObject(luaState, -1);
KopiLua.Lua.lua_settop(luaState, -2); LuaCore.lua_settop(luaState, -2);
if(!obj.IsNull() && paramType.IsAssignableFrom(obj.GetType())) if(!obj.IsNull() && paramType.IsAssignableFrom(obj.GetType()))
return extractNetObject; return extractNetObject;
} }
...@@ -186,156 +189,156 @@ namespace LuaInterface ...@@ -186,156 +189,156 @@ 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(LuaCore.lua_State luaState, int stackPos)
{ {
sbyte retVal = (sbyte)KopiLua.Lua.lua_tonumber(luaState, stackPos); sbyte retVal = (sbyte)LuaCore.lua_tonumber(luaState, stackPos);
if(retVal == 0 && !KopiLua.Lua.lua_isnumber(luaState, stackPos).ToBoolean()) if(retVal == 0 && !LuaCore.lua_isnumber(luaState, stackPos).ToBoolean())
return null; return null;
return retVal; return retVal;
} }
private object getAsByte(KopiLua.Lua.lua_State luaState, int stackPos) private object getAsByte(LuaCore.lua_State luaState, int stackPos)
{ {
byte retVal = (byte)KopiLua.Lua.lua_tonumber(luaState, stackPos); byte retVal = (byte)LuaCore.lua_tonumber(luaState, stackPos);
if(retVal == 0 && !KopiLua.Lua.lua_isnumber(luaState, stackPos).ToBoolean()) if(retVal == 0 && !LuaCore.lua_isnumber(luaState, stackPos).ToBoolean())
return null; return null;
return retVal; return retVal;
} }
private object getAsShort(KopiLua.Lua.lua_State luaState, int stackPos) private object getAsShort(LuaCore.lua_State luaState, int stackPos)
{ {
short retVal = (short)KopiLua.Lua.lua_tonumber(luaState, stackPos); short retVal = (short)LuaCore.lua_tonumber(luaState, stackPos);
if(retVal == 0 && !KopiLua.Lua.lua_isnumber(luaState, stackPos).ToBoolean()) if(retVal == 0 && !LuaCore.lua_isnumber(luaState, stackPos).ToBoolean())
return null; return null;
return retVal; return retVal;
} }
private object getAsUshort(KopiLua.Lua.lua_State luaState, int stackPos) private object getAsUshort(LuaCore.lua_State luaState, int stackPos)
{ {
ushort retVal = (ushort)KopiLua.Lua.lua_tonumber(luaState, stackPos); ushort retVal = (ushort)LuaCore.lua_tonumber(luaState, stackPos);
if(retVal == 0 && !KopiLua.Lua.lua_isnumber(luaState, stackPos).ToBoolean()) if(retVal == 0 && !LuaCore.lua_isnumber(luaState, stackPos).ToBoolean())
return null; return null;
return retVal; return retVal;
} }
private object getAsInt(KopiLua.Lua.lua_State luaState, int stackPos) private object getAsInt(LuaCore.lua_State luaState, int stackPos)
{ {
int retVal = (int)KopiLua.Lua.lua_tonumber(luaState, stackPos); int retVal = (int)LuaCore.lua_tonumber(luaState, stackPos);
if(retVal == 0 && !KopiLua.Lua.lua_isnumber(luaState, stackPos).ToBoolean()) if(retVal == 0 && !LuaCore.lua_isnumber(luaState, stackPos).ToBoolean())
return null; return null;
return retVal; return retVal;
} }
private object getAsUint(KopiLua.Lua.lua_State luaState, int stackPos) private object getAsUint(LuaCore.lua_State luaState, int stackPos)
{ {
uint retVal = (uint)KopiLua.Lua.lua_tonumber(luaState, stackPos); uint retVal = (uint)LuaCore.lua_tonumber(luaState, stackPos);
if(retVal == 0 && !KopiLua.Lua.lua_isnumber(luaState, stackPos).ToBoolean()) if(retVal == 0 && !LuaCore.lua_isnumber(luaState, stackPos).ToBoolean())
return null; return null;
return retVal; return retVal;
} }
private object getAsLong(KopiLua.Lua.lua_State luaState, int stackPos) private object getAsLong(LuaCore.lua_State luaState, int stackPos)
{ {
long retVal = (long)KopiLua.Lua.lua_tonumber(luaState, stackPos); long retVal = (long)LuaCore.lua_tonumber(luaState, stackPos);
if(retVal == 0 && !KopiLua.Lua.lua_isnumber(luaState, stackPos).ToBoolean()) if(retVal == 0 && !LuaCore.lua_isnumber(luaState, stackPos).ToBoolean())
return null; return null;
return retVal; return retVal;
} }
private object getAsUlong(KopiLua.Lua.lua_State luaState, int stackPos) private object getAsUlong(LuaCore.lua_State luaState, int stackPos)
{ {
ulong retVal = (ulong)KopiLua.Lua.lua_tonumber(luaState, stackPos); ulong retVal = (ulong)LuaCore.lua_tonumber(luaState, stackPos);
if(retVal == 0 && !KopiLua.Lua.lua_isnumber(luaState, stackPos).ToBoolean()) if(retVal == 0 && !LuaCore.lua_isnumber(luaState, stackPos).ToBoolean())
return null; return null;
return retVal; return retVal;
} }
private object getAsDouble(KopiLua.Lua.lua_State luaState, int stackPos) private object getAsDouble(LuaCore.lua_State luaState, int stackPos)
{ {
double retVal = KopiLua.Lua.lua_tonumber(luaState, stackPos); double retVal = LuaCore.lua_tonumber(luaState, stackPos);
if(retVal == 0 && !KopiLua.Lua.lua_isnumber(luaState, stackPos).ToBoolean()) if(retVal == 0 && !LuaCore.lua_isnumber(luaState, stackPos).ToBoolean())
return null; return null;
return retVal; return retVal;
} }
private object getAsChar(KopiLua.Lua.lua_State luaState, int stackPos) private object getAsChar(LuaCore.lua_State luaState, int stackPos)
{ {
char retVal = (char)KopiLua.Lua.lua_tonumber(luaState, stackPos); char retVal = (char)LuaCore.lua_tonumber(luaState, stackPos);
if(retVal == 0 && !KopiLua.Lua.lua_isnumber(luaState, stackPos).ToBoolean()) if(retVal == 0 && !LuaCore.lua_isnumber(luaState, stackPos).ToBoolean())
return null; return null;
return retVal; return retVal;
} }
private object getAsFloat(KopiLua.Lua.lua_State luaState, int stackPos) private object getAsFloat(LuaCore.lua_State luaState, int stackPos)
{ {
float retVal = (float)KopiLua.Lua.lua_tonumber(luaState, stackPos); float retVal = (float)LuaCore.lua_tonumber(luaState, stackPos);
if(retVal == 0 && !KopiLua.Lua.lua_isnumber(luaState, stackPos).ToBoolean()) if(retVal == 0 && !LuaCore.lua_isnumber(luaState, stackPos).ToBoolean())
return null; return null;
return retVal; return retVal;
} }
private object getAsDecimal(KopiLua.Lua.lua_State luaState, int stackPos) private object getAsDecimal(LuaCore.lua_State luaState, int stackPos)
{ {
decimal retVal = (decimal)KopiLua.Lua.lua_tonumber(luaState, stackPos); decimal retVal = (decimal)LuaCore.lua_tonumber(luaState, stackPos);
if(retVal == 0 && !KopiLua.Lua.lua_isnumber(luaState, stackPos).ToBoolean()) if(retVal == 0 && !LuaCore.lua_isnumber(luaState, stackPos).ToBoolean())
return null; return null;
return retVal; return retVal;
} }
private object getAsBoolean(KopiLua.Lua.lua_State luaState, int stackPos) private object getAsBoolean(LuaCore.lua_State luaState, int stackPos)
{ {
return KopiLua.Lua.lua_toboolean(luaState, stackPos); return LuaCore.lua_toboolean(luaState, stackPos);
} }
private object getAsString(KopiLua.Lua.lua_State luaState, int stackPos) private object getAsString(LuaCore.lua_State luaState, int stackPos)
{ {
string retVal = KopiLua.Lua.lua_tostring(luaState, stackPos).ToString(); string retVal = LuaCore.lua_tostring(luaState, stackPos).ToString();
if(retVal == string.Empty && !KopiLua.Lua.lua_isstring(luaState, stackPos).ToBoolean()) if(retVal == string.Empty && !LuaCore.lua_isstring(luaState, stackPos).ToBoolean())
return null; return null;
return retVal; return retVal;
} }
private object getAsTable(KopiLua.Lua.lua_State luaState, int stackPos) private object getAsTable(LuaCore.lua_State 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(LuaCore.lua_State 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(LuaCore.lua_State 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(LuaCore.lua_State luaState, int stackPos)
{ {
if(KopiLua.Lua.lua_type(luaState, stackPos).ToLuaTypes() == LuaTypes.Table) if(LuaCore.lua_type(luaState, stackPos).ToLuaTypes() == LuaTypes.Table)
{ {
if(KopiLua.Lua.luaL_getmetafield(luaState, stackPos, "__index").ToBoolean()) if(LuaCore.luaL_getmetafield(luaState, stackPos, "__index").ToBoolean())
{ {
if(LuaLib.luaL_checkmetatable(luaState, -1)) if(LuaLib.luaL_checkmetatable(luaState, -1))
{ {
KopiLua.Lua.lua_insert(luaState, stackPos); LuaCore.lua_insert(luaState, stackPos);
KopiLua.Lua.lua_remove(luaState, stackPos+1); LuaCore.lua_remove(luaState, stackPos+1);
} }
else else
KopiLua.Lua.lua_settop(luaState, -2); LuaCore.lua_settop(luaState, -2);
} }
} }
...@@ -343,22 +346,22 @@ namespace LuaInterface ...@@ -343,22 +346,22 @@ namespace LuaInterface
return obj; return obj;
} }
public object getAsNetObject(KopiLua.Lua.lua_State luaState, int stackPos) public object getAsNetObject(LuaCore.lua_State luaState, int stackPos)
{ {
object obj = translator.getNetObject(luaState, stackPos); object obj = translator.getNetObject(luaState, stackPos);
if(obj.IsNull() && KopiLua.Lua.lua_type(luaState, stackPos).ToLuaTypes() == LuaTypes.Table) if(obj.IsNull() && LuaCore.lua_type(luaState, stackPos).ToLuaTypes() == LuaTypes.Table)
{ {
if(KopiLua.Lua.luaL_getmetafield(luaState, stackPos, "__index").ToBoolean()) if(LuaCore.luaL_getmetafield(luaState, stackPos, "__index").ToBoolean())
{ {
if(LuaLib.luaL_checkmetatable(luaState, -1)) if(LuaLib.luaL_checkmetatable(luaState, -1))
{ {
KopiLua.Lua.lua_insert(luaState, stackPos); LuaCore.lua_insert(luaState, stackPos);
KopiLua.Lua.lua_remove(luaState, stackPos+1); LuaCore.lua_remove(luaState, stackPos+1);
obj = translator.getNetObject(luaState, stackPos); obj = translator.getNetObject(luaState, stackPos);
} }
else else
KopiLua.Lua.lua_settop(luaState, -2); LuaCore.lua_settop(luaState, -2);
} }
} }
......
...@@ -29,6 +29,7 @@ using System.Reflection; ...@@ -29,6 +29,7 @@ using System.Reflection;
using System.Reflection.Emit; using System.Reflection.Emit;
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using LuaInterface.Method;
namespace LuaInterface namespace LuaInterface
{ {
......
...@@ -31,10 +31,14 @@ using System.Collections; ...@@ -31,10 +31,14 @@ using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.Collections.Specialized; using System.Collections.Specialized;
using LuaInterface.Event; using LuaInterface.Event;
using LuaInterface.Method;
using LuaInterface.Exceptions; using LuaInterface.Exceptions;
using LuaInterface.Extensions;
namespace LuaInterface namespace LuaInterface
{ {
using LuaCore = KopiLua.Lua;
/* /*
* Main class of LuaInterface * Main class of LuaInterface
* Object-oriented wrapper to Lua API * Object-oriented wrapper to Lua API
...@@ -49,115 +53,162 @@ namespace LuaInterface ...@@ -49,115 +53,162 @@ namespace LuaInterface
[CLSCompliant(true)] [CLSCompliant(true)]
public class Lua : IDisposable public class Lua : IDisposable
{ {
static string init_luanet = #region lua debug functions
"local metatable = {} \n"+ /// <summary>
"local import_type = luanet.import_type \n"+ /// Event that is raised when an exception occures during a hook call.
"local load_assembly = luanet.load_assembly \n"+ /// </summary>
" \n"+ /// <author>Reinhard Ostermeier</author>
"-- Lookup a .NET identifier component. \n"+ public event EventHandler<HookExceptionEventArgs> HookException;
"function metatable:__index(key) -- key is e.g. \"Form\" \n"+ /// <summary>
" -- Get the fully-qualified name, e.g. \"System.Windows.Forms.Form\" \n"+ /// Event when lua hook callback is called
" local fqn = ((rawget(self,\".fqn\") and rawget(self,\".fqn\") .. \n"+ /// </summary>
" \".\") or \"\") .. key \n"+ /// <remarks>
" \n"+ /// Is only raised if SetDebugHook is called before.
" -- Try to find either a luanet function or a CLR type \n"+ /// </remarks>
" local obj = rawget(luanet,key) or import_type(fqn) \n"+ /// <author>Reinhard Ostermeier</author>
" \n"+ public event EventHandler<DebugHookEventArgs> DebugHook;
" -- If key is neither a luanet function or a CLR type, then it is simply \n"+ /// <summary>
" -- an identifier component. \n"+ /// lua hook calback delegate
" if obj == nil then \n"+ /// </summary>
" -- It might be an assembly, so we load it too. \n"+ /// <author>Reinhard Ostermeier</author>
" load_assembly(fqn) \n"+ private LuaCore.lua_Hook hookCallback = null;
" obj = { [\".fqn\"] = fqn } \n"+ #endregion
" setmetatable(obj, metatable) \n"+ #region Globals auto-complete
" end \n"+ private readonly List<string> globals = new List<string>();
" \n"+ private bool globalsSorted;
" -- Cache this lookup \n"+ #endregion
" rawset(self, key, obj) \n"+ private /*readonly */ LuaCore.lua_State luaState;
" return obj \n"+ /// <summary>
"end \n"+ /// True while a script is being executed
" \n"+ /// </summary>
"-- A non-type has been called; e.g. foo = System.Foo() \n"+ public bool IsExecuting { get { return executing; } }
"function metatable:__call(...) \n"+ private LuaCore.lua_CFunction panicCallback;
" error(\"No such type: \" .. rawget(self,\".fqn\"), 2) \n"+
"end \n"+
" \n"+
"-- This is the root of the .NET namespace \n"+
"luanet[\".fqn\"] = false \n"+
"setmetatable(luanet, metatable) \n"+
" \n"+
"-- Preload the mscorlib assembly \n"+
"luanet.load_assembly(\"mscorlib\") \n";
private /*readonly */ KopiLua.Lua.lua_State luaState;
private ObjectTranslator translator; private ObjectTranslator translator;
private KopiLua.Lua.lua_CFunction panicCallback;
/// <summary> /// <summary>
/// Used to ensure multiple .net threads all get serialized by this single lock for access to the lua stack/objects /// Used to ensure multiple .net threads all get serialized by this single lock for access to the lua stack/objects
/// </summary> /// </summary>
private object luaLock = new object(); private object luaLock = new object();
private bool _StatePassed;
private bool executing;
static string init_luanet =
"local metatable = {} \n" +
"local import_type = luanet.import_type \n" +
"local load_assembly = luanet.load_assembly \n" +
" \n" +
"-- Lookup a .NET identifier component. \n" +
"function metatable:__index(key) -- key is e.g. \"Form\" \n" +
" -- Get the fully-qualified name, e.g. \"System.Windows.Forms.Form\" \n" +
" local fqn = ((rawget(self, \".fqn\") and rawget(self, \".fqn\") .. \n" +
" \".\") or \"\") .. key \n" +
" \n" +
" -- Try to find either a luanet function or a CLR type \n" +
" local obj = rawget(luanet, key) or import_type(fqn) \n" +
" \n" +
" -- If key is neither a luanet function or a CLR type, then it is simply \n" +
" -- an identifier component. \n" +
" if obj == nil then \n" +
" -- It might be an assembly, so we load it too. \n" +
" load_assembly(fqn) \n" +
" obj = { [\".fqn\"] = fqn } \n" +
" setmetatable(obj, metatable) \n" +
" end \n" +
" \n" +
" -- Cache this lookup \n" +
" rawset(self, key, obj) \n" +
" return obj \n" +
"end \n" +
" \n" +
"-- A non-type has been called; e.g. foo = System.Foo() \n" +
"function metatable:__call(...) \n" +
" error(\"No such type: \" .. rawget(self, \".fqn\"), 2) \n" +
"end \n" +
" \n" +
"-- This is the root of the .NET namespace \n" +
"luanet[\".fqn\"] = false \n" +
"setmetatable(luanet, metatable) \n" +
" \n" +
"-- Preload the mscorlib assembly \n" +
"luanet.load_assembly(\"mscorlib\") \n";
#region Globals auto-complete
/// <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;
}
}
#endregion
public Lua() public Lua()
{ {
luaState = KopiLua.Lua.luaL_newstate(); // steffenj: Lua 5.1.1 API change (lua_open is gone) luaState = LuaCore.luaL_newstate(); // steffenj: Lua 5.1.1 API change (lua_open is gone)
//KopiLua.Lua.luaopen_base(luaState); // steffenj: luaopen_* no longer used //LuaCore.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) LuaCore.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"); LuaCore.lua_pushstring(luaState, "LUAINTERFACE LOADED");
KopiLua.Lua.lua_pushboolean(luaState, 1); LuaCore.lua_pushboolean(luaState, 1);
KopiLua.Lua.lua_settable(luaState, (int)PseudoIndex.Registry); LuaCore.lua_settable(luaState, (int)PseudoIndex.Registry);
KopiLua.Lua.lua_newtable(luaState); LuaCore.lua_newtable(luaState);
KopiLua.Lua.lua_setglobal(luaState, "luanet"); LuaCore.lua_setglobal(luaState, "luanet");
KopiLua.Lua.lua_pushvalue(luaState, (int)PseudoIndex.Globals); LuaCore.lua_pushvalue(luaState, (int)PseudoIndex.Globals);
KopiLua.Lua.lua_getglobal(luaState, "luanet"); LuaCore.lua_getglobal(luaState, "luanet");
KopiLua.Lua.lua_pushstring(luaState, "getmetatable"); LuaCore.lua_pushstring(luaState, "getmetatable");
KopiLua.Lua.lua_getglobal(luaState, "getmetatable"); LuaCore.lua_getglobal(luaState, "getmetatable");
KopiLua.Lua.lua_settable(luaState, -3); LuaCore.lua_settable(luaState, -3);
KopiLua.Lua.lua_replace(luaState, (int)PseudoIndex.Globals); LuaCore.lua_replace(luaState, (int)PseudoIndex.Globals);
translator=new ObjectTranslator(this,luaState); translator = new ObjectTranslator(this, luaState);
KopiLua.Lua.lua_replace(luaState, (int)PseudoIndex.Globals); LuaCore.lua_replace(luaState, (int)PseudoIndex.Globals);
LuaLib.luaL_dostring(luaState, Lua.init_luanet); // steffenj: lua_dostring renamed to luaL_dostring LuaLib.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 LuaCore.lua_CFunction(PanicCallback);
KopiLua.Lua.lua_atpanic(luaState, panicCallback); LuaCore.lua_atpanic(luaState, panicCallback);
//KopiLua.Lua.lua_atlock(luaState, lockCallback = new KopiLua.Lua.lua_CFunction(LockCallback)); //LuaCore.lua_atlock(luaState, lockCallback = new LuaCore.lua_CFunction(LockCallback));
//KopiLua.Lua.lua_atunlock(luaState, unlockCallback = new KopiLua.Lua.lua_CFunction(UnlockCallback)); //LuaCore.lua_atunlock(luaState, unlockCallback = new LuaCore.lua_CFunction(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(LuaCore.lua_State luaState)
{ {
KopiLua.Lua.lua_State lState = luaState; LuaCore.lua_State lState = luaState;
KopiLua.Lua.lua_pushstring(lState, "LUAINTERFACE LOADED"); LuaCore.lua_pushstring(lState, "LUAINTERFACE LOADED");
KopiLua.Lua.lua_gettable(lState, (int)PseudoIndex.Registry); LuaCore.lua_gettable(lState, (int)PseudoIndex.Registry);
if(KopiLua.Lua.lua_toboolean(lState,-1).ToBoolean()) if(LuaCore.lua_toboolean(lState, -1).ToBoolean())
{ {
KopiLua.Lua.lua_settop(lState,-2); LuaCore.lua_settop(lState, -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 else
{ {
KopiLua.Lua.lua_settop(lState,-2); LuaCore.lua_settop(lState, -2);
KopiLua.Lua.lua_pushstring(lState, "LUAINTERFACE LOADED"); LuaCore.lua_pushstring(lState, "LUAINTERFACE LOADED");
KopiLua.Lua.lua_pushboolean(lState, 1); LuaCore.lua_pushboolean(lState, 1);
KopiLua.Lua.lua_settable(lState, (int)PseudoIndex.Registry); LuaCore.lua_settable(lState, (int)PseudoIndex.Registry);
this.luaState=lState; this.luaState = lState;
KopiLua.Lua.lua_pushvalue(lState, (int)PseudoIndex.Globals); LuaCore.lua_pushvalue(lState, (int)PseudoIndex.Globals);
KopiLua.Lua.lua_getglobal(lState, "luanet"); LuaCore.lua_getglobal(lState, "luanet");
KopiLua.Lua.lua_pushstring(lState, "getmetatable"); LuaCore.lua_pushstring(lState, "getmetatable");
KopiLua.Lua.lua_getglobal(lState, "getmetatable"); LuaCore.lua_getglobal(lState, "getmetatable");
KopiLua.Lua.lua_settable(lState, -3); LuaCore.lua_settable(lState, -3);
KopiLua.Lua.lua_replace(lState, (int)PseudoIndex.Globals); LuaCore.lua_replace(lState, (int)PseudoIndex.Globals);
translator=new ObjectTranslator(this, this.luaState); translator = new ObjectTranslator(this, this.luaState);
KopiLua.Lua.lua_replace(lState, (int)PseudoIndex.Globals); LuaCore.lua_replace(lState, (int)PseudoIndex.Globals);
LuaLib.luaL_dostring(lState, Lua.init_luanet); // steffenj: lua_dostring renamed to luaL_dostring LuaLib.luaL_dostring(lState, Lua.init_luanet); // steffenj: lua_dostring renamed to luaL_dostring
} }
...@@ -167,157 +218,151 @@ namespace LuaInterface ...@@ -167,157 +218,151 @@ namespace LuaInterface
/// <summary> /// <summary>
/// Called for each lua_lock call /// Called for each lua_lock call
/// </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(LuaCore.lua_State luaState)
{ {
// Monitor.Enter(luaLock); // Monitor.Enter(luaLock);
return 0; return 0;
} }*/
/// <summary> /// <summary>
/// Called for each lua_unlock call /// Called for each lua_unlock call
/// </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(LuaCore.lua_State luaState)
{ {
// Monitor.Exit(luaLock); // Monitor.Exit(luaLock);
return 0; return 0;
} }*/
public void Close() public void Close()
{ {
if (_StatePassed) if(_StatePassed)
return; return;
////// if (luaState != KopiLua.Lua.lua_State.Zero) ////// if(luaState != LuaCore.lua_State.Zero)
if (luaState != null) if(!luaState.IsNull())
KopiLua.Lua.lua_close(luaState); LuaCore.lua_close(luaState);
//luaState = KopiLua.Lua.lua_State.Zero; <- suggested by Christopher Cebulski http://luaforge.net/forum/forum.php?thread_id=44593&forum_id=146 //luaState = LuaCore.lua_State.Zero; <- suggested by Christopher Cebulski http://luaforge.net/forum/forum.php?thread_id = 44593&forum_id = 146
} }
static int PanicCallback(KopiLua.Lua.lua_State luaState) static int PanicCallback(LuaCore.lua_State luaState)
{ {
// string desc = KopiLua.Lua.lua_tostring(luaState, 1); // string desc = LuaCore.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})", LuaCore.lua_tostring(luaState, -1));
// lua_tostring(L, -1); // lua_tostring(L, -1);
throw new LuaException(reason); throw new LuaException(reason);
} }
/// <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> /// <exception cref = "LuaScriptException">Thrown if the script caused an exception</exception>
void ThrowExceptionFromError(int oldTop) private void ThrowExceptionFromError(int oldTop)
{ {
object err = translator.getObject(luaState, -1); object err = translator.getObject(luaState, -1);
KopiLua.Lua.lua_settop(luaState, oldTop); LuaCore.lua_settop(luaState, oldTop);
// A pre-wrapped exception - just rethrow it (stack trace of InnerException will be preserved) // A pre-wrapped exception - just rethrow it (stack trace of InnerException will be preserved)
LuaScriptException luaEx = err as LuaScriptException; var luaEx = err as LuaScriptException;
if (luaEx != null) throw luaEx;
// A non-wrapped Lua error (best interpreted as a string) - wrap it and throw it if(!luaEx.IsNull())
if (err == null) err = "Unknown Lua Error"; throw luaEx;
throw new LuaScriptException(err.ToString(), "");
}
// A non-wrapped Lua error (best interpreted as a string) - wrap it and throw it
if(err.IsNull())
err = "Unknown Lua Error";
throw new LuaScriptException(err.ToString(), string.Empty);
}
/// <summary> /// <summary>
/// Convert C# exceptions into Lua errors /// Convert C# exceptions into Lua errors
/// </summary> /// </summary>
/// <returns>num of things on stack</returns> /// <returns>num of things on stack</returns>
/// <param name="e">null for no pending exception</param> /// <param name = "e">null for no pending exception</param>
internal int SetPendingException(Exception e) internal int SetPendingException(Exception e)
{ {
Exception caughtExcept = e; var caughtExcept = e;
if (caughtExcept != null) if(!caughtExcept.IsNull())
{ {
translator.throwError(luaState, caughtExcept); translator.throwError(luaState, caughtExcept);
KopiLua.Lua.lua_pushnil(luaState); LuaCore.lua_pushnil(luaState);
return 1; return 1;
} }
else else
return 0; return 0;
} }
private bool executing;
/// <summary>
/// True while a script is being executed
/// </summary>
public bool IsExecuting { get { return executing; } }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
/// <param name="chunk"></param> /// <param name = "chunk"></param>
/// <param name="name"></param> /// <param name = "name"></param>
/// <returns></returns> /// <returns></returns>
public LuaFunction LoadString(string chunk, string name) public LuaFunction LoadString(string chunk, string name)
{ {
int oldTop = KopiLua.Lua.lua_gettop(luaState); int oldTop = LuaCore.lua_gettop(luaState);
executing = true; executing = true;
try try
{ {
if (LuaLib.luaL_loadbuffer(luaState, chunk, name) != 0) if(LuaLib.luaL_loadbuffer(luaState, chunk, name) != 0)
ThrowExceptionFromError(oldTop); ThrowExceptionFromError(oldTop);
} }
finally { executing = false; } finally
{
executing = false;
}
LuaFunction result = translator.getFunction(luaState, -1); var result = translator.getFunction(luaState, -1);
translator.popValues(luaState, oldTop); translator.popValues(luaState, oldTop);
return result; return result;
} }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
/// <param name="fileName"></param> /// <param name = "fileName"></param>
/// <returns></returns> /// <returns></returns>
public LuaFunction LoadFile(string fileName) public LuaFunction LoadFile(string fileName)
{ {
int oldTop = KopiLua.Lua.lua_gettop(luaState); int oldTop = LuaCore.lua_gettop(luaState);
if (KopiLua.Lua.luaL_loadfile(luaState, fileName) != 0)
if(LuaCore.luaL_loadfile(luaState, fileName) != 0)
ThrowExceptionFromError(oldTop); ThrowExceptionFromError(oldTop);
LuaFunction result = translator.getFunction(luaState, -1); var result = translator.getFunction(luaState, -1);
translator.popValues(luaState, oldTop); translator.popValues(luaState, oldTop);
return result; return result;
} }
/* /*
* Excutes a Lua chunk and returns all the chunk's return * Excutes a Lua chunk and returns all the chunk's return
* values in an array * values in an array
*/ */
public object[] DoString(string chunk) public object[] DoString(string chunk)
{ {
int oldTop=KopiLua.Lua.lua_gettop(luaState); int oldTop = LuaCore.lua_gettop(luaState);
if (LuaLib.luaL_loadbuffer(luaState, chunk, "chunk") == 0)
if(LuaLib.luaL_loadbuffer(luaState, chunk, "chunk") == 0)
{ {
executing = true; executing = true;
try try
{ {
if (KopiLua.Lua.lua_pcall(luaState, 0, -1, 0) == 0) if(LuaCore.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; } finally
{
executing = false;
}
} }
else else
ThrowExceptionFromError(oldTop); ThrowExceptionFromError(oldTop);
...@@ -328,23 +373,27 @@ namespace LuaInterface ...@@ -328,23 +373,27 @@ namespace LuaInterface
/// <summary> /// <summary>
/// Executes a Lua chnk and returns all the chunk's return values in an array. /// Executes a Lua chnk and returns all the chunk's return values in an array.
/// </summary> /// </summary>
/// <param name="chunk">Chunk to execute</param> /// <param name = "chunk">Chunk to execute</param>
/// <param name="chunkName">Name to associate with the chunk</param> /// <param name = "chunkName">Name to associate with the chunk</param>
/// <returns></returns> /// <returns></returns>
public object[] DoString(string chunk, string chunkName) public object[] DoString(string chunk, string chunkName)
{ {
int oldTop = KopiLua.Lua.lua_gettop(luaState); int oldTop = LuaCore.lua_gettop(luaState);
executing = true; executing = true;
if (LuaLib.luaL_loadbuffer(luaState, chunk, chunkName) == 0)
if(LuaLib.luaL_loadbuffer(luaState, chunk, chunkName) == 0)
{ {
try try
{ {
if (KopiLua.Lua.lua_pcall(luaState, 0, -1, 0) == 0) if(LuaCore.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; } finally
{
executing = false;
}
} }
else else
ThrowExceptionFromError(oldTop); ThrowExceptionFromError(oldTop);
...@@ -358,18 +407,23 @@ namespace LuaInterface ...@@ -358,18 +407,23 @@ namespace LuaInterface
*/ */
public object[] DoFile(string fileName) public object[] DoFile(string fileName)
{ {
int oldTop=KopiLua.Lua.lua_gettop(luaState); int oldTop = LuaCore.lua_gettop(luaState);
if(KopiLua.Lua.luaL_loadfile(luaState,fileName)==0)
if(LuaCore.luaL_loadfile(luaState, fileName) == 0)
{ {
executing = true; executing = true;
try try
{ {
if (KopiLua.Lua.lua_pcall(luaState, 0, -1, 0) == 0) if(LuaCore.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; } finally
{
executing = false;
}
} }
else else
ThrowExceptionFromError(oldTop); ThrowExceptionFromError(oldTop);
...@@ -386,40 +440,44 @@ namespace LuaInterface ...@@ -386,40 +440,44 @@ namespace LuaInterface
{ {
get get
{ {
object returnValue=null; object returnValue = null;
int oldTop=KopiLua.Lua.lua_gettop(luaState); int oldTop = LuaCore.lua_gettop(luaState);
string[] path=fullPath.Split(new char[] { '.' }); string[] path = fullPath.Split(new char[] { '.' });
KopiLua.Lua.lua_getglobal(luaState,path[0]); LuaCore.lua_getglobal(luaState, path[0]);
returnValue=translator.getObject(luaState,-1); returnValue = translator.getObject(luaState, -1);
if(path.Length>1) if(path.Length>1)
{ {
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);
returnValue=getObject(remainingPath); returnValue = getObject(remainingPath);
} }
KopiLua.Lua.lua_settop(luaState,oldTop);
LuaCore.lua_settop(luaState, oldTop);
return returnValue; return returnValue;
} }
set set
{ {
int oldTop=KopiLua.Lua.lua_gettop(luaState); int oldTop = LuaCore.lua_gettop(luaState);
string[] path=fullPath.Split(new char[] { '.' }); string[] path = fullPath.Split(new char[] { '.' });
if(path.Length==1)
if(path.Length == 1)
{ {
translator.push(luaState,value); translator.push(luaState, value);
KopiLua.Lua.lua_setglobal(luaState,fullPath); LuaCore.lua_setglobal(luaState, fullPath);
} }
else else
{ {
KopiLua.Lua.lua_getglobal(luaState,path[0]); LuaCore.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);
LuaCore.lua_settop(luaState, oldTop);
// Globals auto-complete // Globals auto-complete
if (value == null) if(value.IsNull())
{ {
// Remove now obsolete entries // Remove now obsolete entries
globals.Remove(fullPath); globals.Remove(fullPath);
...@@ -427,56 +485,34 @@ namespace LuaInterface ...@@ -427,56 +485,34 @@ namespace LuaInterface
else else
{ {
// Add new entries // Add new entries
if (!globals.Contains(fullPath)) if(!globals.Contains(fullPath))
registerGlobal(fullPath, value.GetType(), 0); registerGlobal(fullPath, value.GetType(), 0);
} }
} }
} }
#region Globals auto-complete #region Globals auto-complete
private readonly List<string> globals = new List<string>();
private bool globalsSorted;
/// <summary> /// <summary>
/// An alphabetically sorted list of all globals (objects, methods, etc.) externally added to this Lua instance /// Adds an entry to <see cref = "globals"/> (recursivley handles 2 levels of members)
/// </summary> /// </summary>
/// <remarks>Members of globals are also listed. The formatting is optimized for text input auto-completion.</remarks> /// <param name = "path">The index accessor path ot the entry</param>
public IEnumerable<string> Globals /// <param name = "type">The type of the entry</param>
{ /// <param name = "recursionCounter">How deep have we gone with recursion?</param>
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) private void registerGlobal(string path, Type type, int recursionCounter)
{ {
// If the type is a global method, list it directly // If the type is a global method, list it directly
if (type == typeof(KopiLua.Lua.lua_CFunction)) if(type == typeof(LuaCore.lua_CFunction))
{ {
// Format for easy method invocation // Format for easy method invocation
globals.Add(path + "("); globals.Add(path + "(");
} }
// If the type is a class or an interface and recursion hasn't been running too long, list the members // 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) else if((type.IsClass || type.IsInterface) && type != typeof(string) && recursionCounter < 2)
{ {
#region Methods #region Methods
foreach (MethodInfo method in type.GetMethods(BindingFlags.Public | BindingFlags.Instance)) foreach(var method in type.GetMethods(BindingFlags.Public | BindingFlags.Instance))
{ {
if ( if(
// Check that the LuaHideAttribute and LuaGlobalAttribute were not applied // Check that the LuaHideAttribute and LuaGlobalAttribute were not applied
(method.GetCustomAttributes(typeof(LuaHideAttribute), false).Length == 0) && (method.GetCustomAttributes(typeof(LuaHideAttribute), false).Length == 0) &&
(method.GetCustomAttributes(typeof(LuaGlobalAttribute), false).Length == 0) && (method.GetCustomAttributes(typeof(LuaGlobalAttribute), false).Length == 0) &&
...@@ -491,16 +527,17 @@ namespace LuaInterface ...@@ -491,16 +527,17 @@ namespace LuaInterface
{ {
// Format for easy method invocation // Format for easy method invocation
string command = path + ":" + method.Name + "("; string command = path + ":" + method.Name + "(";
if (method.GetParameters().Length == 0) command += ")";
if(method.GetParameters().Length == 0) command += ")";
globals.Add(command); globals.Add(command);
} }
} }
#endregion #endregion
#region Fields #region Fields
foreach (FieldInfo field in type.GetFields(BindingFlags.Public | BindingFlags.Instance)) foreach(var field in type.GetFields(BindingFlags.Public | BindingFlags.Instance))
{ {
if ( if(
// Check that the LuaHideAttribute and LuaGlobalAttribute were not applied // Check that the LuaHideAttribute and LuaGlobalAttribute were not applied
(field.GetCustomAttributes(typeof(LuaHideAttribute), false).Length == 0) && (field.GetCustomAttributes(typeof(LuaHideAttribute), false).Length == 0) &&
(field.GetCustomAttributes(typeof(LuaGlobalAttribute), false).Length == 0)) (field.GetCustomAttributes(typeof(LuaGlobalAttribute), false).Length == 0))
...@@ -512,9 +549,9 @@ namespace LuaInterface ...@@ -512,9 +549,9 @@ namespace LuaInterface
#endregion #endregion
#region Properties #region Properties
foreach (PropertyInfo property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance)) foreach(var property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance))
{ {
if ( if(
// Check that the LuaHideAttribute and LuaGlobalAttribute were not applied // Check that the LuaHideAttribute and LuaGlobalAttribute were not applied
(property.GetCustomAttributes(typeof(LuaHideAttribute), false).Length == 0) && (property.GetCustomAttributes(typeof(LuaHideAttribute), false).Length == 0) &&
(property.GetCustomAttributes(typeof(LuaGlobalAttribute), false).Length == 0) (property.GetCustomAttributes(typeof(LuaGlobalAttribute), false).Length == 0)
...@@ -527,8 +564,8 @@ namespace LuaInterface ...@@ -527,8 +564,8 @@ namespace LuaInterface
} }
#endregion #endregion
} }
// Otherwise simply add the element to the list else
else globals.Add(path); globals.Add(path); // Otherwise simply add the element to the list
// List will need to be sorted on next access // List will need to be sorted on next access
globalsSorted = false; globalsSorted = false;
...@@ -541,16 +578,21 @@ namespace LuaInterface ...@@ -541,16 +578,21 @@ namespace LuaInterface
*/ */
internal object getObject(string[] remainingPath) internal object getObject(string[] remainingPath)
{ {
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]); LuaCore.lua_pushstring(luaState, remainingPath[i]);
KopiLua.Lua.lua_gettable(luaState,-2); LuaCore.lua_gettable(luaState, -2);
returnValue=translator.getObject(luaState,-1); returnValue = translator.getObject(luaState, -1);
if(returnValue==null) break;
if(returnValue.IsNull())
break;
} }
return returnValue; return returnValue;
} }
/* /*
* Gets a numeric global variable * Gets a numeric global variable
*/ */
...@@ -558,6 +600,7 @@ namespace LuaInterface ...@@ -558,6 +600,7 @@ namespace LuaInterface
{ {
return (double)this[fullPath]; return (double)this[fullPath];
} }
/* /*
* Gets a string global variable * Gets a string global variable
*/ */
...@@ -565,6 +608,7 @@ namespace LuaInterface ...@@ -565,6 +608,7 @@ namespace LuaInterface
{ {
return (string)this[fullPath]; return (string)this[fullPath];
} }
/* /*
* Gets a table global variable * Gets a table global variable
*/ */
...@@ -572,131 +616,145 @@ namespace LuaInterface ...@@ -572,131 +616,145 @@ namespace LuaInterface
{ {
return (LuaTable)this[fullPath]; return (LuaTable)this[fullPath];
} }
/* /*
* Gets a table global variable as an object implementing * Gets a table global variable as an object implementing
* the interfaceType interface * the interfaceType interface
*/ */
public object GetTable(Type interfaceType, string fullPath) public object GetTable(Type interfaceType, string fullPath)
{ {
return CodeGeneration.Instance.GetClassInstance(interfaceType,GetTable(fullPath)); return CodeGeneration.Instance.GetClassInstance(interfaceType, GetTable(fullPath));
} }
/* /*
* Gets a function global variable * Gets a function global variable
*/ */
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 LuaCore.lua_CFunction ? new LuaFunction((LuaCore.lua_CFunction)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)); //return (obj is LuaCore.lua_CFunction ? new LuaFunction((LuaCore.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
* type delegateType * type delegateType
*/ */
public Delegate GetFunction(Type delegateType,string fullPath) public Delegate GetFunction(Type delegateType, string fullPath)
{ {
return CodeGeneration.Instance.GetDelegate(delegateType,GetFunction(fullPath)); return CodeGeneration.Instance.GetDelegate(delegateType, GetFunction(fullPath));
} }
/* /*
* Calls the object as a function with the provided arguments, * Calls the object as a function with the provided arguments,
* returning the function's returned values inside an array * returning the function's returned values inside an array
*/ */
internal object[] callFunction(object function,object[] args) internal object[] callFunction(object function, object[] args)
{ {
return callFunction(function, args, null); return callFunction(function, args, null);
} }
/* /*
* Calls the object as a function with the provided arguments and * Calls the object as a function with the provided arguments and
* casting returned values to the types in returnTypes before returning * casting returned values to the types in returnTypes before returning
* them in an array * them in an array
*/ */
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 = LuaCore.lua_gettop(luaState);
if(!KopiLua.Lua.lua_checkstack(luaState,args.Length+6).ToBoolean())
if(!LuaCore.lua_checkstack(luaState, args.Length+6).ToBoolean())
throw new LuaException("Lua stack overflow"); throw new LuaException("Lua stack overflow");
translator.push(luaState,function);
if(args!=null) translator.push(luaState, function);
{
nArgs=args.Length; if(!args.IsNull())
for(int i=0;i<args.Length;i++)
{ {
translator.push(luaState,args[i]); nArgs = args.Length;
}
for(int i = 0; i < args.Length; i++)
translator.push(luaState, args[i]);
} }
executing = true; executing = true;
try try
{ {
int error = KopiLua.Lua.lua_pcall(luaState, nArgs, -1, 0); int error = LuaCore.lua_pcall(luaState, nArgs, -1, 0);
if (error != 0) if(error != 0)
ThrowExceptionFromError(oldTop); ThrowExceptionFromError(oldTop);
} }
finally { executing = false; } finally
{
executing = false;
}
if(returnTypes != null) return !returnTypes.IsNull() ? translator.popValues(luaState, oldTop, returnTypes) : translator.popValues(luaState, oldTop);
return translator.popValues(luaState,oldTop,returnTypes);
else
return translator.popValues(luaState, oldTop);
} }
/* /*
* Navigates a table to set the value of one of its fields * Navigates a table to set the value of one of its fields
*/ */
internal void setObject(string[] remainingPath, object val) internal void setObject(string[] remainingPath, object val)
{ {
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]); LuaCore.lua_pushstring(luaState, remainingPath[i]);
KopiLua.Lua.lua_gettable(luaState,-2); LuaCore.lua_gettable(luaState, -2);
} }
KopiLua.Lua.lua_pushstring(luaState,remainingPath[remainingPath.Length-1]);
translator.push(luaState,val); LuaCore.lua_pushstring(luaState, remainingPath[remainingPath.Length-1]);
KopiLua.Lua.lua_settable(luaState,-3); translator.push(luaState, val);
LuaCore.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
* inside an existing table * inside an existing table
*/ */
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 = LuaCore.lua_gettop(luaState);
if(path.Length==1)
if(path.Length == 1)
{ {
KopiLua.Lua.lua_newtable(luaState); LuaCore.lua_newtable(luaState);
KopiLua.Lua.lua_setglobal(luaState,fullPath); LuaCore.lua_setglobal(luaState, fullPath);
} }
else else
{ {
KopiLua.Lua.lua_getglobal(luaState,path[0]); LuaCore.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]); LuaCore.lua_pushstring(luaState, path[i]);
KopiLua.Lua.lua_gettable(luaState,-2); LuaCore.lua_gettable(luaState, -2);
} }
KopiLua.Lua.lua_pushstring(luaState,path[path.Length-1]);
KopiLua.Lua.lua_newtable(luaState); LuaCore.lua_pushstring(luaState, path[path.Length-1]);
KopiLua.Lua.lua_settable(luaState,-3); LuaCore.lua_newtable(luaState);
LuaCore.lua_settable(luaState, -3);
} }
KopiLua.Lua.lua_settop(luaState,oldTop);
LuaCore.lua_settop(luaState, oldTop);
} }
public ListDictionary GetTableDict(LuaTable table) public ListDictionary GetTableDict(LuaTable table)
{ {
ListDictionary dict = new ListDictionary(); var dict = new ListDictionary();
int oldTop = LuaCore.lua_gettop(luaState);
int oldTop = KopiLua.Lua.lua_gettop(luaState);
translator.push(luaState, table); translator.push(luaState, table);
KopiLua.Lua.lua_pushnil(luaState); LuaCore.lua_pushnil(luaState);
while (KopiLua.Lua.lua_next(luaState, -2) != 0)
while(LuaCore.lua_next(luaState, -2) != 0)
{ {
dict[translator.getObject(luaState, -2)] = translator.getObject(luaState, -1); dict[translator.getObject(luaState, -2)] = translator.getObject(luaState, -1);
KopiLua.Lua.lua_settop(luaState, -2); LuaCore.lua_settop(luaState, -2);
} }
KopiLua.Lua.lua_settop(luaState, oldTop);
LuaCore.lua_settop(luaState, oldTop);
return dict; return dict;
} }
...@@ -706,26 +764,19 @@ namespace LuaInterface ...@@ -706,26 +764,19 @@ namespace LuaInterface
*/ */
#region lua debug functions #region lua debug functions
/// <summary>
/// lua hook calback delegate
/// </summary>
/// <author>Reinhard Ostermeier</author>
private KopiLua.Lua.lua_Hook hookCallback = null;
/// <summary> /// <summary>
/// Activates the debug hook /// Activates the debug hook
/// </summary> /// </summary>
/// <param name="mask">Mask</param> /// <param name = "mask">Mask</param>
/// <param name="count">Count</param> /// <param name = "count">Count</param>
/// <returns>see lua docs. -1 if hook is already set</returns> /// <returns>see lua docs. -1 if hook is already set</returns>
/// <author>Reinhard Ostermeier</author> /// <author>Reinhard Ostermeier</author>
/*public int SetDebugHook(EventMasks mask, int count) /*public int SetDebugHook(EventMasks mask, int count)
{ {
if (hookCallback == null) if(hookCallback.IsNull())
{ {
hookCallback = new KopiLua.Lua.lua_Hook(DebugHookCallback); hookCallback = new LuaCore.lua_Hook(DebugHookCallback);
return KopiLua.Lua.lua_sethook(luaState, hookCallback, (int)mask, count); return LuaCore.lua_sethook(luaState, hookCallback, (int)mask, count);
} }
return -1; return -1;
}*/ }*/
...@@ -738,7 +789,7 @@ namespace LuaInterface ...@@ -738,7 +789,7 @@ namespace LuaInterface
public int RemoveDebugHook() public int RemoveDebugHook()
{ {
hookCallback = null; hookCallback = null;
return KopiLua.Lua.lua_sethook(luaState, null, 0, 0); return LuaCore.lua_sethook(luaState, null, 0, 0);
} }
/// <summary> /// <summary>
...@@ -748,7 +799,7 @@ namespace LuaInterface ...@@ -748,7 +799,7 @@ namespace LuaInterface
/// <author>Reinhard Ostermeier</author> /// <author>Reinhard Ostermeier</author>
public EventMasks GetHookMask() public EventMasks GetHookMask()
{ {
return (EventMasks)KopiLua.Lua.lua_gethookmask(luaState); return (EventMasks)LuaCore.lua_gethookmask(luaState);
} }
/// <summary> /// <summary>
...@@ -758,24 +809,24 @@ namespace LuaInterface ...@@ -758,24 +809,24 @@ namespace LuaInterface
/// <author>Reinhard Ostermeier</author> /// <author>Reinhard Ostermeier</author>
public int GetHookCount() public int GetHookCount()
{ {
return KopiLua.Lua.lua_gethookcount(luaState); return LuaCore.lua_gethookcount(luaState);
} }
/// <summary> /// <summary>
/// Gets the stack entry on a given level /// Gets the stack entry on a given level
/// </summary> /// </summary>
/// <param name="level">level</param> /// <param name = "level">level</param>
/// <param name="luaDebug">lua debug structure</param> /// <param name = "luaDebug">lua debug structure</param>
/// <returns>Returns true if level was allowed, false if level was invalid.</returns> /// <returns>Returns true if level was allowed, false if level was invalid.</returns>
/// <author>Reinhard Ostermeier</author> /// <author>Reinhard Ostermeier</author>
/*public bool GetStack(int level, out LuaDebug luaDebug) /*public bool GetStack(int level, out LuaDebug luaDebug)
{ {
luaDebug = new LuaDebug(); luaDebug = new LuaDebug();
KopiLua.Lua.lua_State ld = System.Runtime.InteropServices.Marshal.AllocHGlobal(System.Runtime.InteropServices.Marshal.SizeOf(luaDebug)); LuaCore.lua_State ld = System.Runtime.InteropServices.Marshal.AllocHGlobal(System.Runtime.InteropServices.Marshal.SizeOf(luaDebug));
System.Runtime.InteropServices.Marshal.StructureToPtr(luaDebug, ld, false); System.Runtime.InteropServices.Marshal.StructureToPtr(luaDebug, ld, false);
try try
{ {
return KopiLua.Lua.lua_getstack(luaState, level, ld) != 0; return LuaCore.lua_getstack(luaState, level, ld) != 0;
} }
finally finally
{ {
...@@ -787,17 +838,17 @@ namespace LuaInterface ...@@ -787,17 +838,17 @@ namespace LuaInterface
/// <summary> /// <summary>
/// Gets info (see lua docs) /// Gets info (see lua docs)
/// </summary> /// </summary>
/// <param name="what">what (see lua docs)</param> /// <param name = "what">what (see lua docs)</param>
/// <param name="luaDebug">lua debug structure</param> /// <param name = "luaDebug">lua debug structure</param>
/// <returns>see lua docs</returns> /// <returns>see lua docs</returns>
/// <author>Reinhard Ostermeier</author> /// <author>Reinhard Ostermeier</author>
/*public int GetInfo(String what, ref LuaDebug luaDebug) /*public int GetInfo(String what, ref LuaDebug luaDebug)
{ {
KopiLua.Lua.lua_State ld = System.Runtime.InteropServices.Marshal.AllocHGlobal(System.Runtime.InteropServices.Marshal.SizeOf(luaDebug)); LuaCore.lua_State ld = System.Runtime.InteropServices.Marshal.AllocHGlobal(System.Runtime.InteropServices.Marshal.SizeOf(luaDebug));
System.Runtime.InteropServices.Marshal.StructureToPtr(luaDebug, ld, false); System.Runtime.InteropServices.Marshal.StructureToPtr(luaDebug, ld, false);
try try
{ {
return KopiLua.Lua.lua_getinfo(luaState, what, ld); return LuaCore.lua_getinfo(luaState, what, ld);
} }
finally finally
{ {
...@@ -809,17 +860,17 @@ namespace LuaInterface ...@@ -809,17 +860,17 @@ namespace LuaInterface
/// <summary> /// <summary>
/// Gets local (see lua docs) /// Gets local (see lua docs)
/// </summary> /// </summary>
/// <param name="luaDebug">lua debug structure</param> /// <param name = "luaDebug">lua debug structure</param>
/// <param name="n">see lua docs</param> /// <param name = "n">see lua docs</param>
/// <returns>see lua docs</returns> /// <returns>see lua docs</returns>
/// <author>Reinhard Ostermeier</author> /// <author>Reinhard Ostermeier</author>
/*public String GetLocal(LuaDebug luaDebug, int n) /*public String GetLocal(LuaDebug luaDebug, int n)
{ {
KopiLua.Lua.lua_State ld = System.Runtime.InteropServices.Marshal.AllocHGlobal(System.Runtime.InteropServices.Marshal.SizeOf(luaDebug)); LuaCore.lua_State ld = System.Runtime.InteropServices.Marshal.AllocHGlobal(System.Runtime.InteropServices.Marshal.SizeOf(luaDebug));
System.Runtime.InteropServices.Marshal.StructureToPtr(luaDebug, ld, false); System.Runtime.InteropServices.Marshal.StructureToPtr(luaDebug, ld, false);
try try
{ {
return KopiLua.Lua.lua_getlocal(luaState, ld, n); return LuaCore.lua_getlocal(luaState, ld, n);
} }
finally finally
{ {
...@@ -830,17 +881,17 @@ namespace LuaInterface ...@@ -830,17 +881,17 @@ namespace LuaInterface
/// <summary> /// <summary>
/// Sets local (see lua docs) /// Sets local (see lua docs)
/// </summary> /// </summary>
/// <param name="luaDebug">lua debug structure</param> /// <param name = "luaDebug">lua debug structure</param>
/// <param name="n">see lua docs</param> /// <param name = "n">see lua docs</param>
/// <returns>see lua docs</returns> /// <returns>see lua docs</returns>
/// <author>Reinhard Ostermeier</author> /// <author>Reinhard Ostermeier</author>
/*public String SetLocal(LuaDebug luaDebug, int n) /*public String SetLocal(LuaDebug luaDebug, int n)
{ {
KopiLua.Lua.lua_State ld = System.Runtime.InteropServices.Marshal.AllocHGlobal(System.Runtime.InteropServices.Marshal.SizeOf(luaDebug)); LuaCore.lua_State ld = System.Runtime.InteropServices.Marshal.AllocHGlobal(System.Runtime.InteropServices.Marshal.SizeOf(luaDebug));
System.Runtime.InteropServices.Marshal.StructureToPtr(luaDebug, ld, false); System.Runtime.InteropServices.Marshal.StructureToPtr(luaDebug, ld, false);
try try
{ {
return KopiLua.Lua.lua_setlocal(luaState, ld, n); return LuaCore.lua_setlocal(luaState, ld, n);
} }
finally finally
{ {
...@@ -851,40 +902,40 @@ namespace LuaInterface ...@@ -851,40 +902,40 @@ namespace LuaInterface
/// <summary> /// <summary>
/// Gets up value (see lua docs) /// Gets up value (see lua docs)
/// </summary> /// </summary>
/// <param name="funcindex">see lua docs</param> /// <param name = "funcindex">see lua docs</param>
/// <param name="n">see lua docs</param> /// <param name = "n">see lua docs</param>
/// <returns>see lua docs</returns> /// <returns>see lua docs</returns>
/// <author>Reinhard Ostermeier</author> /// <author>Reinhard Ostermeier</author>
public String GetUpValue(int funcindex, int n) public string GetUpValue(int funcindex, int n)
{ {
return KopiLua.Lua.lua_getupvalue(luaState, funcindex, n).ToString(); return LuaCore.lua_getupvalue(luaState, funcindex, n).ToString();
} }
/// <summary> /// <summary>
/// Sets up value (see lua docs) /// Sets up value (see lua docs)
/// </summary> /// </summary>
/// <param name="funcindex">see lua docs</param> /// <param name = "funcindex">see lua docs</param>
/// <param name="n">see lua docs</param> /// <param name = "n">see lua docs</param>
/// <returns>see lua docs</returns> /// <returns>see lua docs</returns>
/// <author>Reinhard Ostermeier</author> /// <author>Reinhard Ostermeier</author>
public String SetUpValue(int funcindex, int n) public string SetUpValue(int funcindex, int n)
{ {
return KopiLua.Lua.lua_setupvalue(luaState, funcindex, n).ToString(); return LuaCore.lua_setupvalue(luaState, funcindex, n).ToString();
} }
/// <summary> /// <summary>
/// Delegate that is called on lua hook callback /// Delegate that is called on lua hook callback
/// </summary> /// </summary>
/// <param name="luaState">lua state</param> /// <param name = "luaState">lua state</param>
/// <param name="luaDebug">Pointer to LuaDebug (lua_debug) structure</param> /// <param name = "luaDebug">Pointer to LuaDebug (lua_debug) structure</param>
/// <author>Reinhard Ostermeier</author> /// <author>Reinhard Ostermeier</author>
/*private void DebugHookCallback(KopiLua.Lua.lua_State luaState, KopiLua.Lua.lua_Debug luaDebug) /*private void DebugHookCallback(LuaCore.lua_State luaState, LuaCore.lua_Debug luaDebug)
{ {
try try
{ {
LuaDebug ld = (LuaDebug)System.Runtime.InteropServices.Marshal.PtrToStructure(luaDebug, typeof(LuaDebug)); LuaDebug ld = (LuaDebug)System.Runtime.InteropServices.Marshal.PtrToStructure(luaDebug, typeof(LuaDebug));
EventHandler<DebugHookEventArgs> temp = DebugHook; EventHandler<DebugHookEventArgs> temp = DebugHook;
if (temp != null) if(temp != null)
{ {
temp(this, new DebugHookEventArgs(ld)); temp(this, new DebugHookEventArgs(ld));
} }
...@@ -895,28 +946,12 @@ namespace LuaInterface ...@@ -895,28 +946,12 @@ namespace LuaInterface
} }
}*/ }*/
/// <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) private void OnHookException(HookExceptionEventArgs e)
{ {
EventHandler<HookExceptionEventArgs> temp = HookException; var temp = HookException;
if (temp != null) if(!temp.IsNull())
{
temp(this, e); 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> /// <summary>
/// Pops a value from the lua stack. /// Pops a value from the lua stack.
...@@ -925,145 +960,143 @@ namespace LuaInterface ...@@ -925,145 +960,143 @@ namespace LuaInterface
/// <author>Reinhard Ostermeier</author> /// <author>Reinhard Ostermeier</author>
public object Pop() public object Pop()
{ {
int top = KopiLua.Lua.lua_gettop(luaState); int top = LuaCore.lua_gettop(luaState);
return translator.popValues(luaState, top - 1)[0]; return translator.popValues(luaState, top - 1)[0];
} }
/// <summary> /// <summary>
/// Pushes a value onto the lua stack. /// Pushes a value onto the lua stack.
/// </summary> /// </summary>
/// <param name="value">Value to push.</param> /// <param name = "value">Value to push.</param>
/// <author>Reinhard Ostermeier</author> /// <author>Reinhard Ostermeier</author>
public void Push(object value) public void Push(object value)
{ {
translator.push(luaState, value); translator.push(luaState, value);
} }
#endregion #endregion
internal void dispose(int reference) internal void dispose(int reference)
{ {
///////////// if (luaState != KopiLua.Lua.lua_State.Zero) ///////////// if(luaState != LuaCore.lua_State.Zero)
if (luaState != null) //Fix submitted by Qingrui Li if(!luaState.IsNull()) //Fix submitted by Qingrui Li
LuaLib.lua_unref(luaState,reference); LuaLib.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
* using rawget (do not use metatables) * using rawget (do not use metatables)
*/ */
internal object rawGetObject(int reference,string field) internal object rawGetObject(int reference, string field)
{ {
int oldTop=KopiLua.Lua.lua_gettop(luaState); int oldTop = LuaCore.lua_gettop(luaState);
LuaLib.lua_getref(luaState,reference); LuaLib.lua_getref(luaState, reference);
KopiLua.Lua.lua_pushstring(luaState,field); LuaCore.lua_pushstring(luaState, field);
KopiLua.Lua.lua_rawget(luaState,-2); LuaCore.lua_rawget(luaState, -2);
object obj=translator.getObject(luaState,-1); object obj = translator.getObject(luaState, -1);
KopiLua.Lua.lua_settop(luaState,oldTop); LuaCore.lua_settop(luaState, oldTop);
return obj; return obj;
} }
/* /*
* Gets a field of the table or userdata corresponding to the provided reference * Gets a field of the table or userdata corresponding to the provided reference
*/ */
internal object getObject(int reference,string field) internal object getObject(int reference, string field)
{ {
int oldTop=KopiLua.Lua.lua_gettop(luaState); int oldTop = LuaCore.lua_gettop(luaState);
LuaLib.lua_getref(luaState,reference); LuaLib.lua_getref(luaState, reference);
object returnValue=getObject(field.Split(new char[] {'.'})); object returnValue = getObject(field.Split(new char[] {'.'}));
KopiLua.Lua.lua_settop(luaState,oldTop); LuaCore.lua_settop(luaState, oldTop);
return returnValue; return returnValue;
} }
/* /*
* Gets a numeric field of the table or userdata corresponding the the provided reference * Gets a numeric field of the table or userdata corresponding the the provided reference
*/ */
internal object getObject(int reference,object field)
{ internal object getObject(int reference, object field)
int oldTop=KopiLua.Lua.lua_gettop(luaState); {
LuaLib.lua_getref(luaState,reference); int oldTop = LuaCore.lua_gettop(luaState);
translator.push(luaState,field); LuaLib.lua_getref(luaState, reference);
KopiLua.Lua.lua_gettable(luaState,-2); translator.push(luaState, field);
object returnValue=translator.getObject(luaState,-1); LuaCore.lua_gettable(luaState, -2);
KopiLua.Lua.lua_settop(luaState,oldTop); object returnValue = translator.getObject(luaState, -1);
LuaCore.lua_settop(luaState, oldTop);
return returnValue; return returnValue;
} }
/* /*
* Sets a field of the table or userdata corresponding the the provided reference * Sets a field of the table or userdata corresponding the the provided reference
* to the provided value * to the provided value
*/ */
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 = LuaCore.lua_gettop(luaState);
LuaLib.lua_getref(luaState,reference); LuaLib.lua_getref(luaState, reference);
setObject(field.Split(new char[] {'.'}),val); setObject(field.Split(new char[] {'.'}), val);
KopiLua.Lua.lua_settop(luaState,oldTop); LuaCore.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
* to the provided value * to the provided value
*/ */
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 = LuaCore.lua_gettop(luaState);
LuaLib.lua_getref(luaState,reference); LuaLib.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); LuaCore.lua_settable(luaState, -3);
KopiLua.Lua.lua_settop(luaState,oldTop); LuaCore.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, 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) 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 = LuaCore.lua_gettop(luaState);
var wrapper = new LuaMethodWrapper(translator, target, function.DeclaringType, function);
LuaMethodWrapper wrapper=new LuaMethodWrapper(translator,target,function.DeclaringType,function); translator.push(luaState, new LuaCore.lua_CFunction(wrapper.call));
translator.push(luaState,new KopiLua.Lua.lua_CFunction(wrapper.call)); this[path] = translator.getObject(luaState, -1);
var f = GetFunction(path);
this[path]=translator.getObject(luaState,-1); LuaCore.lua_settop(luaState, oldTop);
LuaFunction f = GetFunction(path);
KopiLua.Lua.lua_settop(luaState, oldTop);
return f; return f;
} }
/* /*
* Compares the two values referenced by ref1 and ref2 for equality * Compares the two values referenced by ref1 and ref2 for equality
*/ */
internal bool compareRef(int ref1, int ref2) internal bool compareRef(int ref1, int ref2)
{ {
int top=KopiLua.Lua.lua_gettop(luaState); int top = LuaCore.lua_gettop(luaState);
LuaLib.lua_getref(luaState,ref1); LuaLib.lua_getref(luaState, ref1);
LuaLib.lua_getref(luaState,ref2); LuaLib.lua_getref(luaState, ref2);
int equal=KopiLua.Lua.lua_equal(luaState,-1,-2); int equal = LuaCore.lua_equal(luaState, -1, -2);
KopiLua.Lua.lua_settop(luaState,top); LuaCore.lua_settop(luaState, top);
return (equal!=0); return (equal != 0);
} }
internal void pushCSFunction(KopiLua.Lua.lua_CFunction function) internal void pushCSFunction(LuaCore.lua_CFunction function)
{ {
translator.pushFunction(luaState,function); translator.pushFunction(luaState, function);
} }
#region IDisposable Members #region IDisposable Members
public virtual void Dispose() public virtual void Dispose()
{ {
if (translator != null) if(!translator.IsNull())
{ {
translator.pendingEvents.Dispose(); translator.pendingEvents.Dispose();
translator = null; translator = null;
} }
this.Close(); this.Close();
System.GC.Collect(); GC.Collect();
System.GC.WaitForPendingFinalizers(); GC.WaitForPendingFinalizers();
} }
#endregion #endregion
} }
} }
\ No newline at end of file
...@@ -24,8 +24,8 @@ ...@@ -24,8 +24,8 @@
*/ */
using System; using System;
using System.Collections.Generic;
using System.Text; using System.Text;
using System.Collections.Generic;
namespace LuaInterface namespace LuaInterface
{ {
...@@ -51,13 +51,14 @@ namespace LuaInterface ...@@ -51,13 +51,14 @@ namespace LuaInterface
public virtual void Dispose(bool disposeManagedResources) public virtual void Dispose(bool disposeManagedResources)
{ {
if (!_Disposed) if(!_Disposed)
{ {
if (disposeManagedResources) if(disposeManagedResources)
{ {
if (_Reference != 0) if(_Reference != 0)
_Interpreter.dispose(_Reference); _Interpreter.dispose(_Reference);
} }
_Interpreter = null; _Interpreter = null;
_Disposed = true; _Disposed = true;
} }
...@@ -65,12 +66,13 @@ namespace LuaInterface ...@@ -65,12 +66,13 @@ namespace LuaInterface
public override bool Equals(object o) public override bool Equals(object o)
{ {
if (o is LuaBase) if(o is LuaBase)
{ {
LuaBase l = (LuaBase)o; var l = (LuaBase)o;
return _Interpreter.compareRef(l._Reference, _Reference); return _Interpreter.compareRef(l._Reference, _Reference);
} }
else return false; else
return false;
} }
public override int GetHashCode() public override int GetHashCode()
......
...@@ -29,9 +29,11 @@ using System.Collections.Generic; ...@@ -29,9 +29,11 @@ using System.Collections.Generic;
namespace LuaInterface namespace LuaInterface
{ {
using LuaCore = KopiLua.Lua;
public class LuaFunction : LuaBase public class LuaFunction : LuaBase
{ {
internal KopiLua.Lua.lua_CFunction function; internal LuaCore.lua_CFunction function;
public LuaFunction(int reference, Lua interpreter) public LuaFunction(int reference, Lua interpreter)
{ {
...@@ -40,7 +42,7 @@ namespace LuaInterface ...@@ -40,7 +42,7 @@ namespace LuaInterface
_Interpreter = interpreter; _Interpreter = interpreter;
} }
public LuaFunction(KopiLua.Lua.lua_CFunction function, Lua interpreter) public LuaFunction(LuaCore.lua_CFunction function, Lua interpreter)
{ {
_Reference = 0; _Reference = 0;
this.function = function; this.function = function;
...@@ -55,6 +57,7 @@ namespace LuaInterface ...@@ -55,6 +57,7 @@ namespace LuaInterface
{ {
return _Interpreter.callFunction(this, args, returnTypes); return _Interpreter.callFunction(this, args, returnTypes);
} }
/* /*
* Calls the function and returns its return values inside * Calls the function and returns its return values inside
* an array * an array
...@@ -63,39 +66,41 @@ namespace LuaInterface ...@@ -63,39 +66,41 @@ namespace LuaInterface
{ {
return _Interpreter.callFunction(this, args); return _Interpreter.callFunction(this, args);
} }
/* /*
* Pushes the function into the Lua stack * Pushes the function into the Lua stack
*/ */
internal void push(KopiLua.Lua.lua_State luaState) internal void push(LuaCore.lua_State luaState)
{ {
if (_Reference != 0) if(_Reference != 0)
LuaLib.lua_getref(luaState, _Reference); LuaLib.lua_getref(luaState, _Reference);
else else
_Interpreter.pushCSFunction(function); _Interpreter.pushCSFunction(function);
} }
public override string ToString() public override string ToString()
{ {
return "function"; return "function";
} }
public override bool Equals(object o) public override bool Equals(object o)
{ {
if (o is LuaFunction) if(o is LuaFunction)
{ {
LuaFunction l = (LuaFunction)o; var l = (LuaFunction)o;
if (this._Reference != 0 && l._Reference != 0)
if(this._Reference != 0 && l._Reference != 0)
return _Interpreter.compareRef(l._Reference, this._Reference); return _Interpreter.compareRef(l._Reference, this._Reference);
else else
return this.function == l.function; return this.function == l.function;
} }
else return false; else
return false;
} }
public override int GetHashCode() public override int GetHashCode()
{ {
if (_Reference != 0) return _Reference != 0 ? _Reference : function.GetHashCode();
return _Reference;
else
return function.GetHashCode();
} }
} }
} }
\ No newline at end of file
...@@ -38,7 +38,6 @@ ...@@ -38,7 +38,6 @@
<Compile Include="CheckType.cs" /> <Compile Include="CheckType.cs" />
<Compile Include="Lua.cs" /> <Compile Include="Lua.cs" />
<Compile Include="Metatables.cs" /> <Compile Include="Metatables.cs" />
<Compile Include="MethodWrapper.cs" />
<Compile Include="ObjectTranslator.cs" /> <Compile Include="ObjectTranslator.cs" />
<Compile Include="ProxyType.cs" /> <Compile Include="ProxyType.cs" />
<Compile Include="LuaLib\LuaLib.cs" /> <Compile Include="LuaLib\LuaLib.cs" />
...@@ -68,6 +67,14 @@ ...@@ -68,6 +67,14 @@
<Compile Include="LuaLib\LuaTypes.cs" /> <Compile Include="LuaLib\LuaTypes.cs" />
<Compile Include="LuaLib\GCOption.cs" /> <Compile Include="LuaLib\GCOption.cs" />
<Compile Include="LuaLib\PseudoIndex.cs" /> <Compile Include="LuaLib\PseudoIndex.cs" />
<Compile Include="Method\MethodCache.cs" />
<Compile Include="Method\MethodArgs.cs" />
<Compile Include="Method\LuaMethodWrapper.cs" />
<Compile Include="Method\EventHandlerContainer.cs" />
<Compile Include="Method\RegisterEventHandler.cs" />
<Compile Include="Method\LuaEventHandler.cs" />
<Compile Include="Method\LuaDelegate.cs" />
<Compile Include="Method\LuaClassHelper.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.
...@@ -88,5 +95,6 @@ ...@@ -88,5 +95,6 @@
<Folder Include="GenerateEventAssembly\" /> <Folder Include="GenerateEventAssembly\" />
<Folder Include="Event\" /> <Folder Include="Event\" />
<Folder Include="Exceptions\" /> <Folder Include="Exceptions\" />
<Folder Include="Method\" />
</ItemGroup> </ItemGroup>
</Project> </Project>
...@@ -32,6 +32,8 @@ using LuaInterface.Extensions; ...@@ -32,6 +32,8 @@ using LuaInterface.Extensions;
namespace LuaInterface namespace LuaInterface
{ {
using LuaCore = KopiLua.Lua;
public static class LuaLib public static class LuaLib
{ {
private static int tag = 0; private static int tag = 0;
...@@ -77,9 +79,9 @@ namespace LuaInterface ...@@ -77,9 +79,9 @@ namespace LuaInterface
/// <param name="fn"> /// <param name="fn">
/// A <see cref="CallbackFunction"/> /// A <see cref="CallbackFunction"/>
/// </param> /// </param>
public static void lua_pushcfunction(KopiLua.Lua.lua_State state, KopiLua.Lua.lua_CFunction fn) public static void lua_pushcfunction(LuaCore.lua_State state, LuaCore.lua_CFunction fn)
{ {
KopiLua.Lua.lua_pushcclosure(state, fn, 0); LuaCore.lua_pushcclosure(state, fn, 0);
} }
#endregion #endregion
...@@ -96,9 +98,9 @@ namespace LuaInterface ...@@ -96,9 +98,9 @@ namespace LuaInterface
/// <returns> /// <returns>
/// A <see cref="System.Boolean"/> /// A <see cref="System.Boolean"/>
/// </returns> /// </returns>
public static bool luaL_dofile(KopiLua.Lua.lua_State state, string filename) public static bool luaL_dofile(LuaCore.lua_State state, string filename)
{ {
return (KopiLua.Lua.luaL_loadfile(state, filename).ToLuaEnums() == LuaEnums.Ok) && (KopiLua.Lua.lua_pcall(state, 0, (int)LuaEnums.MultiRet, 0).ToLuaEnums() == LuaEnums.Ok); return (LuaCore.luaL_loadfile(state, filename).ToLuaEnums() == LuaEnums.Ok) && (LuaCore.lua_pcall(state, 0, (int)LuaEnums.MultiRet, 0).ToLuaEnums() == LuaEnums.Ok);
} }
/// <summary> /// <summary>
...@@ -113,14 +115,14 @@ namespace LuaInterface ...@@ -113,14 +115,14 @@ namespace LuaInterface
/// <returns> /// <returns>
/// A <see cref="System.Boolean"/> /// A <see cref="System.Boolean"/>
/// </returns> /// </returns>
public static bool luaL_dostring(KopiLua.Lua.lua_State state, string chunk) public static bool luaL_dostring(LuaCore.lua_State state, string chunk)
{ {
return (KopiLua.Lua.luaL_loadstring(state, chunk).ToLuaEnums() == LuaEnums.Ok) && (KopiLua.Lua.lua_pcall(state, 0, (int)LuaEnums.MultiRet, 0).ToLuaEnums() == LuaEnums.Ok); return (LuaCore.luaL_loadstring(state, chunk).ToLuaEnums() == LuaEnums.Ok) && (LuaCore.lua_pcall(state, 0, (int)LuaEnums.MultiRet, 0).ToLuaEnums() == LuaEnums.Ok);
} }
public static LuaEnums luaL_loadbuffer(KopiLua.Lua.lua_State luaState, string buff, string name) public static LuaEnums luaL_loadbuffer(LuaCore.lua_State luaState, string buff, string name)
{ {
var result = KopiLua.Lua.luaL_loadbuffer(luaState, buff, (uint)buff.Length, name).ToLuaEnums(); var result = LuaCore.luaL_loadbuffer(luaState, buff, (uint)buff.Length, name).ToLuaEnums();
return result; return result;
} }
...@@ -136,22 +138,22 @@ namespace LuaInterface ...@@ -136,22 +138,22 @@ namespace LuaInterface
/// <param name="r"> /// <param name="r">
/// A <see cref="System.Int32"/> /// A <see cref="System.Int32"/>
/// </param> /// </param>
public static void luaL_getref(KopiLua.Lua.lua_State state, int t, int r) public static void luaL_getref(LuaCore.lua_State state, int t, int r)
{ {
KopiLua.Lua.lua_rawgeti(state, t, r); LuaCore.lua_rawgeti(state, t, r);
} }
public static bool luaL_checkmetatable(KopiLua.Lua.lua_State luaState,int index) public static bool luaL_checkmetatable(LuaCore.lua_State luaState,int index)
{ {
bool retVal = false; bool retVal = false;
Console.WriteLine("v: " + luaState.tt.ToString()); Console.WriteLine("v: " + luaState.tt.ToString());
if(KopiLua.Lua.lua_getmetatable(luaState,index)!=0) if(LuaCore.lua_getmetatable(luaState,index)!=0)
{ {
KopiLua.Lua.lua_pushlightuserdata(luaState, tag); LuaCore.lua_pushlightuserdata(luaState, tag);
KopiLua.Lua.lua_rawget(luaState, -2); LuaCore.lua_rawget(luaState, -2);
retVal = !KopiLua.Lua.lua_isnil(luaState, -1); retVal = !LuaCore.lua_isnil(luaState, -1);
KopiLua.Lua.lua_settop(luaState, -3); LuaCore.lua_settop(luaState, -3);
} }
return retVal; return retVal;
...@@ -162,43 +164,43 @@ namespace LuaInterface ...@@ -162,43 +164,43 @@ namespace LuaInterface
return tag; return tag;
} }
public static void lua_getref(KopiLua.Lua.lua_State luaState, int reference) public static void lua_getref(LuaCore.lua_State luaState, int reference)
{ {
KopiLua.Lua.lua_rawgeti(luaState, (int)PseudoIndex.Registry, reference); LuaCore.lua_rawgeti(luaState, (int)PseudoIndex.Registry, reference);
} }
public static void lua_unref(KopiLua.Lua.lua_State luaState, int reference) public static void lua_unref(LuaCore.lua_State luaState, int reference)
{ {
KopiLua.Lua.luaL_unref(luaState, (int)PseudoIndex.Registry, reference); LuaCore.luaL_unref(luaState, (int)PseudoIndex.Registry, reference);
} }
public static int luanet_rawnetobj(KopiLua.Lua.lua_State luaState,int obj) public static int luanet_rawnetobj(LuaCore.lua_State luaState,int obj)
{ {
int udata = (int)KopiLua.Lua.lua_touserdata2(luaState, obj); int udata = (int)LuaCore.lua_touserdata2(luaState, obj);
return udata != 0 ? udata : -1; return udata != 0 ? udata : -1;
} }
public static void lua_pushstdcallcfunction(KopiLua.Lua.lua_State luaState,KopiLua.Lua.lua_CFunction function) public static void lua_pushstdcallcfunction(LuaCore.lua_State luaState,LuaCore.lua_CFunction function)
{ {
lua_pushcfunction(luaState, function); lua_pushcfunction(luaState, function);
} }
public static int checkudata_raw(KopiLua.Lua.lua_State luaState, int ud, string tname) public static int checkudata_raw(LuaCore.lua_State luaState, int ud, string tname)
{ {
int p = (int)KopiLua.Lua.lua_touserdata2(luaState, ud); int p = (int)LuaCore.lua_touserdata2(luaState, ud);
//Console.WriteLine(BitConverter.ToInt32(ObjectToByteArray(KopiLua.Lua.lua_touserdata(luaState, ud)), 0)); //Console.WriteLine(BitConverter.ToInt32(ObjectToByteArray(LuaCore.lua_touserdata(luaState, ud)), 0));
if(p != 0) if(p != 0)
{ {
/* value is a userdata? */ /* value is a userdata? */
if(KopiLua.Lua.lua_getmetatable(luaState, ud)!=0) if(LuaCore.lua_getmetatable(luaState, ud)!=0)
{ {
/* does it have a metatable? */ /* does it have a metatable? */
KopiLua.Lua.lua_getfield(luaState, (int)PseudoIndex.Registry, tname); /* get correct metatable */ LuaCore.lua_getfield(luaState, (int)PseudoIndex.Registry, tname); /* get correct metatable */
bool isEqual = KopiLua.Lua.lua_rawequal(luaState, -1, -2).ToBoolean(); bool isEqual = LuaCore.lua_rawequal(luaState, -1, -2).ToBoolean();
// NASTY - we need our own version of the lua_pop macro // NASTY - we need our own version of the lua_pop macro
// lua_pop(L, 2); /* remove both metatables */ // lua_pop(L, 2); /* remove both metatables */
KopiLua.Lua.lua_settop(luaState, -(2) - 1); LuaCore.lua_settop(luaState, -(2) - 1);
if(isEqual) /* does it have the correct mt? */ if(isEqual) /* does it have the correct mt? */
return p; return p;
...@@ -208,27 +210,27 @@ namespace LuaInterface ...@@ -208,27 +210,27 @@ namespace LuaInterface
return 0; return 0;
} }
public static int luanet_checkudata(KopiLua.Lua.lua_State luaState, int ud, string tname) public static int luanet_checkudata(LuaCore.lua_State luaState, int ud, string tname)
{ {
int udata = checkudata_raw(luaState, ud, tname); int udata = checkudata_raw(luaState, ud, tname);
return udata != 0 ? udata : -1; return udata != 0 ? udata : -1;
} }
public static void luanet_newudata(KopiLua.Lua.lua_State luaState, int val) public static void luanet_newudata(LuaCore.lua_State luaState, int val)
{ {
KopiLua.Lua.lua_newuserdata(luaState, (uint)val); LuaCore.lua_newuserdata(luaState, (uint)val);
} }
public static int luanet_tonetobject(KopiLua.Lua.lua_State luaState, int index) public static int luanet_tonetobject(LuaCore.lua_State luaState, int index)
{ {
int udata; int udata;
Console.WriteLine("x" + KopiLua.Lua.lua_type(luaState, index).ToString()); Console.WriteLine("x" + LuaCore.lua_type(luaState, index).ToString());
if(KopiLua.Lua.lua_type(luaState, index).ToLuaTypes() == LuaTypes.UserData) if(LuaCore.lua_type(luaState, index).ToLuaTypes() == LuaTypes.UserData)
{ {
if(luaL_checkmetatable(luaState, index)) if(luaL_checkmetatable(luaState, index))
{ {
udata = (int)KopiLua.Lua.lua_touserdata2(luaState, index); udata = (int)LuaCore.lua_touserdata2(luaState, index);
if(udata != 0) if(udata != 0)
return udata; return udata;
} }
...@@ -249,9 +251,9 @@ namespace LuaInterface ...@@ -249,9 +251,9 @@ namespace LuaInterface
return -1; return -1;
} }
public static int lua_ref(KopiLua.Lua.lua_State luaState, int lockRef) public static int lua_ref(LuaCore.lua_State luaState, int lockRef)
{ {
return lockRef != 0 ? KopiLua.Lua.luaL_ref(luaState, (int)PseudoIndex.Registry) : 0; return lockRef != 0 ? LuaCore.luaL_ref(luaState, (int)PseudoIndex.Registry) : 0;
} }
#endregion #endregion
} }
......
...@@ -24,8 +24,9 @@ ...@@ -24,8 +24,9 @@
*/ */
using System; using System;
using System.Diagnostics.CodeAnalysis;
using System.Reflection; using System.Reflection;
using System.Diagnostics.CodeAnalysis;
using LuaInterface.Extensions;
namespace LuaInterface namespace LuaInterface
{ {
...@@ -40,15 +41,18 @@ namespace LuaInterface ...@@ -40,15 +41,18 @@ namespace LuaInterface
public static void TaggedInstanceMethods(Lua lua, object o) public static void TaggedInstanceMethods(Lua lua, object o)
{ {
#region Sanity checks #region Sanity checks
if (lua == null) throw new ArgumentNullException("lua"); if(lua.IsNull())
if (o == null) throw new ArgumentNullException("o"); throw new ArgumentNullException("lua");
if(o.IsNull())
throw new ArgumentNullException("o");
#endregion #endregion
foreach (MethodInfo method in o.GetType().GetMethods(BindingFlags.Instance | BindingFlags.Public)) foreach(var method in o.GetType().GetMethods(BindingFlags.Instance | BindingFlags.Public))
{ {
foreach (LuaGlobalAttribute attribute in method.GetCustomAttributes(typeof(LuaGlobalAttribute), true)) foreach(LuaGlobalAttribute attribute in method.GetCustomAttributes(typeof(LuaGlobalAttribute), true))
{ {
if (string.IsNullOrEmpty(attribute.Name)) if(string.IsNullOrEmpty(attribute.Name))
lua.RegisterFunction(method.Name, o, method); // CLR name lua.RegisterFunction(method.Name, o, method); // CLR name
else else
lua.RegisterFunction(attribute.Name, o, method); // Custom name lua.RegisterFunction(attribute.Name, o, method); // Custom name
...@@ -66,16 +70,21 @@ namespace LuaInterface ...@@ -66,16 +70,21 @@ namespace LuaInterface
public static void TaggedStaticMethods(Lua lua, Type type) public static void TaggedStaticMethods(Lua lua, Type type)
{ {
#region Sanity checks #region Sanity checks
if (lua == null) throw new ArgumentNullException("lua"); if(lua.IsNull())
if (type == null) throw new ArgumentNullException("type"); throw new ArgumentNullException("lua");
if (!type.IsClass) throw new ArgumentException("The type must be a class!", "type");
if(type.IsNull())
throw new ArgumentNullException("type");
if(!type.IsClass)
throw new ArgumentException("The type must be a class!", "type");
#endregion #endregion
foreach (MethodInfo method in type.GetMethods(BindingFlags.Static | BindingFlags.Public)) foreach(var method in type.GetMethods(BindingFlags.Static | BindingFlags.Public))
{ {
foreach (LuaGlobalAttribute attribute in method.GetCustomAttributes(typeof(LuaGlobalAttribute), false)) foreach(LuaGlobalAttribute attribute in method.GetCustomAttributes(typeof(LuaGlobalAttribute), false))
{ {
if (string.IsNullOrEmpty(attribute.Name)) if(string.IsNullOrEmpty(attribute.Name))
lua.RegisterFunction(method.Name, null, method); // CLR name lua.RegisterFunction(method.Name, null, method); // CLR name
else else
lua.RegisterFunction(attribute.Name, null, method); // Custom name lua.RegisterFunction(attribute.Name, null, method); // Custom name
...@@ -94,17 +103,20 @@ namespace LuaInterface ...@@ -94,17 +103,20 @@ namespace LuaInterface
public static void Enumeration<T>(Lua lua) public static void Enumeration<T>(Lua lua)
{ {
#region Sanity checks #region Sanity checks
if (lua == null) throw new ArgumentNullException("lua"); if(lua.IsNull())
throw new ArgumentNullException("lua");
#endregion #endregion
Type type = typeof(T); var type = typeof(T);
if (!type.IsEnum) throw new ArgumentException("The type must be an enumeration!");
if(!type.IsEnum)
throw new ArgumentException("The type must be an enumeration!");
string[] names = Enum.GetNames(type); string[] names = Enum.GetNames(type);
var values = (T[])Enum.GetValues(type); var values = (T[])Enum.GetValues(type);
lua.NewTable(type.Name); lua.NewTable(type.Name);
for (int i = 0; i < names.Length; i++)
for(int i = 0; i < names.Length; i++)
{ {
string path = type.Name + "." + names[i]; string path = type.Name + "." + names[i];
lua[path] = values[i]; lua[path] = values[i];
......
...@@ -30,6 +30,8 @@ using System.Collections.Generic; ...@@ -30,6 +30,8 @@ using System.Collections.Generic;
namespace LuaInterface namespace LuaInterface
{ {
using LuaCore = KopiLua.Lua;
/* /*
* Wrapper class for Lua tables * Wrapper class for Lua tables
* *
...@@ -58,6 +60,7 @@ namespace LuaInterface ...@@ -58,6 +60,7 @@ namespace LuaInterface
_Interpreter.setObject(_Reference, field, value); _Interpreter.setObject(_Reference, field, value);
} }
} }
/* /*
* Indexer for numeric fields of the table * Indexer for numeric fields of the table
*/ */
...@@ -73,7 +76,6 @@ namespace LuaInterface ...@@ -73,7 +76,6 @@ namespace LuaInterface
} }
} }
public System.Collections.IDictionaryEnumerator GetEnumerator() public System.Collections.IDictionaryEnumerator GetEnumerator()
{ {
return _Interpreter.GetTableDict(this).GetEnumerator(); return _Interpreter.GetTableDict(this).GetEnumerator();
...@@ -102,8 +104,8 @@ namespace LuaInterface ...@@ -102,8 +104,8 @@ namespace LuaInterface
{ {
object obj = _Interpreter.rawGetObject(_Reference, field); object obj = _Interpreter.rawGetObject(_Reference, field);
if (obj is KopiLua.Lua.lua_CFunction) if(obj is LuaCore.lua_CFunction)
return new LuaFunction((KopiLua.Lua.lua_CFunction)obj, _Interpreter); return new LuaFunction((LuaCore.lua_CFunction)obj, _Interpreter);
else else
return obj; return obj;
} }
...@@ -111,10 +113,11 @@ namespace LuaInterface ...@@ -111,10 +113,11 @@ namespace LuaInterface
/* /*
* Pushes this table into the Lua stack * Pushes this table into the Lua stack
*/ */
internal void push(KopiLua.Lua.lua_State luaState) internal void push(LuaCore.lua_State luaState)
{ {
LuaLib.lua_getref(luaState, _Reference); LuaLib.lua_getref(luaState, _Reference);
} }
public override string ToString() public override string ToString()
{ {
return "table"; return "table";
......
...@@ -29,6 +29,8 @@ using System.Collections.Generic; ...@@ -29,6 +29,8 @@ using System.Collections.Generic;
namespace LuaInterface namespace LuaInterface
{ {
using LuaCore = KopiLua.Lua;
public class LuaUserData : LuaBase public class LuaUserData : LuaBase
{ {
public LuaUserData(int reference, Lua interpreter) public LuaUserData(int reference, Lua interpreter)
...@@ -51,6 +53,7 @@ namespace LuaInterface ...@@ -51,6 +53,7 @@ namespace LuaInterface
_Interpreter.setObject(_Reference, field, value); _Interpreter.setObject(_Reference, field, value);
} }
} }
/* /*
* Indexer for numeric fields of the userdata * Indexer for numeric fields of the userdata
*/ */
...@@ -65,6 +68,7 @@ namespace LuaInterface ...@@ -65,6 +68,7 @@ namespace LuaInterface
_Interpreter.setObject(_Reference, field, value); _Interpreter.setObject(_Reference, field, value);
} }
} }
/* /*
* Calls the userdata and returns its return values inside * Calls the userdata and returns its return values inside
* an array * an array
...@@ -73,13 +77,15 @@ namespace LuaInterface ...@@ -73,13 +77,15 @@ namespace LuaInterface
{ {
return _Interpreter.callFunction(this, args); return _Interpreter.callFunction(this, args);
} }
/* /*
* Pushes the userdata into the Lua stack * Pushes the userdata into the Lua stack
*/ */
internal void push(KopiLua.Lua.lua_State luaState) internal void push(LuaCore.lua_State luaState)
{ {
LuaLib.lua_getref(luaState, _Reference); LuaLib.lua_getref(luaState, _Reference);
} }
public override string ToString() public override string ToString()
{ {
return "userdata"; return "userdata";
......
...@@ -30,9 +30,13 @@ using System.Reflection; ...@@ -30,9 +30,13 @@ using System.Reflection;
using System.Diagnostics; using System.Diagnostics;
using System.Collections.Generic; using System.Collections.Generic;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using LuaInterface.Method;
using LuaInterface.Extensions;
namespace LuaInterface namespace LuaInterface
{ {
using LuaCore = KopiLua.Lua;
/* /*
* Functions used in the metatables of userdata representing * Functions used in the metatables of userdata representing
* CLR objects * CLR objects
...@@ -42,81 +46,83 @@ namespace LuaInterface ...@@ -42,81 +46,83 @@ namespace LuaInterface
*/ */
class MetaFunctions class MetaFunctions
{ {
internal LuaCore.lua_CFunction gcFunction, indexFunction, newindexFunction, baseIndexFunction,
classIndexFunction, classNewindexFunction, execDelegateFunction, callConstructorFunction, toStringFunction;
private Hashtable memberCache = new Hashtable();
private ObjectTranslator translator;
/* /*
* __index metafunction for CLR objects. Implemented in Lua. * __index metafunction for CLR objects. Implemented in Lua.
*/ */
internal static string luaIndexFunction = internal static string luaIndexFunction =
"local function index(obj,name)\n" + "local function index(obj,name) \n" +
" local meta=getmetatable(obj)\n" + " local meta=getmetatable(obj) \n" +
" local cached=meta.cache[name]\n" + " local cached=meta.cache[name] \n" +
" if cached~=nil then\n" + " if cached~=nil then \n" +
" return cached\n" + " return cached \n" +
" else\n" + " else \n" +
" local value,isFunc=get_object_member(obj,name)\n" + " local value,isFunc=get_object_member(obj,name) \n" +
" if isFunc then\n" + " if isFunc then \n" +
" meta.cache[name]=value\n" + " meta.cache[name]=value \n" +
" end\n" + " end \n" +
" return value\n" + " return value \n" +
" end\n" + " end \n" +
"end\n" + "end \n" +
"return index"; "return index ";
private ObjectTranslator translator;
private Hashtable memberCache = new Hashtable();
internal KopiLua.Lua.lua_CFunction gcFunction, indexFunction, newindexFunction,
baseIndexFunction, classIndexFunction, classNewindexFunction,
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 LuaCore.lua_CFunction(this.collectObject);
toStringFunction = new KopiLua.Lua.lua_CFunction(this.toString); toStringFunction = new LuaCore.lua_CFunction(this.toString);
indexFunction = new KopiLua.Lua.lua_CFunction(this.getMethod); indexFunction = new LuaCore.lua_CFunction(this.getMethod);
newindexFunction = new KopiLua.Lua.lua_CFunction(this.setFieldOrProperty); newindexFunction = new LuaCore.lua_CFunction(this.setFieldOrProperty);
baseIndexFunction = new KopiLua.Lua.lua_CFunction(this.getBaseMethod); baseIndexFunction = new LuaCore.lua_CFunction(this.getBaseMethod);
callConstructorFunction = new KopiLua.Lua.lua_CFunction(this.callConstructor); callConstructorFunction = new LuaCore.lua_CFunction(this.callConstructor);
classIndexFunction = new KopiLua.Lua.lua_CFunction(this.getClassMethod); classIndexFunction = new LuaCore.lua_CFunction(this.getClassMethod);
classNewindexFunction = new KopiLua.Lua.lua_CFunction(this.setClassFieldOrProperty); classNewindexFunction = new LuaCore.lua_CFunction(this.setClassFieldOrProperty);
execDelegateFunction = new KopiLua.Lua.lua_CFunction(this.runFunctionDelegate); execDelegateFunction = new LuaCore.lua_CFunction(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(LuaCore.lua_State luaState)
{ {
KopiLua.Lua.lua_CFunction func = (KopiLua.Lua.lua_CFunction)translator.getRawNetObject(luaState, 1); LuaCore.lua_CFunction func = (LuaCore.lua_CFunction)translator.getRawNetObject(luaState, 1);
KopiLua.Lua.lua_remove(luaState, 1); LuaCore.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(LuaCore.lua_State luaState)
{ {
int udata = LuaLib.luanet_rawnetobj(luaState, 1); int udata = LuaLib.luanet_rawnetobj(luaState, 1);
if (udata != -1)
{ if(udata != -1)
translator.collectObject(udata); translator.collectObject(udata);
}
else else
{ {
// Debug.WriteLine("not found: " + udata); // Debug.WriteLine("not found: " + udata);
} }
return 0; return 0;
} }
/* /*
* __tostring metafunction of CLR objects. * __tostring metafunction of CLR objects.
*/ */
private int toString(KopiLua.Lua.lua_State luaState) private int toString(LuaCore.lua_State luaState)
{ {
object obj = translator.getRawNetObject(luaState, 1); object obj = translator.getRawNetObject(luaState, 1);
if (obj != null)
{ if(!obj.IsNull())
translator.push(luaState, obj.ToString() + ": " + obj.GetHashCode()); translator.push(luaState, obj.ToString() + ": " + obj.GetHashCode());
} else
else KopiLua.Lua.lua_pushnil(luaState); LuaCore.lua_pushnil(luaState);
return 1; return 1;
} }
...@@ -125,19 +131,19 @@ namespace LuaInterface ...@@ -125,19 +131,19 @@ namespace LuaInterface
/// 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, LuaCore.lua_State luaState)
{ {
int depth = KopiLua.Lua.lua_gettop(luaState); int depth = LuaCore.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++)
{ {
LuaTypes type = KopiLua.Lua.lua_type(luaState, i).ToLuaTypes(); var type = LuaCore.lua_type(luaState, i).ToLuaTypes();
// 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 == LuaTypes.Table) ? "table" : KopiLua.Lua.lua_typename(luaState, (int)type).ToString(); string typestr = (type == LuaTypes.Table) ? "table" : LuaCore.lua_typename(luaState, (int)type).ToString();
string strrep = LuaCore.lua_tostring(luaState, i).ToString();
string strrep = KopiLua.Lua.lua_tostring(luaState, i).ToString(); if(type == LuaTypes.UserData)
if (type == LuaTypes.UserData)
{ {
object obj = translator.getRawNetObject(luaState, i); object obj = translator.getRawNetObject(luaState, i);
strrep = obj.ToString(); strrep = obj.ToString();
...@@ -147,7 +153,6 @@ namespace LuaInterface ...@@ -147,7 +153,6 @@ 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.
...@@ -155,21 +160,21 @@ namespace LuaInterface ...@@ -155,21 +160,21 @@ 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(LuaCore.lua_State luaState)
{ {
object obj = translator.getRawNetObject(luaState, 1); object obj = translator.getRawNetObject(luaState, 1);
if (obj == null)
if(obj.IsNull())
{ {
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); LuaCore.lua_pushnil(luaState);
return 1; return 1;
} }
object index = translator.getObject(luaState, 2); object index = translator.getObject(luaState, 2);
Type indexType = index.GetType(); var 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(); var 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.
...@@ -177,27 +182,29 @@ namespace LuaInterface ...@@ -177,27 +182,29 @@ namespace LuaInterface
// ie: xmlelement['item'] <- item is a property of xmlelement // ie: xmlelement['item'] <- item is a property of xmlelement
try try
{ {
if (methodName != null && isMemberPresent(objType, methodName)) if(!methodName.IsNull() && isMemberPresent(objType, methodName))
return getMember(luaState, objType, obj, methodName, BindingFlags.Instance | BindingFlags.IgnoreCase); return getMember(luaState, objType, obj, methodName, BindingFlags.Instance | BindingFlags.IgnoreCase);
} }
catch { } 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)
{ {
int intIndex = (int)((double)index); int intIndex = (int)((double)index);
if (objType.UnderlyingSystemType == typeof(float[])) if(objType.UnderlyingSystemType == typeof(float[]))
{ {
float[] arr = ((float[])obj); float[] arr = ((float[])obj);
translator.push(luaState, arr[intIndex]); translator.push(luaState, arr[intIndex]);
} }
else if (objType.UnderlyingSystemType == typeof(double[])) else if(objType.UnderlyingSystemType == typeof(double[]))
{ {
double[] arr = ((double[])obj); double[] arr = ((double[])obj);
translator.push(luaState, arr[intIndex]); translator.push(luaState, arr[intIndex]);
} }
else if (objType.UnderlyingSystemType == typeof(int[])) else if(objType.UnderlyingSystemType == typeof(int[]))
{ {
int[] arr = ((int[])obj); int[] arr = ((int[])obj);
translator.push(luaState, arr[intIndex]); translator.push(luaState, arr[intIndex]);
...@@ -212,94 +219,95 @@ namespace LuaInterface ...@@ -212,94 +219,95 @@ namespace LuaInterface
{ {
// 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(); var methods = objType.GetMethods();
foreach (MethodInfo mInfo in methods) foreach(var mInfo in methods)
{ {
if (mInfo.Name == "get_Item") if(mInfo.Name == "get_Item")
{ {
//check if the signature matches the input //check if the signature matches the input
if (mInfo.GetParameters().Length == 1) if(mInfo.GetParameters().Length == 1)
{ {
MethodInfo getter = mInfo; var getter = mInfo;
ParameterInfo[] actualParms = (getter != null) ? getter.GetParameters() : null; var actualParms = (!getter.IsNull()) ? getter.GetParameters() : null;
if (actualParms == null || actualParms.Length != 1) if(actualParms.IsNull() || actualParms.Length != 1)
{ {
translator.throwError(luaState, "method not found (or no indexer): " + index); translator.throwError(luaState, "method not found (or no indexer): " + index);
LuaCore.lua_pushnil(luaState);
KopiLua.Lua.lua_pushnil(luaState);
} }
else else
{ {
// Get the index in a form acceptable to the getter // Get the index in a form acceptable to the getter
index = translator.getAsType(luaState, 2, actualParms[0].ParameterType); index = translator.getAsType(luaState, 2, actualParms[0].ParameterType);
object[] args = new object[1]; object[] args = new object[1];
// Just call the indexer - if out of bounds an exception will happen // Just call the indexer - if out of bounds an exception will happen
args[0] = index; args[0] = index;
try try
{ {
object result = getter.Invoke(obj, args); object result = getter.Invoke(obj, args);
translator.push(luaState, result); translator.push(luaState, result);
} }
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); LuaCore.lua_pushnil(luaState);
} }
} }
} }
} }
} }
} }
KopiLua.Lua.lua_pushboolean(luaState, 0); LuaCore.lua_pushboolean(luaState, 0);
return 2; return 2;
} }
/* /*
* __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(LuaCore.lua_State luaState)
{ {
object obj = translator.getRawNetObject(luaState, 1); object obj = translator.getRawNetObject(luaState, 1);
if (obj == null)
if(obj.IsNull())
{ {
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); LuaCore.lua_pushnil(luaState);
KopiLua.Lua.lua_pushboolean(luaState, 0); LuaCore.lua_pushboolean(luaState, 0);
return 2; return 2;
} }
string methodName = KopiLua.Lua.lua_tostring(luaState, 2).ToString();
if (methodName == null) string methodName = LuaCore.lua_tostring(luaState, 2).ToString();
if(methodName.IsNull())
{ {
KopiLua.Lua.lua_pushnil(luaState); LuaCore.lua_pushnil(luaState);
KopiLua.Lua.lua_pushboolean(luaState, 0); LuaCore.lua_pushboolean(luaState, 0);
return 2; return 2;
} }
getMember(luaState, obj.GetType(), obj, "__luaInterface_base_" + methodName, BindingFlags.Instance | BindingFlags.IgnoreCase); getMember(luaState, obj.GetType(), obj, "__luaInterface_base_" + methodName, BindingFlags.Instance | BindingFlags.IgnoreCase);
KopiLua.Lua.lua_settop(luaState, -2); LuaCore.lua_settop(luaState, -2);
if (KopiLua.Lua.lua_type(luaState, -1).ToLuaTypes() == LuaTypes.Nil)
if(LuaCore.lua_type(luaState, -1).ToLuaTypes() == LuaTypes.Nil)
{ {
KopiLua.Lua.lua_settop(luaState, -2); LuaCore.lua_settop(luaState, -2);
return getMember(luaState, obj.GetType(), obj, methodName, BindingFlags.Instance | BindingFlags.IgnoreCase); return getMember(luaState, obj.GetType(), obj, methodName, BindingFlags.Instance | BindingFlags.IgnoreCase);
} }
KopiLua.Lua.lua_pushboolean(luaState, 0);
LuaCore.lua_pushboolean(luaState, 0);
return 2; return 2;
} }
/// <summary> /// <summary>
/// Does this method exist as either an instance or static? /// Does this method exist as either an instance or static?
/// </summary> /// </summary>
...@@ -310,11 +318,11 @@ namespace LuaInterface ...@@ -310,11 +318,11 @@ namespace LuaInterface
{ {
object cachedMember = checkMemberCache(memberCache, objType, methodName); object cachedMember = checkMemberCache(memberCache, objType, methodName);
if (cachedMember != null) if(!cachedMember.IsNull())
return true; return true;
//CP: Removed NonPublic binding search //CP: Removed NonPublic binding search
MemberInfo[] members = objType.GetMember(methodName, BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase/* | BindingFlags.NonPublic*/); var members = objType.GetMember(methodName, BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase/* | BindingFlags.NonPublic*/);
return (members.Length > 0); return (members.Length > 0);
} }
...@@ -324,27 +332,27 @@ namespace LuaInterface ...@@ -324,27 +332,27 @@ 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(LuaCore.lua_State 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 LuaCore.lua_CFunction)
{ {
translator.pushFunction(luaState, (KopiLua.Lua.lua_CFunction)cachedMember); translator.pushFunction(luaState, (LuaCore.lua_CFunction)cachedMember);
translator.push(luaState, true); translator.push(luaState, true);
return 2; return 2;
} }
else if (cachedMember != null) else if(!cachedMember.IsNull())
{
member = (MemberInfo)cachedMember; member = (MemberInfo)cachedMember;
}
else else
{ {
//CP: Removed NonPublic binding search //CP: Removed NonPublic binding search
MemberInfo[] members = objType.GetMember(methodName, bindingType | BindingFlags.Public | BindingFlags.IgnoreCase/*| BindingFlags.NonPublic*/); var 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
{ {
...@@ -353,85 +361,92 @@ namespace LuaInterface ...@@ -353,85 +361,92 @@ namespace LuaInterface
//CP: Removed NonPublic binding search and made case insensitive //CP: Removed NonPublic binding search and made case insensitive
members = objType.GetMember(methodName, bindingType | BindingFlags.Static | BindingFlags.Public | BindingFlags.IgnoreCase/*| BindingFlags.NonPublic*/); members = objType.GetMember(methodName, bindingType | BindingFlags.Static | BindingFlags.Public | BindingFlags.IgnoreCase/*| BindingFlags.NonPublic*/);
if (members.Length > 0) if(members.Length > 0)
{ {
member = members[0]; member = members[0];
implicitStatic = true; implicitStatic = true;
} }
} }
} }
if (member != null)
if(!member.IsNull())
{ {
if (member.MemberType == MemberTypes.Field) if(member.MemberType == MemberTypes.Field)
{ {
FieldInfo field = (FieldInfo)member; var field = (FieldInfo)member;
if (cachedMember == null) setMemberCache(memberCache, objType, methodName, member);
if(cachedMember.IsNull())
setMemberCache(memberCache, objType, methodName, member);
try try
{ {
translator.push(luaState, field.GetValue(obj)); translator.push(luaState, field.GetValue(obj));
} }
catch catch
{ {
KopiLua.Lua.lua_pushnil(luaState); LuaCore.lua_pushnil(luaState);
} }
} }
else if (member.MemberType == MemberTypes.Property) else if(member.MemberType == MemberTypes.Property)
{ {
PropertyInfo property = (PropertyInfo)member; var property = (PropertyInfo)member;
if (cachedMember == null) setMemberCache(memberCache, objType, methodName, member); if(cachedMember.IsNull())
setMemberCache(memberCache, objType, methodName, member);
try try
{ {
object val = property.GetValue(obj, null); object val = property.GetValue(obj, null);
translator.push(luaState, val); translator.push(luaState, val);
} }
catch (ArgumentException) catch(ArgumentException)
{ {
// If we can't find the getter in our class, recurse up to the base class and see // If we can't find the getter in our class, recurse up to the base class and see
// if they can help. // if they can help.
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); LuaCore.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); LuaCore.lua_pushnil(luaState);
} }
} }
else if (member.MemberType == MemberTypes.Event) else if(member.MemberType == MemberTypes.Event)
{ {
EventInfo eventInfo = (EventInfo)member; var eventInfo = (EventInfo)member;
if (cachedMember == null) setMemberCache(memberCache, objType, methodName, member); if(cachedMember.IsNull())
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)
{ {
// kevinh - added support for finding nested types // kevinh - added support for finding nested types
// cache us // cache us
if (cachedMember == null) setMemberCache(memberCache, objType, methodName, member); if(cachedMember.IsNull())
setMemberCache(memberCache, objType, methodName, member);
// Find the name of our class // Find the name of our class
string name = member.Name; string name = member.Name;
Type dectype = member.DeclaringType; var dectype = member.DeclaringType;
// Build a new long name and try to find the type by name // Build a new long name and try to find the type by name
string longname = dectype.FullName + "+" + name; string longname = dectype.FullName + "+" + name;
Type nestedType = translator.FindType(longname); var nestedType = translator.FindType(longname);
translator.pushType(luaState, nestedType); translator.pushType(luaState, nestedType);
} }
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); var wrapper = new LuaCore.lua_CFunction((new LuaMethodWrapper(translator, objType, methodName, bindingType)).call);
if(cachedMember.IsNull())
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);
return 2; return 2;
...@@ -441,8 +456,7 @@ namespace LuaInterface ...@@ -441,8 +456,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);
LuaCore.lua_pushnil(luaState);
KopiLua.Lua.lua_pushnil(luaState);
} }
} }
else else
...@@ -450,86 +464,86 @@ namespace LuaInterface ...@@ -450,86 +464,86 @@ namespace LuaInterface
// kevinh - we want to throw an exception because meerly returning 'nil' in this case // kevinh - we want to throw an exception because meerly returning 'nil' in this case
// is not sufficient. valid data members may return nil and therefore there must be some // is not sufficient. valid data members may return nil and therefore there must be some
// way to know the member just doesn't exist. // way to know the member just doesn't exist.
translator.throwError(luaState, "unknown member name " + methodName); translator.throwError(luaState, "unknown member name " + methodName);
LuaCore.lua_pushnil(luaState);
KopiLua.Lua.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)
translator.push(luaState, false); translator.push(luaState, false);
return 2; return 2;
} }
/* /*
* Checks if a MemberInfo object is cached, returning it or null. * Checks if a MemberInfo object is cached, returning it or null.
*/ */
private object checkMemberCache(Hashtable memberCache, IReflect objType, string memberName) private object checkMemberCache(Hashtable memberCache, IReflect objType, string memberName)
{ {
Hashtable members = (Hashtable)memberCache[objType]; var members = (Hashtable)memberCache[objType];
if (members != null) return !members.IsNull() ? members[memberName] : null;
return members[memberName];
else
return null;
} }
/* /*
* Stores a MemberInfo object in the member cache. * Stores a MemberInfo object in the member cache.
*/ */
private void setMemberCache(Hashtable memberCache, IReflect objType, string memberName, object member) private void setMemberCache(Hashtable memberCache, IReflect objType, string memberName, object member)
{ {
Hashtable members = (Hashtable)memberCache[objType]; var members = (Hashtable)memberCache[objType];
if (members == null)
if(members.IsNull())
{ {
members = new Hashtable(); members = new Hashtable();
memberCache[objType] = members; memberCache[objType] = members;
} }
members[memberName] = member; members[memberName] = member;
} }
/* /*
* __newindex metafunction of CLR objects. Receives the object, * __newindex metafunction of CLR objects. Receives the object,
* 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(LuaCore.lua_State luaState)
{ {
object target = translator.getRawNetObject(luaState, 1); object target = translator.getRawNetObject(luaState, 1);
if (target == null)
if(target.IsNull())
{ {
translator.throwError(luaState, "trying to index and invalid object reference"); translator.throwError(luaState, "trying to index and invalid object reference");
return 0; return 0;
} }
Type type = target.GetType();
var type = target.GetType();
// 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 | BindingFlags.IgnoreCase, 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
// 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 && LuaCore.lua_isnumber(luaState, 2).ToBoolean())
{ {
int index = (int)KopiLua.Lua.lua_tonumber(luaState, 2); int index = (int)LuaCore.lua_tonumber(luaState, 2);
var 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());
arr.SetValue(val, index); arr.SetValue(val, index);
} }
else else
{ {
// Try to see if we have a this[] accessor // Try to see if we have a this[] accessor
MethodInfo setter = type.GetMethod("set_Item"); var setter = type.GetMethod("set_Item");
if (setter != null) if(!setter.IsNull())
{ {
ParameterInfo[] args = setter.GetParameters(); var args = setter.GetParameters();
Type valueType = args[1].ParameterType; var valueType = args[1].ParameterType;
// The new val ue the user specified // The new val ue the user specified
object val = translator.getAsType(luaState, 3, valueType); object val = translator.getAsType(luaState, 3, valueType);
var indexType = args[0].ParameterType;
Type indexType = args[0].ParameterType;
object index = translator.getAsType(luaState, 2, indexType); object index = translator.getAsType(luaState, 2, indexType);
object[] methodArgs = new object[2]; object[] methodArgs = new object[2];
...@@ -537,24 +551,22 @@ namespace LuaInterface ...@@ -537,24 +551,22 @@ namespace LuaInterface
// Just call the indexer - if out of bounds an exception will happen // Just call the indexer - if out of bounds an exception will happen
methodArgs[0] = index; methodArgs[0] = index;
methodArgs[1] = val; methodArgs[1] = val;
setter.Invoke(target, methodArgs); setter.Invoke(target, methodArgs);
} }
else else
{
translator.throwError(luaState, detailMessage); // Pass the original message from trySetMember because it is probably best translator.throwError(luaState, detailMessage); // Pass the original message from trySetMember because it is probably best
} }
} }
} catch(SEHException)
catch (SEHException)
{ {
// If we are seeing a C++ exception - this must actually be for Lua's private use. Let it handle it // If we are seeing a C++ exception - this must actually be for Lua's private use. Let it handle it
throw; throw;
} }
catch (Exception e) catch(Exception e)
{ {
ThrowError(luaState, e); ThrowError(luaState, e);
} }
return 0; return 0;
} }
...@@ -566,7 +578,7 @@ namespace LuaInterface ...@@ -566,7 +578,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(LuaCore.lua_State luaState, IReflect targetType, object target, BindingFlags bindingType, out string detailMessage)
{ {
detailMessage = null; // No error yet detailMessage = null; // No error yet
...@@ -574,27 +586,28 @@ namespace LuaInterface ...@@ -574,27 +586,28 @@ 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).ToLuaTypes() != LuaTypes.String) if(LuaCore.lua_type(luaState, 2).ToLuaTypes() != LuaTypes.String)
{ {
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 = LuaCore.lua_tostring(luaState, 2).ToString();
if (fieldName == null || fieldName.Length < 1 || !(char.IsLetter(fieldName[0]) || fieldName[0] == '_')) if(fieldName.IsNull() || fieldName.Length < 1 || !(char.IsLetter(fieldName[0]) || fieldName[0] == '_'))
{ {
detailMessage = "invalid property name"; detailMessage = "invalid property name";
return false; return false;
} }
// Find our member via reflection or the cache // Find our member via reflection or the cache
MemberInfo member = (MemberInfo)checkMemberCache(memberCache, targetType, fieldName); var member = (MemberInfo)checkMemberCache(memberCache, targetType, fieldName);
if (member == null) if(member.IsNull())
{ {
//CP: Removed NonPublic binding search and made case insensitive //CP: Removed NonPublic binding search and made case insensitive
MemberInfo[] members = targetType.GetMember(fieldName, bindingType | BindingFlags.Public | BindingFlags.IgnoreCase/*| BindingFlags.NonPublic*/); var 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];
setMemberCache(memberCache, targetType, fieldName, member); setMemberCache(memberCache, targetType, fieldName, member);
...@@ -606,10 +619,11 @@ namespace LuaInterface ...@@ -606,10 +619,11 @@ namespace LuaInterface
} }
} }
if (member.MemberType == MemberTypes.Field) if(member.MemberType == MemberTypes.Field)
{ {
FieldInfo field = (FieldInfo)member; var field = (FieldInfo)member;
object val = translator.getAsType(luaState, 3, field.FieldType); object val = translator.getAsType(luaState, 3, field.FieldType);
try try
{ {
field.SetValue(target, val); field.SetValue(target, val);
...@@ -618,13 +632,15 @@ namespace LuaInterface ...@@ -618,13 +632,15 @@ namespace LuaInterface
{ {
ThrowError(luaState, e); ThrowError(luaState, e);
} }
// We did a call // We did a call
return true; return true;
} }
else if (member.MemberType == MemberTypes.Property) else if(member.MemberType == MemberTypes.Property)
{ {
PropertyInfo property = (PropertyInfo)member; var property = (PropertyInfo)member;
object val = translator.getAsType(luaState, 3, property.PropertyType); object val = translator.getAsType(luaState, 3, property.PropertyType);
try try
{ {
property.SetValue(target, val, null); property.SetValue(target, val, null);
...@@ -633,6 +649,7 @@ namespace LuaInterface ...@@ -633,6 +649,7 @@ namespace LuaInterface
{ {
ThrowError(luaState, e); ThrowError(luaState, e);
} }
// We did a call // We did a call
return true; return true;
} }
...@@ -641,17 +658,16 @@ namespace LuaInterface ...@@ -641,17 +658,16 @@ namespace LuaInterface
return false; return false;
} }
/* /*
* 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(LuaCore.lua_State 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;
...@@ -662,12 +678,12 @@ namespace LuaInterface ...@@ -662,12 +678,12 @@ 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(LuaCore.lua_State 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; var te = e as TargetInvocationException;
if (te != null) if (!te.IsNull())
e = te.InnerException; e = te.InnerException;
translator.throwError(luaState, e); translator.throwError(luaState, e);
...@@ -676,162 +692,169 @@ namespace LuaInterface ...@@ -676,162 +692,169 @@ 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(LuaCore.lua_State 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.IsNull() || !(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); LuaCore.lua_pushnil(luaState);
return 1; return 1;
} }
else klass = (IReflect)obj; else
if (KopiLua.Lua.lua_isnumber(luaState, 2).ToBoolean()) klass = (IReflect)obj;
if(LuaCore.lua_isnumber(luaState, 2).ToBoolean())
{ {
int size = (int)KopiLua.Lua.lua_tonumber(luaState, 2); int size = (int)LuaCore.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 = LuaCore.lua_tostring(luaState, 2).ToString();
if (methodName == null)
if(methodName.IsNull())
{ {
KopiLua.Lua.lua_pushnil(luaState); LuaCore.lua_pushnil(luaState);
return 1; return 1;
} //CP: Ignore case } //CP: Ignore case
else return getMember(luaState, klass, null, methodName, BindingFlags.FlattenHierarchy | BindingFlags.Static | BindingFlags.IgnoreCase); 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(LuaCore.lua_State luaState)
{ {
IReflect target; IReflect target;
object obj = translator.getRawNetObject(luaState, 1); object obj = translator.getRawNetObject(luaState, 1);
if (obj == null || !(obj is IReflect))
if(obj.IsNull() || !(obj is IReflect))
{ {
translator.throwError(luaState, "trying to index an invalid type reference"); translator.throwError(luaState, "trying to index an invalid type reference");
return 0; return 0;
} }
else target = (IReflect)obj; else
target = (IReflect)obj;
return setMember(luaState, target, null, BindingFlags.FlattenHierarchy | BindingFlags.Static | BindingFlags.IgnoreCase); 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
* a constructor for the type. Returns nil if the constructor is not * a constructor for the type. Returns nil if the constructor is not
* found or if the arguments are invalid. Throws an error if the constructor * 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(LuaCore.lua_State luaState)
{ {
MethodCache validConstructor = new MethodCache(); var validConstructor = new MethodCache();
IReflect klass; IReflect klass;
object obj = translator.getRawNetObject(luaState, 1); object obj = translator.getRawNetObject(luaState, 1);
if (obj == null || !(obj is IReflect))
if(obj.IsNull() || !(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); LuaCore.lua_pushnil(luaState);
return 1; return 1;
} }
else klass = (IReflect)obj; else
KopiLua.Lua.lua_remove(luaState, 1); klass = (IReflect)obj;
ConstructorInfo[] constructors = klass.UnderlyingSystemType.GetConstructors();
foreach (ConstructorInfo constructor in constructors) LuaCore.lua_remove(luaState, 1);
var constructors = klass.UnderlyingSystemType.GetConstructors();
foreach(var constructor in constructors)
{ {
bool isConstructor = matchParameters(luaState, constructor, ref validConstructor); bool isConstructor = matchParameters(luaState, constructor, ref validConstructor);
if (isConstructor)
if(isConstructor)
{ {
try try
{ {
translator.push(luaState, constructor.Invoke(validConstructor.args)); translator.push(luaState, constructor.Invoke(validConstructor.args));
} }
catch (TargetInvocationException e) catch(TargetInvocationException e)
{ {
ThrowError(luaState, e); ThrowError(luaState, e);
KopiLua.Lua.lua_pushnil(luaState); LuaCore.lua_pushnil(luaState);
} }
catch catch
{ {
KopiLua.Lua.lua_pushnil(luaState); LuaCore.lua_pushnil(luaState);
} }
return 1; return 1;
} }
} }
string constructorName = (constructors.Length == 0) ? "unknown" : constructors[0].Name; string constructorName = (constructors.Length == 0) ? "unknown" : constructors[0].Name;
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)); LuaCore.lua_pushnil(luaState);
KopiLua.Lua.lua_pushnil(luaState);
return 1; return 1;
} }
/* /*
* Matches a method against its arguments in the Lua stack. Returns * Matches a method against its arguments in the Lua stack. Returns
* 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(LuaCore.lua_State luaState, MethodBase method, ref MethodCache methodCache)
{ {
ExtractValue extractValue; ExtractValue extractValue;
bool isMethod = true; bool isMethod = true;
ParameterInfo[] paramInfo = method.GetParameters(); var paramInfo = method.GetParameters();
int currentLuaParam = 1; int currentLuaParam = 1;
int nLuaParams = KopiLua.Lua.lua_gettop(luaState); int nLuaParams = LuaCore.lua_gettop(luaState);
ArrayList paramList = new ArrayList(); var paramList = new ArrayList();
List<int> outList = new List<int>(); var outList = new List<int>();
List<MethodArgs> argTypes = new List<MethodArgs>(); var argTypes = new List<MethodArgs>();
foreach (ParameterInfo currentNetParam in paramInfo)
{ foreach(var currentNetParam in paramInfo)
if (!currentNetParam.IsIn && currentNetParam.IsOut) // Skips out params
{ {
if(!currentNetParam.IsIn && currentNetParam.IsOut) // Skips out params
outList.Add(paramList.Add(null)); outList.Add(paramList.Add(null));
} else if(currentLuaParam > nLuaParams) // Adds optional parameters
else if (currentLuaParam > nLuaParams) // Adds optional parameters
{
if (currentNetParam.IsOptional)
{ {
if(currentNetParam.IsOptional)
paramList.Add(currentNetParam.DefaultValue); paramList.Add(currentNetParam.DefaultValue);
}
else else
{ {
isMethod = false; isMethod = false;
break; break;
} }
} }
else if (_IsTypeCorrect(luaState, currentLuaParam, currentNetParam, out extractValue)) // 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));
var 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)) else if(_IsParamsArray(luaState, currentLuaParam, currentNetParam, out extractValue))
{ {
object luaParamValue = extractValue(luaState, currentLuaParam); object luaParamValue = extractValue(luaState, currentLuaParam);
var paramArrayType = currentNetParam.ParameterType.GetElementType();
Type paramArrayType = currentNetParam.ParameterType.GetElementType();
Array paramArray; Array paramArray;
if (luaParamValue is LuaTable) if(luaParamValue is LuaTable)
{ {
LuaTable table = (LuaTable)luaParamValue; var table = (LuaTable)luaParamValue;
IDictionaryEnumerator tableEnumerator = table.GetEnumerator(); var tableEnumerator = table.GetEnumerator();
paramArray = Array.CreateInstance(paramArrayType, table.Values.Count); paramArray = Array.CreateInstance(paramArrayType, table.Values.Count);
tableEnumerator.Reset(); tableEnumerator.Reset();
int paramArrayIndex = 0; int paramArrayIndex = 0;
while(tableEnumerator.MoveNext()) while(tableEnumerator.MoveNext())
...@@ -847,35 +870,33 @@ namespace LuaInterface ...@@ -847,35 +870,33 @@ namespace LuaInterface
} }
int index = paramList.Add(paramArray); int index = paramList.Add(paramArray);
var methodArg = new MethodArgs();
MethodArgs methodArg = new MethodArgs();
methodArg.index = index; methodArg.index = index;
methodArg.extractValue = extractValue; methodArg.extractValue = extractValue;
methodArg.isParamsArray = true; methodArg.isParamsArray = true;
methodArg.paramsArrayType = paramArrayType; methodArg.paramsArrayType = paramArrayType;
argTypes.Add(methodArg); argTypes.Add(methodArg);
currentLuaParam++; currentLuaParam++;
} }
else if (currentNetParam.IsOptional) else if(currentNetParam.IsOptional)
{
paramList.Add(currentNetParam.DefaultValue); paramList.Add(currentNetParam.DefaultValue);
}
else // No match else // No match
{ {
isMethod = false; isMethod = false;
break; break;
} }
} }
if (currentLuaParam != nLuaParams + 1) // Number of parameters does not match
if(currentLuaParam != nLuaParams + 1) // Number of parameters does not match
isMethod = false; isMethod = false;
if (isMethod) if(isMethod)
{ {
methodCache.args = paramList.ToArray(); methodCache.args = paramList.ToArray();
methodCache.cachedMethod = method; methodCache.cachedMethod = method;
methodCache.outList = outList.ToArray(); methodCache.outList = outList.ToArray();
methodCache.argTypes = argTypes.ToArray(); methodCache.argTypes = argTypes.ToArray();
} }
return isMethod; return isMethod;
} }
...@@ -888,7 +909,7 @@ namespace LuaInterface ...@@ -888,7 +909,7 @@ namespace LuaInterface
/// <param name="currentNetParam"></param> /// <param name="currentNetParam"></param>
/// <param name="extractValue"></param> /// <param name="extractValue"></param>
/// <returns></returns> /// <returns></returns>
private bool _IsTypeCorrect(KopiLua.Lua.lua_State luaState, int currentLuaParam, ParameterInfo currentNetParam, out ExtractValue extractValue) private bool _IsTypeCorrect(LuaCore.lua_State luaState, int currentLuaParam, ParameterInfo currentNetParam, out ExtractValue extractValue)
{ {
try try
{ {
...@@ -902,7 +923,7 @@ namespace LuaInterface ...@@ -902,7 +923,7 @@ namespace LuaInterface
} }
} }
private bool _IsParamsArray(KopiLua.Lua.lua_State luaState, int currentLuaParam, ParameterInfo currentNetParam, out ExtractValue extractValue) private bool _IsParamsArray(LuaCore.lua_State luaState, int currentLuaParam, ParameterInfo currentNetParam, out ExtractValue extractValue)
{ {
extractValue = null; extractValue = null;
...@@ -912,9 +933,9 @@ namespace LuaInterface ...@@ -912,9 +933,9 @@ namespace LuaInterface
try try
{ {
luaType = KopiLua.Lua.lua_type(luaState, currentLuaParam).ToLuaTypes(); luaType = LuaCore.lua_type(luaState, currentLuaParam).ToLuaTypes();
} }
catch (Exception ex) catch(Exception ex)
{ {
Debug.WriteLine("Could not retrieve lua type while attempting to determine params Array Status."); Debug.WriteLine("Could not retrieve lua type while attempting to determine params Array Status.");
Debug.WriteLine(ex.Message); Debug.WriteLine(ex.Message);
...@@ -922,25 +943,25 @@ namespace LuaInterface ...@@ -922,25 +943,25 @@ namespace LuaInterface
return false; return false;
} }
if (luaType == LuaTypes.Table) if(luaType == LuaTypes.Table)
{ {
try try
{ {
extractValue = translator.typeChecker.getExtractor(typeof(LuaTable)); extractValue = translator.typeChecker.getExtractor(typeof(LuaTable));
} }
catch (Exception/* ex*/) catch(Exception/* ex*/)
{ {
Debug.WriteLine("An error occurred during an attempt to retrieve a LuaTable extractor while checking for params array status."); Debug.WriteLine("An error occurred during an attempt to retrieve a LuaTable extractor while checking for params array status.");
} }
if (extractValue != null) if(!extractValue.IsNull())
{ {
return true; return true;
} }
} }
else else
{ {
Type paramElementType = currentNetParam.ParameterType.GetElementType(); var paramElementType = currentNetParam.ParameterType.GetElementType();
try try
{ {
...@@ -951,7 +972,7 @@ namespace LuaInterface ...@@ -951,7 +972,7 @@ namespace LuaInterface
Debug.WriteLine(string.Format("An error occurred during an attempt to retrieve an extractor ({0}) while checking for params array status.", paramElementType.FullName)); 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) if(!extractValue.IsNull())
{ {
return true; return true;
} }
...@@ -959,7 +980,6 @@ namespace LuaInterface ...@@ -959,7 +980,6 @@ namespace LuaInterface
} }
Debug.WriteLine("Type wasn't Params object."); Debug.WriteLine("Type wasn't Params object.");
return false; return false;
} }
} }
......
/*
* This file is part of LuaInterface.
*
* Copyright (C) 2003-2005 Fabio Mascarenhas de Queiroz.
* Copyright (C) 2012 Megax <http://megax.yeahunter.hu/>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Diagnostics;
using System.Collections.Generic;
namespace LuaInterface.Method
{
/// <summary>
/// We keep track of what delegates we have auto attached to an event - to allow us to cleanly exit a LuaInterface session
/// </summary>
class EventHandlerContainer : IDisposable
{
private Dictionary<Delegate, RegisterEventHandler> dict = new Dictionary<Delegate, RegisterEventHandler>();
public void Add(Delegate handler, RegisterEventHandler eventInfo)
{
dict.Add(handler, eventInfo);
}
public void Remove(Delegate handler)
{
bool found = dict.Remove(handler);
Debug.Assert(found);
}
/// <summary>
/// Remove any still registered handlers
/// </summary>
public void Dispose()
{
foreach(KeyValuePair<Delegate, RegisterEventHandler> pair in dict)
pair.Value.RemovePending(pair.Key);
dict.Clear();
}
}
}
\ No newline at end of file
/*
* This file is part of LuaInterface.
*
* Copyright (C) 2003-2005 Fabio Mascarenhas de Queiroz.
* Copyright (C) 2012 Megax <http://megax.yeahunter.hu/>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
namespace LuaInterface.Method
{
/*
* Static helper methods for Lua tables acting as CLR objects.
*
* Author: Fabio Mascarenhas
* Version: 1.0
*/
public class LuaClassHelper
{
/*
* Gets the function called name from the provided table,
* returning null if it does not exist
*/
public static LuaFunction getTableFunction(LuaTable luaTable, string name)
{
object funcObj = luaTable.rawget(name);
if(funcObj is LuaFunction)
return (LuaFunction)funcObj;
else
return null;
}
/*
* Calls the provided function with the provided parameters
*/
public static object callFunction(LuaFunction function, object[] args, Type[] returnTypes, object[] inArgs, int[] outArgs)
{
// args is the return array of arguments, inArgs is the actual array
// of arguments passed to the function (with in parameters only), outArgs
// has the positions of out parameters
object returnValue;
int iRefArgs;
object[] returnValues = function.call(inArgs, returnTypes);
if(returnTypes[0] == typeof(void))
{
returnValue = null;
iRefArgs = 0;
}
else
{
returnValue = returnValues[0];
iRefArgs = 1;
}
for(int i = 0; i < outArgs.Length; i++)
{
args[outArgs[i]] = returnValues[iRefArgs];
iRefArgs++;
}
return returnValue;
}
}
}
\ No newline at end of file
/*
* This file is part of LuaInterface.
*
* Copyright (C) 2003-2005 Fabio Mascarenhas de Queiroz.
* Copyright (C) 2012 Megax <http://megax.yeahunter.hu/>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
namespace LuaInterface.Method
{
/*
* Wrapper class for Lua functions as delegates
* Subclasses with correct signatures are created
* at runtime.
*
* Author: Fabio Mascarenhas
* Version: 1.0
*/
public class LuaDelegate
{
public LuaFunction function;
public Type[] returnTypes;
public LuaDelegate()
{
function = null;
returnTypes = null;
}
public object callFunction(object[] args, object[] inArgs, int[] outArgs)
{
// args is the return array of arguments, inArgs is the actual array
// of arguments passed to the function (with in parameters only), outArgs
// has the positions of out parameters
object returnValue;
int iRefArgs;
object[] returnValues = function.call(inArgs, returnTypes);
if(returnTypes[0] == typeof(void))
{
returnValue = null;
iRefArgs = 0;
}
else
{
returnValue = returnValues[0];
iRefArgs = 1;
}
// Sets the value of out and ref parameters (from
// the values returned by the Lua function).
for(int i = 0; i < outArgs.Length; i++)
{
args[outArgs[i]] = returnValues[iRefArgs];
iRefArgs++;
}
return returnValue;
}
}
}
\ No newline at end of file
/*
* This file is part of LuaInterface.
*
* Copyright (C) 2003-2005 Fabio Mascarenhas de Queiroz.
* Copyright (C) 2012 Megax <http://megax.yeahunter.hu/>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
namespace LuaInterface.Method
{
/*
* Base wrapper class for Lua function event handlers.
* Subclasses that do actual event handling are created
* at runtime.
*
* Author: Fabio Mascarenhas
* Version: 1.0
*/
public class LuaEventHandler
{
public LuaFunction handler = null;
// CP: Fix provided by Ben Bryant for delegates with one param
// link: http://luaforge.net/forum/message.php?msg_id=9318
public void handleEvent(object[] args)
{
handler.Call(args);
}
//public void handleEvent(object sender,object data)
//{
// handler.call(new object[] { sender,data },new Type[0]);
//}
}
}
\ No newline at end of file
/*
* This file is part of LuaInterface.
*
* Copyright (C) 2003-2005 Fabio Mascarenhas de Queiroz.
* Copyright (C) 2012 Megax <http://megax.yeahunter.hu/>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Reflection;
using System.Collections.Generic;
using LuaInterface.Exceptions;
using LuaInterface.Extensions;
namespace LuaInterface.Method
{
using LuaCore = KopiLua.Lua;
/*
* Argument extraction with type-conversion function
*/
delegate object ExtractValue(LuaCore.lua_State luaState, int stackPos);
/*
* Wrapper class for methods/constructors accessed from Lua.
*
* Author: Fabio Mascarenhas
* Version: 1.0
*/
class LuaMethodWrapper
{
private ObjectTranslator _Translator;
private MethodBase _Method;
private MethodCache _LastCalledMethod = new MethodCache();
private string _MethodName;
private MemberInfo[] _Members;
private IReflect _TargetType;
private ExtractValue _ExtractTarget;
private object _Target;
private BindingFlags _BindingType;
/*
* Constructs the wrapper for a known MethodBase instance
*/
public LuaMethodWrapper(ObjectTranslator translator, object target, IReflect targetType, MethodBase method)
{
_Translator = translator;
_Target = target;
_TargetType = targetType;
if(!targetType.IsNull())
_ExtractTarget = translator.typeChecker.getExtractor(targetType);
_Method = method;
_MethodName = method.Name;
if(method.IsStatic)
_BindingType = BindingFlags.Static;
else
_BindingType = BindingFlags.Instance;
}
/*
* Constructs the wrapper for a known method name
*/
public LuaMethodWrapper(ObjectTranslator translator, IReflect targetType, string methodName, BindingFlags bindingType)
{
_Translator = translator;
_MethodName = methodName;
_TargetType = targetType;
if(!targetType.IsNull())
_ExtractTarget = translator.typeChecker.getExtractor(targetType);
_BindingType = bindingType;
//CP: Removed NonPublic binding search and added IgnoreCase
_Members = targetType.UnderlyingSystemType.GetMember(methodName, MemberTypes.Method, bindingType | BindingFlags.Public | BindingFlags.IgnoreCase/*|BindingFlags.NonPublic*/);
}
/// <summary>
/// Convert C# exceptions into Lua errors
/// </summary>
/// <returns>num of things on stack</returns>
/// <param name="e">null for no pending exception</param>
int SetPendingException(Exception e)
{
return _Translator.interpreter.SetPendingException(e);
}
/*
* Calls the method. Receives the arguments from the Lua stack
* and returns values in it.
*/
public int call(LuaCore.lua_State luaState)
{
var methodToCall = _Method;
object targetObject = _Target;
bool failedCall = true;
int nReturnValues = 0;
if(!LuaCore.lua_checkstack(luaState, 5).ToBoolean())
throw new LuaException("Lua stack overflow");
bool isStatic = (_BindingType & BindingFlags.Static) == BindingFlags.Static;
SetPendingException(null);
if(methodToCall.IsNull()) // Method from name
{
if(isStatic)
targetObject = null;
else
targetObject = _ExtractTarget(luaState, 1);
//LuaCore.lua_remove(luaState,1); // Pops the receiver
if(!_LastCalledMethod.cachedMethod.IsNull()) // Cached?
{
int numStackToSkip = isStatic ? 0 : 1; // If this is an instance invoe we will have an extra arg on the stack for the targetObject
int numArgsPassed = LuaCore.lua_gettop(luaState) - numStackToSkip;
if(numArgsPassed == _LastCalledMethod.argTypes.Length) // No. of args match?
{
if(!LuaCore.lua_checkstack(luaState, _LastCalledMethod.outList.Length + 6).ToBoolean())
throw new LuaException("Lua stack overflow");
try
{
for(int i = 0; i < _LastCalledMethod.argTypes.Length; i++)
{
if(_LastCalledMethod.argTypes[i].isParamsArray)
{
object luaParamValue = _LastCalledMethod.argTypes[i].extractValue(luaState, i + 1 + numStackToSkip);
var paramArrayType = _LastCalledMethod.argTypes[i].paramsArrayType;
Array paramArray;
if(luaParamValue is LuaTable)
{
var table = (LuaTable)luaParamValue;
paramArray = Array.CreateInstance(paramArrayType, table.Values.Count);
for(int x = 1; x <= table.Values.Count; x++)
paramArray.SetValue(Convert.ChangeType(table[x], paramArrayType), x - 1);
}
else
{
paramArray = Array.CreateInstance(paramArrayType, 1);
paramArray.SetValue(luaParamValue, 0);
}
_LastCalledMethod.args[_LastCalledMethod.argTypes[i].index] = paramArray;
}
else
{
_LastCalledMethod.args[_LastCalledMethod.argTypes[i].index] =
_LastCalledMethod.argTypes[i].extractValue(luaState, i + 1 + numStackToSkip);
}
if(_LastCalledMethod.args[_LastCalledMethod.argTypes[i].index] == null &&
!LuaCore.lua_isnil(luaState, i + 1 + numStackToSkip))
throw new LuaException("argument number " + (i + 1) + " is invalid");
}
if((_BindingType & BindingFlags.Static) == BindingFlags.Static)
_Translator.push(luaState, _LastCalledMethod.cachedMethod.Invoke(null, _LastCalledMethod.args));
else
{
if(_LastCalledMethod.cachedMethod.IsConstructor)
_Translator.push(luaState, ((ConstructorInfo)_LastCalledMethod.cachedMethod).Invoke(_LastCalledMethod.args));
else
_Translator.push(luaState, _LastCalledMethod.cachedMethod.Invoke(targetObject, _LastCalledMethod.args));
}
failedCall = false;
}
catch(TargetInvocationException e)
{
// Failure of method invocation
return SetPendingException(e.GetBaseException());
}
catch(Exception e)
{
if(_Members.Length == 1) // Is the method overloaded?
// No, throw error
return SetPendingException(e);
}
}
}
// Cache miss
if(failedCall)
{
// System.Diagnostics.Debug.WriteLine("cache miss on " + methodName);
// If we are running an instance variable, we can now pop the targetObject from the stack
if(!isStatic)
{
if(targetObject.IsNull())
{
_Translator.throwError(luaState, String.Format("instance method '{0}' requires a non null target object", _MethodName));
LuaCore.lua_pushnil(luaState);
return 1;
}
LuaCore.lua_remove(luaState, 1); // Pops the receiver
}
bool hasMatch = false;
string candidateName = null;
foreach(var member in _Members)
{
candidateName = member.ReflectedType.Name + "." + member.Name;
var m = (MethodInfo)member;
bool isMethod = _Translator.matchParameters(luaState, m, ref _LastCalledMethod);
if(isMethod)
{
hasMatch = true;
break;
}
}
if(!hasMatch)
{
string msg = (candidateName == null) ? "invalid arguments to method call" : ("invalid arguments to method: " + candidateName);
_Translator.throwError(luaState, msg);
LuaCore.lua_pushnil(luaState);
return 1;
}
}
}
else // Method from MethodBase instance
{
if(methodToCall.ContainsGenericParameters)
{
bool isMethod = _Translator.matchParameters(luaState, methodToCall, ref _LastCalledMethod);
if(methodToCall.IsGenericMethodDefinition)
{
//need to make a concrete type of the generic method definition
var typeArgs = new List<Type>();
foreach(object arg in _LastCalledMethod.args)
typeArgs.Add(arg.GetType());
var concreteMethod = (methodToCall as MethodInfo).MakeGenericMethod(typeArgs.ToArray());
_Translator.push(luaState, concreteMethod.Invoke(targetObject, _LastCalledMethod.args));
failedCall = false;
}
else if(methodToCall.ContainsGenericParameters)
{
_Translator.throwError(luaState, "unable to invoke method on generic class as the current method is an open generic method");
LuaCore.lua_pushnil(luaState);
return 1;
}
}
else
{
if(!methodToCall.IsStatic && !methodToCall.IsConstructor && targetObject == null)
{
targetObject = _ExtractTarget(luaState, 1);
LuaCore.lua_remove(luaState, 1); // Pops the receiver
}
if(!_Translator.matchParameters(luaState, methodToCall, ref _LastCalledMethod))
{
_Translator.throwError(luaState, "invalid arguments to method call");
LuaCore.lua_pushnil(luaState);
return 1;
}
}
}
if(failedCall)
{
if(!LuaCore.lua_checkstack(luaState, _LastCalledMethod.outList.Length + 6).ToBoolean())
throw new LuaException("Lua stack overflow");
try
{
if(isStatic)
_Translator.push(luaState, _LastCalledMethod.cachedMethod.Invoke(null, _LastCalledMethod.args));
else
{
if(_LastCalledMethod.cachedMethod.IsConstructor)
_Translator.push(luaState, ((ConstructorInfo)_LastCalledMethod.cachedMethod).Invoke(_LastCalledMethod.args));
else
_Translator.push(luaState, _LastCalledMethod.cachedMethod.Invoke(targetObject, _LastCalledMethod.args));
}
}
catch(TargetInvocationException e)
{
return SetPendingException(e.GetBaseException());
}
catch(Exception e)
{
return SetPendingException(e);
}
}
// Pushes out and ref return values
for(int index = 0; index < _LastCalledMethod.outList.Length; index++)
{
nReturnValues++;
//for(int i=0;i<lastCalledMethod.outList.Length;i++)
_Translator.push(luaState, _LastCalledMethod.args[_LastCalledMethod.outList[index]]);
}
//by isSingle 2010-09-10 11:26:31
//Desc:
// if not return void,we need add 1,
// or we will lost the function's return value
// when call dotnet function like "int foo(arg1,out arg2,out arg3)" in lua code
if(!_LastCalledMethod.IsReturnVoid && nReturnValues > 0)
nReturnValues++;
return nReturnValues < 1 ? 1 : nReturnValues;
}
}
}
\ No newline at end of file
/*
* This file is part of LuaInterface.
*
* Copyright (C) 2003-2005 Fabio Mascarenhas de Queiroz.
* Copyright (C) 2012 Megax <http://megax.yeahunter.hu/>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
namespace LuaInterface.Method
{
/*
* Parameter information
*/
struct MethodArgs
{
// Position of parameter
public int index;
// Type-conversion function
public ExtractValue extractValue;
public bool isParamsArray;
public Type paramsArrayType;
}
}
\ No newline at end of file
/*
* This file is part of LuaInterface.
*
* Copyright (C) 2003-2005 Fabio Mascarenhas de Queiroz.
* Copyright (C) 2012 Megax <http://megax.yeahunter.hu/>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Reflection;
using LuaInterface.Extensions;
namespace LuaInterface.Method
{
/*
* Cached method
*/
struct MethodCache
{
private MethodBase _cachedMethod;
public MethodBase cachedMethod
{
get
{
return _cachedMethod;
}
set
{
_cachedMethod = value;
var mi = value as MethodInfo;
if(!mi.IsNull())
IsReturnVoid = string.Compare(mi.ReturnType.Name, "System.Void", true) == 0;
}
}
public bool IsReturnVoid;
// List or arguments
public object[] args;
// Positions of out parameters
public int[] outList;
// Types of parameters
public MethodArgs[] argTypes;
}
}
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment