Commit 68bdf7fa authored by Megax's avatar Megax Committed by Megax
Browse files

* Autotols alapú Makefile generátor hozzáadva a kódhoz.

parent 856d0cb7
/* /*
* This file is part of LuaInterface. * This file is part of LuaInterface.
* *
* Copyright (C) 2003-2005 Fabio Mascarenhas de Queiroz. * Copyright (C) 2003-2005 Fabio Mascarenhas de Queiroz.
* Copyright (C) 2012 Megax <http://megax.yeahunter.hu/> * Copyright (C) 2012 Megax <http://megax.yeahunter.hu/>
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal * of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights * in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is * copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions: * furnished to do so, subject to the following conditions:
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* 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.
*/ */
using System; using System;
namespace LuaInterface namespace LuaInterface
{ {
/* /*
* Common interface for types generated from tables. The method * Common interface for types generated from tables. The method
* returns the table that overrides some or all of the type's methods. * returns the table that overrides some or all of the type's methods.
*/ */
public interface ILuaGeneratedType public interface ILuaGeneratedType
{ {
LuaTable __luaInterface_getLuaTable(); LuaTable __luaInterface_getLuaTable();
} }
} }
\ No newline at end of file
/* /*
* This file is part of LuaInterface. * This file is part of LuaInterface.
* *
* Copyright (C) 2003-2005 Fabio Mascarenhas de Queiroz. * Copyright (C) 2003-2005 Fabio Mascarenhas de Queiroz.
* Copyright (C) 2012 Megax <http://megax.yeahunter.hu/> * Copyright (C) 2012 Megax <http://megax.yeahunter.hu/>
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal * of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights * in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is * copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions: * furnished to do so, subject to the following conditions:
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* 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.
*/ */
using System; using System;
namespace LuaInterface namespace LuaInterface
{ {
/* /*
* Structure to store a type and the return types of * Structure to store a type and the return types of
* its methods (the type of the returned value and out/ref * its methods (the type of the returned value and out/ref
* parameters). * parameters).
*/ */
struct LuaClassType struct LuaClassType
{ {
public Type klass; public Type klass;
public Type[][] returnTypes; public Type[][] returnTypes;
} }
} }
\ No newline at end of file
/* /*
* This file is part of LuaInterface. * This file is part of LuaInterface.
* *
* Copyright (C) 2003-2005 Fabio Mascarenhas de Queiroz. * Copyright (C) 2003-2005 Fabio Mascarenhas de Queiroz.
* Copyright (C) 2012 Megax <http://megax.yeahunter.hu/> * Copyright (C) 2012 Megax <http://megax.yeahunter.hu/>
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal * of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights * in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is * copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions: * furnished to do so, subject to the following conditions:
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* 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.
*/ */
using System; using System;
using System.IO; using System.IO;
using System.Threading; using System.Threading;
using System.Reflection; using System.Reflection;
using System.Collections; 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.Method;
using LuaInterface.Exceptions; using LuaInterface.Exceptions;
using LuaInterface.Extensions; using LuaInterface.Extensions;
namespace LuaInterface namespace LuaInterface
{ {
using LuaCore = KopiLua.Lua; using LuaCore = KopiLua.Lua;
/* /*
* Main class of LuaInterface * Main class of LuaInterface
* Object-oriented wrapper to Lua API * Object-oriented wrapper to Lua API
* *
* Author: Fabio Mascarenhas * Author: Fabio Mascarenhas
* Version: 1.0 * Version: 1.0
* *
* // steffenj: important changes in Lua class: * // steffenj: important changes in Lua class:
* - removed all Open*Lib() functions * - removed all Open*Lib() functions
* - all libs automatically open in the Lua class constructor (just assign nil to unwanted libs) * - all libs automatically open in the Lua class constructor (just assign nil to unwanted libs)
* */ * */
[CLSCompliant(true)] [CLSCompliant(true)]
public class Lua : IDisposable public class Lua : IDisposable
{ {
#region lua debug functions #region lua debug functions
/// <summary> /// <summary>
/// Event that is raised when an exception occures during a hook call. /// Event that is raised when an exception occures during a hook call.
/// </summary> /// </summary>
/// <author>Reinhard Ostermeier</author> /// <author>Reinhard Ostermeier</author>
public event EventHandler<HookExceptionEventArgs> HookException; public event EventHandler<HookExceptionEventArgs> HookException;
/// <summary> /// <summary>
/// Event when lua hook callback is called /// Event when lua hook callback is called
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// Is only raised if SetDebugHook is called before. /// Is only raised if SetDebugHook is called before.
/// </remarks> /// </remarks>
/// <author>Reinhard Ostermeier</author> /// <author>Reinhard Ostermeier</author>
public event EventHandler<DebugHookEventArgs> DebugHook; public event EventHandler<DebugHookEventArgs> DebugHook;
/// <summary> /// <summary>
/// lua hook calback delegate /// lua hook calback delegate
/// </summary> /// </summary>
/// <author>Reinhard Ostermeier</author> /// <author>Reinhard Ostermeier</author>
private LuaCore.lua_Hook hookCallback = null; private LuaCore.lua_Hook hookCallback = null;
#endregion #endregion
#region Globals auto-complete #region Globals auto-complete
private readonly List<string> globals = new List<string>(); private readonly List<string> globals = new List<string>();
private bool globalsSorted; private bool globalsSorted;
#endregion #endregion
private /*readonly */ LuaCore.lua_State luaState; private /*readonly */ LuaCore.lua_State luaState;
/// <summary> /// <summary>
/// True while a script is being executed /// True while a script is being executed
/// </summary> /// </summary>
public bool IsExecuting { get { return executing; } } public bool IsExecuting { get { return executing; } }
private LuaCore.lua_CFunction panicCallback; private LuaCore.lua_CFunction panicCallback;
private ObjectTranslator translator; private ObjectTranslator translator;
/// <summary> /// <summary>
/// Used to ensure multiple .net threads all get serialized by this single lock for access to the lua stack/objects /// Used to ensure multiple .net threads all get serialized by this single lock for access to the lua stack/objects
/// </summary> /// </summary>
//private object luaLock = new object(); //private object luaLock = new object();
private bool _StatePassed; private bool _StatePassed;
private bool executing; private bool executing;
static string init_luanet = static string init_luanet =
"local metatable = {} \n" + "local metatable = {} \n" +
"local import_type = luanet.import_type \n" + "local import_type = luanet.import_type \n" +
"local load_assembly = luanet.load_assembly \n" + "local load_assembly = luanet.load_assembly \n" +
" \n" + " \n" +
"-- Lookup a .NET identifier component. \n" + "-- Lookup a .NET identifier component. \n" +
"function metatable:__index(key) -- key is e.g. \"Form\" \n" + "function metatable:__index(key) -- key is e.g. \"Form\" \n" +
" -- Get the fully-qualified name, e.g. \"System.Windows.Forms.Form\" \n" + " -- Get the fully-qualified name, e.g. \"System.Windows.Forms.Form\" \n" +
" local fqn = ((rawget(self, \".fqn\") and rawget(self, \".fqn\") .. \n" + " local fqn = ((rawget(self, \".fqn\") and rawget(self, \".fqn\") .. \n" +
" \".\") or \"\") .. key \n" + " \".\") or \"\") .. key \n" +
" \n" + " \n" +
" -- Try to find either a luanet function or a CLR type \n" + " -- Try to find either a luanet function or a CLR type \n" +
" local obj = rawget(luanet, key) or import_type(fqn) \n" + " local obj = rawget(luanet, key) or import_type(fqn) \n" +
" \n" + " \n" +
" -- If key is neither a luanet function or a CLR type, then it is simply \n" + " -- If key is neither a luanet function or a CLR type, then it is simply \n" +
" -- an identifier component. \n" + " -- an identifier component. \n" +
" if obj == nil then \n" + " if obj == nil then \n" +
" -- It might be an assembly, so we load it too. \n" + " -- It might be an assembly, so we load it too. \n" +
" load_assembly(fqn) \n" + " load_assembly(fqn) \n" +
" obj = { [\".fqn\"] = fqn } \n" + " obj = { [\".fqn\"] = fqn } \n" +
" setmetatable(obj, metatable) \n" + " setmetatable(obj, metatable) \n" +
" end \n" + " end \n" +
" \n" + " \n" +
" -- Cache this lookup \n" + " -- Cache this lookup \n" +
" rawset(self, key, obj) \n" + " rawset(self, key, obj) \n" +
" return obj \n" + " return obj \n" +
"end \n" + "end \n" +
" \n" + " \n" +
"-- A non-type has been called; e.g. foo = System.Foo() \n" + "-- A non-type has been called; e.g. foo = System.Foo() \n" +
"function metatable:__call(...) \n" + "function metatable:__call(...) \n" +
" error(\"No such type: \" .. rawget(self, \".fqn\"), 2) \n" + " error(\"No such type: \" .. rawget(self, \".fqn\"), 2) \n" +
"end \n" + "end \n" +
" \n" + " \n" +
"-- This is the root of the .NET namespace \n" + "-- This is the root of the .NET namespace \n" +
"luanet[\".fqn\"] = false \n" + "luanet[\".fqn\"] = false \n" +
"setmetatable(luanet, metatable) \n" + "setmetatable(luanet, metatable) \n" +
" \n" + " \n" +
"-- Preload the mscorlib assembly \n" + "-- Preload the mscorlib assembly \n" +
"luanet.load_assembly(\"mscorlib\") \n"; "luanet.load_assembly(\"mscorlib\") \n";
#region Globals auto-complete #region Globals auto-complete
/// <summary> /// <summary>
/// An alphabetically sorted list of all globals (objects, methods, etc.) externally added to this Lua instance /// An alphabetically sorted list of all globals (objects, methods, etc.) externally added to this Lua instance
/// </summary> /// </summary>
/// <remarks>Members of globals are also listed. The formatting is optimized for text input auto-completion.</remarks> /// <remarks>Members of globals are also listed. The formatting is optimized for text input auto-completion.</remarks>
public IEnumerable<string> Globals public IEnumerable<string> Globals
{ {
get get
{ {
// Only sort list when necessary // Only sort list when necessary
if(!globalsSorted) if(!globalsSorted)
{ {
globals.Sort(); globals.Sort();
globalsSorted = true; globalsSorted = true;
} }
return globals; return globals;
} }
} }
#endregion #endregion
public Lua() public Lua()
{ {
luaState = LuaLib.luaL_newstate(); // steffenj: Lua 5.1.1 API change (lua_open is gone) luaState = LuaLib.luaL_newstate(); // steffenj: Lua 5.1.1 API change (lua_open is gone)
//LuaLib.luaopen_base(luaState); // steffenj: luaopen_* no longer used //LuaLib.luaopen_base(luaState); // steffenj: luaopen_* no longer used
LuaLib.luaL_openlibs(luaState); // steffenj: Lua 5.1.1 API change (luaopen_base is gone, just open all libs right here) LuaLib.luaL_openlibs(luaState); // steffenj: Lua 5.1.1 API change (luaopen_base is gone, just open all libs right here)
LuaLib.lua_pushstring(luaState, "LUAINTERFACE LOADED"); LuaLib.lua_pushstring(luaState, "LUAINTERFACE LOADED");
LuaLib.lua_pushboolean(luaState, true); LuaLib.lua_pushboolean(luaState, true);
LuaLib.lua_settable(luaState, (int)LuaIndexes.Registry); LuaLib.lua_settable(luaState, (int)LuaIndexes.Registry);
LuaLib.lua_newtable(luaState); LuaLib.lua_newtable(luaState);
LuaLib.lua_setglobal(luaState, "luanet"); LuaLib.lua_setglobal(luaState, "luanet");
LuaLib.lua_pushvalue(luaState, (int)LuaIndexes.Globals); LuaLib.lua_pushvalue(luaState, (int)LuaIndexes.Globals);
LuaLib.lua_getglobal(luaState, "luanet"); LuaLib.lua_getglobal(luaState, "luanet");
LuaLib.lua_pushstring(luaState, "getmetatable"); LuaLib.lua_pushstring(luaState, "getmetatable");
LuaLib.lua_getglobal(luaState, "getmetatable"); LuaLib.lua_getglobal(luaState, "getmetatable");
LuaLib.lua_settable(luaState, -3); LuaLib.lua_settable(luaState, -3);
LuaLib.lua_replace(luaState, (int)LuaIndexes.Globals); LuaLib.lua_replace(luaState, (int)LuaIndexes.Globals);
translator = new ObjectTranslator(this, luaState); translator = new ObjectTranslator(this, luaState);
LuaLib.lua_replace(luaState, (int)LuaIndexes.Globals); LuaLib.lua_replace(luaState, (int)LuaIndexes.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 LuaCore.lua_CFunction(PanicCallback); panicCallback = new LuaCore.lua_CFunction(PanicCallback);
LuaLib.lua_atpanic(luaState, panicCallback); LuaLib.lua_atpanic(luaState, panicCallback);
//LuaLib.lua_atlock(luaState, lockCallback = new LuaCore.lua_CFunction(LockCallback)); //LuaLib.lua_atlock(luaState, lockCallback = new LuaCore.lua_CFunction(LockCallback));
//LuaLib.lua_atunlock(luaState, unlockCallback = new LuaCore.lua_CFunction(UnlockCallback)); //LuaLib.lua_atunlock(luaState, unlockCallback = new LuaCore.lua_CFunction(UnlockCallback));
} }
/* /*
* 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 lState) public Lua(LuaCore.lua_State lState)
{ {
LuaLib.lua_pushstring(lState, "LUAINTERFACE LOADED"); LuaLib.lua_pushstring(lState, "LUAINTERFACE LOADED");
LuaLib.lua_gettable(lState, (int)LuaIndexes.Registry); LuaLib.lua_gettable(lState, (int)LuaIndexes.Registry);
if(LuaLib.lua_toboolean(lState, -1)) if(LuaLib.lua_toboolean(lState, -1))
{ {
LuaLib.lua_settop(lState, -2); LuaLib.lua_settop(lState, -2);
throw new LuaException("There is already a LuaInterface.Lua instance associated with this Lua state"); throw new LuaException("There is already a LuaInterface.Lua instance associated with this Lua state");
} }
else else
{ {
LuaLib.lua_settop(lState, -2); LuaLib.lua_settop(lState, -2);
LuaLib.lua_pushstring(lState, "LUAINTERFACE LOADED"); LuaLib.lua_pushstring(lState, "LUAINTERFACE LOADED");
LuaLib.lua_pushboolean(lState, true); LuaLib.lua_pushboolean(lState, true);
LuaLib.lua_settable(lState, (int)LuaIndexes.Registry); LuaLib.lua_settable(lState, (int)LuaIndexes.Registry);
luaState = lState; luaState = lState;
LuaLib.lua_pushvalue(lState, (int)LuaIndexes.Globals); LuaLib.lua_pushvalue(lState, (int)LuaIndexes.Globals);
LuaLib.lua_getglobal(lState, "luanet"); LuaLib.lua_getglobal(lState, "luanet");
LuaLib.lua_pushstring(lState, "getmetatable"); LuaLib.lua_pushstring(lState, "getmetatable");
LuaLib.lua_getglobal(lState, "getmetatable"); LuaLib.lua_getglobal(lState, "getmetatable");
LuaLib.lua_settable(lState, -3); LuaLib.lua_settable(lState, -3);
LuaLib.lua_replace(lState, (int)LuaIndexes.Globals); LuaLib.lua_replace(lState, (int)LuaIndexes.Globals);
translator = new ObjectTranslator(this, luaState); translator = new ObjectTranslator(this, luaState);
LuaLib.lua_replace(lState, (int)LuaIndexes.Globals); LuaLib.lua_replace(lState, (int)LuaIndexes.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(LuaCore.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(LuaCore.lua_State luaState)
{ {
// Monitor.Exit(luaLock); // Monitor.Exit(luaLock);
return 0; return 0;
}*/ }*/
public void Close() public void Close()
{ {
if(_StatePassed) if(_StatePassed)
return; return;
////// if(luaState != LuaCore.lua_State.Zero) ////// if(luaState != LuaCore.lua_State.Zero)
if(!luaState.IsNull()) if(!luaState.IsNull())
LuaCore.lua_close(luaState); LuaCore.lua_close(luaState);
//luaState = LuaCore.lua_State.Zero; <- suggested by Christopher Cebulski http://luaforge.net/forum/forum.php?thread_id = 44593&forum_id = 146 //luaState = LuaCore.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(LuaCore.lua_State luaState)
{ {
// string desc = LuaLib.lua_tostring(luaState, 1); // string desc = LuaLib.lua_tostring(luaState, 1);
string reason = string.Format("unprotected error in call to Lua API ({0})", LuaLib.lua_tostring(luaState, -1)); string reason = string.Format("unprotected error in call to Lua API ({0})", LuaLib.lua_tostring(luaState, -1));
// lua_tostring(L, -1); // lua_tostring(L, -1);
throw new LuaException(reason); throw new LuaException(reason);
} }
/// <summary> /// <summary>
/// Assuming we have a Lua error string sitting on the stack, throw a C# exception out to the user's app /// Assuming we have a Lua error string sitting on the stack, throw a C# exception out to the user's app
/// </summary> /// </summary>
/// <exception cref = "LuaScriptException">Thrown if the script caused an exception</exception> /// <exception cref = "LuaScriptException">Thrown if the script caused an exception</exception>
private void ThrowExceptionFromError(int oldTop) private void ThrowExceptionFromError(int oldTop)
{ {
object err = translator.getObject(luaState, -1); object err = translator.getObject(luaState, -1);
LuaLib.lua_settop(luaState, oldTop); LuaLib.lua_settop(luaState, oldTop);
// A pre-wrapped exception - just rethrow it (stack trace of InnerException will be preserved) // A pre-wrapped exception - just rethrow it (stack trace of InnerException will be preserved)
var luaEx = err as LuaScriptException; var luaEx = err as LuaScriptException;
if(!luaEx.IsNull()) if(!luaEx.IsNull())
throw luaEx; throw luaEx;
// A non-wrapped Lua error (best interpreted as a string) - wrap it and throw it // A non-wrapped Lua error (best interpreted as a string) - wrap it and throw it
if(err.IsNull()) if(err.IsNull())
err = "Unknown Lua Error"; err = "Unknown Lua Error";
throw new LuaScriptException(err.ToString(), string.Empty); throw new LuaScriptException(err.ToString(), string.Empty);
} }
/// <summary> /// <summary>
/// Convert C# exceptions into Lua errors /// Convert C# exceptions into Lua errors
/// </summary> /// </summary>
/// <returns>num of things on stack</returns> /// <returns>num of things on stack</returns>
/// <param name = "e">null for no pending exception</param> /// <param name = "e">null for no pending exception</param>
internal int SetPendingException(Exception e) internal int SetPendingException(Exception e)
{ {
var caughtExcept = e; var caughtExcept = e;
if(!caughtExcept.IsNull()) if(!caughtExcept.IsNull())
{ {
translator.throwError(luaState, caughtExcept); translator.throwError(luaState, caughtExcept);
LuaLib.lua_pushnil(luaState); LuaLib.lua_pushnil(luaState);
return 1; return 1;
} }
else else
return 0; return 0;
} }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
/// <param name = "chunk"></param> /// <param name = "chunk"></param>
/// <param name = "name"></param> /// <param name = "name"></param>
/// <returns></returns> /// <returns></returns>
public LuaFunction LoadString(string chunk, string name) public LuaFunction LoadString(string chunk, string name)
{ {
int oldTop = LuaLib.lua_gettop(luaState); int oldTop = LuaLib.lua_gettop(luaState);
executing = true; executing = true;
try try
{ {
if(LuaLib.luaL_loadbuffer(luaState, chunk, name) != 0) if(LuaLib.luaL_loadbuffer(luaState, chunk, name) != 0)
ThrowExceptionFromError(oldTop); ThrowExceptionFromError(oldTop);
} }
finally finally
{ {
executing = false; executing = false;
} }
var result = translator.getFunction(luaState, -1); var result = translator.getFunction(luaState, -1);
translator.popValues(luaState, oldTop); translator.popValues(luaState, oldTop);
return result; return result;
} }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
/// <param name = "fileName"></param> /// <param name = "fileName"></param>
/// <returns></returns> /// <returns></returns>
public LuaFunction LoadFile(string fileName) public LuaFunction LoadFile(string fileName)
{ {
int oldTop = LuaLib.lua_gettop(luaState); int oldTop = LuaLib.lua_gettop(luaState);
if(LuaLib.luaL_loadfile(luaState, fileName) != 0) if(LuaLib.luaL_loadfile(luaState, fileName) != 0)
ThrowExceptionFromError(oldTop); ThrowExceptionFromError(oldTop);
var result = translator.getFunction(luaState, -1); var result = translator.getFunction(luaState, -1);
translator.popValues(luaState, oldTop); translator.popValues(luaState, oldTop);
return result; return result;
} }
/* /*
* Excutes a Lua chunk and returns all the chunk's return * Excutes a Lua chunk and returns all the chunk's return
* values in an array * values in an array
*/ */
public object[] DoString(string chunk) public object[] DoString(string chunk)
{ {
int oldTop = LuaLib.lua_gettop(luaState); int oldTop = LuaLib.lua_gettop(luaState);
if(LuaLib.luaL_loadbuffer(luaState, chunk, "chunk") == 0) if(LuaLib.luaL_loadbuffer(luaState, chunk, "chunk") == 0)
{ {
executing = true; executing = true;
try try
{ {
if(LuaLib.lua_pcall(luaState, 0, -1, 0) == 0) if(LuaLib.lua_pcall(luaState, 0, -1, 0) == 0)
return translator.popValues(luaState, oldTop); return translator.popValues(luaState, oldTop);
else else
ThrowExceptionFromError(oldTop); ThrowExceptionFromError(oldTop);
} }
finally finally
{ {
executing = false; executing = false;
} }
} }
else else
ThrowExceptionFromError(oldTop); ThrowExceptionFromError(oldTop);
return null; // Never reached - keeps compiler happy 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 = LuaLib.lua_gettop(luaState); int oldTop = LuaLib.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(LuaLib.lua_pcall(luaState, 0, -1, 0) == 0) if(LuaLib.lua_pcall(luaState, 0, -1, 0) == 0)
return translator.popValues(luaState, oldTop); return translator.popValues(luaState, oldTop);
else else
ThrowExceptionFromError(oldTop); ThrowExceptionFromError(oldTop);
} }
finally finally
{ {
executing = false; executing = false;
} }
} }
else else
ThrowExceptionFromError(oldTop); ThrowExceptionFromError(oldTop);
return null; // Never reached - keeps compiler happy 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 = LuaLib.lua_gettop(luaState); int oldTop = LuaLib.lua_gettop(luaState);
if(LuaLib.luaL_loadfile(luaState, fileName) == 0) if(LuaLib.luaL_loadfile(luaState, fileName) == 0)
{ {
executing = true; executing = true;
try try
{ {
if(LuaLib.lua_pcall(luaState, 0, -1, 0) == 0) if(LuaLib.lua_pcall(luaState, 0, -1, 0) == 0)
return translator.popValues(luaState, oldTop); return translator.popValues(luaState, oldTop);
else else
ThrowExceptionFromError(oldTop); ThrowExceptionFromError(oldTop);
} }
finally finally
{ {
executing = false; 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 = LuaLib.lua_gettop(luaState); int oldTop = LuaLib.lua_gettop(luaState);
string[] path = fullPath.Split(new char[] { '.' }); string[] path = fullPath.Split(new char[] { '.' });
LuaLib.lua_getglobal(luaState, path[0]); LuaLib.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);
} }
LuaLib.lua_settop(luaState, oldTop); LuaLib.lua_settop(luaState, oldTop);
return returnValue; return returnValue;
} }
set set
{ {
int oldTop = LuaLib.lua_gettop(luaState); int oldTop = LuaLib.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);
LuaLib.lua_setglobal(luaState, fullPath); LuaLib.lua_setglobal(luaState, fullPath);
} }
else else
{ {
LuaLib.lua_getglobal(luaState, path[0]); LuaLib.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);
} }
LuaLib.lua_settop(luaState, oldTop); LuaLib.lua_settop(luaState, oldTop);
// Globals auto-complete // Globals auto-complete
if(value.IsNull()) if(value.IsNull())
{ {
// Remove now obsolete entries // Remove now obsolete entries
globals.Remove(fullPath); globals.Remove(fullPath);
} }
else else
{ {
// Add new entries // Add new entries
if(!globals.Contains(fullPath)) if(!globals.Contains(fullPath))
registerGlobal(fullPath, value.GetType(), 0); registerGlobal(fullPath, value.GetType(), 0);
} }
} }
} }
#region Globals auto-complete #region Globals auto-complete
/// <summary> /// <summary>
/// Adds an entry to <see cref = "globals"/> (recursivley handles 2 levels of members) /// 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> /// <param name = "path">The index accessor path ot the entry</param>
/// <param name = "type">The type of the entry</param> /// <param name = "type">The type of the entry</param>
/// <param name = "recursionCounter">How deep have we gone with recursion?</param> /// <param name = "recursionCounter">How deep have we gone with recursion?</param>
private void registerGlobal(string path, Type type, int recursionCounter) private void registerGlobal(string path, Type type, int recursionCounter)
{ {
// If the type is a global method, list it directly // If the type is a global method, list it directly
if(type == typeof(LuaCore.lua_CFunction)) if(type == typeof(LuaCore.lua_CFunction))
{ {
// Format for easy method invocation // Format for easy method invocation
globals.Add(path + "("); globals.Add(path + "(");
} }
// If the type is a class or an interface and recursion hasn't been running too long, list the members // If the type is a class or an interface and recursion hasn't been running too long, list the members
else if((type.IsClass || type.IsInterface) && type != typeof(string) && recursionCounter < 2) else if((type.IsClass || type.IsInterface) && type != typeof(string) && recursionCounter < 2)
{ {
#region Methods #region Methods
foreach(var method in type.GetMethods(BindingFlags.Public | BindingFlags.Instance)) foreach(var method in type.GetMethods(BindingFlags.Public | BindingFlags.Instance))
{ {
if( if(
// Check that the LuaHideAttribute and LuaGlobalAttribute were not applied // Check that the LuaHideAttribute and LuaGlobalAttribute were not applied
(method.GetCustomAttributes(typeof(LuaHideAttribute), false).Length == 0) && (method.GetCustomAttributes(typeof(LuaHideAttribute), false).Length == 0) &&
(method.GetCustomAttributes(typeof(LuaGlobalAttribute), false).Length == 0) && (method.GetCustomAttributes(typeof(LuaGlobalAttribute), false).Length == 0) &&
// Exclude some generic .NET methods that wouldn't be very usefull in Lua // Exclude some generic .NET methods that wouldn't be very usefull in Lua
method.Name != "GetType" && method.Name != "GetHashCode" && method.Name != "Equals" && method.Name != "GetType" && method.Name != "GetHashCode" && method.Name != "Equals" &&
method.Name != "ToString" && method.Name != "Clone" && method.Name != "Dispose" && method.Name != "ToString" && method.Name != "Clone" && method.Name != "Dispose" &&
method.Name != "GetEnumerator" && method.Name != "CopyTo" && method.Name != "GetEnumerator" && method.Name != "CopyTo" &&
!method.Name.StartsWith("get_", StringComparison.Ordinal) && !method.Name.StartsWith("get_", StringComparison.Ordinal) &&
!method.Name.StartsWith("set_", StringComparison.Ordinal) && !method.Name.StartsWith("set_", StringComparison.Ordinal) &&
!method.Name.StartsWith("add_", StringComparison.Ordinal) && !method.Name.StartsWith("add_", StringComparison.Ordinal) &&
!method.Name.StartsWith("remove_", StringComparison.Ordinal)) !method.Name.StartsWith("remove_", StringComparison.Ordinal))
{ {
// Format for easy method invocation // Format for easy method invocation
string command = path + ":" + method.Name + "("; string command = path + ":" + method.Name + "(";
if(method.GetParameters().Length == 0) command += ")"; if(method.GetParameters().Length == 0) command += ")";
globals.Add(command); globals.Add(command);
} }
} }
#endregion #endregion
#region Fields #region Fields
foreach(var field in type.GetFields(BindingFlags.Public | BindingFlags.Instance)) foreach(var field in type.GetFields(BindingFlags.Public | BindingFlags.Instance))
{ {
if( if(
// Check that the LuaHideAttribute and LuaGlobalAttribute were not applied // Check that the LuaHideAttribute and LuaGlobalAttribute were not applied
(field.GetCustomAttributes(typeof(LuaHideAttribute), false).Length == 0) && (field.GetCustomAttributes(typeof(LuaHideAttribute), false).Length == 0) &&
(field.GetCustomAttributes(typeof(LuaGlobalAttribute), false).Length == 0)) (field.GetCustomAttributes(typeof(LuaGlobalAttribute), false).Length == 0))
{ {
// Go into recursion for members // Go into recursion for members
registerGlobal(path + "." + field.Name, field.FieldType, recursionCounter + 1); registerGlobal(path + "." + field.Name, field.FieldType, recursionCounter + 1);
} }
} }
#endregion #endregion
#region Properties #region Properties
foreach(var property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance)) foreach(var property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance))
{ {
if( if(
// Check that the LuaHideAttribute and LuaGlobalAttribute were not applied // Check that the LuaHideAttribute and LuaGlobalAttribute were not applied
(property.GetCustomAttributes(typeof(LuaHideAttribute), false).Length == 0) && (property.GetCustomAttributes(typeof(LuaHideAttribute), false).Length == 0) &&
(property.GetCustomAttributes(typeof(LuaGlobalAttribute), false).Length == 0) (property.GetCustomAttributes(typeof(LuaGlobalAttribute), false).Length == 0)
// Exclude some generic .NET properties that wouldn't be very usefull in Lua // Exclude some generic .NET properties that wouldn't be very usefull in Lua
&& property.Name != "Item") && property.Name != "Item")
{ {
// Go into recursion for members // Go into recursion for members
registerGlobal(path + "." + property.Name, property.PropertyType, recursionCounter + 1); registerGlobal(path + "." + property.Name, property.PropertyType, recursionCounter + 1);
} }
} }
#endregion #endregion
} }
else else
globals.Add(path); // Otherwise simply add the element to the list globals.Add(path); // Otherwise simply add the element to the list
// List will need to be sorted on next access // List will need to be sorted on next access
globalsSorted = false; globalsSorted = false;
} }
#endregion #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++)
{ {
LuaLib.lua_pushstring(luaState, remainingPath[i]); LuaLib.lua_pushstring(luaState, remainingPath[i]);
LuaLib.lua_gettable(luaState, -2); LuaLib.lua_gettable(luaState, -2);
returnValue = translator.getObject(luaState, -1); returnValue = translator.getObject(luaState, -1);
if(returnValue.IsNull()) if(returnValue.IsNull())
break; 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 this[fullPath].ToString(); return this[fullPath].ToString();
} }
/* /*
* 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 LuaCore.lua_CFunction ? new LuaFunction((LuaCore.lua_CFunction)obj, this) : (LuaFunction)obj); return (obj is LuaCore.lua_CFunction ? new LuaFunction((LuaCore.lua_CFunction)obj, this) : (LuaFunction)obj);
} }
/* /*
* 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 = LuaLib.lua_gettop(luaState); int oldTop = LuaLib.lua_gettop(luaState);
if(!LuaLib.lua_checkstack(luaState, args.Length+6)) if(!LuaLib.lua_checkstack(luaState, args.Length+6))
throw new LuaException("Lua stack overflow"); throw new LuaException("Lua stack overflow");
translator.push(luaState, function); translator.push(luaState, function);
if(!args.IsNull()) 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 = LuaLib.lua_pcall(luaState, nArgs, -1, 0); int error = LuaLib.lua_pcall(luaState, nArgs, -1, 0);
if(error != 0) if(error != 0)
ThrowExceptionFromError(oldTop); ThrowExceptionFromError(oldTop);
} }
finally finally
{ {
executing = false; executing = false;
} }
return !returnTypes.IsNull() ? translator.popValues(luaState, oldTop, returnTypes) : 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++)
{ {
LuaLib.lua_pushstring(luaState, remainingPath[i]); LuaLib.lua_pushstring(luaState, remainingPath[i]);
LuaLib.lua_gettable(luaState, -2); LuaLib.lua_gettable(luaState, -2);
} }
LuaLib.lua_pushstring(luaState, remainingPath[remainingPath.Length-1]); LuaLib.lua_pushstring(luaState, remainingPath[remainingPath.Length-1]);
translator.push(luaState, val); translator.push(luaState, val);
LuaLib.lua_settable(luaState, -3); LuaLib.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 = LuaLib.lua_gettop(luaState); int oldTop = LuaLib.lua_gettop(luaState);
if(path.Length == 1) if(path.Length == 1)
{ {
LuaLib.lua_newtable(luaState); LuaLib.lua_newtable(luaState);
LuaLib.lua_setglobal(luaState, fullPath); LuaLib.lua_setglobal(luaState, fullPath);
} }
else else
{ {
LuaLib.lua_getglobal(luaState, path[0]); LuaLib.lua_getglobal(luaState, path[0]);
for(int i = 1; i < path.Length-1; i++) for(int i = 1; i < path.Length-1; i++)
{ {
LuaLib.lua_pushstring(luaState, path[i]); LuaLib.lua_pushstring(luaState, path[i]);
LuaLib.lua_gettable(luaState, -2); LuaLib.lua_gettable(luaState, -2);
} }
LuaLib.lua_pushstring(luaState, path[path.Length-1]); LuaLib.lua_pushstring(luaState, path[path.Length-1]);
LuaLib.lua_newtable(luaState); LuaLib.lua_newtable(luaState);
LuaLib.lua_settable(luaState, -3); LuaLib.lua_settable(luaState, -3);
} }
LuaLib.lua_settop(luaState, oldTop); LuaLib.lua_settop(luaState, oldTop);
} }
public ListDictionary GetTableDict(LuaTable table) public ListDictionary GetTableDict(LuaTable table)
{ {
var dict = new ListDictionary(); var dict = new ListDictionary();
int oldTop = LuaLib.lua_gettop(luaState); int oldTop = LuaLib.lua_gettop(luaState);
translator.push(luaState, table); translator.push(luaState, table);
LuaLib.lua_pushnil(luaState); LuaLib.lua_pushnil(luaState);
while(LuaLib.lua_next(luaState, -2) != 0) while(LuaLib.lua_next(luaState, -2) != 0)
{ {
dict[translator.getObject(luaState, -2)] = translator.getObject(luaState, -1); dict[translator.getObject(luaState, -2)] = translator.getObject(luaState, -1);
LuaLib.lua_settop(luaState, -2); LuaLib.lua_settop(luaState, -2);
} }
LuaLib.lua_settop(luaState, oldTop); LuaLib.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 #region lua debug functions
/// <summary> /// <summary>
/// Activates the debug hook /// Activates the debug hook
/// </summary> /// </summary>
/// <param name = "mask">Mask</param> /// <param name = "mask">Mask</param>
/// <param name = "count">Count</param> /// <param name = "count">Count</param>
/// <returns>see lua docs. -1 if hook is already set</returns> /// <returns>see lua docs. -1 if hook is already set</returns>
/// <author>Reinhard Ostermeier</author> /// <author>Reinhard Ostermeier</author>
public int SetDebugHook(EventMasks mask, int count) public int SetDebugHook(EventMasks mask, int count)
{ {
if(hookCallback.IsNull()) if(hookCallback.IsNull())
{ {
hookCallback = new LuaCore.lua_Hook(DebugHookCallback); hookCallback = new LuaCore.lua_Hook(DebugHookCallback);
return LuaCore.lua_sethook(luaState, hookCallback, (int)mask, count); return LuaCore.lua_sethook(luaState, hookCallback, (int)mask, count);
} }
return -1; return -1;
} }
/// <summary> /// <summary>
/// Removes the debug hook /// Removes the debug hook
/// </summary> /// </summary>
/// <returns>see lua docs</returns> /// <returns>see lua docs</returns>
/// <author>Reinhard Ostermeier</author> /// <author>Reinhard Ostermeier</author>
public int RemoveDebugHook() public int RemoveDebugHook()
{ {
hookCallback = null; hookCallback = null;
return LuaCore.lua_sethook(luaState, null, 0, 0); return LuaCore.lua_sethook(luaState, null, 0, 0);
} }
/// <summary> /// <summary>
/// Gets the hook mask. /// Gets the hook mask.
/// </summary> /// </summary>
/// <returns>hook mask</returns> /// <returns>hook mask</returns>
/// <author>Reinhard Ostermeier</author> /// <author>Reinhard Ostermeier</author>
public EventMasks GetHookMask() public EventMasks GetHookMask()
{ {
return (EventMasks)LuaCore.lua_gethookmask(luaState); return (EventMasks)LuaCore.lua_gethookmask(luaState);
} }
/// <summary> /// <summary>
/// Gets the hook count /// Gets the hook count
/// </summary> /// </summary>
/// <returns>see lua docs</returns> /// <returns>see lua docs</returns>
/// <author>Reinhard Ostermeier</author> /// <author>Reinhard Ostermeier</author>
public int GetHookCount() public int GetHookCount()
{ {
return LuaCore.lua_gethookcount(luaState); return LuaCore.lua_gethookcount(luaState);
} }
/// <summary> /// <summary>
/// Gets the stack entry on a given level /// Gets the stack entry on a given level
/// </summary> /// </summary>
/// <param name = "level">level</param> /// <param name = "level">level</param>
/// <param name = "luaDebug">lua debug structure</param> /// <param name = "luaDebug">lua debug structure</param>
/// <returns>Returns true if level was allowed, false if level was invalid.</returns> /// <returns>Returns true if level was allowed, false if level was invalid.</returns>
/// <author>Reinhard Ostermeier</author> /// <author>Reinhard Ostermeier</author>
/*public bool GetStack(int level, out LuaCore.lua_Debug luaDebug) /*public bool GetStack(int level, out LuaCore.lua_Debug luaDebug)
{ {
luaDebug = new LuaDebug(); luaDebug = new LuaDebug();
LuaCore.lua_State ld = System.Runtime.InteropServices.Marshal.AllocHGlobal(System.Runtime.InteropServices.Marshal.SizeOf(luaDebug)); LuaCore.lua_State ld = System.Runtime.InteropServices.Marshal.AllocHGlobal(System.Runtime.InteropServices.Marshal.SizeOf(luaDebug));
System.Runtime.InteropServices.Marshal.StructureToPtr(luaDebug, ld, false); System.Runtime.InteropServices.Marshal.StructureToPtr(luaDebug, ld, false);
try try
{ {
return LuaLib.lua_getstack(luaState, level, luaDebug) != 0; return LuaLib.lua_getstack(luaState, level, luaDebug) != 0;
} }
finally finally
{ {
luaDebug = (LuaDebug)System.Runtime.InteropServices.Marshal.PtrToStructure(ld, typeof(LuaDebug)); luaDebug = (LuaDebug)System.Runtime.InteropServices.Marshal.PtrToStructure(ld, typeof(LuaDebug));
System.Runtime.InteropServices.Marshal.FreeHGlobal(ld); System.Runtime.InteropServices.Marshal.FreeHGlobal(ld);
} }
}*/ }*/
/// <summary> /// <summary>
/// Gets info (see lua docs) /// Gets info (see lua docs)
/// </summary> /// </summary>
/// <param name = "what">what (see lua docs)</param> /// <param name = "what">what (see lua docs)</param>
/// <param name = "luaDebug">lua debug structure</param> /// <param name = "luaDebug">lua debug structure</param>
/// <returns>see lua docs</returns> /// <returns>see lua docs</returns>
/// <author>Reinhard Ostermeier</author> /// <author>Reinhard Ostermeier</author>
/*public int GetInfo(String what, ref LuaCore.lua_Debug luaDebug) /*public int GetInfo(String what, ref LuaCore.lua_Debug luaDebug)
{ {
LuaCore.lua_State ld = System.Runtime.InteropServices.Marshal.AllocHGlobal(System.Runtime.InteropServices.Marshal.SizeOf(luaDebug)); LuaCore.lua_State ld = System.Runtime.InteropServices.Marshal.AllocHGlobal(System.Runtime.InteropServices.Marshal.SizeOf(luaDebug));
System.Runtime.InteropServices.Marshal.StructureToPtr(luaDebug, ld, false); System.Runtime.InteropServices.Marshal.StructureToPtr(luaDebug, ld, false);
try try
{ {
return LuaLib.lua_getinfo(luaState, what, ld); return LuaLib.lua_getinfo(luaState, what, ld);
} }
finally finally
{ {
luaDebug = (LuaDebug)System.Runtime.InteropServices.Marshal.PtrToStructure(ld, typeof(LuaDebug)); luaDebug = (LuaDebug)System.Runtime.InteropServices.Marshal.PtrToStructure(ld, typeof(LuaDebug));
System.Runtime.InteropServices.Marshal.FreeHGlobal(ld); System.Runtime.InteropServices.Marshal.FreeHGlobal(ld);
} }
}*/ }*/
/// <summary> /// <summary>
/// Gets local (see lua docs) /// Gets local (see lua docs)
/// </summary> /// </summary>
/// <param name = "luaDebug">lua debug structure</param> /// <param name = "luaDebug">lua debug structure</param>
/// <param name = "n">see lua docs</param> /// <param name = "n">see lua docs</param>
/// <returns>see lua docs</returns> /// <returns>see lua docs</returns>
/// <author>Reinhard Ostermeier</author> /// <author>Reinhard Ostermeier</author>
public string GetLocal(LuaCore.lua_Debug luaDebug, int n) public string GetLocal(LuaCore.lua_Debug luaDebug, int n)
{ {
try try
{ {
return LuaCore.lua_getlocal(luaState, luaDebug, n).ToString(); return LuaCore.lua_getlocal(luaState, luaDebug, n).ToString();
} }
finally finally
{ {
//System.Runtime.InteropServices.Marshal.FreeHGlobal(ld); //System.Runtime.InteropServices.Marshal.FreeHGlobal(ld);
} }
} }
/// <summary> /// <summary>
/// Sets local (see lua docs) /// Sets local (see lua docs)
/// </summary> /// </summary>
/// <param name = "luaDebug">lua debug structure</param> /// <param name = "luaDebug">lua debug structure</param>
/// <param name = "n">see lua docs</param> /// <param name = "n">see lua docs</param>
/// <returns>see lua docs</returns> /// <returns>see lua docs</returns>
/// <author>Reinhard Ostermeier</author> /// <author>Reinhard Ostermeier</author>
public string SetLocal(LuaCore.lua_Debug luaDebug, int n) public string SetLocal(LuaCore.lua_Debug luaDebug, int n)
{ {
try try
{ {
return LuaCore.lua_setlocal(luaState, luaDebug, n).ToString(); return LuaCore.lua_setlocal(luaState, luaDebug, n).ToString();
} }
finally finally
{ {
//System.Runtime.InteropServices.Marshal.FreeHGlobal(ld); //System.Runtime.InteropServices.Marshal.FreeHGlobal(ld);
} }
} }
/// <summary> /// <summary>
/// Gets up value (see lua docs) /// Gets up value (see lua docs)
/// </summary> /// </summary>
/// <param name = "funcindex">see lua docs</param> /// <param name = "funcindex">see lua docs</param>
/// <param name = "n">see lua docs</param> /// <param name = "n">see lua docs</param>
/// <returns>see lua docs</returns> /// <returns>see lua docs</returns>
/// <author>Reinhard Ostermeier</author> /// <author>Reinhard Ostermeier</author>
public string GetUpValue(int funcindex, int n) public string GetUpValue(int funcindex, int n)
{ {
return LuaCore.lua_getupvalue(luaState, funcindex, n).ToString(); return LuaCore.lua_getupvalue(luaState, funcindex, n).ToString();
} }
/// <summary> /// <summary>
/// Sets up value (see lua docs) /// Sets up value (see lua docs)
/// </summary> /// </summary>
/// <param name = "funcindex">see lua docs</param> /// <param name = "funcindex">see lua docs</param>
/// <param name = "n">see lua docs</param> /// <param name = "n">see lua docs</param>
/// <returns>see lua docs</returns> /// <returns>see lua docs</returns>
/// <author>Reinhard Ostermeier</author> /// <author>Reinhard Ostermeier</author>
public string SetUpValue(int funcindex, int n) public string SetUpValue(int funcindex, int n)
{ {
return LuaCore.lua_setupvalue(luaState, funcindex, n).ToString(); return LuaCore.lua_setupvalue(luaState, funcindex, n).ToString();
} }
/// <summary> /// <summary>
/// Delegate that is called on lua hook callback /// Delegate that is called on lua hook callback
/// </summary> /// </summary>
/// <param name = "luaState">lua state</param> /// <param name = "luaState">lua state</param>
/// <param name = "luaDebug">Pointer to LuaDebug (lua_debug) structure</param> /// <param name = "luaDebug">Pointer to LuaDebug (lua_debug) structure</param>
/// <author>Reinhard Ostermeier</author> /// <author>Reinhard Ostermeier</author>
private void DebugHookCallback(LuaCore.lua_State luaState, LuaCore.lua_Debug luaDebug) private void DebugHookCallback(LuaCore.lua_State luaState, LuaCore.lua_Debug luaDebug)
{ {
try try
{ {
var temp = DebugHook; var temp = DebugHook;
if(!temp.IsNull()) if(!temp.IsNull())
temp(this, new DebugHookEventArgs(luaDebug)); temp(this, new DebugHookEventArgs(luaDebug));
} }
catch(Exception ex) catch(Exception ex)
{ {
OnHookException(new HookExceptionEventArgs(ex)); OnHookException(new HookExceptionEventArgs(ex));
} }
} }
private void OnHookException(HookExceptionEventArgs e) private void OnHookException(HookExceptionEventArgs e)
{ {
var temp = HookException; var temp = HookException;
if(!temp.IsNull()) if(!temp.IsNull())
temp(this, e); temp(this, e);
} }
/// <summary> /// <summary>
/// Pops a value from the lua stack. /// Pops a value from the lua stack.
/// </summary> /// </summary>
/// <returns>Returns the top value from the lua stack.</returns> /// <returns>Returns the top value from the lua stack.</returns>
/// <author>Reinhard Ostermeier</author> /// <author>Reinhard Ostermeier</author>
public object Pop() public object Pop()
{ {
int top = LuaLib.lua_gettop(luaState); int top = LuaLib.lua_gettop(luaState);
return translator.popValues(luaState, top - 1)[0]; return translator.popValues(luaState, top - 1)[0];
} }
/// <summary> /// <summary>
/// Pushes a value onto the lua stack. /// Pushes a value onto the lua stack.
/// </summary> /// </summary>
/// <param name = "value">Value to push.</param> /// <param name = "value">Value to push.</param>
/// <author>Reinhard Ostermeier</author> /// <author>Reinhard Ostermeier</author>
public void Push(object value) public void Push(object value)
{ {
translator.push(luaState, value); translator.push(luaState, value);
} }
#endregion #endregion
internal void dispose(int reference) internal void dispose(int reference)
{ {
if(!luaState.IsNull()) //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 = LuaLib.lua_gettop(luaState); int oldTop = LuaLib.lua_gettop(luaState);
LuaLib.lua_getref(luaState, reference); LuaLib.lua_getref(luaState, reference);
LuaLib.lua_pushstring(luaState, field); LuaLib.lua_pushstring(luaState, field);
LuaLib.lua_rawget(luaState, -2); LuaLib.lua_rawget(luaState, -2);
object obj = translator.getObject(luaState, -1); object obj = translator.getObject(luaState, -1);
LuaLib.lua_settop(luaState, oldTop); LuaLib.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 = LuaLib.lua_gettop(luaState); int oldTop = LuaLib.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[] {'.'}));
LuaLib.lua_settop(luaState, oldTop); LuaLib.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 = LuaLib.lua_gettop(luaState); int oldTop = LuaLib.lua_gettop(luaState);
LuaLib.lua_getref(luaState, reference); LuaLib.lua_getref(luaState, reference);
translator.push(luaState, field); translator.push(luaState, field);
LuaLib.lua_gettable(luaState, -2); LuaLib.lua_gettable(luaState, -2);
object returnValue = translator.getObject(luaState, -1); object returnValue = translator.getObject(luaState, -1);
LuaLib.lua_settop(luaState, oldTop); LuaLib.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 = LuaLib.lua_gettop(luaState); int oldTop = LuaLib.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);
LuaLib.lua_settop(luaState, oldTop); LuaLib.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 = LuaLib.lua_gettop(luaState); int oldTop = LuaLib.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);
LuaLib.lua_settable(luaState, -3); LuaLib.lua_settable(luaState, -3);
LuaLib.lua_settop(luaState, oldTop); LuaLib.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 = LuaLib.lua_gettop(luaState); int oldTop = LuaLib.lua_gettop(luaState);
var wrapper = new LuaMethodWrapper(translator, target, function.DeclaringType, function); var wrapper = new LuaMethodWrapper(translator, target, function.DeclaringType, function);
translator.push(luaState, new LuaCore.lua_CFunction(wrapper.call)); translator.push(luaState, new LuaCore.lua_CFunction(wrapper.call));
this[path] = translator.getObject(luaState, -1); this[path] = translator.getObject(luaState, -1);
var f = GetFunction(path); var f = GetFunction(path);
LuaLib.lua_settop(luaState, oldTop); LuaLib.lua_settop(luaState, oldTop);
return f; return f;
} }
/* /*
* Compares the two values referenced by ref1 and ref2 for equality * Compares the two values referenced by ref1 and ref2 for equality
*/ */
internal bool compareRef(int ref1, int ref2) internal bool compareRef(int ref1, int ref2)
{ {
int top = LuaLib.lua_gettop(luaState); int top = LuaLib.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 = LuaLib.lua_equal(luaState, -1, -2); int equal = LuaLib.lua_equal(luaState, -1, -2);
LuaLib.lua_settop(luaState, top); LuaLib.lua_settop(luaState, top);
return (equal != 0); return (equal != 0);
} }
internal void pushCSFunction(LuaCore.lua_CFunction function) internal void pushCSFunction(LuaCore.lua_CFunction function)
{ {
translator.pushFunction(luaState, function); translator.pushFunction(luaState, function);
} }
#region IDisposable Members #region IDisposable Members
public virtual void Dispose() public virtual void Dispose()
{ {
if(!translator.IsNull()) if(!translator.IsNull())
{ {
translator.pendingEvents.Dispose(); translator.pendingEvents.Dispose();
translator = null; translator = null;
} }
this.Close(); this.Close();
GC.Collect(); GC.Collect();
GC.WaitForPendingFinalizers(); GC.WaitForPendingFinalizers();
} }
#endregion #endregion
} }
} }
\ No newline at end of file
/* /*
* This file is part of LuaInterface. * This file is part of LuaInterface.
* *
* Copyright (C) 2003-2005 Fabio Mascarenhas de Queiroz. * Copyright (C) 2003-2005 Fabio Mascarenhas de Queiroz.
* Copyright (C) 2012 Megax <http://megax.yeahunter.hu/> * Copyright (C) 2012 Megax <http://megax.yeahunter.hu/>
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal * of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights * in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is * copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions: * furnished to do so, subject to the following conditions:
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* 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.
*/ */
using System; using System;
using System.Text; using System.Text;
using System.Collections.Generic; 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;
[CLSCompliantAttribute(false)] [CLSCompliantAttribute(false)]
protected int _Reference; protected int _Reference;
[CLSCompliantAttribute(false)] [CLSCompliantAttribute(false)]
protected Lua _Interpreter; protected Lua _Interpreter;
~LuaBase() ~LuaBase()
{ {
Dispose(false); Dispose(false);
} }
public void Dispose() public void Dispose()
{ {
Dispose(true); Dispose(true);
GC.SuppressFinalize(this); GC.SuppressFinalize(this);
} }
public virtual void Dispose(bool disposeManagedResources) public virtual void Dispose(bool disposeManagedResources)
{ {
if(!_Disposed) if(!_Disposed)
{ {
if(disposeManagedResources) if(disposeManagedResources)
{ {
if(_Reference != 0) if(_Reference != 0)
_Interpreter.dispose(_Reference); _Interpreter.dispose(_Reference);
} }
_Interpreter = null; _Interpreter = null;
_Disposed = true; _Disposed = true;
} }
} }
public override bool Equals(object o) public override bool Equals(object o)
{ {
if(o is LuaBase) if(o is LuaBase)
{ {
var l = (LuaBase)o; var l = (LuaBase)o;
return _Interpreter.compareRef(l._Reference, _Reference); return _Interpreter.compareRef(l._Reference, _Reference);
} }
else else
return false; return false;
} }
public override int GetHashCode() public override int GetHashCode()
{ {
return _Reference; return _Reference;
} }
} }
} }
\ No newline at end of file
/* /*
* This file is part of LuaInterface. * This file is part of LuaInterface.
* *
* Copyright (C) 2003-2005 Fabio Mascarenhas de Queiroz. * Copyright (C) 2003-2005 Fabio Mascarenhas de Queiroz.
* Copyright (C) 2012 Megax <http://megax.yeahunter.hu/> * Copyright (C) 2012 Megax <http://megax.yeahunter.hu/>
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal * of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights * in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is * copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions: * furnished to do so, subject to the following conditions:
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* 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.
*/ */
using System; using System;
using System.Text; using System.Text;
using System.Collections.Generic; using System.Collections.Generic;
namespace LuaInterface namespace LuaInterface
{ {
using LuaCore = KopiLua.Lua; using LuaCore = KopiLua.Lua;
public class LuaFunction : LuaBase public class LuaFunction : LuaBase
{ {
internal LuaCore.lua_CFunction function; internal LuaCore.lua_CFunction function;
public LuaFunction(int reference, Lua interpreter) public LuaFunction(int reference, Lua interpreter)
{ {
_Reference = reference; _Reference = reference;
this.function = null; this.function = null;
_Interpreter = interpreter; _Interpreter = interpreter;
} }
public LuaFunction(LuaCore.lua_CFunction function, Lua interpreter) public LuaFunction(LuaCore.lua_CFunction function, Lua interpreter)
{ {
_Reference = 0; _Reference = 0;
this.function = function; this.function = function;
_Interpreter = interpreter; _Interpreter = interpreter;
} }
/* /*
* Calls the function casting return values to the types * Calls the function casting return values to the types
* in returnTypes * in returnTypes
*/ */
internal object[] call(object[] args, Type[] returnTypes) internal object[] call(object[] args, Type[] returnTypes)
{ {
return _Interpreter.callFunction(this, args, returnTypes); return _Interpreter.callFunction(this, args, returnTypes);
} }
/* /*
* Calls the function and returns its return values inside * Calls the function and returns its return values inside
* an array * an array
*/ */
public object[] Call(params object[] args) public object[] Call(params object[] args)
{ {
return _Interpreter.callFunction(this, args); return _Interpreter.callFunction(this, args);
} }
/* /*
* Pushes the function into the Lua stack * Pushes the function into the Lua stack
*/ */
internal void push(LuaCore.lua_State luaState) internal void push(LuaCore.lua_State luaState)
{ {
if(_Reference != 0) if(_Reference != 0)
LuaLib.lua_getref(luaState, _Reference); LuaLib.lua_getref(luaState, _Reference);
else else
_Interpreter.pushCSFunction(function); _Interpreter.pushCSFunction(function);
} }
public override string ToString() public override string ToString()
{ {
return "function"; return "function";
} }
public override bool Equals(object o) public override bool Equals(object o)
{ {
if(o is LuaFunction) if(o is LuaFunction)
{ {
var l = (LuaFunction)o; var l = (LuaFunction)o;
if(this._Reference != 0 && l._Reference != 0) if(this._Reference != 0 && l._Reference != 0)
return _Interpreter.compareRef(l._Reference, this._Reference); return _Interpreter.compareRef(l._Reference, this._Reference);
else else
return this.function == l.function; return this.function == l.function;
} }
else else
return false; return false;
} }
public override int GetHashCode() public override int GetHashCode()
{ {
return _Reference != 0 ? _Reference : function.GetHashCode(); return _Reference != 0 ? _Reference : function.GetHashCode();
} }
} }
} }
\ No newline at end of file
/* /*
* This file is part of LuaInterface. * This file is part of LuaInterface.
* *
* Copyright (C) 2003-2005 Fabio Mascarenhas de Queiroz. * Copyright (C) 2003-2005 Fabio Mascarenhas de Queiroz.
* Copyright (C) 2012 Megax <http://megax.yeahunter.hu/> * Copyright (C) 2012 Megax <http://megax.yeahunter.hu/>
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal * of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights * in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is * copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions: * furnished to do so, subject to the following conditions:
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* 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.
*/ */
using System; 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
/* /*
* This file is part of LuaInterface. * This file is part of LuaInterface.
* *
* Copyright (C) 2003-2005 Fabio Mascarenhas de Queiroz. * Copyright (C) 2003-2005 Fabio Mascarenhas de Queiroz.
* Copyright (C) 2012 Megax <http://megax.yeahunter.hu/> * Copyright (C) 2012 Megax <http://megax.yeahunter.hu/>
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal * of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights * in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is * copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions: * furnished to do so, subject to the following conditions:
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* 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.
*/ */
using System; 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
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0"> <Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">
<PropertyGroup> <PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">x86</Platform> <Platform Condition=" '$(Platform)' == '' ">x86</Platform>
<ProductVersion>9.0.21022</ProductVersion> <ProductVersion>9.0.21022</ProductVersion>
<SchemaVersion>2.0</SchemaVersion> <SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{F55CABBB-4108-4A39-94E1-581FD46DC021}</ProjectGuid> <ProjectGuid>{F55CABBB-4108-4A39-94E1-581FD46DC021}</ProjectGuid>
<OutputType>Library</OutputType> <OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder> <AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>LuaInterface</RootNamespace> <RootNamespace>LuaInterface</RootNamespace>
<AssemblyName>LuaInterface</AssemblyName> <AssemblyName>LuaInterface</AssemblyName>
<ReleaseVersion>2.x</ReleaseVersion> <ReleaseVersion>2.x</ReleaseVersion>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
<DebugSymbols>true</DebugSymbols> <DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType> <DebugType>full</DebugType>
<Optimize>false</Optimize> <Optimize>false</Optimize>
<OutputPath>..\..\Run\Debug</OutputPath> <OutputPath>..\..\Run\Debug</OutputPath>
<DefineConstants>DEBUG</DefineConstants> <DefineConstants>DEBUG</DefineConstants>
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
<PlatformTarget>x86</PlatformTarget> <PlatformTarget>x86</PlatformTarget>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
<DebugType>none</DebugType> <DebugType>none</DebugType>
<Optimize>true</Optimize> <Optimize>true</Optimize>
<OutputPath>..\..\Run\Release</OutputPath> <OutputPath>..\..\Run\Release</OutputPath>
<DefineConstants>RELEASE</DefineConstants> <DefineConstants>RELEASE</DefineConstants>
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
<PlatformTarget>x86</PlatformTarget> <PlatformTarget>x86</PlatformTarget>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x64' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x64' ">
<DebugSymbols>true</DebugSymbols> <DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType> <DebugType>full</DebugType>
<Optimize>false</Optimize> <Optimize>false</Optimize>
<OutputPath>..\..\Run\Debug_x64</OutputPath> <OutputPath>..\..\Run\Debug_x64</OutputPath>
<DefineConstants>DEBUG</DefineConstants> <DefineConstants>DEBUG</DefineConstants>
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
<PlatformTarget>x64</PlatformTarget> <PlatformTarget>x64</PlatformTarget>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x64' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x64' ">
<DebugType>none</DebugType> <DebugType>none</DebugType>
<Optimize>true</Optimize> <Optimize>true</Optimize>
<OutputPath>..\..\Run\Release_x64</OutputPath> <OutputPath>..\..\Run\Release_x64</OutputPath>
<DefineConstants>RELEASE</DefineConstants> <DefineConstants>RELEASE</DefineConstants>
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
<PlatformTarget>x64</PlatformTarget> <PlatformTarget>x64</PlatformTarget>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<Reference Include="System" /> <Reference Include="System" />
<Reference Include="System.Data" /> <Reference Include="System.Data" />
<Reference Include="System.Xml" /> <Reference Include="System.Xml" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<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="ObjectTranslator.cs" /> <Compile Include="ObjectTranslator.cs" />
<Compile Include="ProxyType.cs" /> <Compile Include="ProxyType.cs" />
<Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="LuaBase.cs" /> <Compile Include="LuaBase.cs" />
<Compile Include="LuaFunction.cs" /> <Compile Include="LuaFunction.cs" />
<Compile Include="LuaGlobalAttribute.cs" /> <Compile Include="LuaGlobalAttribute.cs" />
<Compile Include="LuaHideAttribute.cs" /> <Compile Include="LuaHideAttribute.cs" />
<Compile Include="LuaRegistrationHelper.cs" /> <Compile Include="LuaRegistrationHelper.cs" />
<Compile Include="LuaTable.cs" /> <Compile Include="LuaTable.cs" />
<Compile Include="LuaUserData.cs" /> <Compile Include="LuaUserData.cs" />
<Compile Include="Extensions\GeneralExtensions.cs" /> <Compile Include="Extensions\GeneralExtensions.cs" />
<Compile Include="GenerateEventAssembly\LuaClassType.cs" /> <Compile Include="GenerateEventAssembly\LuaClassType.cs" />
<Compile Include="GenerateEventAssembly\ILuaGeneratedType.cs" /> <Compile Include="GenerateEventAssembly\ILuaGeneratedType.cs" />
<Compile Include="GenerateEventAssembly\DelegateGenerator.cs" /> <Compile Include="GenerateEventAssembly\DelegateGenerator.cs" />
<Compile Include="GenerateEventAssembly\ClassGenerator.cs" /> <Compile Include="GenerateEventAssembly\ClassGenerator.cs" />
<Compile Include="GenerateEventAssembly\CodeGeneration.cs" /> <Compile Include="GenerateEventAssembly\CodeGeneration.cs" />
<Compile Include="Event\EventCodes.cs" /> <Compile Include="Event\EventCodes.cs" />
<Compile Include="Event\EventMasks.cs" /> <Compile Include="Event\EventMasks.cs" />
<Compile Include="Event\DebugHookEventArgs.cs" /> <Compile Include="Event\DebugHookEventArgs.cs" />
<Compile Include="Event\HookExceptionEventArgs.cs" /> <Compile Include="Event\HookExceptionEventArgs.cs" />
<Compile Include="Exceptions\LuaException.cs" /> <Compile Include="Exceptions\LuaException.cs" />
<Compile Include="Exceptions\LuaScriptException.cs" /> <Compile Include="Exceptions\LuaScriptException.cs" />
<Compile Include="LuaLib\LuaEnums.cs" /> <Compile Include="LuaLib\LuaEnums.cs" />
<Compile Include="LuaLib\References.cs" /> <Compile Include="LuaLib\References.cs" />
<Compile Include="LuaLib\LuaTypes.cs" /> <Compile Include="LuaLib\LuaTypes.cs" />
<Compile Include="Method\MethodCache.cs" /> <Compile Include="Method\MethodCache.cs" />
<Compile Include="Method\MethodArgs.cs" /> <Compile Include="Method\MethodArgs.cs" />
<Compile Include="Method\LuaMethodWrapper.cs" /> <Compile Include="Method\LuaMethodWrapper.cs" />
<Compile Include="Method\EventHandlerContainer.cs" /> <Compile Include="Method\EventHandlerContainer.cs" />
<Compile Include="Method\RegisterEventHandler.cs" /> <Compile Include="Method\RegisterEventHandler.cs" />
<Compile Include="Method\LuaEventHandler.cs" /> <Compile Include="Method\LuaEventHandler.cs" />
<Compile Include="Method\LuaDelegate.cs" /> <Compile Include="Method\LuaDelegate.cs" />
<Compile Include="Method\LuaClassHelper.cs" /> <Compile Include="Method\LuaClassHelper.cs" />
<Compile Include="LuaLib\LuaIndexes.cs" /> <Compile Include="LuaLib\LuaIndexes.cs" />
<Compile Include="LuaLib\GCOptions.cs" /> <Compile Include="LuaLib\GCOptions.cs" />
<Compile Include="LuaLib\LuaLib.cs" /> <Compile Include="LuaLib\LuaLib.cs" />
<Compile Include="Config\LuaInterfaceConfig.cs" /> <Compile Include="Config\LuaInterfaceConfig.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.
Other similar extension points exist, see Microsoft.Common.targets. Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild"> <Target Name="BeforeBuild">
</Target> </Target>
<Target Name="AfterBuild"> <Target Name="AfterBuild">
</Target> </Target>
--> -->
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\KopiLua\KopiLua.csproj"> <ProjectReference Include="..\KopiLua\KopiLua.csproj">
<Project>{E8DDBC21-EF74-4ABA-9C49-BFC702BE25D8}</Project> <Project>{E8DDBC21-EF74-4ABA-9C49-BFC702BE25D8}</Project>
<Name>KopiLua</Name> <Name>KopiLua</Name>
</ProjectReference> </ProjectReference>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Folder Include="Extensions\" /> <Folder Include="Extensions\" />
<Folder Include="GenerateEventAssembly\" /> <Folder Include="GenerateEventAssembly\" />
<Folder Include="Event\" /> <Folder Include="Event\" />
<Folder Include="Exceptions\" /> <Folder Include="Exceptions\" />
<Folder Include="Method\" /> <Folder Include="Method\" />
<Folder Include="Config\" /> <Folder Include="Config\" />
</ItemGroup> </ItemGroup>
</Project> </Project>
/* /*
* This file is part of LuaInterface. * This file is part of LuaInterface.
* *
* Copyright (C) 2003-2005 Fabio Mascarenhas de Queiroz. * Copyright (C) 2003-2005 Fabio Mascarenhas de Queiroz.
* Copyright (C) 2009 Joshua Simmons <simmons.44@gmail.com> * Copyright (C) 2009 Joshua Simmons <simmons.44@gmail.com>
* Copyright (C) 2012 Megax <http://megax.yeahunter.hu/> * Copyright (C) 2012 Megax <http://megax.yeahunter.hu/>
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal * of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights * in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is * copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions: * furnished to do so, subject to the following conditions:
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* 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.
*/ */
using System; using System;
namespace LuaInterface namespace LuaInterface
{ {
/// <summary> /// <summary>
/// Enumeration of basic lua globals. /// Enumeration of basic lua globals.
/// </summary> /// </summary>
public enum LuaEnums : int public enum LuaEnums : int
{ {
/// <summary> /// <summary>
/// Option for multiple returns in `lua_pcall' and `lua_call' /// Option for multiple returns in `lua_pcall' and `lua_call'
/// </summary> /// </summary>
MultiRet = -1, MultiRet = -1,
/// <summary> /// <summary>
/// Everything is OK. /// Everything is OK.
/// </summary> /// </summary>
Ok = 0, Ok = 0,
/// <summary> /// <summary>
/// Thread status, Ok or Yield /// Thread status, Ok or Yield
/// </summary> /// </summary>
Yield = 1, Yield = 1,
/// <summary> /// <summary>
/// A Runtime error. /// A Runtime error.
/// </summary> /// </summary>
ErrorRun = 2, ErrorRun = 2,
/// <summary> /// <summary>
/// A syntax error. /// A syntax error.
/// </summary> /// </summary>
ErrorSyntax = 3, ErrorSyntax = 3,
/// <summary> /// <summary>
/// A memory allocation error. For such errors, Lua does not call the error handler function. /// A memory allocation error. For such errors, Lua does not call the error handler function.
/// </summary> /// </summary>
ErrorMemory = 4, ErrorMemory = 4,
/// <summary> /// <summary>
/// An error in the error handling function. /// An error in the error handling function.
/// </summary> /// </summary>
ErrorError = 5, ErrorError = 5,
/// <summary> /// <summary>
/// An extra error for file load errors when using luaL_loadfile. /// An extra error for file load errors when using luaL_loadfile.
/// </summary> /// </summary>
ErrorFile = 6 ErrorFile = 6
} }
} }
\ No newline at end of file
/* /*
* This file is part of LuaInterface. * This file is part of LuaInterface.
* *
* Copyright (C) 2003-2005 Fabio Mascarenhas de Queiroz. * Copyright (C) 2003-2005 Fabio Mascarenhas de Queiroz.
* Copyright (C) 2009 Joshua Simmons <simmons.44@gmail.com> * Copyright (C) 2009 Joshua Simmons <simmons.44@gmail.com>
* Copyright (C) 2012 Megax <http://megax.yeahunter.hu/> * Copyright (C) 2012 Megax <http://megax.yeahunter.hu/>
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal * of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights * in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is * copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions: * furnished to do so, subject to the following conditions:
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* 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.
*/ */
using System; using System;
using System.IO; using System.IO;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Runtime.Serialization.Formatters.Binary; using System.Runtime.Serialization.Formatters.Binary;
using LuaInterface.Extensions; using LuaInterface.Extensions;
namespace LuaInterface namespace LuaInterface
{ {
public enum LuaTypes : int public enum LuaTypes : int
{ {
None = -1, None = -1,
Nil = 0, Nil = 0,
Boolean = 1, Boolean = 1,
LightUserdata = 2, LightUserdata = 2,
Number = 3, Number = 3,
String = 4, String = 4,
Table = 5, Table = 5,
Function = 6, Function = 6,
UserData = 7, UserData = 7,
Thread = 8 Thread = 8
} }
} }
\ No newline at end of file
/* /*
* This file is part of LuaInterface. * This file is part of LuaInterface.
* *
* Copyright (C) 2003-2005 Fabio Mascarenhas de Queiroz. * Copyright (C) 2003-2005 Fabio Mascarenhas de Queiroz.
* Copyright (C) 2009 Joshua Simmons <simmons.44@gmail.com> * Copyright (C) 2009 Joshua Simmons <simmons.44@gmail.com>
* Copyright (C) 2012 Megax <http://megax.yeahunter.hu/> * Copyright (C) 2012 Megax <http://megax.yeahunter.hu/>
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal * of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights * in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is * copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions: * furnished to do so, subject to the following conditions:
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* 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.
*/ */
using System; using System;
namespace LuaInterface namespace LuaInterface
{ {
public enum References : int public enum References : int
{ {
RefNil = -1, RefNil = -1,
NoRef = -2 NoRef = -2
} }
} }
\ No newline at end of file
/* /*
* This file is part of LuaInterface. * This file is part of LuaInterface.
* *
* Copyright (C) 2003-2005 Fabio Mascarenhas de Queiroz. * Copyright (C) 2003-2005 Fabio Mascarenhas de Queiroz.
* Copyright (C) 2012 Megax <http://megax.yeahunter.hu/> * Copyright (C) 2012 Megax <http://megax.yeahunter.hu/>
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal * of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights * in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is * copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions: * furnished to do so, subject to the following conditions:
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* 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.
*/ */
using System; using System;
using System.Reflection; using System.Reflection;
using System.Diagnostics.CodeAnalysis; using System.Diagnostics.CodeAnalysis;
using LuaInterface.Extensions; 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.IsNull()) if(lua.IsNull())
throw new ArgumentNullException("lua"); throw new ArgumentNullException("lua");
if(o.IsNull()) if(o.IsNull())
throw new ArgumentNullException("o"); throw new ArgumentNullException("o");
#endregion #endregion
foreach(var method in o.GetType().GetMethods(BindingFlags.Instance | BindingFlags.Public)) foreach(var method in o.GetType().GetMethods(BindingFlags.Instance | BindingFlags.Public))
{ {
foreach(LuaGlobalAttribute attribute in method.GetCustomAttributes(typeof(LuaGlobalAttribute), true)) foreach(LuaGlobalAttribute attribute in method.GetCustomAttributes(typeof(LuaGlobalAttribute), true))
{ {
if(string.IsNullOrEmpty(attribute.Name)) if(string.IsNullOrEmpty(attribute.Name))
lua.RegisterFunction(method.Name, o, method); // CLR name lua.RegisterFunction(method.Name, o, method); // CLR name
else else
lua.RegisterFunction(attribute.Name, o, method); // Custom name lua.RegisterFunction(attribute.Name, o, method); // Custom name
} }
} }
} }
#endregion #endregion
#region Tagged static methods #region Tagged static methods
/// <summary> /// <summary>
/// Registers all public static methods in a class tagged with <see cref="LuaGlobalAttribute"/> as Lua global functions /// Registers all public static methods in a class 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="type">The class type to get the methods from</param> /// <param name="type">The class type to get the methods from</param>
public static void TaggedStaticMethods(Lua lua, Type type) public static void TaggedStaticMethods(Lua lua, Type type)
{ {
#region Sanity checks #region Sanity checks
if(lua.IsNull()) if(lua.IsNull())
throw new ArgumentNullException("lua"); throw new ArgumentNullException("lua");
if(type.IsNull()) if(type.IsNull())
throw new ArgumentNullException("type"); throw new ArgumentNullException("type");
if(!type.IsClass) if(!type.IsClass)
throw new ArgumentException("The type must be a class!", "type"); throw new ArgumentException("The type must be a class!", "type");
#endregion #endregion
foreach(var method in type.GetMethods(BindingFlags.Static | BindingFlags.Public)) foreach(var method in type.GetMethods(BindingFlags.Static | BindingFlags.Public))
{ {
foreach(LuaGlobalAttribute attribute in method.GetCustomAttributes(typeof(LuaGlobalAttribute), false)) foreach(LuaGlobalAttribute attribute in method.GetCustomAttributes(typeof(LuaGlobalAttribute), false))
{ {
if(string.IsNullOrEmpty(attribute.Name)) if(string.IsNullOrEmpty(attribute.Name))
lua.RegisterFunction(method.Name, null, method); // CLR name lua.RegisterFunction(method.Name, null, method); // CLR name
else else
lua.RegisterFunction(attribute.Name, null, method); // Custom name lua.RegisterFunction(attribute.Name, null, method); // Custom name
} }
} }
} }
#endregion #endregion
#region Enumeration #region Enumeration
/// <summary> /// <summary>
/// Registers an enumeration's values for usage as a Lua variable table /// Registers an enumeration's values for usage as a Lua variable table
/// </summary> /// </summary>
/// <typeparam name="T">The enum type to register</typeparam> /// <typeparam name="T">The enum type to register</typeparam>
/// <param name="lua">The Lua VM to add the enum to</param> /// <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")] [SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter", Justification = "The type parameter is used to select an enum type")]
public static void Enumeration<T>(Lua lua) public static void Enumeration<T>(Lua lua)
{ {
#region Sanity checks #region Sanity checks
if(lua.IsNull()) if(lua.IsNull())
throw new ArgumentNullException("lua"); throw new ArgumentNullException("lua");
#endregion #endregion
var type = typeof(T); var 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
/* /*
* This file is part of LuaInterface. * This file is part of LuaInterface.
* *
* Copyright (C) 2003-2005 Fabio Mascarenhas de Queiroz. * Copyright (C) 2003-2005 Fabio Mascarenhas de Queiroz.
* Copyright (C) 2012 Megax <http://megax.yeahunter.hu/> * Copyright (C) 2012 Megax <http://megax.yeahunter.hu/>
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal * of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights * in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is * copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions: * furnished to do so, subject to the following conditions:
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* 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.
*/ */
using System; using System;
using System.Text; using System.Text;
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
namespace LuaInterface namespace LuaInterface
{ {
using LuaCore = KopiLua.Lua; 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 * Indexer for string fields of the table
*/ */
public object this[string field] public object this[string 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 * Indexer for numeric fields of the table
*/ */
public object this[object 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);
} }
} }
public System.Collections.IDictionaryEnumerator GetEnumerator() public System.Collections.IDictionaryEnumerator GetEnumerator()
{ {
return _Interpreter.GetTableDict(this).GetEnumerator(); return _Interpreter.GetTableDict(this).GetEnumerator();
} }
public ICollection Keys public ICollection Keys
{ {
get { return _Interpreter.GetTableDict(this).Keys; } get { return _Interpreter.GetTableDict(this).Keys; }
} }
public ICollection Values public ICollection Values
{ {
get { return _Interpreter.GetTableDict(this).Values; } get { return _Interpreter.GetTableDict(this).Values; }
} }
/* /*
* Gets an string fields of a table ignoring its metatable, * Gets an string fields of a table ignoring its metatable,
* if it exists * if it exists
*/ */
internal object rawget(string field) internal object rawget(string field)
{ {
return _Interpreter.rawGetObject(_Reference, field); return _Interpreter.rawGetObject(_Reference, field);
} }
internal object rawgetFunction(string field) internal object rawgetFunction(string field)
{ {
object obj = _Interpreter.rawGetObject(_Reference, field); object obj = _Interpreter.rawGetObject(_Reference, field);
if(obj is LuaCore.lua_CFunction) if(obj is LuaCore.lua_CFunction)
return new LuaFunction((LuaCore.lua_CFunction)obj, _Interpreter); return new LuaFunction((LuaCore.lua_CFunction)obj, _Interpreter);
else else
return obj; return obj;
} }
/* /*
* Pushes this table into the Lua stack * Pushes this table into the Lua stack
*/ */
internal void push(LuaCore.lua_State luaState) internal void push(LuaCore.lua_State luaState)
{ {
LuaLib.lua_getref(luaState, _Reference); LuaLib.lua_getref(luaState, _Reference);
} }
public override string ToString() public override string ToString()
{ {
return "table"; return "table";
} }
} }
} }
\ No newline at end of file
/* /*
* This file is part of LuaInterface. * This file is part of LuaInterface.
* *
* Copyright (C) 2003-2005 Fabio Mascarenhas de Queiroz. * Copyright (C) 2003-2005 Fabio Mascarenhas de Queiroz.
* Copyright (C) 2012 Megax <http://megax.yeahunter.hu/> * Copyright (C) 2012 Megax <http://megax.yeahunter.hu/>
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal * of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights * in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is * copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions: * furnished to do so, subject to the following conditions:
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* 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.
*/ */
using System; using System;
using System.Text; using System.Text;
using System.Collections.Generic; using System.Collections.Generic;
namespace LuaInterface namespace LuaInterface
{ {
using LuaCore = KopiLua.Lua; using LuaCore = KopiLua.Lua;
public class LuaUserData : LuaBase public class LuaUserData : LuaBase
{ {
public LuaUserData(int reference, Lua interpreter) public LuaUserData(int reference, Lua interpreter)
{ {
_Reference = reference; _Reference = reference;
_Interpreter = interpreter; _Interpreter = interpreter;
} }
/* /*
* Indexer for string fields of the userdata * Indexer for string fields of the userdata
*/ */
public object this[string field] public object this[string 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 userdata * Indexer for numeric fields of the userdata
*/ */
public object this[object 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);
} }
} }
/* /*
* Calls the userdata and returns its return values inside * Calls the userdata and returns its return values inside
* an array * an array
*/ */
public object[] Call(params object[] args) public object[] Call(params object[] args)
{ {
return _Interpreter.callFunction(this, args); return _Interpreter.callFunction(this, args);
} }
/* /*
* Pushes the userdata into the Lua stack * Pushes the userdata into the Lua stack
*/ */
internal void push(LuaCore.lua_State luaState) internal void push(LuaCore.lua_State luaState)
{ {
LuaLib.lua_getref(luaState, _Reference); LuaLib.lua_getref(luaState, _Reference);
} }
public override string ToString() public override string ToString()
{ {
return "userdata"; return "userdata";
} }
} }
} }
\ No newline at end of file
EXTRA_DIST =
# Warning: This is an automatically generated file, do not edit!
if ENABLE_DEBUG_X86
ASSEMBLY_COMPILER_COMMAND = dmcs
ASSEMBLY_COMPILER_FLAGS = -noconfig -codepage:utf8 -warn:4 -optimize- -debug "-define:DEBUG"
ASSEMBLY = ../../Run/Debug/LuaInterface.dll
ASSEMBLY_MDB = $(ASSEMBLY).mdb
COMPILE_TARGET = library
PROJECT_REFERENCES = \
../../Run/Debug/KopiLua.dll
BUILD_DIR = ../../Run/Debug
LUAINTERFACE_DLL_MDB_SOURCE=../../Run/Debug/LuaInterface.dll.mdb
LUAINTERFACE_DLL_MDB=$(BUILD_DIR)/LuaInterface.dll.mdb
KOPILUA_DLL_SOURCE=../../Run/Debug/KopiLua.dll
endif
if ENABLE_RELEASE_X86
ASSEMBLY_COMPILER_COMMAND = dmcs
ASSEMBLY_COMPILER_FLAGS = -noconfig -codepage:utf8 -warn:4 -optimize+ "-define:RELEASE"
ASSEMBLY = ../../Run/Release/LuaInterface.dll
ASSEMBLY_MDB =
COMPILE_TARGET = library
PROJECT_REFERENCES = \
../../Run/Release/KopiLua.dll
BUILD_DIR = ../../Run/Release
LUAINTERFACE_DLL_MDB=
KOPILUA_DLL_SOURCE=../../Run/Release/KopiLua.dll
endif
if ENABLE_DEBUG_X64
ASSEMBLY_COMPILER_COMMAND = dmcs
ASSEMBLY_COMPILER_FLAGS = -noconfig -codepage:utf8 -warn:4 -optimize- -debug "-define:DEBUG"
ASSEMBLY = ../../Run/Debug_x64/LuaInterface.dll
ASSEMBLY_MDB = $(ASSEMBLY).mdb
COMPILE_TARGET = library
PROJECT_REFERENCES = \
../../Run/Debug_x64/KopiLua.dll
BUILD_DIR = ../../Run/Debug_x64
LUAINTERFACE_DLL_MDB_SOURCE=../../Run/Debug_x64/LuaInterface.dll.mdb
LUAINTERFACE_DLL_MDB=$(BUILD_DIR)/LuaInterface.dll.mdb
KOPILUA_DLL_SOURCE=../../Run/Debug_x64/KopiLua.dll
endif
if ENABLE_RELEASE_X64
ASSEMBLY_COMPILER_COMMAND = dmcs
ASSEMBLY_COMPILER_FLAGS = -noconfig -codepage:utf8 -warn:4 -optimize+ "-define:RELEASE"
ASSEMBLY = ../../Run/Release_x64/LuaInterface.dll
ASSEMBLY_MDB =
COMPILE_TARGET = library
PROJECT_REFERENCES = \
../../Run/Release_x64/KopiLua.dll
BUILD_DIR = ../../Run/Release_x64
LUAINTERFACE_DLL_MDB=
KOPILUA_DLL_SOURCE=../../Run/Release_x64/KopiLua.dll
endif
AL=al
SATELLITE_ASSEMBLY_NAME=$(notdir $(basename $(ASSEMBLY))).resources.dll
PROGRAMFILES = \
$(LUAINTERFACE_DLL_MDB) \
$(KOPILUA_DLL)
LINUX_PKGCONFIG = \
$(LUAINTERFACE_PC)
RESGEN=resgen2
all: $(ASSEMBLY) $(PROGRAMFILES) $(LINUX_PKGCONFIG)
FILES = \
CheckType.cs \
Lua.cs \
Metatables.cs \
ObjectTranslator.cs \
ProxyType.cs \
Properties/AssemblyInfo.cs \
LuaBase.cs \
LuaFunction.cs \
LuaGlobalAttribute.cs \
LuaHideAttribute.cs \
LuaRegistrationHelper.cs \
LuaTable.cs \
LuaUserData.cs \
Extensions/GeneralExtensions.cs \
GenerateEventAssembly/LuaClassType.cs \
GenerateEventAssembly/ILuaGeneratedType.cs \
GenerateEventAssembly/DelegateGenerator.cs \
GenerateEventAssembly/ClassGenerator.cs \
GenerateEventAssembly/CodeGeneration.cs \
Event/EventCodes.cs \
Event/EventMasks.cs \
Event/DebugHookEventArgs.cs \
Event/HookExceptionEventArgs.cs \
Exceptions/LuaException.cs \
Exceptions/LuaScriptException.cs \
LuaLib/LuaEnums.cs \
LuaLib/References.cs \
LuaLib/LuaTypes.cs \
Method/MethodCache.cs \
Method/MethodArgs.cs \
Method/LuaMethodWrapper.cs \
Method/EventHandlerContainer.cs \
Method/RegisterEventHandler.cs \
Method/LuaEventHandler.cs \
Method/LuaDelegate.cs \
Method/LuaClassHelper.cs \
LuaLib/LuaIndexes.cs \
LuaLib/GCOptions.cs \
LuaLib/LuaLib.cs \
Config/LuaInterfaceConfig.cs
DATA_FILES =
RESOURCES =
EXTRAS = \
Extensions \
GenerateEventAssembly \
Event \
Exceptions \
Method \
Config \
luainterface.pc.in
REFERENCES = \
System \
System.Data \
System.Xml
DLL_REFERENCES =
CLEANFILES = $(PROGRAMFILES) $(LINUX_PKGCONFIG)
include $(top_srcdir)/Makefile.include
KOPILUA_DLL = $(BUILD_DIR)/KopiLua.dll
LUAINTERFACE_PC = $(BUILD_DIR)/luainterface.pc
$(eval $(call emit-deploy-wrapper,LUAINTERFACE_PC,luainterface.pc))
$(eval $(call emit_resgen_targets))
$(build_xamlg_list): %.xaml.g.cs: %.xaml
xamlg '$<'
$(ASSEMBLY_MDB): $(ASSEMBLY)
$(ASSEMBLY): $(build_sources) $(build_resources) $(build_datafiles) $(DLL_REFERENCES) $(PROJECT_REFERENCES) $(build_xamlg_list) $(build_satellite_assembly_list)
mkdir -p $(shell dirname $(ASSEMBLY))
$(ASSEMBLY_COMPILER_COMMAND) $(ASSEMBLY_COMPILER_FLAGS) -out:$(ASSEMBLY) -target:$(COMPILE_TARGET) $(build_sources_embed) $(build_resources_embed) $(build_references_ref)
/* /*
* This file is part of LuaInterface. * This file is part of LuaInterface.
* *
* Copyright (C) 2003-2005 Fabio Mascarenhas de Queiroz. * Copyright (C) 2003-2005 Fabio Mascarenhas de Queiroz.
* Copyright (C) 2012 Megax <http://megax.yeahunter.hu/> * Copyright (C) 2012 Megax <http://megax.yeahunter.hu/>
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal * of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights * in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is * copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions: * furnished to do so, subject to the following conditions:
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* 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.
*/ */
using System; using System;
using System.IO; using System.IO;
using System.Collections; using System.Collections;
using System.Reflection; using System.Reflection;
using System.Diagnostics; using System.Diagnostics;
using System.Collections.Generic; using System.Collections.Generic;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using LuaInterface.Method; using LuaInterface.Method;
using LuaInterface.Extensions; using LuaInterface.Extensions;
namespace LuaInterface namespace LuaInterface
{ {
using LuaCore = KopiLua.Lua; using LuaCore = KopiLua.Lua;
/* /*
* Functions used in the metatables of userdata representing * Functions used in the metatables of userdata representing
* CLR objects * CLR objects
* *
* Author: Fabio Mascarenhas * Author: Fabio Mascarenhas
* Version: 1.0 * Version: 1.0
*/ */
class MetaFunctions class MetaFunctions
{ {
internal LuaCore.lua_CFunction gcFunction, indexFunction, newindexFunction, baseIndexFunction, internal LuaCore.lua_CFunction gcFunction, indexFunction, newindexFunction, baseIndexFunction,
classIndexFunction, classNewindexFunction, execDelegateFunction, callConstructorFunction, toStringFunction; classIndexFunction, classNewindexFunction, execDelegateFunction, callConstructorFunction, toStringFunction;
private Hashtable memberCache = new Hashtable(); private Hashtable memberCache = new Hashtable();
private ObjectTranslator translator; private ObjectTranslator translator;
/* /*
* __index metafunction for CLR objects. Implemented in Lua. * __index metafunction for CLR objects. Implemented in Lua.
*/ */
internal static string luaIndexFunction = internal static string luaIndexFunction =
"local function index(obj,name) \n" + "local function index(obj,name) \n" +
" local meta=getmetatable(obj) \n" + " local meta=getmetatable(obj) \n" +
" local cached=meta.cache[name] \n" + " local cached=meta.cache[name] \n" +
" if cached~=nil then \n" + " if cached~=nil then \n" +
" return cached \n" + " return cached \n" +
" else \n" + " else \n" +
" local value,isFunc=get_object_member(obj,name) \n" + " local value,isFunc=get_object_member(obj,name) \n" +
" if isFunc then \n" + " if isFunc then \n" +
" meta.cache[name]=value \n" + " meta.cache[name]=value \n" +
" end \n" + " end \n" +
" return value \n" + " return value \n" +
" end \n" + " end \n" +
"end \n" + "end \n" +
"return index "; "return index ";
public MetaFunctions(ObjectTranslator translator) public MetaFunctions(ObjectTranslator translator)
{ {
this.translator = translator; this.translator = translator;
gcFunction = new LuaCore.lua_CFunction(this.collectObject); gcFunction = new LuaCore.lua_CFunction(this.collectObject);
toStringFunction = new LuaCore.lua_CFunction(this.toString); toStringFunction = new LuaCore.lua_CFunction(this.toString);
indexFunction = new LuaCore.lua_CFunction(this.getMethod); indexFunction = new LuaCore.lua_CFunction(this.getMethod);
newindexFunction = new LuaCore.lua_CFunction(this.setFieldOrProperty); newindexFunction = new LuaCore.lua_CFunction(this.setFieldOrProperty);
baseIndexFunction = new LuaCore.lua_CFunction(this.getBaseMethod); baseIndexFunction = new LuaCore.lua_CFunction(this.getBaseMethod);
callConstructorFunction = new LuaCore.lua_CFunction(this.callConstructor); callConstructorFunction = new LuaCore.lua_CFunction(this.callConstructor);
classIndexFunction = new LuaCore.lua_CFunction(this.getClassMethod); classIndexFunction = new LuaCore.lua_CFunction(this.getClassMethod);
classNewindexFunction = new LuaCore.lua_CFunction(this.setClassFieldOrProperty); classNewindexFunction = new LuaCore.lua_CFunction(this.setClassFieldOrProperty);
execDelegateFunction = new LuaCore.lua_CFunction(this.runFunctionDelegate); execDelegateFunction = new LuaCore.lua_CFunction(this.runFunctionDelegate);
} }
/* /*
* __call metafunction of CLR delegates, retrieves and calls the delegate. * __call metafunction of CLR delegates, retrieves and calls the delegate.
*/ */
private int runFunctionDelegate(LuaCore.lua_State luaState) private int runFunctionDelegate(LuaCore.lua_State luaState)
{ {
LuaCore.lua_CFunction func = (LuaCore.lua_CFunction)translator.getRawNetObject(luaState, 1); LuaCore.lua_CFunction func = (LuaCore.lua_CFunction)translator.getRawNetObject(luaState, 1);
LuaLib.lua_remove(luaState, 1); LuaLib.lua_remove(luaState, 1);
return func(luaState); return func(luaState);
} }
/* /*
* __gc metafunction of CLR objects. * __gc metafunction of CLR objects.
*/ */
private int collectObject(LuaCore.lua_State luaState) private int collectObject(LuaCore.lua_State luaState)
{ {
int udata = LuaLib.luanet_rawnetobj(luaState, 1); int udata = LuaLib.luanet_rawnetobj(luaState, 1);
if(udata != -1) if(udata != -1)
translator.collectObject(udata); translator.collectObject(udata);
else else
{ {
// Debug.WriteLine("not found: " + udata); // Debug.WriteLine("not found: " + udata);
} }
return 0; return 0;
} }
/* /*
* __tostring metafunction of CLR objects. * __tostring metafunction of CLR objects.
*/ */
private int toString(LuaCore.lua_State luaState) private int toString(LuaCore.lua_State luaState)
{ {
object obj = translator.getRawNetObject(luaState, 1); object obj = translator.getRawNetObject(luaState, 1);
if(!obj.IsNull()) if(!obj.IsNull())
translator.push(luaState, obj.ToString() + ": " + obj.GetHashCode()); translator.push(luaState, obj.ToString() + ": " + obj.GetHashCode());
else else
LuaLib.lua_pushnil(luaState); LuaLib.lua_pushnil(luaState);
return 1; return 1;
} }
/// <summary> /// <summary>
/// Debug tool to dump the lua stack /// Debug tool to dump the lua stack
/// </summary> /// </summary>
/// FIXME, move somewhere else /// FIXME, move somewhere else
public static void dumpStack(ObjectTranslator translator, LuaCore.lua_State luaState) public static void dumpStack(ObjectTranslator translator, LuaCore.lua_State luaState)
{ {
int depth = LuaLib.lua_gettop(luaState); int depth = LuaLib.lua_gettop(luaState);
Debug.WriteLine("lua stack depth: " + depth); Debug.WriteLine("lua stack depth: " + depth);
for(int i = 1; i <= depth; i++) for(int i = 1; i <= depth; i++)
{ {
var type = LuaLib.lua_type(luaState, i); var type = LuaLib.lua_type(luaState, i);
// we dump stacks when deep in calls, calling typename while the stack is in flux can fail sometimes, so manually check for key types // we dump stacks when deep in calls, calling typename while the stack is in flux can fail sometimes, so manually check for key types
string typestr = (type == LuaTypes.Table) ? "table" : LuaLib.lua_typename(luaState, type); string typestr = (type == LuaTypes.Table) ? "table" : LuaLib.lua_typename(luaState, type);
string strrep = LuaLib.lua_tostring(luaState, i).ToString(); string strrep = LuaLib.lua_tostring(luaState, i).ToString();
if(type == LuaTypes.UserData) if(type == LuaTypes.UserData)
{ {
object obj = translator.getRawNetObject(luaState, i); object obj = translator.getRawNetObject(luaState, i);
strrep = obj.ToString(); strrep = obj.ToString();
} }
Debug.Print("{0}: ({1}) {2}", i, typestr, strrep); Debug.Print("{0}: ({1}) {2}", i, typestr, strrep);
} }
} }
/* /*
* Called by the __index metafunction of CLR objects in case the * Called by the __index metafunction of CLR objects in case the
* method is not cached or it is a field/property/event. * method is not cached or it is a field/property/event.
* Receives the object and the member name as arguments and returns * Receives the object and the member name as arguments and returns
* either the value of the member or a delegate to call it. * either the value of the member or a delegate to call it.
* If the member does not exist returns nil. * If the member does not exist returns nil.
*/ */
private int getMethod(LuaCore.lua_State luaState) private int getMethod(LuaCore.lua_State luaState)
{ {
object obj = translator.getRawNetObject(luaState, 1); object obj = translator.getRawNetObject(luaState, 1);
if(obj.IsNull()) if(obj.IsNull())
{ {
translator.throwError(luaState, "trying to index an invalid object reference"); translator.throwError(luaState, "trying to index an invalid object reference");
LuaLib.lua_pushnil(luaState); LuaLib.lua_pushnil(luaState);
return 1; return 1;
} }
object index = translator.getObject(luaState, 2); object index = translator.getObject(luaState, 2);
//var indexType = index.GetType(); //var indexType = index.GetType();
string methodName = index as string; // will be null if not a string arg string methodName = index as string; // will be null if not a string arg
var objType = obj.GetType(); var objType = obj.GetType();
// Handle the most common case, looking up the method by name. // Handle the most common case, looking up the method by name.
// CP: This will fail when using indexers and attempting to get a value with the same name as a property of the object, // 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 // ie: xmlelement['item'] <- item is a property of xmlelement
try try
{ {
if(!methodName.IsNull() && isMemberPresent(objType, methodName)) if(!methodName.IsNull() && isMemberPresent(objType, methodName))
return getMember(luaState, objType, obj, methodName, BindingFlags.Instance | BindingFlags.IgnoreCase); return getMember(luaState, objType, obj, methodName, BindingFlags.Instance | BindingFlags.IgnoreCase);
} }
catch catch
{ {
} }
// Try to access by array if the type is right and index is an int (lua numbers always come across as double) // Try to access by array if the type is right and index is an int (lua numbers always come across as double)
if(objType.IsArray && index is double) if(objType.IsArray && index is double)
{ {
int intIndex = (int)((double)index); int intIndex = (int)((double)index);
if(objType.UnderlyingSystemType == typeof(float[])) if(objType.UnderlyingSystemType == typeof(float[]))
{ {
float[] arr = ((float[])obj); float[] arr = ((float[])obj);
translator.push(luaState, arr[intIndex]); translator.push(luaState, arr[intIndex]);
} }
else if(objType.UnderlyingSystemType == typeof(double[])) else if(objType.UnderlyingSystemType == typeof(double[]))
{ {
double[] arr = ((double[])obj); double[] arr = ((double[])obj);
translator.push(luaState, arr[intIndex]); translator.push(luaState, arr[intIndex]);
} }
else if(objType.UnderlyingSystemType == typeof(int[])) else if(objType.UnderlyingSystemType == typeof(int[]))
{ {
int[] arr = ((int[])obj); int[] arr = ((int[])obj);
translator.push(luaState, arr[intIndex]); translator.push(luaState, arr[intIndex]);
} }
else else
{ {
object[] arr = (object[])obj; object[] arr = (object[])obj;
translator.push(luaState, arr[intIndex]); translator.push(luaState, arr[intIndex]);
} }
} }
else else
{ {
// Try to use get_Item to index into this .net object // Try to use get_Item to index into this .net object
//MethodInfo getter = objType.GetMethod("get_Item"); //MethodInfo getter = objType.GetMethod("get_Item");
var methods = objType.GetMethods(); var methods = objType.GetMethods();
foreach(var mInfo in methods) foreach(var mInfo in methods)
{ {
if(mInfo.Name == "get_Item") if(mInfo.Name == "get_Item")
{ {
//check if the signature matches the input //check if the signature matches the input
if(mInfo.GetParameters().Length == 1) if(mInfo.GetParameters().Length == 1)
{ {
var getter = mInfo; var getter = mInfo;
var actualParms = (!getter.IsNull()) ? getter.GetParameters() : null; var actualParms = (!getter.IsNull()) ? getter.GetParameters() : null;
if(actualParms.IsNull() || actualParms.Length != 1) if(actualParms.IsNull() || actualParms.Length != 1)
{ {
translator.throwError(luaState, "method not found (or no indexer): " + index); translator.throwError(luaState, "method not found (or no indexer): " + index);
LuaLib.lua_pushnil(luaState); LuaLib.lua_pushnil(luaState);
} }
else else
{ {
// Get the index in a form acceptable to the getter // Get the index in a form acceptable to the getter
index = translator.getAsType(luaState, 2, actualParms[0].ParameterType); index = translator.getAsType(luaState, 2, actualParms[0].ParameterType);
object[] args = new object[1]; object[] args = new object[1];
// Just call the indexer - if out of bounds an exception will happen // Just call the indexer - if out of bounds an exception will happen
args[0] = index; args[0] = index;
try try
{ {
object result = getter.Invoke(obj, args); object result = getter.Invoke(obj, args);
translator.push(luaState, result); translator.push(luaState, result);
} }
catch(TargetInvocationException e) catch(TargetInvocationException e)
{ {
// Provide a more readable description for the common case of key not found // Provide a more readable description for the common case of key not found
if(e.InnerException is KeyNotFoundException) if(e.InnerException is KeyNotFoundException)
translator.throwError(luaState, "key '" + index + "' not found "); translator.throwError(luaState, "key '" + index + "' not found ");
else else
translator.throwError(luaState, "exception indexing '" + index + "' " + e.Message); translator.throwError(luaState, "exception indexing '" + index + "' " + e.Message);
LuaLib.lua_pushnil(luaState); LuaLib.lua_pushnil(luaState);
} }
} }
} }
} }
} }
} }
LuaLib.lua_pushboolean(luaState, false); LuaLib.lua_pushboolean(luaState, false);
return 2; return 2;
} }
/* /*
* __index metafunction of base classes (the base field of Lua tables). * __index metafunction of base classes (the base field of Lua tables).
* Adds a prefix to the method name to call the base version of the method. * Adds a prefix to the method name to call the base version of the method.
*/ */
private int getBaseMethod(LuaCore.lua_State luaState) private int getBaseMethod(LuaCore.lua_State luaState)
{ {
object obj = translator.getRawNetObject(luaState, 1); object obj = translator.getRawNetObject(luaState, 1);
if(obj.IsNull()) if(obj.IsNull())
{ {
translator.throwError(luaState, "trying to index an invalid object reference"); translator.throwError(luaState, "trying to index an invalid object reference");
LuaLib.lua_pushnil(luaState); LuaLib.lua_pushnil(luaState);
LuaLib.lua_pushboolean(luaState, false); LuaLib.lua_pushboolean(luaState, false);
return 2; return 2;
} }
string methodName = LuaLib.lua_tostring(luaState, 2).ToString(); string methodName = LuaLib.lua_tostring(luaState, 2).ToString();
if(methodName.IsNull()) if(methodName.IsNull())
{ {
LuaLib.lua_pushnil(luaState); LuaLib.lua_pushnil(luaState);
LuaLib.lua_pushboolean(luaState, false); LuaLib.lua_pushboolean(luaState, false);
return 2; return 2;
} }
getMember(luaState, obj.GetType(), obj, "__luaInterface_base_" + methodName, BindingFlags.Instance | BindingFlags.IgnoreCase); getMember(luaState, obj.GetType(), obj, "__luaInterface_base_" + methodName, BindingFlags.Instance | BindingFlags.IgnoreCase);
LuaLib.lua_settop(luaState, -2); LuaLib.lua_settop(luaState, -2);
if(LuaLib.lua_type(luaState, -1) == LuaTypes.Nil) if(LuaLib.lua_type(luaState, -1) == LuaTypes.Nil)
{ {
LuaLib.lua_settop(luaState, -2); LuaLib.lua_settop(luaState, -2);
return getMember(luaState, obj.GetType(), obj, methodName, BindingFlags.Instance | BindingFlags.IgnoreCase); return getMember(luaState, obj.GetType(), obj, methodName, BindingFlags.Instance | BindingFlags.IgnoreCase);
} }
LuaLib.lua_pushboolean(luaState, false); LuaLib.lua_pushboolean(luaState, false);
return 2; return 2;
} }
/// <summary> /// <summary>
/// Does this method exist as either an instance or static? /// Does this method exist as either an instance or static?
/// </summary> /// </summary>
/// <param name="objType"></param> /// <param name="objType"></param>
/// <param name="methodName"></param> /// <param name="methodName"></param>
/// <returns></returns> /// <returns></returns>
bool isMemberPresent(IReflect objType, string methodName) bool isMemberPresent(IReflect objType, string methodName)
{ {
object cachedMember = checkMemberCache(memberCache, objType, methodName); object cachedMember = checkMemberCache(memberCache, objType, methodName);
if(!cachedMember.IsNull()) if(!cachedMember.IsNull())
return true; return true;
//CP: Removed NonPublic binding search //CP: Removed NonPublic binding search
var members = objType.GetMember(methodName, BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase/* | BindingFlags.NonPublic*/); var members = objType.GetMember(methodName, BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase/* | BindingFlags.NonPublic*/);
return (members.Length > 0); return (members.Length > 0);
} }
/* /*
* Pushes the value of a member or a delegate to call it, depending on the type of * Pushes the value of a member or a delegate to call it, depending on the type of
* the member. Works with static or instance members. * the member. Works with static or instance members.
* Uses reflection to find members, and stores the reflected MemberInfo object in * Uses reflection to find members, and stores the reflected MemberInfo object in
* a cache (indexed by the type of the object and the name of the member). * a cache (indexed by the type of the object and the name of the member).
*/ */
private int getMember(LuaCore.lua_State luaState, IReflect objType, object obj, string methodName, BindingFlags bindingType) private int getMember(LuaCore.lua_State luaState, IReflect objType, object obj, string methodName, BindingFlags bindingType)
{ {
bool implicitStatic = false; bool implicitStatic = false;
MemberInfo member = null; MemberInfo member = null;
object cachedMember = checkMemberCache(memberCache, objType, methodName); object cachedMember = checkMemberCache(memberCache, objType, methodName);
//object cachedMember=null; //object cachedMember=null;
if(cachedMember is LuaCore.lua_CFunction) if(cachedMember is LuaCore.lua_CFunction)
{ {
translator.pushFunction(luaState, (LuaCore.lua_CFunction)cachedMember); translator.pushFunction(luaState, (LuaCore.lua_CFunction)cachedMember);
translator.push(luaState, true); translator.push(luaState, true);
return 2; return 2;
} }
else if(!cachedMember.IsNull()) else if(!cachedMember.IsNull())
member = (MemberInfo)cachedMember; member = (MemberInfo)cachedMember;
else else
{ {
//CP: Removed NonPublic binding search //CP: Removed NonPublic binding search
var members = objType.GetMember(methodName, bindingType | BindingFlags.Public | BindingFlags.IgnoreCase/*| BindingFlags.NonPublic*/); var members = objType.GetMember(methodName, bindingType | BindingFlags.Public | BindingFlags.IgnoreCase/*| BindingFlags.NonPublic*/);
if(members.Length > 0) if(members.Length > 0)
member = members[0]; member = members[0];
else else
{ {
// If we can't find any suitable instance members, try to find them as statics - but we only want to allow implicit static // If we can't find any suitable instance members, try to find them as statics - but we only want to allow implicit static
// lookups for fields/properties/events -kevinh // lookups for fields/properties/events -kevinh
//CP: Removed NonPublic binding search and made case insensitive //CP: Removed NonPublic binding search and made case insensitive
members = objType.GetMember(methodName, bindingType | BindingFlags.Static | BindingFlags.Public | BindingFlags.IgnoreCase/*| BindingFlags.NonPublic*/); members = objType.GetMember(methodName, bindingType | BindingFlags.Static | BindingFlags.Public | BindingFlags.IgnoreCase/*| BindingFlags.NonPublic*/);
if(members.Length > 0) if(members.Length > 0)
{ {
member = members[0]; member = members[0];
implicitStatic = true; implicitStatic = true;
} }
} }
} }
if(!member.IsNull()) if(!member.IsNull())
{ {
if(member.MemberType == MemberTypes.Field) if(member.MemberType == MemberTypes.Field)
{ {
var field = (FieldInfo)member; var field = (FieldInfo)member;
if(cachedMember.IsNull()) if(cachedMember.IsNull())
setMemberCache(memberCache, objType, methodName, member); setMemberCache(memberCache, objType, methodName, member);
try try
{ {
translator.push(luaState, field.GetValue(obj)); translator.push(luaState, field.GetValue(obj));
} }
catch catch
{ {
LuaLib.lua_pushnil(luaState); LuaLib.lua_pushnil(luaState);
} }
} }
else if(member.MemberType == MemberTypes.Property) else if(member.MemberType == MemberTypes.Property)
{ {
var property = (PropertyInfo)member; var property = (PropertyInfo)member;
if(cachedMember.IsNull()) if(cachedMember.IsNull())
setMemberCache(memberCache, objType, methodName, member); setMemberCache(memberCache, objType, methodName, member);
try try
{ {
object val = property.GetValue(obj, null); object val = property.GetValue(obj, null);
translator.push(luaState, val); translator.push(luaState, val);
} }
catch(ArgumentException) catch(ArgumentException)
{ {
// If we can't find the getter in our class, recurse up to the base class and see // If we can't find the getter in our class, recurse up to the base class and see
// if they can help. // if they can help.
if(objType is Type && !(((Type)objType) == typeof(object))) if(objType is Type && !(((Type)objType) == typeof(object)))
return getMember(luaState, ((Type)objType).BaseType, obj, methodName, bindingType); return getMember(luaState, ((Type)objType).BaseType, obj, methodName, bindingType);
else else
LuaLib.lua_pushnil(luaState); LuaLib.lua_pushnil(luaState);
} }
catch(TargetInvocationException e) // Convert this exception into a Lua error catch(TargetInvocationException e) // Convert this exception into a Lua error
{ {
ThrowError(luaState, e); ThrowError(luaState, e);
LuaLib.lua_pushnil(luaState); LuaLib.lua_pushnil(luaState);
} }
} }
else if(member.MemberType == MemberTypes.Event) else if(member.MemberType == MemberTypes.Event)
{ {
var eventInfo = (EventInfo)member; var eventInfo = (EventInfo)member;
if(cachedMember.IsNull()) if(cachedMember.IsNull())
setMemberCache(memberCache, objType, methodName, member); setMemberCache(memberCache, objType, methodName, member);
translator.push(luaState, new RegisterEventHandler(translator.pendingEvents, obj, eventInfo)); translator.push(luaState, new RegisterEventHandler(translator.pendingEvents, obj, eventInfo));
} }
else if(!implicitStatic) else if(!implicitStatic)
{ {
if(member.MemberType == MemberTypes.NestedType) if(member.MemberType == MemberTypes.NestedType)
{ {
// kevinh - added support for finding nested types // kevinh - added support for finding nested types
// cache us // cache us
if(cachedMember.IsNull()) if(cachedMember.IsNull())
setMemberCache(memberCache, objType, methodName, member); setMemberCache(memberCache, objType, methodName, member);
// Find the name of our class // Find the name of our class
string name = member.Name; string name = member.Name;
var dectype = member.DeclaringType; var dectype = member.DeclaringType;
// Build a new long name and try to find the type by name // Build a new long name and try to find the type by name
string longname = dectype.FullName + "+" + name; string longname = dectype.FullName + "+" + name;
var nestedType = translator.FindType(longname); var nestedType = translator.FindType(longname);
translator.pushType(luaState, nestedType); translator.pushType(luaState, nestedType);
} }
else else
{ {
// Member type must be 'method' // Member type must be 'method'
var wrapper = new LuaCore.lua_CFunction((new LuaMethodWrapper(translator, objType, methodName, bindingType)).call); var wrapper = new LuaCore.lua_CFunction((new LuaMethodWrapper(translator, objType, methodName, bindingType)).call);
if(cachedMember.IsNull()) if(cachedMember.IsNull())
setMemberCache(memberCache, objType, methodName, wrapper); setMemberCache(memberCache, objType, methodName, wrapper);
translator.pushFunction(luaState, wrapper); translator.pushFunction(luaState, wrapper);
translator.push(luaState, true); translator.push(luaState, true);
return 2; return 2;
} }
} }
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 // If we reach this point we found a static method, but can't use it in this context because the user passed in an instance
translator.throwError(luaState, "can't pass instance to static method " + methodName); translator.throwError(luaState, "can't pass instance to static method " + methodName);
LuaLib.lua_pushnil(luaState); LuaLib.lua_pushnil(luaState);
} }
} }
else else
{ {
// kevinh - we want to throw an exception because meerly returning 'nil' in this case // kevinh - we want to throw an exception because meerly returning 'nil' in this case
// is not sufficient. valid data members may return nil and therefore there must be some // is not sufficient. valid data members may return nil and therefore there must be some
// way to know the member just doesn't exist. // way to know the member just doesn't exist.
translator.throwError(luaState, "unknown member name " + methodName); translator.throwError(luaState, "unknown member name " + methodName);
LuaLib.lua_pushnil(luaState); LuaLib.lua_pushnil(luaState);
} }
// push false because we are NOT returning a function (see luaIndexFunction) // push false because we are NOT returning a function (see luaIndexFunction)
translator.push(luaState, false); translator.push(luaState, false);
return 2; return 2;
} }
/* /*
* Checks if a MemberInfo object is cached, returning it or null. * Checks if a MemberInfo object is cached, returning it or null.
*/ */
private object checkMemberCache(Hashtable memberCache, IReflect objType, string memberName) private object checkMemberCache(Hashtable memberCache, IReflect objType, string memberName)
{ {
var members = (Hashtable)memberCache[objType]; var members = (Hashtable)memberCache[objType];
return !members.IsNull() ? members[memberName] : null; return !members.IsNull() ? members[memberName] : null;
} }
/* /*
* Stores a MemberInfo object in the member cache. * Stores a MemberInfo object in the member cache.
*/ */
private void setMemberCache(Hashtable memberCache, IReflect objType, string memberName, object member) private void setMemberCache(Hashtable memberCache, IReflect objType, string memberName, object member)
{ {
var members = (Hashtable)memberCache[objType]; var members = (Hashtable)memberCache[objType];
if(members.IsNull()) if(members.IsNull())
{ {
members = new Hashtable(); members = new Hashtable();
memberCache[objType] = members; memberCache[objType] = members;
} }
members[memberName] = member; members[memberName] = member;
} }
/* /*
* __newindex metafunction of CLR objects. Receives the object, * __newindex metafunction of CLR objects. Receives the object,
* the member name and the value to be stored as arguments. Throws * the member name and the value to be stored as arguments. Throws
* and error if the assignment is invalid. * and error if the assignment is invalid.
*/ */
private int setFieldOrProperty(LuaCore.lua_State luaState) private int setFieldOrProperty(LuaCore.lua_State luaState)
{ {
object target = translator.getRawNetObject(luaState, 1); object target = translator.getRawNetObject(luaState, 1);
if(target.IsNull()) if(target.IsNull())
{ {
translator.throwError(luaState, "trying to index and invalid object reference"); translator.throwError(luaState, "trying to index and invalid object reference");
return 0; return 0;
} }
var type = target.GetType(); var type = target.GetType();
// First try to look up the parameter as a property name // First try to look up the parameter as a property name
string detailMessage; string detailMessage;
bool didMember = trySetMember(luaState, type, target, BindingFlags.Instance | BindingFlags.IgnoreCase, out detailMessage); bool didMember = trySetMember(luaState, type, target, BindingFlags.Instance | BindingFlags.IgnoreCase, out detailMessage);
if(didMember) if(didMember)
return 0; // Must have found the property name return 0; // Must have found the property name
// We didn't find a property name, now see if we can use a [] style this accessor to set array contents // We didn't find a property name, now see if we can use a [] style this accessor to set array contents
try try
{ {
if(type.IsArray && LuaLib.lua_isnumber(luaState, 2)) if(type.IsArray && LuaLib.lua_isnumber(luaState, 2))
{ {
int index = (int)LuaLib.lua_tonumber(luaState, 2); int index = (int)LuaLib.lua_tonumber(luaState, 2);
var arr = (Array)target; var arr = (Array)target;
object val = translator.getAsType(luaState, 3, arr.GetType().GetElementType()); object val = translator.getAsType(luaState, 3, arr.GetType().GetElementType());
arr.SetValue(val, index); arr.SetValue(val, index);
} }
else else
{ {
// Try to see if we have a this[] accessor // Try to see if we have a this[] accessor
var setter = type.GetMethod("set_Item"); var setter = type.GetMethod("set_Item");
if(!setter.IsNull()) if(!setter.IsNull())
{ {
var args = setter.GetParameters(); var args = setter.GetParameters();
var valueType = args[1].ParameterType; var valueType = args[1].ParameterType;
// The new val ue the user specified // The new val ue the user specified
object val = translator.getAsType(luaState, 3, valueType); object val = translator.getAsType(luaState, 3, valueType);
var indexType = args[0].ParameterType; var indexType = args[0].ParameterType;
object index = translator.getAsType(luaState, 2, indexType); object index = translator.getAsType(luaState, 2, indexType);
object[] methodArgs = new object[2]; object[] methodArgs = new object[2];
// Just call the indexer - if out of bounds an exception will happen // Just call the indexer - if out of bounds an exception will happen
methodArgs[0] = index; methodArgs[0] = index;
methodArgs[1] = val; methodArgs[1] = val;
setter.Invoke(target, methodArgs); setter.Invoke(target, methodArgs);
} }
else else
translator.throwError(luaState, detailMessage); // Pass the original message from trySetMember because it is probably best translator.throwError(luaState, detailMessage); // Pass the original message from trySetMember because it is probably best
} }
} }
catch(SEHException) catch(SEHException)
{ {
// If we are seeing a C++ exception - this must actually be for Lua's private use. Let it handle it // If we are seeing a C++ exception - this must actually be for Lua's private use. Let it handle it
throw; throw;
} }
catch(Exception e) catch(Exception e)
{ {
ThrowError(luaState, e); ThrowError(luaState, e);
} }
return 0; return 0;
} }
/// <summary> /// <summary>
/// Tries to set a named property or field /// Tries to set a named property or field
/// </summary> /// </summary>
/// <param name="luaState"></param> /// <param name="luaState"></param>
/// <param name="targetType"></param> /// <param name="targetType"></param>
/// <param name="target"></param> /// <param name="target"></param>
/// <param name="bindingType"></param> /// <param name="bindingType"></param>
/// <returns>false if unable to find the named member, true for success</returns> /// <returns>false if unable to find the named member, true for success</returns>
private bool trySetMember(LuaCore.lua_State luaState, IReflect targetType, object target, BindingFlags bindingType, out string detailMessage) private bool trySetMember(LuaCore.lua_State luaState, IReflect targetType, object target, BindingFlags bindingType, out string detailMessage)
{ {
detailMessage = null; // No error yet detailMessage = null; // No error yet
// If not already a string just return - we don't want to call tostring - which has the side effect of // If not already a string just return - we don't want to call tostring - which has the side effect of
// changing the lua typecode to string // changing the lua typecode to string
// Note: We don't use isstring because the standard lua C isstring considers either strings or numbers to // Note: We don't use isstring because the standard lua C isstring considers either strings or numbers to
// be true for isstring. // be true for isstring.
if(LuaLib.lua_type(luaState, 2) != LuaTypes.String) if(LuaLib.lua_type(luaState, 2) != LuaTypes.String)
{ {
detailMessage = "property names must be strings"; detailMessage = "property names must be strings";
return false; return false;
} }
// We only look up property names by string // We only look up property names by string
string fieldName = LuaLib.lua_tostring(luaState, 2).ToString(); string fieldName = LuaLib.lua_tostring(luaState, 2).ToString();
if(fieldName.IsNull() || fieldName.Length < 1 || !(char.IsLetter(fieldName[0]) || fieldName[0] == '_')) if(fieldName.IsNull() || fieldName.Length < 1 || !(char.IsLetter(fieldName[0]) || fieldName[0] == '_'))
{ {
detailMessage = "invalid property name"; detailMessage = "invalid property name";
return false; return false;
} }
// Find our member via reflection or the cache // Find our member via reflection or the cache
var member = (MemberInfo)checkMemberCache(memberCache, targetType, fieldName); var member = (MemberInfo)checkMemberCache(memberCache, targetType, fieldName);
if(member.IsNull()) if(member.IsNull())
{ {
//CP: Removed NonPublic binding search and made case insensitive //CP: Removed NonPublic binding search and made case insensitive
var members = targetType.GetMember(fieldName, bindingType | BindingFlags.Public | BindingFlags.IgnoreCase/*| BindingFlags.NonPublic*/); var members = targetType.GetMember(fieldName, bindingType | BindingFlags.Public | BindingFlags.IgnoreCase/*| BindingFlags.NonPublic*/);
if(members.Length > 0) if(members.Length > 0)
{ {
member = members[0]; member = members[0];
setMemberCache(memberCache, targetType, fieldName, member); setMemberCache(memberCache, targetType, fieldName, member);
} }
else else
{ {
detailMessage = "field or property '" + fieldName + "' does not exist"; detailMessage = "field or property '" + fieldName + "' does not exist";
return false; return false;
} }
} }
if(member.MemberType == MemberTypes.Field) if(member.MemberType == MemberTypes.Field)
{ {
var field = (FieldInfo)member; var field = (FieldInfo)member;
object val = translator.getAsType(luaState, 3, field.FieldType); object val = translator.getAsType(luaState, 3, field.FieldType);
try try
{ {
field.SetValue(target, val); field.SetValue(target, val);
} }
catch (Exception e) catch (Exception e)
{ {
ThrowError(luaState, e); ThrowError(luaState, e);
} }
// We did a call // We did a call
return true; return true;
} }
else if(member.MemberType == MemberTypes.Property) else if(member.MemberType == MemberTypes.Property)
{ {
var property = (PropertyInfo)member; var property = (PropertyInfo)member;
object val = translator.getAsType(luaState, 3, property.PropertyType); object val = translator.getAsType(luaState, 3, property.PropertyType);
try try
{ {
property.SetValue(target, val, null); property.SetValue(target, val, null);
} }
catch (Exception e) catch (Exception e)
{ {
ThrowError(luaState, e); ThrowError(luaState, e);
} }
// We did a call // We did a call
return true; return true;
} }
detailMessage = "'" + fieldName + "' is not a .net field or property"; detailMessage = "'" + fieldName + "' is not a .net field or property";
return false; return false;
} }
/* /*
* Writes to fields or properties, either static or instance. Throws an error * Writes to fields or properties, either static or instance. Throws an error
* if the operation is invalid. * if the operation is invalid.
*/ */
private int setMember(LuaCore.lua_State luaState, IReflect targetType, object target, BindingFlags bindingType) private int setMember(LuaCore.lua_State luaState, IReflect targetType, object target, BindingFlags bindingType)
{ {
string detail; string detail;
bool success = trySetMember(luaState, targetType, target, bindingType, out detail); bool success = trySetMember(luaState, targetType, target, bindingType, out detail);
if(!success) if(!success)
translator.throwError(luaState, detail); translator.throwError(luaState, detail);
return 0; return 0;
} }
/// <summary> /// <summary>
/// Convert a C# exception into a Lua error /// Convert a C# exception into a Lua error
/// </summary> /// </summary>
/// <param name="e"></param> /// <param name="e"></param>
/// We try to look into the exception to give the most meaningful description /// We try to look into the exception to give the most meaningful description
void ThrowError(LuaCore.lua_State luaState, Exception e) void ThrowError(LuaCore.lua_State luaState, Exception e)
{ {
// If we got inside a reflection show what really happened // If we got inside a reflection show what really happened
var te = e as TargetInvocationException; var te = e as TargetInvocationException;
if (!te.IsNull()) if (!te.IsNull())
e = te.InnerException; e = te.InnerException;
translator.throwError(luaState, e); translator.throwError(luaState, e);
} }
/* /*
* __index metafunction of type references, works on static members. * __index metafunction of type references, works on static members.
*/ */
private int getClassMethod(LuaCore.lua_State luaState) private int getClassMethod(LuaCore.lua_State luaState)
{ {
IReflect klass; IReflect klass;
object obj = translator.getRawNetObject(luaState, 1); object obj = translator.getRawNetObject(luaState, 1);
if(obj.IsNull() || !(obj is IReflect)) if(obj.IsNull() || !(obj is IReflect))
{ {
translator.throwError(luaState, "trying to index an invalid type reference"); translator.throwError(luaState, "trying to index an invalid type reference");
LuaLib.lua_pushnil(luaState); LuaLib.lua_pushnil(luaState);
return 1; return 1;
} }
else else
klass = (IReflect)obj; klass = (IReflect)obj;
if(LuaLib.lua_isnumber(luaState, 2)) if(LuaLib.lua_isnumber(luaState, 2))
{ {
int size = (int)LuaLib.lua_tonumber(luaState, 2); int size = (int)LuaLib.lua_tonumber(luaState, 2);
translator.push(luaState, Array.CreateInstance(klass.UnderlyingSystemType, size)); translator.push(luaState, Array.CreateInstance(klass.UnderlyingSystemType, size));
return 1; return 1;
} }
else else
{ {
string methodName = LuaLib.lua_tostring(luaState, 2).ToString(); string methodName = LuaLib.lua_tostring(luaState, 2).ToString();
if(methodName.IsNull()) if(methodName.IsNull())
{ {
LuaLib.lua_pushnil(luaState); LuaLib.lua_pushnil(luaState);
return 1; return 1;
} //CP: Ignore case } //CP: Ignore case
else else
return getMember(luaState, klass, null, methodName, BindingFlags.FlattenHierarchy | BindingFlags.Static | BindingFlags.IgnoreCase); return getMember(luaState, klass, null, methodName, BindingFlags.FlattenHierarchy | BindingFlags.Static | BindingFlags.IgnoreCase);
} }
} }
/* /*
* __newindex function of type references, works on static members. * __newindex function of type references, works on static members.
*/ */
private int setClassFieldOrProperty(LuaCore.lua_State luaState) private int setClassFieldOrProperty(LuaCore.lua_State luaState)
{ {
IReflect target; IReflect target;
object obj = translator.getRawNetObject(luaState, 1); object obj = translator.getRawNetObject(luaState, 1);
if(obj.IsNull() || !(obj is IReflect)) if(obj.IsNull() || !(obj is IReflect))
{ {
translator.throwError(luaState, "trying to index an invalid type reference"); translator.throwError(luaState, "trying to index an invalid type reference");
return 0; return 0;
} }
else else
target = (IReflect)obj; target = (IReflect)obj;
return setMember(luaState, target, null, BindingFlags.FlattenHierarchy | BindingFlags.Static | BindingFlags.IgnoreCase); return setMember(luaState, target, null, BindingFlags.FlattenHierarchy | BindingFlags.Static | BindingFlags.IgnoreCase);
} }
/* /*
* __call metafunction of type references. Searches for and calls * __call metafunction of type references. Searches for and calls
* a constructor for the type. Returns nil if the constructor is not * a constructor for the type. Returns nil if the constructor is not
* found or if the arguments are invalid. Throws an error if the constructor * found or if the arguments are invalid. Throws an error if the constructor
* generates an exception. * generates an exception.
*/ */
private int callConstructor(LuaCore.lua_State luaState) private int callConstructor(LuaCore.lua_State luaState)
{ {
var validConstructor = new MethodCache(); var validConstructor = new MethodCache();
IReflect klass; IReflect klass;
object obj = translator.getRawNetObject(luaState, 1); object obj = translator.getRawNetObject(luaState, 1);
if(obj.IsNull() || !(obj is IReflect)) if(obj.IsNull() || !(obj is IReflect))
{ {
translator.throwError(luaState, "trying to call constructor on an invalid type reference"); translator.throwError(luaState, "trying to call constructor on an invalid type reference");
LuaLib.lua_pushnil(luaState); LuaLib.lua_pushnil(luaState);
return 1; return 1;
} }
else else
klass = (IReflect)obj; klass = (IReflect)obj;
LuaLib.lua_remove(luaState, 1); LuaLib.lua_remove(luaState, 1);
var constructors = klass.UnderlyingSystemType.GetConstructors(); var constructors = klass.UnderlyingSystemType.GetConstructors();
foreach(var constructor in constructors) foreach(var constructor in constructors)
{ {
bool isConstructor = matchParameters(luaState, constructor, ref validConstructor); bool isConstructor = matchParameters(luaState, constructor, ref validConstructor);
if(isConstructor) if(isConstructor)
{ {
try try
{ {
translator.push(luaState, constructor.Invoke(validConstructor.args)); translator.push(luaState, constructor.Invoke(validConstructor.args));
} }
catch(TargetInvocationException e) catch(TargetInvocationException e)
{ {
ThrowError(luaState, e); ThrowError(luaState, e);
LuaLib.lua_pushnil(luaState); LuaLib.lua_pushnil(luaState);
} }
catch catch
{ {
LuaLib.lua_pushnil(luaState); LuaLib.lua_pushnil(luaState);
} }
return 1; return 1;
} }
} }
string constructorName = (constructors.Length == 0) ? "unknown" : constructors[0].Name; string constructorName = (constructors.Length == 0) ? "unknown" : constructors[0].Name;
translator.throwError(luaState, String.Format("{0} does not contain constructor({1}) argument match", translator.throwError(luaState, String.Format("{0} does not contain constructor({1}) argument match",
klass.UnderlyingSystemType, constructorName)); klass.UnderlyingSystemType, constructorName));
LuaLib.lua_pushnil(luaState); LuaLib.lua_pushnil(luaState);
return 1; return 1;
} }
/* /*
* Matches a method against its arguments in the Lua stack. Returns * Matches a method against its arguments in the Lua stack. Returns
* if the match was succesful. It it was also returns the information * if the match was succesful. It it was also returns the information
* necessary to invoke the method. * necessary to invoke the method.
*/ */
internal bool matchParameters(LuaCore.lua_State luaState, MethodBase method, ref MethodCache methodCache) internal bool matchParameters(LuaCore.lua_State luaState, MethodBase method, ref MethodCache methodCache)
{ {
ExtractValue extractValue; ExtractValue extractValue;
bool isMethod = true; bool isMethod = true;
var paramInfo = method.GetParameters(); var paramInfo = method.GetParameters();
int currentLuaParam = 1; int currentLuaParam = 1;
int nLuaParams = LuaLib.lua_gettop(luaState); int nLuaParams = LuaLib.lua_gettop(luaState);
var paramList = new ArrayList(); var paramList = new ArrayList();
var outList = new List<int>(); var outList = new List<int>();
var argTypes = new List<MethodArgs>(); var argTypes = new List<MethodArgs>();
foreach(var currentNetParam in paramInfo) foreach(var currentNetParam in paramInfo)
{ {
if(!currentNetParam.IsIn && currentNetParam.IsOut) // Skips out params if(!currentNetParam.IsIn && currentNetParam.IsOut) // Skips out params
outList.Add(paramList.Add(null)); outList.Add(paramList.Add(null));
else if(currentLuaParam > nLuaParams) // Adds optional parameters else if(currentLuaParam > nLuaParams) // Adds optional parameters
{ {
if(currentNetParam.IsOptional) if(currentNetParam.IsOptional)
paramList.Add(currentNetParam.DefaultValue); paramList.Add(currentNetParam.DefaultValue);
else else
{ {
isMethod = false; isMethod = false;
break; break;
} }
} }
else if(_IsTypeCorrect(luaState, currentLuaParam, currentNetParam, out extractValue)) // Type checking else if(_IsTypeCorrect(luaState, currentLuaParam, currentNetParam, out extractValue)) // Type checking
{ {
int index = paramList.Add(extractValue(luaState, currentLuaParam)); int index = paramList.Add(extractValue(luaState, currentLuaParam));
var methodArg = new MethodArgs(); var methodArg = new MethodArgs();
methodArg.index = index; methodArg.index = index;
methodArg.extractValue = extractValue; methodArg.extractValue = extractValue;
argTypes.Add(methodArg); argTypes.Add(methodArg);
if(currentNetParam.ParameterType.IsByRef) if(currentNetParam.ParameterType.IsByRef)
outList.Add(index); outList.Add(index);
currentLuaParam++; currentLuaParam++;
} // Type does not match, ignore if the parameter is optional } // Type does not match, ignore if the parameter is optional
else if(_IsParamsArray(luaState, currentLuaParam, currentNetParam, out extractValue)) else if(_IsParamsArray(luaState, currentLuaParam, currentNetParam, out extractValue))
{ {
object luaParamValue = extractValue(luaState, currentLuaParam); object luaParamValue = extractValue(luaState, currentLuaParam);
var paramArrayType = currentNetParam.ParameterType.GetElementType(); var paramArrayType = currentNetParam.ParameterType.GetElementType();
Array paramArray; Array paramArray;
if(luaParamValue is LuaTable) if(luaParamValue is LuaTable)
{ {
var table = (LuaTable)luaParamValue; var table = (LuaTable)luaParamValue;
var tableEnumerator = table.GetEnumerator(); var tableEnumerator = table.GetEnumerator();
paramArray = Array.CreateInstance(paramArrayType, table.Values.Count); paramArray = Array.CreateInstance(paramArrayType, table.Values.Count);
tableEnumerator.Reset(); tableEnumerator.Reset();
int paramArrayIndex = 0; int paramArrayIndex = 0;
while(tableEnumerator.MoveNext()) while(tableEnumerator.MoveNext())
{ {
paramArray.SetValue(Convert.ChangeType(tableEnumerator.Value, currentNetParam.ParameterType.GetElementType()), paramArrayIndex); paramArray.SetValue(Convert.ChangeType(tableEnumerator.Value, currentNetParam.ParameterType.GetElementType()), paramArrayIndex);
paramArrayIndex++; paramArrayIndex++;
} }
} }
else else
{ {
paramArray = Array.CreateInstance(paramArrayType, 1); paramArray = Array.CreateInstance(paramArrayType, 1);
paramArray.SetValue(luaParamValue, 0); paramArray.SetValue(luaParamValue, 0);
} }
int index = paramList.Add(paramArray); int index = paramList.Add(paramArray);
var methodArg = new MethodArgs(); var methodArg = new MethodArgs();
methodArg.index = index; methodArg.index = index;
methodArg.extractValue = extractValue; methodArg.extractValue = extractValue;
methodArg.isParamsArray = true; methodArg.isParamsArray = true;
methodArg.paramsArrayType = paramArrayType; methodArg.paramsArrayType = paramArrayType;
argTypes.Add(methodArg); argTypes.Add(methodArg);
currentLuaParam++; currentLuaParam++;
} }
else if(currentNetParam.IsOptional) else if(currentNetParam.IsOptional)
paramList.Add(currentNetParam.DefaultValue); paramList.Add(currentNetParam.DefaultValue);
else // No match else // No match
{ {
isMethod = false; isMethod = false;
break; break;
} }
} }
if(currentLuaParam != nLuaParams + 1) // Number of parameters does not match if(currentLuaParam != nLuaParams + 1) // Number of parameters does not match
isMethod = false; isMethod = false;
if(isMethod) if(isMethod)
{ {
methodCache.args = paramList.ToArray(); methodCache.args = paramList.ToArray();
methodCache.cachedMethod = method; methodCache.cachedMethod = method;
methodCache.outList = outList.ToArray(); methodCache.outList = outList.ToArray();
methodCache.argTypes = argTypes.ToArray(); methodCache.argTypes = argTypes.ToArray();
} }
return isMethod; return isMethod;
} }
/// <summary> /// <summary>
/// CP: Fix for operator overloading failure /// CP: Fix for operator overloading failure
/// Returns true if the type is set and assigns the extract value /// Returns true if the type is set and assigns the extract value
/// </summary> /// </summary>
/// <param name="luaState"></param> /// <param name="luaState"></param>
/// <param name="currentLuaParam"></param> /// <param name="currentLuaParam"></param>
/// <param name="currentNetParam"></param> /// <param name="currentNetParam"></param>
/// <param name="extractValue"></param> /// <param name="extractValue"></param>
/// <returns></returns> /// <returns></returns>
private bool _IsTypeCorrect(LuaCore.lua_State luaState, int currentLuaParam, ParameterInfo currentNetParam, out ExtractValue extractValue) private bool _IsTypeCorrect(LuaCore.lua_State luaState, int currentLuaParam, ParameterInfo currentNetParam, out ExtractValue extractValue)
{ {
try try
{ {
return (extractValue = translator.typeChecker.checkType(luaState, currentLuaParam, currentNetParam.ParameterType)) != null; return (extractValue = translator.typeChecker.checkType(luaState, currentLuaParam, currentNetParam.ParameterType)) != null;
} }
catch catch
{ {
extractValue = null; extractValue = null;
Debug.WriteLine("Type wasn't correct"); Debug.WriteLine("Type wasn't correct");
return false; return false;
} }
} }
private bool _IsParamsArray(LuaCore.lua_State luaState, int currentLuaParam, ParameterInfo currentNetParam, out ExtractValue extractValue) private bool _IsParamsArray(LuaCore.lua_State luaState, int currentLuaParam, ParameterInfo currentNetParam, out ExtractValue extractValue)
{ {
extractValue = null; extractValue = null;
if (currentNetParam.GetCustomAttributes(typeof(ParamArrayAttribute), false).Length > 0) if (currentNetParam.GetCustomAttributes(typeof(ParamArrayAttribute), false).Length > 0)
{ {
LuaTypes luaType; LuaTypes luaType;
try try
{ {
luaType = LuaLib.lua_type(luaState, currentLuaParam); luaType = LuaLib.lua_type(luaState, currentLuaParam);
} }
catch(Exception ex) catch(Exception ex)
{ {
Debug.WriteLine("Could not retrieve lua type while attempting to determine params Array Status."); Debug.WriteLine("Could not retrieve lua type while attempting to determine params Array Status.");
Debug.WriteLine(ex.Message); Debug.WriteLine(ex.Message);
extractValue = null; extractValue = null;
return false; return false;
} }
if(luaType == LuaTypes.Table) if(luaType == LuaTypes.Table)
{ {
try try
{ {
extractValue = translator.typeChecker.getExtractor(typeof(LuaTable)); extractValue = translator.typeChecker.getExtractor(typeof(LuaTable));
} }
catch(Exception/* ex*/) catch(Exception/* ex*/)
{ {
Debug.WriteLine("An error occurred during an attempt to retrieve a LuaTable extractor while checking for params array status."); Debug.WriteLine("An error occurred during an attempt to retrieve a LuaTable extractor while checking for params array status.");
} }
if(!extractValue.IsNull()) if(!extractValue.IsNull())
{ {
return true; return true;
} }
} }
else else
{ {
var paramElementType = currentNetParam.ParameterType.GetElementType(); var paramElementType = currentNetParam.ParameterType.GetElementType();
try try
{ {
extractValue = translator.typeChecker.checkType(luaState, currentLuaParam, paramElementType); extractValue = translator.typeChecker.checkType(luaState, currentLuaParam, paramElementType);
} }
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(string.Format("An error occurred during an attempt to retrieve an extractor ({0}) while checking for params array status.", paramElementType.FullName));
} }
if(!extractValue.IsNull()) if(!extractValue.IsNull())
{ {
return true; return true;
} }
} }
} }
Debug.WriteLine("Type wasn't Params object."); Debug.WriteLine("Type wasn't Params object.");
return false; return false;
} }
} }
} }
\ No newline at end of file
/* /*
* This file is part of LuaInterface. * This file is part of LuaInterface.
* *
* Copyright (C) 2003-2005 Fabio Mascarenhas de Queiroz. * Copyright (C) 2003-2005 Fabio Mascarenhas de Queiroz.
* Copyright (C) 2012 Megax <http://megax.yeahunter.hu/> * Copyright (C) 2012 Megax <http://megax.yeahunter.hu/>
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal * of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights * in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is * copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions: * furnished to do so, subject to the following conditions:
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* 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.
*/ */
using System; using System;
using System.Diagnostics; using System.Diagnostics;
using System.Collections.Generic; using System.Collections.Generic;
namespace LuaInterface.Method namespace LuaInterface.Method
{ {
/// <summary> /// <summary>
/// We keep track of what delegates we have auto attached to an event - to allow us to cleanly exit a LuaInterface session /// We keep track of what delegates we have auto attached to an event - to allow us to cleanly exit a LuaInterface session
/// </summary> /// </summary>
class EventHandlerContainer : IDisposable class EventHandlerContainer : IDisposable
{ {
private Dictionary<Delegate, RegisterEventHandler> dict = new Dictionary<Delegate, RegisterEventHandler>(); private Dictionary<Delegate, RegisterEventHandler> dict = new Dictionary<Delegate, RegisterEventHandler>();
public void Add(Delegate handler, RegisterEventHandler eventInfo) public void Add(Delegate handler, RegisterEventHandler eventInfo)
{ {
dict.Add(handler, eventInfo); dict.Add(handler, eventInfo);
} }
public void Remove(Delegate handler) public void Remove(Delegate handler)
{ {
bool found = dict.Remove(handler); bool found = dict.Remove(handler);
Debug.Assert(found); Debug.Assert(found);
} }
/// <summary> /// <summary>
/// Remove any still registered handlers /// Remove any still registered handlers
/// </summary> /// </summary>
public void Dispose() public void Dispose()
{ {
foreach(KeyValuePair<Delegate, RegisterEventHandler> pair in dict) foreach(KeyValuePair<Delegate, RegisterEventHandler> pair in dict)
pair.Value.RemovePending(pair.Key); pair.Value.RemovePending(pair.Key);
dict.Clear(); dict.Clear();
} }
} }
} }
\ No newline at end of file
/* /*
* This file is part of LuaInterface. * This file is part of LuaInterface.
* *
* Copyright (C) 2003-2005 Fabio Mascarenhas de Queiroz. * Copyright (C) 2003-2005 Fabio Mascarenhas de Queiroz.
* Copyright (C) 2012 Megax <http://megax.yeahunter.hu/> * Copyright (C) 2012 Megax <http://megax.yeahunter.hu/>
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal * of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights * in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is * copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions: * furnished to do so, subject to the following conditions:
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* 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.
*/ */
using System; using System;
namespace LuaInterface.Method namespace LuaInterface.Method
{ {
/* /*
* Static helper methods for Lua tables acting as CLR objects. * Static helper methods for Lua tables acting as CLR objects.
* *
* Author: Fabio Mascarenhas * Author: Fabio Mascarenhas
* Version: 1.0 * Version: 1.0
*/ */
public class LuaClassHelper public class LuaClassHelper
{ {
/* /*
* Gets the function called name from the provided table, * Gets the function called name from the provided table,
* returning null if it does not exist * returning null if it does not exist
*/ */
public static LuaFunction getTableFunction(LuaTable luaTable, string name) public static LuaFunction getTableFunction(LuaTable luaTable, string name)
{ {
object funcObj = luaTable.rawget(name); object funcObj = luaTable.rawget(name);
if(funcObj is LuaFunction) if(funcObj is LuaFunction)
return (LuaFunction)funcObj; return (LuaFunction)funcObj;
else else
return null; return null;
} }
/* /*
* Calls the provided function with the provided parameters * Calls the provided function with the provided parameters
*/ */
public static object callFunction(LuaFunction function, object[] args, Type[] returnTypes, object[] inArgs, int[] outArgs) public static object callFunction(LuaFunction function, object[] args, Type[] returnTypes, object[] inArgs, int[] outArgs)
{ {
// args is the return array of arguments, inArgs is the actual array // args is the return array of arguments, inArgs is the actual array
// of arguments passed to the function (with in parameters only), outArgs // of arguments passed to the function (with in parameters only), outArgs
// has the positions of out parameters // has the positions of out parameters
object returnValue; object returnValue;
int iRefArgs; int iRefArgs;
object[] returnValues = function.call(inArgs, returnTypes); object[] returnValues = function.call(inArgs, returnTypes);
if(returnTypes[0] == typeof(void)) if(returnTypes[0] == typeof(void))
{ {
returnValue = null; returnValue = null;
iRefArgs = 0; iRefArgs = 0;
} }
else else
{ {
returnValue = returnValues[0]; returnValue = returnValues[0];
iRefArgs = 1; iRefArgs = 1;
} }
for(int i = 0; i < outArgs.Length; i++) for(int i = 0; i < outArgs.Length; i++)
{ {
args[outArgs[i]] = returnValues[iRefArgs]; args[outArgs[i]] = returnValues[iRefArgs];
iRefArgs++; iRefArgs++;
} }
return returnValue; return returnValue;
} }
} }
} }
\ No newline at end of file
/* /*
* This file is part of LuaInterface. * This file is part of LuaInterface.
* *
* Copyright (C) 2003-2005 Fabio Mascarenhas de Queiroz. * Copyright (C) 2003-2005 Fabio Mascarenhas de Queiroz.
* Copyright (C) 2012 Megax <http://megax.yeahunter.hu/> * Copyright (C) 2012 Megax <http://megax.yeahunter.hu/>
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal * of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights * in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is * copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions: * furnished to do so, subject to the following conditions:
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* 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.
*/ */
using System; using System;
namespace LuaInterface.Method namespace LuaInterface.Method
{ {
/* /*
* Wrapper class for Lua functions as delegates * Wrapper class for Lua functions as delegates
* Subclasses with correct signatures are created * Subclasses with correct signatures are created
* at runtime. * at runtime.
* *
* Author: Fabio Mascarenhas * Author: Fabio Mascarenhas
* Version: 1.0 * Version: 1.0
*/ */
public class LuaDelegate public class LuaDelegate
{ {
public LuaFunction function; public LuaFunction function;
public Type[] returnTypes; public Type[] returnTypes;
public LuaDelegate() public LuaDelegate()
{ {
function = null; function = null;
returnTypes = null; returnTypes = null;
} }
public object callFunction(object[] args, object[] inArgs, int[] outArgs) public object callFunction(object[] args, object[] inArgs, int[] outArgs)
{ {
// args is the return array of arguments, inArgs is the actual array // args is the return array of arguments, inArgs is the actual array
// of arguments passed to the function (with in parameters only), outArgs // of arguments passed to the function (with in parameters only), outArgs
// has the positions of out parameters // has the positions of out parameters
object returnValue; object returnValue;
int iRefArgs; int iRefArgs;
object[] returnValues = function.call(inArgs, returnTypes); object[] returnValues = function.call(inArgs, returnTypes);
if(returnTypes[0] == typeof(void)) if(returnTypes[0] == typeof(void))
{ {
returnValue = null; returnValue = null;
iRefArgs = 0; iRefArgs = 0;
} }
else else
{ {
returnValue = returnValues[0]; returnValue = returnValues[0];
iRefArgs = 1; iRefArgs = 1;
} }
// Sets the value of out and ref parameters (from // Sets the value of out and ref parameters (from
// the values returned by the Lua function). // the values returned by the Lua function).
for(int i = 0; i < outArgs.Length; i++) for(int i = 0; i < outArgs.Length; i++)
{ {
args[outArgs[i]] = returnValues[iRefArgs]; args[outArgs[i]] = returnValues[iRefArgs];
iRefArgs++; iRefArgs++;
} }
return returnValue; return returnValue;
} }
} }
} }
\ No newline at end of file
/* /*
* This file is part of LuaInterface. * This file is part of LuaInterface.
* *
* Copyright (C) 2003-2005 Fabio Mascarenhas de Queiroz. * Copyright (C) 2003-2005 Fabio Mascarenhas de Queiroz.
* Copyright (C) 2012 Megax <http://megax.yeahunter.hu/> * Copyright (C) 2012 Megax <http://megax.yeahunter.hu/>
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal * of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights * in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is * copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions: * furnished to do so, subject to the following conditions:
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* 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.
*/ */
using System; using System;
namespace LuaInterface.Method namespace LuaInterface.Method
{ {
/* /*
* Base wrapper class for Lua function event handlers. * Base wrapper class for Lua function event handlers.
* Subclasses that do actual event handling are created * Subclasses that do actual event handling are created
* at runtime. * at runtime.
* *
* Author: Fabio Mascarenhas * Author: Fabio Mascarenhas
* Version: 1.0 * Version: 1.0
*/ */
public class LuaEventHandler public class LuaEventHandler
{ {
public LuaFunction handler = null; public LuaFunction handler = null;
// CP: Fix provided by Ben Bryant for delegates with one param // CP: Fix provided by Ben Bryant for delegates with one param
// link: http://luaforge.net/forum/message.php?msg_id=9318 // link: http://luaforge.net/forum/message.php?msg_id=9318
public void handleEvent(object[] args) public void handleEvent(object[] args)
{ {
handler.Call(args); handler.Call(args);
} }
//public void handleEvent(object sender,object data) //public void handleEvent(object sender,object data)
//{ //{
// handler.call(new object[] { sender,data },new Type[0]); // handler.call(new object[] { sender,data },new Type[0]);
//} //}
} }
} }
\ 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