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

Mono-style format.

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