Commit 5fc72461 authored by Vinicius Jarina's avatar Vinicius Jarina
Browse files

Mono-style format.

parent a0e1671c
......@@ -23,7 +23,6 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
namespace LuaInterface
......
......@@ -23,7 +23,6 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
namespace LuaInterface
......
......@@ -23,7 +23,6 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.IO;
using LuaInterface.Extensions;
......@@ -38,294 +37,284 @@ namespace LuaInterface
private static object tag = 0;
// steffenj: BEGIN additional Lua API functions new in Lua 5.1
public static int lua_gc(LuaCore.lua_State luaState, GCOptions what, int data)
public static int lua_gc (LuaCore.lua_State luaState, GCOptions what, int data)
{
return LuaCore.lua_gc(luaState, (int)what, data);
return LuaCore.lua_gc (luaState, (int)what, data);
}
public static string lua_typename(LuaCore.lua_State luaState, LuaTypes type)
public static string lua_typename (LuaCore.lua_State luaState, LuaTypes type)
{
return LuaCore.lua_typename(luaState, (int)type).ToString();
return LuaCore.lua_typename (luaState, (int)type).ToString ();
}
public static string luaL_typename(LuaCore.lua_State luaState, int stackPos)
public static string luaL_typename (LuaCore.lua_State luaState, int stackPos)
{
return lua_typename(luaState, lua_type(luaState, stackPos));
return lua_typename (luaState, lua_type (luaState, stackPos));
}
public static void luaL_error(LuaCore.lua_State luaState, string message)
public static void luaL_error (LuaCore.lua_State luaState, string message)
{
LuaCore.luaL_error(luaState, message);
LuaCore.luaL_error (luaState, message);
}
public static void luaL_where(LuaCore.lua_State luaState, int level)
public static void luaL_where (LuaCore.lua_State luaState, int level)
{
LuaCore.luaL_where(luaState, level);
LuaCore.luaL_where (luaState, level);
}
// steffenj: BEGIN Lua 5.1.1 API change (lua_open replaced by luaL_newstate)
public static LuaCore.lua_State luaL_newstate()
public static LuaCore.lua_State luaL_newstate ()
{
return LuaCore.luaL_newstate();
return LuaCore.luaL_newstate ();
}
// steffenj: BEGIN Lua 5.1.1 API change (new function luaL_openlibs)
public static void luaL_openlibs(LuaCore.lua_State luaState)
public static void luaL_openlibs (LuaCore.lua_State luaState)
{
LuaCore.luaL_openlibs(luaState);
LuaCore.luaL_openlibs (luaState);
}
// steffenj: END Lua 5.1.1 API change (lua_strlen is now lua_objlen)
// steffenj: BEGIN Lua 5.1.1 API change (lua_dostring is now a macro luaL_dostring)
public static int luaL_loadstring(LuaCore.lua_State luaState, string chunk)
public static int luaL_loadstring (LuaCore.lua_State luaState, string chunk)
{
return LuaCore.luaL_loadstring(luaState, chunk);
return LuaCore.luaL_loadstring (luaState, chunk);
}
public static int luaL_dostring(LuaCore.lua_State luaState, string chunk)
public static int luaL_dostring (LuaCore.lua_State luaState, string chunk)
{
int result = luaL_loadstring(luaState, chunk);
if(result != 0)
int result = luaL_loadstring (luaState, chunk);
if (result != 0)
return result;
return lua_pcall(luaState, 0, -1, 0);
return lua_pcall (luaState, 0, -1, 0);
}
/// <summary>DEPRECATED - use luaL_dostring(LuaCore.lua_State luaState, string chunk) instead!</summary>
public static int lua_dostring(LuaCore.lua_State luaState, string chunk)
public static int lua_dostring (LuaCore.lua_State luaState, string chunk)
{
return luaL_dostring(luaState, chunk);
return luaL_dostring (luaState, chunk);
}
// steffenj: END Lua 5.1.1 API change (lua_dostring is now a macro luaL_dostring)
// steffenj: BEGIN Lua 5.1.1 API change (lua_newtable is gone, lua_createtable is new)
public static void lua_createtable(LuaCore.lua_State luaState, int narr, int nrec)
public static void lua_createtable (LuaCore.lua_State luaState, int narr, int nrec)
{
LuaCore.lua_createtable(luaState, narr, nrec);
LuaCore.lua_createtable (luaState, narr, nrec);
}
public static void lua_newtable(LuaCore.lua_State luaState)
public static void lua_newtable (LuaCore.lua_State luaState)
{
lua_createtable(luaState, 0, 0);
lua_createtable (luaState, 0, 0);
}
// steffenj: END Lua 5.1.1 API change (lua_newtable is gone, lua_createtable is new)
// steffenj: BEGIN Lua 5.1.1 API change (lua_dofile now in LuaLib as luaL_dofile macro)
public static int luaL_dofile(LuaCore.lua_State luaState, string fileName)
public static int luaL_dofile (LuaCore.lua_State luaState, string fileName)
{
int result = LuaCore.luaL_loadfile(luaState, fileName);
if(result != 0)
int result = LuaCore.luaL_loadfile (luaState, fileName);
if (result != 0)
return result;
return LuaCore.lua_pcall(luaState, 0, -1, 0);
return LuaCore.lua_pcall (luaState, 0, -1, 0);
}
// steffenj: END Lua 5.1.1 API change (lua_dofile now in LuaLib as luaL_dofile)
public static void lua_getglobal(LuaCore.lua_State luaState, string name)
public static void lua_getglobal (LuaCore.lua_State luaState, string name)
{
lua_pushstring(luaState, name);
LuaCore.lua_gettable(luaState, (int)LuaIndexes.Globals);
lua_pushstring (luaState, name);
LuaCore.lua_gettable (luaState, (int)LuaIndexes.Globals);
}
public static void lua_setglobal(LuaCore.lua_State luaState, string name)
public static void lua_setglobal (LuaCore.lua_State luaState, string name)
{
lua_pushstring(luaState,name);
lua_insert(luaState,-2);
lua_settable(luaState, (int)LuaIndexes.Globals);
lua_pushstring (luaState, name);
lua_insert (luaState, -2);
lua_settable (luaState, (int)LuaIndexes.Globals);
}
public static void lua_settop(LuaCore.lua_State luaState, int newTop)
public static void lua_settop (LuaCore.lua_State luaState, int newTop)
{
LuaCore.lua_settop(luaState, newTop);
LuaCore.lua_settop (luaState, newTop);
}
public static void lua_pop(LuaCore.lua_State luaState, int amount)
public static void lua_pop (LuaCore.lua_State luaState, int amount)
{
lua_settop(luaState, -(amount) - 1);
lua_settop (luaState, -(amount) - 1);
}
public static void lua_insert(LuaCore.lua_State luaState, int newTop)
public static void lua_insert (LuaCore.lua_State luaState, int newTop)
{
LuaCore.lua_insert(luaState, newTop);
LuaCore.lua_insert (luaState, newTop);
}
public static void lua_remove(LuaCore.lua_State luaState, int index)
public static void lua_remove (LuaCore.lua_State luaState, int index)
{
LuaCore.lua_remove(luaState, index);
LuaCore.lua_remove (luaState, index);
}
public static void lua_gettable(LuaCore.lua_State luaState, int index)
public static void lua_gettable (LuaCore.lua_State luaState, int index)
{
LuaCore.lua_gettable(luaState, index);
LuaCore.lua_gettable (luaState, index);
}
public static void lua_rawget(LuaCore.lua_State luaState, int index)
public static void lua_rawget (LuaCore.lua_State luaState, int index)
{
LuaCore.lua_rawget(luaState, index);
LuaCore.lua_rawget (luaState, index);
}
public static void lua_settable(LuaCore.lua_State luaState, int index)
public static void lua_settable (LuaCore.lua_State luaState, int index)
{
LuaCore.lua_settable(luaState, index);
LuaCore.lua_settable (luaState, index);
}
public static void lua_rawset(LuaCore.lua_State luaState, int index)
public static void lua_rawset (LuaCore.lua_State luaState, int index)
{
LuaCore.lua_rawset(luaState, index);
LuaCore.lua_rawset (luaState, index);
}
public static void lua_setmetatable(LuaCore.lua_State luaState, int objIndex)
public static void lua_setmetatable (LuaCore.lua_State luaState, int objIndex)
{
LuaCore.lua_setmetatable(luaState, objIndex);
LuaCore.lua_setmetatable (luaState, objIndex);
}
public static int lua_getmetatable(LuaCore.lua_State luaState, int objIndex)
public static int lua_getmetatable (LuaCore.lua_State luaState, int objIndex)
{
return LuaCore.lua_getmetatable(luaState, objIndex);
return LuaCore.lua_getmetatable (luaState, objIndex);
}
public static int lua_equal(LuaCore.lua_State luaState, int index1, int index2)
public static int lua_equal (LuaCore.lua_State luaState, int index1, int index2)
{
return LuaCore.lua_equal(luaState, index1, index2);
return LuaCore.lua_equal (luaState, index1, index2);
}
public static void lua_pushvalue(LuaCore.lua_State luaState, int index)
public static void lua_pushvalue (LuaCore.lua_State luaState, int index)
{
LuaCore.lua_pushvalue(luaState, index);
LuaCore.lua_pushvalue (luaState, index);
}
public static void lua_replace(LuaCore.lua_State luaState, int index)
public static void lua_replace (LuaCore.lua_State luaState, int index)
{
LuaCore.lua_replace(luaState, index);
LuaCore.lua_replace (luaState, index);
}
public static int lua_gettop(LuaCore.lua_State luaState)
public static int lua_gettop (LuaCore.lua_State luaState)
{
return LuaCore.lua_gettop(luaState);
return LuaCore.lua_gettop (luaState);
}
public static LuaTypes lua_type(LuaCore.lua_State luaState, int index)
public static LuaTypes lua_type (LuaCore.lua_State luaState, int index)
{
return (LuaTypes) LuaCore.lua_type(luaState, index);
return (LuaTypes)LuaCore.lua_type (luaState, index);
}
public static bool lua_isnil(LuaCore.lua_State luaState, int index)
public static bool lua_isnil (LuaCore.lua_State luaState, int index)
{
return lua_type(luaState, index) == LuaTypes.Nil;
return lua_type (luaState, index) == LuaTypes.Nil;
}
public static bool lua_isnumber(LuaCore.lua_State luaState, int index)
public static bool lua_isnumber (LuaCore.lua_State luaState, int index)
{
return lua_type(luaState, index) == LuaTypes.Number;
return lua_type (luaState, index) == LuaTypes.Number;
}
public static bool lua_isboolean(LuaCore.lua_State luaState, int index)
public static bool lua_isboolean (LuaCore.lua_State luaState, int index)
{
return lua_type(luaState, index) == LuaTypes.Boolean;
return lua_type (luaState, index) == LuaTypes.Boolean;
}
public static int luaL_ref(LuaCore.lua_State luaState, int registryIndex)
public static int luaL_ref (LuaCore.lua_State luaState, int registryIndex)
{
return LuaCore.luaL_ref(luaState, registryIndex);
return LuaCore.luaL_ref (luaState, registryIndex);
}
public static int lua_ref(LuaCore.lua_State luaState, int lockRef)
public static int lua_ref (LuaCore.lua_State luaState, int lockRef)
{
return lockRef != 0 ? luaL_ref(luaState, (int)LuaIndexes.Registry) : 0;
return lockRef != 0 ? luaL_ref (luaState, (int)LuaIndexes.Registry) : 0;
}
public static void lua_rawgeti(LuaCore.lua_State luaState, int tableIndex, int index)
public static void lua_rawgeti (LuaCore.lua_State luaState, int tableIndex, int index)
{
LuaCore.lua_rawgeti(luaState, tableIndex, index);
LuaCore.lua_rawgeti (luaState, tableIndex, index);
}
public static void lua_rawseti(LuaCore.lua_State luaState, int tableIndex, int index)
public static void lua_rawseti (LuaCore.lua_State luaState, int tableIndex, int index)
{
LuaCore.lua_rawseti(luaState, tableIndex, index);
LuaCore.lua_rawseti (luaState, tableIndex, index);
}
public static object lua_newuserdata(LuaCore.lua_State luaState, int size)
public static object lua_newuserdata (LuaCore.lua_State luaState, int size)
{
return LuaCore.lua_newuserdata(luaState, (uint)size);
return LuaCore.lua_newuserdata (luaState, (uint)size);
}
public static object lua_touserdata(LuaCore.lua_State luaState, int index)
public static object lua_touserdata (LuaCore.lua_State luaState, int index)
{
return LuaCore.lua_touserdata(luaState, index);
return LuaCore.lua_touserdata (luaState, index);
}
public static void lua_getref(LuaCore.lua_State luaState, int reference)
public static void lua_getref (LuaCore.lua_State luaState, int reference)
{
lua_rawgeti(luaState, (int)LuaIndexes.Registry, reference);
lua_rawgeti (luaState, (int)LuaIndexes.Registry, reference);
}
public static void lua_unref(LuaCore.lua_State luaState, int reference)
public static void lua_unref (LuaCore.lua_State luaState, int reference)
{
LuaCore.luaL_unref(luaState, (int)LuaIndexes.Registry, reference);
LuaCore.luaL_unref (luaState, (int)LuaIndexes.Registry, reference);
}
public static bool lua_isstring(LuaCore.lua_State luaState, int index)
public static bool lua_isstring (LuaCore.lua_State luaState, int index)
{
return LuaCore.lua_isstring(luaState, index) != 0;
return LuaCore.lua_isstring (luaState, index) != 0;
}
public static bool lua_iscfunction(LuaCore.lua_State luaState, int index)
public static bool lua_iscfunction (LuaCore.lua_State luaState, int index)
{
return LuaCore.lua_iscfunction(luaState, index);
return LuaCore.lua_iscfunction (luaState, index);
}
public static void lua_pushnil(LuaCore.lua_State luaState)
public static void lua_pushnil (LuaCore.lua_State luaState)
{
LuaCore.lua_pushnil(luaState);
LuaCore.lua_pushnil (luaState);
}
public static void lua_call(LuaCore.lua_State luaState, int nArgs, int nResults)
public static void lua_call (LuaCore.lua_State luaState, int nArgs, int nResults)
{
LuaCore.lua_call(luaState, nArgs, nResults);
LuaCore.lua_call (luaState, nArgs, nResults);
}
public static int lua_pcall(LuaCore.lua_State luaState, int nArgs, int nResults, int errfunc)
public static int lua_pcall (LuaCore.lua_State luaState, int nArgs, int nResults, int errfunc)
{
return LuaCore.lua_pcall(luaState, nArgs, nResults, errfunc);
return LuaCore.lua_pcall (luaState, nArgs, nResults, errfunc);
}
public static LuaCore.lua_CFunction lua_tocfunction(LuaCore.lua_State luaState, int index)
public static LuaCore.lua_CFunction lua_tocfunction (LuaCore.lua_State luaState, int index)
{
return LuaCore.lua_tocfunction(luaState, index);
return LuaCore.lua_tocfunction (luaState, index);
}
public static double lua_tonumber(LuaCore.lua_State luaState, int index)
public static double lua_tonumber (LuaCore.lua_State luaState, int index)
{
return LuaCore.lua_tonumber(luaState, index);
return LuaCore.lua_tonumber (luaState, index);
}
public static bool lua_toboolean(LuaCore.lua_State luaState, int index)
public static bool lua_toboolean (LuaCore.lua_State luaState, int index)
{
return LuaCore.lua_toboolean(luaState, index) != 0;
return LuaCore.lua_toboolean (luaState, index) != 0;
}
public static string lua_tostring(LuaCore.lua_State luaState, int index)
public static string lua_tostring (LuaCore.lua_State luaState, int index)
{
#if true
// FIXME use the same format string as lua i.e. LUA_NUMBER_FMT
var t = lua_type(luaState, index);
var t = lua_type (luaState, index);
if(t == LuaTypes.Number)
return string.Format("{0}", lua_tonumber(luaState, index));
else if(t == LuaTypes.String)
{
if (t == LuaTypes.Number)
return string.Format ("{0}", lua_tonumber (luaState, index));
else if (t == LuaTypes.String) {
uint strlen;
return LuaCore.lua_tolstring(luaState, index, out strlen).ToString();
}
else if(t == LuaTypes.Nil)
return LuaCore.lua_tolstring (luaState, index, out strlen).ToString ();
} else if (t == LuaTypes.Nil)
return null; // treat lua nulls to as C# nulls
else
return "0"; // Because luaV_tostring does this
......@@ -342,116 +331,114 @@ namespace LuaInterface
#endif
}
public static void lua_atpanic(LuaCore.lua_State luaState, LuaCore.lua_CFunction panicf)
public static void lua_atpanic (LuaCore.lua_State luaState, LuaCore.lua_CFunction panicf)
{
LuaCore.lua_atpanic(luaState, (LuaCore.lua_CFunction)panicf);
LuaCore.lua_atpanic (luaState, (LuaCore.lua_CFunction)panicf);
}
public static void lua_pushstdcallcfunction(LuaCore.lua_State luaState, LuaCore.lua_CFunction function)
public static void lua_pushstdcallcfunction (LuaCore.lua_State luaState, LuaCore.lua_CFunction function)
{
LuaCore.lua_pushcfunction(luaState, function);
LuaCore.lua_pushcfunction (luaState, function);
}
public static void lua_pushnumber(LuaCore.lua_State luaState, double number)
public static void lua_pushnumber (LuaCore.lua_State luaState, double number)
{
LuaCore.lua_pushnumber(luaState, number);
LuaCore.lua_pushnumber (luaState, number);
}
public static void lua_pushboolean(LuaCore.lua_State luaState, bool value)
public static void lua_pushboolean (LuaCore.lua_State luaState, bool value)
{
LuaCore.lua_pushboolean(luaState, value ? 1 : 0);
LuaCore.lua_pushboolean (luaState, value ? 1 : 0);
}
public static void lua_pushstring(LuaCore.lua_State luaState, string str)
public static void lua_pushstring (LuaCore.lua_State luaState, string str)
{
LuaCore.lua_pushstring(luaState, str);
LuaCore.lua_pushstring (luaState, str);
}
public static int luaL_newmetatable(LuaCore.lua_State luaState, string meta)
public static int luaL_newmetatable (LuaCore.lua_State luaState, string meta)
{
return LuaCore.luaL_newmetatable(luaState, meta);
return LuaCore.luaL_newmetatable (luaState, meta);
}
// steffenj: BEGIN Lua 5.1.1 API change (luaL_getmetatable is now a macro using lua_getfield)
public static void lua_getfield(LuaCore.lua_State luaState, int stackPos, string meta)
public static void lua_getfield (LuaCore.lua_State luaState, int stackPos, string meta)
{
LuaCore.lua_getfield(luaState, stackPos, meta);
LuaCore.lua_getfield (luaState, stackPos, meta);
}
public static void luaL_getmetatable(LuaCore.lua_State luaState, string meta)
public static void luaL_getmetatable (LuaCore.lua_State luaState, string meta)
{
lua_getfield(luaState, (int)LuaIndexes.Registry, meta);
lua_getfield (luaState, (int)LuaIndexes.Registry, meta);
}
public static object luaL_checkudata(LuaCore.lua_State luaState, int stackPos, string meta)
public static object luaL_checkudata (LuaCore.lua_State luaState, int stackPos, string meta)
{
return LuaCore.luaL_checkudata(luaState, stackPos, meta);
return LuaCore.luaL_checkudata (luaState, stackPos, meta);
}
public static bool luaL_getmetafield(LuaCore.lua_State luaState, int stackPos, string field)
public static bool luaL_getmetafield (LuaCore.lua_State luaState, int stackPos, string field)
{
return LuaCore.luaL_getmetafield(luaState, stackPos, field) != 0;
return LuaCore.luaL_getmetafield (luaState, stackPos, field) != 0;
}
public static int luaL_loadbuffer(LuaCore.lua_State luaState, string buff, string name)
public static int luaL_loadbuffer (LuaCore.lua_State luaState, string buff, string name)
{
return LuaCore.luaL_loadbuffer(luaState, buff, (uint)buff.Length, name);
return LuaCore.luaL_loadbuffer (luaState, buff, (uint)buff.Length, name);
}
public static int luaL_loadfile(LuaCore.lua_State luaState, string filename)
public static int luaL_loadfile (LuaCore.lua_State luaState, string filename)
{
return LuaCore.luaL_loadfile(luaState, filename);
return LuaCore.luaL_loadfile (luaState, filename);
}
public static void lua_error(LuaCore.lua_State luaState)
public static void lua_error (LuaCore.lua_State luaState)
{
LuaCore.lua_error(luaState);
LuaCore.lua_error (luaState);
}
public static bool lua_checkstack(LuaCore.lua_State luaState,int extra)
public static bool lua_checkstack (LuaCore.lua_State luaState, int extra)
{
return LuaCore.lua_checkstack(luaState, extra) != 0;
return LuaCore.lua_checkstack (luaState, extra) != 0;
}
public static int lua_next(LuaCore.lua_State luaState,int index)
public static int lua_next (LuaCore.lua_State luaState, int index)
{
return LuaCore.lua_next(luaState, index);
return LuaCore.lua_next (luaState, index);
}
public static void lua_pushlightuserdata(LuaCore.lua_State luaState, object udata)
public static void lua_pushlightuserdata (LuaCore.lua_State luaState, object udata)
{
LuaCore.lua_pushlightuserdata(luaState, udata);
LuaCore.lua_pushlightuserdata (luaState, udata);
}
public static int luanet_rawnetobj(LuaCore.lua_State luaState,int obj)
public static int luanet_rawnetobj (LuaCore.lua_State luaState, int obj)
{
byte[] bytes = lua_touserdata(luaState, obj) as byte[];
return fourBytesToInt(bytes);
byte[] bytes = lua_touserdata (luaState, obj) as byte[];
return fourBytesToInt (bytes);
}
// Starting with 5.1 the auxlib version of checkudata throws an exception if the type isn't right
// Instead, we want to run our own version that checks the type and just returns null for failure
private static object checkudata_raw(LuaCore.lua_State L, int ud, string tname)
private static object checkudata_raw (LuaCore.lua_State L, int ud, string tname)
{
object p = LuaCore.lua_touserdata(L, ud);
object p = LuaCore.lua_touserdata (L, ud);
if(p != null)
{
if (p != null) {
/* value is a userdata? */
if(LuaCore.lua_getmetatable(L, ud) != 0)
{
if (LuaCore.lua_getmetatable (L, ud) != 0) {
bool isEqual;
/* does it have a metatable? */
LuaCore.lua_getfield(L, (int)LuaIndexes.Registry, tname); /* get correct metatable */
LuaCore.lua_getfield (L, (int)LuaIndexes.Registry, tname); /* get correct metatable */
isEqual = LuaCore.lua_rawequal(L, -1, -2) != 0;
isEqual = LuaCore.lua_rawequal (L, -1, -2) != 0;
// NASTY - we need our own version of the lua_pop macro
// lua_pop(L, 2); /* remove both metatables */
LuaCore.lua_settop(L, -(2) - 1);
LuaCore.lua_settop (L, -(2) - 1);
if(isEqual) /* does it have the correct mt? */
if (isEqual) /* does it have the correct mt? */
return p;
}
}
......@@ -459,79 +446,76 @@ namespace LuaInterface
return null;
}
public static int luanet_checkudata(LuaCore.lua_State luaState, int ud, string tname)
public static int luanet_checkudata (LuaCore.lua_State luaState, int ud, string tname)
{
object udata = checkudata_raw(luaState, ud, tname);
return !udata.IsNull() ? fourBytesToInt(udata as byte[]) : -1;
object udata = checkudata_raw (luaState, ud, tname);
return !udata.IsNull () ? fourBytesToInt (udata as byte[]) : -1;
}
public static bool luaL_checkmetatable(LuaCore.lua_State luaState,int index)
public static bool luaL_checkmetatable (LuaCore.lua_State luaState, int index)
{
bool retVal = false;
if(lua_getmetatable(luaState, index) != 0)
{
lua_pushlightuserdata(luaState, tag);
lua_rawget(luaState, -2);
retVal = !lua_isnil(luaState, -1);
lua_settop(luaState, -3);
if (lua_getmetatable (luaState, index) != 0) {
lua_pushlightuserdata (luaState, tag);
lua_rawget (luaState, -2);
retVal = !lua_isnil (luaState, -1);
lua_settop (luaState, -3);
}
return retVal;
}
public static object luanet_gettag()
public static object luanet_gettag ()
{
return tag;
}
public static void luanet_newudata(LuaCore.lua_State luaState,int val)
public static void luanet_newudata (LuaCore.lua_State luaState, int val)
{
var userdata = lua_newuserdata(luaState, sizeof(int)) as byte[];
intToFourBytes(val, userdata);
var userdata = lua_newuserdata (luaState, sizeof(int)) as byte[];
intToFourBytes (val, userdata);
}
public static int luanet_tonetobject(LuaCore.lua_State luaState,int index)
public static int luanet_tonetobject (LuaCore.lua_State luaState, int index)
{
byte[] udata;
if(lua_type(luaState, index) == LuaTypes.UserData)
{
if(luaL_checkmetatable(luaState, index))
{
udata=lua_touserdata(luaState, index) as byte[];
if(!udata.IsNull())
return fourBytesToInt(udata);
if (lua_type (luaState, index) == LuaTypes.UserData) {
if (luaL_checkmetatable (luaState, index)) {
udata = lua_touserdata (luaState, index) as byte[];
if (!udata.IsNull ())
return fourBytesToInt (udata);
}
udata = checkudata_raw(luaState, index, "luaNet_class") as byte[];
if(!udata.IsNull())
return fourBytesToInt(udata);
udata = checkudata_raw (luaState, index, "luaNet_class") as byte[];
if (!udata.IsNull ())
return fourBytesToInt (udata);
udata = checkudata_raw(luaState, index, "luaNet_searchbase") as byte[];
if(!udata.IsNull())
return fourBytesToInt(udata);
udata = checkudata_raw (luaState, index, "luaNet_searchbase") as byte[];
if (!udata.IsNull ())
return fourBytesToInt (udata);
udata = checkudata_raw(luaState, index, "luaNet_function") as byte[];
if(!udata.IsNull())
return fourBytesToInt(udata);
udata = checkudata_raw (luaState, index, "luaNet_function") as byte[];
if (!udata.IsNull ())
return fourBytesToInt (udata);
}
return -1;
}
private static int fourBytesToInt(byte[] bytes)
private static int fourBytesToInt (byte[] bytes)
{
return bytes[0] + (bytes[1] << 8) + (bytes[2] << 16) + (bytes[3] << 24);
return bytes [0] + (bytes [1] << 8) + (bytes [2] << 16) + (bytes [3] << 24);
}
private static void intToFourBytes(int val, byte[] bytes)
private static void intToFourBytes (int val, byte[] bytes)
{
// gfoot: is this really a good idea?
bytes[0] = (byte)val;
bytes[1] = (byte)(val >> 8);
bytes[2] = (byte)(val >> 16);
bytes[3] = (byte)(val >> 24);
bytes [0] = (byte)val;
bytes [1] = (byte)(val >> 8);
bytes [2] = (byte)(val >> 16);
bytes [3] = (byte)(val >> 24);
}
}
}
\ No newline at end of file
......@@ -23,7 +23,6 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.IO;
using System.Runtime.InteropServices;
......
......@@ -23,7 +23,6 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
namespace LuaInterface
......
......@@ -22,7 +22,6 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Reflection;
using System.Diagnostics.CodeAnalysis;
......@@ -38,24 +37,22 @@ namespace LuaInterface
/// </summary>
/// <param name="lua">The Lua VM to add the methods to</param>
/// <param name="o">The object to get the methods from</param>
public static void TaggedInstanceMethods(Lua lua, object o)
public static void TaggedInstanceMethods (Lua lua, object o)
{
#region Sanity checks
if(lua.IsNull())
throw new ArgumentNullException("lua");
if (lua.IsNull ())
throw new ArgumentNullException ("lua");
if(o.IsNull())
throw new ArgumentNullException("o");
if (o.IsNull ())
throw new ArgumentNullException ("o");
#endregion
foreach(var method in o.GetType().GetMethods(BindingFlags.Instance | BindingFlags.Public))
{
foreach(LuaGlobalAttribute attribute in method.GetCustomAttributes(typeof(LuaGlobalAttribute), true))
{
if(string.IsNullOrEmpty(attribute.Name))
lua.RegisterFunction(method.Name, o, method); // CLR name
foreach (var method in o.GetType().GetMethods(BindingFlags.Instance | BindingFlags.Public)) {
foreach (LuaGlobalAttribute attribute in method.GetCustomAttributes(typeof(LuaGlobalAttribute), true)) {
if (string.IsNullOrEmpty (attribute.Name))
lua.RegisterFunction (method.Name, o, method); // CLR name
else
lua.RegisterFunction(attribute.Name, o, method); // Custom name
lua.RegisterFunction (attribute.Name, o, method); // Custom name
}
}
}
......@@ -67,27 +64,25 @@ namespace LuaInterface
/// </summary>
/// <param name="lua">The Lua VM to add the methods to</param>
/// <param name="type">The class type to get the methods from</param>
public static void TaggedStaticMethods(Lua lua, Type type)
public static void TaggedStaticMethods (Lua lua, Type type)
{
#region Sanity checks
if(lua.IsNull())
throw new ArgumentNullException("lua");
if (lua.IsNull ())
throw new ArgumentNullException ("lua");
if(type.IsNull())
throw new ArgumentNullException("type");
if (type.IsNull ())
throw new ArgumentNullException ("type");
if(!type.IsClass)
throw new ArgumentException("The type must be a class!", "type");
if (!type.IsClass)
throw new ArgumentException ("The type must be a class!", "type");
#endregion
foreach(var method in type.GetMethods(BindingFlags.Static | BindingFlags.Public))
{
foreach(LuaGlobalAttribute attribute in method.GetCustomAttributes(typeof(LuaGlobalAttribute), false))
{
if(string.IsNullOrEmpty(attribute.Name))
lua.RegisterFunction(method.Name, null, method); // CLR name
foreach (var method in type.GetMethods(BindingFlags.Static | BindingFlags.Public)) {
foreach (LuaGlobalAttribute attribute in method.GetCustomAttributes(typeof(LuaGlobalAttribute), false)) {
if (string.IsNullOrEmpty (attribute.Name))
lua.RegisterFunction (method.Name, null, method); // CLR name
else
lua.RegisterFunction(attribute.Name, null, method); // Custom name
lua.RegisterFunction (attribute.Name, null, method); // Custom name
}
}
}
......@@ -100,26 +95,25 @@ namespace LuaInterface
/// <typeparam name="T">The enum type to register</typeparam>
/// <param name="lua">The Lua VM to add the enum to</param>
[SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter", Justification = "The type parameter is used to select an enum type")]
public static void Enumeration<T>(Lua lua)
public static void Enumeration<T> (Lua lua)
{
#region Sanity checks
if(lua.IsNull())
throw new ArgumentNullException("lua");
if (lua.IsNull ())
throw new ArgumentNullException ("lua");
#endregion
var type = typeof(T);
if(!type.IsEnum)
throw new ArgumentException("The type must be an enumeration!");
if (!type.IsEnum)
throw new ArgumentException ("The type must be an enumeration!");
string[] names = Enum.GetNames(type);
var values = (T[])Enum.GetValues(type);
lua.NewTable(type.Name);
string[] names = Enum.GetNames (type);
var values = (T[])Enum.GetValues (type);
lua.NewTable (type.Name);
for(int i = 0; i < names.Length; i++)
{
string path = type.Name + "." + names[i];
lua[path] = values[i];
for (int i = 0; i < names.Length; i++) {
string path = type.Name + "." + names [i];
lua [path] = values [i];
}
}
#endregion
......
......@@ -22,7 +22,6 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Text;
using System.Collections;
......@@ -40,7 +39,7 @@ namespace LuaInterface
*/
public class LuaTable : LuaBase
{
public LuaTable(int reference, Lua interpreter)
public LuaTable (int reference, Lua interpreter)
{
_Reference = reference;
_Interpreter = interpreter;
......@@ -49,63 +48,55 @@ namespace LuaInterface
/*
* Indexer for string fields of the table
*/
public object this[string field]
{
get
{
return _Interpreter.getObject(_Reference, field);
public object this [string field] {
get {
return _Interpreter.getObject (_Reference, field);
}
set
{
_Interpreter.setObject(_Reference, field, value);
set {
_Interpreter.setObject (_Reference, field, value);
}
}
/*
* Indexer for numeric fields of the table
*/
public object this[object field]
{
get
{
return _Interpreter.getObject(_Reference, field);
public object this [object field] {
get {
return _Interpreter.getObject (_Reference, field);
}
set
{
_Interpreter.setObject(_Reference, field, value);
set {
_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
{
get { return _Interpreter.GetTableDict(this).Keys; }
public ICollection Keys {
get { return _Interpreter.GetTableDict (this).Keys; }
}
public ICollection Values
{
get { return _Interpreter.GetTableDict(this).Values; }
public ICollection Values {
get { return _Interpreter.GetTableDict (this).Values; }
}
/*
* Gets an string fields of a table ignoring its metatable,
* if it exists
*/
internal object rawget(string field)
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)
return new LuaFunction((LuaCore.lua_CFunction)obj, _Interpreter);
if (obj is LuaCore.lua_CFunction)
return new LuaFunction ((LuaCore.lua_CFunction)obj, _Interpreter);
else
return obj;
}
......@@ -113,12 +104,12 @@ namespace LuaInterface
/*
* 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";
}
......
......@@ -22,7 +22,6 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Text;
using System.Collections.Generic;
......@@ -33,7 +32,7 @@ namespace LuaInterface
public class LuaUserData : LuaBase
{
public LuaUserData(int reference, Lua interpreter)
public LuaUserData (int reference, Lua interpreter)
{
_Reference = reference;
_Interpreter = interpreter;
......@@ -42,30 +41,24 @@ namespace LuaInterface
/*
* Indexer for string fields of the userdata
*/
public object this[string field]
{
get
{
return _Interpreter.getObject(_Reference, field);
public object this [string field] {
get {
return _Interpreter.getObject (_Reference, field);
}
set
{
_Interpreter.setObject(_Reference, field, value);
set {
_Interpreter.setObject (_Reference, field, value);
}
}
/*
* Indexer for numeric fields of the userdata
*/
public object this[object field]
{
get
{
return _Interpreter.getObject(_Reference, field);
public object this [object field] {
get {
return _Interpreter.getObject (_Reference, field);
}
set
{
_Interpreter.setObject(_Reference, field, value);
set {
_Interpreter.setObject (_Reference, field, value);
}
}
......@@ -73,20 +66,20 @@ namespace LuaInterface
* Calls the userdata and returns its return values inside
* 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
*/
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";
}
......
......@@ -22,7 +22,6 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.IO;
using System.Collections;
......@@ -48,7 +47,7 @@ namespace LuaInterface
{
internal LuaCore.lua_CFunction gcFunction, indexFunction, newindexFunction, baseIndexFunction,
classIndexFunction, classNewindexFunction, execDelegateFunction, callConstructorFunction, toStringFunction;
private Hashtable memberCache = new Hashtable();
private Hashtable memberCache = new Hashtable ();
private ObjectTranslator translator;
/*
......@@ -70,41 +69,40 @@ namespace LuaInterface
"end \n" +
"return index ";
public MetaFunctions(ObjectTranslator translator)
public MetaFunctions (ObjectTranslator translator)
{
this.translator = translator;
gcFunction = new LuaCore.lua_CFunction(this.collectObject);
toStringFunction = new LuaCore.lua_CFunction(this.toString);
indexFunction = new LuaCore.lua_CFunction(this.getMethod);
newindexFunction = new LuaCore.lua_CFunction(this.setFieldOrProperty);
baseIndexFunction = new LuaCore.lua_CFunction(this.getBaseMethod);
callConstructorFunction = new LuaCore.lua_CFunction(this.callConstructor);
classIndexFunction = new LuaCore.lua_CFunction(this.getClassMethod);
classNewindexFunction = new LuaCore.lua_CFunction(this.setClassFieldOrProperty);
execDelegateFunction = new LuaCore.lua_CFunction(this.runFunctionDelegate);
gcFunction = new LuaCore.lua_CFunction (this.collectObject);
toStringFunction = new LuaCore.lua_CFunction (this.toString);
indexFunction = new LuaCore.lua_CFunction (this.getMethod);
newindexFunction = new LuaCore.lua_CFunction (this.setFieldOrProperty);
baseIndexFunction = new LuaCore.lua_CFunction (this.getBaseMethod);
callConstructorFunction = new LuaCore.lua_CFunction (this.callConstructor);
classIndexFunction = new LuaCore.lua_CFunction (this.getClassMethod);
classNewindexFunction = new LuaCore.lua_CFunction (this.setClassFieldOrProperty);
execDelegateFunction = new LuaCore.lua_CFunction (this.runFunctionDelegate);
}
/*
* __call metafunction of CLR delegates, retrieves and calls the delegate.
*/
private int runFunctionDelegate(LuaCore.lua_State luaState)
private int runFunctionDelegate (LuaCore.lua_State luaState)
{
LuaCore.lua_CFunction func = (LuaCore.lua_CFunction)translator.getRawNetObject(luaState, 1);
LuaLib.lua_remove(luaState, 1);
return func(luaState);
LuaCore.lua_CFunction func = (LuaCore.lua_CFunction)translator.getRawNetObject (luaState, 1);
LuaLib.lua_remove (luaState, 1);
return func (luaState);
}
/*
* __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)
translator.collectObject(udata);
else
{
if (udata != -1)
translator.collectObject (udata);
else {
// Debug.WriteLine("not found: " + udata);
}
......@@ -114,14 +112,14 @@ namespace LuaInterface
/*
* __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())
translator.push(luaState, obj.ToString() + ": " + obj.GetHashCode());
if (!obj.IsNull ())
translator.push (luaState, obj.ToString () + ": " + obj.GetHashCode ());
else
LuaLib.lua_pushnil(luaState);
LuaLib.lua_pushnil (luaState);
return 1;
}
......@@ -131,25 +129,23 @@ namespace LuaInterface
/// Debug tool to dump the lua stack
/// </summary>
/// 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);
Debug.WriteLine("lua stack depth: " + depth);
int depth = LuaLib.lua_gettop (luaState);
Debug.WriteLine ("lua stack depth: " + depth);
for(int i = 1; i <= depth; i++)
{
var type = LuaLib.lua_type(luaState, i);
for (int i = 1; i <= depth; 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
string typestr = (type == LuaTypes.Table) ? "table" : LuaLib.lua_typename(luaState, type);
string strrep = LuaLib.lua_tostring(luaState, i).ToString();
string typestr = (type == LuaTypes.Table) ? "table" : LuaLib.lua_typename (luaState, type);
string strrep = LuaLib.lua_tostring (luaState, i).ToString ();
if(type == LuaTypes.UserData)
{
object obj = translator.getRawNetObject(luaState, i);
strrep = obj.ToString();
if (type == LuaTypes.UserData) {
object obj = translator.getRawNetObject (luaState, i);
strrep = obj.ToString ();
}
Debug.Print("{0}: ({1}) {2}", i, typestr, strrep);
Debug.Print ("{0}: ({1}) {2}", i, typestr, strrep);
}
}
......@@ -160,105 +156,82 @@ namespace LuaInterface
* either the value of the member or a delegate to call it.
* If the member does not exist returns nil.
*/
private int getMethod(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())
{
translator.throwError(luaState, "trying to index an invalid object reference");
LuaLib.lua_pushnil(luaState);
if (obj.IsNull ()) {
translator.throwError (luaState, "trying to index an invalid object reference");
LuaLib.lua_pushnil (luaState);
return 1;
}
object index = translator.getObject(luaState, 2);
object index = translator.getObject (luaState, 2);
//var indexType = index.GetType();
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.
// CP: This will fail when using indexers and attempting to get a value with the same name as a property of the object,
// ie: xmlelement['item'] <- item is a property of xmlelement
try
{
if(!methodName.IsNull() && isMemberPresent(objType, methodName))
return getMember(luaState, objType, obj, methodName, BindingFlags.Instance | BindingFlags.IgnoreCase);
}
catch
{
try {
if (!methodName.IsNull () && isMemberPresent (objType, methodName))
return getMember (luaState, objType, obj, methodName, BindingFlags.Instance | BindingFlags.IgnoreCase);
} catch {
}
// Try to access by array if the type is right and index is an int (lua numbers always come across as double)
if(objType.IsArray && index is double)
{
if (objType.IsArray && index is double) {
int intIndex = (int)((double)index);
if(objType.UnderlyingSystemType == typeof(float[]))
{
if (objType.UnderlyingSystemType == typeof(float[])) {
float[] arr = ((float[])obj);
translator.push(luaState, arr[intIndex]);
}
else if(objType.UnderlyingSystemType == typeof(double[]))
{
translator.push (luaState, arr [intIndex]);
} else if (objType.UnderlyingSystemType == typeof(double[])) {
double[] arr = ((double[])obj);
translator.push(luaState, arr[intIndex]);
}
else if(objType.UnderlyingSystemType == typeof(int[]))
{
translator.push (luaState, arr [intIndex]);
} else if (objType.UnderlyingSystemType == typeof(int[])) {
int[] arr = ((int[])obj);
translator.push(luaState, arr[intIndex]);
}
else
{
translator.push (luaState, arr [intIndex]);
} else {
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
//MethodInfo getter = objType.GetMethod("get_Item");
var methods = objType.GetMethods();
var methods = objType.GetMethods ();
foreach(var mInfo in methods)
{
if(mInfo.Name == "get_Item")
{
foreach (var mInfo in methods) {
if (mInfo.Name == "get_Item") {
//check if the signature matches the input
if(mInfo.GetParameters().Length == 1)
{
if (mInfo.GetParameters ().Length == 1) {
var getter = mInfo;
var actualParms = (!getter.IsNull()) ? getter.GetParameters() : null;
var actualParms = (!getter.IsNull ()) ? getter.GetParameters () : null;
if(actualParms.IsNull() || actualParms.Length != 1)
{
translator.throwError(luaState, "method not found (or no indexer): " + index);
LuaLib.lua_pushnil(luaState);
}
else
{
if (actualParms.IsNull () || actualParms.Length != 1) {
translator.throwError (luaState, "method not found (or no indexer): " + index);
LuaLib.lua_pushnil (luaState);
} else {
// 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];
// Just call the indexer - if out of bounds an exception will happen
args[0] = index;
args [0] = index;
try
{
object result = getter.Invoke(obj, args);
translator.push(luaState, result);
}
catch(TargetInvocationException e)
{
try {
object result = getter.Invoke (obj, args);
translator.push (luaState, result);
} catch (TargetInvocationException e) {
// Provide a more readable description for the common case of key not found
if(e.InnerException is KeyNotFoundException)
translator.throwError(luaState, "key '" + index + "' not found ");
if (e.InnerException is KeyNotFoundException)
translator.throwError (luaState, "key '" + index + "' not found ");
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);
}
}
}
......@@ -266,7 +239,7 @@ namespace LuaInterface
}
}
LuaLib.lua_pushboolean(luaState, false);
LuaLib.lua_pushboolean (luaState, false);
return 2;
}
......@@ -274,37 +247,34 @@ namespace LuaInterface
* __index metafunction of base classes (the base field of Lua tables).
* Adds a prefix to the method name to call the base version of the method.
*/
private int getBaseMethod(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())
{
translator.throwError(luaState, "trying to index an invalid object reference");
LuaLib.lua_pushnil(luaState);
LuaLib.lua_pushboolean(luaState, false);
if (obj.IsNull ()) {
translator.throwError (luaState, "trying to index an invalid object reference");
LuaLib.lua_pushnil (luaState);
LuaLib.lua_pushboolean (luaState, false);
return 2;
}
string methodName = LuaLib.lua_tostring(luaState, 2).ToString();
string methodName = LuaLib.lua_tostring (luaState, 2).ToString ();
if(methodName.IsNull())
{
LuaLib.lua_pushnil(luaState);
LuaLib.lua_pushboolean(luaState, false);
if (methodName.IsNull ()) {
LuaLib.lua_pushnil (luaState);
LuaLib.lua_pushboolean (luaState, false);
return 2;
}
getMember(luaState, obj.GetType(), obj, "__luaInterface_base_" + methodName, BindingFlags.Instance | BindingFlags.IgnoreCase);
LuaLib.lua_settop(luaState, -2);
getMember (luaState, obj.GetType (), obj, "__luaInterface_base_" + methodName, BindingFlags.Instance | BindingFlags.IgnoreCase);
LuaLib.lua_settop (luaState, -2);
if(LuaLib.lua_type(luaState, -1) == LuaTypes.Nil)
{
LuaLib.lua_settop(luaState, -2);
return getMember(luaState, obj.GetType(), obj, methodName, BindingFlags.Instance | BindingFlags.IgnoreCase);
if (LuaLib.lua_type (luaState, -1) == LuaTypes.Nil) {
LuaLib.lua_settop (luaState, -2);
return getMember (luaState, obj.GetType (), obj, methodName, BindingFlags.Instance | BindingFlags.IgnoreCase);
}
LuaLib.lua_pushboolean(luaState, false);
LuaLib.lua_pushboolean (luaState, false);
return 2;
}
......@@ -314,15 +284,15 @@ namespace LuaInterface
/// <param name="objType"></param>
/// <param name="methodName"></param>
/// <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;
//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);
}
......@@ -332,103 +302,81 @@ namespace LuaInterface
* Uses reflection to find members, and stores the reflected MemberInfo object in
* a cache (indexed by the type of the object and the name of the member).
*/
private int getMember(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;
MemberInfo member = null;
object cachedMember = checkMemberCache(memberCache, objType, methodName);
object cachedMember = checkMemberCache (memberCache, objType, methodName);
//object cachedMember=null;
if(cachedMember is LuaCore.lua_CFunction)
{
translator.pushFunction(luaState, (LuaCore.lua_CFunction)cachedMember);
translator.push(luaState, true);
if (cachedMember is LuaCore.lua_CFunction) {
translator.pushFunction (luaState, (LuaCore.lua_CFunction)cachedMember);
translator.push (luaState, true);
return 2;
}
else if(!cachedMember.IsNull())
} else if (!cachedMember.IsNull ())
member = (MemberInfo)cachedMember;
else
{
else {
//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)
member = members[0];
else
{
if (members.Length > 0)
member = members [0];
else {
// 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
//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)
{
member = members[0];
if (members.Length > 0) {
member = members [0];
implicitStatic = true;
}
}
}
if(!member.IsNull())
{
if(member.MemberType == MemberTypes.Field)
{
if (!member.IsNull ()) {
if (member.MemberType == MemberTypes.Field) {
var field = (FieldInfo)member;
if(cachedMember.IsNull())
setMemberCache(memberCache, objType, methodName, member);
if (cachedMember.IsNull ())
setMemberCache (memberCache, objType, methodName, member);
try
{
translator.push(luaState, field.GetValue(obj));
try {
translator.push (luaState, field.GetValue (obj));
} catch {
LuaLib.lua_pushnil (luaState);
}
catch
{
LuaLib.lua_pushnil(luaState);
}
}
else if(member.MemberType == MemberTypes.Property)
{
} else if (member.MemberType == MemberTypes.Property) {
var property = (PropertyInfo)member;
if(cachedMember.IsNull())
setMemberCache(memberCache, objType, methodName, member);
if (cachedMember.IsNull ())
setMemberCache (memberCache, objType, methodName, member);
try
{
object val = property.GetValue(obj, null);
translator.push(luaState, val);
}
catch(ArgumentException)
{
try {
object val = property.GetValue (obj, null);
translator.push (luaState, val);
} catch (ArgumentException) {
// If we can't find the getter in our class, recurse up to the base class and see
// if they can help.
if(objType is Type && !(((Type)objType) == typeof(object)))
return getMember(luaState, ((Type)objType).BaseType, obj, methodName, bindingType);
if (objType is Type && !(((Type)objType) == typeof(object)))
return getMember (luaState, ((Type)objType).BaseType, obj, methodName, bindingType);
else
LuaLib.lua_pushnil(luaState);
}
catch(TargetInvocationException e) // Convert this exception into a Lua error
{
ThrowError(luaState, e);
LuaLib.lua_pushnil(luaState);
}
LuaLib.lua_pushnil (luaState);
} catch (TargetInvocationException e) { // Convert this exception into a Lua error
ThrowError (luaState, e);
LuaLib.lua_pushnil (luaState);
}
else if(member.MemberType == MemberTypes.Event)
{
} else if (member.MemberType == MemberTypes.Event) {
var eventInfo = (EventInfo)member;
if(cachedMember.IsNull())
setMemberCache(memberCache, objType, methodName, member);
if (cachedMember.IsNull ())
setMemberCache (memberCache, objType, methodName, member);
translator.push(luaState, new RegisterEventHandler(translator.pendingEvents, obj, eventInfo));
}
else if(!implicitStatic)
{
if(member.MemberType == MemberTypes.NestedType)
{
translator.push (luaState, new RegisterEventHandler (translator.pendingEvents, obj, eventInfo));
} else if (!implicitStatic) {
if (member.MemberType == MemberTypes.NestedType) {
// kevinh - added support for finding nested types
// cache us
if(cachedMember.IsNull())
setMemberCache(memberCache, objType, methodName, member);
if (cachedMember.IsNull ())
setMemberCache (memberCache, objType, methodName, member);
// Find the name of our class
string name = member.Name;
......@@ -436,66 +384,59 @@ namespace LuaInterface
// Build a new long name and try to find the type by name
string longname = dectype.FullName + "+" + name;
var nestedType = translator.FindType(longname);
translator.pushType(luaState, nestedType);
}
else
{
var nestedType = translator.FindType (longname);
translator.pushType (luaState, nestedType);
} else {
// 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())
setMemberCache(memberCache, objType, methodName, wrapper);
if (cachedMember.IsNull ())
setMemberCache (memberCache, objType, methodName, wrapper);
translator.pushFunction(luaState, wrapper);
translator.push(luaState, true);
translator.pushFunction (luaState, wrapper);
translator.push (luaState, true);
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
translator.throwError(luaState, "can't pass instance to static method " + methodName);
LuaLib.lua_pushnil(luaState);
}
translator.throwError (luaState, "can't pass instance to static method " + methodName);
LuaLib.lua_pushnil (luaState);
}
else
{
} else {
// kevinh - we want to throw an exception because meerly returning 'nil' in this case
// is not sufficient. valid data members may return nil and therefore there must be some
// way to know the member just doesn't exist.
translator.throwError(luaState, "unknown member name " + methodName);
LuaLib.lua_pushnil(luaState);
translator.throwError (luaState, "unknown member name " + methodName);
LuaLib.lua_pushnil (luaState);
}
// push false because we are NOT returning a function (see luaIndexFunction)
translator.push(luaState, false);
translator.push (luaState, false);
return 2;
}
/*
* Checks if a MemberInfo object is cached, returning it or null.
*/
private object checkMemberCache(Hashtable memberCache, IReflect objType, string memberName)
private object checkMemberCache (Hashtable memberCache, IReflect objType, string memberName)
{
var members = (Hashtable)memberCache[objType];
return !members.IsNull() ? members[memberName] : null;
var members = (Hashtable)memberCache [objType];
return !members.IsNull () ? members [memberName] : null;
}
/*
* Stores a MemberInfo object in the member cache.
*/
private void setMemberCache(Hashtable memberCache, IReflect objType, string memberName, object member)
private void setMemberCache (Hashtable memberCache, IReflect objType, string memberName, object member)
{
var members = (Hashtable)memberCache[objType];
var members = (Hashtable)memberCache [objType];
if(members.IsNull())
{
members = new Hashtable();
memberCache[objType] = members;
if (members.IsNull ()) {
members = new Hashtable ();
memberCache [objType] = members;
}
members[memberName] = member;
members [memberName] = member;
}
/*
......@@ -503,68 +444,57 @@ namespace LuaInterface
* the member name and the value to be stored as arguments. Throws
* 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())
{
translator.throwError(luaState, "trying to index and invalid object reference");
if (target.IsNull ()) {
translator.throwError (luaState, "trying to index and invalid object reference");
return 0;
}
var type = target.GetType();
var type = target.GetType ();
// First try to look up the parameter as a property name
string detailMessage;
bool didMember = trySetMember(luaState, type, target, BindingFlags.Instance | BindingFlags.IgnoreCase, out detailMessage);
bool didMember = trySetMember (luaState, type, target, BindingFlags.Instance | BindingFlags.IgnoreCase, out detailMessage);
if(didMember)
if (didMember)
return 0; // Must have found the property name
// We didn't find a property name, now see if we can use a [] style this accessor to set array contents
try
{
if(type.IsArray && LuaLib.lua_isnumber(luaState, 2))
{
int index = (int)LuaLib.lua_tonumber(luaState, 2);
try {
if (type.IsArray && LuaLib.lua_isnumber (luaState, 2)) {
int index = (int)LuaLib.lua_tonumber (luaState, 2);
var arr = (Array)target;
object val = translator.getAsType(luaState, 3, arr.GetType().GetElementType());
arr.SetValue(val, index);
}
else
{
object val = translator.getAsType (luaState, 3, arr.GetType ().GetElementType ());
arr.SetValue (val, index);
} else {
// Try to see if we have a this[] accessor
var setter = type.GetMethod("set_Item");
if(!setter.IsNull())
{
var args = setter.GetParameters();
var valueType = args[1].ParameterType;
var setter = type.GetMethod ("set_Item");
if (!setter.IsNull ()) {
var args = setter.GetParameters ();
var valueType = args [1].ParameterType;
// The new val ue the user specified
object val = translator.getAsType(luaState, 3, valueType);
var indexType = args[0].ParameterType;
object index = translator.getAsType(luaState, 2, indexType);
object val = translator.getAsType (luaState, 3, valueType);
var indexType = args [0].ParameterType;
object index = translator.getAsType (luaState, 2, indexType);
object[] methodArgs = new object[2];
// Just call the indexer - if out of bounds an exception will happen
methodArgs[0] = index;
methodArgs[1] = val;
setter.Invoke(target, methodArgs);
}
else
translator.throwError(luaState, detailMessage); // Pass the original message from trySetMember because it is probably best
methodArgs [0] = index;
methodArgs [1] = val;
setter.Invoke (target, methodArgs);
} else
translator.throwError (luaState, detailMessage); // Pass the original message from trySetMember because it is probably best
}
}
catch(SEHException)
{
} catch (SEHException) {
// If we are seeing a C++ exception - this must actually be for Lua's private use. Let it handle it
throw;
}
catch(Exception e)
{
ThrowError(luaState, e);
} catch (Exception e) {
ThrowError (luaState, e);
}
return 0;
......@@ -578,7 +508,7 @@ namespace LuaInterface
/// <param name="target"></param>
/// <param name="bindingType"></param>
/// <returns>false if unable to find the named member, true for success</returns>
private bool trySetMember(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
......@@ -586,68 +516,53 @@ namespace LuaInterface
// changing the lua typecode to string
// Note: We don't use isstring because the standard lua C isstring considers either strings or numbers to
// be true for isstring.
if(LuaLib.lua_type(luaState, 2) != LuaTypes.String)
{
if (LuaLib.lua_type (luaState, 2) != LuaTypes.String) {
detailMessage = "property names must be strings";
return false;
}
// We only look up property names by string
string fieldName = LuaLib.lua_tostring(luaState, 2).ToString();
if(fieldName.IsNull() || fieldName.Length < 1 || !(char.IsLetter(fieldName[0]) || fieldName[0] == '_'))
{
string fieldName = LuaLib.lua_tostring (luaState, 2).ToString ();
if (fieldName.IsNull () || fieldName.Length < 1 || !(char.IsLetter (fieldName [0]) || fieldName [0] == '_')) {
detailMessage = "invalid property name";
return false;
}
// Find our member via reflection or the cache
var member = (MemberInfo)checkMemberCache(memberCache, targetType, fieldName);
if(member.IsNull())
{
var member = (MemberInfo)checkMemberCache (memberCache, targetType, fieldName);
if (member.IsNull ()) {
//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)
{
member = members[0];
setMemberCache(memberCache, targetType, fieldName, member);
}
else
{
if (members.Length > 0) {
member = members [0];
setMemberCache (memberCache, targetType, fieldName, member);
} else {
detailMessage = "field or property '" + fieldName + "' does not exist";
return false;
}
}
if(member.MemberType == MemberTypes.Field)
{
if (member.MemberType == MemberTypes.Field) {
var field = (FieldInfo)member;
object val = translator.getAsType(luaState, 3, field.FieldType);
object val = translator.getAsType (luaState, 3, field.FieldType);
try
{
field.SetValue(target, val);
}
catch (Exception e)
{
ThrowError(luaState, e);
try {
field.SetValue (target, val);
} catch (Exception e) {
ThrowError (luaState, e);
}
// We did a call
return true;
}
else if(member.MemberType == MemberTypes.Property)
{
} else if (member.MemberType == MemberTypes.Property) {
var property = (PropertyInfo)member;
object val = translator.getAsType(luaState, 3, property.PropertyType);
object val = translator.getAsType (luaState, 3, property.PropertyType);
try
{
property.SetValue(target, val, null);
}
catch (Exception e)
{
ThrowError(luaState, e);
try {
property.SetValue (target, val, null);
} catch (Exception e) {
ThrowError (luaState, e);
}
// We did a call
......@@ -662,13 +577,13 @@ namespace LuaInterface
* Writes to fields or properties, either static or instance. Throws an error
* 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;
bool success = trySetMember(luaState, targetType, target, bindingType, out detail);
bool success = trySetMember (luaState, targetType, target, bindingType, out detail);
if(!success)
translator.throwError(luaState, detail);
if (!success)
translator.throwError (luaState, detail);
return 0;
}
......@@ -678,71 +593,63 @@ namespace LuaInterface
/// </summary>
/// <param name="e"></param>
/// 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
var te = e as TargetInvocationException;
if (!te.IsNull())
if (!te.IsNull ())
e = te.InnerException;
translator.throwError(luaState, e);
translator.throwError (luaState, e);
}
/*
* __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;
object obj = translator.getRawNetObject(luaState, 1);
object obj = translator.getRawNetObject (luaState, 1);
if(obj.IsNull() || !(obj is IReflect))
{
translator.throwError(luaState, "trying to index an invalid type reference");
LuaLib.lua_pushnil(luaState);
if (obj.IsNull () || !(obj is IReflect)) {
translator.throwError (luaState, "trying to index an invalid type reference");
LuaLib.lua_pushnil (luaState);
return 1;
}
else
} else
klass = (IReflect)obj;
if(LuaLib.lua_isnumber(luaState, 2))
{
int size = (int)LuaLib.lua_tonumber(luaState, 2);
translator.push(luaState, Array.CreateInstance(klass.UnderlyingSystemType, size));
if (LuaLib.lua_isnumber (luaState, 2)) {
int size = (int)LuaLib.lua_tonumber (luaState, 2);
translator.push (luaState, Array.CreateInstance (klass.UnderlyingSystemType, size));
return 1;
}
else
{
string methodName = LuaLib.lua_tostring(luaState, 2).ToString();
} else {
string methodName = LuaLib.lua_tostring (luaState, 2).ToString ();
if(methodName.IsNull())
{
LuaLib.lua_pushnil(luaState);
if (methodName.IsNull ()) {
LuaLib.lua_pushnil (luaState);
return 1;
} //CP: Ignore case
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.
*/
private int setClassFieldOrProperty(LuaCore.lua_State luaState)
private int setClassFieldOrProperty (LuaCore.lua_State luaState)
{
IReflect target;
object obj = translator.getRawNetObject(luaState, 1);
object obj = translator.getRawNetObject (luaState, 1);
if(obj.IsNull() || !(obj is IReflect))
{
translator.throwError(luaState, "trying to index an invalid type reference");
if (obj.IsNull () || !(obj is IReflect)) {
translator.throwError (luaState, "trying to index an invalid type reference");
return 0;
}
else
} else
target = (IReflect)obj;
return setMember(luaState, target, null, BindingFlags.FlattenHierarchy | BindingFlags.Static | BindingFlags.IgnoreCase);
return setMember (luaState, target, null, BindingFlags.FlattenHierarchy | BindingFlags.Static | BindingFlags.IgnoreCase);
}
/*
......@@ -751,52 +658,43 @@ namespace LuaInterface
* found or if the arguments are invalid. Throws an error if the constructor
* 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;
object obj = translator.getRawNetObject(luaState, 1);
object obj = translator.getRawNetObject (luaState, 1);
if(obj.IsNull() || !(obj is IReflect))
{
translator.throwError(luaState, "trying to call constructor on an invalid type reference");
LuaLib.lua_pushnil(luaState);
if (obj.IsNull () || !(obj is IReflect)) {
translator.throwError (luaState, "trying to call constructor on an invalid type reference");
LuaLib.lua_pushnil (luaState);
return 1;
}
else
} else
klass = (IReflect)obj;
LuaLib.lua_remove(luaState, 1);
var constructors = klass.UnderlyingSystemType.GetConstructors();
LuaLib.lua_remove (luaState, 1);
var constructors = klass.UnderlyingSystemType.GetConstructors ();
foreach(var constructor in constructors)
{
bool isConstructor = matchParameters(luaState, constructor, ref validConstructor);
foreach (var constructor in constructors) {
bool isConstructor = matchParameters (luaState, constructor, ref validConstructor);
if(isConstructor)
{
try
{
translator.push(luaState, constructor.Invoke(validConstructor.args));
}
catch(TargetInvocationException e)
{
ThrowError(luaState, e);
LuaLib.lua_pushnil(luaState);
}
catch
{
LuaLib.lua_pushnil(luaState);
if (isConstructor) {
try {
translator.push (luaState, constructor.Invoke (validConstructor.args));
} catch (TargetInvocationException e) {
ThrowError (luaState, e);
LuaLib.lua_pushnil (luaState);
} catch {
LuaLib.lua_pushnil (luaState);
}
return 1;
}
}
string constructorName = (constructors.Length == 0) ? "unknown" : constructors[0].Name;
translator.throwError(luaState, String.Format("{0} does not contain constructor({1}) argument match",
string constructorName = (constructors.Length == 0) ? "unknown" : constructors [0].Name;
translator.throwError (luaState, String.Format ("{0} does not contain constructor({1}) argument match",
klass.UnderlyingSystemType, constructorName));
LuaLib.lua_pushnil(luaState);
LuaLib.lua_pushnil (luaState);
return 1;
}
......@@ -805,96 +703,83 @@ namespace LuaInterface
* if the match was succesful. It it was also returns the information
* 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;
bool isMethod = true;
var paramInfo = method.GetParameters();
var paramInfo = method.GetParameters ();
int currentLuaParam = 1;
int nLuaParams = LuaLib.lua_gettop(luaState);
var paramList = new ArrayList();
var outList = new List<int>();
var argTypes = new List<MethodArgs>();
foreach(var currentNetParam in paramInfo)
{
if(!currentNetParam.IsIn && currentNetParam.IsOut) // Skips out params
outList.Add(paramList.Add(null));
else if(currentLuaParam > nLuaParams) // Adds optional parameters
{
if(currentNetParam.IsOptional)
paramList.Add(currentNetParam.DefaultValue);
else
{
int nLuaParams = LuaLib.lua_gettop (luaState);
var paramList = new ArrayList ();
var outList = new List<int> ();
var argTypes = new List<MethodArgs> ();
foreach (var currentNetParam in paramInfo) {
if (!currentNetParam.IsIn && currentNetParam.IsOut) // Skips out params
outList.Add (paramList.Add (null));
else if (currentLuaParam > nLuaParams) { // Adds optional parameters
if (currentNetParam.IsOptional)
paramList.Add (currentNetParam.DefaultValue);
else {
isMethod = false;
break;
}
}
else if(_IsTypeCorrect(luaState, currentLuaParam, currentNetParam, out extractValue)) // Type checking
{
int index = paramList.Add(extractValue(luaState, currentLuaParam));
var methodArg = new MethodArgs();
} else if (_IsTypeCorrect (luaState, currentLuaParam, currentNetParam, out extractValue)) { // Type checking
int index = paramList.Add (extractValue (luaState, currentLuaParam));
var methodArg = new MethodArgs ();
methodArg.index = index;
methodArg.extractValue = extractValue;
argTypes.Add(methodArg);
argTypes.Add (methodArg);
if(currentNetParam.ParameterType.IsByRef)
outList.Add(index);
if (currentNetParam.ParameterType.IsByRef)
outList.Add (index);
currentLuaParam++;
} // Type does not match, ignore if the parameter is optional
else if(_IsParamsArray(luaState, currentLuaParam, currentNetParam, out extractValue))
{
object luaParamValue = extractValue(luaState, currentLuaParam);
var paramArrayType = currentNetParam.ParameterType.GetElementType();
else if (_IsParamsArray (luaState, currentLuaParam, currentNetParam, out extractValue)) {
object luaParamValue = extractValue (luaState, currentLuaParam);
var paramArrayType = currentNetParam.ParameterType.GetElementType ();
Array paramArray;
if(luaParamValue is LuaTable)
{
if (luaParamValue is LuaTable) {
var table = (LuaTable)luaParamValue;
var tableEnumerator = table.GetEnumerator();
paramArray = Array.CreateInstance(paramArrayType, table.Values.Count);
tableEnumerator.Reset();
var tableEnumerator = table.GetEnumerator ();
paramArray = Array.CreateInstance (paramArrayType, table.Values.Count);
tableEnumerator.Reset ();
int paramArrayIndex = 0;
while(tableEnumerator.MoveNext())
{
paramArray.SetValue(Convert.ChangeType(tableEnumerator.Value, currentNetParam.ParameterType.GetElementType()), paramArrayIndex);
while (tableEnumerator.MoveNext()) {
paramArray.SetValue (Convert.ChangeType (tableEnumerator.Value, currentNetParam.ParameterType.GetElementType ()), paramArrayIndex);
paramArrayIndex++;
}
}
else
{
paramArray = Array.CreateInstance(paramArrayType, 1);
paramArray.SetValue(luaParamValue, 0);
} else {
paramArray = Array.CreateInstance (paramArrayType, 1);
paramArray.SetValue (luaParamValue, 0);
}
int index = paramList.Add(paramArray);
var methodArg = new MethodArgs();
int index = paramList.Add (paramArray);
var methodArg = new MethodArgs ();
methodArg.index = index;
methodArg.extractValue = extractValue;
methodArg.isParamsArray = true;
methodArg.paramsArrayType = paramArrayType;
argTypes.Add(methodArg);
argTypes.Add (methodArg);
currentLuaParam++;
}
else if(currentNetParam.IsOptional)
paramList.Add(currentNetParam.DefaultValue);
else // No match
{
} else if (currentNetParam.IsOptional)
paramList.Add (currentNetParam.DefaultValue);
else { // No match
isMethod = false;
break;
}
}
if(currentLuaParam != nLuaParams + 1) // Number of parameters does not match
if (currentLuaParam != nLuaParams + 1) // Number of parameters does not match
isMethod = false;
if(isMethod)
{
methodCache.args = paramList.ToArray();
if (isMethod) {
methodCache.args = paramList.ToArray ();
methodCache.cachedMethod = method;
methodCache.outList = outList.ToArray();
methodCache.argTypes = argTypes.ToArray();
methodCache.outList = outList.ToArray ();
methodCache.argTypes = argTypes.ToArray ();
}
return isMethod;
......@@ -909,77 +794,59 @@ namespace LuaInterface
/// <param name="currentNetParam"></param>
/// <param name="extractValue"></param>
/// <returns></returns>
private bool _IsTypeCorrect(LuaCore.lua_State luaState, int currentLuaParam, ParameterInfo currentNetParam, out ExtractValue extractValue)
{
try
{
return (extractValue = translator.typeChecker.checkType(luaState, currentLuaParam, currentNetParam.ParameterType)) != null;
}
catch
private bool _IsTypeCorrect (LuaCore.lua_State luaState, int currentLuaParam, ParameterInfo currentNetParam, out ExtractValue extractValue)
{
try {
return (extractValue = translator.typeChecker.checkType (luaState, currentLuaParam, currentNetParam.ParameterType)) != null;
} catch {
extractValue = null;
Debug.WriteLine("Type wasn't correct");
Debug.WriteLine ("Type wasn't correct");
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;
if (currentNetParam.GetCustomAttributes(typeof(ParamArrayAttribute), false).Length > 0)
{
if (currentNetParam.GetCustomAttributes (typeof(ParamArrayAttribute), false).Length > 0) {
LuaTypes luaType;
try
{
luaType = LuaLib.lua_type(luaState, currentLuaParam);
}
catch(Exception ex)
{
Debug.WriteLine("Could not retrieve lua type while attempting to determine params Array Status.");
Debug.WriteLine(ex.Message);
try {
luaType = LuaLib.lua_type (luaState, currentLuaParam);
} catch (Exception ex) {
Debug.WriteLine ("Could not retrieve lua type while attempting to determine params Array Status.");
Debug.WriteLine (ex.Message);
extractValue = null;
return false;
}
if(luaType == LuaTypes.Table)
{
try
{
extractValue = translator.typeChecker.getExtractor(typeof(LuaTable));
}
catch(Exception/* ex*/)
{
Debug.WriteLine("An error occurred during an attempt to retrieve a LuaTable extractor while checking for params array status.");
if (luaType == LuaTypes.Table) {
try {
extractValue = translator.typeChecker.getExtractor (typeof(LuaTable));
} catch (Exception/* ex*/) {
Debug.WriteLine ("An error occurred during an attempt to retrieve a LuaTable extractor while checking for params array status.");
}
if(!extractValue.IsNull())
{
if (!extractValue.IsNull ()) {
return true;
}
}
else
{
var paramElementType = currentNetParam.ParameterType.GetElementType();
} else {
var paramElementType = currentNetParam.ParameterType.GetElementType ();
try
{
extractValue = translator.typeChecker.checkType(luaState, currentLuaParam, paramElementType);
}
catch (Exception/* ex*/)
{
Debug.WriteLine(string.Format("An error occurred during an attempt to retrieve an extractor ({0}) while checking for params array status.", paramElementType.FullName));
try {
extractValue = translator.typeChecker.checkType (luaState, currentLuaParam, paramElementType);
} catch (Exception/* ex*/) {
Debug.WriteLine (string.Format ("An error occurred during an attempt to retrieve an extractor ({0}) while checking for params array status.", paramElementType.FullName));
}
if(!extractValue.IsNull())
{
if (!extractValue.IsNull ()) {
return true;
}
}
}
Debug.WriteLine("Type wasn't Params object.");
Debug.WriteLine ("Type wasn't Params object.");
return false;
}
}
......
......@@ -22,7 +22,6 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Diagnostics;
using System.Collections.Generic;
......@@ -34,28 +33,28 @@ namespace LuaInterface.Method
/// </summary>
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);
Debug.Assert(found);
bool found = dict.Remove (handler);
Debug.Assert (found);
}
/// <summary>
/// Remove any still registered handlers
/// </summary>
public void Dispose()
public void Dispose ()
{
foreach(KeyValuePair<Delegate, RegisterEventHandler> pair in dict)
pair.Value.RemovePending(pair.Key);
foreach (KeyValuePair<Delegate, RegisterEventHandler> pair in dict)
pair.Value.RemovePending (pair.Key);
dict.Clear();
dict.Clear ();
}
}
}
\ No newline at end of file
......@@ -22,7 +22,6 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
namespace LuaInterface.Method
......@@ -39,11 +38,11 @@ namespace LuaInterface.Method
* Gets the function called name from the provided table,
* 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;
else
return null;
......@@ -52,29 +51,25 @@ namespace LuaInterface.Method
/*
* 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
// of arguments passed to the function (with in parameters only), outArgs
// has the positions of out parameters
object returnValue;
int iRefArgs;
object[] returnValues = function.call(inArgs, returnTypes);
object[] returnValues = function.call (inArgs, returnTypes);
if(returnTypes[0] == typeof(void))
{
if (returnTypes [0] == typeof(void)) {
returnValue = null;
iRefArgs = 0;
}
else
{
returnValue = returnValues[0];
} else {
returnValue = returnValues [0];
iRefArgs = 1;
}
for(int i = 0; i < outArgs.Length; i++)
{
args[outArgs[i]] = returnValues[iRefArgs];
for (int i = 0; i < outArgs.Length; i++) {
args [outArgs [i]] = returnValues [iRefArgs];
iRefArgs++;
}
......
......@@ -22,7 +22,6 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
namespace LuaInterface.Method
......@@ -40,37 +39,33 @@ namespace LuaInterface.Method
public LuaFunction function;
public Type[] returnTypes;
public LuaDelegate()
public LuaDelegate ()
{
function = 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
// of arguments passed to the function (with in parameters only), outArgs
// has the positions of out parameters
object returnValue;
int iRefArgs;
object[] returnValues = function.call(inArgs, returnTypes);
object[] returnValues = function.call (inArgs, returnTypes);
if(returnTypes[0] == typeof(void))
{
if (returnTypes [0] == typeof(void)) {
returnValue = null;
iRefArgs = 0;
}
else
{
returnValue = returnValues[0];
} else {
returnValue = returnValues [0];
iRefArgs = 1;
}
// Sets the value of out and ref parameters (from
// the values returned by the Lua function).
for(int i = 0; i < outArgs.Length; i++)
{
args[outArgs[i]] = returnValues[iRefArgs];
for (int i = 0; i < outArgs.Length; i++) {
args [outArgs [i]] = returnValues [iRefArgs];
iRefArgs++;
}
......
......@@ -22,7 +22,6 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
namespace LuaInterface.Method
......@@ -41,9 +40,9 @@ namespace LuaInterface.Method
// CP: Fix provided by Ben Bryant for delegates with one param
// link: http://luaforge.net/forum/message.php?msg_id=9318
public void handleEvent(object[] args)
public void handleEvent (object[] args)
{
handler.Call(args);
handler.Call (args);
}
//public void handleEvent(object sender,object data)
//{
......
......@@ -22,7 +22,6 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Reflection;
using System.Collections.Generic;
......@@ -36,7 +35,7 @@ namespace LuaInterface.Method
/*
* Argument extraction with type-conversion function
*/
delegate object ExtractValue(LuaCore.lua_State luaState, int stackPos);
delegate object ExtractValue (LuaCore.lua_State luaState, int stackPos);
/*
* Wrapper class for methods/constructors accessed from Lua.
......@@ -48,10 +47,9 @@ namespace LuaInterface.Method
{
private ObjectTranslator _Translator;
private MethodBase _Method;
private MethodCache _LastCalledMethod = new MethodCache();
private MethodCache _LastCalledMethod = new MethodCache ();
private string _MethodName;
private MemberInfo[] _Members;
private IReflect _TargetType;
private ExtractValue _ExtractTarget;
private object _Target;
private BindingFlags _BindingType;
......@@ -59,19 +57,18 @@ namespace LuaInterface.Method
/*
* Constructs the wrapper for a known MethodBase instance
*/
public LuaMethodWrapper(ObjectTranslator translator, object target, IReflect targetType, MethodBase method)
public LuaMethodWrapper (ObjectTranslator translator, object target, IReflect targetType, MethodBase method)
{
_Translator = translator;
_Target = target;
_TargetType = targetType;
if(!targetType.IsNull())
_ExtractTarget = translator.typeChecker.getExtractor(targetType);
if (!targetType.IsNull ())
_ExtractTarget = translator.typeChecker.getExtractor (targetType);
_Method = method;
_MethodName = method.Name;
if(method.IsStatic)
if (method.IsStatic)
_BindingType = BindingFlags.Static;
else
_BindingType = BindingFlags.Instance;
......@@ -80,18 +77,17 @@ namespace LuaInterface.Method
/*
* Constructs the wrapper for a known method name
*/
public LuaMethodWrapper(ObjectTranslator translator, IReflect targetType, string methodName, BindingFlags bindingType)
public LuaMethodWrapper (ObjectTranslator translator, IReflect targetType, string methodName, BindingFlags bindingType)
{
_Translator = translator;
_MethodName = methodName;
_TargetType = targetType;
if(!targetType.IsNull())
_ExtractTarget = translator.typeChecker.getExtractor(targetType);
if (!targetType.IsNull ())
_ExtractTarget = translator.typeChecker.getExtractor (targetType);
_BindingType = bindingType;
//CP: Removed NonPublic binding search and added IgnoreCase
_Members = targetType.UnderlyingSystemType.GetMember(methodName, MemberTypes.Method, bindingType | BindingFlags.Public | BindingFlags.IgnoreCase/*|BindingFlags.NonPublic*/);
_Members = targetType.UnderlyingSystemType.GetMember (methodName, MemberTypes.Method, bindingType | BindingFlags.Public | BindingFlags.IgnoreCase/*|BindingFlags.NonPublic*/);
}
/// <summary>
......@@ -99,226 +95,187 @@ namespace LuaInterface.Method
/// </summary>
/// <returns>num of things on stack</returns>
/// <param name="e">null for no pending exception</param>
int SetPendingException(Exception e)
int SetPendingException (Exception e)
{
return _Translator.interpreter.SetPendingException(e);
return _Translator.interpreter.SetPendingException (e);
}
/*
* Calls the method. Receives the arguments from the Lua stack
* and returns values in it.
*/
public int call(LuaCore.lua_State luaState)
public int call (LuaCore.lua_State luaState)
{
var methodToCall = _Method;
object targetObject = _Target;
bool failedCall = true;
int nReturnValues = 0;
if(!LuaLib.lua_checkstack(luaState, 5))
throw new LuaException("Lua stack overflow");
if (!LuaLib.lua_checkstack (luaState, 5))
throw new LuaException ("Lua stack overflow");
bool isStatic = (_BindingType & BindingFlags.Static) == BindingFlags.Static;
SetPendingException(null);
SetPendingException (null);
if(methodToCall.IsNull()) // Method from name
{
if(isStatic)
if (methodToCall.IsNull ()) { // Method from name
if (isStatic)
targetObject = null;
else
targetObject = _ExtractTarget(luaState, 1);
targetObject = _ExtractTarget (luaState, 1);
//LuaLib.lua_remove(luaState,1); // Pops the receiver
if(!_LastCalledMethod.cachedMethod.IsNull()) // Cached?
{
if (!_LastCalledMethod.cachedMethod.IsNull ()) { // Cached?
int numStackToSkip = isStatic ? 0 : 1; // If this is an instance invoe we will have an extra arg on the stack for the targetObject
int numArgsPassed = LuaLib.lua_gettop(luaState) - numStackToSkip;
int numArgsPassed = LuaLib.lua_gettop (luaState) - numStackToSkip;
if(numArgsPassed == _LastCalledMethod.argTypes.Length) // No. of args match?
{
if(!LuaLib.lua_checkstack(luaState, _LastCalledMethod.outList.Length + 6))
throw new LuaException("Lua stack overflow");
if (numArgsPassed == _LastCalledMethod.argTypes.Length) { // No. of args match?
if (!LuaLib.lua_checkstack (luaState, _LastCalledMethod.outList.Length + 6))
throw new LuaException ("Lua stack overflow");
try
{
for(int i = 0; i < _LastCalledMethod.argTypes.Length; i++)
{
if(_LastCalledMethod.argTypes[i].isParamsArray)
{
object luaParamValue = _LastCalledMethod.argTypes[i].extractValue(luaState, i + 1 + numStackToSkip);
var paramArrayType = _LastCalledMethod.argTypes[i].paramsArrayType;
try {
for (int i = 0; i < _LastCalledMethod.argTypes.Length; i++) {
if (_LastCalledMethod.argTypes [i].isParamsArray) {
object luaParamValue = _LastCalledMethod.argTypes [i].extractValue (luaState, i + 1 + numStackToSkip);
var paramArrayType = _LastCalledMethod.argTypes [i].paramsArrayType;
Array paramArray;
if(luaParamValue is LuaTable)
{
if (luaParamValue is LuaTable) {
var table = (LuaTable)luaParamValue;
paramArray = Array.CreateInstance(paramArrayType, table.Values.Count);
paramArray = Array.CreateInstance (paramArrayType, table.Values.Count);
for(int x = 1; x <= table.Values.Count; x++)
paramArray.SetValue(Convert.ChangeType(table[x], paramArrayType), x - 1);
}
else
{
paramArray = Array.CreateInstance(paramArrayType, 1);
paramArray.SetValue(luaParamValue, 0);
for (int x = 1; x <= table.Values.Count; x++)
paramArray.SetValue (Convert.ChangeType (table [x], paramArrayType), x - 1);
} else {
paramArray = Array.CreateInstance (paramArrayType, 1);
paramArray.SetValue (luaParamValue, 0);
}
_LastCalledMethod.args[_LastCalledMethod.argTypes[i].index] = paramArray;
}
else
{
_LastCalledMethod.args[_LastCalledMethod.argTypes[i].index] =
_LastCalledMethod.argTypes[i].extractValue(luaState, i + 1 + numStackToSkip);
_LastCalledMethod.args [_LastCalledMethod.argTypes [i].index] = paramArray;
} else {
_LastCalledMethod.args [_LastCalledMethod.argTypes [i].index] =
_LastCalledMethod.argTypes [i].extractValue (luaState, i + 1 + numStackToSkip);
}
if(_LastCalledMethod.args[_LastCalledMethod.argTypes[i].index] == null &&
!LuaLib.lua_isnil(luaState, i + 1 + numStackToSkip))
throw new LuaException("argument number " + (i + 1) + " is invalid");
if (_LastCalledMethod.args [_LastCalledMethod.argTypes [i].index] == null &&
!LuaLib.lua_isnil (luaState, i + 1 + numStackToSkip))
throw new LuaException ("argument number " + (i + 1) + " is invalid");
}
if((_BindingType & BindingFlags.Static) == BindingFlags.Static)
_Translator.push(luaState, _LastCalledMethod.cachedMethod.Invoke(null, _LastCalledMethod.args));
else
{
if(_LastCalledMethod.cachedMethod.IsConstructor)
_Translator.push(luaState, ((ConstructorInfo)_LastCalledMethod.cachedMethod).Invoke(_LastCalledMethod.args));
if ((_BindingType & BindingFlags.Static) == BindingFlags.Static)
_Translator.push (luaState, _LastCalledMethod.cachedMethod.Invoke (null, _LastCalledMethod.args));
else {
if (_LastCalledMethod.cachedMethod.IsConstructor)
_Translator.push (luaState, ((ConstructorInfo)_LastCalledMethod.cachedMethod).Invoke (_LastCalledMethod.args));
else
_Translator.push(luaState, _LastCalledMethod.cachedMethod.Invoke(targetObject, _LastCalledMethod.args));
_Translator.push (luaState, _LastCalledMethod.cachedMethod.Invoke (targetObject, _LastCalledMethod.args));
}
failedCall = false;
}
catch(TargetInvocationException e)
{
} catch (TargetInvocationException e) {
// Failure of method invocation
return SetPendingException(e.GetBaseException());
}
catch(Exception e)
{
if(_Members.Length == 1) // Is the method overloaded?
return SetPendingException (e.GetBaseException ());
} catch (Exception e) {
if (_Members.Length == 1) // Is the method overloaded?
// No, throw error
return SetPendingException(e);
return SetPendingException (e);
}
}
}
// Cache miss
if(failedCall)
{
if (failedCall) {
// System.Diagnostics.Debug.WriteLine("cache miss on " + methodName);
// If we are running an instance variable, we can now pop the targetObject from the stack
if(!isStatic)
{
if(targetObject.IsNull())
{
_Translator.throwError(luaState, String.Format("instance method '{0}' requires a non null target object", _MethodName));
LuaLib.lua_pushnil(luaState);
if (!isStatic) {
if (targetObject.IsNull ()) {
_Translator.throwError (luaState, String.Format ("instance method '{0}' requires a non null target object", _MethodName));
LuaLib.lua_pushnil (luaState);
return 1;
}
LuaLib.lua_remove(luaState, 1); // Pops the receiver
LuaLib.lua_remove (luaState, 1); // Pops the receiver
}
bool hasMatch = false;
string candidateName = null;
foreach(var member in _Members)
{
foreach (var member in _Members) {
candidateName = member.ReflectedType.Name + "." + member.Name;
var m = (MethodInfo)member;
bool isMethod = _Translator.matchParameters(luaState, m, ref _LastCalledMethod);
bool isMethod = _Translator.matchParameters (luaState, m, ref _LastCalledMethod);
if(isMethod)
{
if (isMethod) {
hasMatch = true;
break;
}
}
if(!hasMatch)
{
if (!hasMatch) {
string msg = (candidateName == null) ? "invalid arguments to method call" : ("invalid arguments to method: " + candidateName);
_Translator.throwError(luaState, msg);
LuaLib.lua_pushnil(luaState);
_Translator.throwError (luaState, msg);
LuaLib.lua_pushnil (luaState);
return 1;
}
}
}
else // Method from MethodBase instance
{
if(methodToCall.ContainsGenericParameters)
{
/*bool isMethod = */_Translator.matchParameters(luaState, methodToCall, ref _LastCalledMethod);
} else { // Method from MethodBase instance
if (methodToCall.ContainsGenericParameters) {
/*bool isMethod = */
_Translator.matchParameters (luaState, methodToCall, ref _LastCalledMethod);
if(methodToCall.IsGenericMethodDefinition)
{
if (methodToCall.IsGenericMethodDefinition) {
//need to make a concrete type of the generic method definition
var typeArgs = new List<Type>();
var typeArgs = new List<Type> ();
foreach(object arg in _LastCalledMethod.args)
typeArgs.Add(arg.GetType());
foreach (object arg in _LastCalledMethod.args)
typeArgs.Add (arg.GetType ());
var concreteMethod = (methodToCall as MethodInfo).MakeGenericMethod(typeArgs.ToArray());
_Translator.push(luaState, concreteMethod.Invoke(targetObject, _LastCalledMethod.args));
var concreteMethod = (methodToCall as MethodInfo).MakeGenericMethod (typeArgs.ToArray ());
_Translator.push (luaState, concreteMethod.Invoke (targetObject, _LastCalledMethod.args));
failedCall = false;
}
else if(methodToCall.ContainsGenericParameters)
{
_Translator.throwError(luaState, "unable to invoke method on generic class as the current method is an open generic method");
LuaLib.lua_pushnil(luaState);
} else if (methodToCall.ContainsGenericParameters) {
_Translator.throwError (luaState, "unable to invoke method on generic class as the current method is an open generic method");
LuaLib.lua_pushnil (luaState);
return 1;
}
}
else
{
if(!methodToCall.IsStatic && !methodToCall.IsConstructor && targetObject == null)
{
targetObject = _ExtractTarget(luaState, 1);
LuaLib.lua_remove(luaState, 1); // Pops the receiver
} else {
if (!methodToCall.IsStatic && !methodToCall.IsConstructor && targetObject == null) {
targetObject = _ExtractTarget (luaState, 1);
LuaLib.lua_remove (luaState, 1); // Pops the receiver
}
if(!_Translator.matchParameters(luaState, methodToCall, ref _LastCalledMethod))
{
_Translator.throwError(luaState, "invalid arguments to method call");
LuaLib.lua_pushnil(luaState);
if (!_Translator.matchParameters (luaState, methodToCall, ref _LastCalledMethod)) {
_Translator.throwError (luaState, "invalid arguments to method call");
LuaLib.lua_pushnil (luaState);
return 1;
}
}
}
if(failedCall)
{
if(!LuaLib.lua_checkstack(luaState, _LastCalledMethod.outList.Length + 6))
throw new LuaException("Lua stack overflow");
if (failedCall) {
if (!LuaLib.lua_checkstack (luaState, _LastCalledMethod.outList.Length + 6))
throw new LuaException ("Lua stack overflow");
try
{
if(isStatic)
_Translator.push(luaState, _LastCalledMethod.cachedMethod.Invoke(null, _LastCalledMethod.args));
else
{
if(_LastCalledMethod.cachedMethod.IsConstructor)
_Translator.push(luaState, ((ConstructorInfo)_LastCalledMethod.cachedMethod).Invoke(_LastCalledMethod.args));
try {
if (isStatic)
_Translator.push (luaState, _LastCalledMethod.cachedMethod.Invoke (null, _LastCalledMethod.args));
else {
if (_LastCalledMethod.cachedMethod.IsConstructor)
_Translator.push (luaState, ((ConstructorInfo)_LastCalledMethod.cachedMethod).Invoke (_LastCalledMethod.args));
else
_Translator.push(luaState, _LastCalledMethod.cachedMethod.Invoke(targetObject, _LastCalledMethod.args));
_Translator.push (luaState, _LastCalledMethod.cachedMethod.Invoke (targetObject, _LastCalledMethod.args));
}
}
catch(TargetInvocationException e)
{
return SetPendingException(e.GetBaseException());
}
catch(Exception e)
{
return SetPendingException(e);
} catch (TargetInvocationException e) {
return SetPendingException (e.GetBaseException ());
} catch (Exception e) {
return SetPendingException (e);
}
}
// Pushes out and ref return values
for(int index = 0; index < _LastCalledMethod.outList.Length; index++)
{
for (int index = 0; index < _LastCalledMethod.outList.Length; index++) {
nReturnValues++;
//for(int i=0;i<lastCalledMethod.outList.Length;i++)
_Translator.push(luaState, _LastCalledMethod.args[_LastCalledMethod.outList[index]]);
_Translator.push (luaState, _LastCalledMethod.args [_LastCalledMethod.outList [index]]);
}
//by isSingle 2010-09-10 11:26:31
......@@ -326,7 +283,7 @@ namespace LuaInterface.Method
// if not return void,we need add 1,
// or we will lost the function's return value
// when call dotnet function like "int foo(arg1,out arg2,out arg3)" in lua code
if(!_LastCalledMethod.IsReturnVoid && nReturnValues > 0)
if (!_LastCalledMethod.IsReturnVoid && nReturnValues > 0)
nReturnValues++;
return nReturnValues < 1 ? 1 : nReturnValues;
......
......@@ -22,7 +22,6 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
namespace LuaInterface.Method
......
......@@ -22,7 +22,6 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Reflection;
using LuaInterface.Extensions;
......@@ -36,19 +35,16 @@ namespace LuaInterface.Method
{
private MethodBase _cachedMethod;
public MethodBase cachedMethod
{
get
{
public MethodBase cachedMethod {
get {
return _cachedMethod;
}
set
{
set {
_cachedMethod = value;
var mi = value as MethodInfo;
if(!mi.IsNull())
IsReturnVoid = string.Compare(mi.ReturnType.Name, "System.Void", true) == 0;
if (!mi.IsNull ())
IsReturnVoid = string.Compare (mi.ReturnType.Name, "System.Void", true) == 0;
}
}
......
......@@ -22,7 +22,6 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Reflection;
......@@ -41,7 +40,7 @@ namespace LuaInterface.Method
private EventInfo eventInfo;
private object target;
public RegisterEventHandler(EventHandlerContainer pendingEvents, object target, EventInfo eventInfo)
public RegisterEventHandler (EventHandlerContainer pendingEvents, object target, EventInfo eventInfo)
{
this.target = target;
this.eventInfo = eventInfo;
......@@ -51,13 +50,13 @@ namespace LuaInterface.Method
/*
* Adds a new event handler
*/
public Delegate Add(LuaFunction function)
public Delegate Add (LuaFunction function)
{
//CP: Fix by Ben Bryant for event handling with one parameter
//link: http://luaforge.net/forum/message.php?msg_id=9266
Delegate handlerDelegate = CodeGeneration.Instance.GetDelegate(eventInfo.EventHandlerType, function);
eventInfo.AddEventHandler(target, handlerDelegate);
pendingEvents.Add(handlerDelegate, this);
Delegate handlerDelegate = CodeGeneration.Instance.GetDelegate (eventInfo.EventHandlerType, function);
eventInfo.AddEventHandler (target, handlerDelegate);
pendingEvents.Add (handlerDelegate, this);
return handlerDelegate;
//MethodInfo mi = eventInfo.EventHandlerType.GetMethod("Invoke");
......@@ -72,18 +71,18 @@ namespace LuaInterface.Method
/*
* Removes an existing event handler
*/
public void Remove(Delegate handlerDelegate)
public void Remove (Delegate handlerDelegate)
{
RemovePending(handlerDelegate);
pendingEvents.Remove(handlerDelegate);
RemovePending (handlerDelegate);
pendingEvents.Remove (handlerDelegate);
}
/*
* Removes an existing event handler (without updating the pending handlers list)
*/
internal void RemovePending(Delegate handlerDelegate)
internal void RemovePending (Delegate handlerDelegate)
{
eventInfo.RemoveEventHandler(target, handlerDelegate);
eventInfo.RemoveEventHandler (target, handlerDelegate);
}
}
}
\ No newline at end of file
......@@ -22,7 +22,6 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.IO;
using System.Reflection;
......@@ -48,10 +47,10 @@ namespace LuaInterface
private LuaCore.lua_CFunction registerTableFunction, unregisterTableFunction, getMethodSigFunction,
getConstructorSigFunction, importTypeFunction, loadAssemblyFunction;
// object to object #
public readonly Dictionary<object, int> objectsBackMap = new Dictionary<object, int>();
public readonly Dictionary<object, int> objectsBackMap = new Dictionary<object, int> ();
// object # to object (FIXME - it should be possible to get object address as an object #)
public readonly Dictionary<int, object> objects = new Dictionary<int, object>();
internal EventHandlerContainer pendingEvents = new EventHandlerContainer();
public readonly Dictionary<int, object> objects = new Dictionary<int, object> ();
internal EventHandlerContainer pendingEvents = new EventHandlerContainer ();
private MetaFunctions metaFunctions;
private List<Assembly> assemblies;
internal CheckType typeChecker;
......@@ -61,219 +60,208 @@ namespace LuaInterface
/// </summary>
private int nextObj = 0;
public ObjectTranslator(Lua interpreter, LuaCore.lua_State luaState)
public ObjectTranslator (Lua interpreter, LuaCore.lua_State luaState)
{
this.interpreter = interpreter;
typeChecker = new CheckType(this);
metaFunctions = new MetaFunctions(this);
assemblies = new List<Assembly>();
typeChecker = new CheckType (this);
metaFunctions = new MetaFunctions (this);
assemblies = new List<Assembly> ();
importTypeFunction = new LuaCore.lua_CFunction(this.importType);
loadAssemblyFunction = new LuaCore.lua_CFunction(this.loadAssembly);
registerTableFunction = new LuaCore.lua_CFunction(this.registerTable);
unregisterTableFunction = new LuaCore.lua_CFunction(this.unregisterTable);
getMethodSigFunction = new LuaCore.lua_CFunction(this.getMethodSignature);
getConstructorSigFunction = new LuaCore.lua_CFunction(this.getConstructorSignature);
importTypeFunction = new LuaCore.lua_CFunction (this.importType);
loadAssemblyFunction = new LuaCore.lua_CFunction (this.loadAssembly);
registerTableFunction = new LuaCore.lua_CFunction (this.registerTable);
unregisterTableFunction = new LuaCore.lua_CFunction (this.unregisterTable);
getMethodSigFunction = new LuaCore.lua_CFunction (this.getMethodSignature);
getConstructorSigFunction = new LuaCore.lua_CFunction (this.getConstructorSignature);
createLuaObjectList(luaState);
createIndexingMetaFunction(luaState);
createBaseClassMetatable(luaState);
createClassMetatable(luaState);
createFunctionMetatable(luaState);
setGlobalFunctions(luaState);
createLuaObjectList (luaState);
createIndexingMetaFunction (luaState);
createBaseClassMetatable (luaState);
createClassMetatable (luaState);
createFunctionMetatable (luaState);
setGlobalFunctions (luaState);
}
/*
* Sets up the list of objects in the Lua side
*/
private void createLuaObjectList(LuaCore.lua_State luaState)
private void createLuaObjectList (LuaCore.lua_State luaState)
{
LuaLib.lua_pushstring(luaState, "luaNet_objects");
LuaLib.lua_newtable(luaState);
LuaLib.lua_newtable(luaState);
LuaLib.lua_pushstring(luaState, "__mode");
LuaLib.lua_pushstring(luaState, "v");
LuaLib.lua_settable(luaState, -3);
LuaLib.lua_setmetatable(luaState, -2);
LuaLib.lua_settable(luaState, (int)LuaIndexes.Registry);
LuaLib.lua_pushstring (luaState, "luaNet_objects");
LuaLib.lua_newtable (luaState);
LuaLib.lua_newtable (luaState);
LuaLib.lua_pushstring (luaState, "__mode");
LuaLib.lua_pushstring (luaState, "v");
LuaLib.lua_settable (luaState, -3);
LuaLib.lua_setmetatable (luaState, -2);
LuaLib.lua_settable (luaState, (int)LuaIndexes.Registry);
}
/*
* Registers the indexing function of CLR objects
* passed to Lua
*/
private void createIndexingMetaFunction(LuaCore.lua_State luaState)
private void createIndexingMetaFunction (LuaCore.lua_State luaState)
{
LuaLib.lua_pushstring(luaState, "luaNet_indexfunction");
LuaLib.luaL_dostring(luaState, MetaFunctions.luaIndexFunction); // steffenj: lua_dostring renamed to luaL_dostring
LuaLib.lua_pushstring (luaState, "luaNet_indexfunction");
LuaLib.luaL_dostring (luaState, MetaFunctions.luaIndexFunction); // steffenj: lua_dostring renamed to luaL_dostring
//LuaLib.lua_pushstdcallcfunction(luaState, indexFunction);
LuaLib.lua_rawset(luaState, (int)LuaIndexes.Registry);
LuaLib.lua_rawset (luaState, (int)LuaIndexes.Registry);
}
/*
* Creates the metatable for superclasses (the base
* field of registered tables)
*/
private void createBaseClassMetatable(LuaCore.lua_State luaState)
{
LuaLib.luaL_newmetatable(luaState, "luaNet_searchbase");
LuaLib.lua_pushstring(luaState, "__gc");
LuaLib.lua_pushstdcallcfunction(luaState, metaFunctions.gcFunction);
LuaLib.lua_settable(luaState, -3);
LuaLib.lua_pushstring(luaState, "__tostring");
LuaLib.lua_pushstdcallcfunction(luaState, metaFunctions.toStringFunction);
LuaLib.lua_settable(luaState, -3);
LuaLib.lua_pushstring(luaState, "__index");
LuaLib.lua_pushstdcallcfunction(luaState, metaFunctions.baseIndexFunction);
LuaLib.lua_settable(luaState, -3);
LuaLib.lua_pushstring(luaState, "__newindex");
LuaLib.lua_pushstdcallcfunction(luaState, metaFunctions.newindexFunction);
LuaLib.lua_settable(luaState, -3);
LuaLib.lua_settop(luaState, -2);
private void createBaseClassMetatable (LuaCore.lua_State luaState)
{
LuaLib.luaL_newmetatable (luaState, "luaNet_searchbase");
LuaLib.lua_pushstring (luaState, "__gc");
LuaLib.lua_pushstdcallcfunction (luaState, metaFunctions.gcFunction);
LuaLib.lua_settable (luaState, -3);
LuaLib.lua_pushstring (luaState, "__tostring");
LuaLib.lua_pushstdcallcfunction (luaState, metaFunctions.toStringFunction);
LuaLib.lua_settable (luaState, -3);
LuaLib.lua_pushstring (luaState, "__index");
LuaLib.lua_pushstdcallcfunction (luaState, metaFunctions.baseIndexFunction);
LuaLib.lua_settable (luaState, -3);
LuaLib.lua_pushstring (luaState, "__newindex");
LuaLib.lua_pushstdcallcfunction (luaState, metaFunctions.newindexFunction);
LuaLib.lua_settable (luaState, -3);
LuaLib.lua_settop (luaState, -2);
}
/*
* Creates the metatable for type references
*/
private void createClassMetatable(LuaCore.lua_State luaState)
{
LuaLib.luaL_newmetatable(luaState, "luaNet_class");
LuaLib.lua_pushstring(luaState, "__gc");
LuaLib.lua_pushstdcallcfunction(luaState, metaFunctions.gcFunction);
LuaLib.lua_settable(luaState, -3);
LuaLib.lua_pushstring(luaState, "__tostring");
LuaLib.lua_pushstdcallcfunction(luaState, metaFunctions.toStringFunction);
LuaLib.lua_settable(luaState, -3);
LuaLib.lua_pushstring(luaState, "__index");
LuaLib.lua_pushstdcallcfunction(luaState, metaFunctions.classIndexFunction);
LuaLib.lua_settable(luaState, -3);
LuaLib.lua_pushstring(luaState, "__newindex");
LuaLib.lua_pushstdcallcfunction(luaState, metaFunctions.classNewindexFunction);
LuaLib.lua_settable(luaState, -3);
LuaLib.lua_pushstring(luaState, "__call");
LuaLib.lua_pushstdcallcfunction(luaState, metaFunctions.callConstructorFunction);
LuaLib.lua_settable(luaState, -3);
LuaLib.lua_settop(luaState, -2);
private void createClassMetatable (LuaCore.lua_State luaState)
{
LuaLib.luaL_newmetatable (luaState, "luaNet_class");
LuaLib.lua_pushstring (luaState, "__gc");
LuaLib.lua_pushstdcallcfunction (luaState, metaFunctions.gcFunction);
LuaLib.lua_settable (luaState, -3);
LuaLib.lua_pushstring (luaState, "__tostring");
LuaLib.lua_pushstdcallcfunction (luaState, metaFunctions.toStringFunction);
LuaLib.lua_settable (luaState, -3);
LuaLib.lua_pushstring (luaState, "__index");
LuaLib.lua_pushstdcallcfunction (luaState, metaFunctions.classIndexFunction);
LuaLib.lua_settable (luaState, -3);
LuaLib.lua_pushstring (luaState, "__newindex");
LuaLib.lua_pushstdcallcfunction (luaState, metaFunctions.classNewindexFunction);
LuaLib.lua_settable (luaState, -3);
LuaLib.lua_pushstring (luaState, "__call");
LuaLib.lua_pushstdcallcfunction (luaState, metaFunctions.callConstructorFunction);
LuaLib.lua_settable (luaState, -3);
LuaLib.lua_settop (luaState, -2);
}
/*
* Registers the global functions used by LuaInterface
*/
private void setGlobalFunctions(LuaCore.lua_State luaState)
{
LuaLib.lua_pushstdcallcfunction(luaState, metaFunctions.indexFunction);
LuaLib.lua_setglobal(luaState, "get_object_member");
LuaLib.lua_pushstdcallcfunction(luaState, importTypeFunction);
LuaLib.lua_setglobal(luaState, "import_type");
LuaLib.lua_pushstdcallcfunction(luaState, loadAssemblyFunction);
LuaLib.lua_setglobal(luaState, "load_assembly");
LuaLib.lua_pushstdcallcfunction(luaState, registerTableFunction);
LuaLib.lua_setglobal(luaState, "make_object");
LuaLib.lua_pushstdcallcfunction(luaState, unregisterTableFunction);
LuaLib.lua_setglobal(luaState, "free_object");
LuaLib.lua_pushstdcallcfunction(luaState, getMethodSigFunction);
LuaLib.lua_setglobal(luaState, "get_method_bysig");
LuaLib.lua_pushstdcallcfunction(luaState, getConstructorSigFunction);
LuaLib.lua_setglobal(luaState, "get_constructor_bysig");
private void setGlobalFunctions (LuaCore.lua_State luaState)
{
LuaLib.lua_pushstdcallcfunction (luaState, metaFunctions.indexFunction);
LuaLib.lua_setglobal (luaState, "get_object_member");
LuaLib.lua_pushstdcallcfunction (luaState, importTypeFunction);
LuaLib.lua_setglobal (luaState, "import_type");
LuaLib.lua_pushstdcallcfunction (luaState, loadAssemblyFunction);
LuaLib.lua_setglobal (luaState, "load_assembly");
LuaLib.lua_pushstdcallcfunction (luaState, registerTableFunction);
LuaLib.lua_setglobal (luaState, "make_object");
LuaLib.lua_pushstdcallcfunction (luaState, unregisterTableFunction);
LuaLib.lua_setglobal (luaState, "free_object");
LuaLib.lua_pushstdcallcfunction (luaState, getMethodSigFunction);
LuaLib.lua_setglobal (luaState, "get_method_bysig");
LuaLib.lua_pushstdcallcfunction (luaState, getConstructorSigFunction);
LuaLib.lua_setglobal (luaState, "get_constructor_bysig");
}
/*
* Creates the metatable for delegates
*/
private void createFunctionMetatable(LuaCore.lua_State luaState)
private void createFunctionMetatable (LuaCore.lua_State luaState)
{
LuaLib.luaL_newmetatable(luaState, "luaNet_function");
LuaLib.lua_pushstring(luaState, "__gc");
LuaLib.lua_pushstdcallcfunction(luaState, metaFunctions.gcFunction);
LuaLib.lua_settable(luaState, -3);
LuaLib.lua_pushstring(luaState, "__call");
LuaLib.lua_pushstdcallcfunction(luaState, metaFunctions.execDelegateFunction);
LuaLib.lua_settable(luaState, -3);
LuaLib.lua_settop(luaState, -2);
LuaLib.luaL_newmetatable (luaState, "luaNet_function");
LuaLib.lua_pushstring (luaState, "__gc");
LuaLib.lua_pushstdcallcfunction (luaState, metaFunctions.gcFunction);
LuaLib.lua_settable (luaState, -3);
LuaLib.lua_pushstring (luaState, "__call");
LuaLib.lua_pushstdcallcfunction (luaState, metaFunctions.execDelegateFunction);
LuaLib.lua_settable (luaState, -3);
LuaLib.lua_settop (luaState, -2);
}
/*
* Passes errors (argument e) to the Lua interpreter
*/
internal void throwError(LuaCore.lua_State luaState, object e)
internal void throwError (LuaCore.lua_State luaState, object e)
{
// We use this to remove anything pushed by luaL_where
int oldTop = LuaLib.lua_gettop(luaState);
int oldTop = LuaLib.lua_gettop (luaState);
// Stack frame #1 is our C# wrapper, so not very interesting to the user
// Stack frame #2 must be the lua code that called us, so that's what we want to use
LuaLib.luaL_where(luaState, 1);
var curlev = popValues(luaState, oldTop);
LuaLib.luaL_where (luaState, 1);
var curlev = popValues (luaState, oldTop);
// Determine the position in the script where the exception was triggered
string errLocation = string.Empty;
if(curlev.Length > 0)
errLocation = curlev[0].ToString();
if (curlev.Length > 0)
errLocation = curlev [0].ToString ();
string message = e as string;
if(!message.IsNull())
{
if (!message.IsNull ()) {
// Wrap Lua error (just a string) and store the error location
e = new LuaScriptException(message, errLocation);
}
else
{
e = new LuaScriptException (message, errLocation);
} else {
var ex = e as Exception;
if(!ex.IsNull())
{
if (!ex.IsNull ()) {
// Wrap generic .NET exception as an InnerException and store the error location
e = new LuaScriptException(ex, errLocation);
e = new LuaScriptException (ex, errLocation);
}
}
push(luaState, e);
LuaLib.lua_error(luaState);
push (luaState, e);
LuaLib.lua_error (luaState);
}
/*
* Implementation of load_assembly. Throws an error
* if the assembly is not found.
*/
private int loadAssembly(LuaCore.lua_State luaState)
{
try
private int loadAssembly (LuaCore.lua_State luaState)
{
string assemblyName = LuaLib.lua_tostring(luaState, 1).ToString();
try {
string assemblyName = LuaLib.lua_tostring (luaState, 1).ToString ();
Assembly assembly = null;
try
{
assembly = Assembly.Load(assemblyName);
}
catch(BadImageFormatException)
{
try {
assembly = Assembly.Load (assemblyName);
} catch (BadImageFormatException) {
// The assemblyName was invalid. It is most likely a path.
}
if(assembly.IsNull())
assembly = Assembly.Load(AssemblyName.GetAssemblyName(assemblyName));
if (assembly.IsNull ())
assembly = Assembly.Load (AssemblyName.GetAssemblyName (assemblyName));
if(!assembly.IsNull() && !assemblies.Contains(assembly))
assemblies.Add(assembly);
}
catch(Exception e)
{
throwError(luaState, e);
if (!assembly.IsNull () && !assemblies.Contains (assembly))
assemblies.Add (assembly);
} catch (Exception e) {
throwError (luaState, e);
}
return 0;
}
internal Type FindType(string className)
{
foreach(var assembly in assemblies)
internal Type FindType (string className)
{
var klass = assembly.GetType(className);
foreach (var assembly in assemblies) {
var klass = assembly.GetType (className);
if(!klass.IsNull())
if (!klass.IsNull ())
return klass;
}
return null;
......@@ -283,15 +271,15 @@ namespace LuaInterface
* Implementation of import_type. Returns nil if the
* type is not found.
*/
private int importType(LuaCore.lua_State luaState)
private int importType (LuaCore.lua_State luaState)
{
string className = LuaLib.lua_tostring(luaState, 1).ToString();
var klass = FindType(className);
string className = LuaLib.lua_tostring (luaState, 1).ToString ();
var klass = FindType (className);
if(!klass.IsNull())
pushType(luaState, klass);
if (!klass.IsNull ())
pushType (luaState, klass);
else
LuaLib.lua_pushnil(luaState);
LuaLib.lua_pushnil (luaState);
return 1;
}
......@@ -301,46 +289,40 @@ namespace LuaInterface
* argument in the stack) as an object subclassing the
* type passed as second argument in the stack.
*/
private int registerTable(LuaCore.lua_State luaState)
private int registerTable (LuaCore.lua_State luaState)
{
if(LuaLib.lua_type(luaState, 1) == LuaTypes.Table)
{
var luaTable = getTable(luaState, 1);
string superclassName = LuaLib.lua_tostring(luaState, 2).ToString();
if (LuaLib.lua_type (luaState, 1) == LuaTypes.Table) {
var luaTable = getTable (luaState, 1);
string superclassName = LuaLib.lua_tostring (luaState, 2).ToString ();
if(!superclassName.IsNull())
{
var klass = FindType(superclassName);
if (!superclassName.IsNull ()) {
var klass = FindType (superclassName);
if(!klass.IsNull())
{
if (!klass.IsNull ()) {
// Creates and pushes the object in the stack, setting
// it as the metatable of the first argument
object obj = CodeGeneration.Instance.GetClassInstance(klass, luaTable);
pushObject(luaState, obj, "luaNet_metatable");
LuaLib.lua_newtable(luaState);
LuaLib.lua_pushstring(luaState, "__index");
LuaLib.lua_pushvalue(luaState, -3);
LuaLib.lua_settable(luaState, -3);
LuaLib.lua_pushstring(luaState, "__newindex");
LuaLib.lua_pushvalue(luaState, -3);
LuaLib.lua_settable(luaState, -3);
LuaLib.lua_setmetatable(luaState, 1);
object obj = CodeGeneration.Instance.GetClassInstance (klass, luaTable);
pushObject (luaState, obj, "luaNet_metatable");
LuaLib.lua_newtable (luaState);
LuaLib.lua_pushstring (luaState, "__index");
LuaLib.lua_pushvalue (luaState, -3);
LuaLib.lua_settable (luaState, -3);
LuaLib.lua_pushstring (luaState, "__newindex");
LuaLib.lua_pushvalue (luaState, -3);
LuaLib.lua_settable (luaState, -3);
LuaLib.lua_setmetatable (luaState, 1);
// Pushes the object again, this time as the base field
// of the table and with the luaNet_searchbase metatable
LuaLib.lua_pushstring(luaState, "base");
int index = addObject(obj);
pushNewObject(luaState, obj, index, "luaNet_searchbase");
LuaLib.lua_rawset(luaState, 1);
}
else
throwError(luaState, "register_table: can not find superclass '" + superclassName + "'");
}
else
throwError(luaState, "register_table: superclass name can not be null");
}
else
throwError(luaState, "register_table: first arg is not a table");
LuaLib.lua_pushstring (luaState, "base");
int index = addObject (obj);
pushNewObject (luaState, obj, index, "luaNet_searchbase");
LuaLib.lua_rawset (luaState, 1);
} else
throwError (luaState, "register_table: can not find superclass '" + superclassName + "'");
} else
throwError (luaState, "register_table: superclass name can not be null");
} else
throwError (luaState, "register_table: first arg is not a table");
return 0;
}
......@@ -349,37 +331,32 @@ namespace LuaInterface
* Implementation of free_object. Clears the metatable and the
* base field, freeing the created object for garbage-collection
*/
private int unregisterTable(LuaCore.lua_State luaState)
{
try
private int unregisterTable (LuaCore.lua_State luaState)
{
if(LuaLib.lua_getmetatable(luaState, 1) != 0)
{
LuaLib.lua_pushstring(luaState, "__index");
LuaLib.lua_gettable(luaState, -2);
object obj = getRawNetObject(luaState, -1);
try {
if (LuaLib.lua_getmetatable (luaState, 1) != 0) {
LuaLib.lua_pushstring (luaState, "__index");
LuaLib.lua_gettable (luaState, -2);
object obj = getRawNetObject (luaState, -1);
if(obj.IsNull())
throwError(luaState, "unregister_table: arg is not valid table");
if (obj.IsNull ())
throwError (luaState, "unregister_table: arg is not valid table");
var luaTableField = obj.GetType().GetField("__luaInterface_luaTable");
var luaTableField = obj.GetType ().GetField ("__luaInterface_luaTable");
if(luaTableField.IsNull())
throwError(luaState, "unregister_table: arg is not valid table");
if (luaTableField.IsNull ())
throwError (luaState, "unregister_table: arg is not valid table");
luaTableField.SetValue(obj, null);
LuaLib.lua_pushnil(luaState);
LuaLib.lua_setmetatable(luaState, 1);
LuaLib.lua_pushstring(luaState, "base");
LuaLib.lua_pushnil(luaState);
LuaLib.lua_settable(luaState, 1);
}
else
throwError(luaState, "unregister_table: arg is not valid table");
}
catch(Exception e)
{
throwError(luaState, e.Message);
luaTableField.SetValue (obj, null);
LuaLib.lua_pushnil (luaState);
LuaLib.lua_setmetatable (luaState, 1);
LuaLib.lua_pushstring (luaState, "base");
LuaLib.lua_pushnil (luaState);
LuaLib.lua_settable (luaState, 1);
} else
throwError (luaState, "unregister_table: arg is not valid table");
} catch (Exception e) {
throwError (luaState, e.Message);
}
return 0;
......@@ -389,48 +366,41 @@ namespace LuaInterface
* Implementation of get_method_bysig. Returns nil
* if no matching method is not found.
*/
private int getMethodSignature(LuaCore.lua_State luaState)
private int getMethodSignature (LuaCore.lua_State luaState)
{
IReflect klass;
object target;
int udata = LuaLib.luanet_checkudata(luaState, 1, "luaNet_class");
int udata = LuaLib.luanet_checkudata (luaState, 1, "luaNet_class");
if(udata != -1)
{
klass = (IReflect)objects[udata];
if (udata != -1) {
klass = (IReflect)objects [udata];
target = null;
}
else
{
target = getRawNetObject(luaState, 1);
} else {
target = getRawNetObject (luaState, 1);
if(target.IsNull())
{
throwError(luaState, "get_method_bysig: first arg is not type or object reference");
LuaLib.lua_pushnil(luaState);
if (target.IsNull ()) {
throwError (luaState, "get_method_bysig: first arg is not type or object reference");
LuaLib.lua_pushnil (luaState);
return 1;
}
klass = target.GetType();
klass = target.GetType ();
}
string methodName = LuaLib.lua_tostring(luaState, 2).ToString();
var signature = new Type[LuaLib.lua_gettop(luaState)-2];
string methodName = LuaLib.lua_tostring (luaState, 2).ToString ();
var signature = new Type[LuaLib.lua_gettop (luaState) - 2];
for(int i = 0; i < signature.Length; i++)
signature[i] = FindType(LuaLib.lua_tostring(luaState, i+3).ToString());
for (int i = 0; i < signature.Length; i++)
signature [i] = FindType (LuaLib.lua_tostring (luaState, i + 3).ToString ());
try
{
try {
//CP: Added ignore case
var method = klass.GetMethod(methodName, BindingFlags.Public | BindingFlags.Static |
var method = klass.GetMethod (methodName, BindingFlags.Public | BindingFlags.Static |
BindingFlags.Instance | BindingFlags.FlattenHierarchy | BindingFlags.IgnoreCase, null, signature, null);
pushFunction(luaState, new LuaCore.lua_CFunction((new LuaMethodWrapper(this, target, klass, method)).call));
}
catch(Exception e)
{
throwError(luaState, e);
LuaLib.lua_pushnil(luaState);
pushFunction (luaState, new LuaCore.lua_CFunction ((new LuaMethodWrapper (this, target, klass, method)).call));
} catch (Exception e) {
throwError (luaState, e);
LuaLib.lua_pushnil (luaState);
}
return 1;
......@@ -440,31 +410,28 @@ namespace LuaInterface
* Implementation of get_constructor_bysig. Returns nil
* if no matching constructor is found.
*/
private int getConstructorSignature(LuaCore.lua_State luaState)
private int getConstructorSignature (LuaCore.lua_State luaState)
{
IReflect klass = null;
int udata = LuaLib.luanet_checkudata(luaState, 1, "luaNet_class");
int udata = LuaLib.luanet_checkudata (luaState, 1, "luaNet_class");
if(udata != -1)
klass = (IReflect)objects[udata];
if (udata != -1)
klass = (IReflect)objects [udata];
if(klass.IsNull())
throwError(luaState, "get_constructor_bysig: first arg is invalid type reference");
if (klass.IsNull ())
throwError (luaState, "get_constructor_bysig: first arg is invalid type reference");
var signature = new Type[LuaLib.lua_gettop(luaState)-1];
var signature = new Type[LuaLib.lua_gettop (luaState) - 1];
for(int i = 0; i < signature.Length; i++)
signature[i] = FindType(LuaLib.lua_tostring(luaState, i+2).ToString());
for (int i = 0; i < signature.Length; i++)
signature [i] = FindType (LuaLib.lua_tostring (luaState, i + 2).ToString ());
try
{
ConstructorInfo constructor = klass.UnderlyingSystemType.GetConstructor(signature);
pushFunction(luaState, new LuaCore.lua_CFunction((new LuaMethodWrapper(this, null, klass, constructor)).call));
}
catch(Exception e)
{
throwError(luaState, e);
LuaLib.lua_pushnil(luaState);
try {
ConstructorInfo constructor = klass.UnderlyingSystemType.GetConstructor (signature);
pushFunction (luaState, new LuaCore.lua_CFunction ((new LuaMethodWrapper (this, null, klass, constructor)).call));
} catch (Exception e) {
throwError (luaState, e);
LuaLib.lua_pushnil (luaState);
}
return 1;
......@@ -473,140 +440,133 @@ namespace LuaInterface
/*
* Pushes a type reference into the stack
*/
internal void pushType(LuaCore.lua_State luaState, Type t)
internal void pushType (LuaCore.lua_State luaState, Type t)
{
pushObject(luaState, new ProxyType(t), "luaNet_class");
pushObject (luaState, new ProxyType (t), "luaNet_class");
}
/*
* Pushes a delegate into the stack
*/
internal void pushFunction(LuaCore.lua_State luaState, LuaCore.lua_CFunction func)
internal void pushFunction (LuaCore.lua_State luaState, LuaCore.lua_CFunction func)
{
pushObject(luaState, func, "luaNet_function");
pushObject (luaState, func, "luaNet_function");
}
/*
* Pushes a CLR object into the Lua stack as an userdata
* with the provided metatable
*/
internal void pushObject(LuaCore.lua_State luaState, object o, string metatable)
internal void pushObject (LuaCore.lua_State luaState, object o, string metatable)
{
int index = -1;
// Pushes nil
if(o.IsNull())
{
LuaLib.lua_pushnil(luaState);
if (o.IsNull ()) {
LuaLib.lua_pushnil (luaState);
return;
}
// Object already in the list of Lua objects? Push the stored reference.
bool found = objectsBackMap.TryGetValue(o, out index);
bool found = objectsBackMap.TryGetValue (o, out index);
if(found)
{
LuaLib.luaL_getmetatable(luaState, "luaNet_objects");
LuaLib.lua_rawgeti(luaState, -1, index);
if (found) {
LuaLib.luaL_getmetatable (luaState, "luaNet_objects");
LuaLib.lua_rawgeti (luaState, -1, index);
// Note: starting with lua5.1 the garbage collector may remove weak reference items (such as our luaNet_objects values) when the initial GC sweep
// occurs, but the actual call of the __gc finalizer for that object may not happen until a little while later. During that window we might call
// this routine and find the element missing from luaNet_objects, but collectObject() has not yet been called. In that case, we go ahead and call collect
// object here
// did we find a non nil object in our table? if not, we need to call collect object
var type = LuaLib.lua_type(luaState, -1);
if(type != LuaTypes.Nil)
{
LuaLib.lua_remove(luaState, -2); // drop the metatable - we're going to leave our object on the stack
var type = LuaLib.lua_type (luaState, -1);
if (type != LuaTypes.Nil) {
LuaLib.lua_remove (luaState, -2); // drop the metatable - we're going to leave our object on the stack
return;
}
// MetaFunctions.dumpStack(this, luaState);
LuaLib.lua_remove(luaState, -1); // remove the nil object value
LuaLib.lua_remove(luaState, -1); // remove the metatable
collectObject(o, index); // Remove from both our tables and fall out to get a new ID
LuaLib.lua_remove (luaState, -1); // remove the nil object value
LuaLib.lua_remove (luaState, -1); // remove the metatable
collectObject (o, index); // Remove from both our tables and fall out to get a new ID
}
index = addObject(o);
pushNewObject(luaState, o, index, metatable);
index = addObject (o);
pushNewObject (luaState, o, index, metatable);
}
/*
* Pushes a new object into the Lua stack with the provided
* metatable
*/
private void pushNewObject(LuaCore.lua_State luaState, object o, int index, string metatable)
{
if(metatable == "luaNet_metatable")
private void pushNewObject (LuaCore.lua_State luaState, object o, int index, string metatable)
{
if (metatable == "luaNet_metatable") {
// Gets or creates the metatable for the object's type
LuaLib.luaL_getmetatable(luaState, o.GetType().AssemblyQualifiedName);
if(LuaLib.lua_isnil(luaState, -1))
{
LuaLib.lua_settop(luaState, -2);
LuaLib.luaL_newmetatable(luaState, o.GetType().AssemblyQualifiedName);
LuaLib.lua_pushstring(luaState, "cache");
LuaLib.lua_newtable(luaState);
LuaLib.lua_rawset(luaState, -3);
LuaLib.lua_pushlightuserdata(luaState, LuaLib.luanet_gettag());
LuaLib.lua_pushnumber(luaState, 1);
LuaLib.lua_rawset(luaState, -3);
LuaLib.lua_pushstring(luaState, "__index");
LuaLib.lua_pushstring(luaState, "luaNet_indexfunction");
LuaLib.lua_rawget(luaState, (int)LuaIndexes.Registry);
LuaLib.lua_rawset(luaState, -3);
LuaLib.lua_pushstring(luaState, "__gc");
LuaLib.lua_pushstdcallcfunction(luaState, metaFunctions.gcFunction);
LuaLib.lua_rawset(luaState, -3);
LuaLib.lua_pushstring(luaState, "__tostring");
LuaLib.lua_pushstdcallcfunction(luaState, metaFunctions.toStringFunction);
LuaLib.lua_rawset(luaState, -3);
LuaLib.lua_pushstring(luaState, "__newindex");
LuaLib.lua_pushstdcallcfunction(luaState, metaFunctions.newindexFunction);
LuaLib.lua_rawset(luaState, -3);
}
}
else
LuaLib.luaL_getmetatable(luaState, metatable);
LuaLib.luaL_getmetatable (luaState, o.GetType ().AssemblyQualifiedName);
if (LuaLib.lua_isnil (luaState, -1)) {
LuaLib.lua_settop (luaState, -2);
LuaLib.luaL_newmetatable (luaState, o.GetType ().AssemblyQualifiedName);
LuaLib.lua_pushstring (luaState, "cache");
LuaLib.lua_newtable (luaState);
LuaLib.lua_rawset (luaState, -3);
LuaLib.lua_pushlightuserdata (luaState, LuaLib.luanet_gettag ());
LuaLib.lua_pushnumber (luaState, 1);
LuaLib.lua_rawset (luaState, -3);
LuaLib.lua_pushstring (luaState, "__index");
LuaLib.lua_pushstring (luaState, "luaNet_indexfunction");
LuaLib.lua_rawget (luaState, (int)LuaIndexes.Registry);
LuaLib.lua_rawset (luaState, -3);
LuaLib.lua_pushstring (luaState, "__gc");
LuaLib.lua_pushstdcallcfunction (luaState, metaFunctions.gcFunction);
LuaLib.lua_rawset (luaState, -3);
LuaLib.lua_pushstring (luaState, "__tostring");
LuaLib.lua_pushstdcallcfunction (luaState, metaFunctions.toStringFunction);
LuaLib.lua_rawset (luaState, -3);
LuaLib.lua_pushstring (luaState, "__newindex");
LuaLib.lua_pushstdcallcfunction (luaState, metaFunctions.newindexFunction);
LuaLib.lua_rawset (luaState, -3);
}
} else
LuaLib.luaL_getmetatable (luaState, metatable);
// Stores the object index in the Lua list and pushes the
// index into the Lua stack
LuaLib.luaL_getmetatable(luaState, "luaNet_objects");
LuaLib.luanet_newudata(luaState, index);
LuaLib.lua_pushvalue(luaState, -3);
LuaLib.lua_remove(luaState, -4);
LuaLib.lua_setmetatable(luaState, -2);
LuaLib.lua_pushvalue(luaState, -1);
LuaLib.lua_rawseti(luaState, -3, index);
LuaLib.lua_remove(luaState, -2);
LuaLib.luaL_getmetatable (luaState, "luaNet_objects");
LuaLib.luanet_newudata (luaState, index);
LuaLib.lua_pushvalue (luaState, -3);
LuaLib.lua_remove (luaState, -4);
LuaLib.lua_setmetatable (luaState, -2);
LuaLib.lua_pushvalue (luaState, -1);
LuaLib.lua_rawseti (luaState, -3, index);
LuaLib.lua_remove (luaState, -2);
}
/*
* Gets an object from the Lua stack with the desired type, if it matches, otherwise
* returns null.
*/
internal object getAsType(LuaCore.lua_State luaState, int stackPos, Type paramType)
internal object getAsType (LuaCore.lua_State luaState, int stackPos, Type paramType)
{
var extractor = typeChecker.checkType(luaState, stackPos, paramType);
return !extractor.IsNull() ? extractor(luaState, stackPos) : null;
var extractor = typeChecker.checkType (luaState, stackPos, paramType);
return !extractor.IsNull () ? extractor (luaState, stackPos) : null;
}
/// <summary>
/// Given the Lua int ID for an object remove it from our maps
/// </summary>
/// <param name = "udata"></param>
internal void collectObject(int udata)
internal void collectObject (int udata)
{
object o;
bool found = objects.TryGetValue(udata, out o);
bool found = objects.TryGetValue (udata, out o);
// The other variant of collectObject might have gotten here first, in that case we will silently ignore the missing entry
if(found)
{
if (found) {
// Debug.WriteLine("Removing " + o.ToString() + " @ " + udata);
objects.Remove(udata);
objectsBackMap.Remove(o);
objects.Remove (udata);
objectsBackMap.Remove (o);
}
}
......@@ -614,56 +574,55 @@ namespace LuaInterface
/// Given an object reference, remove it from our maps
/// </summary>
/// <param name = "udata"></param>
private void collectObject(object o, int udata)
private void collectObject (object o, int udata)
{
// Debug.WriteLine("Removing " + o.ToString() + " @ " + udata);
objects.Remove(udata);
objectsBackMap.Remove(o);
objects.Remove (udata);
objectsBackMap.Remove (o);
}
private int addObject(object obj)
private int addObject (object obj)
{
// New object: inserts it in the list
int index = nextObj++;
// Debug.WriteLine("Adding " + obj.ToString() + " @ " + index);
objects[index] = obj;
objectsBackMap[obj] = index;
objects [index] = obj;
objectsBackMap [obj] = index;
return index;
}
/*
* Gets an object from the Lua stack according to its Lua type.
*/
internal object getObject(LuaCore.lua_State luaState, int index)
internal object getObject (LuaCore.lua_State luaState, int index)
{
var type = LuaLib.lua_type(luaState, index);
var type = LuaLib.lua_type (luaState, index);
switch(type)
{
switch (type) {
case LuaTypes.Number:
{
return LuaLib.lua_tonumber(luaState, index);
return LuaLib.lua_tonumber (luaState, index);
}
case LuaTypes.String:
{
return LuaLib.lua_tostring(luaState, index);
return LuaLib.lua_tostring (luaState, index);
}
case LuaTypes.Boolean:
{
return LuaLib.lua_toboolean(luaState, index);
return LuaLib.lua_toboolean (luaState, index);
}
case LuaTypes.Table:
{
return getTable(luaState, index);
return getTable (luaState, index);
}
case LuaTypes.Function:
{
return getFunction(luaState, index);
return getFunction (luaState, index);
}
case LuaTypes.UserData:
{
int udata = LuaLib.luanet_tonetobject(luaState, index);
return udata != -1 ? objects[udata] : getUserData(luaState, index);
int udata = LuaLib.luanet_tonetobject (luaState, index);
return udata != -1 ? objects [udata] : getUserData (luaState, index);
}
default:
return null;
......@@ -673,64 +632,62 @@ namespace LuaInterface
/*
* Gets the table in the index positon of the Lua stack.
*/
internal LuaTable getTable(LuaCore.lua_State luaState, int index)
internal LuaTable getTable (LuaCore.lua_State luaState, int index)
{
LuaLib.lua_pushvalue(luaState, index);
return new LuaTable(LuaLib.lua_ref(luaState, 1), interpreter);
LuaLib.lua_pushvalue (luaState, index);
return new LuaTable (LuaLib.lua_ref (luaState, 1), interpreter);
}
/*
* Gets the userdata in the index positon of the Lua stack.
*/
internal LuaUserData getUserData(LuaCore.lua_State luaState, int index)
internal LuaUserData getUserData (LuaCore.lua_State luaState, int index)
{
LuaLib.lua_pushvalue(luaState, index);
return new LuaUserData(LuaLib.lua_ref(luaState, 1), interpreter);
LuaLib.lua_pushvalue (luaState, index);
return new LuaUserData (LuaLib.lua_ref (luaState, 1), interpreter);
}
/*
* Gets the function in the index positon of the Lua stack.
*/
internal LuaFunction getFunction(LuaCore.lua_State luaState, int index)
internal LuaFunction getFunction (LuaCore.lua_State luaState, int index)
{
LuaLib.lua_pushvalue(luaState, index);
return new LuaFunction(LuaLib.lua_ref(luaState, 1), interpreter);
LuaLib.lua_pushvalue (luaState, index);
return new LuaFunction (LuaLib.lua_ref (luaState, 1), interpreter);
}
/*
* Gets the CLR object in the index positon of the Lua stack. Returns
* delegates as Lua functions.
*/
internal object getNetObject(LuaCore.lua_State luaState, int index)
internal object getNetObject (LuaCore.lua_State luaState, int index)
{
int idx = LuaLib.luanet_tonetobject(luaState, index);
return idx != -1 ? objects[idx] : null;
int idx = LuaLib.luanet_tonetobject (luaState, index);
return idx != -1 ? objects [idx] : null;
}
/*
* Gets the CLR object in the index positon of the Lua stack. Returns
* delegates as is.
*/
internal object getRawNetObject(LuaCore.lua_State luaState, int index)
internal object getRawNetObject (LuaCore.lua_State luaState, int index)
{
int udata = LuaLib.luanet_rawnetobj(luaState, index);
return udata != -1 ? objects[udata] : null;
int udata = LuaLib.luanet_rawnetobj (luaState, index);
return udata != -1 ? objects [udata] : null;
}
/*
* Pushes the entire array into the Lua stack and returns the number
* of elements pushed.
*/
internal int returnValues(LuaCore.lua_State luaState, object[] returnValues)
internal int returnValues (LuaCore.lua_State luaState, object[] returnValues)
{
if(LuaLib.lua_checkstack(luaState, returnValues.Length+5))
{
for(int i = 0; i < returnValues.Length; i++)
push(luaState, returnValues[i]);
if (LuaLib.lua_checkstack (luaState, returnValues.Length + 5)) {
for (int i = 0; i < returnValues.Length; i++)
push (luaState, returnValues [i]);
return returnValues.Length;
}
else
} else
return 0;
}
......@@ -738,20 +695,19 @@ namespace LuaInterface
* Gets the values from the provided index to
* the top of the stack and returns them in an array.
*/
internal object[] popValues(LuaCore.lua_State luaState, int oldTop)
internal object[] popValues (LuaCore.lua_State luaState, int oldTop)
{
int newTop = LuaLib.lua_gettop(luaState);
int newTop = LuaLib.lua_gettop (luaState);
if(oldTop == newTop)
if (oldTop == newTop)
return null;
else
{
var returnValues = new ArrayList();
for(int i = oldTop+1; i <= newTop; i++)
returnValues.Add(getObject(luaState, i));
else {
var returnValues = new ArrayList ();
for (int i = oldTop+1; i <= newTop; i++)
returnValues.Add (getObject (luaState, i));
LuaLib.lua_settop(luaState, oldTop);
return returnValues.ToArray();
LuaLib.lua_settop (luaState, oldTop);
return returnValues.ToArray ();
}
}
......@@ -760,95 +716,83 @@ namespace LuaInterface
* the top of the stack and returns them in an array, casting
* them to the provided types.
*/
internal object[] popValues(LuaCore.lua_State luaState, int oldTop, Type[] popTypes)
internal object[] popValues (LuaCore.lua_State luaState, int oldTop, Type[] popTypes)
{
int newTop = LuaLib.lua_gettop(luaState);
int newTop = LuaLib.lua_gettop (luaState);
if(oldTop == newTop)
if (oldTop == newTop)
return null;
else
{
else {
int iTypes;
var returnValues = new ArrayList();
var returnValues = new ArrayList ();
if(popTypes[0] == typeof(void))
if (popTypes [0] == typeof(void))
iTypes = 1;
else
iTypes = 0;
for(int i = oldTop+1; i <= newTop; i++)
{
returnValues.Add(getAsType(luaState, i, popTypes[iTypes]));
for (int i = oldTop+1; i <= newTop; i++) {
returnValues.Add (getAsType (luaState, i, popTypes [iTypes]));
iTypes++;
}
LuaLib.lua_settop(luaState, oldTop);
return returnValues.ToArray();
LuaLib.lua_settop (luaState, oldTop);
return returnValues.ToArray ();
}
}
// kevinh - the following line doesn't work for remoting proxies - they always return a match for 'is'
// else if(o is ILuaGeneratedType)
private static bool IsILua(object o)
{
if(o is ILuaGeneratedType)
private static bool IsILua (object o)
{
if (o is ILuaGeneratedType) {
// Make sure we are _really_ ILuaGenerated
var typ = o.GetType();
return (!typ.GetInterface("ILuaGeneratedType").IsNull ());
}
else
var typ = o.GetType ();
return (!typ.GetInterface ("ILuaGeneratedType").IsNull ());
} else
return false;
}
/*
* Pushes the object into the Lua stack according to its type.
*/
internal void push(LuaCore.lua_State luaState, object o)
internal void push (LuaCore.lua_State luaState, object o)
{
if(o.IsNull())
LuaLib.lua_pushnil(luaState);
else if(o is sbyte || o is byte || o is short || o is ushort ||
if (o.IsNull ())
LuaLib.lua_pushnil (luaState);
else if (o is sbyte || o is byte || o is short || o is ushort ||
o is int || o is uint || o is long || o is float ||
o is ulong || o is decimal || o is double)
{
double d = Convert.ToDouble(o);
LuaLib.lua_pushnumber(luaState, d);
}
else if(o is char)
{
o is ulong || o is decimal || o is double) {
double d = Convert.ToDouble (o);
LuaLib.lua_pushnumber (luaState, d);
} else if (o is char) {
double d = (char)o;
LuaLib.lua_pushnumber(luaState, d);
}
else if(o is string)
{
LuaLib.lua_pushnumber (luaState, d);
} else if (o is string) {
string str = (string)o;
LuaLib.lua_pushstring(luaState, str);
}
else if(o is bool)
{
LuaLib.lua_pushstring (luaState, str);
} else if (o is bool) {
bool b = (bool)o;
LuaLib.lua_pushboolean(luaState, b);
}
else if(IsILua(o))
(((ILuaGeneratedType)o).__luaInterface_getLuaTable()).push(luaState);
else if(o is LuaTable)
((LuaTable)o).push(luaState);
else if(o is LuaCore.lua_CFunction)
pushFunction(luaState, (LuaCore.lua_CFunction)o);
else if(o is LuaFunction)
((LuaFunction)o).push(luaState);
LuaLib.lua_pushboolean (luaState, b);
} else if (IsILua (o))
(((ILuaGeneratedType)o).__luaInterface_getLuaTable ()).push (luaState);
else if (o is LuaTable)
((LuaTable)o).push (luaState);
else if (o is LuaCore.lua_CFunction)
pushFunction (luaState, (LuaCore.lua_CFunction)o);
else if (o is LuaFunction)
((LuaFunction)o).push (luaState);
else
pushObject(luaState, o, "luaNet_metatable");
pushObject (luaState, o, "luaNet_metatable");
}
/*
* Checks if the method matches the arguments in the Lua stack, getting
* the arguments if it does.
*/
internal bool matchParameters(LuaCore.lua_State luaState, MethodBase method, ref MethodCache methodCache)
internal bool matchParameters (LuaCore.lua_State luaState, MethodBase method, ref MethodCache methodCache)
{
return metaFunctions.matchParameters(luaState, method, ref methodCache);
return metaFunctions.matchParameters (luaState, method, ref methodCache);
}
}
}
\ No newline at end of file
......@@ -22,7 +22,6 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
......
......@@ -22,7 +22,6 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Globalization;
using System.Reflection;
......@@ -38,7 +37,7 @@ namespace LuaInterface
{
private Type proxy;
public ProxyType(Type proxy)
public ProxyType (Type proxy)
{
this.proxy = proxy;
}
......@@ -47,69 +46,68 @@ namespace LuaInterface
/// Provide human readable short hand for this proxy object
/// </summary>
/// <returns></returns>
public override string ToString()
public override string ToString ()
{
return "ProxyType(" + UnderlyingSystemType + ")";
}
public Type UnderlyingSystemType
{
public Type UnderlyingSystemType {
get { return proxy; }
}
public FieldInfo GetField(string name, BindingFlags bindingAttr)
public FieldInfo GetField (string name, BindingFlags bindingAttr)
{
return proxy.GetField(name, bindingAttr);
return proxy.GetField (name, bindingAttr);
}
public FieldInfo[] GetFields(BindingFlags bindingAttr)
public FieldInfo[] GetFields (BindingFlags bindingAttr)
{
return proxy.GetFields(bindingAttr);
return proxy.GetFields (bindingAttr);
}
public MemberInfo[] GetMember(string name, BindingFlags bindingAttr)
public MemberInfo[] GetMember (string name, BindingFlags bindingAttr)
{
return proxy.GetMember(name, bindingAttr);
return proxy.GetMember (name, bindingAttr);
}
public MemberInfo[] GetMembers(BindingFlags bindingAttr)
public MemberInfo[] GetMembers (BindingFlags bindingAttr)
{
return proxy.GetMembers(bindingAttr);
return proxy.GetMembers (bindingAttr);
}
public MethodInfo GetMethod(string name, BindingFlags bindingAttr)
public MethodInfo GetMethod (string name, BindingFlags bindingAttr)
{
return proxy.GetMethod(name, bindingAttr);
return proxy.GetMethod (name, bindingAttr);
}
public MethodInfo GetMethod(string name, BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers)
public MethodInfo GetMethod (string name, BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers)
{
return proxy.GetMethod(name, bindingAttr, binder, types, modifiers);
return proxy.GetMethod (name, bindingAttr, binder, types, modifiers);
}
public MethodInfo[] GetMethods(BindingFlags bindingAttr)
public MethodInfo[] GetMethods (BindingFlags bindingAttr)
{
return proxy.GetMethods(bindingAttr);
return proxy.GetMethods (bindingAttr);
}
public PropertyInfo GetProperty(string name, BindingFlags bindingAttr)
public PropertyInfo GetProperty (string name, BindingFlags bindingAttr)
{
return proxy.GetProperty(name, bindingAttr);
return proxy.GetProperty (name, bindingAttr);
}
public PropertyInfo GetProperty(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers)
public PropertyInfo GetProperty (string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers)
{
return proxy.GetProperty(name, bindingAttr, binder, returnType, types, modifiers);
return proxy.GetProperty (name, bindingAttr, binder, returnType, types, modifiers);
}
public PropertyInfo[] GetProperties(BindingFlags bindingAttr)
public PropertyInfo[] GetProperties (BindingFlags bindingAttr)
{
return proxy.GetProperties(bindingAttr);
return proxy.GetProperties (bindingAttr);
}
public object InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters)
public object InvokeMember (string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters)
{
return proxy.InvokeMember(name, invokeAttr, binder, target, args, modifiers, culture, namedParameters);
return proxy.InvokeMember (name, invokeAttr, binder, target, args, modifiers, culture, namedParameters);
}
}
}
\ 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