Commit d7bb0c93 authored by Megax's avatar Megax
Browse files

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

* Mar csak egy falj nincs atalakitva. Ha az is meglesz (vagy kozben) akkor a fajlok kimeneti helyet is modositom + hozzadom azokat az exeket amik a luainterface-hez voltak.
parent bbf63a7e
...@@ -26,10 +26,13 @@ ...@@ -26,10 +26,13 @@
using System; using System;
using System.Reflection; using System.Reflection;
using System.Collections.Generic; using System.Collections.Generic;
using LuaInterface.Method;
using LuaInterface.Extensions; using LuaInterface.Extensions;
namespace LuaInterface namespace LuaInterface
{ {
using LuaCore = KopiLua.Lua;
/* /*
* Type checking and conversion functions. * Type checking and conversion functions.
* *
...@@ -84,9 +87,9 @@ namespace LuaInterface ...@@ -84,9 +87,9 @@ namespace LuaInterface
return extractValues.ContainsKey(runtimeHandleValue) ? extractValues[runtimeHandleValue] : extractNetObject; return extractValues.ContainsKey(runtimeHandleValue) ? extractValues[runtimeHandleValue] : extractNetObject;
} }
internal ExtractValue checkType(KopiLua.Lua.lua_State luaState, int stackPos, Type paramType) internal ExtractValue checkType(LuaCore.lua_State luaState, int stackPos, Type paramType)
{ {
var luatype = KopiLua.Lua.lua_type(luaState, stackPos).ToLuaTypes(); var luatype = LuaCore.lua_type(luaState, stackPos).ToLuaTypes();
if(paramType.IsByRef) if(paramType.IsByRef)
paramType = paramType.GetElementType(); paramType = paramType.GetElementType();
...@@ -120,17 +123,17 @@ namespace LuaInterface ...@@ -120,17 +123,17 @@ namespace LuaInterface
//;//an unsupported type was encountered //;//an unsupported type was encountered
} }
if(KopiLua.Lua.lua_isnumber(luaState, stackPos).ToBoolean()) if(LuaCore.lua_isnumber(luaState, stackPos).ToBoolean())
return extractValues[runtimeHandleValue]; return extractValues[runtimeHandleValue];
if(paramType == typeof(bool)) if(paramType == typeof(bool))
{ {
if(KopiLua.Lua.lua_isboolean(luaState, stackPos)) if(LuaCore.lua_isboolean(luaState, stackPos))
return extractValues[runtimeHandleValue]; return extractValues[runtimeHandleValue];
} }
else if(paramType == typeof(string)) else if(paramType == typeof(string))
{ {
if(KopiLua.Lua.lua_isstring(luaState, stackPos).ToBoolean()) if(LuaCore.lua_isstring(luaState, stackPos).ToBoolean())
return extractValues[runtimeHandleValue]; return extractValues[runtimeHandleValue];
else if(luatype == LuaTypes.Nil) else if(luatype == LuaTypes.Nil)
return extractNetObject; // kevinh - silently convert nil to a null string pointer return extractNetObject; // kevinh - silently convert nil to a null string pointer
...@@ -159,12 +162,12 @@ namespace LuaInterface ...@@ -159,12 +162,12 @@ namespace LuaInterface
// kevinh - allow nil to be silently converted to null - extractNetObject will return null when the item ain't found // kevinh - allow nil to be silently converted to null - extractNetObject will return null when the item ain't found
return extractNetObject; return extractNetObject;
} }
else if(KopiLua.Lua.lua_type(luaState, stackPos).ToLuaTypes() == LuaTypes.Table) else if(LuaCore.lua_type(luaState, stackPos).ToLuaTypes() == LuaTypes.Table)
{ {
if(KopiLua.Lua.luaL_getmetafield(luaState, stackPos, "__index").ToBoolean()) if(LuaCore.luaL_getmetafield(luaState, stackPos, "__index").ToBoolean())
{ {
object obj = translator.getNetObject(luaState, -1); object obj = translator.getNetObject(luaState, -1);
KopiLua.Lua.lua_settop(luaState, -2); LuaCore.lua_settop(luaState, -2);
if(!obj.IsNull() && paramType.IsAssignableFrom(obj.GetType())) if(!obj.IsNull() && paramType.IsAssignableFrom(obj.GetType()))
return extractNetObject; return extractNetObject;
} }
...@@ -186,156 +189,156 @@ namespace LuaInterface ...@@ -186,156 +189,156 @@ namespace LuaInterface
* index stackPos as the desired type if it can, or null * index stackPos as the desired type if it can, or null
* otherwise. * otherwise.
*/ */
private object getAsSbyte(KopiLua.Lua.lua_State luaState, int stackPos) private object getAsSbyte(LuaCore.lua_State luaState, int stackPos)
{ {
sbyte retVal = (sbyte)KopiLua.Lua.lua_tonumber(luaState, stackPos); sbyte retVal = (sbyte)LuaCore.lua_tonumber(luaState, stackPos);
if(retVal == 0 && !KopiLua.Lua.lua_isnumber(luaState, stackPos).ToBoolean()) if(retVal == 0 && !LuaCore.lua_isnumber(luaState, stackPos).ToBoolean())
return null; return null;
return retVal; return retVal;
} }
private object getAsByte(KopiLua.Lua.lua_State luaState, int stackPos) private object getAsByte(LuaCore.lua_State luaState, int stackPos)
{ {
byte retVal = (byte)KopiLua.Lua.lua_tonumber(luaState, stackPos); byte retVal = (byte)LuaCore.lua_tonumber(luaState, stackPos);
if(retVal == 0 && !KopiLua.Lua.lua_isnumber(luaState, stackPos).ToBoolean()) if(retVal == 0 && !LuaCore.lua_isnumber(luaState, stackPos).ToBoolean())
return null; return null;
return retVal; return retVal;
} }
private object getAsShort(KopiLua.Lua.lua_State luaState, int stackPos) private object getAsShort(LuaCore.lua_State luaState, int stackPos)
{ {
short retVal = (short)KopiLua.Lua.lua_tonumber(luaState, stackPos); short retVal = (short)LuaCore.lua_tonumber(luaState, stackPos);
if(retVal == 0 && !KopiLua.Lua.lua_isnumber(luaState, stackPos).ToBoolean()) if(retVal == 0 && !LuaCore.lua_isnumber(luaState, stackPos).ToBoolean())
return null; return null;
return retVal; return retVal;
} }
private object getAsUshort(KopiLua.Lua.lua_State luaState, int stackPos) private object getAsUshort(LuaCore.lua_State luaState, int stackPos)
{ {
ushort retVal = (ushort)KopiLua.Lua.lua_tonumber(luaState, stackPos); ushort retVal = (ushort)LuaCore.lua_tonumber(luaState, stackPos);
if(retVal == 0 && !KopiLua.Lua.lua_isnumber(luaState, stackPos).ToBoolean()) if(retVal == 0 && !LuaCore.lua_isnumber(luaState, stackPos).ToBoolean())
return null; return null;
return retVal; return retVal;
} }
private object getAsInt(KopiLua.Lua.lua_State luaState, int stackPos) private object getAsInt(LuaCore.lua_State luaState, int stackPos)
{ {
int retVal = (int)KopiLua.Lua.lua_tonumber(luaState, stackPos); int retVal = (int)LuaCore.lua_tonumber(luaState, stackPos);
if(retVal == 0 && !KopiLua.Lua.lua_isnumber(luaState, stackPos).ToBoolean()) if(retVal == 0 && !LuaCore.lua_isnumber(luaState, stackPos).ToBoolean())
return null; return null;
return retVal; return retVal;
} }
private object getAsUint(KopiLua.Lua.lua_State luaState, int stackPos) private object getAsUint(LuaCore.lua_State luaState, int stackPos)
{ {
uint retVal = (uint)KopiLua.Lua.lua_tonumber(luaState, stackPos); uint retVal = (uint)LuaCore.lua_tonumber(luaState, stackPos);
if(retVal == 0 && !KopiLua.Lua.lua_isnumber(luaState, stackPos).ToBoolean()) if(retVal == 0 && !LuaCore.lua_isnumber(luaState, stackPos).ToBoolean())
return null; return null;
return retVal; return retVal;
} }
private object getAsLong(KopiLua.Lua.lua_State luaState, int stackPos) private object getAsLong(LuaCore.lua_State luaState, int stackPos)
{ {
long retVal = (long)KopiLua.Lua.lua_tonumber(luaState, stackPos); long retVal = (long)LuaCore.lua_tonumber(luaState, stackPos);
if(retVal == 0 && !KopiLua.Lua.lua_isnumber(luaState, stackPos).ToBoolean()) if(retVal == 0 && !LuaCore.lua_isnumber(luaState, stackPos).ToBoolean())
return null; return null;
return retVal; return retVal;
} }
private object getAsUlong(KopiLua.Lua.lua_State luaState, int stackPos) private object getAsUlong(LuaCore.lua_State luaState, int stackPos)
{ {
ulong retVal = (ulong)KopiLua.Lua.lua_tonumber(luaState, stackPos); ulong retVal = (ulong)LuaCore.lua_tonumber(luaState, stackPos);
if(retVal == 0 && !KopiLua.Lua.lua_isnumber(luaState, stackPos).ToBoolean()) if(retVal == 0 && !LuaCore.lua_isnumber(luaState, stackPos).ToBoolean())
return null; return null;
return retVal; return retVal;
} }
private object getAsDouble(KopiLua.Lua.lua_State luaState, int stackPos) private object getAsDouble(LuaCore.lua_State luaState, int stackPos)
{ {
double retVal = KopiLua.Lua.lua_tonumber(luaState, stackPos); double retVal = LuaCore.lua_tonumber(luaState, stackPos);
if(retVal == 0 && !KopiLua.Lua.lua_isnumber(luaState, stackPos).ToBoolean()) if(retVal == 0 && !LuaCore.lua_isnumber(luaState, stackPos).ToBoolean())
return null; return null;
return retVal; return retVal;
} }
private object getAsChar(KopiLua.Lua.lua_State luaState, int stackPos) private object getAsChar(LuaCore.lua_State luaState, int stackPos)
{ {
char retVal = (char)KopiLua.Lua.lua_tonumber(luaState, stackPos); char retVal = (char)LuaCore.lua_tonumber(luaState, stackPos);
if(retVal == 0 && !KopiLua.Lua.lua_isnumber(luaState, stackPos).ToBoolean()) if(retVal == 0 && !LuaCore.lua_isnumber(luaState, stackPos).ToBoolean())
return null; return null;
return retVal; return retVal;
} }
private object getAsFloat(KopiLua.Lua.lua_State luaState, int stackPos) private object getAsFloat(LuaCore.lua_State luaState, int stackPos)
{ {
float retVal = (float)KopiLua.Lua.lua_tonumber(luaState, stackPos); float retVal = (float)LuaCore.lua_tonumber(luaState, stackPos);
if(retVal == 0 && !KopiLua.Lua.lua_isnumber(luaState, stackPos).ToBoolean()) if(retVal == 0 && !LuaCore.lua_isnumber(luaState, stackPos).ToBoolean())
return null; return null;
return retVal; return retVal;
} }
private object getAsDecimal(KopiLua.Lua.lua_State luaState, int stackPos) private object getAsDecimal(LuaCore.lua_State luaState, int stackPos)
{ {
decimal retVal = (decimal)KopiLua.Lua.lua_tonumber(luaState, stackPos); decimal retVal = (decimal)LuaCore.lua_tonumber(luaState, stackPos);
if(retVal == 0 && !KopiLua.Lua.lua_isnumber(luaState, stackPos).ToBoolean()) if(retVal == 0 && !LuaCore.lua_isnumber(luaState, stackPos).ToBoolean())
return null; return null;
return retVal; return retVal;
} }
private object getAsBoolean(KopiLua.Lua.lua_State luaState, int stackPos) private object getAsBoolean(LuaCore.lua_State luaState, int stackPos)
{ {
return KopiLua.Lua.lua_toboolean(luaState, stackPos); return LuaCore.lua_toboolean(luaState, stackPos);
} }
private object getAsString(KopiLua.Lua.lua_State luaState, int stackPos) private object getAsString(LuaCore.lua_State luaState, int stackPos)
{ {
string retVal = KopiLua.Lua.lua_tostring(luaState, stackPos).ToString(); string retVal = LuaCore.lua_tostring(luaState, stackPos).ToString();
if(retVal == string.Empty && !KopiLua.Lua.lua_isstring(luaState, stackPos).ToBoolean()) if(retVal == string.Empty && !LuaCore.lua_isstring(luaState, stackPos).ToBoolean())
return null; return null;
return retVal; return retVal;
} }
private object getAsTable(KopiLua.Lua.lua_State luaState, int stackPos) private object getAsTable(LuaCore.lua_State luaState, int stackPos)
{ {
return translator.getTable(luaState, stackPos); return translator.getTable(luaState, stackPos);
} }
private object getAsFunction(KopiLua.Lua.lua_State luaState, int stackPos) private object getAsFunction(LuaCore.lua_State luaState, int stackPos)
{ {
return translator.getFunction(luaState, stackPos); return translator.getFunction(luaState, stackPos);
} }
private object getAsUserdata(KopiLua.Lua.lua_State luaState, int stackPos) private object getAsUserdata(LuaCore.lua_State luaState, int stackPos)
{ {
return translator.getUserData(luaState, stackPos); return translator.getUserData(luaState, stackPos);
} }
public object getAsObject(KopiLua.Lua.lua_State luaState, int stackPos) public object getAsObject(LuaCore.lua_State luaState, int stackPos)
{ {
if(KopiLua.Lua.lua_type(luaState, stackPos).ToLuaTypes() == LuaTypes.Table) if(LuaCore.lua_type(luaState, stackPos).ToLuaTypes() == LuaTypes.Table)
{ {
if(KopiLua.Lua.luaL_getmetafield(luaState, stackPos, "__index").ToBoolean()) if(LuaCore.luaL_getmetafield(luaState, stackPos, "__index").ToBoolean())
{ {
if(LuaLib.luaL_checkmetatable(luaState, -1)) if(LuaLib.luaL_checkmetatable(luaState, -1))
{ {
KopiLua.Lua.lua_insert(luaState, stackPos); LuaCore.lua_insert(luaState, stackPos);
KopiLua.Lua.lua_remove(luaState, stackPos+1); LuaCore.lua_remove(luaState, stackPos+1);
} }
else else
KopiLua.Lua.lua_settop(luaState, -2); LuaCore.lua_settop(luaState, -2);
} }
} }
...@@ -343,22 +346,22 @@ namespace LuaInterface ...@@ -343,22 +346,22 @@ namespace LuaInterface
return obj; return obj;
} }
public object getAsNetObject(KopiLua.Lua.lua_State luaState, int stackPos) public object getAsNetObject(LuaCore.lua_State luaState, int stackPos)
{ {
object obj = translator.getNetObject(luaState, stackPos); object obj = translator.getNetObject(luaState, stackPos);
if(obj.IsNull() && KopiLua.Lua.lua_type(luaState, stackPos).ToLuaTypes() == LuaTypes.Table) if(obj.IsNull() && LuaCore.lua_type(luaState, stackPos).ToLuaTypes() == LuaTypes.Table)
{ {
if(KopiLua.Lua.luaL_getmetafield(luaState, stackPos, "__index").ToBoolean()) if(LuaCore.luaL_getmetafield(luaState, stackPos, "__index").ToBoolean())
{ {
if(LuaLib.luaL_checkmetatable(luaState, -1)) if(LuaLib.luaL_checkmetatable(luaState, -1))
{ {
KopiLua.Lua.lua_insert(luaState, stackPos); LuaCore.lua_insert(luaState, stackPos);
KopiLua.Lua.lua_remove(luaState, stackPos+1); LuaCore.lua_remove(luaState, stackPos+1);
obj = translator.getNetObject(luaState, stackPos); obj = translator.getNetObject(luaState, stackPos);
} }
else else
KopiLua.Lua.lua_settop(luaState, -2); LuaCore.lua_settop(luaState, -2);
} }
} }
......
...@@ -29,6 +29,7 @@ using System.Reflection; ...@@ -29,6 +29,7 @@ using System.Reflection;
using System.Reflection.Emit; using System.Reflection.Emit;
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using LuaInterface.Method;
namespace LuaInterface namespace LuaInterface
{ {
......
...@@ -15,10 +15,10 @@ ...@@ -15,10 +15,10 @@
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * 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 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE. * THE SOFTWARE.
*/ */
...@@ -31,10 +31,14 @@ using System.Collections; ...@@ -31,10 +31,14 @@ using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.Collections.Specialized; using System.Collections.Specialized;
using LuaInterface.Event; using LuaInterface.Event;
using LuaInterface.Method;
using LuaInterface.Exceptions; using LuaInterface.Exceptions;
using LuaInterface.Extensions;
namespace LuaInterface namespace LuaInterface
{ {
using LuaCore = KopiLua.Lua;
/* /*
* Main class of LuaInterface * Main class of LuaInterface
* Object-oriented wrapper to Lua API * Object-oriented wrapper to Lua API
...@@ -47,1023 +51,1052 @@ namespace LuaInterface ...@@ -47,1023 +51,1052 @@ namespace LuaInterface
* - all libs automatically open in the Lua class constructor (just assign nil to unwanted libs) * - all libs automatically open in the Lua class constructor (just assign nil to unwanted libs)
* */ * */
[CLSCompliant(true)] [CLSCompliant(true)]
public class Lua : IDisposable public class Lua : IDisposable
{ {
static string init_luanet = #region lua debug functions
"local metatable = {} \n"+ /// <summary>
"local import_type = luanet.import_type \n"+ /// Event that is raised when an exception occures during a hook call.
"local load_assembly = luanet.load_assembly \n"+ /// </summary>
" \n"+ /// <author>Reinhard Ostermeier</author>
"-- Lookup a .NET identifier component. \n"+ public event EventHandler<HookExceptionEventArgs> HookException;
"function metatable:__index(key) -- key is e.g. \"Form\" \n"+ /// <summary>
" -- Get the fully-qualified name, e.g. \"System.Windows.Forms.Form\" \n"+ /// Event when lua hook callback is called
" local fqn = ((rawget(self,\".fqn\") and rawget(self,\".fqn\") .. \n"+ /// </summary>
" \".\") or \"\") .. key \n"+ /// <remarks>
" \n"+ /// Is only raised if SetDebugHook is called before.
" -- Try to find either a luanet function or a CLR type \n"+ /// </remarks>
" local obj = rawget(luanet,key) or import_type(fqn) \n"+ /// <author>Reinhard Ostermeier</author>
" \n"+ public event EventHandler<DebugHookEventArgs> DebugHook;
" -- If key is neither a luanet function or a CLR type, then it is simply \n"+ /// <summary>
" -- an identifier component. \n"+ /// lua hook calback delegate
" if obj == nil then \n"+ /// </summary>
" -- It might be an assembly, so we load it too. \n"+ /// <author>Reinhard Ostermeier</author>
" load_assembly(fqn) \n"+ private LuaCore.lua_Hook hookCallback = null;
" obj = { [\".fqn\"] = fqn } \n"+ #endregion
" setmetatable(obj, metatable) \n"+ #region Globals auto-complete
" end \n"+ private readonly List<string> globals = new List<string>();
" \n"+ private bool globalsSorted;
" -- Cache this lookup \n"+ #endregion
" rawset(self, key, obj) \n"+ private /*readonly */ LuaCore.lua_State luaState;
" return obj \n"+ /// <summary>
"end \n"+ /// True while a script is being executed
" \n"+ /// </summary>
"-- A non-type has been called; e.g. foo = System.Foo() \n"+ public bool IsExecuting { get { return executing; } }
"function metatable:__call(...) \n"+ private LuaCore.lua_CFunction panicCallback;
" error(\"No such type: \" .. rawget(self,\".fqn\"), 2) \n"+
"end \n"+
" \n"+
"-- This is the root of the .NET namespace \n"+
"luanet[\".fqn\"] = false \n"+
"setmetatable(luanet, metatable) \n"+
" \n"+
"-- Preload the mscorlib assembly \n"+
"luanet.load_assembly(\"mscorlib\") \n";
private /*readonly */ KopiLua.Lua.lua_State luaState;
private ObjectTranslator translator; private ObjectTranslator translator;
/// <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;
private KopiLua.Lua.lua_CFunction panicCallback; 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;
}
/// <summary> return globals;
/// 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(); #endregion
public Lua() public Lua()
{ {
luaState = KopiLua.Lua.luaL_newstate(); // steffenj: Lua 5.1.1 API change (lua_open is gone) luaState = LuaCore.luaL_newstate(); // steffenj: Lua 5.1.1 API change (lua_open is gone)
//KopiLua.Lua.luaopen_base(luaState); // steffenj: luaopen_* no longer used //LuaCore.luaopen_base(luaState); // steffenj: luaopen_* no longer used
KopiLua.Lua.luaL_openlibs(luaState); // steffenj: Lua 5.1.1 API change (luaopen_base is gone, just open all libs right here) LuaCore.luaL_openlibs(luaState); // steffenj: Lua 5.1.1 API change (luaopen_base is gone, just open all libs right here)
KopiLua.Lua.lua_pushstring(luaState, "LUAINTERFACE LOADED"); LuaCore.lua_pushstring(luaState, "LUAINTERFACE LOADED");
KopiLua.Lua.lua_pushboolean(luaState, 1); LuaCore.lua_pushboolean(luaState, 1);
KopiLua.Lua.lua_settable(luaState, (int)PseudoIndex.Registry); LuaCore.lua_settable(luaState, (int)PseudoIndex.Registry);
KopiLua.Lua.lua_newtable(luaState); LuaCore.lua_newtable(luaState);
KopiLua.Lua.lua_setglobal(luaState, "luanet"); LuaCore.lua_setglobal(luaState, "luanet");
KopiLua.Lua.lua_pushvalue(luaState, (int)PseudoIndex.Globals); LuaCore.lua_pushvalue(luaState, (int)PseudoIndex.Globals);
KopiLua.Lua.lua_getglobal(luaState, "luanet"); LuaCore.lua_getglobal(luaState, "luanet");
KopiLua.Lua.lua_pushstring(luaState, "getmetatable"); LuaCore.lua_pushstring(luaState, "getmetatable");
KopiLua.Lua.lua_getglobal(luaState, "getmetatable"); LuaCore.lua_getglobal(luaState, "getmetatable");
KopiLua.Lua.lua_settable(luaState, -3); LuaCore.lua_settable(luaState, -3);
KopiLua.Lua.lua_replace(luaState, (int)PseudoIndex.Globals); LuaCore.lua_replace(luaState, (int)PseudoIndex.Globals);
translator=new ObjectTranslator(this,luaState); translator = new ObjectTranslator(this, luaState);
KopiLua.Lua.lua_replace(luaState, (int)PseudoIndex.Globals); LuaCore.lua_replace(luaState, (int)PseudoIndex.Globals);
LuaLib.luaL_dostring(luaState, Lua.init_luanet); // steffenj: lua_dostring renamed to luaL_dostring LuaLib.luaL_dostring(luaState, Lua.init_luanet); // steffenj: lua_dostring renamed to luaL_dostring
// We need to keep this in a managed reference so the delegate doesn't get garbage collected // We need to keep this in a managed reference so the delegate doesn't get garbage collected
panicCallback = new KopiLua.Lua.lua_CFunction(PanicCallback); panicCallback = new LuaCore.lua_CFunction(PanicCallback);
KopiLua.Lua.lua_atpanic(luaState, panicCallback); LuaCore.lua_atpanic(luaState, panicCallback);
//KopiLua.Lua.lua_atlock(luaState, lockCallback = new KopiLua.Lua.lua_CFunction(LockCallback)); //LuaCore.lua_atlock(luaState, lockCallback = new LuaCore.lua_CFunction(LockCallback));
//KopiLua.Lua.lua_atunlock(luaState, unlockCallback = new KopiLua.Lua.lua_CFunction(UnlockCallback)); //LuaCore.lua_atunlock(luaState, unlockCallback = new LuaCore.lua_CFunction(UnlockCallback));
} }
private bool _StatePassed; /*
* CAUTION: LuaInterface.Lua instances can't share the same lua state!
/* */
* CAUTION: LuaInterface.Lua instances can't share the same lua state! public Lua(LuaCore.lua_State luaState)
*/ {
public Lua(KopiLua.Lua.lua_State luaState) LuaCore.lua_State lState = luaState;
{ LuaCore.lua_pushstring(lState, "LUAINTERFACE LOADED");
KopiLua.Lua.lua_State lState = luaState; LuaCore.lua_gettable(lState, (int)PseudoIndex.Registry);
KopiLua.Lua.lua_pushstring(lState, "LUAINTERFACE LOADED");
KopiLua.Lua.lua_gettable(lState, (int)PseudoIndex.Registry); if(LuaCore.lua_toboolean(lState, -1).ToBoolean())
{
if(KopiLua.Lua.lua_toboolean(lState,-1).ToBoolean()) LuaCore.lua_settop(lState, -2);
{ throw new LuaException("There is already a LuaInterface.Lua instance associated with this Lua state");
KopiLua.Lua.lua_settop(lState,-2); }
throw new LuaException("There is already a LuaInterface.Lua instance associated with this Lua state"); else
} {
else LuaCore.lua_settop(lState, -2);
{ LuaCore.lua_pushstring(lState, "LUAINTERFACE LOADED");
KopiLua.Lua.lua_settop(lState,-2); LuaCore.lua_pushboolean(lState, 1);
KopiLua.Lua.lua_pushstring(lState, "LUAINTERFACE LOADED"); LuaCore.lua_settable(lState, (int)PseudoIndex.Registry);
KopiLua.Lua.lua_pushboolean(lState, 1); this.luaState = lState;
KopiLua.Lua.lua_settable(lState, (int)PseudoIndex.Registry); LuaCore.lua_pushvalue(lState, (int)PseudoIndex.Globals);
this.luaState=lState; LuaCore.lua_getglobal(lState, "luanet");
KopiLua.Lua.lua_pushvalue(lState, (int)PseudoIndex.Globals); LuaCore.lua_pushstring(lState, "getmetatable");
KopiLua.Lua.lua_getglobal(lState, "luanet"); LuaCore.lua_getglobal(lState, "getmetatable");
KopiLua.Lua.lua_pushstring(lState, "getmetatable"); LuaCore.lua_settable(lState, -3);
KopiLua.Lua.lua_getglobal(lState, "getmetatable"); LuaCore.lua_replace(lState, (int)PseudoIndex.Globals);
KopiLua.Lua.lua_settable(lState, -3); translator = new ObjectTranslator(this, this.luaState);
KopiLua.Lua.lua_replace(lState, (int)PseudoIndex.Globals); LuaCore.lua_replace(lState, (int)PseudoIndex.Globals);
translator=new ObjectTranslator(this, this.luaState);
KopiLua.Lua.lua_replace(lState, (int)PseudoIndex.Globals);
LuaLib.luaL_dostring(lState, Lua.init_luanet); // steffenj: lua_dostring renamed to luaL_dostring LuaLib.luaL_dostring(lState, Lua.init_luanet); // steffenj: lua_dostring renamed to luaL_dostring
} }
_StatePassed = true; _StatePassed = true;
} }
/// <summary> /// <summary>
/// Called for each lua_lock call /// Called for each lua_lock call
/// </summary> /// </summary>
/// <param name="luaState"></param> /// <param name = "luaState"></param>
/// Not yet used /// Not yet used
int LockCallback(KopiLua.Lua.lua_State luaState) /*int LockCallback(LuaCore.lua_State luaState)
{ {
// Monitor.Enter(luaLock); // Monitor.Enter(luaLock);
return 0;
return 0; }*/
}
/// <summary>
/// <summary> /// Called for each lua_unlock call
/// Called for each lua_unlock call /// </summary>
/// </summary> /// <param name = "luaState"></param>
/// <param name="luaState"></param> /// Not yet used
/// Not yet used /*int UnlockCallback(LuaCore.lua_State luaState)
int UnlockCallback(KopiLua.Lua.lua_State luaState) {
{ // Monitor.Exit(luaLock);
// Monitor.Exit(luaLock); return 0;
}*/
return 0;
} public void Close()
{
public void Close() if(_StatePassed)
{ return;
if (_StatePassed)
return; ////// if(luaState != LuaCore.lua_State.Zero)
if(!luaState.IsNull())
////// if (luaState != KopiLua.Lua.lua_State.Zero) LuaCore.lua_close(luaState);
if (luaState != null) //luaState = LuaCore.lua_State.Zero; <- suggested by Christopher Cebulski http://luaforge.net/forum/forum.php?thread_id = 44593&forum_id = 146
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
} static int PanicCallback(LuaCore.lua_State luaState)
{
static int PanicCallback(KopiLua.Lua.lua_State luaState) // string desc = LuaCore.lua_tostring(luaState, 1);
{ string reason = string.Format("unprotected error in call to Lua API ({0})", LuaCore.lua_tostring(luaState, -1));
// string desc = KopiLua.Lua.lua_tostring(luaState, 1); // lua_tostring(L, -1);
string reason = String.Format("unprotected error in call to Lua API ({0})", KopiLua.Lua.lua_tostring(luaState, -1)); throw new LuaException(reason);
}
// lua_tostring(L, -1);
/// <summary>
throw new LuaException(reason); /// 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>
private void ThrowExceptionFromError(int oldTop)
{
/// <summary> object err = translator.getObject(luaState, -1);
/// Assuming we have a Lua error string sitting on the stack, throw a C# exception out to the user's app LuaCore.lua_settop(luaState, oldTop);
/// </summary>
/// <exception cref="LuaScriptException">Thrown if the script caused an exception</exception> // A pre-wrapped exception - just rethrow it (stack trace of InnerException will be preserved)
void ThrowExceptionFromError(int oldTop) var luaEx = err as LuaScriptException;
{
object err = translator.getObject(luaState, -1);
KopiLua.Lua.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;
// 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(), "");
}
/// <summary>
/// Convert C# exceptions into Lua errors
/// </summary>
/// <returns>num of things on stack</returns>
/// <param name="e">null for no pending exception</param>
internal int SetPendingException(Exception e)
{
Exception caughtExcept = e;
if (caughtExcept != null)
{
translator.throwError(luaState, caughtExcept);
KopiLua.Lua.lua_pushnil(luaState);
return 1;
}
else
return 0;
}
private bool executing;
/// <summary>
/// True while a script is being executed
/// </summary>
public bool IsExecuting { get { return executing; } }
/// <summary>
///
/// </summary>
/// <param name="chunk"></param>
/// <param name="name"></param>
/// <returns></returns>
public LuaFunction LoadString(string chunk, string name)
{
int oldTop = KopiLua.Lua.lua_gettop(luaState);
executing = true;
try
{
if (LuaLib.luaL_loadbuffer(luaState, chunk, name) != 0)
ThrowExceptionFromError(oldTop);
}
finally { executing = false; }
LuaFunction result = translator.getFunction(luaState, -1);
translator.popValues(luaState, oldTop);
return result;
}
/// <summary>
///
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
public LuaFunction LoadFile(string fileName)
{
int oldTop = KopiLua.Lua.lua_gettop(luaState);
if (KopiLua.Lua.luaL_loadfile(luaState, fileName) != 0)
ThrowExceptionFromError(oldTop);
LuaFunction result = translator.getFunction(luaState, -1);
translator.popValues(luaState, oldTop);
return result;
}
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>
internal int SetPendingException(Exception e)
{
var caughtExcept = e;
if(!caughtExcept.IsNull())
{
translator.throwError(luaState, caughtExcept);
LuaCore.lua_pushnil(luaState);
return 1;
}
else
return 0;
}
/// <summary>
///
/// </summary>
/// <param name = "chunk"></param>
/// <param name = "name"></param>
/// <returns></returns>
public LuaFunction LoadString(string chunk, string name)
{
int oldTop = LuaCore.lua_gettop(luaState);
executing = true;
try
{
if(LuaLib.luaL_loadbuffer(luaState, chunk, name) != 0)
ThrowExceptionFromError(oldTop);
}
finally
{
executing = false;
}
var result = translator.getFunction(luaState, -1);
translator.popValues(luaState, oldTop);
return result;
}
/// <summary>
///
/// </summary>
/// <param name = "fileName"></param>
/// <returns></returns>
public LuaFunction LoadFile(string fileName)
{
int oldTop = LuaCore.lua_gettop(luaState);
if(LuaCore.luaL_loadfile(luaState, fileName) != 0)
ThrowExceptionFromError(oldTop);
var result = translator.getFunction(luaState, -1);
translator.popValues(luaState, oldTop);
return result;
}
/* /*
* Excutes a Lua chunk and returns all the chunk's return * Excutes a Lua chunk and returns all the chunk's return
* values in an array * values in an array
*/ */
public object[] DoString(string chunk) public object[] DoString(string chunk)
{ {
int oldTop=KopiLua.Lua.lua_gettop(luaState); int oldTop = LuaCore.lua_gettop(luaState);
if (LuaLib.luaL_loadbuffer(luaState, chunk, "chunk") == 0)
{ if(LuaLib.luaL_loadbuffer(luaState, chunk, "chunk") == 0)
executing = true; {
try executing = true;
{
if (KopiLua.Lua.lua_pcall(luaState, 0, -1, 0) == 0) try
return translator.popValues(luaState, oldTop); {
else if(LuaCore.lua_pcall(luaState, 0, -1, 0) == 0)
ThrowExceptionFromError(oldTop); return translator.popValues(luaState, oldTop);
} else
finally { executing = false; } ThrowExceptionFromError(oldTop);
} }
else finally
ThrowExceptionFromError(oldTop); {
executing = false;
return null; // Never reached - keeps compiler happy }
}
else
ThrowExceptionFromError(oldTop);
return null; // Never reached - keeps compiler happy
} }
/// <summary> /// <summary>
/// Executes a Lua chnk and returns all the chunk's return values in an array. /// Executes a Lua chnk and returns all the chunk's return values in an array.
/// </summary> /// </summary>
/// <param name="chunk">Chunk to execute</param> /// <param name = "chunk">Chunk to execute</param>
/// <param name="chunkName">Name to associate with the chunk</param> /// <param name = "chunkName">Name to associate with the chunk</param>
/// <returns></returns> /// <returns></returns>
public object[] DoString(string chunk, string chunkName) public object[] DoString(string chunk, string chunkName)
{ {
int oldTop = KopiLua.Lua.lua_gettop(luaState); int oldTop = LuaCore.lua_gettop(luaState);
executing = true; executing = true;
if (LuaLib.luaL_loadbuffer(luaState, chunk, chunkName) == 0)
{ if(LuaLib.luaL_loadbuffer(luaState, chunk, chunkName) == 0)
try {
{ try
if (KopiLua.Lua.lua_pcall(luaState, 0, -1, 0) == 0) {
return translator.popValues(luaState, oldTop); if(LuaCore.lua_pcall(luaState, 0, -1, 0) == 0)
else return translator.popValues(luaState, oldTop);
ThrowExceptionFromError(oldTop); else
} ThrowExceptionFromError(oldTop);
finally { executing = false; } }
} finally
else {
ThrowExceptionFromError(oldTop); executing = false;
}
return null; // Never reached - keeps compiler happy }
} else
ThrowExceptionFromError(oldTop);
return null; // Never reached - keeps compiler happy
}
/* /*
* Excutes a Lua file and returns all the chunk's return * Excutes a Lua file and returns all the chunk's return
* values in an array * values in an array
*/ */
public object[] DoFile(string fileName) public object[] DoFile(string fileName)
{ {
int oldTop=KopiLua.Lua.lua_gettop(luaState); int oldTop = LuaCore.lua_gettop(luaState);
if(KopiLua.Lua.luaL_loadfile(luaState,fileName)==0)
if(LuaCore.luaL_loadfile(luaState, fileName) == 0)
{ {
executing = true; executing = true;
try
{ try
if (KopiLua.Lua.lua_pcall(luaState, 0, -1, 0) == 0) {
return translator.popValues(luaState, oldTop); if(LuaCore.lua_pcall(luaState, 0, -1, 0) == 0)
else return translator.popValues(luaState, oldTop);
ThrowExceptionFromError(oldTop); else
} ThrowExceptionFromError(oldTop);
finally { executing = false; } }
finally
{
executing = false;
}
} }
else else
ThrowExceptionFromError(oldTop); ThrowExceptionFromError(oldTop);
return null; // Never reached - keeps compiler happy return null; // Never reached - keeps compiler happy
} }
/* /*
* Indexer for global variables from the LuaInterpreter * Indexer for global variables from the LuaInterpreter
* Supports navigation of tables by using . operator * Supports navigation of tables by using . operator
*/ */
public object this[string fullPath] public object this[string fullPath]
{ {
get get
{ {
object returnValue=null; object returnValue = null;
int oldTop=KopiLua.Lua.lua_gettop(luaState); int oldTop = LuaCore.lua_gettop(luaState);
string[] path=fullPath.Split(new char[] { '.' }); string[] path = fullPath.Split(new char[] { '.' });
KopiLua.Lua.lua_getglobal(luaState,path[0]); LuaCore.lua_getglobal(luaState, path[0]);
returnValue=translator.getObject(luaState,-1); returnValue = translator.getObject(luaState, -1);
if(path.Length>1) if(path.Length>1)
{ {
string[] remainingPath=new string[path.Length-1]; string[] remainingPath = new string[path.Length-1];
Array.Copy(path,1,remainingPath,0,path.Length-1); Array.Copy(path, 1, remainingPath, 0, path.Length-1);
returnValue=getObject(remainingPath); returnValue = getObject(remainingPath);
} }
KopiLua.Lua.lua_settop(luaState,oldTop);
LuaCore.lua_settop(luaState, oldTop);
return returnValue; return returnValue;
} }
set set
{ {
int oldTop=KopiLua.Lua.lua_gettop(luaState); int oldTop = LuaCore.lua_gettop(luaState);
string[] path=fullPath.Split(new char[] { '.' }); string[] path = fullPath.Split(new char[] { '.' });
if(path.Length==1)
if(path.Length == 1)
{ {
translator.push(luaState,value); translator.push(luaState, value);
KopiLua.Lua.lua_setglobal(luaState,fullPath); LuaCore.lua_setglobal(luaState, fullPath);
} }
else else
{ {
KopiLua.Lua.lua_getglobal(luaState,path[0]); LuaCore.lua_getglobal(luaState, path[0]);
string[] remainingPath=new string[path.Length-1]; string[] remainingPath = new string[path.Length-1];
Array.Copy(path,1,remainingPath,0,path.Length-1); Array.Copy(path, 1, remainingPath, 0, path.Length-1);
setObject(remainingPath,value); setObject(remainingPath, value);
}
LuaCore.lua_settop(luaState, oldTop);
// Globals auto-complete
if(value.IsNull())
{
// Remove now obsolete entries
globals.Remove(fullPath);
} }
KopiLua.Lua.lua_settop(luaState,oldTop); else
{
// Globals auto-complete // Add new entries
if (value == null) if(!globals.Contains(fullPath))
{ registerGlobal(fullPath, value.GetType(), 0);
// Remove now obsolete entries }
globals.Remove(fullPath); }
}
else
{
// Add new entries
if (!globals.Contains(fullPath))
registerGlobal(fullPath, value.GetType(), 0);
}
}
} }
#region Globals auto-complete #region Globals auto-complete
private readonly List<string> globals = new List<string>(); /// <summary>
private bool globalsSorted; /// Adds an entry to <see cref = "globals"/> (recursivley handles 2 levels of members)
/// </summary>
/// <summary> /// <param name = "path">The index accessor path ot the entry</param>
/// An alphabetically sorted list of all globals (objects, methods, etc.) externally added to this Lua instance /// <param name = "type">The type of the entry</param>
/// </summary> /// <param name = "recursionCounter">How deep have we gone with recursion?</param>
/// <remarks>Members of globals are also listed. The formatting is optimized for text input auto-completion.</remarks> private void registerGlobal(string path, Type type, int recursionCounter)
public IEnumerable<string> Globals {
{ // If the type is a global method, list it directly
get if(type == typeof(LuaCore.lua_CFunction))
{ {
// Only sort list when necessary // Format for easy method invocation
if (!globalsSorted) globals.Add(path + "(");
{ }
globals.Sort(); // If the type is a class or an interface and recursion hasn't been running too long, list the members
globalsSorted = true; else if((type.IsClass || type.IsInterface) && type != typeof(string) && recursionCounter < 2)
} {
#region Methods
return globals; foreach(var method in type.GetMethods(BindingFlags.Public | BindingFlags.Instance))
} {
} if(
// Check that the LuaHideAttribute and LuaGlobalAttribute were not applied
/// <summary> (method.GetCustomAttributes(typeof(LuaHideAttribute), false).Length == 0) &&
/// Adds an entry to <see cref="globals"/> (recursivley handles 2 levels of members) (method.GetCustomAttributes(typeof(LuaGlobalAttribute), false).Length == 0) &&
/// </summary> // Exclude some generic .NET methods that wouldn't be very usefull in Lua
/// <param name="path">The index accessor path ot the entry</param> method.Name != "GetType" && method.Name != "GetHashCode" && method.Name != "Equals" &&
/// <param name="type">The type of the entry</param> method.Name != "ToString" && method.Name != "Clone" && method.Name != "Dispose" &&
/// <param name="recursionCounter">How deep have we gone with recursion?</param> method.Name != "GetEnumerator" && method.Name != "CopyTo" &&
private void registerGlobal(string path, Type type, int recursionCounter) !method.Name.StartsWith("get_", StringComparison.Ordinal) &&
{ !method.Name.StartsWith("set_", StringComparison.Ordinal) &&
// If the type is a global method, list it directly !method.Name.StartsWith("add_", StringComparison.Ordinal) &&
if (type == typeof(KopiLua.Lua.lua_CFunction)) !method.Name.StartsWith("remove_", StringComparison.Ordinal))
{ {
// Format for easy method invocation // Format for easy method invocation
globals.Add(path + "("); string command = path + ":" + method.Name + "(";
}
// If the type is a class or an interface and recursion hasn't been running too long, list the members if(method.GetParameters().Length == 0) command += ")";
else if ((type.IsClass || type.IsInterface) && type != typeof(string) && recursionCounter < 2) globals.Add(command);
{ }
#region Methods }
foreach (MethodInfo method in type.GetMethods(BindingFlags.Public | BindingFlags.Instance)) #endregion
{
if ( #region Fields
// Check that the LuaHideAttribute and LuaGlobalAttribute were not applied foreach(var field in type.GetFields(BindingFlags.Public | BindingFlags.Instance))
(method.GetCustomAttributes(typeof(LuaHideAttribute), false).Length == 0) && {
(method.GetCustomAttributes(typeof(LuaGlobalAttribute), false).Length == 0) && if(
// Exclude some generic .NET methods that wouldn't be very usefull in Lua // Check that the LuaHideAttribute and LuaGlobalAttribute were not applied
method.Name != "GetType" && method.Name != "GetHashCode" && method.Name != "Equals" && (field.GetCustomAttributes(typeof(LuaHideAttribute), false).Length == 0) &&
method.Name != "ToString" && method.Name != "Clone" && method.Name != "Dispose" && (field.GetCustomAttributes(typeof(LuaGlobalAttribute), false).Length == 0))
method.Name != "GetEnumerator" && method.Name != "CopyTo" && {
!method.Name.StartsWith("get_", StringComparison.Ordinal) && // Go into recursion for members
!method.Name.StartsWith("set_", StringComparison.Ordinal) && registerGlobal(path + "." + field.Name, field.FieldType, recursionCounter + 1);
!method.Name.StartsWith("add_", StringComparison.Ordinal) && }
!method.Name.StartsWith("remove_", StringComparison.Ordinal)) }
{ #endregion
// Format for easy method invocation
string command = path + ":" + method.Name + "("; #region Properties
if (method.GetParameters().Length == 0) command += ")"; foreach(var property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance))
globals.Add(command); {
} if(
} // Check that the LuaHideAttribute and LuaGlobalAttribute were not applied
#endregion (property.GetCustomAttributes(typeof(LuaHideAttribute), false).Length == 0) &&
(property.GetCustomAttributes(typeof(LuaGlobalAttribute), false).Length == 0)
#region Fields // Exclude some generic .NET properties that wouldn't be very usefull in Lua
foreach (FieldInfo field in type.GetFields(BindingFlags.Public | BindingFlags.Instance)) && property.Name != "Item")
{ {
if ( // Go into recursion for members
// Check that the LuaHideAttribute and LuaGlobalAttribute were not applied registerGlobal(path + "." + property.Name, property.PropertyType, recursionCounter + 1);
(field.GetCustomAttributes(typeof(LuaHideAttribute), false).Length == 0) && }
(field.GetCustomAttributes(typeof(LuaGlobalAttribute), false).Length == 0)) }
{ #endregion
// Go into recursion for members }
registerGlobal(path + "." + field.Name, field.FieldType, recursionCounter + 1); else
} globals.Add(path); // Otherwise simply add the element to the list
}
#endregion // List will need to be sorted on next access
globalsSorted = false;
#region Properties }
foreach (PropertyInfo property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance)) #endregion
{
if (
// Check that the LuaHideAttribute and LuaGlobalAttribute were not applied
(property.GetCustomAttributes(typeof(LuaHideAttribute), false).Length == 0) &&
(property.GetCustomAttributes(typeof(LuaGlobalAttribute), false).Length == 0)
// Exclude some generic .NET properties that wouldn't be very usefull in Lua
&& property.Name != "Item")
{
// Go into recursion for members
registerGlobal(path + "." + property.Name, property.PropertyType, recursionCounter + 1);
}
}
#endregion
}
// Otherwise simply add the element to the list
else globals.Add(path);
// List will need to be sorted on next access
globalsSorted = false;
}
#endregion
/* /*
* Navigates a table in the top of the stack, returning * Navigates a table in the top of the stack, returning
* the value of the specified field * the value of the specified field
*/ */
internal object getObject(string[] remainingPath) internal object getObject(string[] remainingPath)
{ {
object returnValue=null; object returnValue = null;
for(int i=0;i<remainingPath.Length;i++)
for(int i = 0; i < remainingPath.Length; i++)
{ {
KopiLua.Lua.lua_pushstring(luaState,remainingPath[i]); LuaCore.lua_pushstring(luaState, remainingPath[i]);
KopiLua.Lua.lua_gettable(luaState,-2); LuaCore.lua_gettable(luaState, -2);
returnValue=translator.getObject(luaState,-1); returnValue = translator.getObject(luaState, -1);
if(returnValue==null) break;
if(returnValue.IsNull())
break;
} }
return returnValue;
return returnValue;
} }
/* /*
* Gets a numeric global variable * Gets a numeric global variable
*/ */
public double GetNumber(string fullPath) public double GetNumber(string fullPath)
{ {
return (double)this[fullPath]; return (double)this[fullPath];
} }
/* /*
* Gets a string global variable * Gets a string global variable
*/ */
public string GetString(string fullPath) public string GetString(string fullPath)
{ {
return (string)this[fullPath]; return (string)this[fullPath];
} }
/* /*
* Gets a table global variable * Gets a table global variable
*/ */
public LuaTable GetTable(string fullPath) public LuaTable GetTable(string fullPath)
{ {
return (LuaTable)this[fullPath]; return (LuaTable)this[fullPath];
} }
/* /*
* Gets a table global variable as an object implementing * Gets a table global variable as an object implementing
* the interfaceType interface * the interfaceType interface
*/ */
public object GetTable(Type interfaceType, string fullPath) public object GetTable(Type interfaceType, string fullPath)
{ {
return CodeGeneration.Instance.GetClassInstance(interfaceType,GetTable(fullPath)); return CodeGeneration.Instance.GetClassInstance(interfaceType, GetTable(fullPath));
} }
/* /*
* Gets a function global variable * Gets a function global variable
*/ */
public LuaFunction GetFunction(string fullPath) public LuaFunction GetFunction(string fullPath)
{ {
object obj=this[fullPath]; object obj = this[fullPath];
return (obj is KopiLua.Lua.lua_CFunction ? new LuaFunction((KopiLua.Lua.lua_CFunction)obj,this) : (LuaFunction)obj); return (obj is LuaCore.lua_CFunction ? new LuaFunction((LuaCore.lua_CFunction)obj, this) : (LuaFunction)obj);
//return (obj is KopiLua.Lua.lua_CFunction ? new LuaFunction((KopiLua.Lua.lua_CFunction)obj,this) : /*(LuaFunction)*/new LuaFunction(obj.GetHashCode(), this)); //return (obj is LuaCore.lua_CFunction ? new LuaFunction((LuaCore.lua_CFunction)obj, this) : /*(LuaFunction)*/new LuaFunction(obj.GetHashCode(), this));
} }
/* /*
* Gets a function global variable as a delegate of * Gets a function global variable as a delegate of
* type delegateType * type delegateType
*/ */
public Delegate GetFunction(Type delegateType,string fullPath) public Delegate GetFunction(Type delegateType, string fullPath)
{ {
return CodeGeneration.Instance.GetDelegate(delegateType,GetFunction(fullPath)); return CodeGeneration.Instance.GetDelegate(delegateType, GetFunction(fullPath));
} }
/* /*
* Calls the object as a function with the provided arguments, * Calls the object as a function with the provided arguments,
* returning the function's returned values inside an array * returning the function's returned values inside an array
*/ */
internal object[] callFunction(object function,object[] args) internal object[] callFunction(object function, object[] args)
{ {
return callFunction(function, args, null); return callFunction(function, args, null);
} }
/* /*
* Calls the object as a function with the provided arguments and * Calls the object as a function with the provided arguments and
* casting returned values to the types in returnTypes before returning * casting returned values to the types in returnTypes before returning
* them in an array * them in an array
*/ */
internal object[] callFunction(object function,object[] args,Type[] returnTypes) internal object[] callFunction(object function, object[] args, Type[] returnTypes)
{ {
int nArgs=0; int nArgs = 0;
int oldTop=KopiLua.Lua.lua_gettop(luaState); int oldTop = LuaCore.lua_gettop(luaState);
if(!KopiLua.Lua.lua_checkstack(luaState,args.Length+6).ToBoolean())
throw new LuaException("Lua stack overflow"); if(!LuaCore.lua_checkstack(luaState, args.Length+6).ToBoolean())
translator.push(luaState,function); throw new LuaException("Lua stack overflow");
if(args!=null)
translator.push(luaState, function);
if(!args.IsNull())
{ {
nArgs=args.Length; nArgs = args.Length;
for(int i=0;i<args.Length;i++)
{ for(int i = 0; i < args.Length; i++)
translator.push(luaState,args[i]); translator.push(luaState, args[i]);
} }
}
executing = true; executing = true;
try
{ try
int error = KopiLua.Lua.lua_pcall(luaState, nArgs, -1, 0); {
if (error != 0) int error = LuaCore.lua_pcall(luaState, nArgs, -1, 0);
ThrowExceptionFromError(oldTop); if(error != 0)
} ThrowExceptionFromError(oldTop);
finally { executing = false; } }
finally
if(returnTypes != null) {
return translator.popValues(luaState,oldTop,returnTypes); executing = false;
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 * Navigates a table to set the value of one of its fields
*/ */
internal void setObject(string[] remainingPath, object val) internal void setObject(string[] remainingPath, object val)
{ {
for(int i=0; i<remainingPath.Length-1;i++) for(int i = 0; i < remainingPath.Length-1; i++)
{ {
KopiLua.Lua.lua_pushstring(luaState,remainingPath[i]); LuaCore.lua_pushstring(luaState, remainingPath[i]);
KopiLua.Lua.lua_gettable(luaState,-2); LuaCore.lua_gettable(luaState, -2);
} }
KopiLua.Lua.lua_pushstring(luaState,remainingPath[remainingPath.Length-1]);
translator.push(luaState,val); LuaCore.lua_pushstring(luaState, remainingPath[remainingPath.Length-1]);
KopiLua.Lua.lua_settable(luaState,-3); translator.push(luaState, val);
LuaCore.lua_settable(luaState, -3);
} }
/* /*
* Creates a new table as a global variable or as a field * Creates a new table as a global variable or as a field
* inside an existing table * inside an existing table
*/ */
public void NewTable(string fullPath) public void NewTable(string fullPath)
{ {
string[] path=fullPath.Split(new char[] { '.' }); string[] path = fullPath.Split(new char[] { '.' });
int oldTop=KopiLua.Lua.lua_gettop(luaState); int oldTop = LuaCore.lua_gettop(luaState);
if(path.Length==1)
if(path.Length == 1)
{ {
KopiLua.Lua.lua_newtable(luaState); LuaCore.lua_newtable(luaState);
KopiLua.Lua.lua_setglobal(luaState,fullPath); LuaCore.lua_setglobal(luaState, fullPath);
} }
else else
{ {
KopiLua.Lua.lua_getglobal(luaState,path[0]); LuaCore.lua_getglobal(luaState, path[0]);
for(int i=1; i<path.Length-1;i++)
for(int i = 1; i < path.Length-1; i++)
{ {
KopiLua.Lua.lua_pushstring(luaState,path[i]); LuaCore.lua_pushstring(luaState, path[i]);
KopiLua.Lua.lua_gettable(luaState,-2); LuaCore.lua_gettable(luaState, -2);
} }
KopiLua.Lua.lua_pushstring(luaState,path[path.Length-1]);
KopiLua.Lua.lua_newtable(luaState); LuaCore.lua_pushstring(luaState, path[path.Length-1]);
KopiLua.Lua.lua_settable(luaState,-3); LuaCore.lua_newtable(luaState);
LuaCore.lua_settable(luaState, -3);
} }
KopiLua.Lua.lua_settop(luaState,oldTop);
LuaCore.lua_settop(luaState, oldTop);
} }
public ListDictionary GetTableDict(LuaTable table) public ListDictionary GetTableDict(LuaTable table)
{ {
ListDictionary dict = new ListDictionary(); var dict = new ListDictionary();
int oldTop = LuaCore.lua_gettop(luaState);
int oldTop = KopiLua.Lua.lua_gettop(luaState);
translator.push(luaState, table); translator.push(luaState, table);
KopiLua.Lua.lua_pushnil(luaState); LuaCore.lua_pushnil(luaState);
while (KopiLua.Lua.lua_next(luaState, -2) != 0)
while(LuaCore.lua_next(luaState, -2) != 0)
{ {
dict[translator.getObject(luaState, -2)] = translator.getObject(luaState, -1); dict[translator.getObject(luaState, -2)] = translator.getObject(luaState, -1);
KopiLua.Lua.lua_settop(luaState, -2); LuaCore.lua_settop(luaState, -2);
} }
KopiLua.Lua.lua_settop(luaState, oldTop);
LuaCore.lua_settop(luaState, oldTop);
return dict; return dict;
} }
/* /*
* Lets go of a previously allocated reference to a table, function * Lets go of a previously allocated reference to a table, function
* or userdata * or userdata
*/ */
#region lua debug functions
/// <summary>
/// Activates the debug hook
/// </summary>
/// <param name = "mask">Mask</param>
/// <param name = "count">Count</param>
/// <returns>see lua docs. -1 if hook is already set</returns>
/// <author>Reinhard Ostermeier</author>
/*public int SetDebugHook(EventMasks mask, int count)
{
if(hookCallback.IsNull())
{
hookCallback = new LuaCore.lua_Hook(DebugHookCallback);
return LuaCore.lua_sethook(luaState, hookCallback, (int)mask, count);
}
return -1;
}*/
/// <summary>
/// Removes the debug hook
/// </summary>
/// <returns>see lua docs</returns>
/// <author>Reinhard Ostermeier</author>
public int RemoveDebugHook()
{
hookCallback = null;
return LuaCore.lua_sethook(luaState, null, 0, 0);
}
/// <summary>
/// Gets the hook mask.
/// </summary>
/// <returns>hook mask</returns>
/// <author>Reinhard Ostermeier</author>
public EventMasks GetHookMask()
{
return (EventMasks)LuaCore.lua_gethookmask(luaState);
}
#region lua debug functions /// <summary>
/// Gets the hook count
/// <summary> /// </summary>
/// lua hook calback delegate /// <returns>see lua docs</returns>
/// </summary> /// <author>Reinhard Ostermeier</author>
/// <author>Reinhard Ostermeier</author> public int GetHookCount()
private KopiLua.Lua.lua_Hook hookCallback = null; {
return LuaCore.lua_gethookcount(luaState);
/// <summary> }
/// Activates the debug hook
/// </summary> /// <summary>
/// <param name="mask">Mask</param> /// Gets the stack entry on a given level
/// <param name="count">Count</param> /// </summary>
/// <returns>see lua docs. -1 if hook is already set</returns> /// <param name = "level">level</param>
/// <author>Reinhard Ostermeier</author> /// <param name = "luaDebug">lua debug structure</param>
/*public int SetDebugHook(EventMasks mask, int count) /// <returns>Returns true if level was allowed, false if level was invalid.</returns>
{ /// <author>Reinhard Ostermeier</author>
if (hookCallback == null) /*public bool GetStack(int level, out LuaDebug luaDebug)
{ {
hookCallback = new KopiLua.Lua.lua_Hook(DebugHookCallback); luaDebug = new LuaDebug();
return KopiLua.Lua.lua_sethook(luaState, hookCallback, (int)mask, count); LuaCore.lua_State ld = System.Runtime.InteropServices.Marshal.AllocHGlobal(System.Runtime.InteropServices.Marshal.SizeOf(luaDebug));
} System.Runtime.InteropServices.Marshal.StructureToPtr(luaDebug, ld, false);
return -1; try
}*/ {
return LuaCore.lua_getstack(luaState, level, ld) != 0;
/// <summary> }
/// Removes the debug hook finally
/// </summary> {
/// <returns>see lua docs</returns> luaDebug = (LuaDebug)System.Runtime.InteropServices.Marshal.PtrToStructure(ld, typeof(LuaDebug));
/// <author>Reinhard Ostermeier</author> System.Runtime.InteropServices.Marshal.FreeHGlobal(ld);
public int RemoveDebugHook() }
{ }*/
hookCallback = null;
return KopiLua.Lua.lua_sethook(luaState, null, 0, 0); /// <summary>
} /// Gets info (see lua docs)
/// </summary>
/// <summary> /// <param name = "what">what (see lua docs)</param>
/// Gets the hook mask. /// <param name = "luaDebug">lua debug structure</param>
/// </summary> /// <returns>see lua docs</returns>
/// <returns>hook mask</returns> /// <author>Reinhard Ostermeier</author>
/// <author>Reinhard Ostermeier</author> /*public int GetInfo(String what, ref LuaDebug luaDebug)
public EventMasks GetHookMask() {
{ LuaCore.lua_State ld = System.Runtime.InteropServices.Marshal.AllocHGlobal(System.Runtime.InteropServices.Marshal.SizeOf(luaDebug));
return (EventMasks)KopiLua.Lua.lua_gethookmask(luaState); System.Runtime.InteropServices.Marshal.StructureToPtr(luaDebug, ld, false);
} try
{
/// <summary> return LuaCore.lua_getinfo(luaState, what, ld);
/// Gets the hook count }
/// </summary> finally
/// <returns>see lua docs</returns> {
/// <author>Reinhard Ostermeier</author> luaDebug = (LuaDebug)System.Runtime.InteropServices.Marshal.PtrToStructure(ld, typeof(LuaDebug));
public int GetHookCount() System.Runtime.InteropServices.Marshal.FreeHGlobal(ld);
{ }
return KopiLua.Lua.lua_gethookcount(luaState); }*/
}
/// <summary>
/// <summary> /// Gets local (see lua docs)
/// Gets the stack entry on a given level /// </summary>
/// </summary> /// <param name = "luaDebug">lua debug structure</param>
/// <param name="level">level</param> /// <param name = "n">see lua docs</param>
/// <param name="luaDebug">lua debug structure</param> /// <returns>see lua docs</returns>
/// <returns>Returns true if level was allowed, false if level was invalid.</returns> /// <author>Reinhard Ostermeier</author>
/// <author>Reinhard Ostermeier</author> /*public String GetLocal(LuaDebug luaDebug, int n)
/*public bool GetStack(int level, out LuaDebug luaDebug) {
{ LuaCore.lua_State ld = System.Runtime.InteropServices.Marshal.AllocHGlobal(System.Runtime.InteropServices.Marshal.SizeOf(luaDebug));
luaDebug = new LuaDebug(); System.Runtime.InteropServices.Marshal.StructureToPtr(luaDebug, ld, false);
KopiLua.Lua.lua_State ld = System.Runtime.InteropServices.Marshal.AllocHGlobal(System.Runtime.InteropServices.Marshal.SizeOf(luaDebug)); try
System.Runtime.InteropServices.Marshal.StructureToPtr(luaDebug, ld, false); {
try return LuaCore.lua_getlocal(luaState, ld, n);
{ }
return KopiLua.Lua.lua_getstack(luaState, level, ld) != 0; finally
} {
finally System.Runtime.InteropServices.Marshal.FreeHGlobal(ld);
{ }
luaDebug = (LuaDebug)System.Runtime.InteropServices.Marshal.PtrToStructure(ld, typeof(LuaDebug)); }*/
System.Runtime.InteropServices.Marshal.FreeHGlobal(ld);
} /// <summary>
}*/ /// Sets local (see lua docs)
/// </summary>
/// <summary> /// <param name = "luaDebug">lua debug structure</param>
/// Gets info (see lua docs) /// <param name = "n">see lua docs</param>
/// </summary> /// <returns>see lua docs</returns>
/// <param name="what">what (see lua docs)</param> /// <author>Reinhard Ostermeier</author>
/// <param name="luaDebug">lua debug structure</param> /*public String SetLocal(LuaDebug luaDebug, int n)
/// <returns>see lua docs</returns> {
/// <author>Reinhard Ostermeier</author> LuaCore.lua_State ld = System.Runtime.InteropServices.Marshal.AllocHGlobal(System.Runtime.InteropServices.Marshal.SizeOf(luaDebug));
/*public int GetInfo(String what, ref LuaDebug luaDebug) System.Runtime.InteropServices.Marshal.StructureToPtr(luaDebug, ld, false);
{ try
KopiLua.Lua.lua_State ld = System.Runtime.InteropServices.Marshal.AllocHGlobal(System.Runtime.InteropServices.Marshal.SizeOf(luaDebug)); {
System.Runtime.InteropServices.Marshal.StructureToPtr(luaDebug, ld, false); return LuaCore.lua_setlocal(luaState, ld, n);
try }
{ finally
return KopiLua.Lua.lua_getinfo(luaState, what, ld); {
} System.Runtime.InteropServices.Marshal.FreeHGlobal(ld);
finally }
{ }*/
luaDebug = (LuaDebug)System.Runtime.InteropServices.Marshal.PtrToStructure(ld, typeof(LuaDebug));
System.Runtime.InteropServices.Marshal.FreeHGlobal(ld); /// <summary>
} /// Gets up value (see lua docs)
}*/ /// </summary>
/// <param name = "funcindex">see lua docs</param>
/// <summary> /// <param name = "n">see lua docs</param>
/// Gets local (see lua docs) /// <returns>see lua docs</returns>
/// </summary> /// <author>Reinhard Ostermeier</author>
/// <param name="luaDebug">lua debug structure</param> public string GetUpValue(int funcindex, int n)
/// <param name="n">see lua docs</param> {
/// <returns>see lua docs</returns> return LuaCore.lua_getupvalue(luaState, funcindex, n).ToString();
/// <author>Reinhard Ostermeier</author> }
/*public String GetLocal(LuaDebug luaDebug, int n)
{ /// <summary>
KopiLua.Lua.lua_State ld = System.Runtime.InteropServices.Marshal.AllocHGlobal(System.Runtime.InteropServices.Marshal.SizeOf(luaDebug)); /// Sets up value (see lua docs)
System.Runtime.InteropServices.Marshal.StructureToPtr(luaDebug, ld, false); /// </summary>
try /// <param name = "funcindex">see lua docs</param>
{ /// <param name = "n">see lua docs</param>
return KopiLua.Lua.lua_getlocal(luaState, ld, n); /// <returns>see lua docs</returns>
} /// <author>Reinhard Ostermeier</author>
finally public string SetUpValue(int funcindex, int n)
{ {
System.Runtime.InteropServices.Marshal.FreeHGlobal(ld); return LuaCore.lua_setupvalue(luaState, funcindex, n).ToString();
} }
}*/
/// <summary>
/// <summary> /// Delegate that is called on lua hook callback
/// Sets local (see lua docs) /// </summary>
/// </summary> /// <param name = "luaState">lua state</param>
/// <param name="luaDebug">lua debug structure</param> /// <param name = "luaDebug">Pointer to LuaDebug (lua_debug) structure</param>
/// <param name="n">see lua docs</param> /// <author>Reinhard Ostermeier</author>
/// <returns>see lua docs</returns> /*private void DebugHookCallback(LuaCore.lua_State luaState, LuaCore.lua_Debug luaDebug)
/// <author>Reinhard Ostermeier</author> {
/*public String SetLocal(LuaDebug luaDebug, int n) try
{ {
KopiLua.Lua.lua_State ld = System.Runtime.InteropServices.Marshal.AllocHGlobal(System.Runtime.InteropServices.Marshal.SizeOf(luaDebug)); LuaDebug ld = (LuaDebug)System.Runtime.InteropServices.Marshal.PtrToStructure(luaDebug, typeof(LuaDebug));
System.Runtime.InteropServices.Marshal.StructureToPtr(luaDebug, ld, false); EventHandler<DebugHookEventArgs> temp = DebugHook;
try if(temp != null)
{ {
return KopiLua.Lua.lua_setlocal(luaState, ld, n); temp(this, new DebugHookEventArgs(ld));
} }
finally }
{ catch (Exception ex)
System.Runtime.InteropServices.Marshal.FreeHGlobal(ld); {
} OnHookException(new HookExceptionEventArgs(ex));
}*/ }
}*/
/// <summary>
/// Gets up value (see lua docs) private void OnHookException(HookExceptionEventArgs e)
/// </summary> {
/// <param name="funcindex">see lua docs</param> var temp = HookException;
/// <param name="n">see lua docs</param> if(!temp.IsNull())
/// <returns>see lua docs</returns> temp(this, e);
/// <author>Reinhard Ostermeier</author> }
public String GetUpValue(int funcindex, int n)
{ /// <summary>
return KopiLua.Lua.lua_getupvalue(luaState, funcindex, n).ToString(); /// Pops a value from the lua stack.
} /// </summary>
/// <returns>Returns the top value from the lua stack.</returns>
/// <summary> /// <author>Reinhard Ostermeier</author>
/// Sets up value (see lua docs) public object Pop()
/// </summary> {
/// <param name="funcindex">see lua docs</param> int top = LuaCore.lua_gettop(luaState);
/// <param name="n">see lua docs</param> return translator.popValues(luaState, top - 1)[0];
/// <returns>see lua docs</returns> }
/// <author>Reinhard Ostermeier</author>
public String SetUpValue(int funcindex, int n) /// <summary>
{ /// Pushes a value onto the lua stack.
return KopiLua.Lua.lua_setupvalue(luaState, funcindex, n).ToString(); /// </summary>
} /// <param name = "value">Value to push.</param>
/// <author>Reinhard Ostermeier</author>
/// <summary> public void Push(object value)
/// Delegate that is called on lua hook callback {
/// </summary> translator.push(luaState, value);
/// <param name="luaState">lua state</param> }
/// <param name="luaDebug">Pointer to LuaDebug (lua_debug) structure</param> #endregion
/// <author>Reinhard Ostermeier</author>
/*private void DebugHookCallback(KopiLua.Lua.lua_State luaState, KopiLua.Lua.lua_Debug luaDebug)
{
try
{
LuaDebug ld = (LuaDebug)System.Runtime.InteropServices.Marshal.PtrToStructure(luaDebug, typeof(LuaDebug));
EventHandler<DebugHookEventArgs> temp = DebugHook;
if (temp != null)
{
temp(this, new DebugHookEventArgs(ld));
}
}
catch (Exception ex)
{
OnHookException(new HookExceptionEventArgs(ex));
}
}*/
/// <summary>
/// Event that is raised when an exception occures during a hook call.
/// </summary>
/// <author>Reinhard Ostermeier</author>
public event EventHandler<HookExceptionEventArgs> HookException;
private void OnHookException(HookExceptionEventArgs e)
{
EventHandler<HookExceptionEventArgs> temp = HookException;
if (temp != null)
{
temp(this, e);
}
}
/// <summary>
/// Event when lua hook callback is called
/// </summary>
/// <remarks>
/// Is only raised if SetDebugHook is called before.
/// </remarks>
/// <author>Reinhard Ostermeier</author>
public event EventHandler<DebugHookEventArgs> DebugHook;
/// <summary>
/// Pops a value from the lua stack.
/// </summary>
/// <returns>Returns the top value from the lua stack.</returns>
/// <author>Reinhard Ostermeier</author>
public object Pop()
{
int top = KopiLua.Lua.lua_gettop(luaState);
return translator.popValues(luaState, top - 1)[0];
}
/// <summary>
/// Pushes a value onto the lua stack.
/// </summary>
/// <param name="value">Value to push.</param>
/// <author>Reinhard Ostermeier</author>
public void Push(object value)
{
translator.push(luaState, value);
}
#endregion
internal void dispose(int reference) internal void dispose(int reference)
{ {
///////////// if (luaState != KopiLua.Lua.lua_State.Zero) ///////////// if(luaState != LuaCore.lua_State.Zero)
if (luaState != null) //Fix submitted by Qingrui Li if(!luaState.IsNull()) //Fix submitted by Qingrui Li
LuaLib.lua_unref(luaState,reference); LuaLib.lua_unref(luaState, reference);
} }
/* /*
* Gets a field of the table corresponding to the provided reference * Gets a field of the table corresponding to the provided reference
* using rawget (do not use metatables) * using rawget (do not use metatables)
*/ */
internal object rawGetObject(int reference,string field) internal object rawGetObject(int reference, string field)
{ {
int oldTop=KopiLua.Lua.lua_gettop(luaState); int oldTop = LuaCore.lua_gettop(luaState);
LuaLib.lua_getref(luaState,reference); LuaLib.lua_getref(luaState, reference);
KopiLua.Lua.lua_pushstring(luaState,field); LuaCore.lua_pushstring(luaState, field);
KopiLua.Lua.lua_rawget(luaState,-2); LuaCore.lua_rawget(luaState, -2);
object obj=translator.getObject(luaState,-1); object obj = translator.getObject(luaState, -1);
KopiLua.Lua.lua_settop(luaState,oldTop); LuaCore.lua_settop(luaState, oldTop);
return obj; return obj;
} }
/* /*
* Gets a field of the table or userdata corresponding to the provided reference * Gets a field of the table or userdata corresponding to the provided reference
*/ */
internal object getObject(int reference,string field) internal object getObject(int reference, string field)
{ {
int oldTop=KopiLua.Lua.lua_gettop(luaState); int oldTop = LuaCore.lua_gettop(luaState);
LuaLib.lua_getref(luaState,reference); LuaLib.lua_getref(luaState, reference);
object returnValue=getObject(field.Split(new char[] {'.'})); object returnValue = getObject(field.Split(new char[] {'.'}));
KopiLua.Lua.lua_settop(luaState,oldTop); LuaCore.lua_settop(luaState, oldTop);
return returnValue; return returnValue;
} }
/* /*
* Gets a numeric field of the table or userdata corresponding the the provided reference * Gets a numeric field of the table or userdata corresponding the the provided reference
*/ */
internal object getObject(int reference,object field)
internal object getObject(int reference, object field)
{ {
int oldTop=KopiLua.Lua.lua_gettop(luaState); int oldTop = LuaCore.lua_gettop(luaState);
LuaLib.lua_getref(luaState,reference); LuaLib.lua_getref(luaState, reference);
translator.push(luaState,field); translator.push(luaState, field);
KopiLua.Lua.lua_gettable(luaState,-2); LuaCore.lua_gettable(luaState, -2);
object returnValue=translator.getObject(luaState,-1); object returnValue = translator.getObject(luaState, -1);
KopiLua.Lua.lua_settop(luaState,oldTop); LuaCore.lua_settop(luaState, oldTop);
return returnValue; return returnValue;
} }
/* /*
* Sets a field of the table or userdata corresponding the the provided reference * Sets a field of the table or userdata corresponding the the provided reference
* to the provided value * to the provided value
*/ */
internal void setObject(int reference, string field, object val) internal void setObject(int reference, string field, object val)
{ {
int oldTop=KopiLua.Lua.lua_gettop(luaState); int oldTop = LuaCore.lua_gettop(luaState);
LuaLib.lua_getref(luaState,reference); LuaLib.lua_getref(luaState, reference);
setObject(field.Split(new char[] {'.'}),val); setObject(field.Split(new char[] {'.'}), val);
KopiLua.Lua.lua_settop(luaState,oldTop); LuaCore.lua_settop(luaState, oldTop);
} }
/* /*
* Sets a numeric field of the table or userdata corresponding the the provided reference * Sets a numeric field of the table or userdata corresponding the the provided reference
* to the provided value * to the provided value
*/ */
internal void setObject(int reference, object field, object val) internal void setObject(int reference, object field, object val)
{ {
int oldTop=KopiLua.Lua.lua_gettop(luaState); int oldTop = LuaCore.lua_gettop(luaState);
LuaLib.lua_getref(luaState,reference); LuaLib.lua_getref(luaState, reference);
translator.push(luaState,field); translator.push(luaState, field);
translator.push(luaState,val); translator.push(luaState, val);
KopiLua.Lua.lua_settable(luaState,-3); LuaCore.lua_settable(luaState, -3);
KopiLua.Lua.lua_settop(luaState,oldTop); LuaCore.lua_settop(luaState, oldTop);
} }
/* /*
* Registers an object's method as a Lua function (global or table field) * Registers an object's method as a Lua function (global or table field)
* The method may have any signature * The method may have any signature
*/ */
public LuaFunction RegisterFunction(string path, object target, MethodBase function /*MethodInfo function*/) //CP: Fix for struct constructor by Alexander Kappner (link: http://luaforge.net/forum/forum.php?thread_id=2859&forum_id=145) public LuaFunction RegisterFunction(string path, object target, MethodBase function /*MethodInfo function*/) //CP: Fix for struct constructor by Alexander Kappner (link: http://luaforge.net/forum/forum.php?thread_id = 2859&forum_id = 145)
{ {
// We leave nothing on the stack when we are done // We leave nothing on the stack when we are done
int oldTop = KopiLua.Lua.lua_gettop(luaState); int oldTop = LuaCore.lua_gettop(luaState);
var wrapper = new LuaMethodWrapper(translator, target, function.DeclaringType, function);
LuaMethodWrapper wrapper=new LuaMethodWrapper(translator,target,function.DeclaringType,function); translator.push(luaState, new LuaCore.lua_CFunction(wrapper.call));
translator.push(luaState,new KopiLua.Lua.lua_CFunction(wrapper.call)); this[path] = translator.getObject(luaState, -1);
var f = GetFunction(path);
this[path]=translator.getObject(luaState,-1); LuaCore.lua_settop(luaState, oldTop);
LuaFunction f = GetFunction(path); return f;
KopiLua.Lua.lua_settop(luaState, oldTop);
return f;
} }
/* /*
* Compares the two values referenced by ref1 and ref2 for equality * Compares the two values referenced by ref1 and ref2 for equality
*/ */
internal bool compareRef(int ref1, int ref2) internal bool compareRef(int ref1, int ref2)
{ {
int top=KopiLua.Lua.lua_gettop(luaState); int top = LuaCore.lua_gettop(luaState);
LuaLib.lua_getref(luaState,ref1); LuaLib.lua_getref(luaState, ref1);
LuaLib.lua_getref(luaState,ref2); LuaLib.lua_getref(luaState, ref2);
int equal=KopiLua.Lua.lua_equal(luaState,-1,-2); int equal = LuaCore.lua_equal(luaState, -1, -2);
KopiLua.Lua.lua_settop(luaState,top); LuaCore.lua_settop(luaState, top);
return (equal!=0); return (equal != 0);
}
internal void pushCSFunction(LuaCore.lua_CFunction function)
{
translator.pushFunction(luaState, function);
}
#region IDisposable Members
public virtual void Dispose()
{
if(!translator.IsNull())
{
translator.pendingEvents.Dispose();
translator = null;
}
this.Close();
GC.Collect();
GC.WaitForPendingFinalizers();
} }
#endregion
internal void pushCSFunction(KopiLua.Lua.lua_CFunction function)
{
translator.pushFunction(luaState,function);
}
#region IDisposable Members
public virtual void Dispose()
{
if (translator != null)
{
translator.pendingEvents.Dispose();
translator = null;
}
this.Close();
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
}
#endregion
} }
} }
\ No newline at end of file
...@@ -24,58 +24,60 @@ ...@@ -24,58 +24,60 @@
*/ */
using System; using System;
using System.Collections.Generic;
using System.Text; using System.Text;
using System.Collections.Generic;
namespace LuaInterface namespace LuaInterface
{ {
/// <summary> /// <summary>
/// Base class to provide consistent disposal flow across lua objects. Uses code provided by Yves Duhoux and suggestions by Hans Schmeidenbacher and Qingrui Li /// Base class to provide consistent disposal flow across lua objects. Uses code provided by Yves Duhoux and suggestions by Hans Schmeidenbacher and Qingrui Li
/// </summary> /// </summary>
public abstract class LuaBase : IDisposable public abstract class LuaBase : IDisposable
{ {
private bool _Disposed; private bool _Disposed;
protected int _Reference; protected int _Reference;
protected Lua _Interpreter; protected Lua _Interpreter;
~LuaBase()
{
Dispose(false);
}
~LuaBase() public void Dispose()
{ {
Dispose(false); Dispose(true);
} GC.SuppressFinalize(this);
}
public void Dispose() public virtual void Dispose(bool disposeManagedResources)
{ {
Dispose(true); if(!_Disposed)
GC.SuppressFinalize(this); {
} if(disposeManagedResources)
{
if(_Reference != 0)
_Interpreter.dispose(_Reference);
}
public virtual void Dispose(bool disposeManagedResources) _Interpreter = null;
{ _Disposed = true;
if (!_Disposed) }
{ }
if (disposeManagedResources)
{
if (_Reference != 0)
_Interpreter.dispose(_Reference);
}
_Interpreter = null;
_Disposed = true;
}
}
public override bool Equals(object o) public override bool Equals(object o)
{ {
if (o is LuaBase) if(o is LuaBase)
{ {
LuaBase l = (LuaBase)o; var l = (LuaBase)o;
return _Interpreter.compareRef(l._Reference, _Reference); return _Interpreter.compareRef(l._Reference, _Reference);
} }
else return false; else
} return false;
}
public override int GetHashCode() public override int GetHashCode()
{ {
return _Reference; return _Reference;
} }
} }
} }
\ No newline at end of file
...@@ -29,73 +29,78 @@ using System.Collections.Generic; ...@@ -29,73 +29,78 @@ using System.Collections.Generic;
namespace LuaInterface namespace LuaInterface
{ {
public class LuaFunction : LuaBase using LuaCore = KopiLua.Lua;
{
internal KopiLua.Lua.lua_CFunction function;
public LuaFunction(int reference, Lua interpreter) public class LuaFunction : LuaBase
{ {
_Reference = reference; internal LuaCore.lua_CFunction function;
this.function = null;
_Interpreter = interpreter;
}
public LuaFunction(KopiLua.Lua.lua_CFunction function, Lua interpreter) public LuaFunction(int reference, Lua interpreter)
{ {
_Reference = 0; _Reference = reference;
this.function = function; this.function = null;
_Interpreter = interpreter; _Interpreter = interpreter;
} }
/* public LuaFunction(LuaCore.lua_CFunction function, Lua interpreter)
* Calls the function casting return values to the types {
* in returnTypes _Reference = 0;
*/ this.function = function;
internal object[] call(object[] args, Type[] returnTypes) _Interpreter = interpreter;
{ }
return _Interpreter.callFunction(this, args, returnTypes);
}
/*
* Calls the function and returns its return values inside
* an array
*/
public object[] Call(params object[] args)
{
return _Interpreter.callFunction(this, args);
}
/*
* Pushes the function into the Lua stack
*/
internal void push(KopiLua.Lua.lua_State luaState)
{
if (_Reference != 0)
LuaLib.lua_getref(luaState, _Reference);
else
_Interpreter.pushCSFunction(function);
}
public override string ToString()
{
return "function";
}
public override bool Equals(object o)
{
if (o is LuaFunction)
{
LuaFunction l = (LuaFunction)o;
if (this._Reference != 0 && l._Reference != 0)
return _Interpreter.compareRef(l._Reference, this._Reference);
else
return this.function == l.function;
}
else return false;
}
public override int GetHashCode()
{
if (_Reference != 0)
return _Reference;
else
return function.GetHashCode();
}
}
} /*
* Calls the function casting return values to the types
* in returnTypes
*/
internal object[] call(object[] args, Type[] returnTypes)
{
return _Interpreter.callFunction(this, args, returnTypes);
}
/*
* Calls the function and returns its return values inside
* an array
*/
public object[] Call(params object[] args)
{
return _Interpreter.callFunction(this, args);
}
/*
* Pushes the function into the Lua stack
*/
internal void push(LuaCore.lua_State luaState)
{
if(_Reference != 0)
LuaLib.lua_getref(luaState, _Reference);
else
_Interpreter.pushCSFunction(function);
}
public override string ToString()
{
return "function";
}
public override bool Equals(object o)
{
if(o is LuaFunction)
{
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;
}
public override int GetHashCode()
{
return _Reference != 0 ? _Reference : function.GetHashCode();
}
}
}
\ No newline at end of file
...@@ -27,22 +27,22 @@ using System; ...@@ -27,22 +27,22 @@ using System;
namespace LuaInterface namespace LuaInterface
{ {
/// <summary> /// <summary>
/// Marks a method for global usage in Lua scripts /// Marks a method for global usage in Lua scripts
/// </summary> /// </summary>
/// <see cref="LuaRegistrationHelper.TaggedInstanceMethods"/> /// <see cref="LuaRegistrationHelper.TaggedInstanceMethods"/>
/// <see cref="LuaRegistrationHelper.TaggedStaticMethods"/> /// <see cref="LuaRegistrationHelper.TaggedStaticMethods"/>
[AttributeUsage(AttributeTargets.Method)] [AttributeUsage(AttributeTargets.Method)]
public sealed class LuaGlobalAttribute : Attribute public sealed class LuaGlobalAttribute : Attribute
{ {
/// <summary> /// <summary>
/// An alternative name to use for calling the function in Lua - leave empty for CLR name /// An alternative name to use for calling the function in Lua - leave empty for CLR name
/// </summary> /// </summary>
public string Name { get; set; } public string Name { get; set; }
/// <summary> /// <summary>
/// A description of the function /// A description of the function
/// </summary> /// </summary>
public string Description { get; set; } public string Description { get; set; }
} }
} }
\ No newline at end of file
...@@ -27,11 +27,11 @@ using System; ...@@ -27,11 +27,11 @@ using System;
namespace LuaInterface namespace LuaInterface
{ {
/// <summary> /// <summary>
/// Marks a method, field or property to be hidden from Lua auto-completion /// Marks a method, field or property to be hidden from Lua auto-completion
/// </summary> /// </summary>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Field | AttributeTargets.Property)] [AttributeUsage(AttributeTargets.Method | AttributeTargets.Field | AttributeTargets.Property)]
public sealed class LuaHideAttribute : Attribute public sealed class LuaHideAttribute : Attribute
{ {
} }
} }
\ No newline at end of file
...@@ -38,7 +38,6 @@ ...@@ -38,7 +38,6 @@
<Compile Include="CheckType.cs" /> <Compile Include="CheckType.cs" />
<Compile Include="Lua.cs" /> <Compile Include="Lua.cs" />
<Compile Include="Metatables.cs" /> <Compile Include="Metatables.cs" />
<Compile Include="MethodWrapper.cs" />
<Compile Include="ObjectTranslator.cs" /> <Compile Include="ObjectTranslator.cs" />
<Compile Include="ProxyType.cs" /> <Compile Include="ProxyType.cs" />
<Compile Include="LuaLib\LuaLib.cs" /> <Compile Include="LuaLib\LuaLib.cs" />
...@@ -68,6 +67,14 @@ ...@@ -68,6 +67,14 @@
<Compile Include="LuaLib\LuaTypes.cs" /> <Compile Include="LuaLib\LuaTypes.cs" />
<Compile Include="LuaLib\GCOption.cs" /> <Compile Include="LuaLib\GCOption.cs" />
<Compile Include="LuaLib\PseudoIndex.cs" /> <Compile Include="LuaLib\PseudoIndex.cs" />
<Compile Include="Method\MethodCache.cs" />
<Compile Include="Method\MethodArgs.cs" />
<Compile Include="Method\LuaMethodWrapper.cs" />
<Compile Include="Method\EventHandlerContainer.cs" />
<Compile Include="Method\RegisterEventHandler.cs" />
<Compile Include="Method\LuaEventHandler.cs" />
<Compile Include="Method\LuaDelegate.cs" />
<Compile Include="Method\LuaClassHelper.cs" />
</ItemGroup> </ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it. <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
...@@ -88,5 +95,6 @@ ...@@ -88,5 +95,6 @@
<Folder Include="GenerateEventAssembly\" /> <Folder Include="GenerateEventAssembly\" />
<Folder Include="Event\" /> <Folder Include="Event\" />
<Folder Include="Exceptions\" /> <Folder Include="Exceptions\" />
<Folder Include="Method\" />
</ItemGroup> </ItemGroup>
</Project> </Project>
...@@ -32,6 +32,8 @@ using LuaInterface.Extensions; ...@@ -32,6 +32,8 @@ using LuaInterface.Extensions;
namespace LuaInterface namespace LuaInterface
{ {
using LuaCore = KopiLua.Lua;
public static class LuaLib public static class LuaLib
{ {
private static int tag = 0; private static int tag = 0;
...@@ -77,9 +79,9 @@ namespace LuaInterface ...@@ -77,9 +79,9 @@ namespace LuaInterface
/// <param name="fn"> /// <param name="fn">
/// A <see cref="CallbackFunction"/> /// A <see cref="CallbackFunction"/>
/// </param> /// </param>
public static void lua_pushcfunction(KopiLua.Lua.lua_State state, KopiLua.Lua.lua_CFunction fn) public static void lua_pushcfunction(LuaCore.lua_State state, LuaCore.lua_CFunction fn)
{ {
KopiLua.Lua.lua_pushcclosure(state, fn, 0); LuaCore.lua_pushcclosure(state, fn, 0);
} }
#endregion #endregion
...@@ -96,9 +98,9 @@ namespace LuaInterface ...@@ -96,9 +98,9 @@ namespace LuaInterface
/// <returns> /// <returns>
/// A <see cref="System.Boolean"/> /// A <see cref="System.Boolean"/>
/// </returns> /// </returns>
public static bool luaL_dofile(KopiLua.Lua.lua_State state, string filename) public static bool luaL_dofile(LuaCore.lua_State state, string filename)
{ {
return (KopiLua.Lua.luaL_loadfile(state, filename).ToLuaEnums() == LuaEnums.Ok) && (KopiLua.Lua.lua_pcall(state, 0, (int)LuaEnums.MultiRet, 0).ToLuaEnums() == LuaEnums.Ok); return (LuaCore.luaL_loadfile(state, filename).ToLuaEnums() == LuaEnums.Ok) && (LuaCore.lua_pcall(state, 0, (int)LuaEnums.MultiRet, 0).ToLuaEnums() == LuaEnums.Ok);
} }
/// <summary> /// <summary>
...@@ -113,14 +115,14 @@ namespace LuaInterface ...@@ -113,14 +115,14 @@ namespace LuaInterface
/// <returns> /// <returns>
/// A <see cref="System.Boolean"/> /// A <see cref="System.Boolean"/>
/// </returns> /// </returns>
public static bool luaL_dostring(KopiLua.Lua.lua_State state, string chunk) public static bool luaL_dostring(LuaCore.lua_State state, string chunk)
{ {
return (KopiLua.Lua.luaL_loadstring(state, chunk).ToLuaEnums() == LuaEnums.Ok) && (KopiLua.Lua.lua_pcall(state, 0, (int)LuaEnums.MultiRet, 0).ToLuaEnums() == LuaEnums.Ok); return (LuaCore.luaL_loadstring(state, chunk).ToLuaEnums() == LuaEnums.Ok) && (LuaCore.lua_pcall(state, 0, (int)LuaEnums.MultiRet, 0).ToLuaEnums() == LuaEnums.Ok);
} }
public static LuaEnums luaL_loadbuffer(KopiLua.Lua.lua_State luaState, string buff, string name) public static LuaEnums luaL_loadbuffer(LuaCore.lua_State luaState, string buff, string name)
{ {
var result = KopiLua.Lua.luaL_loadbuffer(luaState, buff, (uint)buff.Length, name).ToLuaEnums(); var result = LuaCore.luaL_loadbuffer(luaState, buff, (uint)buff.Length, name).ToLuaEnums();
return result; return result;
} }
...@@ -136,22 +138,22 @@ namespace LuaInterface ...@@ -136,22 +138,22 @@ namespace LuaInterface
/// <param name="r"> /// <param name="r">
/// A <see cref="System.Int32"/> /// A <see cref="System.Int32"/>
/// </param> /// </param>
public static void luaL_getref(KopiLua.Lua.lua_State state, int t, int r) public static void luaL_getref(LuaCore.lua_State state, int t, int r)
{ {
KopiLua.Lua.lua_rawgeti(state, t, r); LuaCore.lua_rawgeti(state, t, r);
} }
public static bool luaL_checkmetatable(KopiLua.Lua.lua_State luaState,int index) public static bool luaL_checkmetatable(LuaCore.lua_State luaState,int index)
{ {
bool retVal = false; bool retVal = false;
Console.WriteLine("v: " + luaState.tt.ToString()); Console.WriteLine("v: " + luaState.tt.ToString());
if(KopiLua.Lua.lua_getmetatable(luaState,index)!=0) if(LuaCore.lua_getmetatable(luaState,index)!=0)
{ {
KopiLua.Lua.lua_pushlightuserdata(luaState, tag); LuaCore.lua_pushlightuserdata(luaState, tag);
KopiLua.Lua.lua_rawget(luaState, -2); LuaCore.lua_rawget(luaState, -2);
retVal = !KopiLua.Lua.lua_isnil(luaState, -1); retVal = !LuaCore.lua_isnil(luaState, -1);
KopiLua.Lua.lua_settop(luaState, -3); LuaCore.lua_settop(luaState, -3);
} }
return retVal; return retVal;
...@@ -162,43 +164,43 @@ namespace LuaInterface ...@@ -162,43 +164,43 @@ namespace LuaInterface
return tag; return tag;
} }
public static void lua_getref(KopiLua.Lua.lua_State luaState, int reference) public static void lua_getref(LuaCore.lua_State luaState, int reference)
{ {
KopiLua.Lua.lua_rawgeti(luaState, (int)PseudoIndex.Registry, reference); LuaCore.lua_rawgeti(luaState, (int)PseudoIndex.Registry, reference);
} }
public static void lua_unref(KopiLua.Lua.lua_State luaState, int reference) public static void lua_unref(LuaCore.lua_State luaState, int reference)
{ {
KopiLua.Lua.luaL_unref(luaState, (int)PseudoIndex.Registry, reference); LuaCore.luaL_unref(luaState, (int)PseudoIndex.Registry, reference);
} }
public static int luanet_rawnetobj(KopiLua.Lua.lua_State luaState,int obj) public static int luanet_rawnetobj(LuaCore.lua_State luaState,int obj)
{ {
int udata = (int)KopiLua.Lua.lua_touserdata2(luaState, obj); int udata = (int)LuaCore.lua_touserdata2(luaState, obj);
return udata != 0 ? udata : -1; return udata != 0 ? udata : -1;
} }
public static void lua_pushstdcallcfunction(KopiLua.Lua.lua_State luaState,KopiLua.Lua.lua_CFunction function) public static void lua_pushstdcallcfunction(LuaCore.lua_State luaState,LuaCore.lua_CFunction function)
{ {
lua_pushcfunction(luaState, function); lua_pushcfunction(luaState, function);
} }
public static int checkudata_raw(KopiLua.Lua.lua_State luaState, int ud, string tname) public static int checkudata_raw(LuaCore.lua_State luaState, int ud, string tname)
{ {
int p = (int)KopiLua.Lua.lua_touserdata2(luaState, ud); int p = (int)LuaCore.lua_touserdata2(luaState, ud);
//Console.WriteLine(BitConverter.ToInt32(ObjectToByteArray(KopiLua.Lua.lua_touserdata(luaState, ud)), 0)); //Console.WriteLine(BitConverter.ToInt32(ObjectToByteArray(LuaCore.lua_touserdata(luaState, ud)), 0));
if(p != 0) if(p != 0)
{ {
/* value is a userdata? */ /* value is a userdata? */
if(KopiLua.Lua.lua_getmetatable(luaState, ud)!=0) if(LuaCore.lua_getmetatable(luaState, ud)!=0)
{ {
/* does it have a metatable? */ /* does it have a metatable? */
KopiLua.Lua.lua_getfield(luaState, (int)PseudoIndex.Registry, tname); /* get correct metatable */ LuaCore.lua_getfield(luaState, (int)PseudoIndex.Registry, tname); /* get correct metatable */
bool isEqual = KopiLua.Lua.lua_rawequal(luaState, -1, -2).ToBoolean(); bool isEqual = LuaCore.lua_rawequal(luaState, -1, -2).ToBoolean();
// NASTY - we need our own version of the lua_pop macro // NASTY - we need our own version of the lua_pop macro
// lua_pop(L, 2); /* remove both metatables */ // lua_pop(L, 2); /* remove both metatables */
KopiLua.Lua.lua_settop(luaState, -(2) - 1); LuaCore.lua_settop(luaState, -(2) - 1);
if(isEqual) /* does it have the correct mt? */ if(isEqual) /* does it have the correct mt? */
return p; return p;
...@@ -208,27 +210,27 @@ namespace LuaInterface ...@@ -208,27 +210,27 @@ namespace LuaInterface
return 0; return 0;
} }
public static int luanet_checkudata(KopiLua.Lua.lua_State luaState, int ud, string tname) public static int luanet_checkudata(LuaCore.lua_State luaState, int ud, string tname)
{ {
int udata = checkudata_raw(luaState, ud, tname); int udata = checkudata_raw(luaState, ud, tname);
return udata != 0 ? udata : -1; return udata != 0 ? udata : -1;
} }
public static void luanet_newudata(KopiLua.Lua.lua_State luaState, int val) public static void luanet_newudata(LuaCore.lua_State luaState, int val)
{ {
KopiLua.Lua.lua_newuserdata(luaState, (uint)val); LuaCore.lua_newuserdata(luaState, (uint)val);
} }
public static int luanet_tonetobject(KopiLua.Lua.lua_State luaState, int index) public static int luanet_tonetobject(LuaCore.lua_State luaState, int index)
{ {
int udata; int udata;
Console.WriteLine("x" + KopiLua.Lua.lua_type(luaState, index).ToString()); Console.WriteLine("x" + LuaCore.lua_type(luaState, index).ToString());
if(KopiLua.Lua.lua_type(luaState, index).ToLuaTypes() == LuaTypes.UserData) if(LuaCore.lua_type(luaState, index).ToLuaTypes() == LuaTypes.UserData)
{ {
if(luaL_checkmetatable(luaState, index)) if(luaL_checkmetatable(luaState, index))
{ {
udata = (int)KopiLua.Lua.lua_touserdata2(luaState, index); udata = (int)LuaCore.lua_touserdata2(luaState, index);
if(udata != 0) if(udata != 0)
return udata; return udata;
} }
...@@ -249,9 +251,9 @@ namespace LuaInterface ...@@ -249,9 +251,9 @@ namespace LuaInterface
return -1; return -1;
} }
public static int lua_ref(KopiLua.Lua.lua_State luaState, int lockRef) public static int lua_ref(LuaCore.lua_State luaState, int lockRef)
{ {
return lockRef != 0 ? KopiLua.Lua.luaL_ref(luaState, (int)PseudoIndex.Registry) : 0; return lockRef != 0 ? LuaCore.luaL_ref(luaState, (int)PseudoIndex.Registry) : 0;
} }
#endregion #endregion
} }
......
...@@ -24,92 +24,104 @@ ...@@ -24,92 +24,104 @@
*/ */
using System; using System;
using System.Diagnostics.CodeAnalysis;
using System.Reflection; using System.Reflection;
using System.Diagnostics.CodeAnalysis;
using LuaInterface.Extensions;
namespace LuaInterface namespace LuaInterface
{ {
public static class LuaRegistrationHelper public static class LuaRegistrationHelper
{ {
#region Tagged instance methods #region Tagged instance methods
/// <summary> /// <summary>
/// Registers all public instance methods in an object tagged with <see cref="LuaGlobalAttribute"/> as Lua global functions /// Registers all public instance methods in an object tagged with <see cref="LuaGlobalAttribute"/> as Lua global functions
/// </summary> /// </summary>
/// <param name="lua">The Lua VM to add the methods to</param> /// <param name="lua">The Lua VM to add the methods to</param>
/// <param name="o">The object to get the methods from</param> /// <param name="o">The object to get the methods from</param>
public static void TaggedInstanceMethods(Lua lua, object o) public static void TaggedInstanceMethods(Lua lua, object o)
{ {
#region Sanity checks #region Sanity checks
if (lua == null) throw new ArgumentNullException("lua"); if(lua.IsNull())
if (o == null) throw new ArgumentNullException("o"); throw new ArgumentNullException("lua");
#endregion
if(o.IsNull())
throw new ArgumentNullException("o");
#endregion
foreach(var method in o.GetType().GetMethods(BindingFlags.Instance | BindingFlags.Public))
{
foreach(LuaGlobalAttribute attribute in method.GetCustomAttributes(typeof(LuaGlobalAttribute), true))
{
if(string.IsNullOrEmpty(attribute.Name))
lua.RegisterFunction(method.Name, o, method); // CLR name
else
lua.RegisterFunction(attribute.Name, o, method); // Custom name
}
}
}
#endregion
#region Tagged static methods
/// <summary>
/// Registers all public static methods in a class tagged with <see cref="LuaGlobalAttribute"/> as Lua global functions
/// </summary>
/// <param name="lua">The Lua VM to add the methods to</param>
/// <param name="type">The class type to get the methods from</param>
public static void TaggedStaticMethods(Lua lua, Type type)
{
#region Sanity checks
if(lua.IsNull())
throw new ArgumentNullException("lua");
if(type.IsNull())
throw new ArgumentNullException("type");
foreach (MethodInfo method in o.GetType().GetMethods(BindingFlags.Instance | BindingFlags.Public)) if(!type.IsClass)
{ throw new ArgumentException("The type must be a class!", "type");
foreach (LuaGlobalAttribute attribute in method.GetCustomAttributes(typeof(LuaGlobalAttribute), true)) #endregion
{
if (string.IsNullOrEmpty(attribute.Name))
lua.RegisterFunction(method.Name, o, method); // CLR name
else
lua.RegisterFunction(attribute.Name, o, method); // Custom name
}
}
}
#endregion
#region Tagged static methods foreach(var method in type.GetMethods(BindingFlags.Static | BindingFlags.Public))
/// <summary> {
/// Registers all public static methods in a class tagged with <see cref="LuaGlobalAttribute"/> as Lua global functions foreach(LuaGlobalAttribute attribute in method.GetCustomAttributes(typeof(LuaGlobalAttribute), false))
/// </summary> {
/// <param name="lua">The Lua VM to add the methods to</param> if(string.IsNullOrEmpty(attribute.Name))
/// <param name="type">The class type to get the methods from</param> lua.RegisterFunction(method.Name, null, method); // CLR name
public static void TaggedStaticMethods(Lua lua, Type type) else
{ lua.RegisterFunction(attribute.Name, null, method); // Custom name
#region Sanity checks }
if (lua == null) throw new ArgumentNullException("lua"); }
if (type == null) throw new ArgumentNullException("type"); }
if (!type.IsClass) throw new ArgumentException("The type must be a class!", "type"); #endregion
#endregion
foreach (MethodInfo method in type.GetMethods(BindingFlags.Static | BindingFlags.Public)) #region Enumeration
{ /// <summary>
foreach (LuaGlobalAttribute attribute in method.GetCustomAttributes(typeof(LuaGlobalAttribute), false)) /// Registers an enumeration's values for usage as a Lua variable table
{ /// </summary>
if (string.IsNullOrEmpty(attribute.Name)) /// <typeparam name="T">The enum type to register</typeparam>
lua.RegisterFunction(method.Name, null, method); // CLR name /// <param name="lua">The Lua VM to add the enum to</param>
else [SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter", Justification = "The type parameter is used to select an enum type")]
lua.RegisterFunction(attribute.Name, null, method); // Custom name public static void Enumeration<T>(Lua lua)
} {
} #region Sanity checks
} if(lua.IsNull())
#endregion throw new ArgumentNullException("lua");
#endregion
#region Enumeration var type = typeof(T);
/// <summary>
/// Registers an enumeration's values for usage as a Lua variable table
/// </summary>
/// <typeparam name="T">The enum type to register</typeparam>
/// <param name="lua">The Lua VM to add the enum to</param>
[SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter", Justification = "The type parameter is used to select an enum type")]
public static void Enumeration<T>(Lua lua)
{
#region Sanity checks
if (lua == null) throw new ArgumentNullException("lua");
#endregion
Type type = typeof(T); if(!type.IsEnum)
if (!type.IsEnum) throw new ArgumentException("The type must be an enumeration!"); throw new ArgumentException("The type must be an enumeration!");
string[] names = Enum.GetNames(type); string[] names = Enum.GetNames(type);
var values = (T[])Enum.GetValues(type); var values = (T[])Enum.GetValues(type);
lua.NewTable(type.Name);
lua.NewTable(type.Name); for(int i = 0; i < names.Length; i++)
for (int i = 0; i < names.Length; i++) {
{ string path = type.Name + "." + names[i];
string path = type.Name + "." + names[i]; lua[path] = values[i];
lua[path] = values[i]; }
} }
} #endregion
#endregion }
}
} }
\ No newline at end of file
...@@ -30,94 +30,97 @@ using System.Collections.Generic; ...@@ -30,94 +30,97 @@ using System.Collections.Generic;
namespace LuaInterface namespace LuaInterface
{ {
/* using LuaCore = KopiLua.Lua;
/*
* Wrapper class for Lua tables * Wrapper class for Lua tables
* *
* Author: Fabio Mascarenhas * Author: Fabio Mascarenhas
* Version: 1.0 * Version: 1.0
*/ */
public class LuaTable : LuaBase public class LuaTable : LuaBase
{ {
public LuaTable(int reference, Lua interpreter) public LuaTable(int reference, Lua interpreter)
{ {
_Reference = reference; _Reference = reference;
_Interpreter = interpreter; _Interpreter = interpreter;
} }
/*
* Indexer for string fields of the table
*/
public object this[string field]
{
get
{
return _Interpreter.getObject(_Reference, field);
}
set
{
_Interpreter.setObject(_Reference, field, value);
}
}
/* /*
* Indexer for string fields of the table * Indexer for numeric fields of the table
*/ */
public object this[string field] public object this[object field]
{ {
get get
{ {
return _Interpreter.getObject(_Reference, field); return _Interpreter.getObject(_Reference, field);
} }
set set
{ {
_Interpreter.setObject(_Reference, field, value); _Interpreter.setObject(_Reference, field, value);
} }
} }
/*
* Indexer for numeric fields of the table
*/
public object this[object field]
{
get
{
return _Interpreter.getObject(_Reference, field);
}
set
{
_Interpreter.setObject(_Reference, field, value);
}
}
public System.Collections.IDictionaryEnumerator GetEnumerator()
{
return _Interpreter.GetTableDict(this).GetEnumerator();
}
public System.Collections.IDictionaryEnumerator GetEnumerator() public ICollection Keys
{ {
return _Interpreter.GetTableDict(this).GetEnumerator(); get { return _Interpreter.GetTableDict(this).Keys; }
} }
public ICollection Keys public ICollection Values
{ {
get { return _Interpreter.GetTableDict(this).Keys; } get { return _Interpreter.GetTableDict(this).Values; }
} }
public ICollection Values /*
{ * Gets an string fields of a table ignoring its metatable,
get { return _Interpreter.GetTableDict(this).Values; } * if it exists
} */
internal object rawget(string field)
{
return _Interpreter.rawGetObject(_Reference, field);
}
/* internal object rawgetFunction(string field)
* Gets an string fields of a table ignoring its metatable, {
* if it exists object obj = _Interpreter.rawGetObject(_Reference, field);
*/
internal object rawget(string field)
{
return _Interpreter.rawGetObject(_Reference, field);
}
internal object rawgetFunction(string field) if(obj is LuaCore.lua_CFunction)
{ return new LuaFunction((LuaCore.lua_CFunction)obj, _Interpreter);
object obj = _Interpreter.rawGetObject(_Reference, field); else
return obj;
}
if (obj is KopiLua.Lua.lua_CFunction) /*
return new LuaFunction((KopiLua.Lua.lua_CFunction)obj, _Interpreter); * Pushes this table into the Lua stack
else */
return obj; internal void push(LuaCore.lua_State luaState)
} {
LuaLib.lua_getref(luaState, _Reference);
}
/* public override string ToString()
* Pushes this table into the Lua stack {
*/ return "table";
internal void push(KopiLua.Lua.lua_State luaState) }
{ }
LuaLib.lua_getref(luaState, _Reference); }
} \ No newline at end of file
public override string ToString()
{
return "table";
}
}
}
...@@ -29,60 +29,66 @@ using System.Collections.Generic; ...@@ -29,60 +29,66 @@ using System.Collections.Generic;
namespace LuaInterface namespace LuaInterface
{ {
public class LuaUserData : LuaBase using LuaCore = KopiLua.Lua;
{
public LuaUserData(int reference, Lua interpreter)
{
_Reference = reference;
_Interpreter = interpreter;
}
/* public class LuaUserData : LuaBase
* Indexer for string fields of the userdata {
*/ public LuaUserData(int reference, Lua interpreter)
public object this[string field] {
{ _Reference = reference;
get _Interpreter = interpreter;
{ }
return _Interpreter.getObject(_Reference, field);
} /*
set * Indexer for string fields of the userdata
{ */
_Interpreter.setObject(_Reference, field, value); public object this[string field]
} {
} get
/* {
* Indexer for numeric fields of the userdata return _Interpreter.getObject(_Reference, field);
*/ }
public object this[object field] set
{ {
get _Interpreter.setObject(_Reference, field, value);
{ }
return _Interpreter.getObject(_Reference, field); }
}
set /*
{ * Indexer for numeric fields of the userdata
_Interpreter.setObject(_Reference, field, value); */
} public object this[object field]
} {
/* get
* Calls the userdata and returns its return values inside {
* an array return _Interpreter.getObject(_Reference, field);
*/ }
public object[] Call(params object[] args) set
{ {
return _Interpreter.callFunction(this, args); _Interpreter.setObject(_Reference, field, value);
} }
/* }
* Pushes the userdata into the Lua stack
*/ /*
internal void push(KopiLua.Lua.lua_State luaState) * Calls the userdata and returns its return values inside
{ * an array
LuaLib.lua_getref(luaState, _Reference); */
} public object[] Call(params object[] args)
public override string ToString() {
{ return _Interpreter.callFunction(this, args);
return "userdata"; }
}
} /*
* Pushes the userdata into the Lua stack
*/
internal void push(LuaCore.lua_State luaState)
{
LuaLib.lua_getref(luaState, _Reference);
}
public override string ToString()
{
return "userdata";
}
}
} }
\ No newline at end of file
...@@ -30,937 +30,957 @@ using System.Reflection; ...@@ -30,937 +30,957 @@ using System.Reflection;
using System.Diagnostics; using System.Diagnostics;
using System.Collections.Generic; using System.Collections.Generic;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using LuaInterface.Method;
using LuaInterface.Extensions;
namespace LuaInterface namespace LuaInterface
{ {
/* using LuaCore = KopiLua.Lua;
* Functions used in the metatables of userdata representing
* CLR objects /*
* * Functions used in the metatables of userdata representing
* Author: Fabio Mascarenhas * CLR objects
* Version: 1.0 *
*/ * Author: Fabio Mascarenhas
class MetaFunctions * Version: 1.0
{ */
/* class MetaFunctions
* __index metafunction for CLR objects. Implemented in Lua. {
*/ internal LuaCore.lua_CFunction gcFunction, indexFunction, newindexFunction, baseIndexFunction,
internal static string luaIndexFunction = classIndexFunction, classNewindexFunction, execDelegateFunction, callConstructorFunction, toStringFunction;
"local function index(obj,name)\n" + private Hashtable memberCache = new Hashtable();
" local meta=getmetatable(obj)\n" + private ObjectTranslator translator;
" local cached=meta.cache[name]\n" +
" if cached~=nil then\n" + /*
" return cached\n" + * __index metafunction for CLR objects. Implemented in Lua.
" else\n" + */
" local value,isFunc=get_object_member(obj,name)\n" + internal static string luaIndexFunction =
" if isFunc then\n" + "local function index(obj,name) \n" +
" meta.cache[name]=value\n" + " local meta=getmetatable(obj) \n" +
" end\n" + " local cached=meta.cache[name] \n" +
" return value\n" + " if cached~=nil then \n" +
" end\n" + " return cached \n" +
"end\n" + " else \n" +
"return index"; " local value,isFunc=get_object_member(obj,name) \n" +
" if isFunc then \n" +
private ObjectTranslator translator; " meta.cache[name]=value \n" +
private Hashtable memberCache = new Hashtable(); " end \n" +
internal KopiLua.Lua.lua_CFunction gcFunction, indexFunction, newindexFunction, " return value \n" +
baseIndexFunction, classIndexFunction, classNewindexFunction, " end \n" +
execDelegateFunction, callConstructorFunction, toStringFunction; "end \n" +
"return index ";
public MetaFunctions(ObjectTranslator translator)
{ public MetaFunctions(ObjectTranslator translator)
this.translator = translator; {
gcFunction = new KopiLua.Lua.lua_CFunction(this.collectObject); this.translator = translator;
toStringFunction = new KopiLua.Lua.lua_CFunction(this.toString); gcFunction = new LuaCore.lua_CFunction(this.collectObject);
indexFunction = new KopiLua.Lua.lua_CFunction(this.getMethod); toStringFunction = new LuaCore.lua_CFunction(this.toString);
newindexFunction = new KopiLua.Lua.lua_CFunction(this.setFieldOrProperty); indexFunction = new LuaCore.lua_CFunction(this.getMethod);
baseIndexFunction = new KopiLua.Lua.lua_CFunction(this.getBaseMethod); newindexFunction = new LuaCore.lua_CFunction(this.setFieldOrProperty);
callConstructorFunction = new KopiLua.Lua.lua_CFunction(this.callConstructor); baseIndexFunction = new LuaCore.lua_CFunction(this.getBaseMethod);
classIndexFunction = new KopiLua.Lua.lua_CFunction(this.getClassMethod); callConstructorFunction = new LuaCore.lua_CFunction(this.callConstructor);
classNewindexFunction = new KopiLua.Lua.lua_CFunction(this.setClassFieldOrProperty); classIndexFunction = new LuaCore.lua_CFunction(this.getClassMethod);
execDelegateFunction = new KopiLua.Lua.lua_CFunction(this.runFunctionDelegate); classNewindexFunction = new LuaCore.lua_CFunction(this.setClassFieldOrProperty);
} execDelegateFunction = new LuaCore.lua_CFunction(this.runFunctionDelegate);
}
/*
* __call metafunction of CLR delegates, retrieves and calls the delegate. /*
*/ * __call metafunction of CLR delegates, retrieves and calls the delegate.
private int runFunctionDelegate(KopiLua.Lua.lua_State luaState) */
{ private int runFunctionDelegate(LuaCore.lua_State luaState)
KopiLua.Lua.lua_CFunction func = (KopiLua.Lua.lua_CFunction)translator.getRawNetObject(luaState, 1); {
KopiLua.Lua.lua_remove(luaState, 1); LuaCore.lua_CFunction func = (LuaCore.lua_CFunction)translator.getRawNetObject(luaState, 1);
return func(luaState); LuaCore.lua_remove(luaState, 1);
} return func(luaState);
/* }
* __gc metafunction of CLR objects.
*/ /*
private int collectObject(KopiLua.Lua.lua_State luaState) * __gc metafunction of CLR objects.
{ */
int udata = LuaLib.luanet_rawnetobj(luaState, 1); private int collectObject(LuaCore.lua_State luaState)
if (udata != -1) {
{ int udata = LuaLib.luanet_rawnetobj(luaState, 1);
translator.collectObject(udata);
} if(udata != -1)
else translator.collectObject(udata);
{ else
// Debug.WriteLine("not found: " + udata); {
} // Debug.WriteLine("not found: " + udata);
return 0; }
}
/* return 0;
* __tostring metafunction of CLR objects. }
*/
private int toString(KopiLua.Lua.lua_State luaState) /*
{ * __tostring metafunction of CLR objects.
object obj = translator.getRawNetObject(luaState, 1); */
if (obj != null) private int toString(LuaCore.lua_State luaState)
{ {
translator.push(luaState, obj.ToString() + ": " + obj.GetHashCode()); object obj = translator.getRawNetObject(luaState, 1);
}
else KopiLua.Lua.lua_pushnil(luaState); if(!obj.IsNull())
return 1; translator.push(luaState, obj.ToString() + ": " + obj.GetHashCode());
} else
LuaCore.lua_pushnil(luaState);
/// <summary> return 1;
/// Debug tool to dump the lua stack }
/// </summary>
/// FIXME, move somewhere else
public static void dumpStack(ObjectTranslator translator, KopiLua.Lua.lua_State luaState) /// <summary>
{ /// Debug tool to dump the lua stack
int depth = KopiLua.Lua.lua_gettop(luaState); /// </summary>
/// FIXME, move somewhere else
Debug.WriteLine("lua stack depth: " + depth); public static void dumpStack(ObjectTranslator translator, LuaCore.lua_State luaState)
for (int i = 1; i <= depth; i++) {
{ int depth = LuaCore.lua_gettop(luaState);
LuaTypes type = KopiLua.Lua.lua_type(luaState, i).ToLuaTypes(); Debug.WriteLine("lua stack depth: " + depth);
// 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(); for(int i = 1; i <= depth; i++)
{
string strrep = KopiLua.Lua.lua_tostring(luaState, i).ToString(); var type = LuaCore.lua_type(luaState, i).ToLuaTypes();
if (type == LuaTypes.UserData) // 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" : LuaCore.lua_typename(luaState, (int)type).ToString();
object obj = translator.getRawNetObject(luaState, i); string strrep = LuaCore.lua_tostring(luaState, i).ToString();
strrep = obj.ToString();
} if(type == LuaTypes.UserData)
{
Debug.Print("{0}: ({1}) {2}", i, typestr, strrep); object obj = translator.getRawNetObject(luaState, i);
} strrep = obj.ToString();
} }
Debug.Print("{0}: ({1}) {2}", i, typestr, strrep);
/* }
* Called by the __index metafunction of CLR objects in case the }
* method is not cached or it is a field/property/event.
* Receives the object and the member name as arguments and returns /*
* either the value of the member or a delegate to call it. * Called by the __index metafunction of CLR objects in case the
* If the member does not exist returns nil. * method is not cached or it is a field/property/event.
*/ * Receives the object and the member name as arguments and returns
private int getMethod(KopiLua.Lua.lua_State luaState) * either the value of the member or a delegate to call it.
{ * If the member does not exist returns nil.
object obj = translator.getRawNetObject(luaState, 1); */
if (obj == null) private int getMethod(LuaCore.lua_State luaState)
{ {
translator.throwError(luaState, "trying to index an invalid object reference"); object obj = translator.getRawNetObject(luaState, 1);
KopiLua.Lua.lua_pushnil(luaState);
return 1; if(obj.IsNull())
} {
translator.throwError(luaState, "trying to index an invalid object reference");
object index = translator.getObject(luaState, 2); LuaCore.lua_pushnil(luaState);
Type indexType = index.GetType(); return 1;
}
string methodName = index as string; // will be null if not a string arg
Type objType = obj.GetType(); object index = translator.getObject(luaState, 2);
var indexType = index.GetType();
// Handle the most common case, looking up the method by name. string methodName = index as string; // will be null if not a string arg
var objType = obj.GetType();
// CP: This will fail when using indexers and attempting to get a value with the same name as a property of the object,
// ie: xmlelement['item'] <- item is a property of xmlelement // Handle the most common case, looking up the method by name.
try
{ // CP: This will fail when using indexers and attempting to get a value with the same name as a property of the object,
if (methodName != null && isMemberPresent(objType, methodName)) // ie: xmlelement['item'] <- item is a property of xmlelement
return getMember(luaState, objType, obj, methodName, BindingFlags.Instance | BindingFlags.IgnoreCase); try
} {
catch { } if(!methodName.IsNull() && isMemberPresent(objType, methodName))
return getMember(luaState, objType, obj, methodName, BindingFlags.Instance | BindingFlags.IgnoreCase);
// 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) catch
{ {
int intIndex = (int)((double)index); }
if (objType.UnderlyingSystemType == typeof(float[])) // 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)
float[] arr = ((float[])obj); {
translator.push(luaState, arr[intIndex]); int intIndex = (int)((double)index);
}
else if (objType.UnderlyingSystemType == typeof(double[])) if(objType.UnderlyingSystemType == typeof(float[]))
{ {
double[] arr = ((double[])obj); float[] arr = ((float[])obj);
translator.push(luaState, arr[intIndex]); translator.push(luaState, arr[intIndex]);
} }
else if (objType.UnderlyingSystemType == typeof(int[])) else if(objType.UnderlyingSystemType == typeof(double[]))
{ {
int[] arr = ((int[])obj); double[] arr = ((double[])obj);
translator.push(luaState, arr[intIndex]); translator.push(luaState, arr[intIndex]);
} }
else else if(objType.UnderlyingSystemType == typeof(int[]))
{ {
object[] arr = (object[])obj; int[] arr = ((int[])obj);
translator.push(luaState, arr[intIndex]); translator.push(luaState, arr[intIndex]);
} }
} else
else {
{ object[] arr = (object[])obj;
// Try to use get_Item to index into this .net object translator.push(luaState, arr[intIndex]);
//MethodInfo getter = objType.GetMethod("get_Item"); }
MethodInfo[] methods = objType.GetMethods(); }
else
foreach (MethodInfo mInfo in methods) {
{ // Try to use get_Item to index into this .net object
if (mInfo.Name == "get_Item") //MethodInfo getter = objType.GetMethod("get_Item");
{ var methods = objType.GetMethods();
//check if the signature matches the input
if (mInfo.GetParameters().Length == 1) foreach(var mInfo in methods)
{ {
MethodInfo getter = mInfo; if(mInfo.Name == "get_Item")
ParameterInfo[] actualParms = (getter != null) ? getter.GetParameters() : null; {
//check if the signature matches the input
if (actualParms == null || actualParms.Length != 1) if(mInfo.GetParameters().Length == 1)
{ {
translator.throwError(luaState, "method not found (or no indexer): " + index); var getter = mInfo;
var actualParms = (!getter.IsNull()) ? getter.GetParameters() : null;
KopiLua.Lua.lua_pushnil(luaState);
} if(actualParms.IsNull() || actualParms.Length != 1)
else {
{ translator.throwError(luaState, "method not found (or no indexer): " + index);
// Get the index in a form acceptable to the getter LuaCore.lua_pushnil(luaState);
index = translator.getAsType(luaState, 2, actualParms[0].ParameterType); }
else
object[] args = new object[1]; {
// Get the index in a form acceptable to the getter
// Just call the indexer - if out of bounds an exception will happen index = translator.getAsType(luaState, 2, actualParms[0].ParameterType);
args[0] = index; object[] args = new object[1];
try
{ // Just call the indexer - if out of bounds an exception will happen
object result = getter.Invoke(obj, args); args[0] = index;
translator.push(luaState, result);
} try
catch (TargetInvocationException e) {
{ object result = getter.Invoke(obj, args);
// Provide a more readable description for the common case of key not found translator.push(luaState, result);
if (e.InnerException is KeyNotFoundException) }
translator.throwError(luaState, "key '" + index + "' not found "); catch(TargetInvocationException e)
else {
translator.throwError(luaState, "exception indexing '" + index + "' " + e.Message); // Provide a more readable description for the common case of key not found
if(e.InnerException is KeyNotFoundException)
KopiLua.Lua.lua_pushnil(luaState); translator.throwError(luaState, "key '" + index + "' not found ");
} else
} translator.throwError(luaState, "exception indexing '" + index + "' " + e.Message);
}
} LuaCore.lua_pushnil(luaState);
} }
}
}
} }
}
KopiLua.Lua.lua_pushboolean(luaState, 0); }
return 2;
} 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. * __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) object obj = translator.getRawNetObject(luaState, 1);
{
translator.throwError(luaState, "trying to index an invalid object reference"); if(obj.IsNull())
KopiLua.Lua.lua_pushnil(luaState); {
KopiLua.Lua.lua_pushboolean(luaState, 0); translator.throwError(luaState, "trying to index an invalid object reference");
return 2; LuaCore.lua_pushnil(luaState);
} LuaCore.lua_pushboolean(luaState, 0);
string methodName = KopiLua.Lua.lua_tostring(luaState, 2).ToString(); return 2;
if (methodName == null) }
{
KopiLua.Lua.lua_pushnil(luaState); string methodName = LuaCore.lua_tostring(luaState, 2).ToString();
KopiLua.Lua.lua_pushboolean(luaState, 0);
return 2; if(methodName.IsNull())
} {
getMember(luaState, obj.GetType(), obj, "__luaInterface_base_" + methodName, BindingFlags.Instance | BindingFlags.IgnoreCase); LuaCore.lua_pushnil(luaState);
KopiLua.Lua.lua_settop(luaState, -2); LuaCore.lua_pushboolean(luaState, 0);
if (KopiLua.Lua.lua_type(luaState, -1).ToLuaTypes() == LuaTypes.Nil) return 2;
{ }
KopiLua.Lua.lua_settop(luaState, -2);
return getMember(luaState, obj.GetType(), obj, methodName, BindingFlags.Instance | BindingFlags.IgnoreCase); getMember(luaState, obj.GetType(), obj, "__luaInterface_base_" + methodName, BindingFlags.Instance | BindingFlags.IgnoreCase);
} LuaCore.lua_settop(luaState, -2);
KopiLua.Lua.lua_pushboolean(luaState, 0);
return 2; if(LuaCore.lua_type(luaState, -1).ToLuaTypes() == LuaTypes.Nil)
} {
LuaCore.lua_settop(luaState, -2);
return getMember(luaState, obj.GetType(), obj, methodName, BindingFlags.Instance | BindingFlags.IgnoreCase);
/// <summary> }
/// Does this method exist as either an instance or static?
/// </summary> LuaCore.lua_pushboolean(luaState, 0);
/// <param name="objType"></param> return 2;
/// <param name="methodName"></param> }
/// <returns></returns>
bool isMemberPresent(IReflect objType, string methodName) /// <summary>
{ /// Does this method exist as either an instance or static?
object cachedMember = checkMemberCache(memberCache, objType, methodName); /// </summary>
/// <param name="objType"></param>
if (cachedMember != null) /// <param name="methodName"></param>
return true; /// <returns></returns>
bool isMemberPresent(IReflect objType, string methodName)
//CP: Removed NonPublic binding search {
MemberInfo[] members = objType.GetMember(methodName, BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase/* | BindingFlags.NonPublic*/); object cachedMember = checkMemberCache(memberCache, objType, methodName);
return (members.Length > 0);
} if(!cachedMember.IsNull())
return true;
/*
* Pushes the value of a member or a delegate to call it, depending on the type of //CP: Removed NonPublic binding search
* the member. Works with static or instance members. var members = objType.GetMember(methodName, BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase/* | BindingFlags.NonPublic*/);
* Uses reflection to find members, and stores the reflected MemberInfo object in return (members.Length > 0);
* 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) /*
{ * Pushes the value of a member or a delegate to call it, depending on the type of
bool implicitStatic = false; * the member. Works with static or instance members.
MemberInfo member = null; * Uses reflection to find members, and stores the reflected MemberInfo object in
object cachedMember = checkMemberCache(memberCache, objType, methodName); * a cache (indexed by the type of the object and the name of the member).
//object cachedMember=null; */
if (cachedMember is KopiLua.Lua.lua_CFunction) private int getMember(LuaCore.lua_State luaState, IReflect objType, object obj, string methodName, BindingFlags bindingType)
{ {
translator.pushFunction(luaState, (KopiLua.Lua.lua_CFunction)cachedMember); bool implicitStatic = false;
translator.push(luaState, true); MemberInfo member = null;
return 2; object cachedMember = checkMemberCache(memberCache, objType, methodName);
} //object cachedMember=null;
else if (cachedMember != null)
{ if(cachedMember is LuaCore.lua_CFunction)
member = (MemberInfo)cachedMember; {
} translator.pushFunction(luaState, (LuaCore.lua_CFunction)cachedMember);
else translator.push(luaState, true);
{ return 2;
//CP: Removed NonPublic binding search }
MemberInfo[] members = objType.GetMember(methodName, bindingType | BindingFlags.Public | BindingFlags.IgnoreCase/*| BindingFlags.NonPublic*/); else if(!cachedMember.IsNull())
if (members.Length > 0) member = (MemberInfo)cachedMember;
member = members[0]; else
else {
{ //CP: Removed NonPublic binding search
// If we can't find any suitable instance members, try to find them as statics - but we only want to allow implicit static var members = objType.GetMember(methodName, bindingType | BindingFlags.Public | BindingFlags.IgnoreCase/*| BindingFlags.NonPublic*/);
// lookups for fields/properties/events -kevinh
//CP: Removed NonPublic binding search and made case insensitive if(members.Length > 0)
members = objType.GetMember(methodName, bindingType | BindingFlags.Static | BindingFlags.Public | BindingFlags.IgnoreCase/*| BindingFlags.NonPublic*/); member = members[0];
else
if (members.Length > 0) {
{ // If we can't find any suitable instance members, try to find them as statics - but we only want to allow implicit static
member = members[0]; // lookups for fields/properties/events -kevinh
implicitStatic = true; //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 (member != null) {
{ member = members[0];
if (member.MemberType == MemberTypes.Field) implicitStatic = true;
{ }
FieldInfo field = (FieldInfo)member; }
if (cachedMember == null) setMemberCache(memberCache, objType, methodName, member); }
try
{ if(!member.IsNull())
translator.push(luaState, field.GetValue(obj)); {
} if(member.MemberType == MemberTypes.Field)
catch {
{ var field = (FieldInfo)member;
KopiLua.Lua.lua_pushnil(luaState);
} if(cachedMember.IsNull())
} setMemberCache(memberCache, objType, methodName, member);
else if (member.MemberType == MemberTypes.Property)
{ try
PropertyInfo property = (PropertyInfo)member; {
if (cachedMember == null) setMemberCache(memberCache, objType, methodName, member); translator.push(luaState, field.GetValue(obj));
try }
{ catch
object val = property.GetValue(obj, null); {
LuaCore.lua_pushnil(luaState);
translator.push(luaState, val); }
} }
catch (ArgumentException) else if(member.MemberType == MemberTypes.Property)
{ {
// If we can't find the getter in our class, recurse up to the base class and see var property = (PropertyInfo)member;
// if they can help. if(cachedMember.IsNull())
setMemberCache(memberCache, objType, methodName, member);
if (objType is Type && !(((Type)objType) == typeof(object)))
return getMember(luaState, ((Type)objType).BaseType, obj, methodName, bindingType); try
else {
KopiLua.Lua.lua_pushnil(luaState); object val = property.GetValue(obj, null);
} translator.push(luaState, val);
catch (TargetInvocationException e) // Convert this exception into a Lua error }
{ catch(ArgumentException)
ThrowError(luaState, e); {
KopiLua.Lua.lua_pushnil(luaState); // 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)))
else if (member.MemberType == MemberTypes.Event) return getMember(luaState, ((Type)objType).BaseType, obj, methodName, bindingType);
{ else
EventInfo eventInfo = (EventInfo)member; LuaCore.lua_pushnil(luaState);
if (cachedMember == null) setMemberCache(memberCache, objType, methodName, member); }
translator.push(luaState, new RegisterEventHandler(translator.pendingEvents, obj, eventInfo)); catch(TargetInvocationException e) // Convert this exception into a Lua error
} {
else if (!implicitStatic) ThrowError(luaState, e);
{ LuaCore.lua_pushnil(luaState);
if (member.MemberType == MemberTypes.NestedType) }
{ }
// kevinh - added support for finding nested types else if(member.MemberType == MemberTypes.Event)
{
// cache us var eventInfo = (EventInfo)member;
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; translator.push(luaState, new RegisterEventHandler(translator.pendingEvents, obj, eventInfo));
Type dectype = member.DeclaringType; }
else if(!implicitStatic)
// Build a new long name and try to find the type by name {
string longname = dectype.FullName + "+" + name; if(member.MemberType == MemberTypes.NestedType)
Type nestedType = translator.FindType(longname); {
// kevinh - added support for finding nested types
translator.pushType(luaState, nestedType); // cache us
} if(cachedMember.IsNull())
else setMemberCache(memberCache, objType, methodName, member);
{
// Member type must be 'method' // Find the name of our class
KopiLua.Lua.lua_CFunction wrapper = new KopiLua.Lua.lua_CFunction((new LuaMethodWrapper(translator, objType, methodName, bindingType)).call); string name = member.Name;
var dectype = member.DeclaringType;
if (cachedMember == null) setMemberCache(memberCache, objType, methodName, wrapper);
translator.pushFunction(luaState, wrapper); // Build a new long name and try to find the type by name
translator.push(luaState, true); string longname = dectype.FullName + "+" + name;
return 2; var nestedType = translator.FindType(longname);
} translator.pushType(luaState, nestedType);
} }
else else
{ {
// 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 // Member type must be 'method'
translator.throwError(luaState, "can't pass instance to static method " + methodName); var wrapper = new LuaCore.lua_CFunction((new LuaMethodWrapper(translator, objType, methodName, bindingType)).call);
KopiLua.Lua.lua_pushnil(luaState); if(cachedMember.IsNull())
} setMemberCache(memberCache, objType, methodName, wrapper);
}
else translator.pushFunction(luaState, wrapper);
{ translator.push(luaState, true);
// kevinh - we want to throw an exception because meerly returning 'nil' in this case return 2;
// is not sufficient. valid data members may return nil and therefore there must be some }
// way to know the member just doesn't exist. }
else
translator.throwError(luaState, "unknown member name " + methodName); {
// 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
KopiLua.Lua.lua_pushnil(luaState); translator.throwError(luaState, "can't pass instance to static method " + methodName);
} LuaCore.lua_pushnil(luaState);
}
// push false because we are NOT returning a function (see luaIndexFunction) }
translator.push(luaState, false); else
return 2; {
} // 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
* Checks if a MemberInfo object is cached, returning it or null. // way to know the member just doesn't exist.
*/ translator.throwError(luaState, "unknown member name " + methodName);
private object checkMemberCache(Hashtable memberCache, IReflect objType, string memberName) LuaCore.lua_pushnil(luaState);
{ }
Hashtable members = (Hashtable)memberCache[objType];
if (members != null) // push false because we are NOT returning a function (see luaIndexFunction)
return members[memberName]; translator.push(luaState, false);
else return 2;
return null; }
}
/* /*
* Stores a MemberInfo object in the member cache. * Checks if a MemberInfo object is cached, returning it or null.
*/ */
private void setMemberCache(Hashtable memberCache, IReflect objType, string memberName, object member) private object checkMemberCache(Hashtable memberCache, IReflect objType, string memberName)
{ {
Hashtable members = (Hashtable)memberCache[objType]; var members = (Hashtable)memberCache[objType];
if (members == null) return !members.IsNull() ? members[memberName] : null;
{ }
members = new Hashtable();
memberCache[objType] = members; /*
} * Stores a MemberInfo object in the member cache.
members[memberName] = member; */
} private void setMemberCache(Hashtable memberCache, IReflect objType, string memberName, object member)
/* {
* __newindex metafunction of CLR objects. Receives the object, var members = (Hashtable)memberCache[objType];
* the member name and the value to be stored as arguments. Throws
* and error if the assignment is invalid. if(members.IsNull())
*/ {
private int setFieldOrProperty(KopiLua.Lua.lua_State luaState) members = new Hashtable();
{ memberCache[objType] = members;
object target = translator.getRawNetObject(luaState, 1); }
if (target == null)
{ members[memberName] = member;
translator.throwError(luaState, "trying to index and invalid object reference"); }
return 0;
} /*
Type type = target.GetType(); * __newindex metafunction of CLR objects. Receives the object,
* the member name and the value to be stored as arguments. Throws
// First try to look up the parameter as a property name * and error if the assignment is invalid.
string detailMessage; */
bool didMember = trySetMember(luaState, type, target, BindingFlags.Instance | BindingFlags.IgnoreCase, out detailMessage); private int setFieldOrProperty(LuaCore.lua_State luaState)
{
if (didMember) object target = translator.getRawNetObject(luaState, 1);
return 0; // Must have found the property name
if(target.IsNull())
// We didn't find a property name, now see if we can use a [] style this accessor to set array contents {
try translator.throwError(luaState, "trying to index and invalid object reference");
{ return 0;
if (type.IsArray && KopiLua.Lua.lua_isnumber(luaState, 2).ToBoolean()) }
{
int index = (int)KopiLua.Lua.lua_tonumber(luaState, 2); var type = target.GetType();
Array arr = (Array)target; // First try to look up the parameter as a property name
object val = translator.getAsType(luaState, 3, arr.GetType().GetElementType()); string detailMessage;
arr.SetValue(val, index); bool didMember = trySetMember(luaState, type, target, BindingFlags.Instance | BindingFlags.IgnoreCase, out detailMessage);
}
else if(didMember)
{ return 0; // Must have found the property name
// Try to see if we have a this[] accessor
MethodInfo setter = type.GetMethod("set_Item"); // We didn't find a property name, now see if we can use a [] style this accessor to set array contents
if (setter != null) try
{ {
ParameterInfo[] args = setter.GetParameters(); if(type.IsArray && LuaCore.lua_isnumber(luaState, 2).ToBoolean())
Type valueType = args[1].ParameterType; {
int index = (int)LuaCore.lua_tonumber(luaState, 2);
// The new val ue the user specified var arr = (Array)target;
object val = translator.getAsType(luaState, 3, valueType); object val = translator.getAsType(luaState, 3, arr.GetType().GetElementType());
arr.SetValue(val, index);
Type indexType = args[0].ParameterType; }
object index = translator.getAsType(luaState, 2, indexType); else
{
object[] methodArgs = new object[2]; // Try to see if we have a this[] accessor
var setter = type.GetMethod("set_Item");
// Just call the indexer - if out of bounds an exception will happen if(!setter.IsNull())
methodArgs[0] = index; {
methodArgs[1] = val; var args = setter.GetParameters();
var valueType = args[1].ParameterType;
setter.Invoke(target, methodArgs);
} // The new val ue the user specified
else object val = translator.getAsType(luaState, 3, valueType);
{ var indexType = args[0].ParameterType;
translator.throwError(luaState, detailMessage); // Pass the original message from trySetMember because it is probably best object index = translator.getAsType(luaState, 2, indexType);
}
} object[] methodArgs = new object[2];
}
catch (SEHException) // Just call the indexer - if out of bounds an exception will happen
{ methodArgs[0] = index;
// If we are seeing a C++ exception - this must actually be for Lua's private use. Let it handle it methodArgs[1] = val;
throw; setter.Invoke(target, methodArgs);
} }
catch (Exception e) else
{ translator.throwError(luaState, detailMessage); // Pass the original message from trySetMember because it is probably best
ThrowError(luaState, e); }
} }
return 0; catch(SEHException)
} {
// If we are seeing a C++ exception - this must actually be for Lua's private use. Let it handle it
/// <summary> throw;
/// Tries to set a named property or field }
/// </summary> catch(Exception e)
/// <param name="luaState"></param> {
/// <param name="targetType"></param> ThrowError(luaState, e);
/// <param name="target"></param> }
/// <param name="bindingType"></param>
/// <returns>false if unable to find the named member, true for success</returns> return 0;
private bool trySetMember(KopiLua.Lua.lua_State luaState, IReflect targetType, object target, BindingFlags bindingType, out string detailMessage) }
{
detailMessage = null; // No error yet /// <summary>
/// Tries to set a named property or field
// If not already a string just return - we don't want to call tostring - which has the side effect of /// </summary>
// changing the lua typecode to string /// <param name="luaState"></param>
// Note: We don't use isstring because the standard lua C isstring considers either strings or numbers to /// <param name="targetType"></param>
// be true for isstring. /// <param name="target"></param>
if (KopiLua.Lua.lua_type(luaState, 2).ToLuaTypes() != LuaTypes.String) /// <param name="bindingType"></param>
{ /// <returns>false if unable to find the named member, true for success</returns>
detailMessage = "property names must be strings"; private bool trySetMember(LuaCore.lua_State luaState, IReflect targetType, object target, BindingFlags bindingType, out string detailMessage)
return false; {
} detailMessage = null; // No error yet
// We only look up property names by string // If not already a string just return - we don't want to call tostring - which has the side effect of
string fieldName = KopiLua.Lua.lua_tostring(luaState, 2).ToString(); // changing the lua typecode to string
if (fieldName == null || fieldName.Length < 1 || !(char.IsLetter(fieldName[0]) || fieldName[0] == '_')) // Note: We don't use isstring because the standard lua C isstring considers either strings or numbers to
{ // be true for isstring.
detailMessage = "invalid property name"; if(LuaCore.lua_type(luaState, 2).ToLuaTypes() != LuaTypes.String)
return false; {
} detailMessage = "property names must be strings";
return false;
// Find our member via reflection or the cache }
MemberInfo member = (MemberInfo)checkMemberCache(memberCache, targetType, fieldName);
if (member == null) // We only look up property names by string
{ string fieldName = LuaCore.lua_tostring(luaState, 2).ToString();
//CP: Removed NonPublic binding search and made case insensitive if(fieldName.IsNull() || fieldName.Length < 1 || !(char.IsLetter(fieldName[0]) || fieldName[0] == '_'))
MemberInfo[] members = targetType.GetMember(fieldName, bindingType | BindingFlags.Public | BindingFlags.IgnoreCase/*| BindingFlags.NonPublic*/); {
if (members.Length > 0) detailMessage = "invalid property name";
{ return false;
member = members[0]; }
setMemberCache(memberCache, targetType, fieldName, member);
} // Find our member via reflection or the cache
else var member = (MemberInfo)checkMemberCache(memberCache, targetType, fieldName);
{ if(member.IsNull())
detailMessage = "field or property '" + fieldName + "' does not exist"; {
return false; //CP: Removed NonPublic binding search and made case insensitive
} var members = targetType.GetMember(fieldName, bindingType | BindingFlags.Public | BindingFlags.IgnoreCase/*| BindingFlags.NonPublic*/);
}
if(members.Length > 0)
if (member.MemberType == MemberTypes.Field) {
{ member = members[0];
FieldInfo field = (FieldInfo)member; setMemberCache(memberCache, targetType, fieldName, member);
object val = translator.getAsType(luaState, 3, field.FieldType); }
try else
{ {
field.SetValue(target, val); detailMessage = "field or property '" + fieldName + "' does not exist";
} return false;
catch (Exception e) }
{ }
ThrowError(luaState, e);
} if(member.MemberType == MemberTypes.Field)
// We did a call {
return true; var field = (FieldInfo)member;
} object val = translator.getAsType(luaState, 3, field.FieldType);
else if (member.MemberType == MemberTypes.Property)
{ try
PropertyInfo property = (PropertyInfo)member; {
object val = translator.getAsType(luaState, 3, property.PropertyType); field.SetValue(target, val);
try }
{ catch (Exception e)
property.SetValue(target, val, null); {
} ThrowError(luaState, e);
catch (Exception e) }
{
ThrowError(luaState, e); // We did a call
} return true;
// We did a call }
return true; else if(member.MemberType == MemberTypes.Property)
} {
var property = (PropertyInfo)member;
detailMessage = "'" + fieldName + "' is not a .net field or property"; object val = translator.getAsType(luaState, 3, property.PropertyType);
return false;
} try
{
property.SetValue(target, val, null);
/* }
* Writes to fields or properties, either static or instance. Throws an error catch (Exception e)
* if the operation is invalid. {
*/ ThrowError(luaState, e);
private int setMember(KopiLua.Lua.lua_State luaState, IReflect targetType, object target, BindingFlags bindingType) }
{
string detail; // We did a call
bool success = trySetMember(luaState, targetType, target, bindingType, out detail); return true;
}
if (!success)
translator.throwError(luaState, detail); detailMessage = "'" + fieldName + "' is not a .net field or property";
return false;
return 0; }
}
/*
/// <summary> * Writes to fields or properties, either static or instance. Throws an error
/// Convert a C# exception into a Lua error * if the operation is invalid.
/// </summary> */
/// <param name="e"></param> private int setMember(LuaCore.lua_State luaState, IReflect targetType, object target, BindingFlags bindingType)
/// We try to look into the exception to give the most meaningful description {
void ThrowError(KopiLua.Lua.lua_State luaState, Exception e) string detail;
{ bool success = trySetMember(luaState, targetType, target, bindingType, out detail);
// If we got inside a reflection show what really happened
TargetInvocationException te = e as TargetInvocationException; if(!success)
translator.throwError(luaState, detail);
if (te != null)
e = te.InnerException; return 0;
}
translator.throwError(luaState, e);
} /// <summary>
/// Convert a C# exception into a Lua error
/* /// </summary>
* __index metafunction of type references, works on static members. /// <param name="e"></param>
*/ /// We try to look into the exception to give the most meaningful description
private int getClassMethod(KopiLua.Lua.lua_State luaState) void ThrowError(LuaCore.lua_State luaState, Exception e)
{ {
IReflect klass; // If we got inside a reflection show what really happened
object obj = translator.getRawNetObject(luaState, 1); var te = e as TargetInvocationException;
if (obj == null || !(obj is IReflect))
{ if (!te.IsNull())
translator.throwError(luaState, "trying to index an invalid type reference"); e = te.InnerException;
KopiLua.Lua.lua_pushnil(luaState);
return 1; translator.throwError(luaState, e);
} }
else klass = (IReflect)obj;
if (KopiLua.Lua.lua_isnumber(luaState, 2).ToBoolean()) /*
{ * __index metafunction of type references, works on static members.
int size = (int)KopiLua.Lua.lua_tonumber(luaState, 2); */
translator.push(luaState, Array.CreateInstance(klass.UnderlyingSystemType, size)); private int getClassMethod(LuaCore.lua_State luaState)
return 1; {
} IReflect klass;
else object obj = translator.getRawNetObject(luaState, 1);
{
string methodName = KopiLua.Lua.lua_tostring(luaState, 2).ToString(); if(obj.IsNull() || !(obj is IReflect))
if (methodName == null) {
{ translator.throwError(luaState, "trying to index an invalid type reference");
KopiLua.Lua.lua_pushnil(luaState); LuaCore.lua_pushnil(luaState);
return 1; return 1;
} //CP: Ignore case }
else return getMember(luaState, klass, null, methodName, BindingFlags.FlattenHierarchy | BindingFlags.Static | BindingFlags.IgnoreCase); else
} klass = (IReflect)obj;
}
/* if(LuaCore.lua_isnumber(luaState, 2).ToBoolean())
* __newindex function of type references, works on static members. {
*/ int size = (int)LuaCore.lua_tonumber(luaState, 2);
private int setClassFieldOrProperty(KopiLua.Lua.lua_State luaState) translator.push(luaState, Array.CreateInstance(klass.UnderlyingSystemType, size));
{ return 1;
IReflect target; }
object obj = translator.getRawNetObject(luaState, 1); else
if (obj == null || !(obj is IReflect)) {
{ string methodName = LuaCore.lua_tostring(luaState, 2).ToString();
translator.throwError(luaState, "trying to index an invalid type reference");
return 0; if(methodName.IsNull())
} {
else target = (IReflect)obj; LuaCore.lua_pushnil(luaState);
return setMember(luaState, target, null, BindingFlags.FlattenHierarchy | BindingFlags.Static | BindingFlags.IgnoreCase); return 1;
} } //CP: Ignore case
/* else
* __call metafunction of type references. Searches for and calls return getMember(luaState, klass, null, methodName, BindingFlags.FlattenHierarchy | BindingFlags.Static | BindingFlags.IgnoreCase);
* 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) * __newindex function of type references, works on static members.
{ */
MethodCache validConstructor = new MethodCache(); private int setClassFieldOrProperty(LuaCore.lua_State luaState)
IReflect klass; {
object obj = translator.getRawNetObject(luaState, 1); IReflect target;
if (obj == null || !(obj is IReflect)) object obj = translator.getRawNetObject(luaState, 1);
{
translator.throwError(luaState, "trying to call constructor on an invalid type reference"); if(obj.IsNull() || !(obj is IReflect))
KopiLua.Lua.lua_pushnil(luaState); {
return 1; translator.throwError(luaState, "trying to index an invalid type reference");
} return 0;
else klass = (IReflect)obj; }
KopiLua.Lua.lua_remove(luaState, 1); else
ConstructorInfo[] constructors = klass.UnderlyingSystemType.GetConstructors(); target = (IReflect)obj;
foreach (ConstructorInfo constructor in constructors)
{ return setMember(luaState, target, null, BindingFlags.FlattenHierarchy | BindingFlags.Static | BindingFlags.IgnoreCase);
bool isConstructor = matchParameters(luaState, constructor, ref validConstructor); }
if (isConstructor)
{ /*
try * __call metafunction of type references. Searches for and calls
{ * a constructor for the type. Returns nil if the constructor is not
translator.push(luaState, constructor.Invoke(validConstructor.args)); * found or if the arguments are invalid. Throws an error if the constructor
} * generates an exception.
catch (TargetInvocationException e) */
{ private int callConstructor(LuaCore.lua_State luaState)
ThrowError(luaState, e); {
KopiLua.Lua.lua_pushnil(luaState); var validConstructor = new MethodCache();
} IReflect klass;
catch object obj = translator.getRawNetObject(luaState, 1);
{
KopiLua.Lua.lua_pushnil(luaState); if(obj.IsNull() || !(obj is IReflect))
} {
return 1; translator.throwError(luaState, "trying to call constructor on an invalid type reference");
} LuaCore.lua_pushnil(luaState);
} return 1;
}
string constructorName = (constructors.Length == 0) ? "unknown" : constructors[0].Name; else
klass = (IReflect)obj;
translator.throwError(luaState, String.Format("{0} does not contain constructor({1}) argument match",
klass.UnderlyingSystemType, LuaCore.lua_remove(luaState, 1);
constructorName)); var constructors = klass.UnderlyingSystemType.GetConstructors();
KopiLua.Lua.lua_pushnil(luaState);
return 1; foreach(var constructor in constructors)
} {
/* bool isConstructor = matchParameters(luaState, constructor, ref validConstructor);
* Matches a method against its arguments in the Lua stack. Returns
* if the match was succesful. It it was also returns the information if(isConstructor)
* necessary to invoke the method. {
*/ try
internal bool matchParameters(KopiLua.Lua.lua_State luaState, MethodBase method, ref MethodCache methodCache) {
{ translator.push(luaState, constructor.Invoke(validConstructor.args));
ExtractValue extractValue; }
bool isMethod = true; catch(TargetInvocationException e)
ParameterInfo[] paramInfo = method.GetParameters(); {
int currentLuaParam = 1; ThrowError(luaState, e);
int nLuaParams = KopiLua.Lua.lua_gettop(luaState); LuaCore.lua_pushnil(luaState);
ArrayList paramList = new ArrayList(); }
List<int> outList = new List<int>(); catch
List<MethodArgs> argTypes = new List<MethodArgs>(); {
foreach (ParameterInfo currentNetParam in paramInfo) LuaCore.lua_pushnil(luaState);
{ }
if (!currentNetParam.IsIn && currentNetParam.IsOut) // Skips out params
{ return 1;
outList.Add(paramList.Add(null)); }
} }
else if (currentLuaParam > nLuaParams) // Adds optional parameters
{ string constructorName = (constructors.Length == 0) ? "unknown" : constructors[0].Name;
if (currentNetParam.IsOptional) translator.throwError(luaState, String.Format("{0} does not contain constructor({1}) argument match",
{ klass.UnderlyingSystemType, constructorName));
paramList.Add(currentNetParam.DefaultValue); LuaCore.lua_pushnil(luaState);
} return 1;
else }
{
isMethod = false; /*
break; * 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.
else if (_IsTypeCorrect(luaState, currentLuaParam, currentNetParam, out extractValue)) // Type checking */
{ internal bool matchParameters(LuaCore.lua_State luaState, MethodBase method, ref MethodCache methodCache)
int index = paramList.Add(extractValue(luaState, currentLuaParam)); {
ExtractValue extractValue;
MethodArgs methodArg = new MethodArgs(); bool isMethod = true;
methodArg.index = index; var paramInfo = method.GetParameters();
methodArg.extractValue = extractValue; int currentLuaParam = 1;
argTypes.Add(methodArg); int nLuaParams = LuaCore.lua_gettop(luaState);
var paramList = new ArrayList();
if (currentNetParam.ParameterType.IsByRef) var outList = new List<int>();
outList.Add(index); var argTypes = new List<MethodArgs>();
currentLuaParam++;
} // Type does not match, ignore if the parameter is optional foreach(var currentNetParam in paramInfo)
else if (_IsParamsArray(luaState, currentLuaParam, currentNetParam, out extractValue)) {
{ if(!currentNetParam.IsIn && currentNetParam.IsOut) // Skips out params
object luaParamValue = extractValue(luaState, currentLuaParam); outList.Add(paramList.Add(null));
else if(currentLuaParam > nLuaParams) // Adds optional parameters
Type paramArrayType = currentNetParam.ParameterType.GetElementType(); {
if(currentNetParam.IsOptional)
Array paramArray; paramList.Add(currentNetParam.DefaultValue);
else
if (luaParamValue is LuaTable) {
{ isMethod = false;
LuaTable table = (LuaTable)luaParamValue; break;
IDictionaryEnumerator tableEnumerator = table.GetEnumerator(); }
}
paramArray = Array.CreateInstance(paramArrayType, table.Values.Count); else if(_IsTypeCorrect(luaState, currentLuaParam, currentNetParam, out extractValue)) // Type checking
{
tableEnumerator.Reset(); int index = paramList.Add(extractValue(luaState, currentLuaParam));
var methodArg = new MethodArgs();
int paramArrayIndex = 0; methodArg.index = index;
methodArg.extractValue = extractValue;
while(tableEnumerator.MoveNext()) argTypes.Add(methodArg);
{
paramArray.SetValue(Convert.ChangeType(tableEnumerator.Value, currentNetParam.ParameterType.GetElementType()), paramArrayIndex); if(currentNetParam.ParameterType.IsByRef)
paramArrayIndex++; outList.Add(index);
}
} currentLuaParam++;
else } // Type does not match, ignore if the parameter is optional
{ else if(_IsParamsArray(luaState, currentLuaParam, currentNetParam, out extractValue))
paramArray = Array.CreateInstance(paramArrayType, 1); {
paramArray.SetValue(luaParamValue, 0); object luaParamValue = extractValue(luaState, currentLuaParam);
} var paramArrayType = currentNetParam.ParameterType.GetElementType();
Array paramArray;
int index = paramList.Add(paramArray);
if(luaParamValue is LuaTable)
MethodArgs methodArg = new MethodArgs(); {
methodArg.index = index; var table = (LuaTable)luaParamValue;
methodArg.extractValue = extractValue; var tableEnumerator = table.GetEnumerator();
methodArg.isParamsArray = true; paramArray = Array.CreateInstance(paramArrayType, table.Values.Count);
methodArg.paramsArrayType = paramArrayType; tableEnumerator.Reset();
argTypes.Add(methodArg); int paramArrayIndex = 0;
currentLuaParam++; while(tableEnumerator.MoveNext())
} {
else if (currentNetParam.IsOptional) paramArray.SetValue(Convert.ChangeType(tableEnumerator.Value, currentNetParam.ParameterType.GetElementType()), paramArrayIndex);
{ paramArrayIndex++;
paramList.Add(currentNetParam.DefaultValue); }
} }
else // No match else
{ {
isMethod = false; paramArray = Array.CreateInstance(paramArrayType, 1);
break; paramArray.SetValue(luaParamValue, 0);
} }
}
if (currentLuaParam != nLuaParams + 1) // Number of parameters does not match int index = paramList.Add(paramArray);
isMethod = false; var methodArg = new MethodArgs();
if (isMethod) methodArg.index = index;
{ methodArg.extractValue = extractValue;
methodCache.args = paramList.ToArray(); methodArg.isParamsArray = true;
methodCache.cachedMethod = method; methodArg.paramsArrayType = paramArrayType;
methodCache.outList = outList.ToArray(); argTypes.Add(methodArg);
methodCache.argTypes = argTypes.ToArray(); currentLuaParam++;
} }
return isMethod; else if(currentNetParam.IsOptional)
} paramList.Add(currentNetParam.DefaultValue);
else // No match
/// <summary> {
/// CP: Fix for operator overloading failure isMethod = false;
/// Returns true if the type is set and assigns the extract value break;
/// </summary> }
/// <param name="luaState"></param> }
/// <param name="currentLuaParam"></param>
/// <param name="currentNetParam"></param> if(currentLuaParam != nLuaParams + 1) // Number of parameters does not match
/// <param name="extractValue"></param> isMethod = false;
/// <returns></returns> if(isMethod)
private bool _IsTypeCorrect(KopiLua.Lua.lua_State luaState, int currentLuaParam, ParameterInfo currentNetParam, out ExtractValue extractValue) {
{ methodCache.args = paramList.ToArray();
try methodCache.cachedMethod = method;
{ methodCache.outList = outList.ToArray();
return (extractValue = translator.typeChecker.checkType(luaState, currentLuaParam, currentNetParam.ParameterType)) != null; methodCache.argTypes = argTypes.ToArray();
} }
catch
{ return isMethod;
extractValue = null; }
Debug.WriteLine("Type wasn't correct");
return false; /// <summary>
} /// CP: Fix for operator overloading failure
} /// Returns true if the type is set and assigns the extract value
/// </summary>
private bool _IsParamsArray(KopiLua.Lua.lua_State luaState, int currentLuaParam, ParameterInfo currentNetParam, out ExtractValue extractValue) /// <param name="luaState"></param>
{ /// <param name="currentLuaParam"></param>
extractValue = null; /// <param name="currentNetParam"></param>
/// <param name="extractValue"></param>
if (currentNetParam.GetCustomAttributes(typeof(ParamArrayAttribute), false).Length > 0) /// <returns></returns>
{ private bool _IsTypeCorrect(LuaCore.lua_State luaState, int currentLuaParam, ParameterInfo currentNetParam, out ExtractValue extractValue)
LuaTypes luaType; {
try
try {
{ return (extractValue = translator.typeChecker.checkType(luaState, currentLuaParam, currentNetParam.ParameterType)) != null;
luaType = KopiLua.Lua.lua_type(luaState, currentLuaParam).ToLuaTypes(); }
} catch
catch (Exception ex) {
{ extractValue = null;
Debug.WriteLine("Could not retrieve lua type while attempting to determine params Array Status."); Debug.WriteLine("Type wasn't correct");
Debug.WriteLine(ex.Message); return false;
extractValue = null; }
return false; }
}
private bool _IsParamsArray(LuaCore.lua_State luaState, int currentLuaParam, ParameterInfo currentNetParam, out ExtractValue extractValue)
if (luaType == LuaTypes.Table) {
{ extractValue = null;
try
{ if (currentNetParam.GetCustomAttributes(typeof(ParamArrayAttribute), false).Length > 0)
extractValue = translator.typeChecker.getExtractor(typeof(LuaTable)); {
} LuaTypes luaType;
catch (Exception/* ex*/)
{ try
Debug.WriteLine("An error occurred during an attempt to retrieve a LuaTable extractor while checking for params array status."); {
} luaType = LuaCore.lua_type(luaState, currentLuaParam).ToLuaTypes();
}
if (extractValue != null) catch(Exception ex)
{ {
return true; Debug.WriteLine("Could not retrieve lua type while attempting to determine params Array Status.");
} Debug.WriteLine(ex.Message);
} extractValue = null;
else return false;
{ }
Type paramElementType = currentNetParam.ParameterType.GetElementType();
if(luaType == LuaTypes.Table)
try {
{ try
extractValue = translator.typeChecker.checkType(luaState, currentLuaParam, paramElementType); {
} extractValue = translator.typeChecker.getExtractor(typeof(LuaTable));
catch (Exception/* ex*/) }
{ catch(Exception/* ex*/)
Debug.WriteLine(string.Format("An error occurred during an attempt to retrieve an extractor ({0}) while checking for params array status.", paramElementType.FullName)); {
} Debug.WriteLine("An error occurred during an attempt to retrieve a LuaTable extractor while checking for params array status.");
}
if (extractValue != null)
{ if(!extractValue.IsNull())
return true; {
} return true;
} }
} }
else
Debug.WriteLine("Type wasn't Params object."); {
var paramElementType = currentNetParam.ParameterType.GetElementType();
return false;
} try
} {
extractValue = translator.typeChecker.checkType(luaState, currentLuaParam, paramElementType);
}
catch (Exception/* ex*/)
{
Debug.WriteLine(string.Format("An error occurred during an attempt to retrieve an extractor ({0}) while checking for params array status.", paramElementType.FullName));
}
if(!extractValue.IsNull())
{
return true;
}
}
}
Debug.WriteLine("Type wasn't Params object.");
return false;
}
}
} }
\ 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.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