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 @@
using System;
using System.Reflection;
using System.Collections.Generic;
using LuaInterface.Method;
using LuaInterface.Extensions;
namespace LuaInterface
{
using LuaCore = KopiLua.Lua;
/*
* Type checking and conversion functions.
*
......@@ -84,9 +87,9 @@ namespace LuaInterface
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)
paramType = paramType.GetElementType();
......@@ -120,17 +123,17 @@ namespace LuaInterface
//;//an unsupported type was encountered
}
if(KopiLua.Lua.lua_isnumber(luaState, stackPos).ToBoolean())
if(LuaCore.lua_isnumber(luaState, stackPos).ToBoolean())
return extractValues[runtimeHandleValue];
if(paramType == typeof(bool))
{
if(KopiLua.Lua.lua_isboolean(luaState, stackPos))
if(LuaCore.lua_isboolean(luaState, stackPos))
return extractValues[runtimeHandleValue];
}
else if(paramType == typeof(string))
{
if(KopiLua.Lua.lua_isstring(luaState, stackPos).ToBoolean())
if(LuaCore.lua_isstring(luaState, stackPos).ToBoolean())
return extractValues[runtimeHandleValue];
else if(luatype == LuaTypes.Nil)
return extractNetObject; // kevinh - silently convert nil to a null string pointer
......@@ -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
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);
KopiLua.Lua.lua_settop(luaState, -2);
LuaCore.lua_settop(luaState, -2);
if(!obj.IsNull() && paramType.IsAssignableFrom(obj.GetType()))
return extractNetObject;
}
......@@ -186,156 +189,156 @@ namespace LuaInterface
* index stackPos as the desired type if it can, or null
* 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);
if(retVal == 0 && !KopiLua.Lua.lua_isnumber(luaState, stackPos).ToBoolean())
sbyte retVal = (sbyte)LuaCore.lua_tonumber(luaState, stackPos);
if(retVal == 0 && !LuaCore.lua_isnumber(luaState, stackPos).ToBoolean())
return null;
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);
if(retVal == 0 && !KopiLua.Lua.lua_isnumber(luaState, stackPos).ToBoolean())
byte retVal = (byte)LuaCore.lua_tonumber(luaState, stackPos);
if(retVal == 0 && !LuaCore.lua_isnumber(luaState, stackPos).ToBoolean())
return null;
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);
if(retVal == 0 && !KopiLua.Lua.lua_isnumber(luaState, stackPos).ToBoolean())
short retVal = (short)LuaCore.lua_tonumber(luaState, stackPos);
if(retVal == 0 && !LuaCore.lua_isnumber(luaState, stackPos).ToBoolean())
return null;
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);
if(retVal == 0 && !KopiLua.Lua.lua_isnumber(luaState, stackPos).ToBoolean())
ushort retVal = (ushort)LuaCore.lua_tonumber(luaState, stackPos);
if(retVal == 0 && !LuaCore.lua_isnumber(luaState, stackPos).ToBoolean())
return null;
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);
if(retVal == 0 && !KopiLua.Lua.lua_isnumber(luaState, stackPos).ToBoolean())
int retVal = (int)LuaCore.lua_tonumber(luaState, stackPos);
if(retVal == 0 && !LuaCore.lua_isnumber(luaState, stackPos).ToBoolean())
return null;
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);
if(retVal == 0 && !KopiLua.Lua.lua_isnumber(luaState, stackPos).ToBoolean())
uint retVal = (uint)LuaCore.lua_tonumber(luaState, stackPos);
if(retVal == 0 && !LuaCore.lua_isnumber(luaState, stackPos).ToBoolean())
return null;
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);
if(retVal == 0 && !KopiLua.Lua.lua_isnumber(luaState, stackPos).ToBoolean())
long retVal = (long)LuaCore.lua_tonumber(luaState, stackPos);
if(retVal == 0 && !LuaCore.lua_isnumber(luaState, stackPos).ToBoolean())
return null;
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);
if(retVal == 0 && !KopiLua.Lua.lua_isnumber(luaState, stackPos).ToBoolean())
ulong retVal = (ulong)LuaCore.lua_tonumber(luaState, stackPos);
if(retVal == 0 && !LuaCore.lua_isnumber(luaState, stackPos).ToBoolean())
return null;
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);
if(retVal == 0 && !KopiLua.Lua.lua_isnumber(luaState, stackPos).ToBoolean())
double retVal = LuaCore.lua_tonumber(luaState, stackPos);
if(retVal == 0 && !LuaCore.lua_isnumber(luaState, stackPos).ToBoolean())
return null;
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);
if(retVal == 0 && !KopiLua.Lua.lua_isnumber(luaState, stackPos).ToBoolean())
char retVal = (char)LuaCore.lua_tonumber(luaState, stackPos);
if(retVal == 0 && !LuaCore.lua_isnumber(luaState, stackPos).ToBoolean())
return null;
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);
if(retVal == 0 && !KopiLua.Lua.lua_isnumber(luaState, stackPos).ToBoolean())
float retVal = (float)LuaCore.lua_tonumber(luaState, stackPos);
if(retVal == 0 && !LuaCore.lua_isnumber(luaState, stackPos).ToBoolean())
return null;
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);
if(retVal == 0 && !KopiLua.Lua.lua_isnumber(luaState, stackPos).ToBoolean())
decimal retVal = (decimal)LuaCore.lua_tonumber(luaState, stackPos);
if(retVal == 0 && !LuaCore.lua_isnumber(luaState, stackPos).ToBoolean())
return null;
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();
if(retVal == string.Empty && !KopiLua.Lua.lua_isstring(luaState, stackPos).ToBoolean())
string retVal = LuaCore.lua_tostring(luaState, stackPos).ToString();
if(retVal == string.Empty && !LuaCore.lua_isstring(luaState, stackPos).ToBoolean())
return null;
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);
}
private object getAsFunction(KopiLua.Lua.lua_State luaState, int stackPos)
private object getAsFunction(LuaCore.lua_State luaState, int 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);
}
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))
{
KopiLua.Lua.lua_insert(luaState, stackPos);
KopiLua.Lua.lua_remove(luaState, stackPos+1);
LuaCore.lua_insert(luaState, stackPos);
LuaCore.lua_remove(luaState, stackPos+1);
}
else
KopiLua.Lua.lua_settop(luaState, -2);
LuaCore.lua_settop(luaState, -2);
}
}
......@@ -343,22 +346,22 @@ namespace LuaInterface
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);
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))
{
KopiLua.Lua.lua_insert(luaState, stackPos);
KopiLua.Lua.lua_remove(luaState, stackPos+1);
LuaCore.lua_insert(luaState, stackPos);
LuaCore.lua_remove(luaState, stackPos+1);
obj = translator.getNetObject(luaState, stackPos);
}
else
KopiLua.Lua.lua_settop(luaState, -2);
LuaCore.lua_settop(luaState, -2);
}
}
......
......@@ -29,6 +29,7 @@ using System.Reflection;
using System.Reflection.Emit;
using System.Collections;
using System.Collections.Generic;
using LuaInterface.Method;
namespace LuaInterface
{
......
......@@ -31,10 +31,14 @@ using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using LuaInterface.Event;
using LuaInterface.Method;
using LuaInterface.Exceptions;
using LuaInterface.Extensions;
namespace LuaInterface
{
using LuaCore = KopiLua.Lua;
/*
* Main class of LuaInterface
* Object-oriented wrapper to Lua API
......@@ -49,115 +53,162 @@ namespace LuaInterface
[CLSCompliant(true)]
public class Lua : IDisposable
{
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";
private /*readonly */ KopiLua.Lua.lua_State luaState;
#region lua debug functions
/// <summary>
/// Event that is raised when an exception occures during a hook call.
/// </summary>
/// <author>Reinhard Ostermeier</author>
public event EventHandler<HookExceptionEventArgs> HookException;
/// <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>
/// lua hook calback delegate
/// </summary>
/// <author>Reinhard Ostermeier</author>
private LuaCore.lua_Hook hookCallback = null;
#endregion
#region Globals auto-complete
private readonly List<string> globals = new List<string>();
private bool globalsSorted;
#endregion
private /*readonly */ LuaCore.lua_State luaState;
/// <summary>
/// True while a script is being executed
/// </summary>
public bool IsExecuting { get { return executing; } }
private LuaCore.lua_CFunction panicCallback;
private ObjectTranslator translator;
private KopiLua.Lua.lua_CFunction panicCallback;
/// <summary>
/// Used to ensure multiple .net threads all get serialized by this single lock for access to the lua stack/objects
/// </summary>
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()
{
luaState = KopiLua.Lua.luaL_newstate(); // steffenj: Lua 5.1.1 API change (lua_open is gone)
//KopiLua.Lua.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)
KopiLua.Lua.lua_pushstring(luaState, "LUAINTERFACE LOADED");
KopiLua.Lua.lua_pushboolean(luaState, 1);
KopiLua.Lua.lua_settable(luaState, (int)PseudoIndex.Registry);
KopiLua.Lua.lua_newtable(luaState);
KopiLua.Lua.lua_setglobal(luaState, "luanet");
KopiLua.Lua.lua_pushvalue(luaState, (int)PseudoIndex.Globals);
KopiLua.Lua.lua_getglobal(luaState, "luanet");
KopiLua.Lua.lua_pushstring(luaState, "getmetatable");
KopiLua.Lua.lua_getglobal(luaState, "getmetatable");
KopiLua.Lua.lua_settable(luaState, -3);
KopiLua.Lua.lua_replace(luaState, (int)PseudoIndex.Globals);
translator=new ObjectTranslator(this,luaState);
KopiLua.Lua.lua_replace(luaState, (int)PseudoIndex.Globals);
luaState = LuaCore.luaL_newstate(); // steffenj: Lua 5.1.1 API change (lua_open is gone)
//LuaCore.luaopen_base(luaState); // steffenj: luaopen_* no longer used
LuaCore.luaL_openlibs(luaState); // steffenj: Lua 5.1.1 API change (luaopen_base is gone, just open all libs right here)
LuaCore.lua_pushstring(luaState, "LUAINTERFACE LOADED");
LuaCore.lua_pushboolean(luaState, 1);
LuaCore.lua_settable(luaState, (int)PseudoIndex.Registry);
LuaCore.lua_newtable(luaState);
LuaCore.lua_setglobal(luaState, "luanet");
LuaCore.lua_pushvalue(luaState, (int)PseudoIndex.Globals);
LuaCore.lua_getglobal(luaState, "luanet");
LuaCore.lua_pushstring(luaState, "getmetatable");
LuaCore.lua_getglobal(luaState, "getmetatable");
LuaCore.lua_settable(luaState, -3);
LuaCore.lua_replace(luaState, (int)PseudoIndex.Globals);
translator = new ObjectTranslator(this, luaState);
LuaCore.lua_replace(luaState, (int)PseudoIndex.Globals);
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
panicCallback = new KopiLua.Lua.lua_CFunction(PanicCallback);
KopiLua.Lua.lua_atpanic(luaState, panicCallback);
panicCallback = new LuaCore.lua_CFunction(PanicCallback);
LuaCore.lua_atpanic(luaState, panicCallback);
//KopiLua.Lua.lua_atlock(luaState, lockCallback = new KopiLua.Lua.lua_CFunction(LockCallback));
//KopiLua.Lua.lua_atunlock(luaState, unlockCallback = new KopiLua.Lua.lua_CFunction(UnlockCallback));
//LuaCore.lua_atlock(luaState, lockCallback = new LuaCore.lua_CFunction(LockCallback));
//LuaCore.lua_atunlock(luaState, unlockCallback = new LuaCore.lua_CFunction(UnlockCallback));
}
private bool _StatePassed;
/*
* 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;
KopiLua.Lua.lua_pushstring(lState, "LUAINTERFACE LOADED");
KopiLua.Lua.lua_gettable(lState, (int)PseudoIndex.Registry);
LuaCore.lua_State lState = luaState;
LuaCore.lua_pushstring(lState, "LUAINTERFACE LOADED");
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");
}
else
{
KopiLua.Lua.lua_settop(lState,-2);
KopiLua.Lua.lua_pushstring(lState, "LUAINTERFACE LOADED");
KopiLua.Lua.lua_pushboolean(lState, 1);
KopiLua.Lua.lua_settable(lState, (int)PseudoIndex.Registry);
this.luaState=lState;
KopiLua.Lua.lua_pushvalue(lState, (int)PseudoIndex.Globals);
KopiLua.Lua.lua_getglobal(lState, "luanet");
KopiLua.Lua.lua_pushstring(lState, "getmetatable");
KopiLua.Lua.lua_getglobal(lState, "getmetatable");
KopiLua.Lua.lua_settable(lState, -3);
KopiLua.Lua.lua_replace(lState, (int)PseudoIndex.Globals);
translator=new ObjectTranslator(this, this.luaState);
KopiLua.Lua.lua_replace(lState, (int)PseudoIndex.Globals);
LuaCore.lua_settop(lState, -2);
LuaCore.lua_pushstring(lState, "LUAINTERFACE LOADED");
LuaCore.lua_pushboolean(lState, 1);
LuaCore.lua_settable(lState, (int)PseudoIndex.Registry);
this.luaState = lState;
LuaCore.lua_pushvalue(lState, (int)PseudoIndex.Globals);
LuaCore.lua_getglobal(lState, "luanet");
LuaCore.lua_pushstring(lState, "getmetatable");
LuaCore.lua_getglobal(lState, "getmetatable");
LuaCore.lua_settable(lState, -3);
LuaCore.lua_replace(lState, (int)PseudoIndex.Globals);
translator = new ObjectTranslator(this, this.luaState);
LuaCore.lua_replace(lState, (int)PseudoIndex.Globals);
LuaLib.luaL_dostring(lState, Lua.init_luanet); // steffenj: lua_dostring renamed to luaL_dostring
}
......@@ -167,157 +218,151 @@ namespace LuaInterface
/// <summary>
/// Called for each lua_lock call
/// </summary>
/// <param name="luaState"></param>
/// <param name = "luaState"></param>
/// Not yet used
int LockCallback(KopiLua.Lua.lua_State luaState)
/*int LockCallback(LuaCore.lua_State luaState)
{
// Monitor.Enter(luaLock);
return 0;
}
}*/
/// <summary>
/// Called for each lua_unlock call
/// </summary>
/// <param name="luaState"></param>
/// <param name = "luaState"></param>
/// Not yet used
int UnlockCallback(KopiLua.Lua.lua_State luaState)
/*int UnlockCallback(LuaCore.lua_State luaState)
{
// Monitor.Exit(luaLock);
return 0;
}
}*/
public void Close()
{
if (_StatePassed)
if(_StatePassed)
return;
////// if (luaState != KopiLua.Lua.lua_State.Zero)
if (luaState != null)
KopiLua.Lua.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
////// if(luaState != LuaCore.lua_State.Zero)
if(!luaState.IsNull())
LuaCore.lua_close(luaState);
//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 reason = String.Format("unprotected error in call to Lua API ({0})", 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})", LuaCore.lua_tostring(luaState, -1));
// lua_tostring(L, -1);
throw new LuaException(reason);
}
/// <summary>
/// Assuming we have a Lua error string sitting on the stack, throw a C# exception out to the user's app
/// </summary>
/// <exception cref="LuaScriptException">Thrown if the script caused an exception</exception>
void ThrowExceptionFromError(int oldTop)
/// <exception cref = "LuaScriptException">Thrown if the script caused an exception</exception>
private void ThrowExceptionFromError(int oldTop)
{
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)
LuaScriptException luaEx = err as LuaScriptException;
if (luaEx != null) throw luaEx;
var luaEx = err as LuaScriptException;
// A non-wrapped Lua error (best interpreted as a string) - wrap it and throw it
if (err == null) err = "Unknown Lua Error";
throw new LuaScriptException(err.ToString(), "");
}
if(!luaEx.IsNull())
throw luaEx;
// 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>
/// Convert C# exceptions into Lua errors
/// </summary>
/// <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)
{
Exception caughtExcept = e;
var caughtExcept = e;
if (caughtExcept != null)
if(!caughtExcept.IsNull())
{
translator.throwError(luaState, caughtExcept);
KopiLua.Lua.lua_pushnil(luaState);
LuaCore.lua_pushnil(luaState);
return 1;
}
else
return 0;
}
private bool executing;
/// <summary>
/// True while a script is being executed
/// </summary>
public bool IsExecuting { get { return executing; } }
/// <summary>
///
/// </summary>
/// <param name="chunk"></param>
/// <param name="name"></param>
/// <param name = "chunk"></param>
/// <param name = "name"></param>
/// <returns></returns>
public LuaFunction LoadString(string chunk, string name)
{
int oldTop = KopiLua.Lua.lua_gettop(luaState);
int oldTop = LuaCore.lua_gettop(luaState);
executing = true;
try
{
if (LuaLib.luaL_loadbuffer(luaState, chunk, name) != 0)
if(LuaLib.luaL_loadbuffer(luaState, chunk, name) != 0)
ThrowExceptionFromError(oldTop);
}
finally { executing = false; }
finally
{
executing = false;
}
LuaFunction result = translator.getFunction(luaState, -1);
var result = translator.getFunction(luaState, -1);
translator.popValues(luaState, oldTop);
return result;
}
/// <summary>
///
/// </summary>
/// <param name="fileName"></param>
/// <param name = "fileName"></param>
/// <returns></returns>
public LuaFunction LoadFile(string fileName)
{
int oldTop = KopiLua.Lua.lua_gettop(luaState);
if (KopiLua.Lua.luaL_loadfile(luaState, fileName) != 0)
int oldTop = LuaCore.lua_gettop(luaState);
if(LuaCore.luaL_loadfile(luaState, fileName) != 0)
ThrowExceptionFromError(oldTop);
LuaFunction result = translator.getFunction(luaState, -1);
var result = translator.getFunction(luaState, -1);
translator.popValues(luaState, oldTop);
return result;
}
/*
* Excutes a Lua chunk and returns all the chunk's return
* values in an array
*/
public object[] DoString(string chunk)
{
int oldTop=KopiLua.Lua.lua_gettop(luaState);
if (LuaLib.luaL_loadbuffer(luaState, chunk, "chunk") == 0)
int oldTop = LuaCore.lua_gettop(luaState);
if(LuaLib.luaL_loadbuffer(luaState, chunk, "chunk") == 0)
{
executing = true;
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);
else
ThrowExceptionFromError(oldTop);
}
finally { executing = false; }
finally
{
executing = false;
}
}
else
ThrowExceptionFromError(oldTop);
......@@ -328,23 +373,27 @@ namespace LuaInterface
/// <summary>
/// Executes a Lua chnk and returns all the chunk's return values in an array.
/// </summary>
/// <param name="chunk">Chunk to execute</param>
/// <param name="chunkName">Name to associate with the chunk</param>
/// <param name = "chunk">Chunk to execute</param>
/// <param name = "chunkName">Name to associate with the chunk</param>
/// <returns></returns>
public object[] DoString(string chunk, string chunkName)
{
int oldTop = KopiLua.Lua.lua_gettop(luaState);
int oldTop = LuaCore.lua_gettop(luaState);
executing = true;
if (LuaLib.luaL_loadbuffer(luaState, chunk, chunkName) == 0)
if(LuaLib.luaL_loadbuffer(luaState, chunk, chunkName) == 0)
{
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);
else
ThrowExceptionFromError(oldTop);
}
finally { executing = false; }
finally
{
executing = false;
}
}
else
ThrowExceptionFromError(oldTop);
......@@ -358,18 +407,23 @@ namespace LuaInterface
*/
public object[] DoFile(string fileName)
{
int oldTop=KopiLua.Lua.lua_gettop(luaState);
if(KopiLua.Lua.luaL_loadfile(luaState,fileName)==0)
int oldTop = LuaCore.lua_gettop(luaState);
if(LuaCore.luaL_loadfile(luaState, fileName) == 0)
{
executing = true;
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);
else
ThrowExceptionFromError(oldTop);
}
finally { executing = false; }
finally
{
executing = false;
}
}
else
ThrowExceptionFromError(oldTop);
......@@ -386,40 +440,44 @@ namespace LuaInterface
{
get
{
object returnValue=null;
int oldTop=KopiLua.Lua.lua_gettop(luaState);
string[] path=fullPath.Split(new char[] { '.' });
KopiLua.Lua.lua_getglobal(luaState,path[0]);
returnValue=translator.getObject(luaState,-1);
object returnValue = null;
int oldTop = LuaCore.lua_gettop(luaState);
string[] path = fullPath.Split(new char[] { '.' });
LuaCore.lua_getglobal(luaState, path[0]);
returnValue = translator.getObject(luaState, -1);
if(path.Length>1)
{
string[] remainingPath=new string[path.Length-1];
Array.Copy(path,1,remainingPath,0,path.Length-1);
returnValue=getObject(remainingPath);
string[] remainingPath = new string[path.Length-1];
Array.Copy(path, 1, remainingPath, 0, path.Length-1);
returnValue = getObject(remainingPath);
}
KopiLua.Lua.lua_settop(luaState,oldTop);
LuaCore.lua_settop(luaState, oldTop);
return returnValue;
}
set
{
int oldTop=KopiLua.Lua.lua_gettop(luaState);
string[] path=fullPath.Split(new char[] { '.' });
if(path.Length==1)
int oldTop = LuaCore.lua_gettop(luaState);
string[] path = fullPath.Split(new char[] { '.' });
if(path.Length == 1)
{
translator.push(luaState,value);
KopiLua.Lua.lua_setglobal(luaState,fullPath);
translator.push(luaState, value);
LuaCore.lua_setglobal(luaState, fullPath);
}
else
{
KopiLua.Lua.lua_getglobal(luaState,path[0]);
string[] remainingPath=new string[path.Length-1];
Array.Copy(path,1,remainingPath,0,path.Length-1);
setObject(remainingPath,value);
LuaCore.lua_getglobal(luaState, path[0]);
string[] remainingPath = new string[path.Length-1];
Array.Copy(path, 1, remainingPath, 0, path.Length-1);
setObject(remainingPath, value);
}
KopiLua.Lua.lua_settop(luaState,oldTop);
LuaCore.lua_settop(luaState, oldTop);
// Globals auto-complete
if (value == null)
if(value.IsNull())
{
// Remove now obsolete entries
globals.Remove(fullPath);
......@@ -427,56 +485,34 @@ namespace LuaInterface
else
{
// Add new entries
if (!globals.Contains(fullPath))
if(!globals.Contains(fullPath))
registerGlobal(fullPath, value.GetType(), 0);
}
}
}
#region Globals auto-complete
private readonly List<string> globals = new List<string>();
private bool globalsSorted;
/// <summary>
/// An alphabetically sorted list of all globals (objects, methods, etc.) externally added to this Lua instance
/// Adds an entry to <see cref = "globals"/> (recursivley handles 2 levels of members)
/// </summary>
/// <remarks>Members of globals are also listed. The formatting is optimized for text input auto-completion.</remarks>
public IEnumerable<string> Globals
{
get
{
// Only sort list when necessary
if (!globalsSorted)
{
globals.Sort();
globalsSorted = true;
}
return globals;
}
}
/// <summary>
/// Adds an entry to <see cref="globals"/> (recursivley handles 2 levels of members)
/// </summary>
/// <param name="path">The index accessor path ot the entry</param>
/// <param name="type">The type of the entry</param>
/// <param name="recursionCounter">How deep have we gone with recursion?</param>
/// <param name = "path">The index accessor path ot the entry</param>
/// <param name = "type">The type of the entry</param>
/// <param name = "recursionCounter">How deep have we gone with recursion?</param>
private void registerGlobal(string path, Type type, int recursionCounter)
{
// If the type is a global method, list it directly
if (type == typeof(KopiLua.Lua.lua_CFunction))
if(type == typeof(LuaCore.lua_CFunction))
{
// Format for easy method invocation
globals.Add(path + "(");
}
// If the type is a class or an interface and recursion hasn't been running too long, list the members
else if ((type.IsClass || type.IsInterface) && type != typeof(string) && recursionCounter < 2)
else if((type.IsClass || type.IsInterface) && type != typeof(string) && recursionCounter < 2)
{
#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
(method.GetCustomAttributes(typeof(LuaHideAttribute), false).Length == 0) &&
(method.GetCustomAttributes(typeof(LuaGlobalAttribute), false).Length == 0) &&
......@@ -491,16 +527,17 @@ namespace LuaInterface
{
// Format for easy method invocation
string command = path + ":" + method.Name + "(";
if (method.GetParameters().Length == 0) command += ")";
if(method.GetParameters().Length == 0) command += ")";
globals.Add(command);
}
}
#endregion
#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
(field.GetCustomAttributes(typeof(LuaHideAttribute), false).Length == 0) &&
(field.GetCustomAttributes(typeof(LuaGlobalAttribute), false).Length == 0))
......@@ -512,9 +549,9 @@ namespace LuaInterface
#endregion
#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
(property.GetCustomAttributes(typeof(LuaHideAttribute), false).Length == 0) &&
(property.GetCustomAttributes(typeof(LuaGlobalAttribute), false).Length == 0)
......@@ -527,8 +564,8 @@ namespace LuaInterface
}
#endregion
}
// Otherwise simply add the element to the list
else globals.Add(path);
else
globals.Add(path); // Otherwise simply add the element to the list
// List will need to be sorted on next access
globalsSorted = false;
......@@ -541,16 +578,21 @@ namespace LuaInterface
*/
internal object getObject(string[] remainingPath)
{
object returnValue=null;
for(int i=0;i<remainingPath.Length;i++)
object returnValue = null;
for(int i = 0; i < remainingPath.Length; i++)
{
KopiLua.Lua.lua_pushstring(luaState,remainingPath[i]);
KopiLua.Lua.lua_gettable(luaState,-2);
returnValue=translator.getObject(luaState,-1);
if(returnValue==null) break;
LuaCore.lua_pushstring(luaState, remainingPath[i]);
LuaCore.lua_gettable(luaState, -2);
returnValue = translator.getObject(luaState, -1);
if(returnValue.IsNull())
break;
}
return returnValue;
}
/*
* Gets a numeric global variable
*/
......@@ -558,6 +600,7 @@ namespace LuaInterface
{
return (double)this[fullPath];
}
/*
* Gets a string global variable
*/
......@@ -565,6 +608,7 @@ namespace LuaInterface
{
return (string)this[fullPath];
}
/*
* Gets a table global variable
*/
......@@ -572,131 +616,145 @@ namespace LuaInterface
{
return (LuaTable)this[fullPath];
}
/*
* Gets a table global variable as an object implementing
* the interfaceType interface
*/
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
*/
public LuaFunction GetFunction(string 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 KopiLua.Lua.lua_CFunction ? new LuaFunction((KopiLua.Lua.lua_CFunction)obj,this) : /*(LuaFunction)*/new LuaFunction(obj.GetHashCode(), this));
object obj = this[fullPath];
return (obj is LuaCore.lua_CFunction ? new LuaFunction((LuaCore.lua_CFunction)obj, this) : (LuaFunction)obj);
//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
* 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,
* 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);
}
/*
* Calls the object as a function with the provided arguments and
* casting returned values to the types in returnTypes before returning
* 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 oldTop=KopiLua.Lua.lua_gettop(luaState);
if(!KopiLua.Lua.lua_checkstack(luaState,args.Length+6).ToBoolean())
int nArgs = 0;
int oldTop = LuaCore.lua_gettop(luaState);
if(!LuaCore.lua_checkstack(luaState, args.Length+6).ToBoolean())
throw new LuaException("Lua stack overflow");
translator.push(luaState,function);
if(args!=null)
{
nArgs=args.Length;
for(int i=0;i<args.Length;i++)
translator.push(luaState, function);
if(!args.IsNull())
{
translator.push(luaState,args[i]);
}
nArgs = args.Length;
for(int i = 0; i < args.Length; i++)
translator.push(luaState, args[i]);
}
executing = true;
try
{
int error = KopiLua.Lua.lua_pcall(luaState, nArgs, -1, 0);
if (error != 0)
int error = LuaCore.lua_pcall(luaState, nArgs, -1, 0);
if(error != 0)
ThrowExceptionFromError(oldTop);
}
finally { executing = false; }
finally
{
executing = false;
}
if(returnTypes != null)
return translator.popValues(luaState,oldTop,returnTypes);
else
return translator.popValues(luaState, oldTop);
return !returnTypes.IsNull() ? translator.popValues(luaState, oldTop, returnTypes) : translator.popValues(luaState, oldTop);
}
/*
* Navigates a table to set the value of one of its fields
*/
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]);
KopiLua.Lua.lua_gettable(luaState,-2);
LuaCore.lua_pushstring(luaState, remainingPath[i]);
LuaCore.lua_gettable(luaState, -2);
}
KopiLua.Lua.lua_pushstring(luaState,remainingPath[remainingPath.Length-1]);
translator.push(luaState,val);
KopiLua.Lua.lua_settable(luaState,-3);
LuaCore.lua_pushstring(luaState, remainingPath[remainingPath.Length-1]);
translator.push(luaState, val);
LuaCore.lua_settable(luaState, -3);
}
/*
* Creates a new table as a global variable or as a field
* inside an existing table
*/
public void NewTable(string fullPath)
{
string[] path=fullPath.Split(new char[] { '.' });
int oldTop=KopiLua.Lua.lua_gettop(luaState);
if(path.Length==1)
string[] path = fullPath.Split(new char[] { '.' });
int oldTop = LuaCore.lua_gettop(luaState);
if(path.Length == 1)
{
KopiLua.Lua.lua_newtable(luaState);
KopiLua.Lua.lua_setglobal(luaState,fullPath);
LuaCore.lua_newtable(luaState);
LuaCore.lua_setglobal(luaState, fullPath);
}
else
{
KopiLua.Lua.lua_getglobal(luaState,path[0]);
for(int i=1; i<path.Length-1;i++)
LuaCore.lua_getglobal(luaState, path[0]);
for(int i = 1; i < path.Length-1; i++)
{
KopiLua.Lua.lua_pushstring(luaState,path[i]);
KopiLua.Lua.lua_gettable(luaState,-2);
LuaCore.lua_pushstring(luaState, path[i]);
LuaCore.lua_gettable(luaState, -2);
}
KopiLua.Lua.lua_pushstring(luaState,path[path.Length-1]);
KopiLua.Lua.lua_newtable(luaState);
KopiLua.Lua.lua_settable(luaState,-3);
LuaCore.lua_pushstring(luaState, path[path.Length-1]);
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)
{
ListDictionary dict = new ListDictionary();
int oldTop = KopiLua.Lua.lua_gettop(luaState);
var dict = new ListDictionary();
int oldTop = LuaCore.lua_gettop(luaState);
translator.push(luaState, table);
KopiLua.Lua.lua_pushnil(luaState);
while (KopiLua.Lua.lua_next(luaState, -2) != 0)
LuaCore.lua_pushnil(luaState);
while(LuaCore.lua_next(luaState, -2) != 0)
{
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;
}
......@@ -706,26 +764,19 @@ namespace LuaInterface
*/
#region lua debug functions
/// <summary>
/// lua hook calback delegate
/// </summary>
/// <author>Reinhard Ostermeier</author>
private KopiLua.Lua.lua_Hook hookCallback = null;
/// <summary>
/// Activates the debug hook
/// </summary>
/// <param name="mask">Mask</param>
/// <param name="count">Count</param>
/// <param name = "mask">Mask</param>
/// <param name = "count">Count</param>
/// <returns>see lua docs. -1 if hook is already set</returns>
/// <author>Reinhard Ostermeier</author>
/*public int SetDebugHook(EventMasks mask, int count)
{
if (hookCallback == null)
if(hookCallback.IsNull())
{
hookCallback = new KopiLua.Lua.lua_Hook(DebugHookCallback);
return KopiLua.Lua.lua_sethook(luaState, hookCallback, (int)mask, count);
hookCallback = new LuaCore.lua_Hook(DebugHookCallback);
return LuaCore.lua_sethook(luaState, hookCallback, (int)mask, count);
}
return -1;
}*/
......@@ -738,7 +789,7 @@ namespace LuaInterface
public int RemoveDebugHook()
{
hookCallback = null;
return KopiLua.Lua.lua_sethook(luaState, null, 0, 0);
return LuaCore.lua_sethook(luaState, null, 0, 0);
}
/// <summary>
......@@ -748,7 +799,7 @@ namespace LuaInterface
/// <author>Reinhard Ostermeier</author>
public EventMasks GetHookMask()
{
return (EventMasks)KopiLua.Lua.lua_gethookmask(luaState);
return (EventMasks)LuaCore.lua_gethookmask(luaState);
}
/// <summary>
......@@ -758,24 +809,24 @@ namespace LuaInterface
/// <author>Reinhard Ostermeier</author>
public int GetHookCount()
{
return KopiLua.Lua.lua_gethookcount(luaState);
return LuaCore.lua_gethookcount(luaState);
}
/// <summary>
/// Gets the stack entry on a given level
/// </summary>
/// <param name="level">level</param>
/// <param name="luaDebug">lua debug structure</param>
/// <param name = "level">level</param>
/// <param name = "luaDebug">lua debug structure</param>
/// <returns>Returns true if level was allowed, false if level was invalid.</returns>
/// <author>Reinhard Ostermeier</author>
/*public bool GetStack(int level, out LuaDebug luaDebug)
{
luaDebug = new LuaDebug();
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);
try
{
return KopiLua.Lua.lua_getstack(luaState, level, ld) != 0;
return LuaCore.lua_getstack(luaState, level, ld) != 0;
}
finally
{
......@@ -787,17 +838,17 @@ namespace LuaInterface
/// <summary>
/// Gets info (see lua docs)
/// </summary>
/// <param name="what">what (see lua docs)</param>
/// <param name="luaDebug">lua debug structure</param>
/// <param name = "what">what (see lua docs)</param>
/// <param name = "luaDebug">lua debug structure</param>
/// <returns>see lua docs</returns>
/// <author>Reinhard Ostermeier</author>
/*public int GetInfo(String what, ref LuaDebug luaDebug)
{
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);
try
{
return KopiLua.Lua.lua_getinfo(luaState, what, ld);
return LuaCore.lua_getinfo(luaState, what, ld);
}
finally
{
......@@ -809,17 +860,17 @@ namespace LuaInterface
/// <summary>
/// Gets local (see lua docs)
/// </summary>
/// <param name="luaDebug">lua debug structure</param>
/// <param name="n">see lua docs</param>
/// <param name = "luaDebug">lua debug structure</param>
/// <param name = "n">see lua docs</param>
/// <returns>see lua docs</returns>
/// <author>Reinhard Ostermeier</author>
/*public String GetLocal(LuaDebug luaDebug, int n)
{
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);
try
{
return KopiLua.Lua.lua_getlocal(luaState, ld, n);
return LuaCore.lua_getlocal(luaState, ld, n);
}
finally
{
......@@ -830,17 +881,17 @@ namespace LuaInterface
/// <summary>
/// Sets local (see lua docs)
/// </summary>
/// <param name="luaDebug">lua debug structure</param>
/// <param name="n">see lua docs</param>
/// <param name = "luaDebug">lua debug structure</param>
/// <param name = "n">see lua docs</param>
/// <returns>see lua docs</returns>
/// <author>Reinhard Ostermeier</author>
/*public String SetLocal(LuaDebug luaDebug, int n)
{
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);
try
{
return KopiLua.Lua.lua_setlocal(luaState, ld, n);
return LuaCore.lua_setlocal(luaState, ld, n);
}
finally
{
......@@ -851,40 +902,40 @@ namespace LuaInterface
/// <summary>
/// Gets up value (see lua docs)
/// </summary>
/// <param name="funcindex">see lua docs</param>
/// <param name="n">see lua docs</param>
/// <param name = "funcindex">see lua docs</param>
/// <param name = "n">see lua docs</param>
/// <returns>see lua docs</returns>
/// <author>Reinhard Ostermeier</author>
public String GetUpValue(int funcindex, int n)
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>
/// Sets up value (see lua docs)
/// </summary>
/// <param name="funcindex">see lua docs</param>
/// <param name="n">see lua docs</param>
/// <param name = "funcindex">see lua docs</param>
/// <param name = "n">see lua docs</param>
/// <returns>see lua docs</returns>
/// <author>Reinhard Ostermeier</author>
public String SetUpValue(int funcindex, int n)
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>
/// Delegate that is called on lua hook callback
/// </summary>
/// <param name="luaState">lua state</param>
/// <param name="luaDebug">Pointer to LuaDebug (lua_debug) structure</param>
/// <param name = "luaState">lua state</param>
/// <param name = "luaDebug">Pointer to LuaDebug (lua_debug) structure</param>
/// <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
{
LuaDebug ld = (LuaDebug)System.Runtime.InteropServices.Marshal.PtrToStructure(luaDebug, typeof(LuaDebug));
EventHandler<DebugHookEventArgs> temp = DebugHook;
if (temp != null)
if(temp != null)
{
temp(this, new DebugHookEventArgs(ld));
}
......@@ -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)
{
EventHandler<HookExceptionEventArgs> temp = HookException;
if (temp != null)
{
var temp = HookException;
if(!temp.IsNull())
temp(this, e);
}
}
/// <summary>
/// Event when lua hook callback is called
/// </summary>
/// <remarks>
/// Is only raised if SetDebugHook is called before.
/// </remarks>
/// <author>Reinhard Ostermeier</author>
public event EventHandler<DebugHookEventArgs> DebugHook;
/// <summary>
/// Pops a value from the lua stack.
......@@ -925,145 +960,143 @@ namespace LuaInterface
/// <author>Reinhard Ostermeier</author>
public object Pop()
{
int top = KopiLua.Lua.lua_gettop(luaState);
int top = LuaCore.lua_gettop(luaState);
return translator.popValues(luaState, top - 1)[0];
}
/// <summary>
/// Pushes a value onto the lua stack.
/// </summary>
/// <param name="value">Value to push.</param>
/// <param name = "value">Value to push.</param>
/// <author>Reinhard Ostermeier</author>
public void Push(object value)
{
translator.push(luaState, value);
}
#endregion
internal void dispose(int reference)
{
///////////// if (luaState != KopiLua.Lua.lua_State.Zero)
if (luaState != null) //Fix submitted by Qingrui Li
LuaLib.lua_unref(luaState,reference);
///////////// if(luaState != LuaCore.lua_State.Zero)
if(!luaState.IsNull()) //Fix submitted by Qingrui Li
LuaLib.lua_unref(luaState, reference);
}
/*
* Gets a field of the table corresponding to the provided reference
* using rawget (do not use metatables)
*/
internal object rawGetObject(int reference,string field)
{
int oldTop=KopiLua.Lua.lua_gettop(luaState);
LuaLib.lua_getref(luaState,reference);
KopiLua.Lua.lua_pushstring(luaState,field);
KopiLua.Lua.lua_rawget(luaState,-2);
object obj=translator.getObject(luaState,-1);
KopiLua.Lua.lua_settop(luaState,oldTop);
internal object rawGetObject(int reference, string field)
{
int oldTop = LuaCore.lua_gettop(luaState);
LuaLib.lua_getref(luaState, reference);
LuaCore.lua_pushstring(luaState, field);
LuaCore.lua_rawget(luaState, -2);
object obj = translator.getObject(luaState, -1);
LuaCore.lua_settop(luaState, oldTop);
return obj;
}
/*
* 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);
LuaLib.lua_getref(luaState,reference);
object returnValue=getObject(field.Split(new char[] {'.'}));
KopiLua.Lua.lua_settop(luaState,oldTop);
int oldTop = LuaCore.lua_gettop(luaState);
LuaLib.lua_getref(luaState, reference);
object returnValue = getObject(field.Split(new char[] {'.'}));
LuaCore.lua_settop(luaState, oldTop);
return returnValue;
}
/*
* Gets a numeric field of the table or userdata corresponding the the provided reference
*/
internal object getObject(int reference,object field)
{
int oldTop=KopiLua.Lua.lua_gettop(luaState);
LuaLib.lua_getref(luaState,reference);
translator.push(luaState,field);
KopiLua.Lua.lua_gettable(luaState,-2);
object returnValue=translator.getObject(luaState,-1);
KopiLua.Lua.lua_settop(luaState,oldTop);
internal object getObject(int reference, object field)
{
int oldTop = LuaCore.lua_gettop(luaState);
LuaLib.lua_getref(luaState, reference);
translator.push(luaState, field);
LuaCore.lua_gettable(luaState, -2);
object returnValue = translator.getObject(luaState, -1);
LuaCore.lua_settop(luaState, oldTop);
return returnValue;
}
/*
* Sets a field of the table or userdata corresponding the the provided reference
* to the provided value
*/
internal void setObject(int reference, string field, object val)
{
int oldTop=KopiLua.Lua.lua_gettop(luaState);
LuaLib.lua_getref(luaState,reference);
setObject(field.Split(new char[] {'.'}),val);
KopiLua.Lua.lua_settop(luaState,oldTop);
int oldTop = LuaCore.lua_gettop(luaState);
LuaLib.lua_getref(luaState, reference);
setObject(field.Split(new char[] {'.'}), val);
LuaCore.lua_settop(luaState, oldTop);
}
/*
* Sets a numeric field of the table or userdata corresponding the the provided reference
* to the provided value
*/
internal void setObject(int reference, object field, object val)
{
int oldTop=KopiLua.Lua.lua_gettop(luaState);
LuaLib.lua_getref(luaState,reference);
translator.push(luaState,field);
translator.push(luaState,val);
KopiLua.Lua.lua_settable(luaState,-3);
KopiLua.Lua.lua_settop(luaState,oldTop);
int oldTop = LuaCore.lua_gettop(luaState);
LuaLib.lua_getref(luaState, reference);
translator.push(luaState, field);
translator.push(luaState, val);
LuaCore.lua_settable(luaState, -3);
LuaCore.lua_settop(luaState, oldTop);
}
/*
* Registers an object's method as a Lua function (global or table field)
* 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
int oldTop = KopiLua.Lua.lua_gettop(luaState);
LuaMethodWrapper wrapper=new LuaMethodWrapper(translator,target,function.DeclaringType,function);
translator.push(luaState,new KopiLua.Lua.lua_CFunction(wrapper.call));
this[path]=translator.getObject(luaState,-1);
LuaFunction f = GetFunction(path);
KopiLua.Lua.lua_settop(luaState, oldTop);
int oldTop = LuaCore.lua_gettop(luaState);
var wrapper = new LuaMethodWrapper(translator, target, function.DeclaringType, function);
translator.push(luaState, new LuaCore.lua_CFunction(wrapper.call));
this[path] = translator.getObject(luaState, -1);
var f = GetFunction(path);
LuaCore.lua_settop(luaState, oldTop);
return f;
}
/*
* Compares the two values referenced by ref1 and ref2 for equality
*/
internal bool compareRef(int ref1, int ref2)
{
int top=KopiLua.Lua.lua_gettop(luaState);
LuaLib.lua_getref(luaState,ref1);
LuaLib.lua_getref(luaState,ref2);
int equal=KopiLua.Lua.lua_equal(luaState,-1,-2);
KopiLua.Lua.lua_settop(luaState,top);
return (equal!=0);
int top = LuaCore.lua_gettop(luaState);
LuaLib.lua_getref(luaState, ref1);
LuaLib.lua_getref(luaState, ref2);
int equal = LuaCore.lua_equal(luaState, -1, -2);
LuaCore.lua_settop(luaState, top);
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
public virtual void Dispose()
{
if (translator != null)
if(!translator.IsNull())
{
translator.pendingEvents.Dispose();
translator = null;
}
this.Close();
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
}
#endregion
}
}
\ No newline at end of file
......@@ -24,8 +24,8 @@
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.Generic;
namespace LuaInterface
{
......@@ -51,13 +51,14 @@ namespace LuaInterface
public virtual void Dispose(bool disposeManagedResources)
{
if (!_Disposed)
if(!_Disposed)
{
if (disposeManagedResources)
if(disposeManagedResources)
{
if (_Reference != 0)
if(_Reference != 0)
_Interpreter.dispose(_Reference);
}
_Interpreter = null;
_Disposed = true;
}
......@@ -65,12 +66,13 @@ namespace LuaInterface
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);
}
else return false;
else
return false;
}
public override int GetHashCode()
......
......@@ -29,9 +29,11 @@ using System.Collections.Generic;
namespace LuaInterface
{
using LuaCore = KopiLua.Lua;
public class LuaFunction : LuaBase
{
internal KopiLua.Lua.lua_CFunction function;
internal LuaCore.lua_CFunction function;
public LuaFunction(int reference, Lua interpreter)
{
......@@ -40,7 +42,7 @@ namespace LuaInterface
_Interpreter = interpreter;
}
public LuaFunction(KopiLua.Lua.lua_CFunction function, Lua interpreter)
public LuaFunction(LuaCore.lua_CFunction function, Lua interpreter)
{
_Reference = 0;
this.function = function;
......@@ -55,6 +57,7 @@ namespace LuaInterface
{
return _Interpreter.callFunction(this, args, returnTypes);
}
/*
* Calls the function and returns its return values inside
* an array
......@@ -63,39 +66,41 @@ namespace LuaInterface
{
return _Interpreter.callFunction(this, args);
}
/*
* 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);
else
_Interpreter.pushCSFunction(function);
}
public override string ToString()
{
return "function";
}
public override bool Equals(object o)
{
if (o is LuaFunction)
if(o is LuaFunction)
{
LuaFunction l = (LuaFunction)o;
if (this._Reference != 0 && l._Reference != 0)
var l = (LuaFunction)o;
if(this._Reference != 0 && l._Reference != 0)
return _Interpreter.compareRef(l._Reference, this._Reference);
else
return this.function == l.function;
}
else return false;
else
return false;
}
public override int GetHashCode()
{
if (_Reference != 0)
return _Reference;
else
return function.GetHashCode();
return _Reference != 0 ? _Reference : function.GetHashCode();
}
}
}
\ No newline at end of file
......@@ -38,7 +38,6 @@
<Compile Include="CheckType.cs" />
<Compile Include="Lua.cs" />
<Compile Include="Metatables.cs" />
<Compile Include="MethodWrapper.cs" />
<Compile Include="ObjectTranslator.cs" />
<Compile Include="ProxyType.cs" />
<Compile Include="LuaLib\LuaLib.cs" />
......@@ -68,6 +67,14 @@
<Compile Include="LuaLib\LuaTypes.cs" />
<Compile Include="LuaLib\GCOption.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>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
......@@ -88,5 +95,6 @@
<Folder Include="GenerateEventAssembly\" />
<Folder Include="Event\" />
<Folder Include="Exceptions\" />
<Folder Include="Method\" />
</ItemGroup>
</Project>
......@@ -32,6 +32,8 @@ using LuaInterface.Extensions;
namespace LuaInterface
{
using LuaCore = KopiLua.Lua;
public static class LuaLib
{
private static int tag = 0;
......@@ -77,9 +79,9 @@ namespace LuaInterface
/// <param name="fn">
/// A <see cref="CallbackFunction"/>
/// </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
......@@ -96,9 +98,9 @@ namespace LuaInterface
/// <returns>
/// A <see cref="System.Boolean"/>
/// </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>
......@@ -113,14 +115,14 @@ namespace LuaInterface
/// <returns>
/// A <see cref="System.Boolean"/>
/// </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;
}
......@@ -136,22 +138,22 @@ namespace LuaInterface
/// <param name="r">
/// A <see cref="System.Int32"/>
/// </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;
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);
KopiLua.Lua.lua_rawget(luaState, -2);
retVal = !KopiLua.Lua.lua_isnil(luaState, -1);
KopiLua.Lua.lua_settop(luaState, -3);
LuaCore.lua_pushlightuserdata(luaState, tag);
LuaCore.lua_rawget(luaState, -2);
retVal = !LuaCore.lua_isnil(luaState, -1);
LuaCore.lua_settop(luaState, -3);
}
return retVal;
......@@ -162,43 +164,43 @@ namespace LuaInterface
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;
}
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);
}
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);
//Console.WriteLine(BitConverter.ToInt32(ObjectToByteArray(KopiLua.Lua.lua_touserdata(luaState, ud)), 0));
int p = (int)LuaCore.lua_touserdata2(luaState, ud);
//Console.WriteLine(BitConverter.ToInt32(ObjectToByteArray(LuaCore.lua_touserdata(luaState, ud)), 0));
if(p != 0)
{
/* value is a userdata? */
if(KopiLua.Lua.lua_getmetatable(luaState, ud)!=0)
if(LuaCore.lua_getmetatable(luaState, ud)!=0)
{
/* does it have a metatable? */
KopiLua.Lua.lua_getfield(luaState, (int)PseudoIndex.Registry, tname); /* get correct metatable */
bool isEqual = KopiLua.Lua.lua_rawequal(luaState, -1, -2).ToBoolean();
LuaCore.lua_getfield(luaState, (int)PseudoIndex.Registry, tname); /* get correct metatable */
bool isEqual = LuaCore.lua_rawequal(luaState, -1, -2).ToBoolean();
// NASTY - we need our own version of the lua_pop macro
// 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? */
return p;
......@@ -208,27 +210,27 @@ namespace LuaInterface
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);
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;
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))
{
udata = (int)KopiLua.Lua.lua_touserdata2(luaState, index);
udata = (int)LuaCore.lua_touserdata2(luaState, index);
if(udata != 0)
return udata;
}
......@@ -249,9 +251,9 @@ namespace LuaInterface
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
}
......
......@@ -24,8 +24,9 @@
*/
using System;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Diagnostics.CodeAnalysis;
using LuaInterface.Extensions;
namespace LuaInterface
{
......@@ -40,15 +41,18 @@ namespace LuaInterface
public static void TaggedInstanceMethods(Lua lua, object o)
{
#region Sanity checks
if (lua == null) throw new ArgumentNullException("lua");
if (o == null) throw new ArgumentNullException("o");
if(lua.IsNull())
throw new ArgumentNullException("lua");
if(o.IsNull())
throw new ArgumentNullException("o");
#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
else
lua.RegisterFunction(attribute.Name, o, method); // Custom name
......@@ -66,16 +70,21 @@ namespace LuaInterface
public static void TaggedStaticMethods(Lua lua, Type type)
{
#region Sanity checks
if (lua == null) throw new ArgumentNullException("lua");
if (type == null) throw new ArgumentNullException("type");
if (!type.IsClass) throw new ArgumentException("The type must be a class!", "type");
if(lua.IsNull())
throw new ArgumentNullException("lua");
if(type.IsNull())
throw new ArgumentNullException("type");
if(!type.IsClass)
throw new ArgumentException("The type must be a class!", "type");
#endregion
foreach (MethodInfo method in type.GetMethods(BindingFlags.Static | BindingFlags.Public))
foreach(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
else
lua.RegisterFunction(attribute.Name, null, method); // Custom name
......@@ -94,17 +103,20 @@ namespace LuaInterface
public static void Enumeration<T>(Lua lua)
{
#region Sanity checks
if (lua == null) throw new ArgumentNullException("lua");
if(lua.IsNull())
throw new ArgumentNullException("lua");
#endregion
Type type = typeof(T);
if (!type.IsEnum) throw new ArgumentException("The type must be an enumeration!");
var type = typeof(T);
if(!type.IsEnum)
throw new ArgumentException("The type must be an enumeration!");
string[] names = Enum.GetNames(type);
var values = (T[])Enum.GetValues(type);
lua.NewTable(type.Name);
for (int i = 0; i < names.Length; i++)
for(int i = 0; i < names.Length; i++)
{
string path = type.Name + "." + names[i];
lua[path] = values[i];
......
......@@ -30,6 +30,8 @@ using System.Collections.Generic;
namespace LuaInterface
{
using LuaCore = KopiLua.Lua;
/*
* Wrapper class for Lua tables
*
......@@ -58,6 +60,7 @@ namespace LuaInterface
_Interpreter.setObject(_Reference, field, value);
}
}
/*
* Indexer for numeric fields of the table
*/
......@@ -73,7 +76,6 @@ namespace LuaInterface
}
}
public System.Collections.IDictionaryEnumerator GetEnumerator()
{
return _Interpreter.GetTableDict(this).GetEnumerator();
......@@ -102,8 +104,8 @@ namespace LuaInterface
{
object obj = _Interpreter.rawGetObject(_Reference, field);
if (obj is KopiLua.Lua.lua_CFunction)
return new LuaFunction((KopiLua.Lua.lua_CFunction)obj, _Interpreter);
if(obj is LuaCore.lua_CFunction)
return new LuaFunction((LuaCore.lua_CFunction)obj, _Interpreter);
else
return obj;
}
......@@ -111,10 +113,11 @@ namespace LuaInterface
/*
* 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);
}
public override string ToString()
{
return "table";
......
......@@ -29,6 +29,8 @@ using System.Collections.Generic;
namespace LuaInterface
{
using LuaCore = KopiLua.Lua;
public class LuaUserData : LuaBase
{
public LuaUserData(int reference, Lua interpreter)
......@@ -51,6 +53,7 @@ namespace LuaInterface
_Interpreter.setObject(_Reference, field, value);
}
}
/*
* Indexer for numeric fields of the userdata
*/
......@@ -65,6 +68,7 @@ namespace LuaInterface
_Interpreter.setObject(_Reference, field, value);
}
}
/*
* Calls the userdata and returns its return values inside
* an array
......@@ -73,13 +77,15 @@ namespace LuaInterface
{
return _Interpreter.callFunction(this, args);
}
/*
* 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);
}
public override string ToString()
{
return "userdata";
......
......@@ -30,9 +30,13 @@ using System.Reflection;
using System.Diagnostics;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using LuaInterface.Method;
using LuaInterface.Extensions;
namespace LuaInterface
{
using LuaCore = KopiLua.Lua;
/*
* Functions used in the metatables of userdata representing
* CLR objects
......@@ -42,81 +46,83 @@ namespace LuaInterface
*/
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.
*/
internal static string luaIndexFunction =
"local function index(obj,name)\n" +
" local meta=getmetatable(obj)\n" +
" local cached=meta.cache[name]\n" +
" if cached~=nil then\n" +
" return cached\n" +
" else\n" +
" local value,isFunc=get_object_member(obj,name)\n" +
" if isFunc then\n" +
" meta.cache[name]=value\n" +
" end\n" +
" return value\n" +
" end\n" +
"end\n" +
"return index";
private ObjectTranslator translator;
private Hashtable memberCache = new Hashtable();
internal KopiLua.Lua.lua_CFunction gcFunction, indexFunction, newindexFunction,
baseIndexFunction, classIndexFunction, classNewindexFunction,
execDelegateFunction, callConstructorFunction, toStringFunction;
"local function index(obj,name) \n" +
" local meta=getmetatable(obj) \n" +
" local cached=meta.cache[name] \n" +
" if cached~=nil then \n" +
" return cached \n" +
" else \n" +
" local value,isFunc=get_object_member(obj,name) \n" +
" if isFunc then \n" +
" meta.cache[name]=value \n" +
" end \n" +
" return value \n" +
" end \n" +
"end \n" +
"return index ";
public MetaFunctions(ObjectTranslator translator)
{
this.translator = translator;
gcFunction = new KopiLua.Lua.lua_CFunction(this.collectObject);
toStringFunction = new KopiLua.Lua.lua_CFunction(this.toString);
indexFunction = new KopiLua.Lua.lua_CFunction(this.getMethod);
newindexFunction = new KopiLua.Lua.lua_CFunction(this.setFieldOrProperty);
baseIndexFunction = new KopiLua.Lua.lua_CFunction(this.getBaseMethod);
callConstructorFunction = new KopiLua.Lua.lua_CFunction(this.callConstructor);
classIndexFunction = new KopiLua.Lua.lua_CFunction(this.getClassMethod);
classNewindexFunction = new KopiLua.Lua.lua_CFunction(this.setClassFieldOrProperty);
execDelegateFunction = new KopiLua.Lua.lua_CFunction(this.runFunctionDelegate);
gcFunction = new LuaCore.lua_CFunction(this.collectObject);
toStringFunction = new LuaCore.lua_CFunction(this.toString);
indexFunction = new LuaCore.lua_CFunction(this.getMethod);
newindexFunction = new LuaCore.lua_CFunction(this.setFieldOrProperty);
baseIndexFunction = new LuaCore.lua_CFunction(this.getBaseMethod);
callConstructorFunction = new LuaCore.lua_CFunction(this.callConstructor);
classIndexFunction = new LuaCore.lua_CFunction(this.getClassMethod);
classNewindexFunction = new LuaCore.lua_CFunction(this.setClassFieldOrProperty);
execDelegateFunction = new LuaCore.lua_CFunction(this.runFunctionDelegate);
}
/*
* __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);
KopiLua.Lua.lua_remove(luaState, 1);
LuaCore.lua_CFunction func = (LuaCore.lua_CFunction)translator.getRawNetObject(luaState, 1);
LuaCore.lua_remove(luaState, 1);
return func(luaState);
}
/*
* __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);
if (udata != -1)
{
if(udata != -1)
translator.collectObject(udata);
}
else
{
// Debug.WriteLine("not found: " + udata);
}
return 0;
}
/*
* __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);
if (obj != null)
{
if(!obj.IsNull())
translator.push(luaState, obj.ToString() + ": " + obj.GetHashCode());
}
else KopiLua.Lua.lua_pushnil(luaState);
else
LuaCore.lua_pushnil(luaState);
return 1;
}
......@@ -125,19 +131,19 @@ namespace LuaInterface
/// Debug tool to dump the lua stack
/// </summary>
/// 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);
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
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);
strrep = obj.ToString();
......@@ -147,7 +153,6 @@ namespace LuaInterface
}
}
/*
* Called by the __index metafunction of CLR objects in case the
* method is not cached or it is a field/property/event.
......@@ -155,21 +160,21 @@ namespace LuaInterface
* either the value of the member or a delegate to call it.
* 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);
if (obj == null)
if(obj.IsNull())
{
translator.throwError(luaState, "trying to index an invalid object reference");
KopiLua.Lua.lua_pushnil(luaState);
LuaCore.lua_pushnil(luaState);
return 1;
}
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
Type objType = obj.GetType();
var objType = obj.GetType();
// Handle the most common case, looking up the method by name.
......@@ -177,27 +182,29 @@ namespace LuaInterface
// ie: xmlelement['item'] <- item is a property of xmlelement
try
{
if (methodName != null && isMemberPresent(objType, methodName))
if(!methodName.IsNull() && isMemberPresent(objType, methodName))
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)
if (objType.IsArray && index is double)
if(objType.IsArray && index is double)
{
int intIndex = (int)((double)index);
if (objType.UnderlyingSystemType == typeof(float[]))
if(objType.UnderlyingSystemType == typeof(float[]))
{
float[] arr = ((float[])obj);
translator.push(luaState, arr[intIndex]);
}
else if (objType.UnderlyingSystemType == typeof(double[]))
else if(objType.UnderlyingSystemType == typeof(double[]))
{
double[] arr = ((double[])obj);
translator.push(luaState, arr[intIndex]);
}
else if (objType.UnderlyingSystemType == typeof(int[]))
else if(objType.UnderlyingSystemType == typeof(int[]))
{
int[] arr = ((int[])obj);
translator.push(luaState, arr[intIndex]);
......@@ -212,94 +219,95 @@ namespace LuaInterface
{
// Try to use get_Item to index into this .net object
//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
if (mInfo.GetParameters().Length == 1)
if(mInfo.GetParameters().Length == 1)
{
MethodInfo getter = mInfo;
ParameterInfo[] actualParms = (getter != null) ? getter.GetParameters() : null;
var getter = mInfo;
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);
KopiLua.Lua.lua_pushnil(luaState);
LuaCore.lua_pushnil(luaState);
}
else
{
// Get the index in a form acceptable to the getter
index = translator.getAsType(luaState, 2, actualParms[0].ParameterType);
object[] args = new object[1];
// Just call the indexer - if out of bounds an exception will happen
args[0] = index;
try
{
object result = getter.Invoke(obj, args);
translator.push(luaState, result);
}
catch (TargetInvocationException e)
catch(TargetInvocationException e)
{
// 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 ");
else
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;
}
/*
* __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.
*/
private int getBaseMethod(KopiLua.Lua.lua_State luaState)
private int getBaseMethod(LuaCore.lua_State luaState)
{
object obj = translator.getRawNetObject(luaState, 1);
if (obj == null)
if(obj.IsNull())
{
translator.throwError(luaState, "trying to index an invalid object reference");
KopiLua.Lua.lua_pushnil(luaState);
KopiLua.Lua.lua_pushboolean(luaState, 0);
LuaCore.lua_pushnil(luaState);
LuaCore.lua_pushboolean(luaState, 0);
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);
KopiLua.Lua.lua_pushboolean(luaState, 0);
LuaCore.lua_pushnil(luaState);
LuaCore.lua_pushboolean(luaState, 0);
return 2;
}
getMember(luaState, obj.GetType(), obj, "__luaInterface_base_" + methodName, BindingFlags.Instance | BindingFlags.IgnoreCase);
KopiLua.Lua.lua_settop(luaState, -2);
if (KopiLua.Lua.lua_type(luaState, -1).ToLuaTypes() == LuaTypes.Nil)
LuaCore.lua_settop(luaState, -2);
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);
}
KopiLua.Lua.lua_pushboolean(luaState, 0);
LuaCore.lua_pushboolean(luaState, 0);
return 2;
}
/// <summary>
/// Does this method exist as either an instance or static?
/// </summary>
......@@ -310,11 +318,11 @@ namespace LuaInterface
{
object cachedMember = checkMemberCache(memberCache, objType, methodName);
if (cachedMember != null)
if(!cachedMember.IsNull())
return true;
//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);
}
......@@ -324,27 +332,27 @@ namespace LuaInterface
* 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).
*/
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;
MemberInfo member = null;
object cachedMember = checkMemberCache(memberCache, objType, methodName);
//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);
return 2;
}
else if (cachedMember != null)
{
else if(!cachedMember.IsNull())
member = (MemberInfo)cachedMember;
}
else
{
//CP: Removed NonPublic binding search
MemberInfo[] members = objType.GetMember(methodName, bindingType | BindingFlags.Public | BindingFlags.IgnoreCase/*| BindingFlags.NonPublic*/);
if (members.Length > 0)
var members = objType.GetMember(methodName, bindingType | BindingFlags.Public | BindingFlags.IgnoreCase/*| BindingFlags.NonPublic*/);
if(members.Length > 0)
member = members[0];
else
{
......@@ -353,85 +361,92 @@ namespace LuaInterface
//CP: Removed NonPublic binding search and made case insensitive
members = objType.GetMember(methodName, bindingType | BindingFlags.Static | BindingFlags.Public | BindingFlags.IgnoreCase/*| BindingFlags.NonPublic*/);
if (members.Length > 0)
if(members.Length > 0)
{
member = members[0];
implicitStatic = true;
}
}
}
if (member != null)
if(!member.IsNull())
{
if (member.MemberType == MemberTypes.Field)
if(member.MemberType == MemberTypes.Field)
{
FieldInfo field = (FieldInfo)member;
if (cachedMember == null) setMemberCache(memberCache, objType, methodName, member);
var field = (FieldInfo)member;
if(cachedMember.IsNull())
setMemberCache(memberCache, objType, methodName, member);
try
{
translator.push(luaState, field.GetValue(obj));
}
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;
if (cachedMember == null) setMemberCache(memberCache, objType, methodName, member);
var property = (PropertyInfo)member;
if(cachedMember.IsNull())
setMemberCache(memberCache, objType, methodName, member);
try
{
object val = property.GetValue(obj, null);
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 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);
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);
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;
if (cachedMember == null) setMemberCache(memberCache, objType, methodName, member);
var eventInfo = (EventInfo)member;
if(cachedMember.IsNull())
setMemberCache(memberCache, objType, methodName, member);
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
// cache us
if (cachedMember == null) setMemberCache(memberCache, objType, methodName, member);
if(cachedMember.IsNull())
setMemberCache(memberCache, objType, methodName, member);
// Find the name of our class
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
string longname = dectype.FullName + "+" + name;
Type nestedType = translator.FindType(longname);
var nestedType = translator.FindType(longname);
translator.pushType(luaState, nestedType);
}
else
{
// 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.push(luaState, true);
return 2;
......@@ -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
translator.throwError(luaState, "can't pass instance to static method " + methodName);
KopiLua.Lua.lua_pushnil(luaState);
LuaCore.lua_pushnil(luaState);
}
}
else
......@@ -450,86 +464,86 @@ namespace LuaInterface
// 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
// way to know the member just doesn't exist.
translator.throwError(luaState, "unknown member name " + methodName);
KopiLua.Lua.lua_pushnil(luaState);
LuaCore.lua_pushnil(luaState);
}
// push false because we are NOT returning a function (see luaIndexFunction)
translator.push(luaState, false);
return 2;
}
/*
* Checks if a MemberInfo object is cached, returning it or null.
*/
private object checkMemberCache(Hashtable memberCache, IReflect objType, string memberName)
{
Hashtable members = (Hashtable)memberCache[objType];
if (members != null)
return members[memberName];
else
return null;
var members = (Hashtable)memberCache[objType];
return !members.IsNull() ? members[memberName] : null;
}
/*
* Stores a MemberInfo object in the member cache.
*/
private void setMemberCache(Hashtable memberCache, IReflect objType, string memberName, object member)
{
Hashtable members = (Hashtable)memberCache[objType];
if (members == null)
var members = (Hashtable)memberCache[objType];
if(members.IsNull())
{
members = new Hashtable();
memberCache[objType] = members;
}
members[memberName] = member;
}
/*
* __newindex metafunction of CLR objects. Receives the object,
* the member name and the value to be stored as arguments. Throws
* 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);
if (target == null)
if(target.IsNull())
{
translator.throwError(luaState, "trying to index and invalid object reference");
return 0;
}
Type type = target.GetType();
var type = target.GetType();
// First try to look up the parameter as a property name
string 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
// We didn't find a property name, now see if we can use a [] style this accessor to set array contents
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);
Array arr = (Array)target;
int index = (int)LuaCore.lua_tonumber(luaState, 2);
var arr = (Array)target;
object val = translator.getAsType(luaState, 3, arr.GetType().GetElementType());
arr.SetValue(val, index);
}
else
{
// Try to see if we have a this[] accessor
MethodInfo setter = type.GetMethod("set_Item");
if (setter != null)
var setter = type.GetMethod("set_Item");
if(!setter.IsNull())
{
ParameterInfo[] args = setter.GetParameters();
Type valueType = args[1].ParameterType;
var args = setter.GetParameters();
var valueType = args[1].ParameterType;
// The new val ue the user specified
object val = translator.getAsType(luaState, 3, valueType);
Type indexType = args[0].ParameterType;
var indexType = args[0].ParameterType;
object index = translator.getAsType(luaState, 2, indexType);
object[] methodArgs = new object[2];
......@@ -537,24 +551,22 @@ namespace LuaInterface
// Just call the indexer - if out of bounds an exception will happen
methodArgs[0] = index;
methodArgs[1] = val;
setter.Invoke(target, methodArgs);
}
else
{
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
throw;
}
catch (Exception e)
catch(Exception e)
{
ThrowError(luaState, e);
}
return 0;
}
......@@ -566,7 +578,7 @@ namespace LuaInterface
/// <param name="target"></param>
/// <param name="bindingType"></param>
/// <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
......@@ -574,27 +586,28 @@ namespace LuaInterface
// changing the lua typecode to string
// Note: We don't use isstring because the standard lua C isstring considers either strings or numbers to
// 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";
return false;
}
// We only look up property names by string
string fieldName = KopiLua.Lua.lua_tostring(luaState, 2).ToString();
if (fieldName == null || fieldName.Length < 1 || !(char.IsLetter(fieldName[0]) || fieldName[0] == '_'))
string fieldName = LuaCore.lua_tostring(luaState, 2).ToString();
if(fieldName.IsNull() || fieldName.Length < 1 || !(char.IsLetter(fieldName[0]) || fieldName[0] == '_'))
{
detailMessage = "invalid property name";
return false;
}
// Find our member via reflection or the cache
MemberInfo member = (MemberInfo)checkMemberCache(memberCache, targetType, fieldName);
if (member == null)
var member = (MemberInfo)checkMemberCache(memberCache, targetType, fieldName);
if(member.IsNull())
{
//CP: Removed NonPublic binding search and made case insensitive
MemberInfo[] members = targetType.GetMember(fieldName, bindingType | BindingFlags.Public | BindingFlags.IgnoreCase/*| BindingFlags.NonPublic*/);
if (members.Length > 0)
var members = targetType.GetMember(fieldName, bindingType | BindingFlags.Public | BindingFlags.IgnoreCase/*| BindingFlags.NonPublic*/);
if(members.Length > 0)
{
member = members[0];
setMemberCache(memberCache, targetType, fieldName, member);
......@@ -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);
try
{
field.SetValue(target, val);
......@@ -618,13 +632,15 @@ namespace LuaInterface
{
ThrowError(luaState, e);
}
// We did a call
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);
try
{
property.SetValue(target, val, null);
......@@ -633,6 +649,7 @@ namespace LuaInterface
{
ThrowError(luaState, e);
}
// We did a call
return true;
}
......@@ -641,17 +658,16 @@ namespace LuaInterface
return false;
}
/*
* Writes to fields or properties, either static or instance. Throws an error
* 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;
bool success = trySetMember(luaState, targetType, target, bindingType, out detail);
if (!success)
if(!success)
translator.throwError(luaState, detail);
return 0;
......@@ -662,12 +678,12 @@ namespace LuaInterface
/// </summary>
/// <param name="e"></param>
/// 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
TargetInvocationException te = e as TargetInvocationException;
var te = e as TargetInvocationException;
if (te != null)
if (!te.IsNull())
e = te.InnerException;
translator.throwError(luaState, e);
......@@ -676,162 +692,169 @@ namespace LuaInterface
/*
* __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;
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");
KopiLua.Lua.lua_pushnil(luaState);
LuaCore.lua_pushnil(luaState);
return 1;
}
else klass = (IReflect)obj;
if (KopiLua.Lua.lua_isnumber(luaState, 2).ToBoolean())
else
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));
return 1;
}
else
{
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);
return 1;
} //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.
*/
private int setClassFieldOrProperty(KopiLua.Lua.lua_State luaState)
private int setClassFieldOrProperty(LuaCore.lua_State luaState)
{
IReflect target;
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");
return 0;
}
else target = (IReflect)obj;
else
target = (IReflect)obj;
return setMember(luaState, target, null, BindingFlags.FlattenHierarchy | BindingFlags.Static | BindingFlags.IgnoreCase);
}
/*
* __call metafunction of type references. Searches for and calls
* a constructor for the type. Returns nil if the constructor is not
* found or if the arguments are invalid. Throws an error if the constructor
* 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;
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");
KopiLua.Lua.lua_pushnil(luaState);
LuaCore.lua_pushnil(luaState);
return 1;
}
else klass = (IReflect)obj;
KopiLua.Lua.lua_remove(luaState, 1);
ConstructorInfo[] constructors = klass.UnderlyingSystemType.GetConstructors();
foreach (ConstructorInfo constructor in constructors)
else
klass = (IReflect)obj;
LuaCore.lua_remove(luaState, 1);
var constructors = klass.UnderlyingSystemType.GetConstructors();
foreach(var constructor in constructors)
{
bool isConstructor = matchParameters(luaState, constructor, ref validConstructor);
if (isConstructor)
if(isConstructor)
{
try
{
translator.push(luaState, constructor.Invoke(validConstructor.args));
}
catch (TargetInvocationException e)
catch(TargetInvocationException e)
{
ThrowError(luaState, e);
KopiLua.Lua.lua_pushnil(luaState);
LuaCore.lua_pushnil(luaState);
}
catch
{
KopiLua.Lua.lua_pushnil(luaState);
LuaCore.lua_pushnil(luaState);
}
return 1;
}
}
string constructorName = (constructors.Length == 0) ? "unknown" : constructors[0].Name;
translator.throwError(luaState, String.Format("{0} does not contain constructor({1}) argument match",
klass.UnderlyingSystemType,
constructorName));
KopiLua.Lua.lua_pushnil(luaState);
klass.UnderlyingSystemType, constructorName));
LuaCore.lua_pushnil(luaState);
return 1;
}
/*
* Matches a method against its arguments in the Lua stack. Returns
* if the match was succesful. It it was also returns the information
* 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;
bool isMethod = true;
ParameterInfo[] paramInfo = method.GetParameters();
var paramInfo = method.GetParameters();
int currentLuaParam = 1;
int nLuaParams = KopiLua.Lua.lua_gettop(luaState);
ArrayList paramList = new ArrayList();
List<int> outList = new List<int>();
List<MethodArgs> argTypes = new List<MethodArgs>();
foreach (ParameterInfo currentNetParam in paramInfo)
{
if (!currentNetParam.IsIn && currentNetParam.IsOut) // Skips out params
int nLuaParams = LuaCore.lua_gettop(luaState);
var paramList = new ArrayList();
var outList = new List<int>();
var argTypes = new List<MethodArgs>();
foreach(var currentNetParam in paramInfo)
{
if(!currentNetParam.IsIn && currentNetParam.IsOut) // Skips out params
outList.Add(paramList.Add(null));
}
else if (currentLuaParam > nLuaParams) // Adds optional parameters
{
if (currentNetParam.IsOptional)
else if(currentLuaParam > nLuaParams) // Adds optional parameters
{
if(currentNetParam.IsOptional)
paramList.Add(currentNetParam.DefaultValue);
}
else
{
isMethod = false;
break;
}
}
else if (_IsTypeCorrect(luaState, currentLuaParam, currentNetParam, out extractValue)) // Type checking
else if(_IsTypeCorrect(luaState, currentLuaParam, currentNetParam, out extractValue)) // Type checking
{
int index = paramList.Add(extractValue(luaState, currentLuaParam));
MethodArgs methodArg = new MethodArgs();
var methodArg = new MethodArgs();
methodArg.index = index;
methodArg.extractValue = extractValue;
argTypes.Add(methodArg);
if (currentNetParam.ParameterType.IsByRef)
if(currentNetParam.ParameterType.IsByRef)
outList.Add(index);
currentLuaParam++;
} // Type does not match, ignore if the parameter is optional
else if (_IsParamsArray(luaState, currentLuaParam, currentNetParam, out extractValue))
else if(_IsParamsArray(luaState, currentLuaParam, currentNetParam, out extractValue))
{
object luaParamValue = extractValue(luaState, currentLuaParam);
Type paramArrayType = currentNetParam.ParameterType.GetElementType();
var paramArrayType = currentNetParam.ParameterType.GetElementType();
Array paramArray;
if (luaParamValue is LuaTable)
if(luaParamValue is LuaTable)
{
LuaTable table = (LuaTable)luaParamValue;
IDictionaryEnumerator tableEnumerator = table.GetEnumerator();
var table = (LuaTable)luaParamValue;
var tableEnumerator = table.GetEnumerator();
paramArray = Array.CreateInstance(paramArrayType, table.Values.Count);
tableEnumerator.Reset();
int paramArrayIndex = 0;
while(tableEnumerator.MoveNext())
......@@ -847,35 +870,33 @@ namespace LuaInterface
}
int index = paramList.Add(paramArray);
MethodArgs methodArg = new MethodArgs();
var methodArg = new MethodArgs();
methodArg.index = index;
methodArg.extractValue = extractValue;
methodArg.isParamsArray = true;
methodArg.paramsArrayType = paramArrayType;
argTypes.Add(methodArg);
currentLuaParam++;
}
else if (currentNetParam.IsOptional)
{
else if(currentNetParam.IsOptional)
paramList.Add(currentNetParam.DefaultValue);
}
else // No match
{
isMethod = false;
break;
}
}
if (currentLuaParam != nLuaParams + 1) // Number of parameters does not match
if(currentLuaParam != nLuaParams + 1) // Number of parameters does not match
isMethod = false;
if (isMethod)
if(isMethod)
{
methodCache.args = paramList.ToArray();
methodCache.cachedMethod = method;
methodCache.outList = outList.ToArray();
methodCache.argTypes = argTypes.ToArray();
}
return isMethod;
}
......@@ -888,7 +909,7 @@ namespace LuaInterface
/// <param name="currentNetParam"></param>
/// <param name="extractValue"></param>
/// <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
{
......@@ -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;
......@@ -912,9 +933,9 @@ namespace LuaInterface
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(ex.Message);
......@@ -922,25 +943,25 @@ namespace LuaInterface
return false;
}
if (luaType == LuaTypes.Table)
if(luaType == LuaTypes.Table)
{
try
{
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.");
}
if (extractValue != null)
if(!extractValue.IsNull())
{
return true;
}
}
else
{
Type paramElementType = currentNetParam.ParameterType.GetElementType();
var paramElementType = currentNetParam.ParameterType.GetElementType();
try
{
......@@ -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));
}
if (extractValue != null)
if(!extractValue.IsNull())
{
return true;
}
......@@ -959,7 +980,6 @@ namespace LuaInterface
}
Debug.WriteLine("Type wasn't Params object.");
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