Commit 27e4f04c authored by Vinicius Jarina's avatar Vinicius Jarina
Browse files

Fixed call delegate functions.

Automatically register metamethod __call for delegate types.
+ Unit tests.
parent d7f1849b
......@@ -10,14 +10,17 @@ using NLuaTest;
namespace ConsoleTest
{
public class Program
{
static void Main (string [] args)
{
Core c = new Core ();
c.Setup ();
c.Sieve ();
using (var l = new Lua ()) {
Action c = () => { Console.WriteLine ("Ola"); };
l ["d"] = c;
l.DoString (" d () ");
}
}
}
}
/*
* This file is part of NLua.
* Copyright (C) 2014 Vinicius Jarina.
* Copyright (C) 2003-2005 Fabio Mascarenhas de Queiroz.
* Copyright (C) 2012 Megax <http://megax.yeahunter.hu/>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Linq;
using System.IO;
using System.Collections;
using System.Reflection;
using System.Diagnostics;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using NLua.Method;
using NLua.Extensions;
namespace NLua
{
#if USE_KOPILUA
using LuaCore = KopiLua.Lua;
using LuaState = KopiLua.LuaState;
using LuaNativeFunction = KopiLua.LuaNativeFunction;
#else
using LuaCore = KeraLua.Lua;
using LuaState = KeraLua.LuaState;
using LuaNativeFunction = KeraLua.LuaNativeFunction;
#endif
/*
* Functions used in the metatables of userdata representing
* CLR objects
*
*/
public class MetaFunctions
{
public LuaNativeFunction GcFunction { get; private set; }
public LuaNativeFunction IndexFunction { get; private set; }
public LuaNativeFunction NewIndexFunction { get; private set; }
public LuaNativeFunction BaseIndexFunction { get; private set; }
public LuaNativeFunction ClassIndexFunction { get; private set; }
public LuaNativeFunction ClassNewindexFunction { get; private set; }
public LuaNativeFunction ExecuteDelegateFunction { get; private set; }
public LuaNativeFunction CallConstructorFunction { get; private set; }
public LuaNativeFunction ToStringFunction { get; private set; }
public LuaNativeFunction AddFunction { get; private set; }
public LuaNativeFunction SubtractFunction { get; private set; }
public LuaNativeFunction MultiplyFunction { get; private set; }
public LuaNativeFunction DivisionFunction { get; private set; }
public LuaNativeFunction ModulosFunction { get; private set; }
public LuaNativeFunction UnaryNegationFunction { get; private set; }
public LuaNativeFunction EqualFunction { get; private set; }
public LuaNativeFunction LessThanFunction { get; private set; }
public LuaNativeFunction LessThanOrEqualFunction { get; private set; }
Dictionary<object, object> memberCache = new Dictionary<object, object> ();
ObjectTranslator translator;
/*
* __index metafunction for CLR objects. Implemented in Lua.
*/
static string luaIndexFunction =
@"local function index(obj,name)
local meta = getmetatable(obj)
local cached = meta.cache[name]
if cached ~= nil then
return cached
else
local value,isFunc = get_object_member(obj,name)
if isFunc then
meta.cache[name]=value
end
return value
end
end
return index";
public static string LuaIndexFunction {
get { return luaIndexFunction; }
}
public MetaFunctions (ObjectTranslator translator)
{
this.translator = translator;
GcFunction = new LuaNativeFunction (MetaFunctions.CollectObject);
ToStringFunction = new LuaNativeFunction (MetaFunctions.ToStringLua);
IndexFunction = new LuaNativeFunction (MetaFunctions.GetMethod);
NewIndexFunction = new LuaNativeFunction (MetaFunctions.SetFieldOrProperty);
BaseIndexFunction = new LuaNativeFunction (MetaFunctions.GetBaseMethod);
CallConstructorFunction = new LuaNativeFunction (MetaFunctions.CallConstructor);
ClassIndexFunction = new LuaNativeFunction (MetaFunctions.GetClassMethod);
ClassNewindexFunction = new LuaNativeFunction (MetaFunctions.SetClassFieldOrProperty);
ExecuteDelegateFunction = new LuaNativeFunction (MetaFunctions.RunFunctionDelegate);
AddFunction = new LuaNativeFunction (MetaFunctions.AddLua);
SubtractFunction = new LuaNativeFunction (MetaFunctions.SubtractLua);
MultiplyFunction = new LuaNativeFunction (MetaFunctions.MultiplyLua);
DivisionFunction = new LuaNativeFunction (MetaFunctions.DivideLua);
ModulosFunction = new LuaNativeFunction (MetaFunctions.ModLua);
UnaryNegationFunction = new LuaNativeFunction (MetaFunctions.UnaryNegationLua);
EqualFunction = new LuaNativeFunction (MetaFunctions.EqualLua);
LessThanFunction = new LuaNativeFunction (MetaFunctions.LessThanLua);
LessThanOrEqualFunction = new LuaNativeFunction (MetaFunctions.LessThanOrEqualLua);
}
/*
* __call metafunction of CLR delegates, retrieves and calls the delegate.
*/
#if MONOTOUCH
[MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
#endif
private static int RunFunctionDelegate (LuaState luaState)
{
var translator = ObjectTranslatorPool.Instance.Find (luaState);
return RunFunctionDelegate (luaState, translator);
}
private static int RunFunctionDelegate (LuaState luaState, ObjectTranslator translator)
{
LuaNativeFunction func = (LuaNativeFunction)translator.GetRawNetObject (luaState, 1);
LuaLib.LuaRemove (luaState, 1);
return func (luaState);
}
/*
* __gc metafunction of CLR objects.
*/
#if MONOTOUCH
[MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
#endif
private static int CollectObject (LuaState luaState)
{
var translator = ObjectTranslatorPool.Instance.Find (luaState);
return CollectObject (luaState, translator);
}
private static int CollectObject (LuaState luaState, ObjectTranslator translator)
{
int udata = LuaLib.LuaNetRawNetObj (luaState, 1);
if (udata != -1)
translator.CollectObject (udata);
return 0;
}
/*
* __tostring metafunction of CLR objects.
*/
#if MONOTOUCH
[MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
#endif
private static int ToStringLua (LuaState luaState)
{
var translator = ObjectTranslatorPool.Instance.Find (luaState);
return ToStringLua (luaState, translator);
}
private static int ToStringLua (LuaState luaState, ObjectTranslator translator)
{
object obj = translator.GetRawNetObject (luaState, 1);
if (obj != null)
translator.Push (luaState, obj.ToString () + ": " + obj.GetHashCode ().ToString());
else
LuaLib.LuaPushNil (luaState);
return 1;
}
/*
* __add metafunction of CLR objects.
*/
#if MONOTOUCH
[MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
#endif
static int AddLua (LuaState luaState)
{
var translator = ObjectTranslatorPool.Instance.Find (luaState);
return MatchOperator (luaState, "op_Addition", translator);
}
/*
* __sub metafunction of CLR objects.
*/
#if MONOTOUCH
[MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
#endif
static int SubtractLua (LuaState luaState)
{
var translator = ObjectTranslatorPool.Instance.Find (luaState);
return MatchOperator (luaState, "op_Subtraction", translator);
}
/*
* __mul metafunction of CLR objects.
*/
#if MONOTOUCH
[MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
#endif
static int MultiplyLua (LuaState luaState)
{
var translator = ObjectTranslatorPool.Instance.Find (luaState);
return MatchOperator (luaState, "op_Multiply", translator);
}
/*
* __div metafunction of CLR objects.
*/
#if MONOTOUCH
[MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
#endif
static int DivideLua (LuaState luaState)
{
var translator = ObjectTranslatorPool.Instance.Find (luaState);
return MatchOperator (luaState, "op_Division", translator);
}
/*
* __mod metafunction of CLR objects.
*/
#if MONOTOUCH
[MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
#endif
static int ModLua (LuaState luaState)
{
var translator = ObjectTranslatorPool.Instance.Find (luaState);
return MatchOperator (luaState, "op_Modulus", translator);
}
/*
* __unm metafunction of CLR objects.
*/
#if MONOTOUCH
[MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
#endif
static int UnaryNegationLua (LuaState luaState)
{
var translator = ObjectTranslatorPool.Instance.Find (luaState);
return UnaryNegationLua (luaState, translator);
}
static int UnaryNegationLua (LuaState luaState, ObjectTranslator translator)
{
object obj1 = translator.GetRawNetObject (luaState, 1);
if (obj1 == null) {
translator.ThrowError (luaState, "Cannot negate a nil object");
LuaLib.LuaPushNil (luaState);
return 1;
}
Type type = obj1.GetType ();
MethodInfo opUnaryNegation = type.GetMethod ("op_UnaryNegation");
if (opUnaryNegation == null) {
translator.ThrowError (luaState, "Cannot negate object (" + type.Name + " does not overload the operator -)");
LuaLib.LuaPushNil (luaState);
return 1;
}
obj1 = opUnaryNegation.Invoke (obj1, new object [] { obj1 });
translator.Push (luaState, obj1);
return 1;
}
/*
* __eq metafunction of CLR objects.
*/
#if MONOTOUCH
[MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
#endif
static int EqualLua (LuaState luaState)
{
var translator = ObjectTranslatorPool.Instance.Find (luaState);
return MatchOperator (luaState, "op_Equality", translator);
}
/*
* __lt metafunction of CLR objects.
*/
#if MONOTOUCH
[MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
#endif
static int LessThanLua (LuaState luaState)
{
var translator = ObjectTranslatorPool.Instance.Find (luaState);
return MatchOperator (luaState, "op_LessThan", translator);
}
/*
* __le metafunction of CLR objects.
*/
#if MONOTOUCH
[MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
#endif
static int LessThanOrEqualLua (LuaState luaState)
{
var translator = ObjectTranslatorPool.Instance.Find (luaState);
return MatchOperator (luaState, "op_LessThanOrEqual", translator);
}
/// <summary>
/// Debug tool to dump the lua stack
/// </summary>
/// FIXME, move somewhere else
public static void DumpStack (ObjectTranslator translator, LuaState luaState)
{
int depth = LuaLib.LuaGetTop (luaState);
#if WINDOWS_PHONE || NETFX_CORE
Debug.WriteLine("lua stack depth: {0}", depth);
#elif UNITY_3D
UnityEngine.Debug.Log(string.Format("lua stack depth: {0}", depth));
#elif !SILVERLIGHT
Debug.Print ("lua stack depth: {0}", depth);
#endif
for (int i = 1; i <= depth; i++) {
var type = LuaLib.LuaType (luaState, i);
// we dump stacks when deep in calls, calling typename while the stack is in flux can fail sometimes, so manually check for key types
string typestr = (type == LuaTypes.Table) ? "table" : LuaLib.LuaTypeName (luaState, type);
string strrep = LuaLib.LuaToString (luaState, i).ToString ();
if (type == LuaTypes.UserData) {
object obj = translator.GetRawNetObject (luaState, i);
strrep = obj.ToString ();
}
#if WINDOWS_PHONE || NETFX_CORE
Debug.WriteLine("{0}: ({1}) {2}", i, typestr, strrep);
#elif UNITY_3D
UnityEngine.Debug.Log(string.Format("{0}: ({1}) {2}", i, typestr, strrep));
#elif !SILVERLIGHT
Debug.Print ("{0}: ({1}) {2}", i, typestr, strrep);
#endif
}
}
/*
* Called by the __index metafunction of CLR objects in case the
* method is not cached or it is a field/property/event.
* Receives the object and the member name as arguments and returns
* either the value of the member or a delegate to call it.
* If the member does not exist returns nil.
*/
#if MONOTOUCH
[MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
#endif
private static int GetMethod (LuaState luaState)
{
var translator = ObjectTranslatorPool.Instance.Find (luaState);
var instance = translator.MetaFunctionsInstance;
return instance.GetMethodInternal (luaState);
}
private int GetMethodInternal (LuaState luaState)
{
object obj = translator.GetRawNetObject (luaState, 1);
if (obj == null) {
translator.ThrowError (luaState, "trying to index an invalid object reference");
LuaLib.LuaPushNil (luaState);
return 1;
}
object index = translator.GetObject (luaState, 2);
//var indexType = index.GetType();
string methodName = index as string; // will be null if not a string arg
var objType = obj.GetType ();
var proxyType = new ProxyType (objType);
// Handle the most common case, looking up the method by name.
// CP: This will fail when using indexers and attempting to get a value with the same name as a property of the object,
// ie: xmlelement['item'] <- item is a property of xmlelement
try {
if (!string.IsNullOrEmpty(methodName) && IsMemberPresent (proxyType, methodName))
return GetMember (luaState, proxyType, obj, methodName, BindingFlags.Instance);
} catch {
}
// Try to access by array if the type is right and index is an int (lua numbers always come across as double)
if (objType.IsArray && index is double) {
/*
* This file is part of NLua.
* Copyright (C) 2014 Vinicius Jarina.
* Copyright (C) 2003-2005 Fabio Mascarenhas de Queiroz.
* Copyright (C) 2012 Megax <http://megax.yeahunter.hu/>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Linq;
using System.IO;
using System.Collections;
using System.Reflection;
using System.Diagnostics;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using NLua.Method;
using NLua.Extensions;
namespace NLua
{
#if USE_KOPILUA
using LuaCore = KopiLua.Lua;
using LuaState = KopiLua.LuaState;
using LuaNativeFunction = KopiLua.LuaNativeFunction;
#else
using LuaCore = KeraLua.Lua;
using LuaState = KeraLua.LuaState;
using LuaNativeFunction = KeraLua.LuaNativeFunction;
#endif
/*
* Functions used in the metatables of userdata representing
* CLR objects
*
*/
public class MetaFunctions
{
public LuaNativeFunction GcFunction { get; private set; }
public LuaNativeFunction IndexFunction { get; private set; }
public LuaNativeFunction NewIndexFunction { get; private set; }
public LuaNativeFunction BaseIndexFunction { get; private set; }
public LuaNativeFunction ClassIndexFunction { get; private set; }
public LuaNativeFunction ClassNewindexFunction { get; private set; }
public LuaNativeFunction ExecuteDelegateFunction { get; private set; }
public LuaNativeFunction CallConstructorFunction { get; private set; }
public LuaNativeFunction ToStringFunction { get; private set; }
public LuaNativeFunction CallDelegateFunction { get; private set; }
public LuaNativeFunction AddFunction { get; private set; }
public LuaNativeFunction SubtractFunction { get; private set; }
public LuaNativeFunction MultiplyFunction { get; private set; }
public LuaNativeFunction DivisionFunction { get; private set; }
public LuaNativeFunction ModulosFunction { get; private set; }
public LuaNativeFunction UnaryNegationFunction { get; private set; }
public LuaNativeFunction EqualFunction { get; private set; }
public LuaNativeFunction LessThanFunction { get; private set; }
public LuaNativeFunction LessThanOrEqualFunction { get; private set; }
Dictionary<object, object> memberCache = new Dictionary<object, object> ();
ObjectTranslator translator;
/*
* __index metafunction for CLR objects. Implemented in Lua.
*/
static string luaIndexFunction =
@"local function index(obj,name)
local meta = getmetatable(obj)
local cached = meta.cache[name]
if cached ~= nil then
return cached
else
local value,isFunc = get_object_member(obj,name)
if isFunc then
meta.cache[name]=value
end
return value
end
end
return index";
public static string LuaIndexFunction {
get { return luaIndexFunction; }
}
public MetaFunctions (ObjectTranslator translator)
{
this.translator = translator;
GcFunction = new LuaNativeFunction (MetaFunctions.CollectObject);
ToStringFunction = new LuaNativeFunction (MetaFunctions.ToStringLua);
IndexFunction = new LuaNativeFunction (MetaFunctions.GetMethod);
NewIndexFunction = new LuaNativeFunction (MetaFunctions.SetFieldOrProperty);
BaseIndexFunction = new LuaNativeFunction (MetaFunctions.GetBaseMethod);
CallConstructorFunction = new LuaNativeFunction (MetaFunctions.CallConstructor);
ClassIndexFunction = new LuaNativeFunction (MetaFunctions.GetClassMethod);
ClassNewindexFunction = new LuaNativeFunction (MetaFunctions.SetClassFieldOrProperty);
ExecuteDelegateFunction = new LuaNativeFunction (MetaFunctions.RunFunctionDelegate);
CallDelegateFunction = new LuaNativeFunction (MetaFunctions.CallDelegate);
AddFunction = new LuaNativeFunction (MetaFunctions.AddLua);
SubtractFunction = new LuaNativeFunction (MetaFunctions.SubtractLua);
MultiplyFunction = new LuaNativeFunction (MetaFunctions.MultiplyLua);
DivisionFunction = new LuaNativeFunction (MetaFunctions.DivideLua);
ModulosFunction = new LuaNativeFunction (MetaFunctions.ModLua);
UnaryNegationFunction = new LuaNativeFunction (MetaFunctions.UnaryNegationLua);
EqualFunction = new LuaNativeFunction (MetaFunctions.EqualLua);
LessThanFunction = new LuaNativeFunction (MetaFunctions.LessThanLua);
LessThanOrEqualFunction = new LuaNativeFunction (MetaFunctions.LessThanOrEqualLua);
}
/*
* __call metafunction of CLR delegates, retrieves and calls the delegate.
*/
#if MONOTOUCH
[MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
#endif
private static int RunFunctionDelegate (LuaState luaState)
{
var translator = ObjectTranslatorPool.Instance.Find (luaState);
return RunFunctionDelegate (luaState, translator);
}
private static int RunFunctionDelegate (LuaState luaState, ObjectTranslator translator)
{
LuaNativeFunction func = (LuaNativeFunction)translator.GetRawNetObject (luaState, 1);
LuaLib.LuaRemove (luaState, 1);
return func (luaState);
}
/*
* __gc metafunction of CLR objects.
*/
#if MONOTOUCH
[MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
#endif
private static int CollectObject (LuaState luaState)
{
var translator = ObjectTranslatorPool.Instance.Find (luaState);
return CollectObject (luaState, translator);
}
private static int CollectObject (LuaState luaState, ObjectTranslator translator)
{
int udata = LuaLib.LuaNetRawNetObj (luaState, 1);
if (udata != -1)
translator.CollectObject (udata);
return 0;
}
/*
* __tostring metafunction of CLR objects.
*/
#if MONOTOUCH
[MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
#endif
private static int ToStringLua (LuaState luaState)
{
var translator = ObjectTranslatorPool.Instance.Find (luaState);
return ToStringLua (luaState, translator);
}
private static int ToStringLua (LuaState luaState, ObjectTranslator translator)
{
object obj = translator.GetRawNetObject (luaState, 1);
if (obj != null)
translator.Push (luaState, obj.ToString () + ": " + obj.GetHashCode ().ToString());
else
LuaLib.LuaPushNil (luaState);
return 1;
}
/*
* __add metafunction of CLR objects.
*/
#if MONOTOUCH
[MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
#endif
static int AddLua (LuaState luaState)
{
var translator = ObjectTranslatorPool.Instance.Find (luaState);
return MatchOperator (luaState, "op_Addition", translator);
}
/*
* __sub metafunction of CLR objects.
*/
#if MONOTOUCH
[MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
#endif
static int SubtractLua (LuaState luaState)
{
var translator = ObjectTranslatorPool.Instance.Find (luaState);
return MatchOperator (luaState, "op_Subtraction", translator);
}
/*
* __mul metafunction of CLR objects.
*/
#if MONOTOUCH
[MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
#endif
static int MultiplyLua (LuaState luaState)
{
var translator = ObjectTranslatorPool.Instance.Find (luaState);
return MatchOperator (luaState, "op_Multiply", translator);
}
/*
* __div metafunction of CLR objects.
*/
#if MONOTOUCH
[MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
#endif
static int DivideLua (LuaState luaState)
{
var translator = ObjectTranslatorPool.Instance.Find (luaState);
return MatchOperator (luaState, "op_Division", translator);
}
/*
* __mod metafunction of CLR objects.
*/
#if MONOTOUCH
[MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
#endif
static int ModLua (LuaState luaState)
{
var translator = ObjectTranslatorPool.Instance.Find (luaState);
return MatchOperator (luaState, "op_Modulus", translator);
}
/*
* __unm metafunction of CLR objects.
*/
#if MONOTOUCH
[MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
#endif
static int UnaryNegationLua (LuaState luaState)
{
var translator = ObjectTranslatorPool.Instance.Find (luaState);
return UnaryNegationLua (luaState, translator);
}
static int UnaryNegationLua (LuaState luaState, ObjectTranslator translator)
{
object obj1 = translator.GetRawNetObject (luaState, 1);
if (obj1 == null) {
translator.ThrowError (luaState, "Cannot negate a nil object");
LuaLib.LuaPushNil (luaState);
return 1;
}
Type type = obj1.GetType ();
MethodInfo opUnaryNegation = type.GetMethod ("op_UnaryNegation");
if (opUnaryNegation == null) {
translator.ThrowError (luaState, "Cannot negate object (" + type.Name + " does not overload the operator -)");
LuaLib.LuaPushNil (luaState);
return 1;
}
obj1 = opUnaryNegation.Invoke (obj1, new object [] { obj1 });
translator.Push (luaState, obj1);
return 1;
}
/*
* __eq metafunction of CLR objects.
*/
#if MONOTOUCH
[MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
#endif
static int EqualLua (LuaState luaState)
{
var translator = ObjectTranslatorPool.Instance.Find (luaState);
return MatchOperator (luaState, "op_Equality", translator);
}
/*
* __lt metafunction of CLR objects.
*/
#if MONOTOUCH
[MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
#endif
static int LessThanLua (LuaState luaState)
{
var translator = ObjectTranslatorPool.Instance.Find (luaState);
return MatchOperator (luaState, "op_LessThan", translator);
}
/*
* __le metafunction of CLR objects.
*/
#if MONOTOUCH
[MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
#endif
static int LessThanOrEqualLua (LuaState luaState)
{
var translator = ObjectTranslatorPool.Instance.Find (luaState);
return MatchOperator (luaState, "op_LessThanOrEqual", translator);
}
/// <summary>
/// Debug tool to dump the lua stack
/// </summary>
/// FIXME, move somewhere else
public static void DumpStack (ObjectTranslator translator, LuaState luaState)
{
int depth = LuaLib.LuaGetTop (luaState);
#if WINDOWS_PHONE || NETFX_CORE
Debug.WriteLine("lua stack depth: {0}", depth);
#elif UNITY_3D
UnityEngine.Debug.Log(string.Format("lua stack depth: {0}", depth));
#elif !SILVERLIGHT
Debug.Print ("lua stack depth: {0}", depth);
#endif
for (int i = 1; i <= depth; i++) {
var type = LuaLib.LuaType (luaState, i);
// we dump stacks when deep in calls, calling typename while the stack is in flux can fail sometimes, so manually check for key types
string typestr = (type == LuaTypes.Table) ? "table" : LuaLib.LuaTypeName (luaState, type);
string strrep = LuaLib.LuaToString (luaState, i).ToString ();
if (type == LuaTypes.UserData) {
object obj = translator.GetRawNetObject (luaState, i);
strrep = obj.ToString ();
}
#if WINDOWS_PHONE || NETFX_CORE
Debug.WriteLine("{0}: ({1}) {2}", i, typestr, strrep);
#elif UNITY_3D
UnityEngine.Debug.Log(string.Format("{0}: ({1}) {2}", i, typestr, strrep));
#elif !SILVERLIGHT
Debug.Print ("{0}: ({1}) {2}", i, typestr, strrep);
#endif
}
}
/*
* Called by the __index metafunction of CLR objects in case the
* method is not cached or it is a field/property/event.
* Receives the object and the member name as arguments and returns
* either the value of the member or a delegate to call it.
* If the member does not exist returns nil.
*/
#if MONOTOUCH
[MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
#endif
private static int GetMethod (LuaState luaState)
{
var translator = ObjectTranslatorPool.Instance.Find (luaState);
var instance = translator.MetaFunctionsInstance;
return instance.GetMethodInternal (luaState);
}
private int GetMethodInternal (LuaState luaState)
{
object obj = translator.GetRawNetObject (luaState, 1);
if (obj == null) {
translator.ThrowError (luaState, "trying to index an invalid object reference");
LuaLib.LuaPushNil (luaState);
return 1;
}
object index = translator.GetObject (luaState, 2);
//var indexType = index.GetType();
string methodName = index as string; // will be null if not a string arg
var objType = obj.GetType ();
var proxyType = new ProxyType (objType);
// Handle the most common case, looking up the method by name.
// CP: This will fail when using indexers and attempting to get a value with the same name as a property of the object,
// ie: xmlelement['item'] <- item is a property of xmlelement
try {
if (!string.IsNullOrEmpty(methodName) && IsMemberPresent (proxyType, methodName))
return GetMember (luaState, proxyType, obj, methodName, BindingFlags.Instance);
} catch {
}
// Try to access by array if the type is right and index is an int (lua numbers always come across as double)
if (objType.IsArray && index is double) {
int intIndex = (int)((double)index);
#if NETFX_CORE
Type type = objType;
#else
Type type = objType.UnderlyingSystemType;
#endif
if (type == typeof(float[])) {
float[] arr = ((float[])obj);
translator.Push (luaState, arr [intIndex]);
} else if (type == typeof(double[])) {
double[] arr = ((double[])obj);
translator.Push (luaState, arr [intIndex]);
} else if (type == typeof(int[])) {
int[] arr = ((int[])obj);
translator.Push (luaState, arr [intIndex]);
} else {
object[] arr = (object[])obj;
translator.Push (luaState, arr [intIndex]);
}
} else {
if (!string.IsNullOrEmpty (methodName) && IsExtensionMethodPresent (objType, methodName)) {
return GetExtensionMethod (luaState, objType, obj, methodName);
}
// Try to use get_Item to index into this .net object
var methods = objType.GetMethods ();
foreach (var mInfo in methods) {
if (mInfo.Name == "get_Item") {
//check if the signature matches the input
if (mInfo.GetParameters ().Length == 1) {
var getter = mInfo;
var actualParms = (getter != null) ? getter.GetParameters () : null;
if (actualParms == null || actualParms.Length != 1) {
translator.ThrowError (luaState, "method not found (or no indexer): " + index);
LuaLib.LuaPushNil (luaState);
} else {
// Get the index in a form acceptable to the getter
index = translator.GetAsType (luaState, 2, actualParms [0].ParameterType);
object[] args = new object[1];
// Just call the indexer - if out of bounds an exception will happen
args [0] = index;
try {
object result = getter.Invoke (obj, args);
translator.Push (luaState, result);
} catch (TargetInvocationException e) {
// Provide a more readable description for the common case of key not found
if (e.InnerException is KeyNotFoundException)
translator.ThrowError (luaState, "key '" + index + "' not found ");
else
translator.ThrowError (luaState, "exception indexing '" + index + "' " + e.Message);
LuaLib.LuaPushNil (luaState);
}
}
}
}
}
}
LuaLib.LuaPushBoolean (luaState, false);
return 2;
}
/*
* __index metafunction of base classes (the base field of Lua tables).
* Adds a prefix to the method name to call the base version of the method.
*/
#if MONOTOUCH
[MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
#endif
private static int GetBaseMethod (LuaState luaState)
{
var translator = ObjectTranslatorPool.Instance.Find (luaState);
var instance = translator.MetaFunctionsInstance;
return instance.GetBaseMethodInternal (luaState);
}
private int GetBaseMethodInternal (LuaState luaState)
{
object obj = translator.GetRawNetObject (luaState, 1);
if (obj == null) {
translator.ThrowError (luaState, "trying to index an invalid object reference");
LuaLib.LuaPushNil (luaState);
LuaLib.LuaPushBoolean (luaState, false);
return 2;
}
string methodName = LuaLib.LuaToString (luaState, 2).ToString ();
if (string.IsNullOrEmpty(methodName)) {
LuaLib.LuaPushNil (luaState);
LuaLib.LuaPushBoolean (luaState, false);
return 2;
}
GetMember (luaState, new ProxyType(obj.GetType ()), obj, "__luaInterface_base_" + methodName, BindingFlags.Instance);
LuaLib.LuaSetTop (luaState, -2);
if (LuaLib.LuaType (luaState, -1) == LuaTypes.Nil) {
LuaLib.LuaSetTop (luaState, -2);
return GetMember (luaState, new ProxyType(obj.GetType ()), obj, methodName, BindingFlags.Instance);
}
LuaLib.LuaPushBoolean (luaState, false);
return 2;
}
/// <summary>
/// Does this method exist as either an instance or static?
/// </summary>
/// <param name="objType"></param>
/// <param name="methodName"></param>
/// <returns></returns>
bool IsMemberPresent (ProxyType objType, string methodName)
{
object cachedMember = CheckMemberCache (memberCache, objType, methodName);
if (cachedMember != null)
return true;
var members = objType.GetMember (methodName, BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public);
return (members.Length > 0);
}
bool IsExtensionMethodPresent (Type type, string name)
{
object cachedMember = CheckMemberCache (memberCache, type, name);
if (cachedMember != null)
return true;
return translator.IsExtensionMethodPresent (type, name);
}
int GetExtensionMethod (LuaState luaState, Type type, object obj, string name)
{
object cachedMember = CheckMemberCache (memberCache, type, name);
if (cachedMember != null && cachedMember is LuaNativeFunction) {
translator.PushFunction (luaState, (LuaNativeFunction)cachedMember);
translator.Push (luaState, true);
return 2;
}
MethodInfo methodInfo = translator.GetExtensionMethod (type, name);
var wrapper = new LuaNativeFunction ((new LuaMethodWrapper (translator, obj,new ProxyType(type), methodInfo)).invokeFunction);
SetMemberCache (memberCache, type, name, wrapper);
translator.PushFunction (luaState, wrapper);
translator.Push (luaState, true);
return 2;
}
/*
* Pushes the value of a member or a delegate to call it, depending on the type of
* the member. Works with static or instance members.
* 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).
*/
int GetMember (LuaState luaState, ProxyType objType, object obj, string methodName, BindingFlags bindingType)
{
bool implicitStatic = false;
MemberInfo member = null;
object cachedMember = CheckMemberCache (memberCache, objType, methodName);
if (cachedMember is LuaNativeFunction) {
translator.PushFunction (luaState, (LuaNativeFunction)cachedMember);
translator.Push (luaState, true);
return 2;
} else if (cachedMember != null)
member = (MemberInfo)cachedMember;
else {
var members = objType.GetMember (methodName, bindingType | BindingFlags.Public);
if (members.Length > 0)
member = members [0];
else {
// If we can't find any suitable instance members, try to find them as statics - but we only want to allow implicit static
members = objType.GetMember (methodName, bindingType | BindingFlags.Static | BindingFlags.Public);
if (members.Length > 0) {
member = members [0];
implicitStatic = true;
}
}
}
if (member != null) {
Type type = objType;
#else
Type type = objType.UnderlyingSystemType;
#endif
if (type == typeof(float[])) {
float[] arr = ((float[])obj);
translator.Push (luaState, arr [intIndex]);
} else if (type == typeof(double[])) {
double[] arr = ((double[])obj);
translator.Push (luaState, arr [intIndex]);
} else if (type == typeof(int[])) {
int[] arr = ((int[])obj);
translator.Push (luaState, arr [intIndex]);
} else {
object[] arr = (object[])obj;
translator.Push (luaState, arr [intIndex]);
}
} else {
if (!string.IsNullOrEmpty (methodName) && IsExtensionMethodPresent (objType, methodName)) {
return GetExtensionMethod (luaState, objType, obj, methodName);
}
// Try to use get_Item to index into this .net object
var methods = objType.GetMethods ();
foreach (var mInfo in methods) {
if (mInfo.Name == "get_Item") {
//check if the signature matches the input
if (mInfo.GetParameters ().Length == 1) {
var getter = mInfo;
var actualParms = (getter != null) ? getter.GetParameters () : null;
if (actualParms == null || actualParms.Length != 1) {
translator.ThrowError (luaState, "method not found (or no indexer): " + index);
LuaLib.LuaPushNil (luaState);
} else {
// Get the index in a form acceptable to the getter
index = translator.GetAsType (luaState, 2, actualParms [0].ParameterType);
object[] args = new object[1];
// Just call the indexer - if out of bounds an exception will happen
args [0] = index;
try {
object result = getter.Invoke (obj, args);
translator.Push (luaState, result);
} catch (TargetInvocationException e) {
// Provide a more readable description for the common case of key not found
if (e.InnerException is KeyNotFoundException)
translator.ThrowError (luaState, "key '" + index + "' not found ");
else
translator.ThrowError (luaState, "exception indexing '" + index + "' " + e.Message);
LuaLib.LuaPushNil (luaState);
}
}
}
}
}
}
LuaLib.LuaPushBoolean (luaState, false);
return 2;
}
/*
* __index metafunction of base classes (the base field of Lua tables).
* Adds a prefix to the method name to call the base version of the method.
*/
#if MONOTOUCH
[MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
#endif
private static int GetBaseMethod (LuaState luaState)
{
var translator = ObjectTranslatorPool.Instance.Find (luaState);
var instance = translator.MetaFunctionsInstance;
return instance.GetBaseMethodInternal (luaState);
}
private int GetBaseMethodInternal (LuaState luaState)
{
object obj = translator.GetRawNetObject (luaState, 1);
if (obj == null) {
translator.ThrowError (luaState, "trying to index an invalid object reference");
LuaLib.LuaPushNil (luaState);
LuaLib.LuaPushBoolean (luaState, false);
return 2;
}
string methodName = LuaLib.LuaToString (luaState, 2).ToString ();
if (string.IsNullOrEmpty(methodName)) {
LuaLib.LuaPushNil (luaState);
LuaLib.LuaPushBoolean (luaState, false);
return 2;
}
GetMember (luaState, new ProxyType(obj.GetType ()), obj, "__luaInterface_base_" + methodName, BindingFlags.Instance);
LuaLib.LuaSetTop (luaState, -2);
if (LuaLib.LuaType (luaState, -1) == LuaTypes.Nil) {
LuaLib.LuaSetTop (luaState, -2);
return GetMember (luaState, new ProxyType(obj.GetType ()), obj, methodName, BindingFlags.Instance);
}
LuaLib.LuaPushBoolean (luaState, false);
return 2;
}
/// <summary>
/// Does this method exist as either an instance or static?
/// </summary>
/// <param name="objType"></param>
/// <param name="methodName"></param>
/// <returns></returns>
bool IsMemberPresent (ProxyType objType, string methodName)
{
object cachedMember = CheckMemberCache (memberCache, objType, methodName);
if (cachedMember != null)
return true;
var members = objType.GetMember (methodName, BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public);
return (members.Length > 0);
}
bool IsExtensionMethodPresent (Type type, string name)
{
object cachedMember = CheckMemberCache (memberCache, type, name);
if (cachedMember != null)
return true;
return translator.IsExtensionMethodPresent (type, name);
}
int GetExtensionMethod (LuaState luaState, Type type, object obj, string name)
{
object cachedMember = CheckMemberCache (memberCache, type, name);
if (cachedMember != null && cachedMember is LuaNativeFunction) {
translator.PushFunction (luaState, (LuaNativeFunction)cachedMember);
translator.Push (luaState, true);
return 2;
}
MethodInfo methodInfo = translator.GetExtensionMethod (type, name);
var wrapper = new LuaNativeFunction ((new LuaMethodWrapper (translator, obj,new ProxyType(type), methodInfo)).invokeFunction);
SetMemberCache (memberCache, type, name, wrapper);
translator.PushFunction (luaState, wrapper);
translator.Push (luaState, true);
return 2;
}
/*
* Pushes the value of a member or a delegate to call it, depending on the type of
* the member. Works with static or instance members.
* 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).
*/
int GetMember (LuaState luaState, ProxyType objType, object obj, string methodName, BindingFlags bindingType)
{
bool implicitStatic = false;
MemberInfo member = null;
object cachedMember = CheckMemberCache (memberCache, objType, methodName);
if (cachedMember is LuaNativeFunction) {
translator.PushFunction (luaState, (LuaNativeFunction)cachedMember);
translator.Push (luaState, true);
return 2;
} else if (cachedMember != null)
member = (MemberInfo)cachedMember;
else {
var members = objType.GetMember (methodName, bindingType | BindingFlags.Public);
if (members.Length > 0)
member = members [0];
else {
// If we can't find any suitable instance members, try to find them as statics - but we only want to allow implicit static
members = objType.GetMember (methodName, bindingType | BindingFlags.Static | BindingFlags.Public);
if (members.Length > 0) {
member = members [0];
implicitStatic = true;
}
}
}
if (member != null) {
#if NETFX_CORE
if (member is FieldInfo) {
#else
if (member.MemberType == MemberTypes.Field) {
#endif
var field = (FieldInfo)member;
if (cachedMember == null)
SetMemberCache (memberCache, objType, methodName, member);
try {
var value = field.GetValue (obj);
if (!(value is Delegate)) {
translator.Push (luaState, value);
} else {
Delegate del = (Delegate)value;
var wrapper = new LuaNativeFunction ((new LuaMethodWrapper (translator, del.Target, objType, del.Method)).invokeFunction);
translator.PushFunction (luaState, wrapper);
translator.Push (luaState, true);
return 2;
}
} catch {
LuaLib.LuaPushNil (luaState);
}
#if NETFX_CORE
} else if (member is PropertyInfo) {
#else
} else if (member.MemberType == MemberTypes.Property) {
#endif
var property = (PropertyInfo)member;
if (cachedMember == null)
SetMemberCache (memberCache, objType, methodName, member);
try {
object value = property.GetValue (obj, null);
if (!(value is Delegate)) {
translator.Push (luaState, value);
} else {
Delegate del = (Delegate)value;
var wrapper = new LuaNativeFunction ((new LuaMethodWrapper (translator, del.Target, objType, del.Method)).invokeFunction);
translator.PushFunction (luaState, wrapper);
translator.Push (luaState, true);
return 2;
}
} catch (ArgumentException) {
// If we can't find the getter in our class, recurse up to the base class and see
// if they can help.
if (objType.UnderlyingSystemType != typeof(object))
#if NETFX_CORE
if (member is FieldInfo) {
#else
if (member.MemberType == MemberTypes.Field) {
#endif
var field = (FieldInfo)member;
if (cachedMember == null)
SetMemberCache (memberCache, objType, methodName, member);
try {
translator.Push (luaState, field.GetValue (obj));
} catch {
LuaLib.LuaPushNil (luaState);
}
#if NETFX_CORE
} else if (member is PropertyInfo) {
#else
} else if (member.MemberType == MemberTypes.Property) {
#endif
var property = (PropertyInfo)member;
if (cachedMember == null)
SetMemberCache (memberCache, objType, methodName, member);
try {
object val = property.GetValue (obj, null);
translator.Push (luaState, val);
} catch (ArgumentException) {
// If we can't find the getter in our class, recurse up to the base class and see
// if they can help.
if (objType.UnderlyingSystemType != typeof(object))
#if NETFX_CORE
return GetMember (luaState, new ProxyType(objType.UnderlyingSystemType.GetTypeInfo().BaseType), obj, methodName, bindingType);
#else
return GetMember (luaState, new ProxyType(objType.UnderlyingSystemType.BaseType), obj, methodName, bindingType);
return GetMember (luaState, new ProxyType(objType.UnderlyingSystemType.GetTypeInfo().BaseType), obj, methodName, bindingType);
#else
return GetMember (luaState, new ProxyType(objType.UnderlyingSystemType.BaseType), obj, methodName, bindingType);
#endif
else
LuaLib.LuaPushNil (luaState);
} catch (TargetInvocationException e) { // Convert this exception into a Lua error
ThrowError (luaState, e);
LuaLib.LuaPushNil (luaState);
}
else
LuaLib.LuaPushNil (luaState);
} catch (TargetInvocationException e) { // Convert this exception into a Lua error
ThrowError (luaState, e);
LuaLib.LuaPushNil (luaState);
}
#if NETFX_CORE
} else if (member is EventInfo) {
#else
} else if (member.MemberType == MemberTypes.Event) {
} else if (member is EventInfo) {
#else
} else if (member.MemberType == MemberTypes.Event) {
#endif
var eventInfo = (EventInfo)member;
if (cachedMember == null)
SetMemberCache (memberCache, objType, methodName, member);
translator.Push (luaState, new RegisterEventHandler (translator.pendingEvents, obj, eventInfo));
} else if (!implicitStatic) {
var eventInfo = (EventInfo)member;
if (cachedMember == null)
SetMemberCache (memberCache, objType, methodName, member);
translator.Push (luaState, new RegisterEventHandler (translator.pendingEvents, obj, eventInfo));
} else if (!implicitStatic) {
#if NETFX_CORE
var typeInfo = member as TypeInfo;
if (typeInfo != null && !typeInfo.IsPublic && !typeInfo.IsNotPublic) {
#else
if (member.MemberType == MemberTypes.NestedType) {
#endif
// kevinh - added support for finding nested types-
// cache us
if (cachedMember == null)
SetMemberCache (memberCache, objType, methodName, member);
// Find the name of our class
string name = member.Name;
var dectype = member.DeclaringType;
// Build a new long name and try to find the type by name
string longname = dectype.FullName + "+" + name;
var nestedType = translator.FindType (longname);
translator.PushType (luaState, nestedType);
} else {
// Member type must be 'method'
var wrapper = new LuaNativeFunction ((new LuaMethodWrapper (translator, objType, methodName, bindingType)).invokeFunction);
if (cachedMember == null)
SetMemberCache (memberCache, objType, methodName, wrapper);
translator.PushFunction (luaState, wrapper);
translator.Push (luaState, true);
return 2;
}
} else {
// If we reach this point we found a static method, but can't use it in this context because the user passed in an instance
translator.ThrowError (luaState, "can't pass instance to static method " + methodName);
LuaLib.LuaPushNil (luaState);
}
} else {
if (objType.UnderlyingSystemType != typeof(object)) {
#if NETFX_CORE
return GetMember (luaState, new ProxyType(objType.UnderlyingSystemType.GetTypeInfo().BaseType), obj, methodName, bindingType);
#else
return GetMember (luaState, new ProxyType(objType.UnderlyingSystemType.BaseType), obj, methodName, bindingType);
#endif
}
// kevinh - we want to throw an exception because meerly returning 'nil' in this case
// is not sufficient. valid data members may return nil and therefore there must be some
// way to know the member just doesn't exist.
translator.ThrowError (luaState, "unknown member name " + methodName);
LuaLib.LuaPushNil (luaState);
}
// push false because we are NOT returning a function (see luaIndexFunction)
translator.Push (luaState, false);
return 2;
}
/*
* Checks if a MemberInfo object is cached, returning it or null.
*/
object CheckMemberCache (Dictionary<object, object> memberCache, Type objType, string memberName)
{
return CheckMemberCache (memberCache, new ProxyType (objType), memberName);
}
object CheckMemberCache (Dictionary<object, object> memberCache, ProxyType objType, string memberName)
{
object members = null;
if (memberCache.TryGetValue(objType, out members))
{
var membersDict = members as Dictionary<object, object>;
object memberValue = null;
if (members != null && membersDict.TryGetValue(memberName, out memberValue))
{
return memberValue;
}
}
return null;
}
/*
* Stores a MemberInfo object in the member cache.
*/
void SetMemberCache (Dictionary<object, object> memberCache, Type objType, string memberName, object member)
{
SetMemberCache (memberCache, new ProxyType (objType), memberName, member);
}
void SetMemberCache (Dictionary<object, object> memberCache, ProxyType objType, string memberName, object member)
{
Dictionary<object, object> members = null;
object memberCacheValue = null;
if (memberCache.TryGetValue(objType, out memberCacheValue)) {
members = (Dictionary<object, object>)memberCacheValue;
} else {
members = new Dictionary<object, object>();
memberCache[objType] = members;
}
members [memberName] = member;
}
/*
* __newindex metafunction of CLR objects. Receives the object,
* the member name and the value to be stored as arguments. Throws
* and error if the assignment is invalid.
*/
#if MONOTOUCH
[MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
#endif
private static int SetFieldOrProperty (LuaState luaState)
{
var translator = ObjectTranslatorPool.Instance.Find (luaState);
var instance = translator.MetaFunctionsInstance;
return instance.SetFieldOrPropertyInternal (luaState);
}
private int SetFieldOrPropertyInternal (LuaState luaState)
{
object target = translator.GetRawNetObject (luaState, 1);
if (target == null) {
translator.ThrowError (luaState, "trying to index and invalid object reference");
return 0;
}
var type = target.GetType ();
// First try to look up the parameter as a property name
string detailMessage;
bool didMember = TrySetMember (luaState, new ProxyType(type), target, BindingFlags.Instance, out detailMessage);
if (didMember)
return 0; // Must have found the property name
// We didn't find a property name, now see if we can use a [] style this accessor to set array contents
try {
if (type.IsArray && LuaLib.LuaIsNumber (luaState, 2)) {
int index = (int)LuaLib.LuaToNumber (luaState, 2);
var arr = (Array)target;
object val = translator.GetAsType (luaState, 3, arr.GetType ().GetElementType ());
arr.SetValue (val, index);
} else {
// Try to see if we have a this[] accessor
var setter = type.GetMethod ("set_Item");
if (setter != null) {
var args = setter.GetParameters ();
var valueType = args [1].ParameterType;
// The new val ue the user specified
object val = translator.GetAsType (luaState, 3, valueType);
var indexType = args [0].ParameterType;
object index = translator.GetAsType (luaState, 2, indexType);
object[] methodArgs = new object[2];
// Just call the indexer - if out of bounds an exception will happen
methodArgs [0] = index;
methodArgs [1] = val;
setter.Invoke (target, methodArgs);
} else
translator.ThrowError (luaState, detailMessage); // Pass the original message from trySetMember because it is probably best
}
#if !SILVERLIGHT
} catch (SEHException) {
// If we are seeing a C++ exception - this must actually be for Lua's private use. Let it handle it
throw;
#endif
} catch (Exception e) {
ThrowError (luaState, e);
}
return 0;
}
/// <summary>
/// Tries to set a named property or field
/// </summary>
/// <param name="luaState"></param>
/// <param name="targetType"></param>
/// <param name="target"></param>
/// <param name="bindingType"></param>
/// <returns>false if unable to find the named member, true for success</returns>
bool TrySetMember (LuaState luaState, ProxyType targetType, object target, BindingFlags bindingType, out string detailMessage)
{
detailMessage = null; // No error yet
// If not already a string just return - we don't want to call tostring - which has the side effect of
// changing the lua typecode to string
// Note: We don't use isstring because the standard lua C isstring considers either strings or numbers to
// be true for isstring.
if (LuaLib.LuaType (luaState, 2) != LuaTypes.String) {
detailMessage = "property names must be strings";
return false;
}
// We only look up property names by string
string fieldName = LuaLib.LuaToString (luaState, 2).ToString ();
if (fieldName == null || fieldName.Length < 1 || !(char.IsLetter (fieldName [0]) || fieldName [0] == '_')) {
detailMessage = "invalid property name";
return false;
}
// Find our member via reflection or the cache
var member = (MemberInfo)CheckMemberCache (memberCache, targetType, fieldName);
if (member == null) {
var members = targetType.GetMember (fieldName, bindingType | BindingFlags.Public);
if (members.Length > 0) {
member = members [0];
SetMemberCache (memberCache, targetType, fieldName, member);
} else {
detailMessage = "field or property '" + fieldName + "' does not exist";
return false;
}
}
if (typeInfo != null && !typeInfo.IsPublic && !typeInfo.IsNotPublic) {
#else
if (member.MemberType == MemberTypes.NestedType) {
#endif
// kevinh - added support for finding nested types-
// cache us
if (cachedMember == null)
SetMemberCache (memberCache, objType, methodName, member);
// Find the name of our class
string name = member.Name;
var dectype = member.DeclaringType;
// Build a new long name and try to find the type by name
string longname = dectype.FullName + "+" + name;
var nestedType = translator.FindType (longname);
translator.PushType (luaState, nestedType);
} else {
// Member type must be 'method'
var wrapper = new LuaNativeFunction ((new LuaMethodWrapper (translator, objType, methodName, bindingType)).invokeFunction);
if (cachedMember == null)
SetMemberCache (memberCache, objType, methodName, wrapper);
translator.PushFunction (luaState, wrapper);
translator.Push (luaState, true);
return 2;
}
} else {
// If we reach this point we found a static method, but can't use it in this context because the user passed in an instance
translator.ThrowError (luaState, "can't pass instance to static method " + methodName);
LuaLib.LuaPushNil (luaState);
}
} else {
if (objType.UnderlyingSystemType != typeof(object)) {
#if NETFX_CORE
return GetMember (luaState, new ProxyType(objType.UnderlyingSystemType.GetTypeInfo().BaseType), obj, methodName, bindingType);
#else
return GetMember (luaState, new ProxyType(objType.UnderlyingSystemType.BaseType), obj, methodName, bindingType);
#endif
}
// kevinh - we want to throw an exception because meerly returning 'nil' in this case
// is not sufficient. valid data members may return nil and therefore there must be some
// way to know the member just doesn't exist.
translator.ThrowError (luaState, "unknown member name " + methodName);
LuaLib.LuaPushNil (luaState);
}
// push false because we are NOT returning a function (see luaIndexFunction)
translator.Push (luaState, false);
return 2;
}
/*
* Checks if a MemberInfo object is cached, returning it or null.
*/
object CheckMemberCache (Dictionary<object, object> memberCache, Type objType, string memberName)
{
return CheckMemberCache (memberCache, new ProxyType (objType), memberName);
}
object CheckMemberCache (Dictionary<object, object> memberCache, ProxyType objType, string memberName)
{
object members = null;
if (memberCache.TryGetValue(objType, out members))
{
var membersDict = members as Dictionary<object, object>;
object memberValue = null;
if (members != null && membersDict.TryGetValue(memberName, out memberValue))
{
return memberValue;
}
}
return null;
}
/*
* Stores a MemberInfo object in the member cache.
*/
void SetMemberCache (Dictionary<object, object> memberCache, Type objType, string memberName, object member)
{
SetMemberCache (memberCache, new ProxyType (objType), memberName, member);
}
void SetMemberCache (Dictionary<object, object> memberCache, ProxyType objType, string memberName, object member)
{
Dictionary<object, object> members = null;
object memberCacheValue = null;
if (memberCache.TryGetValue(objType, out memberCacheValue)) {
members = (Dictionary<object, object>)memberCacheValue;
} else {
members = new Dictionary<object, object>();
memberCache[objType] = members;
}
members [memberName] = member;
}
/*
* __newindex metafunction of CLR objects. Receives the object,
* the member name and the value to be stored as arguments. Throws
* and error if the assignment is invalid.
*/
#if MONOTOUCH
[MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
#endif
private static int SetFieldOrProperty (LuaState luaState)
{
var translator = ObjectTranslatorPool.Instance.Find (luaState);
var instance = translator.MetaFunctionsInstance;
return instance.SetFieldOrPropertyInternal (luaState);
}
private int SetFieldOrPropertyInternal (LuaState luaState)
{
object target = translator.GetRawNetObject (luaState, 1);
if (target == null) {
translator.ThrowError (luaState, "trying to index and invalid object reference");
return 0;
}
var type = target.GetType ();
// First try to look up the parameter as a property name
string detailMessage;
bool didMember = TrySetMember (luaState, new ProxyType(type), target, BindingFlags.Instance, out detailMessage);
if (didMember)
return 0; // Must have found the property name
// We didn't find a property name, now see if we can use a [] style this accessor to set array contents
try {
if (type.IsArray && LuaLib.LuaIsNumber (luaState, 2)) {
int index = (int)LuaLib.LuaToNumber (luaState, 2);
var arr = (Array)target;
object val = translator.GetAsType (luaState, 3, arr.GetType ().GetElementType ());
arr.SetValue (val, index);
} else {
// Try to see if we have a this[] accessor
var setter = type.GetMethod ("set_Item");
if (setter != null) {
var args = setter.GetParameters ();
var valueType = args [1].ParameterType;
// The new val ue the user specified
object val = translator.GetAsType (luaState, 3, valueType);
var indexType = args [0].ParameterType;
object index = translator.GetAsType (luaState, 2, indexType);
object[] methodArgs = new object[2];
// Just call the indexer - if out of bounds an exception will happen
methodArgs [0] = index;
methodArgs [1] = val;
setter.Invoke (target, methodArgs);
} else
translator.ThrowError (luaState, detailMessage); // Pass the original message from trySetMember because it is probably best
}
#if !SILVERLIGHT
} catch (SEHException) {
// If we are seeing a C++ exception - this must actually be for Lua's private use. Let it handle it
throw;
#endif
} catch (Exception e) {
ThrowError (luaState, e);
}
return 0;
}
/// <summary>
/// Tries to set a named property or field
/// </summary>
/// <param name="luaState"></param>
/// <param name="targetType"></param>
/// <param name="target"></param>
/// <param name="bindingType"></param>
/// <returns>false if unable to find the named member, true for success</returns>
bool TrySetMember (LuaState luaState, ProxyType targetType, object target, BindingFlags bindingType, out string detailMessage)
{
detailMessage = null; // No error yet
// If not already a string just return - we don't want to call tostring - which has the side effect of
// changing the lua typecode to string
// Note: We don't use isstring because the standard lua C isstring considers either strings or numbers to
// be true for isstring.
if (LuaLib.LuaType (luaState, 2) != LuaTypes.String) {
detailMessage = "property names must be strings";
return false;
}
// We only look up property names by string
string fieldName = LuaLib.LuaToString (luaState, 2).ToString ();
if (fieldName == null || fieldName.Length < 1 || !(char.IsLetter (fieldName [0]) || fieldName [0] == '_')) {
detailMessage = "invalid property name";
return false;
}
// Find our member via reflection or the cache
var member = (MemberInfo)CheckMemberCache (memberCache, targetType, fieldName);
if (member == null) {
var members = targetType.GetMember (fieldName, bindingType | BindingFlags.Public);
if (members.Length > 0) {
member = members [0];
SetMemberCache (memberCache, targetType, fieldName, member);
} else {
detailMessage = "field or property '" + fieldName + "' does not exist";
return false;
}
}
#if NETFX_CORE
if (member is FieldInfo) {
#else
if (member.MemberType == MemberTypes.Field) {
#endif
var field = (FieldInfo)member;
object val = translator.GetAsType (luaState, 3, field.FieldType);
try {
field.SetValue (target, val);
} catch (Exception e) {
ThrowError (luaState, e);
}
// We did a call
return true;
if (member is FieldInfo) {
#else
if (member.MemberType == MemberTypes.Field) {
#endif
var field = (FieldInfo)member;
object val = translator.GetAsType (luaState, 3, field.FieldType);
try {
field.SetValue (target, val);
} catch (Exception e) {
ThrowError (luaState, e);
}
// We did a call
return true;
#if NETFX_CORE
} else if (member is PropertyInfo) {
#else
} else if (member.MemberType == MemberTypes.Property) {
#endif
var property = (PropertyInfo)member;
object val = translator.GetAsType (luaState, 3, property.PropertyType);
try {
property.SetValue (target, val, null);
} catch (Exception e) {
ThrowError (luaState, e);
}
// We did a call
return true;
}
detailMessage = "'" + fieldName + "' is not a .net field or property";
return false;
}
/*
* Writes to fields or properties, either static or instance. Throws an error
* if the operation is invalid.
*/
private int SetMember (LuaState luaState, ProxyType targetType, object target, BindingFlags bindingType)
{
string detail;
bool success = TrySetMember (luaState, targetType, target, bindingType, out detail);
if (!success)
translator.ThrowError (luaState, detail);
return 0;
}
/// <summary>
/// Convert a C# exception into a Lua error
/// </summary>
/// <param name="e"></param>
/// We try to look into the exception to give the most meaningful description
void ThrowError (LuaState luaState, Exception e)
{
// If we got inside a reflection show what really happened
var te = e as TargetInvocationException;
if (te != null)
e = te.InnerException;
translator.ThrowError (luaState, e);
}
/*
* __index metafunction of type references, works on static members.
*/
#if MONOTOUCH
[MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
#endif
private static int GetClassMethod (LuaState luaState)
{
var translator = ObjectTranslatorPool.Instance.Find (luaState);
var instance = translator.MetaFunctionsInstance;
return instance.GetClassMethodInternal (luaState);
}
private int GetClassMethodInternal (LuaState luaState)
{
ProxyType klass;
object obj = translator.GetRawNetObject (luaState, 1);
if (obj == null || !(obj is ProxyType)) {
translator.ThrowError (luaState, "trying to index an invalid type reference");
LuaLib.LuaPushNil (luaState);
return 1;
} else
klass = (ProxyType)obj;
if (LuaLib.LuaIsNumber (luaState, 2)) {
int size = (int)LuaLib.LuaToNumber (luaState, 2);
translator.Push (luaState, Array.CreateInstance (klass.UnderlyingSystemType, size));
return 1;
} else {
string methodName = LuaLib.LuaToString (luaState, 2).ToString ();
if (string.IsNullOrEmpty(methodName)) {
LuaLib.LuaPushNil (luaState);
return 1;
}
else
return GetMember (luaState, klass, null, methodName, BindingFlags.Static);
}
}
/*
* __newindex function of type references, works on static members.
*/
#if MONOTOUCH
[MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
#endif
private static int SetClassFieldOrProperty (LuaState luaState)
{
var translator = ObjectTranslatorPool.Instance.Find (luaState);
var instance = translator.MetaFunctionsInstance;
return instance.SetClassFieldOrPropertyInternal (luaState);
}
private int SetClassFieldOrPropertyInternal (LuaState luaState)
{
ProxyType target;
object obj = translator.GetRawNetObject (luaState, 1);
if (obj == null || !(obj is ProxyType)) {
translator.ThrowError (luaState, "trying to index an invalid type reference");
return 0;
} else
target = (ProxyType)obj;
return SetMember (luaState, target, null, BindingFlags.Static);
}
/*
* __call metafunction of type references. Searches for and calls
* a constructor for the type. Returns nil if the constructor is not
* found or if the arguments are invalid. Throws an error if the constructor
* generates an exception.
*/
#if MONOTOUCH
[MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
#endif
private static int CallConstructor (LuaState luaState)
{
var translator = ObjectTranslatorPool.Instance.Find (luaState);
var instance = translator.MetaFunctionsInstance;
return instance.CallConstructorInternal (luaState);
}
private int CallConstructorInternal (LuaState luaState)
{
var validConstructor = new MethodCache ();
ProxyType klass;
object obj = translator.GetRawNetObject (luaState, 1);
if (obj == null || !(obj is ProxyType)) {
translator.ThrowError (luaState, "trying to call constructor on an invalid type reference");
LuaLib.LuaPushNil (luaState);
return 1;
} else
klass = (ProxyType)obj;
LuaLib.LuaRemove (luaState, 1);
var constructors = klass.UnderlyingSystemType.GetConstructors ();
foreach (var constructor in constructors) {
bool isConstructor = MatchParameters (luaState, constructor, ref validConstructor);
if (isConstructor) {
try {
translator.Push (luaState, constructor.Invoke (validConstructor.args));
} catch (TargetInvocationException e) {
ThrowError (luaState, e);
LuaLib.LuaPushNil (luaState);
} catch {
LuaLib.LuaPushNil (luaState);
}
return 1;
}
}
string constructorName = (constructors.Length == 0) ? "unknown" : constructors [0].Name;
translator.ThrowError (luaState, String.Format ("{0} does not contain constructor({1}) argument match",
klass.UnderlyingSystemType, constructorName));
LuaLib.LuaPushNil (luaState);
return 1;
}
static bool IsInteger(double x) {
return Math.Ceiling(x) == x;
}
static object GetTargetObject (LuaState luaState, string operation, ObjectTranslator translator)
{
Type t;
object target = translator.GetRawNetObject (luaState, 1);
if (target != null) {
t = target.GetType ();
if (t.HasMethod (operation))
return target;
}
target = translator.GetRawNetObject (luaState, 2);
if (target != null) {
t = target.GetType ();
if (t.HasMethod (operation))
return target;
}
return null;
}
static int MatchOperator (LuaState luaState, string operation, ObjectTranslator translator)
{
var validOperator = new MethodCache ();
object target = GetTargetObject (luaState, operation, translator);
if (target == null) {
translator.ThrowError (luaState, "Cannot call " + operation + " on a nil object");
LuaLib.LuaPushNil (luaState);
return 1;
}
Type type = target.GetType ();
var operators = type.GetMethods (operation, BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
foreach (var op in operators) {
bool isOk = translator.MatchParameters (luaState, op, ref validOperator);
if (!isOk)
continue;
object result;
if (op.IsStatic)
result = op.Invoke (null, validOperator.args);
else
result = op.Invoke (target, validOperator.args);
translator.Push (luaState, result);
return 1;
}
translator.ThrowError (luaState, "Cannot call (" + operation + ") on object type " + type.Name);
LuaLib.LuaPushNil (luaState);
return 1;
}
internal Array TableToArray (Func<int, object> luaParamValueExtractor, Type paramArrayType, int startIndex, int count)
{
Array paramArray;
if (count == 0)
return Array.CreateInstance (paramArrayType, 0);
var luaParamValue = luaParamValueExtractor (startIndex);
if (luaParamValue is LuaTable) {
LuaTable table = (LuaTable)luaParamValue;
IDictionaryEnumerator tableEnumerator = table.GetEnumerator ();
tableEnumerator.Reset ();
paramArray = Array.CreateInstance (paramArrayType, table.Values.Count);
int paramArrayIndex = 0;
while (tableEnumerator.MoveNext ()) {
object value = tableEnumerator.Value;
if (paramArrayType == typeof (object)) {
if (value != null && value.GetType () == typeof (double) && IsInteger ((double)value))
value = Convert.ToInt32 ((double)value);
}
#if SILVERLIGHT
paramArray.SetValue (Convert.ChangeType (value, paramArrayType, System.Globalization.CultureInfo.InvariantCulture), paramArrayIndex);
#else
paramArray.SetValue (Convert.ChangeType (value, paramArrayType), paramArrayIndex);
#endif
paramArrayIndex++;
}
} else {
paramArray = Array.CreateInstance (paramArrayType, count);
paramArray.SetValue (luaParamValue, 0);
for (int i = 1; i < count; i++) {
startIndex++;
var value = luaParamValueExtractor (startIndex);
paramArray.SetValue (value, i);
}
}
return paramArray;
}
/*
* Matches a method against its arguments in the Lua stack. Returns
* if the match was successful. It it was also returns the information
* necessary to invoke the method.
*/
internal bool MatchParameters (LuaState luaState, MethodBase method, ref MethodCache methodCache)
{
ExtractValue extractValue;
bool isMethod = true;
var paramInfo = method.GetParameters ();
int currentLuaParam = 1;
int nLuaParams = LuaLib.LuaGetTop (luaState);
var paramList = new List<object> ();
var outList = new List<int> ();
var argTypes = new List<MethodArgs> ();
foreach (var currentNetParam in paramInfo) {
#if !SILVERLIGHT
if (!currentNetParam.IsIn && currentNetParam.IsOut) // Skips out params
#else
if (currentNetParam.IsOut) // Skips out params
#endif
{
paramList.Add (null);
outList.Add (paramList.LastIndexOf (null));
} else if (IsTypeCorrect (luaState, currentLuaParam, currentNetParam, out extractValue)) { // Type checking
var value = extractValue (luaState, currentLuaParam);
paramList.Add (value);
int index = paramList.LastIndexOf (value);
var methodArg = new MethodArgs ();
methodArg.index = index;
methodArg.extractValue = extractValue;
argTypes.Add (methodArg);
if (currentNetParam.ParameterType.IsByRef)
outList.Add (index);
currentLuaParam++;
} // Type does not match, ignore if the parameter is optional
else if (IsParamsArray (luaState, currentLuaParam, currentNetParam, out extractValue)) {
var paramArrayType = currentNetParam.ParameterType.GetElementType ();
Func<int, object> extractDelegate = (currentParam) => {
currentLuaParam ++;
return extractValue (luaState, currentParam);
};
int count = (nLuaParams - currentLuaParam) + 1;
Array paramArray = TableToArray (extractDelegate, paramArrayType, currentLuaParam, count);
paramList.Add (paramArray);
int index = paramList.LastIndexOf (paramArray);
var methodArg = new MethodArgs ();
methodArg.index = index;
methodArg.extractValue = extractValue;
methodArg.isParamsArray = true;
methodArg.paramsArrayType = paramArrayType;
argTypes.Add (methodArg);
} else if (currentLuaParam > nLuaParams) { // Adds optional parameters
if (currentNetParam.IsOptional)
paramList.Add (currentNetParam.DefaultValue);
else {
isMethod = false;
break;
}
} else if (currentNetParam.IsOptional)
paramList.Add (currentNetParam.DefaultValue);
else { // No match
isMethod = false;
break;
}
}
if (currentLuaParam != nLuaParams + 1) // Number of parameters does not match
isMethod = false;
if (isMethod) {
methodCache.args = paramList.ToArray ();
methodCache.cachedMethod = method;
methodCache.outList = outList.ToArray ();
methodCache.argTypes = argTypes.ToArray ();
}
return isMethod;
}
/// <summary>
/// CP: Fix for operator overloading failure
/// Returns true if the type is set and assigns the extract value
/// </summary>
/// <param name="luaState"></param>
/// <param name="currentLuaParam"></param>
/// <param name="currentNetParam"></param>
/// <param name="extractValue"></param>
/// <returns></returns>
private bool IsTypeCorrect (LuaState luaState, int currentLuaParam, ParameterInfo currentNetParam, out ExtractValue extractValue)
{
try {
return (extractValue = translator.typeChecker.CheckLuaType (luaState, currentLuaParam, currentNetParam.ParameterType)) != null;
} catch {
extractValue = null;
Debug.WriteLine ("Type wasn't correct");
return false;
}
}
private bool IsParamsArray (LuaState luaState, int currentLuaParam, ParameterInfo currentNetParam, out ExtractValue extractValue)
{
extractValue = null;
if (currentNetParam.GetCustomAttributes (typeof(ParamArrayAttribute), false).Any ()) {
LuaTypes luaType;
try {
luaType = LuaLib.LuaType (luaState, currentLuaParam);
} catch (Exception ex) {
Debug.WriteLine ("Could not retrieve lua type while attempting to determine params Array Status.");
Debug.WriteLine (ex.Message);
extractValue = null;
return false;
}
if (luaType == LuaTypes.Table) {
try {
extractValue = translator.typeChecker.GetExtractor (typeof(LuaTable));
} catch (Exception/* ex*/) {
Debug.WriteLine ("An error occurred during an attempt to retrieve a LuaTable extractor while checking for params array status.");
}
if (extractValue != null) {
return true;
}
} else {
var paramElementType = currentNetParam.ParameterType.GetElementType ();
try {
extractValue = translator.typeChecker.CheckLuaType (luaState, currentLuaParam, paramElementType);
} catch (Exception/* ex*/) {
Debug.WriteLine (string.Format ("An error occurred during an attempt to retrieve an extractor ({0}) while checking for params array status.", paramElementType.FullName));
}
if (extractValue != null) {
return true;
}
}
}
Debug.WriteLine ("Type wasn't Params object.");
return false;
}
}
} else if (member is PropertyInfo) {
#else
} else if (member.MemberType == MemberTypes.Property) {
#endif
var property = (PropertyInfo)member;
object val = translator.GetAsType (luaState, 3, property.PropertyType);
try {
property.SetValue (target, val, null);
} catch (Exception e) {
ThrowError (luaState, e);
}
// We did a call
return true;
}
detailMessage = "'" + fieldName + "' is not a .net field or property";
return false;
}
/*
* Writes to fields or properties, either static or instance. Throws an error
* if the operation is invalid.
*/
private int SetMember (LuaState luaState, ProxyType targetType, object target, BindingFlags bindingType)
{
string detail;
bool success = TrySetMember (luaState, targetType, target, bindingType, out detail);
if (!success)
translator.ThrowError (luaState, detail);
return 0;
}
/// <summary>
/// Convert a C# exception into a Lua error
/// </summary>
/// <param name="e"></param>
/// We try to look into the exception to give the most meaningful description
void ThrowError (LuaState luaState, Exception e)
{
// If we got inside a reflection show what really happened
var te = e as TargetInvocationException;
if (te != null)
e = te.InnerException;
translator.ThrowError (luaState, e);
}
/*
* __index metafunction of type references, works on static members.
*/
#if MONOTOUCH
[MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
#endif
private static int GetClassMethod (LuaState luaState)
{
var translator = ObjectTranslatorPool.Instance.Find (luaState);
var instance = translator.MetaFunctionsInstance;
return instance.GetClassMethodInternal (luaState);
}
private int GetClassMethodInternal (LuaState luaState)
{
ProxyType klass;
object obj = translator.GetRawNetObject (luaState, 1);
if (obj == null || !(obj is ProxyType)) {
translator.ThrowError (luaState, "trying to index an invalid type reference");
LuaLib.LuaPushNil (luaState);
return 1;
} else
klass = (ProxyType)obj;
if (LuaLib.LuaIsNumber (luaState, 2)) {
int size = (int)LuaLib.LuaToNumber (luaState, 2);
translator.Push (luaState, Array.CreateInstance (klass.UnderlyingSystemType, size));
return 1;
} else {
string methodName = LuaLib.LuaToString (luaState, 2).ToString ();
if (string.IsNullOrEmpty(methodName)) {
LuaLib.LuaPushNil (luaState);
return 1;
}
else
return GetMember (luaState, klass, null, methodName, BindingFlags.Static);
}
}
/*
* __newindex function of type references, works on static members.
*/
#if MONOTOUCH
[MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
#endif
private static int SetClassFieldOrProperty (LuaState luaState)
{
var translator = ObjectTranslatorPool.Instance.Find (luaState);
var instance = translator.MetaFunctionsInstance;
return instance.SetClassFieldOrPropertyInternal (luaState);
}
private int SetClassFieldOrPropertyInternal (LuaState luaState)
{
ProxyType target;
object obj = translator.GetRawNetObject (luaState, 1);
if (obj == null || !(obj is ProxyType)) {
translator.ThrowError (luaState, "trying to index an invalid type reference");
return 0;
} else
target = (ProxyType)obj;
return SetMember (luaState, target, null, BindingFlags.Static);
}
/*
* __call metafunction of Delegates.
*/
#if MONOTOUCH
[MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
#endif
static int CallDelegate (LuaState luaState)
{
var translator = ObjectTranslatorPool.Instance.Find (luaState);
var instance = translator.MetaFunctionsInstance;
return instance.CallDelegateInternal (luaState);
}
int CallDelegateInternal (LuaState luaState)
{
object objDelegate = translator.GetRawNetObject (luaState, 1);
if (objDelegate == null || !(objDelegate is Delegate)) {
translator.ThrowError (luaState, "trying to invoke a not delegate or callable value");
LuaLib.LuaPushNil (luaState);
return 1;
}
LuaLib.LuaRemove (luaState, 1);
var validDelegate = new MethodCache ();
Delegate del = (Delegate)objDelegate;
MethodBase methodDelegate = del.Method;
bool isOk = MatchParameters (luaState, methodDelegate, ref validDelegate);
if (isOk) {
object result;
if (methodDelegate.IsStatic)
result = methodDelegate.Invoke (null, validDelegate.args);
else
result = methodDelegate.Invoke (del.Target, validDelegate.args);
translator.Push (luaState, result);
return 1;
}
translator.ThrowError (luaState, "Cannot invoke delegate (invalid arguments for " + methodDelegate.Name + ")");
LuaLib.LuaPushNil (luaState);
return 1;
}
/*
* __call metafunction of type references. Searches for and calls
* a constructor for the type. Returns nil if the constructor is not
* found or if the arguments are invalid. Throws an error if the constructor
* generates an exception.
*/
#if MONOTOUCH
[MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
#endif
private static int CallConstructor (LuaState luaState)
{
var translator = ObjectTranslatorPool.Instance.Find (luaState);
var instance = translator.MetaFunctionsInstance;
return instance.CallConstructorInternal (luaState);
}
private int CallConstructorInternal (LuaState luaState)
{
var validConstructor = new MethodCache ();
ProxyType klass;
object obj = translator.GetRawNetObject (luaState, 1);
if (obj == null || !(obj is ProxyType)) {
translator.ThrowError (luaState, "trying to call constructor on an invalid type reference");
LuaLib.LuaPushNil (luaState);
return 1;
} else
klass = (ProxyType)obj;
LuaLib.LuaRemove (luaState, 1);
var constructors = klass.UnderlyingSystemType.GetConstructors ();
foreach (var constructor in constructors) {
bool isConstructor = MatchParameters (luaState, constructor, ref validConstructor);
if (isConstructor) {
try {
translator.Push (luaState, constructor.Invoke (validConstructor.args));
} catch (TargetInvocationException e) {
ThrowError (luaState, e);
LuaLib.LuaPushNil (luaState);
} catch {
LuaLib.LuaPushNil (luaState);
}
return 1;
}
}
string constructorName = (constructors.Length == 0) ? "unknown" : constructors [0].Name;
translator.ThrowError (luaState, String.Format ("{0} does not contain constructor({1}) argument match",
klass.UnderlyingSystemType, constructorName));
LuaLib.LuaPushNil (luaState);
return 1;
}
static bool IsInteger(double x) {
return Math.Ceiling(x) == x;
}
static object GetTargetObject (LuaState luaState, string operation, ObjectTranslator translator)
{
Type t;
object target = translator.GetRawNetObject (luaState, 1);
if (target != null) {
t = target.GetType ();
if (t.HasMethod (operation))
return target;
}
target = translator.GetRawNetObject (luaState, 2);
if (target != null) {
t = target.GetType ();
if (t.HasMethod (operation))
return target;
}
return null;
}
static int MatchOperator (LuaState luaState, string operation, ObjectTranslator translator)
{
var validOperator = new MethodCache ();
object target = GetTargetObject (luaState, operation, translator);
if (target == null) {
translator.ThrowError (luaState, "Cannot call " + operation + " on a nil object");
LuaLib.LuaPushNil (luaState);
return 1;
}
Type type = target.GetType ();
var operators = type.GetMethods (operation, BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
foreach (var op in operators) {
bool isOk = translator.MatchParameters (luaState, op, ref validOperator);
if (!isOk)
continue;
object result;
if (op.IsStatic)
result = op.Invoke (null, validOperator.args);
else
result = op.Invoke (target, validOperator.args);
translator.Push (luaState, result);
return 1;
}
translator.ThrowError (luaState, "Cannot call (" + operation + ") on object type " + type.Name);
LuaLib.LuaPushNil (luaState);
return 1;
}
internal Array TableToArray (Func<int, object> luaParamValueExtractor, Type paramArrayType, int startIndex, int count)
{
Array paramArray;
if (count == 0)
return Array.CreateInstance (paramArrayType, 0);
var luaParamValue = luaParamValueExtractor (startIndex);
if (luaParamValue is LuaTable) {
LuaTable table = (LuaTable)luaParamValue;
IDictionaryEnumerator tableEnumerator = table.GetEnumerator ();
tableEnumerator.Reset ();
paramArray = Array.CreateInstance (paramArrayType, table.Values.Count);
int paramArrayIndex = 0;
while (tableEnumerator.MoveNext ()) {
object value = tableEnumerator.Value;
if (paramArrayType == typeof (object)) {
if (value != null && value.GetType () == typeof (double) && IsInteger ((double)value))
value = Convert.ToInt32 ((double)value);
}
#if SILVERLIGHT
paramArray.SetValue (Convert.ChangeType (value, paramArrayType, System.Globalization.CultureInfo.InvariantCulture), paramArrayIndex);
#else
paramArray.SetValue (Convert.ChangeType (value, paramArrayType), paramArrayIndex);
#endif
paramArrayIndex++;
}
} else {
paramArray = Array.CreateInstance (paramArrayType, count);
paramArray.SetValue (luaParamValue, 0);
for (int i = 1; i < count; i++) {
startIndex++;
var value = luaParamValueExtractor (startIndex);
paramArray.SetValue (value, i);
}
}
return paramArray;
}
/*
* Matches a method against its arguments in the Lua stack. Returns
* if the match was successful. It it was also returns the information
* necessary to invoke the method.
*/
internal bool MatchParameters (LuaState luaState, MethodBase method, ref MethodCache methodCache)
{
ExtractValue extractValue;
bool isMethod = true;
var paramInfo = method.GetParameters ();
int currentLuaParam = 1;
int nLuaParams = LuaLib.LuaGetTop (luaState);
var paramList = new List<object> ();
var outList = new List<int> ();
var argTypes = new List<MethodArgs> ();
foreach (var currentNetParam in paramInfo) {
#if !SILVERLIGHT
if (!currentNetParam.IsIn && currentNetParam.IsOut) // Skips out params
#else
if (currentNetParam.IsOut) // Skips out params
#endif
{
paramList.Add (null);
outList.Add (paramList.LastIndexOf (null));
} else if (IsTypeCorrect (luaState, currentLuaParam, currentNetParam, out extractValue)) { // Type checking
var value = extractValue (luaState, currentLuaParam);
paramList.Add (value);
int index = paramList.LastIndexOf (value);
var methodArg = new MethodArgs ();
methodArg.index = index;
methodArg.extractValue = extractValue;
argTypes.Add (methodArg);
if (currentNetParam.ParameterType.IsByRef)
outList.Add (index);
currentLuaParam++;
} // Type does not match, ignore if the parameter is optional
else if (IsParamsArray (luaState, currentLuaParam, currentNetParam, out extractValue)) {
var paramArrayType = currentNetParam.ParameterType.GetElementType ();
Func<int, object> extractDelegate = (currentParam) => {
currentLuaParam ++;
return extractValue (luaState, currentParam);
};
int count = (nLuaParams - currentLuaParam) + 1;
Array paramArray = TableToArray (extractDelegate, paramArrayType, currentLuaParam, count);
paramList.Add (paramArray);
int index = paramList.LastIndexOf (paramArray);
var methodArg = new MethodArgs ();
methodArg.index = index;
methodArg.extractValue = extractValue;
methodArg.isParamsArray = true;
methodArg.paramsArrayType = paramArrayType;
argTypes.Add (methodArg);
} else if (currentLuaParam > nLuaParams) { // Adds optional parameters
if (currentNetParam.IsOptional)
paramList.Add (currentNetParam.DefaultValue);
else {
isMethod = false;
break;
}
} else if (currentNetParam.IsOptional)
paramList.Add (currentNetParam.DefaultValue);
else { // No match
isMethod = false;
break;
}
}
if (currentLuaParam != nLuaParams + 1) // Number of parameters does not match
isMethod = false;
if (isMethod) {
methodCache.args = paramList.ToArray ();
methodCache.cachedMethod = method;
methodCache.outList = outList.ToArray ();
methodCache.argTypes = argTypes.ToArray ();
}
return isMethod;
}
/// <summary>
/// CP: Fix for operator overloading failure
/// Returns true if the type is set and assigns the extract value
/// </summary>
/// <param name="luaState"></param>
/// <param name="currentLuaParam"></param>
/// <param name="currentNetParam"></param>
/// <param name="extractValue"></param>
/// <returns></returns>
private bool IsTypeCorrect (LuaState luaState, int currentLuaParam, ParameterInfo currentNetParam, out ExtractValue extractValue)
{
try {
return (extractValue = translator.typeChecker.CheckLuaType (luaState, currentLuaParam, currentNetParam.ParameterType)) != null;
} catch {
extractValue = null;
Debug.WriteLine ("Type wasn't correct");
return false;
}
}
private bool IsParamsArray (LuaState luaState, int currentLuaParam, ParameterInfo currentNetParam, out ExtractValue extractValue)
{
extractValue = null;
if (currentNetParam.GetCustomAttributes (typeof(ParamArrayAttribute), false).Any ()) {
LuaTypes luaType;
try {
luaType = LuaLib.LuaType (luaState, currentLuaParam);
} catch (Exception ex) {
Debug.WriteLine ("Could not retrieve lua type while attempting to determine params Array Status.");
Debug.WriteLine (ex.Message);
extractValue = null;
return false;
}
if (luaType == LuaTypes.Table) {
try {
extractValue = translator.typeChecker.GetExtractor (typeof(LuaTable));
} catch (Exception/* ex*/) {
Debug.WriteLine ("An error occurred during an attempt to retrieve a LuaTable extractor while checking for params array status.");
}
if (extractValue != null) {
return true;
}
} else {
var paramElementType = currentNetParam.ParameterType.GetElementType ();
try {
extractValue = translator.typeChecker.CheckLuaType (luaState, currentLuaParam, paramElementType);
} catch (Exception/* ex*/) {
Debug.WriteLine (string.Format ("An error occurred during an attempt to retrieve an extractor ({0}) while checking for params array status.", paramElementType.FullName));
}
if (extractValue != null) {
return true;
}
}
}
Debug.WriteLine ("Type wasn't Params object.");
return false;
}
}
}
\ No newline at end of file
......@@ -571,6 +571,7 @@ namespace NLua
PushObject (luaState, func, "luaNet_function");
}
/*
* Pushes a CLR object into the Lua stack as an userdata
* with the provided metatable
......@@ -651,6 +652,7 @@ namespace NLua
LuaLib.LuaRawSet (luaState, -3);
// Bind C# operator with Lua metamethods (__add, __sub, __mul)
RegisterOperatorsFunctions (luaState, o.GetType ());
RegisterCallMethodForDelegate (luaState, o);
}
} else
LuaLib.LuaLGetMetatable (luaState, metatable);
......@@ -667,6 +669,16 @@ namespace NLua
LuaLib.LuaRemove (luaState, -2);
}
void RegisterCallMethodForDelegate (LuaState luaState, object o)
{
if (!(o is Delegate))
return;
LuaLib.LuaPushString (luaState, "__call");
LuaLib.LuaPushStdCallCFunction (luaState, metaFunctions.CallDelegateFunction);
LuaLib.LuaRawSet (luaState, -3);
}
void RegisterOperatorsFunctions (LuaState luaState, Type type)
{
if (type.HasAdditionOpertator ()) {
......@@ -930,8 +942,8 @@ namespace NLua
if (o == null)
LuaLib.LuaPushNil (luaState);
else if (o is sbyte || o is byte || o is short || o is ushort ||
o is int || o is uint || o is long || o is float ||
o is ulong || o is decimal || o is double) {
o is int || o is uint || o is long || o is float ||
o is ulong || o is decimal || o is double) {
double d = Convert.ToDouble (o);
LuaLib.LuaPushNumber (luaState, d);
} else if (o is char) {
......
using System;
using System.Text;
using System.Collections.Generic;
using NLuaTest.Mock;
using System.Reflection;
using System.Threading;
using NLua;
using NLua.Exceptions;
#if MONOTOUCH
using MonoTouch.Foundation;
#endif
#if WINDOWS_PHONE
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using SetUp = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestInitializeAttribute;
using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
#else
using NUnit.Framework;
#endif
namespace NLuaTest
{
#if MONOTOUCH
[Preserve (AllMembers = true)]
#endif
public class master
{
public static string read()
{
return "test-master";
}
}
#if MONOTOUCH
[Preserve (AllMembers = true)]
#endif
public class testClass : master
{
public String strData;
public int intData;
public static string read2()
{
return "test";
}
}
#if MONOTOUCH
[Preserve (AllMembers = true)]
using System;
using System.Text;
using System.Collections.Generic;
using NLuaTest.Mock;
using System.Reflection;
using System.Threading;
using NLua;
using NLua.Exceptions;
#if MONOTOUCH
using MonoTouch.Foundation;
#endif
#if WINDOWS_PHONE
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using SetUp = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestInitializeAttribute;
using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
#else
using NUnit.Framework;
#endif
namespace NLuaTest
{
#if MONOTOUCH
[Preserve (AllMembers = true)]
#endif
public class master
{
public static string read()
{
return "test-master";
}
}
#if MONOTOUCH
[Preserve (AllMembers = true)]
#endif
public class testClass : master
{
public String strData;
public int intData;
public static string read2()
{
return "test";
}
}
#if MONOTOUCH
[Preserve (AllMembers = true)]
#endif
public class DefaultElementModel
{
public Action<double> DrawMe{ get; set; }
}
#if MONOTOUCH
[Preserve (AllMembers = true)]
#endif
public class TestCaseName {
public string name = "name";
......@@ -55,1886 +63,1886 @@ namespace NLuaTest
return "**" + name + "**";
}
}
}
}
#if MONOTOUCH
[Preserve (AllMembers = true)]
#endif
public class Vector
{
public double x;
public double y;
public static Vector operator * (float k, Vector v)
{
var r = new Vector ();
r.x = v.x * k;
r.y = v.y * k;
return r;
}
public static Vector operator * (Vector v, float k)
{
var r = new Vector ();
r.x = v.x * k;
r.y = v.y * k;
return r;
}
public void Func ()
{
Console.WriteLine ("Func");
}
}
public static class VectorExtension
{
public static double Lenght (this Vector v)
{
return v.x * v.x + v.y * v.y;
}
}
[TestFixture]
#if MONOTOUCH
[Preserve (AllMembers = true)]
#endif
public class LuaTests
{
public static readonly char UnicodeChar = '\uE007';
public static string UnicodeString
{
get
{
return Convert.ToString (UnicodeChar);
}
}
/*
* Tests capturing an exception
*/
[Test]
public void ThrowException ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("luanet.load_assembly('mscorlib')");
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
lua.DoString ("test=TestClass()");
lua.DoString ("err,errMsg=pcall(test.exceptionMethod,test)");
bool err = (bool)lua ["err"];
Exception errMsg = (Exception)lua ["errMsg"];
Assert.AreEqual (false , err);
Assert.AreNotEqual (null, errMsg.InnerException);
Assert.AreEqual ("exception test", errMsg.InnerException.Message);
}
}
/*
* Tests capturing an exception
*/
[Test]
public void ThrowUncaughtException ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("luanet.load_assembly('mscorlib')");
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
lua.DoString ("test=TestClass()");
try {
lua.DoString ("test:exceptionMethod()");
//failed
Assert.AreEqual(false, true);
} catch (Exception) {
//passed
Assert.AreEqual (true, true);
}
}
}
/*
* Tests nullable fields
*/
[Test]
public void TestNullable ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("luanet.load_assembly('mscorlib')");
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
lua.DoString ("test=TestClass()");
lua.DoString ("val=test.NullableBool");
Assert.AreEqual (null, (object)lua ["val"]);
lua.DoString ("test.NullableBool = true");
lua.DoString ("val=test.NullableBool");
Assert.AreEqual (true, (bool)lua ["val"]);
}
}
/*
* Tests structure assignment
*/
[Test]
public void TestStructs ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
lua.DoString ("test=TestClass()");
lua.DoString ("TestStruct=luanet.import_type('NLuaTest.Mock.TestStruct')");
lua.DoString ("struct=TestStruct(2)");
lua.DoString ("test.Struct = struct");
lua.DoString ("val=test.Struct.val");
Assert.AreEqual (2.0d, (double)lua ["val"]);
}
}
[Test]
public void TestStructHashesEqual()
{
using (Lua lua = new Lua())
{
lua.DoString("luanet.load_assembly('NLuaTest')");
lua.DoString("TestStruct=luanet.import_type('NLuaTest.Mock.TestStruct')");
lua.DoString("struct1=TestStruct(0)");
lua.DoString("struct2=TestStruct(0)");
lua.DoString("struct2.val=1");
Assert.AreEqual(0, (double)lua["struct1.val"]);
}
}
[Test]
public void TestMethodOverloads ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("luanet.load_assembly('mscorlib')");
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
lua.DoString ("test=TestClass()");
lua.DoString ("test:MethodOverload()");
lua.DoString ("test:MethodOverload(test)");
lua.DoString ("test:MethodOverload(1,1,1)");
lua.DoString ("test:MethodOverload(2,2,i)\r\nprint(i)");
}
}
[Test]
public void TestDispose ()
{
System.GC.Collect ();
#if !WINDOWS_PHONE
long startingMem = System.Diagnostics.Process.GetCurrentProcess ().WorkingSet64;
for (int i = 0; i < 100; i++) {
using (Lua lua = new Lua ()) {
_Calc (lua, i);
}
}
//TODO: make this test assert so that it is useful
Console.WriteLine ("Was using " + startingMem / 1024 / 1024 + "MB, now using: " + System.Diagnostics.Process.GetCurrentProcess ().WorkingSet64 / 1024 / 1024 + "MB");
#endif
}
private void _Calc (Lua lua, int i)
{
lua.DoString (
"sqrt = math.sqrt;" +
"sqr = function(x) return math.pow(x,2); end;" +
"log = math.log;" +
"log10 = math.log10;" +
"exp = math.exp;" +
"sin = math.sin;" +
"cos = math.cos;" +
"tan = math.tan;" +
"abs = math.abs;"
);
lua.DoString ("function calcVP(a,b) return a+b end");
LuaFunction lf = lua.GetFunction ("calcVP");
lf.Call (i, 20);
}
[Test]
public void TestThreading ()
{
using (Lua lua = new Lua ()) {
object lua_locker = new object ();
DoWorkClass doWork = new DoWorkClass ();
lua.RegisterFunction ("dowork", doWork, typeof(DoWorkClass).GetMethod ("DoWork"));
bool failureDetected = false;
int completed = 0;
int iterations = 10;
for (int i = 0; i < iterations; i++) {
ThreadPool.QueueUserWorkItem (new WaitCallback (delegate (object o) {
try {
lock (lua_locker) {
lua.DoString ("dowork()");
}
} catch (Exception e) {
Console.Write (e);
failureDetected = true;
}
completed++;
}));
}
while (completed < iterations && !failureDetected)
Thread.Sleep (50);
Assert.AreEqual (false, failureDetected);
}
}
[Test]
public void TestPrivateMethod ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("luanet.load_assembly('mscorlib')");
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
lua.DoString ("test=TestClass()");
try {
lua.DoString ("test:_PrivateMethod()");
} catch {
Assert.AreEqual (true, true);
return;
}
Assert.AreEqual(true, false);
}
}
/*
* Tests functions
*/
[Test]
public void TestFunctions ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("luanet.load_assembly('mscorlib')");
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.RegisterFunction ("p", null, typeof(System.Console).GetMethod ("WriteLine", new Type [] { typeof(String) }));
/// Lua command that works (prints to console)
lua.DoString ("p('Foo')");
/// Yet this works...
lua.DoString ("string.gsub('some string', '(%w+)', function(s) p(s) end)");
/// This fails if you don't fix Lua5.1 lstrlib.c/add_value to treat LUA_TUSERDATA the same as LUA_FUNCTION
lua.DoString ("string.gsub('some string', '(%w+)', p)");
}
}
/*
* Tests making an object from a Lua table and calling one of
* methods the table overrides.
*/
[Test]
public void LuaTableOverridedMethod ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
lua.DoString ("test={}");
lua.DoString ("function test:overridableMethod(x,y) return x*y; end");
lua.DoString ("luanet.make_object(test,'NLuaTest.Mock.TestClass')");
lua.DoString ("a=TestClass.callOverridable(test,2,3)");
int a = (int)lua.GetNumber ("a");
lua.DoString ("luanet.free_object(test)");
Assert.AreEqual (6, a);
}
}
/*
* Tests making an object from a Lua table and calling a method
* the table does not override.
*/
[Test]
public void LuaTableInheritedMethod ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
lua.DoString ("test={}");
lua.DoString ("function test:overridableMethod(x,y) return x*y; end");
lua.DoString ("luanet.make_object(test,'NLuaTest.Mock.TestClass')");
lua.DoString ("test:setVal(3)");
lua.DoString ("a=test.testval");
int a = (int)lua.GetNumber ("a");
lua.DoString ("luanet.free_object(test)");
Assert.AreEqual (3, a);
//Console.WriteLine("interface returned: "+a);
}
}
/// <summary>
/// Basic multiply method which expects 2 floats
/// </summary>
/// <param name="val"></param>
/// <param name="val2"></param>
/// <returns></returns>
private float _TestException (float val, float val2)
{
return val * val2;
}
class LuaEventArgsHandler : NLua.Method.LuaDelegate
{
void CallFunction (object sender, EventArgs eventArgs)
{
object [] args = new object [] {sender, eventArgs };
object [] inArgs = new object [] { sender, eventArgs };
int [] outArgs = new int [] { };
base.CallFunction (args, inArgs, outArgs);
}
}
[Test]
public void TestEventException ()
{
using (Lua lua = new Lua ()) {
//Register a C# function
MethodInfo testException = this.GetType ().GetMethod ("_TestException", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Instance, null, new Type [] {
typeof(float),
typeof(float)
}, null);
lua.RegisterFunction ("Multiply", this, testException);
lua.RegisterLuaDelegateType (typeof(EventHandler<EventArgs>), typeof(LuaEventArgsHandler));
//create the lua event handler code for the entity
//includes the bad code!
lua.DoString ("function OnClick(sender, eventArgs)\r\n" +
"--Multiply expects 2 floats, but instead receives 2 strings\r\n" +
"Multiply(asd, es)\r\n" +
"end");
//create the lua event handler code for the entity
//good code
//lua.DoString("function OnClick(sender, eventArgs)\r\n" +
// "--Multiply expects 2 floats\r\n" +
// "Multiply(2, 50)\r\n" +
// "end");
//Create the event handler script
lua.DoString ("function SubscribeEntity(e)\r\ne.Clicked:Add(OnClick)\r\nend");
//Create the entity object
Entity entity = new Entity ();
//Register the entity object with the event handler inside lua
LuaFunction lf = lua.GetFunction ("SubscribeEntity");
lf.Call (new object [1] { entity });
try {
//Cause the event to be fired
entity.Click ();
//failed
Assert.AreEqual(true, false);
} catch (LuaException) {
//passed
Assert.AreEqual (true, true);
}
}
}
[Test]
public void TestExceptionWithChunkOverload ()
{
using (Lua lua = new Lua ()) {
try {
lua.DoString ("thiswillthrowanerror", "MyChunk");
} catch (Exception e) {
Assert.AreEqual (true, e.Message.StartsWith ("[string \"MyChunk\"]"));
}
}
}
[Test]
public void TestGenerics ()
{
//Im not sure support for generic classes is possible to implement, see: http://msdn.microsoft.com/en-us/library/system.reflection.methodinfo.containsgenericparameters.aspx
//specifically the line that says: "If the ContainsGenericParameters property returns true, the method cannot be invoked"
//TestClassGeneric<string> genericClass = new TestClassGeneric<string>();
//lua.RegisterFunction("genericMethod", genericClass, typeof(TestClassGeneric<>).GetMethod("GenericMethod"));
//lua.RegisterFunction("regularMethod", genericClass, typeof(TestClassGeneric<>).GetMethod("RegularMethod"));
using (Lua lua = new Lua ()) {
TestClassWithGenericMethod classWithGenericMethod = new TestClassWithGenericMethod ();
////////////////////////////////////////////////////////////////////////////
/// ////////////////////////////////////////////////////////////////////////
/// IMPORTANT: Use generic method with the type you will call or generic methods will fail with iOS
/// ////////////////////////////////////////////////////////////////////////
classWithGenericMethod.GenericMethod<double>(99.0);
classWithGenericMethod.GenericMethod<TestClass>(new TestClass (99));
////////////////////////////////////////////////////////////////////////////
/// ////////////////////////////////////////////////////////////////////////
lua.RegisterFunction ("genericMethod2", classWithGenericMethod, typeof(TestClassWithGenericMethod).GetMethod ("GenericMethod"));
try {
lua.DoString ("genericMethod2(100)");
} catch {
}
Assert.AreEqual (true, classWithGenericMethod.GenericMethodSuccess);
Assert.AreEqual (true, classWithGenericMethod.Validate<double> (100)); //note the gotcha: numbers are all being passed to generic methods as doubles
try {
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
lua.DoString ("test=TestClass(56)");
lua.DoString ("genericMethod2(test)");
} catch {
}
Assert.AreEqual (true, classWithGenericMethod.GenericMethodSuccess);
Assert.AreEqual (56, (classWithGenericMethod.PassedValue as TestClass).val);
}
}
[Test]
public void RegisterFunctionStressTest ()
{
const int Count = 200; // it seems to work with 41
using (Lua lua = new Lua ()) {
MyClass t = new MyClass ();
for (int i = 1; i < Count - 1; ++i) {
lua.RegisterFunction ("func" + i, t, typeof(MyClass).GetMethod ("Func1"));
}
lua.RegisterFunction ("func" + (Count - 1), t, typeof(MyClass).GetMethod ("Func1"));
lua.DoString ("print(func1())");
}
}
[Test]
public void TestMultipleOutParameters ()
{
using (Lua lua = new Lua ()) {
TestClass t1 = new TestClass ();
lua ["netobj"] = t1;
lua.DoString ("a,b,c=netobj:outValMutiple(2)");
int a = (int)lua.GetNumber ("a");
string b = (string)lua.GetString ("b");
string c = (string)lua.GetString ("c");
Assert.AreEqual (2, a);
Assert.AreNotEqual (null, b);
Assert.AreNotEqual (null, c);
}
}
[Test]
public void TestLoadStringLeak ()
{
//Test to prevent stack overflow
//See: http://code.google.com/p/nlua/issues/detail?id=5
//number of iterations to test
int count = 1000;
using (Lua lua = new Lua ()) {
for (int i = 0; i < count; i++) {
lua.LoadString ("abc = 'def'", string.Empty);
}
}
//any thrown exceptions cause the test run to fail
}
[Test]
public void TestLoadFileLeak ()
{
//Test to prevent stack overflow
//See: http://code.google.com/p/nlua/issues/detail?id=5
//number of iterations to test
int count = 1000;
using (Lua lua = new Lua ()) {
for (int i = 0; i < count; i++) {
lua.LoadFile (Environment.CurrentDirectory + System.IO.Path.DirectorySeparatorChar + "test.lua");
}
}
//any thrown exceptions cause the test run to fail
}
[Test]
public void TestRegisterFunction ()
{
using (Lua lua = new Lua ()) {
lua.RegisterFunction ("func1", null, typeof(TestClass2).GetMethod ("func"));
object[] vals1 = lua.GetFunction ("func1").Call (2, 3);
Assert.AreEqual (5.0f, Convert.ToSingle (vals1 [0]));
TestClass2 obj = new TestClass2 ();
lua.RegisterFunction ("func2", obj, typeof(TestClass2).GetMethod ("funcInstance"));
vals1 = lua.GetFunction ("func2").Call (2, 3);
Assert.AreEqual (5.0f, Convert.ToSingle (vals1 [0]));
}
}
/*
* Tests if DoString is correctly returning values
*/
[Test]
public void DoString ()
{
using (Lua lua = new Lua ()) {
object[] res = lua.DoString ("a=2\nreturn a,3");
//Console.WriteLine("a="+res[0]+", b="+res[1]);
Assert.AreEqual (res [0], 2d);
Assert.AreEqual (res [1], 3d);
}
}
/*
* Tests getting of global numeric variables
*/
[Test]
public void GetGlobalNumber ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("a=2");
double num = lua.GetNumber ("a");
//Console.WriteLine("a="+num);
Assert.AreEqual (num, 2d);
}
}
/*
* Tests setting of global numeric variables
*/
[Test]
public void SetGlobalNumber ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("a=2");
lua ["a"] = 3;
double num = lua.GetNumber ("a");
//Console.WriteLine("a="+num);
Assert.AreEqual (num, 3d);
}
}
/*
* Tests getting of numeric variables from tables
* by specifying variable path
*/
[Test]
public void GetNumberInTable ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("a={b={c=2}}");
double num = lua.GetNumber ("a.b.c");
//Console.WriteLine("a.b.c="+num);
Assert.AreEqual (num, 2d);
}
}
/*
* Tests setting of numeric variables from tables
* by specifying variable path
*/
[Test]
public void SetNumberInTable ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("a={b={c=2}}");
lua ["a.b.c"] = 3;
double num = lua.GetNumber ("a.b.c");
//Console.WriteLine("a.b.c="+num);
Assert.AreEqual (num, 3d);
}
}
/*
* Tests getting of global string variables
*/
[Test]
public void GetGlobalString ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("a=\"test\"");
string str = lua.GetString ("a");
//Console.WriteLine("a="+str);
Assert.AreEqual (str, "test");
}
}
/*
* Tests setting of global string variables
*/
[Test]
public void SetGlobalString ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("a=\"test\"");
lua ["a"] = "new test";
string str = lua.GetString ("a");
//Console.WriteLine("a="+str);
Assert.AreEqual (str, "new test");
}
}
/*
* Tests getting of string variables from tables
* by specifying variable path
*/
[Test]
public void GetStringInTable ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("a={b={c=\"test\"}}");
string str = lua.GetString ("a.b.c");
//Console.WriteLine("a.b.c="+str);
Assert.AreEqual (str, "test");
}
}
/*
* Tests setting of string variables from tables
* by specifying variable path
*/
[Test]
public void SetStringInTable ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("a={b={c=\"test\"}}");
lua ["a.b.c"] = "new test";
string str = lua.GetString ("a.b.c");
//Console.WriteLine("a.b.c="+str);
Assert.AreEqual (str, "new test");
}
}
/*
* Tests getting and setting of global table variables
*/
[Test]
public void GetAndSetTable ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("a={b={c=2}}\nb={c=3}");
LuaTable tab = lua.GetTable ("b");
lua ["a.b"] = tab;
double num = lua.GetNumber ("a.b.c");
//Console.WriteLine("a.b.c="+num);
Assert.AreEqual (num, 3d);
}
}
/*
* Tests getting of numeric field of a table
*/
[Test]
public void GetTableNumericField1 ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("a={b={c=2}}");
LuaTable tab = lua.GetTable ("a.b");
double num = (double)tab ["c"];
//Console.WriteLine("a.b.c="+num);
Assert.AreEqual (num, 2d);
}
}
/*
* Tests getting of numeric field of a table
* (the field is inside a subtable)
*/
[Test]
public void GetTableNumericField2 ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("a={b={c=2}}");
LuaTable tab = lua.GetTable ("a");
double num = (double)tab ["b.c"];
//Console.WriteLine("a.b.c="+num);
Assert.AreEqual (num, 2d);
}
}
/*
* Tests setting of numeric field of a table
*/
[Test]
public void SetTableNumericField1 ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("a={b={c=2}}");
LuaTable tab = lua.GetTable ("a.b");
tab ["c"] = 3;
double num = lua.GetNumber ("a.b.c");
//Console.WriteLine("a.b.c="+num);
Assert.AreEqual (num, 3d);
}
}
/*
* Tests setting of numeric field of a table
* (the field is inside a subtable)
*/
[Test]
public void SetTableNumericField2 ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("a={b={c=2}}");
LuaTable tab = lua.GetTable ("a");
tab ["b.c"] = 3;
double num = lua.GetNumber ("a.b.c");
//Console.WriteLine("a.b.c="+num);
Assert.AreEqual (num, 3d);
}
}
/*
* Tests getting of string field of a table
*/
[Test]
public void GetTableStringField1 ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("a={b={c=\"test\"}}");
LuaTable tab = lua.GetTable ("a.b");
string str = (string)tab ["c"];
//Console.WriteLine("a.b.c="+str);
Assert.AreEqual (str, "test");
}
}
/*
* Tests getting of string field of a table
* (the field is inside a subtable)
*/
[Test]
public void GetTableStringField2 ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("a={b={c=\"test\"}}");
LuaTable tab = lua.GetTable ("a");
string str = (string)tab ["b.c"];
//Console.WriteLine("a.b.c="+str);
Assert.AreEqual (str, "test");
}
}
/*
* Tests setting of string field of a table
*/
[Test]
public void SetTableStringField1 ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("a={b={c=\"test\"}}");
LuaTable tab = lua.GetTable ("a.b");
tab ["c"] = "new test";
string str = lua.GetString ("a.b.c");
//Console.WriteLine("a.b.c="+str);
Assert.AreEqual (str, "new test");
}
}
/*
* Tests setting of string field of a table
* (the field is inside a subtable)
*/
[Test]
public void SetTableStringField2 ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("a={b={c=\"test\"}}");
LuaTable tab = lua.GetTable ("a");
tab ["b.c"] = "new test";
string str = lua.GetString ("a.b.c");
//Console.WriteLine("a.b.c="+str);
Assert.AreEqual (str, "new test");
}
}
/*
* Tests calling of a global function with zero arguments
*/
[Test]
public void CallGlobalFunctionNoArgs ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("a=2\nfunction f()\na=3\nend");
lua.GetFunction ("f").Call ();
double num = lua.GetNumber ("a");
//Console.WriteLine("a="+num);
Assert.AreEqual (num, 3d);
}
}
/*
* Tests calling of a global function with one argument
*/
[Test]
public void CallGlobalFunctionOneArg ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("a=2\nfunction f(x)\na=a+x\nend");
lua.GetFunction ("f").Call (1);
double num = lua.GetNumber ("a");
//Console.WriteLine("a="+num);
Assert.AreEqual (num, 3d);
}
}
/*
* Tests calling of a global function with two arguments
*/
[Test]
public void CallGlobalFunctionTwoArgs ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("a=2\nfunction f(x,y)\na=x+y\nend");
lua.GetFunction ("f").Call (1, 3);
double num = lua.GetNumber ("a");
//Console.WriteLine("a="+num);
Assert.AreEqual (num, 4d);
}
}
/*
* Tests calling of a global function that returns one value
*/
[Test]
public void CallGlobalFunctionOneReturn ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("function f(x)\nreturn x+2\nend");
object[] ret = lua.GetFunction ("f").Call (3);
//Console.WriteLine("ret="+ret[0]);
Assert.AreEqual (1, ret.Length);
Assert.AreEqual (5, (double)ret [0]);
}
}
/*
* Tests calling of a global function that returns two values
*/
[Test]
public void CallGlobalFunctionTwoReturns ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("function f(x,y)\nreturn x,x+y\nend");
object[] ret = lua.GetFunction ("f").Call (3, 2);
//Console.WriteLine("ret="+ret[0]+","+ret[1]);
Assert.AreEqual (2, ret.Length);
Assert.AreEqual (3, (double)ret [0]);
Assert.AreEqual (5, (double)ret [1]);
}
}
/*
* Tests calling of a function inside a table
*/
[Test]
public void CallTableFunctionTwoReturns ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("a={}\nfunction a.f(x,y)\nreturn x,x+y\nend");
object[] ret = lua.GetFunction ("a.f").Call (3, 2);
//Console.WriteLine("ret="+ret[0]+","+ret[1]);
Assert.AreEqual (2, ret.Length);
Assert.AreEqual (3, (double)ret [0]);
Assert.AreEqual (5, (double)ret [1]);
}
}
/*
* Tests setting of a global variable to a CLR object value
*/
[Test]
public void SetGlobalObject ()
{
using (Lua lua = new Lua ()) {
TestClass t1 = new TestClass ();
t1.testval = 4;
lua ["netobj"] = t1;
object o = lua ["netobj"];
Assert.AreEqual (true, o is TestClass);
TestClass t2 = (TestClass)lua ["netobj"];
Assert.AreEqual (t2.testval, 4);
Assert.AreEqual (t1 , t2);
}
}
///*
// * Tests if CLR object is being correctly collected by Lua
// */
//[Test]
//public void GarbageCollection()
//{
// using (Lua lua = new Lua())
// {
// TestClass t1 = new TestClass();
// t1.testval = 4;
// lua["netobj"] = t1;
// TestClass t2 = (TestClass)lua["netobj"];
// Assert.True(lua[0] != null);
// lua.DoString("netobj=nil;collectgarbage();");
// Assert.True(lua.translator.objects[0] == null);
// }
//}
/*
* Tests setting of a table field to a CLR object value
*/
[Test]
public void SetTableObjectField1 ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("a={b={c=\"test\"}}");
LuaTable tab = lua.GetTable ("a.b");
TestClass t1 = new TestClass ();
t1.testval = 4;
tab ["c"] = t1;
TestClass t2 = (TestClass)lua ["a.b.c"];
//Console.WriteLine("a.b.c="+t2.testval);
Assert.AreEqual (4, t2.testval);
Assert.AreEqual (t1 , t2);
}
}
/*
* Tests reading and writing of an object's field
*/
[Test]
public void AccessObjectField ()
{
using (Lua lua = new Lua ()) {
TestClass t1 = new TestClass ();
t1.val = 4;
lua ["netobj"] = t1;
lua.DoString ("var=netobj.val");
double var = (double)lua ["var"];
//Console.WriteLine("value from Lua="+var);
Assert.AreEqual (4, var);
lua.DoString ("netobj.val=3");
Assert.AreEqual (3, t1.val);
//Console.WriteLine("new val (from Lua)="+t1.val);
}
}
/*
* Tests reading and writing of an object's non-indexed
* property
*/
[Test]
public void AccessObjectProperty ()
{
using (Lua lua = new Lua ()) {
TestClass t1 = new TestClass ();
t1.testval = 4;
lua ["netobj"] = t1;
lua.DoString ("var=netobj.testval");
double var = (double)lua ["var"];
//Console.WriteLine("value from Lua="+var);
Assert.AreEqual (4, var);
lua.DoString ("netobj.testval=3");
Assert.AreEqual (3, t1.testval);
//Console.WriteLine("new val (from Lua)="+t1.testval);
}
}
[Test]
public void AccessObjectStringProperty ()
{
using (Lua lua = new Lua ()) {
TestClass t1 = new TestClass ();
t1.teststrval = "This is a string test";
lua ["netobj"] = t1;
lua.DoString ("var=netobj.teststrval");
string var = (string)lua ["var"];
Assert.AreEqual ("This is a string test", var);
lua.DoString ("netobj.teststrval='Another String'");
Assert.AreEqual ("Another String", t1.teststrval);
//Console.WriteLine("new val (from Lua)="+t1.testval);
}
}
/*
* Tests calling of an object's method with no overloads
*/
[Test]
public void CallObjectMethod ()
{
using (Lua lua = new Lua ()) {
TestClass t1 = new TestClass ();
t1.testval = 4;
lua ["netobj"] = t1;
lua.DoString ("netobj:setVal(3)");
Assert.AreEqual (3, t1.testval);
//Console.WriteLine("new val(from C#)="+t1.testval);
lua.DoString ("val=netobj:getVal()");
int val = (int)lua.GetNumber ("val");
Assert.AreEqual (3, val);
//Console.WriteLine("new val(from Lua)="+val);
}
}
/*
* Tests calling of an object's method with overloading
*/
[Test]
public void CallObjectMethodByType ()
{
using (Lua lua = new Lua ()) {
TestClass t1 = new TestClass ();
lua ["netobj"] = t1;
lua.DoString ("netobj:setVal('str')");
Assert.AreEqual ("str", t1.getStrVal ());
//Console.WriteLine("new val(from C#)="+t1.getStrVal());
}
}
/*
* Tests calling of an object's method with no overloading
* and out parameters
*/
[Test]
public void CallObjectMethodOutParam ()
{
using (Lua lua = new Lua ()) {
TestClass t1 = new TestClass ();
lua ["netobj"] = t1;
lua.DoString ("a,b=netobj:outVal()");
int a = (int)lua.GetNumber ("a");
int b = (int)lua.GetNumber ("b");
Assert.AreEqual (3, a);
Assert.AreEqual (5, b);
//Console.WriteLine("function returned (from lua)="+a+","+b);
}
}
/*
* Tests calling of an object's method with overloading and
* out params
*/
[Test]
public void CallObjectMethodOverloadedOutParam ()
{
using (Lua lua = new Lua ()) {
TestClass t1 = new TestClass ();
lua ["netobj"] = t1;
lua.DoString ("a,b=netobj:outVal(2)");
int a = (int)lua.GetNumber ("a");
int b = (int)lua.GetNumber ("b");
Assert.AreEqual (2, a);
Assert.AreEqual (5, b);
//Console.WriteLine("function returned (from lua)="+a+","+b);
}
}
/*
* Tests calling of an object's method with ref params
*/
[Test]
public void CallObjectMethodByRefParam ()
{
using (Lua lua = new Lua ()) {
TestClass t1 = new TestClass ();
lua ["netobj"] = t1;
lua.DoString ("a,b=netobj:outVal(2,3)");
int a = (int)lua.GetNumber ("a");
int b = (int)lua.GetNumber ("b");
Assert.AreEqual (2, a);
Assert.AreEqual (5, b);
//Console.WriteLine("function returned (from lua)="+a+","+b);
}
}
/*
* Tests calling of two versions of an object's method that have
* the same name and signature but implement different interfaces
*/
[Test]
public void CallObjectMethodDistinctInterfaces ()
{
using (Lua lua = new Lua ()) {
TestClass t1 = new TestClass ();
lua ["netobj"] = t1;
lua.DoString ("a=netobj:foo()");
lua.DoString ("b=netobj['NLuaTest.Mock.IFoo1.foo']");
int a = (int)lua.GetNumber ("a");
int b = (int)lua.GetNumber ("b");
Assert.AreEqual (5, a);
Assert.AreEqual (1, b);
//Console.WriteLine("function returned (from lua)="+a+","+b);
}
}
/*
* Tests instantiating an object with no-argument constructor
*/
[Test]
public void CreateNetObjectNoArgsCons ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("luanet.load_assembly(\"NLuaTest\")");
lua.DoString ("TestClass=luanet.import_type(\"NLuaTest.Mock.TestClass\")");
lua.DoString ("test=TestClass()");
lua.DoString ("test:setVal(3)");
object[] res = lua.DoString ("return test");
TestClass test = (TestClass)res [0];
//Console.WriteLine("returned: "+test.testval);
Assert.AreEqual (3, test.testval);
}
}
/*
* Tests instantiating an object with one-argument constructor
*/
[Test]
public void CreateNetObjectOneArgCons ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("luanet.load_assembly(\"NLuaTest\")");
lua.DoString ("TestClass=luanet.import_type(\"NLuaTest.Mock.TestClass\")");
lua.DoString ("test=TestClass(3)");
object[] res = lua.DoString ("return test");
TestClass test = (TestClass)res [0];
//Console.WriteLine("returned: "+test.testval);
Assert.AreEqual (3, test.testval);
}
}
/*
* Tests instantiating an object with overloaded constructor
*/
[Test]
public void CreateNetObjectOverloadedCons ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("luanet.load_assembly(\"NLuaTest\")");
lua.DoString ("TestClass=luanet.import_type(\"NLuaTest.Mock.TestClass\")");
lua.DoString ("test=TestClass('str')");
object[] res = lua.DoString ("return test");
TestClass test = (TestClass)res [0];
//Console.WriteLine("returned: "+test.getStrVal());
Assert.AreEqual ("str", test.getStrVal ());
}
}
/*
* Tests getting item of a CLR array
*/
[Test]
public void ReadArrayField ()
{
using (Lua lua = new Lua ()) {
string[] arr = new string [] { "str1", "str2", "str3" };
lua ["netobj"] = arr;
lua.DoString ("val=netobj[1]");
string val = lua.GetString ("val");
Assert.AreEqual ("str2", val);
//Console.WriteLine("new val(from array to Lua)="+val);
}
}
/*G
* Tests setting item of a CLR array
*/
[Test]
public void WriteArrayField ()
{
using (Lua lua = new Lua ()) {
string[] arr = new string [] { "str1", "str2", "str3" };
lua ["netobj"] = arr;
lua.DoString ("netobj[1]='test'");
Assert.AreEqual ("test", arr [1]);
//Console.WriteLine("new val(from Lua to array)="+arr[1]);
}
}
/*
* Tests creating a new CLR array
*/
[Test]
public void CreateArray ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("luanet.load_assembly(\"NLuaTest\")");
lua.DoString ("TestClass=luanet.import_type(\"NLuaTest.Mock.TestClass\")");
lua.DoString ("arr=TestClass[3]");
lua.DoString ("for i=0,2 do arr[i]=TestClass(i+1) end");
TestClass[] arr = (TestClass[])lua ["arr"];
Assert.AreEqual (arr [1].testval, 2);
}
}
/*
* Tests passing a Lua function to a delegate
* with value-type arguments
*/
[Test]
public void LuaDelegateValueTypes ()
{
using (Lua lua = new Lua ()) {
lua.RegisterLuaDelegateType (typeof(TestDelegate1), typeof(LuaTestDelegate1Handler));
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
lua.DoString ("test=TestClass()");
lua.DoString ("function func(x,y) return x+y; end");
lua.DoString ("test=TestClass()");
lua.DoString ("a=test:callDelegate1(func)");
int a = (int)lua.GetNumber ("a");
Assert.AreEqual (5, a);
//Console.WriteLine("delegate returned: "+a);
}
}
/*
* Tests passing a Lua function to a delegate
* with value-type arguments and out params
*/
[Test]
public void LuaDelegateValueTypesOutParam ()
{
using (Lua lua = new Lua ()) {
lua.RegisterLuaDelegateType (typeof(TestDelegate2), typeof(LuaTestDelegate2Handler));
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
lua.DoString ("test=TestClass()");
lua.DoString ("function func(x) return x,x*2; end");
lua.DoString ("test=TestClass()");
lua.DoString ("a=test:callDelegate2(func)");
int a = (int)lua.GetNumber ("a");
Assert.AreEqual (6, a);
//Console.WriteLine("delegate returned: "+a);
}
}
/*
* Tests passing a Lua function to a delegate
* with value-type arguments and ref params
*/
[Test]
public void LuaDelegateValueTypesByRefParam ()
{
using (Lua lua = new Lua ()) {
lua.RegisterLuaDelegateType (typeof(TestDelegate3), typeof(LuaTestDelegate3Handler));
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
lua.DoString ("test=TestClass()");
lua.DoString ("function func(x,y) return x+y; end");
lua.DoString ("test=TestClass()");
lua.DoString ("a=test:callDelegate3(func)");
int a = (int)lua.GetNumber ("a");
Assert.AreEqual (5, a);
//Console.WriteLine("delegate returned: "+a);
}
}
/*
* Tests passing a Lua function to a delegate
* with value-type arguments that returns a reference type
*/
[Test]
public void LuaDelegateValueTypesReturnReferenceType ()
{
using (Lua lua = new Lua ()) {
lua.RegisterLuaDelegateType (typeof(TestDelegate4), typeof(LuaTestDelegate4Handler));
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
lua.DoString ("test=TestClass()");
lua.DoString ("function func(x,y) return TestClass(x+y); end");
lua.DoString ("test=TestClass()");
lua.DoString ("a=test:callDelegate4(func)");
int a = (int)lua.GetNumber ("a");
Assert.AreEqual (5, a);
//Console.WriteLine("delegate returned: "+a);
}
}
/*
* Tests passing a Lua function to a delegate
* with reference type arguments
*/
[Test]
public void LuaDelegateReferenceTypes ()
{
using (Lua lua = new Lua ()) {
lua.RegisterLuaDelegateType (typeof(TestDelegate5), typeof(LuaTestDelegate5Handler));
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
lua.DoString ("test=TestClass()");
lua.DoString ("function func(x,y) return x.testval+y.testval; end");
lua.DoString ("a=test:callDelegate5(func)");
int a = (int)lua.GetNumber ("a");
Assert.AreEqual (5, a);
//Console.WriteLine("delegate returned: "+a);
}
}
/*
* Tests passing a Lua function to a delegate
* with reference type arguments and an out param
*/
[Test]
public void LuaDelegateReferenceTypesOutParam ()
{
using (Lua lua = new Lua ()) {
lua.RegisterLuaDelegateType (typeof(TestDelegate6), typeof(LuaTestDelegate6Handler));
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
lua.DoString ("test=TestClass()");
lua.DoString ("function func(x) return x,TestClass(x*2); end");
lua.DoString ("test=TestClass()");
lua.DoString ("a=test:callDelegate6(func)");
int a = (int)lua.GetNumber ("a");
Assert.AreEqual (6, a);
//Console.WriteLine("delegate returned: "+a);
}
}
/*
* Tests passing a Lua function to a delegate
* with reference type arguments and a ref param
*/
[Test]
public void LuaDelegateReferenceTypesByRefParam ()
{
using (Lua lua = new Lua ()) {
lua.RegisterLuaDelegateType (typeof(TestDelegate7), typeof(LuaTestDelegate7Handler));
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
lua.DoString ("test=TestClass()");
lua.DoString ("function func(x,y) return TestClass(x+y.testval); end");
lua.DoString ("a=test:callDelegate7(func)");
int a = (int)lua.GetNumber ("a");
Assert.AreEqual (5, a);
//Console.WriteLine("delegate returned: "+a);
}
}
#if MONOTOUCH
[Preserve (AllMembers = true)]
#endif
public class Vector
{
public double x;
public double y;
public static Vector operator * (float k, Vector v)
/*
* Tests passing a Lua table as an interface and
* calling one of its methods with value-type params
*/
[Test]
public void NLuaAAValueTypes ()
{
var r = new Vector ();
r.x = v.x * k;
r.y = v.y * k;
return r;
using (Lua lua = new Lua ()) {
lua.RegisterLuaClassType (typeof(ITest), typeof(LuaITestClassHandler));
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
lua.DoString ("test=TestClass()");
lua.DoString ("itest={}");
lua.DoString ("function itest:test1(x,y) return x+y; end");
lua.DoString ("test=TestClass()");
lua.DoString ("a=test:callInterface1(itest)");
int a = (int)lua.GetNumber ("a");
Assert.AreEqual (5, a);
//Console.WriteLine("interface returned: "+a);
}
}
/*
* Tests passing a Lua table as an interface and
* calling one of its methods with value-type params
* and an out param
*/
[Test]
public void NLuaValueTypesOutParam ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
lua.DoString ("test=TestClass()");
lua.DoString ("itest={}");
lua.DoString ("function itest:test2(x) return x,x*2; end");
lua.DoString ("test=TestClass()");
lua.DoString ("a=test:callInterface2(itest)");
int a = (int)lua.GetNumber ("a");
Assert.AreEqual (6, a);
//Console.WriteLine("interface returned: "+a);
}
}
/*
* Tests passing a Lua table as an interface and
* calling one of its methods with value-type params
* and a ref param
*/
[Test]
public void NLuaValueTypesByRefParam ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
lua.DoString ("test=TestClass()");
lua.DoString ("itest={}");
lua.DoString ("function itest:test3(x,y) return x+y; end");
lua.DoString ("test=TestClass()");
lua.DoString ("a=test:callInterface3(itest)");
int a = (int)lua.GetNumber ("a");
Assert.AreEqual (5, a);
//Console.WriteLine("interface returned: "+a);
}
}
/*
* Tests passing a Lua table as an interface and
* calling one of its methods with value-type params
* returning a reference type param
*/
[Test]
public void NLuaValueTypesReturnReferenceType ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
lua.DoString ("test=TestClass()");
lua.DoString ("itest={}");
lua.DoString ("function itest:test4(x,y) return TestClass(x+y); end");
lua.DoString ("test=TestClass()");
lua.DoString ("a=test:callInterface4(itest)");
int a = (int)lua.GetNumber ("a");
Assert.AreEqual (5, a);
//Console.WriteLine("interface returned: "+a);
}
}
/*
* Tests passing a Lua table as an interface and
* calling one of its methods with reference type params
*/
[Test]
public void NLuaReferenceTypes ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
lua.DoString ("test=TestClass()");
lua.DoString ("itest={}");
lua.DoString ("function itest:test5(x,y) return x.testval+y.testval; end");
lua.DoString ("test=TestClass()");
lua.DoString ("a=test:callInterface5(itest)");
int a = (int)lua.GetNumber ("a");
Assert.AreEqual (5, a);
//Console.WriteLine("interface returned: "+a);
}
}
/*
* Tests passing a Lua table as an interface and
* calling one of its methods with reference type params
* and an out param
*/
[Test]
public void NLuaReferenceTypesOutParam ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
lua.DoString ("test=TestClass()");
lua.DoString ("itest={}");
lua.DoString ("function itest:test6(x) return x,TestClass(x*2); end");
lua.DoString ("test=TestClass()");
lua.DoString ("a=test:callInterface6(itest)");
int a = (int)lua.GetNumber ("a");
Assert.AreEqual (6, a);
//Console.WriteLine("interface returned: "+a);
}
}
/*
* Tests passing a Lua table as an interface and
* calling one of its methods with reference type params
* and a ref param
*/
[Test]
public void NLuaReferenceTypesByRefParam ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
lua.DoString ("test=TestClass()");
lua.DoString ("itest={}");
lua.DoString ("function itest:test7(x,y) return TestClass(x+y.testval); end");
lua.DoString ("a=test:callInterface7(itest)");
int a = (int)lua.GetNumber ("a");
Assert.AreEqual (5, a);
//Console.WriteLine("interface returned: "+a);
}
}
public static Vector operator * (Vector v, float k)
#region LUA_BOILERPLATE_CLASS
/*** This class is used to bind the .NET world with the Lua world, this boilerplate code is pratically the same, get values call Lua function return value back,
* this class is usually dynamic generated using System.Reflection.Emit, but this will not work on iOS. */
class LuaTestClassHandler: TestClass, ILuaGeneratedType
{
var r = new Vector ();
r.x = v.x * k;
r.y = v.y * k;
return r;
public LuaTable __luaInterface_luaTable;
public Type[][] __luaInterface_returnTypes;
public LuaTestClassHandler (LuaTable luaTable, Type[][] returnTypes)
{
__luaInterface_luaTable = luaTable;
__luaInterface_returnTypes = returnTypes;
}
public LuaTable LuaInterfaceGetLuaTable ()
{
return __luaInterface_luaTable;
}
public override int overridableMethod (int x, int y)
{
object [] args = new object [] {
__luaInterface_luaTable,
x,
y
};
object [] inArgs = new object [] {
__luaInterface_luaTable,
x,
y
};
int [] outArgs = new int [] { };
Type [] returnTypes = __luaInterface_returnTypes [0];
LuaFunction function = NLua.Method.LuaClassHelper.GetTableFunction (__luaInterface_luaTable, "overridableMethod");
object ret = NLua.Method.LuaClassHelper.CallFunction (function, args, returnTypes, inArgs, outArgs);
return (int)ret;
}
}
public void Func ()
class LuaITestClassHandler : ILuaGeneratedType, ITest
{
Console.WriteLine ("Func");
public LuaTable __luaInterface_luaTable;
public Type[][] __luaInterface_returnTypes;
public LuaITestClassHandler (LuaTable luaTable, Type[][] returnTypes)
{
__luaInterface_luaTable = luaTable;
__luaInterface_returnTypes = returnTypes;
}
public LuaTable LuaInterfaceGetLuaTable ()
{
return __luaInterface_luaTable;
}
public int intProp {
get {
object [] args = new object [] { __luaInterface_luaTable };
object [] inArgs = new object [] { __luaInterface_luaTable };
int [] outArgs = new int [] { };
Type [] returnTypes = __luaInterface_returnTypes [0];
LuaFunction function = NLua.Method.LuaClassHelper.GetTableFunction (__luaInterface_luaTable, "get_intProp");
object ret = NLua.Method.LuaClassHelper.CallFunction (function, args, returnTypes, inArgs, outArgs);
return (int)ret;
}
set {
int i = value;
object [] args = new object [] {
__luaInterface_luaTable ,
i
};
object [] inArgs = new object [] {
__luaInterface_luaTable,
i
};
int [] outArgs = new int [] { };
Type [] returnTypes = __luaInterface_returnTypes [1];
LuaFunction function = NLua.Method.LuaClassHelper.GetTableFunction (__luaInterface_luaTable, "set_intProp");
NLua.Method.LuaClassHelper.CallFunction (function, args, returnTypes, inArgs, outArgs);
}
}
public TestClass refProp {
get {
object [] args = new object [] { __luaInterface_luaTable };
object [] inArgs = new object [] { __luaInterface_luaTable };
int [] outArgs = new int [] { };
Type [] returnTypes = __luaInterface_returnTypes [2];
LuaFunction function = NLua.Method.LuaClassHelper.GetTableFunction (__luaInterface_luaTable, "get_refProp");
object ret = NLua.Method.LuaClassHelper.CallFunction (function, args, returnTypes, inArgs, outArgs);
return (TestClass)ret;
}
set {
TestClass test = value;
object [] args = new object [] {
__luaInterface_luaTable ,
test
};
object [] inArgs = new object [] {
__luaInterface_luaTable,
test
};
int [] outArgs = new int [] { };
Type [] returnTypes = __luaInterface_returnTypes [3];
LuaFunction function = NLua.Method.LuaClassHelper.GetTableFunction (__luaInterface_luaTable, "set_refProp");
NLua.Method.LuaClassHelper.CallFunction (function, args, returnTypes, inArgs, outArgs);
}
}
public int test1 (int a, int b)
{
object [] args = new object [] {
__luaInterface_luaTable,
a,
b
};
object [] inArgs = new object [] {
__luaInterface_luaTable,
a,
b
};
int [] outArgs = new int [] { };
Type [] returnTypes = __luaInterface_returnTypes [4];
LuaFunction function = NLua.Method.LuaClassHelper.GetTableFunction (__luaInterface_luaTable, "test1");
object ret = NLua.Method.LuaClassHelper.CallFunction (function, args, returnTypes, inArgs, outArgs);
return (int)ret;
}
public int test2 (int a, out int b)
{
object [] args = new object [] {
__luaInterface_luaTable,
a,
0
};
object [] inArgs = new object [] {
__luaInterface_luaTable,
a
};
int [] outArgs = new int [] { 1 };
Type [] returnTypes = __luaInterface_returnTypes [5];
LuaFunction function = NLua.Method.LuaClassHelper.GetTableFunction (__luaInterface_luaTable, "test2");
object ret = NLua.Method.LuaClassHelper.CallFunction (function, args, returnTypes, inArgs, outArgs);
b = (int)args [1];
return (int)ret;
}
public void test3 (int a, ref int b)
{
object [] args = new object [] {
__luaInterface_luaTable,
a,
b
};
object [] inArgs = new object [] {
__luaInterface_luaTable,
a,
b
};
int [] outArgs = new int [] { 1 };
Type [] returnTypes = __luaInterface_returnTypes [6];
LuaFunction function = NLua.Method.LuaClassHelper.GetTableFunction (__luaInterface_luaTable, "test3");
NLua.Method.LuaClassHelper.CallFunction (function, args, returnTypes, inArgs, outArgs);
b = (int)args [1];
}
public TestClass test4 (int a, int b)
{
object [] args = new object [] {
__luaInterface_luaTable,
a,
b
};
object [] inArgs = new object [] {
__luaInterface_luaTable,
a,
b
};
int [] outArgs = new int [] { };
Type [] returnTypes = __luaInterface_returnTypes [7];
LuaFunction function = NLua.Method.LuaClassHelper.GetTableFunction (__luaInterface_luaTable, "test4");
object ret = NLua.Method.LuaClassHelper.CallFunction (function, args, returnTypes, inArgs, outArgs);
return (TestClass)ret;
}
public int test5 (TestClass a, TestClass b)
{
object [] args = new object [] {
__luaInterface_luaTable,
a,
b
};
object [] inArgs = new object [] {
__luaInterface_luaTable,
a,
b
};
int [] outArgs = new int [] { };
Type [] returnTypes = __luaInterface_returnTypes [8];
LuaFunction function = NLua.Method.LuaClassHelper.GetTableFunction (__luaInterface_luaTable, "test5");
object ret = NLua.Method.LuaClassHelper.CallFunction (function, args, returnTypes, inArgs, outArgs);
return (int)ret;
}
public int test6 (int a, out TestClass b)
{
object [] args = new object [] {
__luaInterface_luaTable,
a,
null
};
object [] inArgs = new object [] {
__luaInterface_luaTable,
a,
};
int [] outArgs = new int [] { 1};
Type [] returnTypes = __luaInterface_returnTypes [9];
LuaFunction function = NLua.Method.LuaClassHelper.GetTableFunction (__luaInterface_luaTable, "test6");
object ret = NLua.Method.LuaClassHelper.CallFunction (function, args, returnTypes, inArgs, outArgs);
b = (TestClass)args [1];
return (int)ret;
}
public void test7 (int a, ref TestClass b)
{
object [] args = new object [] {
__luaInterface_luaTable,
a,
b
};
object [] inArgs = new object [] {
__luaInterface_luaTable,
a,
b
};
int [] outArgs = new int [] { 1 };
Type [] returnTypes = __luaInterface_returnTypes [10];
LuaFunction function = NLua.Method.LuaClassHelper.GetTableFunction (__luaInterface_luaTable, "test7");
NLua.Method.LuaClassHelper.CallFunction (function, args, returnTypes, inArgs, outArgs);
b = (TestClass)args [1];
}
}
}
#endregion
public static class VectorExtension
{
public static double Lenght (this Vector v)
/*
* Tests passing a Lua table as an interface and
* accessing one of its value-type properties
*/
[Test]
public void NLuaValueProperty ()
{
return v.x * v.x + v.y * v.y;
using (Lua lua = new Lua ()) {
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
lua.DoString ("test=TestClass()");
lua.DoString ("itest={}");
lua.DoString ("function itest:get_intProp() return itest.int_prop; end");
lua.DoString ("function itest:set_intProp(val) itest.int_prop=val; end");
lua.DoString ("a=test:callInterface8(itest)");
int a = (int)lua.GetNumber ("a");
Assert.AreEqual (3, a);
//Console.WriteLine("interface returned: "+a);
}
}
}
[TestFixture]
#if MONOTOUCH
[Preserve (AllMembers = true)]
#endif
public class LuaTests
{
public static readonly char UnicodeChar = '\uE007';
public static string UnicodeString
/*
* Tests passing a Lua table as an interface and
* accessing one of its reference type properties
*/
[Test]
public void NLuaReferenceProperty ()
{
get
{
return Convert.ToString (UnicodeChar);
using (Lua lua = new Lua ()) {
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
lua.DoString ("test=TestClass()");
lua.DoString ("itest={}");
lua.DoString ("function itest:get_refProp() return TestClass(itest.int_prop); end");
lua.DoString ("function itest:set_refProp(val) itest.int_prop=val.testval; end");
lua.DoString ("a=test:callInterface9(itest)");
int a = (int)lua.GetNumber ("a");
Assert.AreEqual (3, a);
//Console.WriteLine("interface returned: "+a);
}
}
/*
* Tests capturing an exception
*/
[Test]
public void ThrowException ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("luanet.load_assembly('mscorlib')");
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
lua.DoString ("test=TestClass()");
lua.DoString ("err,errMsg=pcall(test.exceptionMethod,test)");
bool err = (bool)lua ["err"];
Exception errMsg = (Exception)lua ["errMsg"];
Assert.AreEqual (false , err);
Assert.AreNotEqual (null, errMsg.InnerException);
Assert.AreEqual ("exception test", errMsg.InnerException.Message);
}
}
/*
* Tests capturing an exception
*/
[Test]
public void ThrowUncaughtException ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("luanet.load_assembly('mscorlib')");
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
lua.DoString ("test=TestClass()");
try {
lua.DoString ("test:exceptionMethod()");
//failed
Assert.AreEqual(false, true);
} catch (Exception) {
//passed
Assert.AreEqual (true, true);
}
}
}
/*
* Tests nullable fields
*/
[Test]
public void TestNullable ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("luanet.load_assembly('mscorlib')");
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
lua.DoString ("test=TestClass()");
lua.DoString ("val=test.NullableBool");
Assert.AreEqual (null, (object)lua ["val"]);
lua.DoString ("test.NullableBool = true");
lua.DoString ("val=test.NullableBool");
Assert.AreEqual (true, (bool)lua ["val"]);
}
}
/*
* Tests structure assignment
*/
[Test]
public void TestStructs ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
lua.DoString ("test=TestClass()");
lua.DoString ("TestStruct=luanet.import_type('NLuaTest.Mock.TestStruct')");
lua.DoString ("struct=TestStruct(2)");
lua.DoString ("test.Struct = struct");
lua.DoString ("val=test.Struct.val");
Assert.AreEqual (2.0d, (double)lua ["val"]);
}
}
/*
* Tests making an object from a Lua table and calling the base
* class version of one of the methods the table overrides.
*/
[Test]
public void TestStructHashesEqual()
public void LuaTableBaseMethod ()
{
using (Lua lua = new Lua())
{
lua.DoString("luanet.load_assembly('NLuaTest')");
lua.DoString("TestStruct=luanet.import_type('NLuaTest.Mock.TestStruct')");
lua.DoString("struct1=TestStruct(0)");
lua.DoString("struct2=TestStruct(0)");
lua.DoString("struct2.val=1");
Assert.AreEqual(0, (double)lua["struct1.val"]);
using (Lua lua = new Lua ()) {
lua.RegisterLuaClassType (typeof(TestClass), typeof(LuaTestClassHandler));
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
lua.DoString ("test={}");
lua.DoString ("function test:overridableMethod(x,y) print(self[base]); return 6 end");
lua.DoString ("luanet.make_object(test,'NLuaTest.Mock.TestClass')");
lua.DoString ("a=TestClass.callOverridable(test,2,3)");
int a = (int)lua.GetNumber ("a");
lua.DoString ("luanet.free_object(test)");
Assert.AreEqual (6, a);
// lua.DoString("luanet.load_assembly('NLuaTest')");
// lua.DoString("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
// lua.DoString("test={}");
//
// lua.DoString("luanet.make_object(test,'NLuaTest.Mock.TestClass')");
// lua.DoString ("function test.overridableMethod(test,x,y) return 2*test.base.overridableMethod(test,x,y); end");
// lua.DoString("a=TestClass.callOverridable(test,2,3)");
// int a = (int)lua.GetNumber("a");
// lua.DoString("luanet.free_object(test)");
// Assert.AreEqual(10, a);
//Console.WriteLine("interface returned: "+a);
}
}
/*
* Tests getting an object's method by its signature
* (from object)
*/
[Test]
public void GetMethodBySignatureFromObj ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("luanet.load_assembly('mscorlib')");
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
lua.DoString ("test=TestClass()");
lua.DoString ("setMethod=luanet.get_method_bysig(test,'setVal','System.String')");
lua.DoString ("setMethod('test')");
TestClass test = (TestClass)lua ["test"];
Assert.AreEqual ("test", test.getStrVal ());
//Console.WriteLine("interface returned: "+test.getStrVal());
}
}
/*
* Tests getting an object's method by its signature
* (from type)
*/
[Test]
public void GetMethodBySignatureFromType ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("luanet.load_assembly('mscorlib')");
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
lua.DoString ("test=TestClass()");
lua.DoString ("setMethod=luanet.get_method_bysig(TestClass,'setVal','System.String')");
lua.DoString ("setMethod(test,'test')");
TestClass test = (TestClass)lua ["test"];
Assert.AreEqual ("test", test.getStrVal ());
//Console.WriteLine("interface returned: "+test.getStrVal());
}
}
/*
* Tests getting a type's method by its signature
*/
[Test]
public void GetStaticMethodBySignature ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("luanet.load_assembly('mscorlib')");
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
lua.DoString ("make_method=luanet.get_method_bysig(TestClass,'makeFromString','System.String')");
lua.DoString ("test=make_method('test')");
TestClass test = (TestClass)lua ["test"];
Assert.AreEqual ("test", test.getStrVal ());
//Console.WriteLine("interface returned: "+test.getStrVal());
}
}
/*
* Tests getting an object's constructor by its signature
*/
[Test]
public void GetConstructorBySignature ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("luanet.load_assembly('mscorlib')");
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
lua.DoString ("test_cons=luanet.get_constructor_bysig(TestClass,'System.String')");
lua.DoString ("test=test_cons('test')");
TestClass test = (TestClass)lua ["test"];
Assert.AreEqual ("test", test.getStrVal ());
//Console.WriteLine("interface returned: "+test.getStrVal());
}
}
[Test]
public void TestVarargs()
{
using(Lua lua = new Lua()){
lua.DoString ("luanet.load_assembly('mscorlib')");
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
lua.DoString ("test=TestClass()");
lua.DoString ("test:Print('this will pass')");
lua.DoString ("test:Print('this will ','fail')");
}
}
[Test]
public void TestMethodOverloads ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("luanet.load_assembly('mscorlib')");
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
lua.DoString ("test=TestClass()");
lua.DoString ("test:MethodOverload()");
lua.DoString ("test:MethodOverload(test)");
lua.DoString ("test:MethodOverload(1,1,1)");
lua.DoString ("test:MethodOverload(2,2,i)\r\nprint(i)");
}
}
[Test]
public void TestDispose ()
{
System.GC.Collect ();
#if !WINDOWS_PHONE
long startingMem = System.Diagnostics.Process.GetCurrentProcess ().WorkingSet64;
for (int i = 0; i < 100; i++) {
using (Lua lua = new Lua ()) {
_Calc (lua, i);
}
}
//TODO: make this test assert so that it is useful
Console.WriteLine ("Was using " + startingMem / 1024 / 1024 + "MB, now using: " + System.Diagnostics.Process.GetCurrentProcess ().WorkingSet64 / 1024 / 1024 + "MB");
#endif
}
private void _Calc (Lua lua, int i)
{
lua.DoString (
"sqrt = math.sqrt;" +
"sqr = function(x) return math.pow(x,2); end;" +
"log = math.log;" +
"log10 = math.log10;" +
"exp = math.exp;" +
"sin = math.sin;" +
"cos = math.cos;" +
"tan = math.tan;" +
"abs = math.abs;"
);
lua.DoString ("function calcVP(a,b) return a+b end");
LuaFunction lf = lua.GetFunction ("calcVP");
lf.Call (i, 20);
}
[Test]
public void TestThreading ()
{
using (Lua lua = new Lua ()) {
object lua_locker = new object ();
DoWorkClass doWork = new DoWorkClass ();
lua.RegisterFunction ("dowork", doWork, typeof(DoWorkClass).GetMethod ("DoWork"));
bool failureDetected = false;
int completed = 0;
int iterations = 10;
for (int i = 0; i < iterations; i++) {
ThreadPool.QueueUserWorkItem (new WaitCallback (delegate (object o) {
try {
lock (lua_locker) {
lua.DoString ("dowork()");
}
} catch (Exception e) {
Console.Write (e);
failureDetected = true;
}
completed++;
}));
}
while (completed < iterations && !failureDetected)
Thread.Sleep (50);
Assert.AreEqual (false, failureDetected);
}
}
[Test]
public void TestPrivateMethod ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("luanet.load_assembly('mscorlib')");
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
lua.DoString ("test=TestClass()");
try {
lua.DoString ("test:_PrivateMethod()");
} catch {
Assert.AreEqual (true, true);
return;
}
Assert.AreEqual(true, false);
}
}
/*
* Tests functions
*/
[Test]
public void TestFunctions ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("luanet.load_assembly('mscorlib')");
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.RegisterFunction ("p", null, typeof(System.Console).GetMethod ("WriteLine", new Type [] { typeof(String) }));
/// Lua command that works (prints to console)
lua.DoString ("p('Foo')");
/// Yet this works...
lua.DoString ("string.gsub('some string', '(%w+)', function(s) p(s) end)");
/// This fails if you don't fix Lua5.1 lstrlib.c/add_value to treat LUA_TUSERDATA the same as LUA_FUNCTION
lua.DoString ("string.gsub('some string', '(%w+)', p)");
}
}
/*
* Tests making an object from a Lua table and calling one of
* methods the table overrides.
*/
[Test]
public void LuaTableOverridedMethod ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
lua.DoString ("test={}");
lua.DoString ("function test:overridableMethod(x,y) return x*y; end");
lua.DoString ("luanet.make_object(test,'NLuaTest.Mock.TestClass')");
lua.DoString ("a=TestClass.callOverridable(test,2,3)");
int a = (int)lua.GetNumber ("a");
lua.DoString ("luanet.free_object(test)");
Assert.AreEqual (6, a);
}
}
/*
* Tests making an object from a Lua table and calling a method
* the table does not override.
*/
[Test]
public void LuaTableInheritedMethod ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
lua.DoString ("test={}");
lua.DoString ("function test:overridableMethod(x,y) return x*y; end");
lua.DoString ("luanet.make_object(test,'NLuaTest.Mock.TestClass')");
lua.DoString ("test:setVal(3)");
lua.DoString ("a=test.testval");
int a = (int)lua.GetNumber ("a");
lua.DoString ("luanet.free_object(test)");
Assert.AreEqual (3, a);
//Console.WriteLine("interface returned: "+a);
}
}
/// <summary>
/// Basic multiply method which expects 2 floats
/// </summary>
/// <param name="val"></param>
/// <param name="val2"></param>
/// <returns></returns>
private float _TestException (float val, float val2)
{
return val * val2;
}
class LuaEventArgsHandler : NLua.Method.LuaDelegate
{
void CallFunction (object sender, EventArgs eventArgs)
{
object [] args = new object [] {sender, eventArgs };
object [] inArgs = new object [] { sender, eventArgs };
int [] outArgs = new int [] { };
base.CallFunction (args, inArgs, outArgs);
}
}
[Test]
public void TestEventException ()
{
using (Lua lua = new Lua ()) {
//Register a C# function
MethodInfo testException = this.GetType ().GetMethod ("_TestException", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Instance, null, new Type [] {
typeof(float),
typeof(float)
}, null);
lua.RegisterFunction ("Multiply", this, testException);
lua.RegisterLuaDelegateType (typeof(EventHandler<EventArgs>), typeof(LuaEventArgsHandler));
//create the lua event handler code for the entity
//includes the bad code!
lua.DoString ("function OnClick(sender, eventArgs)\r\n" +
"--Multiply expects 2 floats, but instead receives 2 strings\r\n" +
"Multiply(asd, es)\r\n" +
"end");
//create the lua event handler code for the entity
//good code
//lua.DoString("function OnClick(sender, eventArgs)\r\n" +
// "--Multiply expects 2 floats\r\n" +
// "Multiply(2, 50)\r\n" +
// "end");
//Create the event handler script
lua.DoString ("function SubscribeEntity(e)\r\ne.Clicked:Add(OnClick)\r\nend");
//Create the entity object
Entity entity = new Entity ();
//Register the entity object with the event handler inside lua
LuaFunction lf = lua.GetFunction ("SubscribeEntity");
lf.Call (new object [1] { entity });
try {
//Cause the event to be fired
entity.Click ();
//failed
Assert.AreEqual(true, false);
} catch (LuaException) {
//passed
Assert.AreEqual (true, true);
}
}
}
[Test]
public void TestExceptionWithChunkOverload ()
{
using (Lua lua = new Lua ()) {
try {
lua.DoString ("thiswillthrowanerror", "MyChunk");
} catch (Exception e) {
Assert.AreEqual (true, e.Message.StartsWith ("[string \"MyChunk\"]"));
}
}
}
[Test]
public void TestGenerics ()
{
//Im not sure support for generic classes is possible to implement, see: http://msdn.microsoft.com/en-us/library/system.reflection.methodinfo.containsgenericparameters.aspx
//specifically the line that says: "If the ContainsGenericParameters property returns true, the method cannot be invoked"
//TestClassGeneric<string> genericClass = new TestClassGeneric<string>();
//lua.RegisterFunction("genericMethod", genericClass, typeof(TestClassGeneric<>).GetMethod("GenericMethod"));
//lua.RegisterFunction("regularMethod", genericClass, typeof(TestClassGeneric<>).GetMethod("RegularMethod"));
using (Lua lua = new Lua ()) {
TestClassWithGenericMethod classWithGenericMethod = new TestClassWithGenericMethod ();
////////////////////////////////////////////////////////////////////////////
/// ////////////////////////////////////////////////////////////////////////
/// IMPORTANT: Use generic method with the type you will call or generic methods will fail with iOS
/// ////////////////////////////////////////////////////////////////////////
classWithGenericMethod.GenericMethod<double>(99.0);
classWithGenericMethod.GenericMethod<TestClass>(new TestClass (99));
////////////////////////////////////////////////////////////////////////////
/// ////////////////////////////////////////////////////////////////////////
lua.RegisterFunction ("genericMethod2", classWithGenericMethod, typeof(TestClassWithGenericMethod).GetMethod ("GenericMethod"));
try {
lua.DoString ("genericMethod2(100)");
} catch {
}
Assert.AreEqual (true, classWithGenericMethod.GenericMethodSuccess);
Assert.AreEqual (true, classWithGenericMethod.Validate<double> (100)); //note the gotcha: numbers are all being passed to generic methods as doubles
try {
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
lua.DoString ("test=TestClass(56)");
lua.DoString ("genericMethod2(test)");
} catch {
}
Assert.AreEqual (true, classWithGenericMethod.GenericMethodSuccess);
Assert.AreEqual (56, (classWithGenericMethod.PassedValue as TestClass).val);
}
}
[Test]
public void RegisterFunctionStressTest ()
{
const int Count = 200; // it seems to work with 41
using (Lua lua = new Lua ()) {
MyClass t = new MyClass ();
for (int i = 1; i < Count - 1; ++i) {
lua.RegisterFunction ("func" + i, t, typeof(MyClass).GetMethod ("Func1"));
}
lua.RegisterFunction ("func" + (Count - 1), t, typeof(MyClass).GetMethod ("Func1"));
lua.DoString ("print(func1())");
}
}
[Test]
public void TestMultipleOutParameters ()
{
using (Lua lua = new Lua ()) {
TestClass t1 = new TestClass ();
lua ["netobj"] = t1;
lua.DoString ("a,b,c=netobj:outValMutiple(2)");
int a = (int)lua.GetNumber ("a");
string b = (string)lua.GetString ("b");
string c = (string)lua.GetString ("c");
Assert.AreEqual (2, a);
Assert.AreNotEqual (null, b);
Assert.AreNotEqual (null, c);
}
}
[Test]
public void TestLoadStringLeak ()
{
//Test to prevent stack overflow
//See: http://code.google.com/p/nlua/issues/detail?id=5
//number of iterations to test
int count = 1000;
using (Lua lua = new Lua ()) {
for (int i = 0; i < count; i++) {
lua.LoadString ("abc = 'def'", string.Empty);
}
}
//any thrown exceptions cause the test run to fail
}
[Test]
public void TestLoadFileLeak ()
{
//Test to prevent stack overflow
//See: http://code.google.com/p/nlua/issues/detail?id=5
//number of iterations to test
int count = 1000;
using (Lua lua = new Lua ()) {
for (int i = 0; i < count; i++) {
lua.LoadFile (Environment.CurrentDirectory + System.IO.Path.DirectorySeparatorChar + "test.lua");
}
}
//any thrown exceptions cause the test run to fail
}
[Test]
public void TestRegisterFunction ()
{
using (Lua lua = new Lua ()) {
lua.RegisterFunction ("func1", null, typeof(TestClass2).GetMethod ("func"));
object[] vals1 = lua.GetFunction ("func1").Call (2, 3);
Assert.AreEqual (5.0f, Convert.ToSingle (vals1 [0]));
TestClass2 obj = new TestClass2 ();
lua.RegisterFunction ("func2", obj, typeof(TestClass2).GetMethod ("funcInstance"));
vals1 = lua.GetFunction ("func2").Call (2, 3);
Assert.AreEqual (5.0f, Convert.ToSingle (vals1 [0]));
}
}
/*
* Tests if DoString is correctly returning values
*/
[Test]
public void DoString ()
{
using (Lua lua = new Lua ()) {
object[] res = lua.DoString ("a=2\nreturn a,3");
//Console.WriteLine("a="+res[0]+", b="+res[1]);
Assert.AreEqual (res [0], 2d);
Assert.AreEqual (res [1], 3d);
}
}
/*
* Tests getting of global numeric variables
*/
[Test]
public void GetGlobalNumber ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("a=2");
double num = lua.GetNumber ("a");
//Console.WriteLine("a="+num);
Assert.AreEqual (num, 2d);
}
}
/*
* Tests setting of global numeric variables
*/
[Test]
public void SetGlobalNumber ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("a=2");
lua ["a"] = 3;
double num = lua.GetNumber ("a");
//Console.WriteLine("a="+num);
Assert.AreEqual (num, 3d);
}
}
/*
* Tests getting of numeric variables from tables
* by specifying variable path
*/
[Test]
public void GetNumberInTable ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("a={b={c=2}}");
double num = lua.GetNumber ("a.b.c");
//Console.WriteLine("a.b.c="+num);
Assert.AreEqual (num, 2d);
}
}
/*
* Tests setting of numeric variables from tables
* by specifying variable path
*/
[Test]
public void SetNumberInTable ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("a={b={c=2}}");
lua ["a.b.c"] = 3;
double num = lua.GetNumber ("a.b.c");
//Console.WriteLine("a.b.c="+num);
Assert.AreEqual (num, 3d);
}
}
/*
* Tests getting of global string variables
*/
[Test]
public void GetGlobalString ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("a=\"test\"");
string str = lua.GetString ("a");
//Console.WriteLine("a="+str);
Assert.AreEqual (str, "test");
}
}
/*
* Tests setting of global string variables
*/
[Test]
public void SetGlobalString ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("a=\"test\"");
lua ["a"] = "new test";
string str = lua.GetString ("a");
//Console.WriteLine("a="+str);
Assert.AreEqual (str, "new test");
}
}
/*
* Tests getting of string variables from tables
* by specifying variable path
*/
[Test]
public void GetStringInTable ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("a={b={c=\"test\"}}");
string str = lua.GetString ("a.b.c");
//Console.WriteLine("a.b.c="+str);
Assert.AreEqual (str, "test");
}
}
/*
* Tests setting of string variables from tables
* by specifying variable path
*/
[Test]
public void SetStringInTable ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("a={b={c=\"test\"}}");
lua ["a.b.c"] = "new test";
string str = lua.GetString ("a.b.c");
//Console.WriteLine("a.b.c="+str);
Assert.AreEqual (str, "new test");
}
}
/*
* Tests getting and setting of global table variables
*/
[Test]
public void GetAndSetTable ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("a={b={c=2}}\nb={c=3}");
LuaTable tab = lua.GetTable ("b");
lua ["a.b"] = tab;
double num = lua.GetNumber ("a.b.c");
//Console.WriteLine("a.b.c="+num);
Assert.AreEqual (num, 3d);
}
}
/*
* Tests getting of numeric field of a table
*/
[Test]
public void GetTableNumericField1 ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("a={b={c=2}}");
LuaTable tab = lua.GetTable ("a.b");
double num = (double)tab ["c"];
//Console.WriteLine("a.b.c="+num);
Assert.AreEqual (num, 2d);
}
}
/*
* Tests getting of numeric field of a table
* (the field is inside a subtable)
*/
[Test]
public void GetTableNumericField2 ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("a={b={c=2}}");
LuaTable tab = lua.GetTable ("a");
double num = (double)tab ["b.c"];
//Console.WriteLine("a.b.c="+num);
Assert.AreEqual (num, 2d);
}
}
/*
* Tests setting of numeric field of a table
*/
[Test]
public void SetTableNumericField1 ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("a={b={c=2}}");
LuaTable tab = lua.GetTable ("a.b");
tab ["c"] = 3;
double num = lua.GetNumber ("a.b.c");
//Console.WriteLine("a.b.c="+num);
Assert.AreEqual (num, 3d);
}
}
/*
* Tests setting of numeric field of a table
* (the field is inside a subtable)
*/
[Test]
public void SetTableNumericField2 ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("a={b={c=2}}");
LuaTable tab = lua.GetTable ("a");
tab ["b.c"] = 3;
double num = lua.GetNumber ("a.b.c");
//Console.WriteLine("a.b.c="+num);
Assert.AreEqual (num, 3d);
}
}
/*
* Tests getting of string field of a table
*/
[Test]
public void GetTableStringField1 ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("a={b={c=\"test\"}}");
LuaTable tab = lua.GetTable ("a.b");
string str = (string)tab ["c"];
//Console.WriteLine("a.b.c="+str);
Assert.AreEqual (str, "test");
}
}
/*
* Tests getting of string field of a table
* (the field is inside a subtable)
*/
[Test]
public void GetTableStringField2 ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("a={b={c=\"test\"}}");
LuaTable tab = lua.GetTable ("a");
string str = (string)tab ["b.c"];
//Console.WriteLine("a.b.c="+str);
Assert.AreEqual (str, "test");
}
}
/*
* Tests setting of string field of a table
*/
[Test]
public void SetTableStringField1 ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("a={b={c=\"test\"}}");
LuaTable tab = lua.GetTable ("a.b");
tab ["c"] = "new test";
string str = lua.GetString ("a.b.c");
//Console.WriteLine("a.b.c="+str);
Assert.AreEqual (str, "new test");
}
}
/*
* Tests setting of string field of a table
* (the field is inside a subtable)
*/
[Test]
public void SetTableStringField2 ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("a={b={c=\"test\"}}");
LuaTable tab = lua.GetTable ("a");
tab ["b.c"] = "new test";
string str = lua.GetString ("a.b.c");
//Console.WriteLine("a.b.c="+str);
Assert.AreEqual (str, "new test");
}
}
/*
* Tests calling of a global function with zero arguments
*/
[Test]
public void CallGlobalFunctionNoArgs ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("a=2\nfunction f()\na=3\nend");
lua.GetFunction ("f").Call ();
double num = lua.GetNumber ("a");
//Console.WriteLine("a="+num);
Assert.AreEqual (num, 3d);
}
}
/*
* Tests calling of a global function with one argument
*/
[Test]
public void CallGlobalFunctionOneArg ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("a=2\nfunction f(x)\na=a+x\nend");
lua.GetFunction ("f").Call (1);
double num = lua.GetNumber ("a");
//Console.WriteLine("a="+num);
Assert.AreEqual (num, 3d);
}
}
/*
* Tests calling of a global function with two arguments
*/
[Test]
public void CallGlobalFunctionTwoArgs ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("a=2\nfunction f(x,y)\na=x+y\nend");
lua.GetFunction ("f").Call (1, 3);
double num = lua.GetNumber ("a");
//Console.WriteLine("a="+num);
Assert.AreEqual (num, 4d);
}
}
/*
* Tests calling of a global function that returns one value
*/
[Test]
public void CallGlobalFunctionOneReturn ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("function f(x)\nreturn x+2\nend");
object[] ret = lua.GetFunction ("f").Call (3);
//Console.WriteLine("ret="+ret[0]);
Assert.AreEqual (1, ret.Length);
Assert.AreEqual (5, (double)ret [0]);
}
}
/*
* Tests calling of a global function that returns two values
*/
[Test]
public void CallGlobalFunctionTwoReturns ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("function f(x,y)\nreturn x,x+y\nend");
object[] ret = lua.GetFunction ("f").Call (3, 2);
//Console.WriteLine("ret="+ret[0]+","+ret[1]);
Assert.AreEqual (2, ret.Length);
Assert.AreEqual (3, (double)ret [0]);
Assert.AreEqual (5, (double)ret [1]);
}
}
/*
* Tests calling of a function inside a table
*/
[Test]
public void CallTableFunctionTwoReturns ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("a={}\nfunction a.f(x,y)\nreturn x,x+y\nend");
object[] ret = lua.GetFunction ("a.f").Call (3, 2);
//Console.WriteLine("ret="+ret[0]+","+ret[1]);
Assert.AreEqual (2, ret.Length);
Assert.AreEqual (3, (double)ret [0]);
Assert.AreEqual (5, (double)ret [1]);
}
}
/*
* Tests setting of a global variable to a CLR object value
*/
[Test]
public void SetGlobalObject ()
{
using (Lua lua = new Lua ()) {
TestClass t1 = new TestClass ();
t1.testval = 4;
lua ["netobj"] = t1;
object o = lua ["netobj"];
Assert.AreEqual (true, o is TestClass);
TestClass t2 = (TestClass)lua ["netobj"];
Assert.AreEqual (t2.testval, 4);
Assert.AreEqual (t1 , t2);
}
}
///*
// * Tests if CLR object is being correctly collected by Lua
// */
//[Test]
//public void GarbageCollection()
//{
// using (Lua lua = new Lua())
// {
// TestClass t1 = new TestClass();
// t1.testval = 4;
// lua["netobj"] = t1;
// TestClass t2 = (TestClass)lua["netobj"];
// Assert.True(lua[0] != null);
// lua.DoString("netobj=nil;collectgarbage();");
// Assert.True(lua.translator.objects[0] == null);
// }
//}
/*
* Tests setting of a table field to a CLR object value
*/
[Test]
public void SetTableObjectField1 ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("a={b={c=\"test\"}}");
LuaTable tab = lua.GetTable ("a.b");
TestClass t1 = new TestClass ();
t1.testval = 4;
tab ["c"] = t1;
TestClass t2 = (TestClass)lua ["a.b.c"];
//Console.WriteLine("a.b.c="+t2.testval);
Assert.AreEqual (4, t2.testval);
Assert.AreEqual (t1 , t2);
}
}
/*
* Tests reading and writing of an object's field
*/
[Test]
public void AccessObjectField ()
{
using (Lua lua = new Lua ()) {
TestClass t1 = new TestClass ();
t1.val = 4;
lua ["netobj"] = t1;
lua.DoString ("var=netobj.val");
double var = (double)lua ["var"];
//Console.WriteLine("value from Lua="+var);
Assert.AreEqual (4, var);
lua.DoString ("netobj.val=3");
Assert.AreEqual (3, t1.val);
//Console.WriteLine("new val (from Lua)="+t1.val);
}
}
/*
* Tests reading and writing of an object's non-indexed
* property
*/
[Test]
public void AccessObjectProperty ()
{
using (Lua lua = new Lua ()) {
TestClass t1 = new TestClass ();
t1.testval = 4;
lua ["netobj"] = t1;
lua.DoString ("var=netobj.testval");
double var = (double)lua ["var"];
//Console.WriteLine("value from Lua="+var);
Assert.AreEqual (4, var);
lua.DoString ("netobj.testval=3");
Assert.AreEqual (3, t1.testval);
//Console.WriteLine("new val (from Lua)="+t1.testval);
}
}
[Test]
public void AccessObjectStringProperty ()
{
using (Lua lua = new Lua ()) {
TestClass t1 = new TestClass ();
t1.teststrval = "This is a string test";
lua ["netobj"] = t1;
lua.DoString ("var=netobj.teststrval");
string var = (string)lua ["var"];
Assert.AreEqual ("This is a string test", var);
lua.DoString ("netobj.teststrval='Another String'");
Assert.AreEqual ("Another String", t1.teststrval);
//Console.WriteLine("new val (from Lua)="+t1.testval);
}
}
/*
* Tests calling of an object's method with no overloads
*/
[Test]
public void CallObjectMethod ()
{
using (Lua lua = new Lua ()) {
TestClass t1 = new TestClass ();
t1.testval = 4;
lua ["netobj"] = t1;
lua.DoString ("netobj:setVal(3)");
Assert.AreEqual (3, t1.testval);
//Console.WriteLine("new val(from C#)="+t1.testval);
lua.DoString ("val=netobj:getVal()");
int val = (int)lua.GetNumber ("val");
Assert.AreEqual (3, val);
//Console.WriteLine("new val(from Lua)="+val);
}
}
/*
* Tests calling of an object's method with overloading
*/
[Test]
public void CallObjectMethodByType ()
{
using (Lua lua = new Lua ()) {
TestClass t1 = new TestClass ();
lua ["netobj"] = t1;
lua.DoString ("netobj:setVal('str')");
Assert.AreEqual ("str", t1.getStrVal ());
//Console.WriteLine("new val(from C#)="+t1.getStrVal());
}
}
/*
* Tests calling of an object's method with no overloading
* and out parameters
*/
[Test]
public void CallObjectMethodOutParam ()
{
using (Lua lua = new Lua ()) {
TestClass t1 = new TestClass ();
lua ["netobj"] = t1;
lua.DoString ("a,b=netobj:outVal()");
int a = (int)lua.GetNumber ("a");
int b = (int)lua.GetNumber ("b");
Assert.AreEqual (3, a);
Assert.AreEqual (5, b);
//Console.WriteLine("function returned (from lua)="+a+","+b);
}
}
/*
* Tests calling of an object's method with overloading and
* out params
*/
[Test]
public void CallObjectMethodOverloadedOutParam ()
{
using (Lua lua = new Lua ()) {
TestClass t1 = new TestClass ();
lua ["netobj"] = t1;
lua.DoString ("a,b=netobj:outVal(2)");
int a = (int)lua.GetNumber ("a");
int b = (int)lua.GetNumber ("b");
Assert.AreEqual (2, a);
Assert.AreEqual (5, b);
//Console.WriteLine("function returned (from lua)="+a+","+b);
}
}
/*
* Tests calling of an object's method with ref params
*/
[Test]
public void CallObjectMethodByRefParam ()
{
using (Lua lua = new Lua ()) {
TestClass t1 = new TestClass ();
lua ["netobj"] = t1;
lua.DoString ("a,b=netobj:outVal(2,3)");
int a = (int)lua.GetNumber ("a");
int b = (int)lua.GetNumber ("b");
Assert.AreEqual (2, a);
Assert.AreEqual (5, b);
//Console.WriteLine("function returned (from lua)="+a+","+b);
}
}
/*
* Tests calling of two versions of an object's method that have
* the same name and signature but implement different interfaces
*/
[Test]
public void CallObjectMethodDistinctInterfaces ()
{
using (Lua lua = new Lua ()) {
TestClass t1 = new TestClass ();
lua ["netobj"] = t1;
lua.DoString ("a=netobj:foo()");
lua.DoString ("b=netobj['NLuaTest.Mock.IFoo1.foo']");
int a = (int)lua.GetNumber ("a");
int b = (int)lua.GetNumber ("b");
Assert.AreEqual (5, a);
Assert.AreEqual (1, b);
//Console.WriteLine("function returned (from lua)="+a+","+b);
}
}
/*
* Tests instantiating an object with no-argument constructor
*/
[Test]
public void CreateNetObjectNoArgsCons ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("luanet.load_assembly(\"NLuaTest\")");
lua.DoString ("TestClass=luanet.import_type(\"NLuaTest.Mock.TestClass\")");
lua.DoString ("test=TestClass()");
lua.DoString ("test:setVal(3)");
object[] res = lua.DoString ("return test");
TestClass test = (TestClass)res [0];
//Console.WriteLine("returned: "+test.testval);
Assert.AreEqual (3, test.testval);
}
}
/*
* Tests instantiating an object with one-argument constructor
*/
[Test]
public void CreateNetObjectOneArgCons ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("luanet.load_assembly(\"NLuaTest\")");
lua.DoString ("TestClass=luanet.import_type(\"NLuaTest.Mock.TestClass\")");
lua.DoString ("test=TestClass(3)");
object[] res = lua.DoString ("return test");
TestClass test = (TestClass)res [0];
//Console.WriteLine("returned: "+test.testval);
Assert.AreEqual (3, test.testval);
}
}
/*
* Tests instantiating an object with overloaded constructor
*/
[Test]
public void CreateNetObjectOverloadedCons ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("luanet.load_assembly(\"NLuaTest\")");
lua.DoString ("TestClass=luanet.import_type(\"NLuaTest.Mock.TestClass\")");
lua.DoString ("test=TestClass('str')");
object[] res = lua.DoString ("return test");
TestClass test = (TestClass)res [0];
//Console.WriteLine("returned: "+test.getStrVal());
Assert.AreEqual ("str", test.getStrVal ());
}
}
/*
* Tests getting item of a CLR array
*/
[Test]
public void ReadArrayField ()
{
using (Lua lua = new Lua ()) {
string[] arr = new string [] { "str1", "str2", "str3" };
lua ["netobj"] = arr;
lua.DoString ("val=netobj[1]");
string val = lua.GetString ("val");
Assert.AreEqual ("str2", val);
//Console.WriteLine("new val(from array to Lua)="+val);
}
}
/*G
* Tests setting item of a CLR array
*/
[Test]
public void WriteArrayField ()
{
using (Lua lua = new Lua ()) {
string[] arr = new string [] { "str1", "str2", "str3" };
lua ["netobj"] = arr;
lua.DoString ("netobj[1]='test'");
Assert.AreEqual ("test", arr [1]);
//Console.WriteLine("new val(from Lua to array)="+arr[1]);
}
}
/*
* Tests creating a new CLR array
*/
[Test]
public void CreateArray ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("luanet.load_assembly(\"NLuaTest\")");
lua.DoString ("TestClass=luanet.import_type(\"NLuaTest.Mock.TestClass\")");
lua.DoString ("arr=TestClass[3]");
lua.DoString ("for i=0,2 do arr[i]=TestClass(i+1) end");
TestClass[] arr = (TestClass[])lua ["arr"];
Assert.AreEqual (arr [1].testval, 2);
}
}
/*
* Tests passing a Lua function to a delegate
* with value-type arguments
*/
[Test]
public void LuaDelegateValueTypes ()
{
using (Lua lua = new Lua ()) {
lua.RegisterLuaDelegateType (typeof(TestDelegate1), typeof(LuaTestDelegate1Handler));
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
lua.DoString ("test=TestClass()");
lua.DoString ("function func(x,y) return x+y; end");
lua.DoString ("test=TestClass()");
lua.DoString ("a=test:callDelegate1(func)");
int a = (int)lua.GetNumber ("a");
Assert.AreEqual (5, a);
//Console.WriteLine("delegate returned: "+a);
}
}
/*
* Tests passing a Lua function to a delegate
* with value-type arguments and out params
*/
[Test]
public void LuaDelegateValueTypesOutParam ()
{
using (Lua lua = new Lua ()) {
lua.RegisterLuaDelegateType (typeof(TestDelegate2), typeof(LuaTestDelegate2Handler));
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
lua.DoString ("test=TestClass()");
lua.DoString ("function func(x) return x,x*2; end");
lua.DoString ("test=TestClass()");
lua.DoString ("a=test:callDelegate2(func)");
int a = (int)lua.GetNumber ("a");
Assert.AreEqual (6, a);
//Console.WriteLine("delegate returned: "+a);
}
}
/*
* Tests passing a Lua function to a delegate
* with value-type arguments and ref params
*/
[Test]
public void LuaDelegateValueTypesByRefParam ()
{
using (Lua lua = new Lua ()) {
lua.RegisterLuaDelegateType (typeof(TestDelegate3), typeof(LuaTestDelegate3Handler));
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
lua.DoString ("test=TestClass()");
lua.DoString ("function func(x,y) return x+y; end");
lua.DoString ("test=TestClass()");
lua.DoString ("a=test:callDelegate3(func)");
int a = (int)lua.GetNumber ("a");
Assert.AreEqual (5, a);
//Console.WriteLine("delegate returned: "+a);
}
}
/*
* Tests passing a Lua function to a delegate
* with value-type arguments that returns a reference type
*/
[Test]
public void LuaDelegateValueTypesReturnReferenceType ()
{
using (Lua lua = new Lua ()) {
lua.RegisterLuaDelegateType (typeof(TestDelegate4), typeof(LuaTestDelegate4Handler));
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
lua.DoString ("test=TestClass()");
lua.DoString ("function func(x,y) return TestClass(x+y); end");
lua.DoString ("test=TestClass()");
lua.DoString ("a=test:callDelegate4(func)");
int a = (int)lua.GetNumber ("a");
Assert.AreEqual (5, a);
//Console.WriteLine("delegate returned: "+a);
}
}
/*
* Tests passing a Lua function to a delegate
* with reference type arguments
*/
[Test]
public void LuaDelegateReferenceTypes ()
{
using (Lua lua = new Lua ()) {
lua.RegisterLuaDelegateType (typeof(TestDelegate5), typeof(LuaTestDelegate5Handler));
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
lua.DoString ("test=TestClass()");
lua.DoString ("function func(x,y) return x.testval+y.testval; end");
lua.DoString ("a=test:callDelegate5(func)");
int a = (int)lua.GetNumber ("a");
Assert.AreEqual (5, a);
//Console.WriteLine("delegate returned: "+a);
}
}
/*
* Tests passing a Lua function to a delegate
* with reference type arguments and an out param
*/
[Test]
public void LuaDelegateReferenceTypesOutParam ()
{
using (Lua lua = new Lua ()) {
lua.RegisterLuaDelegateType (typeof(TestDelegate6), typeof(LuaTestDelegate6Handler));
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
lua.DoString ("test=TestClass()");
lua.DoString ("function func(x) return x,TestClass(x*2); end");
lua.DoString ("test=TestClass()");
lua.DoString ("a=test:callDelegate6(func)");
int a = (int)lua.GetNumber ("a");
Assert.AreEqual (6, a);
//Console.WriteLine("delegate returned: "+a);
}
}
/*
* Tests passing a Lua function to a delegate
* with reference type arguments and a ref param
*/
[Test]
public void LuaDelegateReferenceTypesByRefParam ()
{
using (Lua lua = new Lua ()) {
lua.RegisterLuaDelegateType (typeof(TestDelegate7), typeof(LuaTestDelegate7Handler));
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
lua.DoString ("test=TestClass()");
lua.DoString ("function func(x,y) return TestClass(x+y.testval); end");
lua.DoString ("a=test:callDelegate7(func)");
int a = (int)lua.GetNumber ("a");
Assert.AreEqual (5, a);
//Console.WriteLine("delegate returned: "+a);
}
}
/*
* Tests passing a Lua table as an interface and
* calling one of its methods with value-type params
*/
[Test]
public void NLuaAAValueTypes ()
{
using (Lua lua = new Lua ()) {
lua.RegisterLuaClassType (typeof(ITest), typeof(LuaITestClassHandler));
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
lua.DoString ("test=TestClass()");
lua.DoString ("itest={}");
lua.DoString ("function itest:test1(x,y) return x+y; end");
lua.DoString ("test=TestClass()");
lua.DoString ("a=test:callInterface1(itest)");
int a = (int)lua.GetNumber ("a");
Assert.AreEqual (5, a);
//Console.WriteLine("interface returned: "+a);
}
}
/*
* Tests passing a Lua table as an interface and
* calling one of its methods with value-type params
* and an out param
*/
[Test]
public void NLuaValueTypesOutParam ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
lua.DoString ("test=TestClass()");
lua.DoString ("itest={}");
lua.DoString ("function itest:test2(x) return x,x*2; end");
lua.DoString ("test=TestClass()");
lua.DoString ("a=test:callInterface2(itest)");
int a = (int)lua.GetNumber ("a");
Assert.AreEqual (6, a);
//Console.WriteLine("interface returned: "+a);
}
}
/*
* Tests passing a Lua table as an interface and
* calling one of its methods with value-type params
* and a ref param
*/
[Test]
public void NLuaValueTypesByRefParam ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
lua.DoString ("test=TestClass()");
lua.DoString ("itest={}");
lua.DoString ("function itest:test3(x,y) return x+y; end");
lua.DoString ("test=TestClass()");
lua.DoString ("a=test:callInterface3(itest)");
int a = (int)lua.GetNumber ("a");
Assert.AreEqual (5, a);
//Console.WriteLine("interface returned: "+a);
}
}
/*
* Tests passing a Lua table as an interface and
* calling one of its methods with value-type params
* returning a reference type param
*/
[Test]
public void NLuaValueTypesReturnReferenceType ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
lua.DoString ("test=TestClass()");
lua.DoString ("itest={}");
lua.DoString ("function itest:test4(x,y) return TestClass(x+y); end");
lua.DoString ("test=TestClass()");
lua.DoString ("a=test:callInterface4(itest)");
int a = (int)lua.GetNumber ("a");
Assert.AreEqual (5, a);
//Console.WriteLine("interface returned: "+a);
}
}
/*
* Tests passing a Lua table as an interface and
* calling one of its methods with reference type params
*/
[Test]
public void NLuaReferenceTypes ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
lua.DoString ("test=TestClass()");
lua.DoString ("itest={}");
lua.DoString ("function itest:test5(x,y) return x.testval+y.testval; end");
lua.DoString ("test=TestClass()");
lua.DoString ("a=test:callInterface5(itest)");
int a = (int)lua.GetNumber ("a");
Assert.AreEqual (5, a);
//Console.WriteLine("interface returned: "+a);
}
}
/*
* Tests passing a Lua table as an interface and
* calling one of its methods with reference type params
* and an out param
*/
[Test]
public void NLuaReferenceTypesOutParam ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
lua.DoString ("test=TestClass()");
lua.DoString ("itest={}");
lua.DoString ("function itest:test6(x) return x,TestClass(x*2); end");
lua.DoString ("test=TestClass()");
lua.DoString ("a=test:callInterface6(itest)");
int a = (int)lua.GetNumber ("a");
Assert.AreEqual (6, a);
//Console.WriteLine("interface returned: "+a);
}
}
/*
* Tests passing a Lua table as an interface and
* calling one of its methods with reference type params
* and a ref param
*/
[Test]
public void NLuaReferenceTypesByRefParam ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
lua.DoString ("test=TestClass()");
lua.DoString ("itest={}");
lua.DoString ("function itest:test7(x,y) return TestClass(x+y.testval); end");
lua.DoString ("a=test:callInterface7(itest)");
int a = (int)lua.GetNumber ("a");
Assert.AreEqual (5, a);
//Console.WriteLine("interface returned: "+a);
}
}
#region LUA_BOILERPLATE_CLASS
/*** This class is used to bind the .NET world with the Lua world, this boilerplate code is pratically the same, get values call Lua function return value back,
* this class is usually dynamic generated using System.Reflection.Emit, but this will not work on iOS. */
class LuaTestClassHandler: TestClass, ILuaGeneratedType
{
public LuaTable __luaInterface_luaTable;
public Type[][] __luaInterface_returnTypes;
public LuaTestClassHandler (LuaTable luaTable, Type[][] returnTypes)
{
__luaInterface_luaTable = luaTable;
__luaInterface_returnTypes = returnTypes;
}
public LuaTable LuaInterfaceGetLuaTable ()
{
return __luaInterface_luaTable;
}
public override int overridableMethod (int x, int y)
{
object [] args = new object [] {
__luaInterface_luaTable,
x,
y
};
object [] inArgs = new object [] {
__luaInterface_luaTable,
x,
y
};
int [] outArgs = new int [] { };
Type [] returnTypes = __luaInterface_returnTypes [0];
LuaFunction function = NLua.Method.LuaClassHelper.GetTableFunction (__luaInterface_luaTable, "overridableMethod");
object ret = NLua.Method.LuaClassHelper.CallFunction (function, args, returnTypes, inArgs, outArgs);
return (int)ret;
}
}
class LuaITestClassHandler : ILuaGeneratedType, ITest
{
public LuaTable __luaInterface_luaTable;
public Type[][] __luaInterface_returnTypes;
public LuaITestClassHandler (LuaTable luaTable, Type[][] returnTypes)
{
__luaInterface_luaTable = luaTable;
__luaInterface_returnTypes = returnTypes;
}
public LuaTable LuaInterfaceGetLuaTable ()
{
return __luaInterface_luaTable;
}
public int intProp {
get {
object [] args = new object [] { __luaInterface_luaTable };
object [] inArgs = new object [] { __luaInterface_luaTable };
int [] outArgs = new int [] { };
Type [] returnTypes = __luaInterface_returnTypes [0];
LuaFunction function = NLua.Method.LuaClassHelper.GetTableFunction (__luaInterface_luaTable, "get_intProp");
object ret = NLua.Method.LuaClassHelper.CallFunction (function, args, returnTypes, inArgs, outArgs);
return (int)ret;
}
set {
int i = value;
object [] args = new object [] {
__luaInterface_luaTable ,
i
};
object [] inArgs = new object [] {
__luaInterface_luaTable,
i
};
int [] outArgs = new int [] { };
Type [] returnTypes = __luaInterface_returnTypes [1];
LuaFunction function = NLua.Method.LuaClassHelper.GetTableFunction (__luaInterface_luaTable, "set_intProp");
NLua.Method.LuaClassHelper.CallFunction (function, args, returnTypes, inArgs, outArgs);
}
}
public TestClass refProp {
get {
object [] args = new object [] { __luaInterface_luaTable };
object [] inArgs = new object [] { __luaInterface_luaTable };
int [] outArgs = new int [] { };
Type [] returnTypes = __luaInterface_returnTypes [2];
LuaFunction function = NLua.Method.LuaClassHelper.GetTableFunction (__luaInterface_luaTable, "get_refProp");
object ret = NLua.Method.LuaClassHelper.CallFunction (function, args, returnTypes, inArgs, outArgs);
return (TestClass)ret;
}
set {
TestClass test = value;
object [] args = new object [] {
__luaInterface_luaTable ,
test
};
object [] inArgs = new object [] {
__luaInterface_luaTable,
test
};
int [] outArgs = new int [] { };
Type [] returnTypes = __luaInterface_returnTypes [3];
LuaFunction function = NLua.Method.LuaClassHelper.GetTableFunction (__luaInterface_luaTable, "set_refProp");
NLua.Method.LuaClassHelper.CallFunction (function, args, returnTypes, inArgs, outArgs);
}
}
public int test1 (int a, int b)
{
object [] args = new object [] {
__luaInterface_luaTable,
a,
b
};
object [] inArgs = new object [] {
__luaInterface_luaTable,
a,
b
};
int [] outArgs = new int [] { };
Type [] returnTypes = __luaInterface_returnTypes [4];
LuaFunction function = NLua.Method.LuaClassHelper.GetTableFunction (__luaInterface_luaTable, "test1");
object ret = NLua.Method.LuaClassHelper.CallFunction (function, args, returnTypes, inArgs, outArgs);
return (int)ret;
}
public int test2 (int a, out int b)
{
object [] args = new object [] {
__luaInterface_luaTable,
a,
0
};
object [] inArgs = new object [] {
__luaInterface_luaTable,
a
};
int [] outArgs = new int [] { 1 };
Type [] returnTypes = __luaInterface_returnTypes [5];
LuaFunction function = NLua.Method.LuaClassHelper.GetTableFunction (__luaInterface_luaTable, "test2");
object ret = NLua.Method.LuaClassHelper.CallFunction (function, args, returnTypes, inArgs, outArgs);
b = (int)args [1];
return (int)ret;
}
public void test3 (int a, ref int b)
{
object [] args = new object [] {
__luaInterface_luaTable,
a,
b
};
object [] inArgs = new object [] {
__luaInterface_luaTable,
a,
b
};
int [] outArgs = new int [] { 1 };
Type [] returnTypes = __luaInterface_returnTypes [6];
LuaFunction function = NLua.Method.LuaClassHelper.GetTableFunction (__luaInterface_luaTable, "test3");
NLua.Method.LuaClassHelper.CallFunction (function, args, returnTypes, inArgs, outArgs);
b = (int)args [1];
}
public TestClass test4 (int a, int b)
{
object [] args = new object [] {
__luaInterface_luaTable,
a,
b
};
object [] inArgs = new object [] {
__luaInterface_luaTable,
a,
b
};
int [] outArgs = new int [] { };
Type [] returnTypes = __luaInterface_returnTypes [7];
LuaFunction function = NLua.Method.LuaClassHelper.GetTableFunction (__luaInterface_luaTable, "test4");
object ret = NLua.Method.LuaClassHelper.CallFunction (function, args, returnTypes, inArgs, outArgs);
return (TestClass)ret;
}
public int test5 (TestClass a, TestClass b)
{
object [] args = new object [] {
__luaInterface_luaTable,
a,
b
};
object [] inArgs = new object [] {
__luaInterface_luaTable,
a,
b
};
int [] outArgs = new int [] { };
Type [] returnTypes = __luaInterface_returnTypes [8];
LuaFunction function = NLua.Method.LuaClassHelper.GetTableFunction (__luaInterface_luaTable, "test5");
object ret = NLua.Method.LuaClassHelper.CallFunction (function, args, returnTypes, inArgs, outArgs);
return (int)ret;
}
public int test6 (int a, out TestClass b)
{
object [] args = new object [] {
__luaInterface_luaTable,
a,
null
};
object [] inArgs = new object [] {
__luaInterface_luaTable,
a,
};
int [] outArgs = new int [] { 1};
Type [] returnTypes = __luaInterface_returnTypes [9];
LuaFunction function = NLua.Method.LuaClassHelper.GetTableFunction (__luaInterface_luaTable, "test6");
object ret = NLua.Method.LuaClassHelper.CallFunction (function, args, returnTypes, inArgs, outArgs);
b = (TestClass)args [1];
return (int)ret;
}
public void test7 (int a, ref TestClass b)
{
object [] args = new object [] {
__luaInterface_luaTable,
a,
b
};
object [] inArgs = new object [] {
__luaInterface_luaTable,
a,
b
};
int [] outArgs = new int [] { 1 };
Type [] returnTypes = __luaInterface_returnTypes [10];
LuaFunction function = NLua.Method.LuaClassHelper.GetTableFunction (__luaInterface_luaTable, "test7");
NLua.Method.LuaClassHelper.CallFunction (function, args, returnTypes, inArgs, outArgs);
b = (TestClass)args [1];
}
}
#endregion
/*
* Tests passing a Lua table as an interface and
* accessing one of its value-type properties
*/
[Test]
public void NLuaValueProperty ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
lua.DoString ("test=TestClass()");
lua.DoString ("itest={}");
lua.DoString ("function itest:get_intProp() return itest.int_prop; end");
lua.DoString ("function itest:set_intProp(val) itest.int_prop=val; end");
lua.DoString ("a=test:callInterface8(itest)");
int a = (int)lua.GetNumber ("a");
Assert.AreEqual (3, a);
//Console.WriteLine("interface returned: "+a);
}
}
/*
* Tests passing a Lua table as an interface and
* accessing one of its reference type properties
*/
[Test]
public void NLuaReferenceProperty ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
lua.DoString ("test=TestClass()");
lua.DoString ("itest={}");
lua.DoString ("function itest:get_refProp() return TestClass(itest.int_prop); end");
lua.DoString ("function itest:set_refProp(val) itest.int_prop=val.testval; end");
lua.DoString ("a=test:callInterface9(itest)");
int a = (int)lua.GetNumber ("a");
Assert.AreEqual (3, a);
//Console.WriteLine("interface returned: "+a);
}
}
/*
* Tests making an object from a Lua table and calling the base
* class version of one of the methods the table overrides.
*/
[Test]
public void LuaTableBaseMethod ()
{
using (Lua lua = new Lua ()) {
lua.RegisterLuaClassType (typeof(TestClass), typeof(LuaTestClassHandler));
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
lua.DoString ("test={}");
lua.DoString ("function test:overridableMethod(x,y) print(self[base]); return 6 end");
lua.DoString ("luanet.make_object(test,'NLuaTest.Mock.TestClass')");
lua.DoString ("a=TestClass.callOverridable(test,2,3)");
int a = (int)lua.GetNumber ("a");
lua.DoString ("luanet.free_object(test)");
Assert.AreEqual (6, a);
// lua.DoString("luanet.load_assembly('NLuaTest')");
// lua.DoString("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
// lua.DoString("test={}");
//
// lua.DoString("luanet.make_object(test,'NLuaTest.Mock.TestClass')");
// lua.DoString ("function test.overridableMethod(test,x,y) return 2*test.base.overridableMethod(test,x,y); end");
// lua.DoString("a=TestClass.callOverridable(test,2,3)");
// int a = (int)lua.GetNumber("a");
// lua.DoString("luanet.free_object(test)");
// Assert.AreEqual(10, a);
//Console.WriteLine("interface returned: "+a);
}
}
/*
* Tests getting an object's method by its signature
* (from object)
*/
[Test]
public void GetMethodBySignatureFromObj ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("luanet.load_assembly('mscorlib')");
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
lua.DoString ("test=TestClass()");
lua.DoString ("setMethod=luanet.get_method_bysig(test,'setVal','System.String')");
lua.DoString ("setMethod('test')");
TestClass test = (TestClass)lua ["test"];
Assert.AreEqual ("test", test.getStrVal ());
//Console.WriteLine("interface returned: "+test.getStrVal());
}
}
/*
* Tests getting an object's method by its signature
* (from type)
*/
[Test]
public void GetMethodBySignatureFromType ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("luanet.load_assembly('mscorlib')");
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
lua.DoString ("test=TestClass()");
lua.DoString ("setMethod=luanet.get_method_bysig(TestClass,'setVal','System.String')");
lua.DoString ("setMethod(test,'test')");
TestClass test = (TestClass)lua ["test"];
Assert.AreEqual ("test", test.getStrVal ());
//Console.WriteLine("interface returned: "+test.getStrVal());
}
}
/*
* Tests getting a type's method by its signature
*/
[Test]
public void GetStaticMethodBySignature ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("luanet.load_assembly('mscorlib')");
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
lua.DoString ("make_method=luanet.get_method_bysig(TestClass,'makeFromString','System.String')");
lua.DoString ("test=make_method('test')");
TestClass test = (TestClass)lua ["test"];
Assert.AreEqual ("test", test.getStrVal ());
//Console.WriteLine("interface returned: "+test.getStrVal());
}
}
/*
* Tests getting an object's constructor by its signature
*/
[Test]
public void GetConstructorBySignature ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("luanet.load_assembly('mscorlib')");
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
lua.DoString ("test_cons=luanet.get_constructor_bysig(TestClass,'System.String')");
lua.DoString ("test=test_cons('test')");
TestClass test = (TestClass)lua ["test"];
Assert.AreEqual ("test", test.getStrVal ());
//Console.WriteLine("interface returned: "+test.getStrVal());
}
}
[Test]
public void TestVarargs()
{
using(Lua lua = new Lua()){
lua.DoString ("luanet.load_assembly('mscorlib')");
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
lua.DoString ("test=TestClass()");
lua.DoString ("test:Print('this will pass')");
lua.DoString ("test:Print('this will ','fail')");
}
}
[Test]
public void TestCtype ()
{
using (Lua lua = new Lua ()) {
lua.LoadCLRPackage ();
lua.LoadCLRPackage ();
lua.DoString ("import'System'");
var x = lua.DoString ("return luanet.ctype(String)")[0];
var x = lua.DoString ("return luanet.ctype(String)")[0];
Assert.AreEqual (x, typeof(String), "#1 String ctype test");
}
}
[Test]
public void TestPrintChars ()
{
using (Lua lua = new Lua ()) {
lua.DoString (@"print(""waüäq?=()[&]ß"")");
Assert.IsTrue (true);
}
}
[Test]
}
[Test]
public void TestPrintChars ()
{
using (Lua lua = new Lua ()) {
lua.DoString (@"print(""waüäq?=()[&]ß"")");
Assert.IsTrue (true);
}
}
[Test]
public void TestUnicodeChars ()
{
using (Lua lua = new Lua ()) {
......@@ -1965,9 +1973,9 @@ namespace NLuaTest
//Console.WriteLine("a="+num);
Assert.AreEqual (num, 2d);
}
}
[Test]
}
[Test]
public void TestDebugHook ()
{
int [] lines = { 1, 2, 1, 3 };
......@@ -1984,9 +1992,9 @@ namespace NLuaTest
val = testing_hooks()
val = val + 1");
}
}
[Test]
}
[Test]
public void TestKeyWithDots ()
{
using (Lua lua = new Lua ()) {
......@@ -1995,9 +2003,9 @@ namespace NLuaTest
Assert.AreEqual (42, (int)(double)lua ["g_dot.key\\.with\\.dot"]);
}
}
#if !WINDOWS_PHONE && !NET_3_5
[Test]
}
#if !WINDOWS_PHONE && !NET_3_5
[Test]
public void TestOperatorAdd ()
{
using (Lua lua = new Lua ()) {
......@@ -2070,8 +2078,8 @@ namespace NLuaTest
var res = lua.DoString (@"return a ~= b") [0];
Assert.AreEqual (x, res);
}
}
}
[Test]
public void TestUnaryMinus ()
{
......@@ -2087,9 +2095,9 @@ namespace NLuaTest
var res = lua ["c"];
Assert.AreEqual (expected, res);
}
}
#endif
[Test]
}
#endif
[Test]
public void TestCaseFields ()
{
using (Lua lua = new Lua ()) {
......@@ -2107,9 +2115,9 @@ namespace NLuaTest
Assert.AreEqual ("**name**", lua ["Name"]);
Assert.AreEqual ("name", lua ["Name2"]);
}
}
[Test]
}
[Test]
public void TestStaticOperators ()
{
using (Lua lua = new Lua ()) {
......@@ -2132,9 +2140,9 @@ namespace NLuaTest
Assert.AreEqual (40, x.x, "#3");
Assert.AreEqual (12, x.y, "#4");
}
}
[Test]
}
[Test]
public void TestExtensionMethods ()
{
using (Lua lua = new Lua ()) {
......@@ -2154,9 +2162,9 @@ namespace NLuaTest
double len2 = (double)lua ["len2"];
Assert.AreEqual (len, len2, "#1");
}
}
[Test]
}
[Test]
public void TestOverloadedMethods ()
{
using (Lua lua = new Lua ()) {
......@@ -2171,10 +2179,10 @@ namespace NLuaTest
");
Assert.AreEqual (3, obj.CallsToIntFunc,"#integer");
Assert.AreEqual (2, obj.CallsToStringFunc, "#string");
}
}
[Test]
}
}
[Test]
public void TestGetStack ()
{
using (Lua lua = new Lua ()) {
......@@ -2198,8 +2206,8 @@ namespace NLuaTest
");
}
m_lua = null;
}
}
public static void func()
{
#if USE_KOPILUA
......@@ -2225,21 +2233,83 @@ namespace NLuaTest
}
string x = sb.ToString ();
Assert.True (!string.IsNullOrEmpty(x));
}
[Test]
public void TestCallImplicitBaseMethod ()
{
using (var l = new Lua ()) {
l.LoadCLRPackage ();
l.DoString ("import ('NLuaTest')");
l.DoString ("res = testClass.read() ");
string res = (string)l ["res"];
Assert.AreEqual (testClass.read (), res);
}
}
static Lua m_lua;
}
}
}
[Test]
public void TestCallImplicitBaseMethod ()
{
using (var l = new Lua ()) {
l.LoadCLRPackage ();
l.DoString ("import ('NLuaTest')");
l.DoString ("res = testClass.read() ");
string res = (string)l ["res"];
Assert.AreEqual (testClass.read (), res);
}
}
[Test]
public void TestPushLuaFunctionWhenReadingDelegateProperty ()
{
bool called = false;
var _model = new DefaultElementModel ();
_model.DrawMe = (x) => {
called = true;
};
using (var l = new Lua ()) {
l ["model"] = _model;
l.DoString (@" model.DrawMe (0) ");
}
Assert.True (called);
}
[Test]
public void TestCallDelegateWithParameters ()
{
string sval = "";
int nval = 0;
using (var l = new Lua ()) {
Action<string,int> c = (s, n) => { sval = s; nval = n; };
l ["d"] = c;
l.DoString (" d ('string', 10) ");
}
Assert.AreEqual ("string", sval, "#1");
Assert.AreEqual (10 , nval, "#2");
}
[Test]
public void TestCallSimpleDelegate ()
{
bool called = false;
using (var l = new Lua ()) {
Action c = () => { called = true; };
l ["d"] = c;
l.DoString (" d () ");
}
Assert.True (called);
}
[Test]
public void TestCallDelegateWithWrongParametersShouldFail ()
{
bool fail = false;
using (var l = new Lua ()) {
Action c = () => { fail = false; };
l ["d"] = c;
try {
l.DoString (" d (10) ");
}
catch (LuaScriptException e) {
fail = true;
}
}
Assert.True (fail);
}
static Lua m_lua;
}
}
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