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; ...@@ -10,14 +10,17 @@ using NLuaTest;
namespace ConsoleTest namespace ConsoleTest
{ {
public class Program public class Program
{ {
static void Main (string [] args) static void Main (string [] args)
{ {
Core c = new Core (); using (var l = new Lua ()) {
c.Setup (); Action c = () => { Console.WriteLine ("Ola"); };
c.Sieve (); l ["d"] = c;
l.DoString (" d () ");
}
} }
} }
} }
/* /*
* This file is part of NLua. * This file is part of NLua.
* Copyright (C) 2014 Vinicius Jarina. * Copyright (C) 2014 Vinicius Jarina.
* Copyright (C) 2003-2005 Fabio Mascarenhas de Queiroz. * Copyright (C) 2003-2005 Fabio Mascarenhas de Queiroz.
* Copyright (C) 2012 Megax <http://megax.yeahunter.hu/> * Copyright (C) 2012 Megax <http://megax.yeahunter.hu/>
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal * of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights * in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is * copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions: * furnished to do so, subject to the following conditions:
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE. * THE SOFTWARE.
*/ */
using System; using System;
using System.Linq; using System.Linq;
using System.IO; using System.IO;
using System.Collections; using System.Collections;
using System.Reflection; using System.Reflection;
using System.Diagnostics; using System.Diagnostics;
using System.Collections.Generic; using System.Collections.Generic;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using NLua.Method; using NLua.Method;
using NLua.Extensions; using NLua.Extensions;
namespace NLua namespace NLua
{ {
#if USE_KOPILUA #if USE_KOPILUA
using LuaCore = KopiLua.Lua; using LuaCore = KopiLua.Lua;
using LuaState = KopiLua.LuaState; using LuaState = KopiLua.LuaState;
using LuaNativeFunction = KopiLua.LuaNativeFunction; using LuaNativeFunction = KopiLua.LuaNativeFunction;
#else #else
using LuaCore = KeraLua.Lua; using LuaCore = KeraLua.Lua;
using LuaState = KeraLua.LuaState; using LuaState = KeraLua.LuaState;
using LuaNativeFunction = KeraLua.LuaNativeFunction; using LuaNativeFunction = KeraLua.LuaNativeFunction;
#endif #endif
/* /*
* Functions used in the metatables of userdata representing * Functions used in the metatables of userdata representing
* CLR objects * CLR objects
* *
*/ */
public class MetaFunctions public class MetaFunctions
{ {
public LuaNativeFunction GcFunction { get; private set; } public LuaNativeFunction GcFunction { get; private set; }
public LuaNativeFunction IndexFunction { get; private set; } public LuaNativeFunction IndexFunction { get; private set; }
public LuaNativeFunction NewIndexFunction { get; private set; } public LuaNativeFunction NewIndexFunction { get; private set; }
public LuaNativeFunction BaseIndexFunction { get; private set; } public LuaNativeFunction BaseIndexFunction { get; private set; }
public LuaNativeFunction ClassIndexFunction { get; private set; } public LuaNativeFunction ClassIndexFunction { get; private set; }
public LuaNativeFunction ClassNewindexFunction { get; private set; } public LuaNativeFunction ClassNewindexFunction { get; private set; }
public LuaNativeFunction ExecuteDelegateFunction { get; private set; } public LuaNativeFunction ExecuteDelegateFunction { get; private set; }
public LuaNativeFunction CallConstructorFunction { get; private set; } public LuaNativeFunction CallConstructorFunction { get; private set; }
public LuaNativeFunction ToStringFunction { 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 AddFunction { get; private set; }
public LuaNativeFunction MultiplyFunction { get; private set; } public LuaNativeFunction SubtractFunction { get; private set; }
public LuaNativeFunction DivisionFunction { get; private set; } public LuaNativeFunction MultiplyFunction { get; private set; }
public LuaNativeFunction ModulosFunction { get; private set; } public LuaNativeFunction DivisionFunction { get; private set; }
public LuaNativeFunction UnaryNegationFunction { get; private set; } public LuaNativeFunction ModulosFunction { get; private set; }
public LuaNativeFunction EqualFunction { get; private set; } public LuaNativeFunction UnaryNegationFunction { get; private set; }
public LuaNativeFunction LessThanFunction { get; private set; } public LuaNativeFunction EqualFunction { get; private set; }
public LuaNativeFunction LessThanOrEqualFunction { 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; Dictionary<object, object> memberCache = new Dictionary<object, object> ();
ObjectTranslator translator;
/*
* __index metafunction for CLR objects. Implemented in Lua. /*
*/ * __index metafunction for CLR objects. Implemented in Lua.
static string luaIndexFunction = */
@"local function index(obj,name) static string luaIndexFunction =
local meta = getmetatable(obj) @"local function index(obj,name)
local cached = meta.cache[name] local meta = getmetatable(obj)
if cached ~= nil then local cached = meta.cache[name]
return cached if cached ~= nil then
else return cached
local value,isFunc = get_object_member(obj,name) else
local value,isFunc = get_object_member(obj,name)
if isFunc then
meta.cache[name]=value if isFunc then
end meta.cache[name]=value
return value end
end return value
end end
return index"; end
public static string LuaIndexFunction { return index";
get { return luaIndexFunction; } public static string LuaIndexFunction {
} get { return luaIndexFunction; }
public MetaFunctions (ObjectTranslator translator) }
{ public MetaFunctions (ObjectTranslator translator)
this.translator = translator; {
GcFunction = new LuaNativeFunction (MetaFunctions.CollectObject); this.translator = translator;
ToStringFunction = new LuaNativeFunction (MetaFunctions.ToStringLua); GcFunction = new LuaNativeFunction (MetaFunctions.CollectObject);
IndexFunction = new LuaNativeFunction (MetaFunctions.GetMethod); ToStringFunction = new LuaNativeFunction (MetaFunctions.ToStringLua);
NewIndexFunction = new LuaNativeFunction (MetaFunctions.SetFieldOrProperty); IndexFunction = new LuaNativeFunction (MetaFunctions.GetMethod);
BaseIndexFunction = new LuaNativeFunction (MetaFunctions.GetBaseMethod); NewIndexFunction = new LuaNativeFunction (MetaFunctions.SetFieldOrProperty);
CallConstructorFunction = new LuaNativeFunction (MetaFunctions.CallConstructor); BaseIndexFunction = new LuaNativeFunction (MetaFunctions.GetBaseMethod);
ClassIndexFunction = new LuaNativeFunction (MetaFunctions.GetClassMethod); CallConstructorFunction = new LuaNativeFunction (MetaFunctions.CallConstructor);
ClassNewindexFunction = new LuaNativeFunction (MetaFunctions.SetClassFieldOrProperty); ClassIndexFunction = new LuaNativeFunction (MetaFunctions.GetClassMethod);
ExecuteDelegateFunction = new LuaNativeFunction (MetaFunctions.RunFunctionDelegate); ClassNewindexFunction = new LuaNativeFunction (MetaFunctions.SetClassFieldOrProperty);
AddFunction = new LuaNativeFunction (MetaFunctions.AddLua); ExecuteDelegateFunction = new LuaNativeFunction (MetaFunctions.RunFunctionDelegate);
SubtractFunction = new LuaNativeFunction (MetaFunctions.SubtractLua); CallDelegateFunction = new LuaNativeFunction (MetaFunctions.CallDelegate);
MultiplyFunction = new LuaNativeFunction (MetaFunctions.MultiplyLua); AddFunction = new LuaNativeFunction (MetaFunctions.AddLua);
DivisionFunction = new LuaNativeFunction (MetaFunctions.DivideLua); SubtractFunction = new LuaNativeFunction (MetaFunctions.SubtractLua);
ModulosFunction = new LuaNativeFunction (MetaFunctions.ModLua); MultiplyFunction = new LuaNativeFunction (MetaFunctions.MultiplyLua);
UnaryNegationFunction = new LuaNativeFunction (MetaFunctions.UnaryNegationLua); DivisionFunction = new LuaNativeFunction (MetaFunctions.DivideLua);
EqualFunction = new LuaNativeFunction (MetaFunctions.EqualLua); ModulosFunction = new LuaNativeFunction (MetaFunctions.ModLua);
LessThanFunction = new LuaNativeFunction (MetaFunctions.LessThanLua); UnaryNegationFunction = new LuaNativeFunction (MetaFunctions.UnaryNegationLua);
LessThanOrEqualFunction = new LuaNativeFunction (MetaFunctions.LessThanOrEqualLua); 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 * __call metafunction of CLR delegates, retrieves and calls the delegate.
[MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))] */
#endif #if MONOTOUCH
private static int RunFunctionDelegate (LuaState luaState) [MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
{ #endif
var translator = ObjectTranslatorPool.Instance.Find (luaState); private static int RunFunctionDelegate (LuaState luaState)
return RunFunctionDelegate (luaState, translator); {
} 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); private static int RunFunctionDelegate (LuaState luaState, ObjectTranslator translator)
LuaLib.LuaRemove (luaState, 1); {
return func (luaState); LuaNativeFunction func = (LuaNativeFunction)translator.GetRawNetObject (luaState, 1);
} LuaLib.LuaRemove (luaState, 1);
return func (luaState);
/* }
* __gc metafunction of CLR objects.
*/ /*
#if MONOTOUCH * __gc metafunction of CLR objects.
[MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))] */
#endif #if MONOTOUCH
private static int CollectObject (LuaState luaState) [MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
{ #endif
var translator = ObjectTranslatorPool.Instance.Find (luaState); private static int CollectObject (LuaState luaState)
return CollectObject (luaState, translator); {
} var translator = ObjectTranslatorPool.Instance.Find (luaState);
return CollectObject (luaState, translator);
private static int CollectObject (LuaState luaState, ObjectTranslator translator) }
{
int udata = LuaLib.LuaNetRawNetObj (luaState, 1); private static int CollectObject (LuaState luaState, ObjectTranslator translator)
{
if (udata != -1) int udata = LuaLib.LuaNetRawNetObj (luaState, 1);
translator.CollectObject (udata);
if (udata != -1)
return 0; translator.CollectObject (udata);
}
return 0;
/* }
* __tostring metafunction of CLR objects.
*/ /*
#if MONOTOUCH * __tostring metafunction of CLR objects.
[MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))] */
#endif #if MONOTOUCH
private static int ToStringLua (LuaState luaState) [MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
{ #endif
var translator = ObjectTranslatorPool.Instance.Find (luaState); private static int ToStringLua (LuaState luaState)
return ToStringLua (luaState, translator); {
} var translator = ObjectTranslatorPool.Instance.Find (luaState);
return ToStringLua (luaState, translator);
private static int ToStringLua (LuaState luaState, ObjectTranslator translator) }
{
object obj = translator.GetRawNetObject (luaState, 1); private static int ToStringLua (LuaState luaState, ObjectTranslator translator)
{
if (obj != null) object obj = translator.GetRawNetObject (luaState, 1);
translator.Push (luaState, obj.ToString () + ": " + obj.GetHashCode ().ToString());
else if (obj != null)
LuaLib.LuaPushNil (luaState); translator.Push (luaState, obj.ToString () + ": " + obj.GetHashCode ().ToString());
else
return 1; LuaLib.LuaPushNil (luaState);
}
return 1;
}
/*
* __add metafunction of CLR objects.
*/ /*
#if MONOTOUCH * __add metafunction of CLR objects.
[MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))] */
#endif #if MONOTOUCH
static int AddLua (LuaState luaState) [MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
{ #endif
var translator = ObjectTranslatorPool.Instance.Find (luaState); static int AddLua (LuaState luaState)
return MatchOperator (luaState, "op_Addition", translator); {
} var translator = ObjectTranslatorPool.Instance.Find (luaState);
return MatchOperator (luaState, "op_Addition", translator);
/* }
* __sub metafunction of CLR objects.
*/ /*
#if MONOTOUCH * __sub metafunction of CLR objects.
[MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))] */
#endif #if MONOTOUCH
static int SubtractLua (LuaState luaState) [MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
{ #endif
var translator = ObjectTranslatorPool.Instance.Find (luaState); static int SubtractLua (LuaState luaState)
return MatchOperator (luaState, "op_Subtraction", translator); {
} var translator = ObjectTranslatorPool.Instance.Find (luaState);
return MatchOperator (luaState, "op_Subtraction", translator);
/* }
* __mul metafunction of CLR objects.
*/ /*
#if MONOTOUCH * __mul metafunction of CLR objects.
[MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))] */
#endif #if MONOTOUCH
static int MultiplyLua (LuaState luaState) [MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
{ #endif
var translator = ObjectTranslatorPool.Instance.Find (luaState); static int MultiplyLua (LuaState luaState)
return MatchOperator (luaState, "op_Multiply", translator); {
} var translator = ObjectTranslatorPool.Instance.Find (luaState);
return MatchOperator (luaState, "op_Multiply", translator);
/* }
* __div metafunction of CLR objects.
*/ /*
#if MONOTOUCH * __div metafunction of CLR objects.
[MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))] */
#endif #if MONOTOUCH
static int DivideLua (LuaState luaState) [MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
{ #endif
var translator = ObjectTranslatorPool.Instance.Find (luaState); static int DivideLua (LuaState luaState)
return MatchOperator (luaState, "op_Division", translator); {
} var translator = ObjectTranslatorPool.Instance.Find (luaState);
return MatchOperator (luaState, "op_Division", translator);
/* }
* __mod metafunction of CLR objects.
*/ /*
#if MONOTOUCH * __mod metafunction of CLR objects.
[MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))] */
#endif #if MONOTOUCH
static int ModLua (LuaState luaState) [MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
{ #endif
var translator = ObjectTranslatorPool.Instance.Find (luaState); static int ModLua (LuaState luaState)
return MatchOperator (luaState, "op_Modulus", translator); {
} var translator = ObjectTranslatorPool.Instance.Find (luaState);
return MatchOperator (luaState, "op_Modulus", translator);
/* }
* __unm metafunction of CLR objects.
*/ /*
#if MONOTOUCH * __unm metafunction of CLR objects.
[MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))] */
#endif #if MONOTOUCH
static int UnaryNegationLua (LuaState luaState) [MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
{ #endif
var translator = ObjectTranslatorPool.Instance.Find (luaState); static int UnaryNegationLua (LuaState luaState)
return UnaryNegationLua (luaState, translator); {
} var translator = ObjectTranslatorPool.Instance.Find (luaState);
return UnaryNegationLua (luaState, translator);
static int UnaryNegationLua (LuaState luaState, ObjectTranslator translator) }
{
object obj1 = translator.GetRawNetObject (luaState, 1); static int UnaryNegationLua (LuaState luaState, ObjectTranslator translator)
{
if (obj1 == null) { object obj1 = translator.GetRawNetObject (luaState, 1);
translator.ThrowError (luaState, "Cannot negate a nil object");
LuaLib.LuaPushNil (luaState); if (obj1 == null) {
return 1; translator.ThrowError (luaState, "Cannot negate a nil object");
} LuaLib.LuaPushNil (luaState);
return 1;
Type type = obj1.GetType (); }
MethodInfo opUnaryNegation = type.GetMethod ("op_UnaryNegation");
Type type = obj1.GetType ();
if (opUnaryNegation == null) { MethodInfo opUnaryNegation = type.GetMethod ("op_UnaryNegation");
translator.ThrowError (luaState, "Cannot negate object (" + type.Name + " does not overload the operator -)");
LuaLib.LuaPushNil (luaState); if (opUnaryNegation == null) {
return 1; translator.ThrowError (luaState, "Cannot negate object (" + type.Name + " does not overload the operator -)");
} LuaLib.LuaPushNil (luaState);
obj1 = opUnaryNegation.Invoke (obj1, new object [] { obj1 }); return 1;
translator.Push (luaState, obj1); }
return 1; obj1 = opUnaryNegation.Invoke (obj1, new object [] { obj1 });
} translator.Push (luaState, obj1);
return 1;
}
/*
* __eq metafunction of CLR objects.
*/ /*
#if MONOTOUCH * __eq metafunction of CLR objects.
[MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))] */
#endif #if MONOTOUCH
static int EqualLua (LuaState luaState) [MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
{ #endif
var translator = ObjectTranslatorPool.Instance.Find (luaState); static int EqualLua (LuaState luaState)
return MatchOperator (luaState, "op_Equality", translator); {
} var translator = ObjectTranslatorPool.Instance.Find (luaState);
return MatchOperator (luaState, "op_Equality", translator);
/* }
* __lt metafunction of CLR objects.
*/ /*
#if MONOTOUCH * __lt metafunction of CLR objects.
[MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))] */
#endif #if MONOTOUCH
static int LessThanLua (LuaState luaState) [MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
{ #endif
var translator = ObjectTranslatorPool.Instance.Find (luaState); static int LessThanLua (LuaState luaState)
return MatchOperator (luaState, "op_LessThan", translator); {
} var translator = ObjectTranslatorPool.Instance.Find (luaState);
return MatchOperator (luaState, "op_LessThan", translator);
/* }
* __le metafunction of CLR objects.
*/ /*
#if MONOTOUCH * __le metafunction of CLR objects.
[MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))] */
#endif #if MONOTOUCH
static int LessThanOrEqualLua (LuaState luaState) [MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
{ #endif
var translator = ObjectTranslatorPool.Instance.Find (luaState); static int LessThanOrEqualLua (LuaState luaState)
return MatchOperator (luaState, "op_LessThanOrEqual", translator); {
} var translator = ObjectTranslatorPool.Instance.Find (luaState);
return MatchOperator (luaState, "op_LessThanOrEqual", translator);
/// <summary> }
/// Debug tool to dump the lua stack
/// </summary> /// <summary>
/// FIXME, move somewhere else /// Debug tool to dump the lua stack
public static void DumpStack (ObjectTranslator translator, LuaState luaState) /// </summary>
{ /// FIXME, move somewhere else
int depth = LuaLib.LuaGetTop (luaState); public static void DumpStack (ObjectTranslator translator, LuaState luaState)
{
#if WINDOWS_PHONE || NETFX_CORE int depth = LuaLib.LuaGetTop (luaState);
Debug.WriteLine("lua stack depth: {0}", depth);
#elif UNITY_3D #if WINDOWS_PHONE || NETFX_CORE
UnityEngine.Debug.Log(string.Format("lua stack depth: {0}", depth)); Debug.WriteLine("lua stack depth: {0}", depth);
#elif !SILVERLIGHT #elif UNITY_3D
Debug.Print ("lua stack depth: {0}", depth); UnityEngine.Debug.Log(string.Format("lua stack depth: {0}", depth));
#endif #elif !SILVERLIGHT
Debug.Print ("lua stack depth: {0}", depth);
for (int i = 1; i <= depth; i++) { #endif
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 for (int i = 1; i <= depth; i++) {
string typestr = (type == LuaTypes.Table) ? "table" : LuaLib.LuaTypeName (luaState, type); var type = LuaLib.LuaType (luaState, i);
string strrep = LuaLib.LuaToString (luaState, i).ToString (); // 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);
if (type == LuaTypes.UserData) { string strrep = LuaLib.LuaToString (luaState, i).ToString ();
object obj = translator.GetRawNetObject (luaState, i);
strrep = obj.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 #if WINDOWS_PHONE || NETFX_CORE
UnityEngine.Debug.Log(string.Format("{0}: ({1}) {2}", i, typestr, strrep)); Debug.WriteLine("{0}: ({1}) {2}", i, typestr, strrep);
#elif !SILVERLIGHT #elif UNITY_3D
Debug.Print ("{0}: ({1}) {2}", i, typestr, strrep); UnityEngine.Debug.Log(string.Format("{0}: ({1}) {2}", i, typestr, strrep));
#endif #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 * Called by the __index metafunction of CLR objects in case the
* either the value of the member or a delegate to call it. * method is not cached or it is a field/property/event.
* If the member does not exist returns nil. * Receives the object and the member name as arguments and returns
*/ * either the value of the member or a delegate to call it.
#if MONOTOUCH * If the member does not exist returns nil.
[MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))] */
#endif #if MONOTOUCH
private static int GetMethod (LuaState luaState) [MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
{ #endif
var translator = ObjectTranslatorPool.Instance.Find (luaState); private static int GetMethod (LuaState luaState)
var instance = translator.MetaFunctionsInstance; {
return instance.GetMethodInternal (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); private int GetMethodInternal (LuaState luaState)
{
if (obj == null) { object obj = translator.GetRawNetObject (luaState, 1);
translator.ThrowError (luaState, "trying to index an invalid object reference");
LuaLib.LuaPushNil (luaState); if (obj == null) {
return 1; 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 object index = translator.GetObject (luaState, 2);
var objType = obj.GetType (); //var indexType = index.GetType();
var proxyType = new ProxyType (objType); string methodName = index as string; // will be null if not a string arg
// Handle the most common case, looking up the method by name. var objType = obj.GetType ();
var proxyType = new ProxyType (objType);
// CP: This will fail when using indexers and attempting to get a value with the same name as a property of the object, // Handle the most common case, looking up the method by name.
// ie: xmlelement['item'] <- item is a property of xmlelement
try { // CP: This will fail when using indexers and attempting to get a value with the same name as a property of the object,
if (!string.IsNullOrEmpty(methodName) && IsMemberPresent (proxyType, methodName)) // ie: xmlelement['item'] <- item is a property of xmlelement
return GetMember (luaState, proxyType, obj, methodName, BindingFlags.Instance); try {
} catch { 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) {
// 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); int intIndex = (int)((double)index);
#if NETFX_CORE #if NETFX_CORE
Type type = objType; Type type = objType;
#else #else
Type type = objType.UnderlyingSystemType; Type type = objType.UnderlyingSystemType;
#endif #endif
if (type == typeof(float[])) { if (type == typeof(float[])) {
float[] arr = ((float[])obj); float[] arr = ((float[])obj);
translator.Push (luaState, arr [intIndex]); translator.Push (luaState, arr [intIndex]);
} else if (type == typeof(double[])) { } else if (type == typeof(double[])) {
double[] arr = ((double[])obj); double[] arr = ((double[])obj);
translator.Push (luaState, arr [intIndex]); translator.Push (luaState, arr [intIndex]);
} else if (type == typeof(int[])) { } else if (type == typeof(int[])) {
int[] arr = ((int[])obj); int[] arr = ((int[])obj);
translator.Push (luaState, arr [intIndex]); translator.Push (luaState, arr [intIndex]);
} else { } else {
object[] arr = (object[])obj; object[] arr = (object[])obj;
translator.Push (luaState, arr [intIndex]); translator.Push (luaState, arr [intIndex]);
} }
} else { } else {
if (!string.IsNullOrEmpty (methodName) && IsExtensionMethodPresent (objType, methodName)) { if (!string.IsNullOrEmpty (methodName) && IsExtensionMethodPresent (objType, methodName)) {
return GetExtensionMethod (luaState, objType, obj, methodName); return GetExtensionMethod (luaState, objType, obj, methodName);
} }
// Try to use get_Item to index into this .net object // Try to use get_Item to index into this .net object
var methods = objType.GetMethods (); var methods = objType.GetMethods ();
foreach (var mInfo in methods) { foreach (var mInfo in methods) {
if (mInfo.Name == "get_Item") { if (mInfo.Name == "get_Item") {
//check if the signature matches the input //check if the signature matches the input
if (mInfo.GetParameters ().Length == 1) { if (mInfo.GetParameters ().Length == 1) {
var getter = mInfo; var getter = mInfo;
var actualParms = (getter != null) ? getter.GetParameters () : null; var actualParms = (getter != null) ? getter.GetParameters () : null;
if (actualParms == null || actualParms.Length != 1) { if (actualParms == null || actualParms.Length != 1) {
translator.ThrowError (luaState, "method not found (or no indexer): " + index); translator.ThrowError (luaState, "method not found (or no indexer): " + index);
LuaLib.LuaPushNil (luaState); LuaLib.LuaPushNil (luaState);
} else { } else {
// Get the index in a form acceptable to the getter // Get the index in a form acceptable to the getter
index = translator.GetAsType (luaState, 2, actualParms [0].ParameterType); index = translator.GetAsType (luaState, 2, actualParms [0].ParameterType);
object[] args = new object[1]; object[] args = new object[1];
// Just call the indexer - if out of bounds an exception will happen // Just call the indexer - if out of bounds an exception will happen
args [0] = index; args [0] = index;
try { try {
object result = getter.Invoke (obj, args); object result = getter.Invoke (obj, args);
translator.Push (luaState, result); translator.Push (luaState, result);
} catch (TargetInvocationException e) { } catch (TargetInvocationException e) {
// Provide a more readable description for the common case of key not found // Provide a more readable description for the common case of key not found
if (e.InnerException is KeyNotFoundException) if (e.InnerException is KeyNotFoundException)
translator.ThrowError (luaState, "key '" + index + "' not found "); translator.ThrowError (luaState, "key '" + index + "' not found ");
else else
translator.ThrowError (luaState, "exception indexing '" + index + "' " + e.Message); translator.ThrowError (luaState, "exception indexing '" + index + "' " + e.Message);
LuaLib.LuaPushNil (luaState); LuaLib.LuaPushNil (luaState);
} }
} }
} }
} }
} }
} }
LuaLib.LuaPushBoolean (luaState, false); LuaLib.LuaPushBoolean (luaState, false);
return 2; return 2;
} }
/* /*
* __index metafunction of base classes (the base field of Lua tables). * __index metafunction of base classes (the base field of Lua tables).
* Adds a prefix to the method name to call the base version of the method. * Adds a prefix to the method name to call the base version of the method.
*/ */
#if MONOTOUCH #if MONOTOUCH
[MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))] [MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
#endif #endif
private static int GetBaseMethod (LuaState luaState) private static int GetBaseMethod (LuaState luaState)
{ {
var translator = ObjectTranslatorPool.Instance.Find (luaState); var translator = ObjectTranslatorPool.Instance.Find (luaState);
var instance = translator.MetaFunctionsInstance; var instance = translator.MetaFunctionsInstance;
return instance.GetBaseMethodInternal (luaState); return instance.GetBaseMethodInternal (luaState);
} }
private int GetBaseMethodInternal (LuaState luaState) private int GetBaseMethodInternal (LuaState luaState)
{ {
object obj = translator.GetRawNetObject (luaState, 1); object obj = translator.GetRawNetObject (luaState, 1);
if (obj == null) { if (obj == null) {
translator.ThrowError (luaState, "trying to index an invalid object reference"); translator.ThrowError (luaState, "trying to index an invalid object reference");
LuaLib.LuaPushNil (luaState); LuaLib.LuaPushNil (luaState);
LuaLib.LuaPushBoolean (luaState, false); LuaLib.LuaPushBoolean (luaState, false);
return 2; return 2;
} }
string methodName = LuaLib.LuaToString (luaState, 2).ToString (); string methodName = LuaLib.LuaToString (luaState, 2).ToString ();
if (string.IsNullOrEmpty(methodName)) { if (string.IsNullOrEmpty(methodName)) {
LuaLib.LuaPushNil (luaState); LuaLib.LuaPushNil (luaState);
LuaLib.LuaPushBoolean (luaState, false); LuaLib.LuaPushBoolean (luaState, false);
return 2; return 2;
} }
GetMember (luaState, new ProxyType(obj.GetType ()), obj, "__luaInterface_base_" + methodName, BindingFlags.Instance); GetMember (luaState, new ProxyType(obj.GetType ()), obj, "__luaInterface_base_" + methodName, BindingFlags.Instance);
LuaLib.LuaSetTop (luaState, -2); LuaLib.LuaSetTop (luaState, -2);
if (LuaLib.LuaType (luaState, -1) == LuaTypes.Nil) { if (LuaLib.LuaType (luaState, -1) == LuaTypes.Nil) {
LuaLib.LuaSetTop (luaState, -2); LuaLib.LuaSetTop (luaState, -2);
return GetMember (luaState, new ProxyType(obj.GetType ()), obj, methodName, BindingFlags.Instance); return GetMember (luaState, new ProxyType(obj.GetType ()), obj, methodName, BindingFlags.Instance);
} }
LuaLib.LuaPushBoolean (luaState, false); LuaLib.LuaPushBoolean (luaState, false);
return 2; return 2;
} }
/// <summary> /// <summary>
/// Does this method exist as either an instance or static? /// Does this method exist as either an instance or static?
/// </summary> /// </summary>
/// <param name="objType"></param> /// <param name="objType"></param>
/// <param name="methodName"></param> /// <param name="methodName"></param>
/// <returns></returns> /// <returns></returns>
bool IsMemberPresent (ProxyType objType, string methodName) bool IsMemberPresent (ProxyType objType, string methodName)
{ {
object cachedMember = CheckMemberCache (memberCache, objType, methodName); object cachedMember = CheckMemberCache (memberCache, objType, methodName);
if (cachedMember != null) if (cachedMember != null)
return true; return true;
var members = objType.GetMember (methodName, BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public); var members = objType.GetMember (methodName, BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public);
return (members.Length > 0); return (members.Length > 0);
} }
bool IsExtensionMethodPresent (Type type, string name) bool IsExtensionMethodPresent (Type type, string name)
{ {
object cachedMember = CheckMemberCache (memberCache, type, name); object cachedMember = CheckMemberCache (memberCache, type, name);
if (cachedMember != null) if (cachedMember != null)
return true; return true;
return translator.IsExtensionMethodPresent (type, name); return translator.IsExtensionMethodPresent (type, name);
} }
int GetExtensionMethod (LuaState luaState, Type type, object obj, string name) int GetExtensionMethod (LuaState luaState, Type type, object obj, string name)
{ {
object cachedMember = CheckMemberCache (memberCache, type, name); object cachedMember = CheckMemberCache (memberCache, type, name);
if (cachedMember != null && cachedMember is LuaNativeFunction) { if (cachedMember != null && cachedMember is LuaNativeFunction) {
translator.PushFunction (luaState, (LuaNativeFunction)cachedMember); translator.PushFunction (luaState, (LuaNativeFunction)cachedMember);
translator.Push (luaState, true); translator.Push (luaState, true);
return 2; return 2;
} }
MethodInfo methodInfo = translator.GetExtensionMethod (type, name); MethodInfo methodInfo = translator.GetExtensionMethod (type, name);
var wrapper = new LuaNativeFunction ((new LuaMethodWrapper (translator, obj,new ProxyType(type), methodInfo)).invokeFunction); var wrapper = new LuaNativeFunction ((new LuaMethodWrapper (translator, obj,new ProxyType(type), methodInfo)).invokeFunction);
SetMemberCache (memberCache, type, name, wrapper); SetMemberCache (memberCache, type, name, wrapper);
translator.PushFunction (luaState, wrapper); translator.PushFunction (luaState, wrapper);
translator.Push (luaState, true); translator.Push (luaState, true);
return 2; return 2;
} }
/* /*
* Pushes the value of a member or a delegate to call it, depending on the type of * Pushes the value of a member or a delegate to call it, depending on the type of
* the member. Works with static or instance members. * the member. Works with static or instance members.
* Uses reflection to find members, and stores the reflected MemberInfo object in * Uses reflection to find members, and stores the reflected MemberInfo object in
* a cache (indexed by the type of the object and the name of the member). * a cache (indexed by the type of the object and the name of the member).
*/ */
int GetMember (LuaState luaState, ProxyType objType, object obj, string methodName, BindingFlags bindingType) int GetMember (LuaState luaState, ProxyType objType, object obj, string methodName, BindingFlags bindingType)
{ {
bool implicitStatic = false; bool implicitStatic = false;
MemberInfo member = null; MemberInfo member = null;
object cachedMember = CheckMemberCache (memberCache, objType, methodName); object cachedMember = CheckMemberCache (memberCache, objType, methodName);
if (cachedMember is LuaNativeFunction) { if (cachedMember is LuaNativeFunction) {
translator.PushFunction (luaState, (LuaNativeFunction)cachedMember); translator.PushFunction (luaState, (LuaNativeFunction)cachedMember);
translator.Push (luaState, true); translator.Push (luaState, true);
return 2; return 2;
} else if (cachedMember != null) } else if (cachedMember != null)
member = (MemberInfo)cachedMember; member = (MemberInfo)cachedMember;
else { else {
var members = objType.GetMember (methodName, bindingType | BindingFlags.Public); var members = objType.GetMember (methodName, bindingType | BindingFlags.Public);
if (members.Length > 0) if (members.Length > 0)
member = members [0]; member = members [0];
else { else {
// If we can't find any suitable instance members, try to find them as statics - but we only want to allow implicit static // If we can't find any suitable instance members, try to find them as statics - but we only want to allow implicit static
members = objType.GetMember (methodName, bindingType | BindingFlags.Static | BindingFlags.Public); members = objType.GetMember (methodName, bindingType | BindingFlags.Static | BindingFlags.Public);
if (members.Length > 0) { if (members.Length > 0) {
member = members [0]; member = members [0];
implicitStatic = true; implicitStatic = true;
} }
} }
} }
if (member != null) { 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 NETFX_CORE
if (member is FieldInfo) { return GetMember (luaState, new ProxyType(objType.UnderlyingSystemType.GetTypeInfo().BaseType), obj, methodName, bindingType);
#else #else
if (member.MemberType == MemberTypes.Field) { return GetMember (luaState, new ProxyType(objType.UnderlyingSystemType.BaseType), obj, methodName, bindingType);
#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);
#endif #endif
else else
LuaLib.LuaPushNil (luaState); LuaLib.LuaPushNil (luaState);
} catch (TargetInvocationException e) { // Convert this exception into a Lua error } catch (TargetInvocationException e) { // Convert this exception into a Lua error
ThrowError (luaState, e); ThrowError (luaState, e);
LuaLib.LuaPushNil (luaState); LuaLib.LuaPushNil (luaState);
} }
#if NETFX_CORE #if NETFX_CORE
} else if (member is EventInfo) { } else if (member is EventInfo) {
#else #else
} else if (member.MemberType == MemberTypes.Event) { } else if (member.MemberType == MemberTypes.Event) {
#endif #endif
var eventInfo = (EventInfo)member; var eventInfo = (EventInfo)member;
if (cachedMember == null) if (cachedMember == null)
SetMemberCache (memberCache, objType, methodName, member); SetMemberCache (memberCache, objType, methodName, member);
translator.Push (luaState, new RegisterEventHandler (translator.pendingEvents, obj, eventInfo)); translator.Push (luaState, new RegisterEventHandler (translator.pendingEvents, obj, eventInfo));
} else if (!implicitStatic) { } else if (!implicitStatic) {
#if NETFX_CORE #if NETFX_CORE
var typeInfo = member as TypeInfo; var typeInfo = member as TypeInfo;
if (typeInfo != null && !typeInfo.IsPublic && !typeInfo.IsNotPublic) { if (typeInfo != null && !typeInfo.IsPublic && !typeInfo.IsNotPublic) {
#else #else
if (member.MemberType == MemberTypes.NestedType) { if (member.MemberType == MemberTypes.NestedType) {
#endif #endif
// kevinh - added support for finding nested types- // kevinh - added support for finding nested types-
// cache us // cache us
if (cachedMember == null) if (cachedMember == null)
SetMemberCache (memberCache, objType, methodName, member); SetMemberCache (memberCache, objType, methodName, member);
// Find the name of our class // Find the name of our class
string name = member.Name; string name = member.Name;
var dectype = member.DeclaringType; var dectype = member.DeclaringType;
// Build a new long name and try to find the type by name // Build a new long name and try to find the type by name
string longname = dectype.FullName + "+" + name; string longname = dectype.FullName + "+" + name;
var nestedType = translator.FindType (longname); var nestedType = translator.FindType (longname);
translator.PushType (luaState, nestedType); translator.PushType (luaState, nestedType);
} else { } else {
// Member type must be 'method' // Member type must be 'method'
var wrapper = new LuaNativeFunction ((new LuaMethodWrapper (translator, objType, methodName, bindingType)).invokeFunction); var wrapper = new LuaNativeFunction ((new LuaMethodWrapper (translator, objType, methodName, bindingType)).invokeFunction);
if (cachedMember == null) if (cachedMember == null)
SetMemberCache (memberCache, objType, methodName, wrapper); SetMemberCache (memberCache, objType, methodName, wrapper);
translator.PushFunction (luaState, wrapper); translator.PushFunction (luaState, wrapper);
translator.Push (luaState, true); translator.Push (luaState, true);
return 2; return 2;
} }
} else { } else {
// If we reach this point we found a static method, but can't use it in this context because the user passed in an instance // If we reach this point we found a static method, but can't use it in this context because the user passed in an instance
translator.ThrowError (luaState, "can't pass instance to static method " + methodName); translator.ThrowError (luaState, "can't pass instance to static method " + methodName);
LuaLib.LuaPushNil (luaState); LuaLib.LuaPushNil (luaState);
} }
} else { } else {
if (objType.UnderlyingSystemType != typeof(object)) { if (objType.UnderlyingSystemType != typeof(object)) {
#if NETFX_CORE #if NETFX_CORE
return GetMember (luaState, new ProxyType(objType.UnderlyingSystemType.GetTypeInfo().BaseType), obj, methodName, bindingType); return GetMember (luaState, new ProxyType(objType.UnderlyingSystemType.GetTypeInfo().BaseType), obj, methodName, bindingType);
#else #else
return GetMember (luaState, new ProxyType(objType.UnderlyingSystemType.BaseType), obj, methodName, bindingType); return GetMember (luaState, new ProxyType(objType.UnderlyingSystemType.BaseType), obj, methodName, bindingType);
#endif #endif
} }
// kevinh - we want to throw an exception because meerly returning 'nil' in this case // kevinh - we want to throw an exception because meerly returning 'nil' in this case
// is not sufficient. valid data members may return nil and therefore there must be some // is not sufficient. valid data members may return nil and therefore there must be some
// way to know the member just doesn't exist. // way to know the member just doesn't exist.
translator.ThrowError (luaState, "unknown member name " + methodName); translator.ThrowError (luaState, "unknown member name " + methodName);
LuaLib.LuaPushNil (luaState); LuaLib.LuaPushNil (luaState);
} }
// push false because we are NOT returning a function (see luaIndexFunction) // push false because we are NOT returning a function (see luaIndexFunction)
translator.Push (luaState, false); translator.Push (luaState, false);
return 2; return 2;
} }
/* /*
* Checks if a MemberInfo object is cached, returning it or null. * Checks if a MemberInfo object is cached, returning it or null.
*/ */
object CheckMemberCache (Dictionary<object, object> memberCache, Type objType, string memberName) object CheckMemberCache (Dictionary<object, object> memberCache, Type objType, string memberName)
{ {
return CheckMemberCache (memberCache, new ProxyType (objType), memberName); return CheckMemberCache (memberCache, new ProxyType (objType), memberName);
} }
object CheckMemberCache (Dictionary<object, object> memberCache, ProxyType objType, string memberName) object CheckMemberCache (Dictionary<object, object> memberCache, ProxyType objType, string memberName)
{ {
object members = null; object members = null;
if (memberCache.TryGetValue(objType, out members)) if (memberCache.TryGetValue(objType, out members))
{ {
var membersDict = members as Dictionary<object, object>; var membersDict = members as Dictionary<object, object>;
object memberValue = null; object memberValue = null;
if (members != null && membersDict.TryGetValue(memberName, out memberValue)) if (members != null && membersDict.TryGetValue(memberName, out memberValue))
{ {
return memberValue; return memberValue;
} }
} }
return null; return null;
} }
/* /*
* Stores a MemberInfo object in the member cache. * Stores a MemberInfo object in the member cache.
*/ */
void SetMemberCache (Dictionary<object, object> memberCache, Type objType, string memberName, object member) void SetMemberCache (Dictionary<object, object> memberCache, Type objType, string memberName, object member)
{ {
SetMemberCache (memberCache, new ProxyType (objType), memberName, member); SetMemberCache (memberCache, new ProxyType (objType), memberName, member);
} }
void SetMemberCache (Dictionary<object, object> memberCache, ProxyType objType, string memberName, object member) void SetMemberCache (Dictionary<object, object> memberCache, ProxyType objType, string memberName, object member)
{ {
Dictionary<object, object> members = null; Dictionary<object, object> members = null;
object memberCacheValue = null; object memberCacheValue = null;
if (memberCache.TryGetValue(objType, out memberCacheValue)) { if (memberCache.TryGetValue(objType, out memberCacheValue)) {
members = (Dictionary<object, object>)memberCacheValue; members = (Dictionary<object, object>)memberCacheValue;
} else { } else {
members = new Dictionary<object, object>(); members = new Dictionary<object, object>();
memberCache[objType] = members; memberCache[objType] = members;
} }
members [memberName] = member; members [memberName] = member;
} }
/* /*
* __newindex metafunction of CLR objects. Receives the object, * __newindex metafunction of CLR objects. Receives the object,
* the member name and the value to be stored as arguments. Throws * the member name and the value to be stored as arguments. Throws
* and error if the assignment is invalid. * and error if the assignment is invalid.
*/ */
#if MONOTOUCH #if MONOTOUCH
[MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))] [MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
#endif #endif
private static int SetFieldOrProperty (LuaState luaState) private static int SetFieldOrProperty (LuaState luaState)
{ {
var translator = ObjectTranslatorPool.Instance.Find (luaState); var translator = ObjectTranslatorPool.Instance.Find (luaState);
var instance = translator.MetaFunctionsInstance; var instance = translator.MetaFunctionsInstance;
return instance.SetFieldOrPropertyInternal (luaState); return instance.SetFieldOrPropertyInternal (luaState);
} }
private int SetFieldOrPropertyInternal (LuaState luaState) private int SetFieldOrPropertyInternal (LuaState luaState)
{ {
object target = translator.GetRawNetObject (luaState, 1); object target = translator.GetRawNetObject (luaState, 1);
if (target == null) { if (target == null) {
translator.ThrowError (luaState, "trying to index and invalid object reference"); translator.ThrowError (luaState, "trying to index and invalid object reference");
return 0; return 0;
} }
var type = target.GetType (); var type = target.GetType ();
// First try to look up the parameter as a property name // First try to look up the parameter as a property name
string detailMessage; string detailMessage;
bool didMember = TrySetMember (luaState, new ProxyType(type), target, BindingFlags.Instance, out detailMessage); bool didMember = TrySetMember (luaState, new ProxyType(type), target, BindingFlags.Instance, out detailMessage);
if (didMember) if (didMember)
return 0; // Must have found the property name return 0; // Must have found the property name
// We didn't find a property name, now see if we can use a [] style this accessor to set array contents // We didn't find a property name, now see if we can use a [] style this accessor to set array contents
try { try {
if (type.IsArray && LuaLib.LuaIsNumber (luaState, 2)) { if (type.IsArray && LuaLib.LuaIsNumber (luaState, 2)) {
int index = (int)LuaLib.LuaToNumber (luaState, 2); int index = (int)LuaLib.LuaToNumber (luaState, 2);
var arr = (Array)target; var arr = (Array)target;
object val = translator.GetAsType (luaState, 3, arr.GetType ().GetElementType ()); object val = translator.GetAsType (luaState, 3, arr.GetType ().GetElementType ());
arr.SetValue (val, index); arr.SetValue (val, index);
} else { } else {
// Try to see if we have a this[] accessor // Try to see if we have a this[] accessor
var setter = type.GetMethod ("set_Item"); var setter = type.GetMethod ("set_Item");
if (setter != null) { if (setter != null) {
var args = setter.GetParameters (); var args = setter.GetParameters ();
var valueType = args [1].ParameterType; var valueType = args [1].ParameterType;
// The new val ue the user specified // The new val ue the user specified
object val = translator.GetAsType (luaState, 3, valueType); object val = translator.GetAsType (luaState, 3, valueType);
var indexType = args [0].ParameterType; var indexType = args [0].ParameterType;
object index = translator.GetAsType (luaState, 2, indexType); object index = translator.GetAsType (luaState, 2, indexType);
object[] methodArgs = new object[2]; object[] methodArgs = new object[2];
// Just call the indexer - if out of bounds an exception will happen // Just call the indexer - if out of bounds an exception will happen
methodArgs [0] = index; methodArgs [0] = index;
methodArgs [1] = val; methodArgs [1] = val;
setter.Invoke (target, methodArgs); setter.Invoke (target, methodArgs);
} else } else
translator.ThrowError (luaState, detailMessage); // Pass the original message from trySetMember because it is probably best translator.ThrowError (luaState, detailMessage); // Pass the original message from trySetMember because it is probably best
} }
#if !SILVERLIGHT #if !SILVERLIGHT
} catch (SEHException) { } catch (SEHException) {
// If we are seeing a C++ exception - this must actually be for Lua's private use. Let it handle it // If we are seeing a C++ exception - this must actually be for Lua's private use. Let it handle it
throw; throw;
#endif #endif
} catch (Exception e) { } catch (Exception e) {
ThrowError (luaState, e); ThrowError (luaState, e);
} }
return 0; return 0;
} }
/// <summary> /// <summary>
/// Tries to set a named property or field /// Tries to set a named property or field
/// </summary> /// </summary>
/// <param name="luaState"></param> /// <param name="luaState"></param>
/// <param name="targetType"></param> /// <param name="targetType"></param>
/// <param name="target"></param> /// <param name="target"></param>
/// <param name="bindingType"></param> /// <param name="bindingType"></param>
/// <returns>false if unable to find the named member, true for success</returns> /// <returns>false if unable to find the named member, true for success</returns>
bool TrySetMember (LuaState luaState, ProxyType targetType, object target, BindingFlags bindingType, out string detailMessage) bool TrySetMember (LuaState luaState, ProxyType targetType, object target, BindingFlags bindingType, out string detailMessage)
{ {
detailMessage = null; // No error yet detailMessage = null; // No error yet
// If not already a string just return - we don't want to call tostring - which has the side effect of // If not already a string just return - we don't want to call tostring - which has the side effect of
// changing the lua typecode to string // changing the lua typecode to string
// Note: We don't use isstring because the standard lua C isstring considers either strings or numbers to // Note: We don't use isstring because the standard lua C isstring considers either strings or numbers to
// be true for isstring. // be true for isstring.
if (LuaLib.LuaType (luaState, 2) != LuaTypes.String) { if (LuaLib.LuaType (luaState, 2) != LuaTypes.String) {
detailMessage = "property names must be strings"; detailMessage = "property names must be strings";
return false; return false;
} }
// We only look up property names by string // We only look up property names by string
string fieldName = LuaLib.LuaToString (luaState, 2).ToString (); string fieldName = LuaLib.LuaToString (luaState, 2).ToString ();
if (fieldName == null || fieldName.Length < 1 || !(char.IsLetter (fieldName [0]) || fieldName [0] == '_')) { if (fieldName == null || fieldName.Length < 1 || !(char.IsLetter (fieldName [0]) || fieldName [0] == '_')) {
detailMessage = "invalid property name"; detailMessage = "invalid property name";
return false; return false;
} }
// Find our member via reflection or the cache // Find our member via reflection or the cache
var member = (MemberInfo)CheckMemberCache (memberCache, targetType, fieldName); var member = (MemberInfo)CheckMemberCache (memberCache, targetType, fieldName);
if (member == null) { if (member == null) {
var members = targetType.GetMember (fieldName, bindingType | BindingFlags.Public); var members = targetType.GetMember (fieldName, bindingType | BindingFlags.Public);
if (members.Length > 0) { if (members.Length > 0) {
member = members [0]; member = members [0];
SetMemberCache (memberCache, targetType, fieldName, member); SetMemberCache (memberCache, targetType, fieldName, member);
} else { } else {
detailMessage = "field or property '" + fieldName + "' does not exist"; detailMessage = "field or property '" + fieldName + "' does not exist";
return false; return false;
} }
} }
#if NETFX_CORE #if NETFX_CORE
if (member is FieldInfo) { if (member is FieldInfo) {
#else #else
if (member.MemberType == MemberTypes.Field) { if (member.MemberType == MemberTypes.Field) {
#endif #endif
var field = (FieldInfo)member; var field = (FieldInfo)member;
object val = translator.GetAsType (luaState, 3, field.FieldType); object val = translator.GetAsType (luaState, 3, field.FieldType);
try { try {
field.SetValue (target, val); field.SetValue (target, val);
} catch (Exception e) { } catch (Exception e) {
ThrowError (luaState, e); ThrowError (luaState, e);
} }
// We did a call // We did a call
return true; return true;
#if NETFX_CORE #if NETFX_CORE
} else if (member is PropertyInfo) { } else if (member is PropertyInfo) {
#else #else
} else if (member.MemberType == MemberTypes.Property) { } else if (member.MemberType == MemberTypes.Property) {
#endif #endif
var property = (PropertyInfo)member; var property = (PropertyInfo)member;
object val = translator.GetAsType (luaState, 3, property.PropertyType); object val = translator.GetAsType (luaState, 3, property.PropertyType);
try { try {
property.SetValue (target, val, null); property.SetValue (target, val, null);
} catch (Exception e) { } catch (Exception e) {
ThrowError (luaState, e); ThrowError (luaState, e);
} }
// We did a call // We did a call
return true; return true;
} }
detailMessage = "'" + fieldName + "' is not a .net field or property"; detailMessage = "'" + fieldName + "' is not a .net field or property";
return false; return false;
} }
/* /*
* Writes to fields or properties, either static or instance. Throws an error * Writes to fields or properties, either static or instance. Throws an error
* if the operation is invalid. * if the operation is invalid.
*/ */
private int SetMember (LuaState luaState, ProxyType targetType, object target, BindingFlags bindingType) private int SetMember (LuaState luaState, ProxyType targetType, object target, BindingFlags bindingType)
{ {
string detail; string detail;
bool success = TrySetMember (luaState, targetType, target, bindingType, out detail); bool success = TrySetMember (luaState, targetType, target, bindingType, out detail);
if (!success) if (!success)
translator.ThrowError (luaState, detail); translator.ThrowError (luaState, detail);
return 0; return 0;
} }
/// <summary> /// <summary>
/// Convert a C# exception into a Lua error /// Convert a C# exception into a Lua error
/// </summary> /// </summary>
/// <param name="e"></param> /// <param name="e"></param>
/// We try to look into the exception to give the most meaningful description /// We try to look into the exception to give the most meaningful description
void ThrowError (LuaState luaState, Exception e) void ThrowError (LuaState luaState, Exception e)
{ {
// If we got inside a reflection show what really happened // If we got inside a reflection show what really happened
var te = e as TargetInvocationException; var te = e as TargetInvocationException;
if (te != null) if (te != null)
e = te.InnerException; e = te.InnerException;
translator.ThrowError (luaState, e); translator.ThrowError (luaState, e);
} }
/* /*
* __index metafunction of type references, works on static members. * __index metafunction of type references, works on static members.
*/ */
#if MONOTOUCH #if MONOTOUCH
[MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))] [MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
#endif #endif
private static int GetClassMethod (LuaState luaState) private static int GetClassMethod (LuaState luaState)
{ {
var translator = ObjectTranslatorPool.Instance.Find (luaState); var translator = ObjectTranslatorPool.Instance.Find (luaState);
var instance = translator.MetaFunctionsInstance; var instance = translator.MetaFunctionsInstance;
return instance.GetClassMethodInternal (luaState); return instance.GetClassMethodInternal (luaState);
} }
private int GetClassMethodInternal (LuaState luaState) private int GetClassMethodInternal (LuaState luaState)
{ {
ProxyType klass; ProxyType klass;
object obj = translator.GetRawNetObject (luaState, 1); object obj = translator.GetRawNetObject (luaState, 1);
if (obj == null || !(obj is ProxyType)) { if (obj == null || !(obj is ProxyType)) {
translator.ThrowError (luaState, "trying to index an invalid type reference"); translator.ThrowError (luaState, "trying to index an invalid type reference");
LuaLib.LuaPushNil (luaState); LuaLib.LuaPushNil (luaState);
return 1; return 1;
} else } else
klass = (ProxyType)obj; klass = (ProxyType)obj;
if (LuaLib.LuaIsNumber (luaState, 2)) { if (LuaLib.LuaIsNumber (luaState, 2)) {
int size = (int)LuaLib.LuaToNumber (luaState, 2); int size = (int)LuaLib.LuaToNumber (luaState, 2);
translator.Push (luaState, Array.CreateInstance (klass.UnderlyingSystemType, size)); translator.Push (luaState, Array.CreateInstance (klass.UnderlyingSystemType, size));
return 1; return 1;
} else { } else {
string methodName = LuaLib.LuaToString (luaState, 2).ToString (); string methodName = LuaLib.LuaToString (luaState, 2).ToString ();
if (string.IsNullOrEmpty(methodName)) { if (string.IsNullOrEmpty(methodName)) {
LuaLib.LuaPushNil (luaState); LuaLib.LuaPushNil (luaState);
return 1; return 1;
} }
else else
return GetMember (luaState, klass, null, methodName, BindingFlags.Static); return GetMember (luaState, klass, null, methodName, BindingFlags.Static);
} }
} }
/* /*
* __newindex function of type references, works on static members. * __newindex function of type references, works on static members.
*/ */
#if MONOTOUCH #if MONOTOUCH
[MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))] [MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
#endif #endif
private static int SetClassFieldOrProperty (LuaState luaState) private static int SetClassFieldOrProperty (LuaState luaState)
{ {
var translator = ObjectTranslatorPool.Instance.Find (luaState); var translator = ObjectTranslatorPool.Instance.Find (luaState);
var instance = translator.MetaFunctionsInstance; var instance = translator.MetaFunctionsInstance;
return instance.SetClassFieldOrPropertyInternal (luaState); return instance.SetClassFieldOrPropertyInternal (luaState);
} }
private int SetClassFieldOrPropertyInternal (LuaState luaState) private int SetClassFieldOrPropertyInternal (LuaState luaState)
{ {
ProxyType target; ProxyType target;
object obj = translator.GetRawNetObject (luaState, 1); object obj = translator.GetRawNetObject (luaState, 1);
if (obj == null || !(obj is ProxyType)) { if (obj == null || !(obj is ProxyType)) {
translator.ThrowError (luaState, "trying to index an invalid type reference"); translator.ThrowError (luaState, "trying to index an invalid type reference");
return 0; return 0;
} else } else
target = (ProxyType)obj; target = (ProxyType)obj;
return SetMember (luaState, target, null, BindingFlags.Static); return SetMember (luaState, target, null, BindingFlags.Static);
} }
/* /*
* __call metafunction of type references. Searches for and calls * __call metafunction of Delegates.
* 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 #if MONOTOUCH
* generates an exception. [MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
*/ #endif
#if MONOTOUCH static int CallDelegate (LuaState luaState)
[MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))] {
#endif var translator = ObjectTranslatorPool.Instance.Find (luaState);
private static int CallConstructor (LuaState luaState) var instance = translator.MetaFunctionsInstance;
{ return instance.CallDelegateInternal (luaState);
var translator = ObjectTranslatorPool.Instance.Find (luaState); }
var instance = translator.MetaFunctionsInstance;
return instance.CallConstructorInternal (luaState); int CallDelegateInternal (LuaState luaState)
} {
object objDelegate = translator.GetRawNetObject (luaState, 1);
private int CallConstructorInternal (LuaState luaState)
{ if (objDelegate == null || !(objDelegate is Delegate)) {
var validConstructor = new MethodCache (); translator.ThrowError (luaState, "trying to invoke a not delegate or callable value");
ProxyType klass; LuaLib.LuaPushNil (luaState);
object obj = translator.GetRawNetObject (luaState, 1); return 1;
}
if (obj == null || !(obj is ProxyType)) {
translator.ThrowError (luaState, "trying to call constructor on an invalid type reference"); LuaLib.LuaRemove (luaState, 1);
LuaLib.LuaPushNil (luaState);
return 1; var validDelegate = new MethodCache ();
} else Delegate del = (Delegate)objDelegate;
klass = (ProxyType)obj; MethodBase methodDelegate = del.Method;
bool isOk = MatchParameters (luaState, methodDelegate, ref validDelegate);
LuaLib.LuaRemove (luaState, 1);
var constructors = klass.UnderlyingSystemType.GetConstructors (); if (isOk) {
object result;
foreach (var constructor in constructors) {
bool isConstructor = MatchParameters (luaState, constructor, ref validConstructor); if (methodDelegate.IsStatic)
result = methodDelegate.Invoke (null, validDelegate.args);
if (isConstructor) { else
try { result = methodDelegate.Invoke (del.Target, validDelegate.args);
translator.Push (luaState, constructor.Invoke (validConstructor.args));
} catch (TargetInvocationException e) { translator.Push (luaState, result);
ThrowError (luaState, e); return 1;
LuaLib.LuaPushNil (luaState); }
} catch {
LuaLib.LuaPushNil (luaState); translator.ThrowError (luaState, "Cannot invoke delegate (invalid arguments for " + methodDelegate.Name + ")");
} LuaLib.LuaPushNil (luaState);
return 1;
return 1; }
}
} /*
* __call metafunction of type references. Searches for and calls
string constructorName = (constructors.Length == 0) ? "unknown" : constructors [0].Name; * a constructor for the type. Returns nil if the constructor is not
translator.ThrowError (luaState, String.Format ("{0} does not contain constructor({1}) argument match", * found or if the arguments are invalid. Throws an error if the constructor
klass.UnderlyingSystemType, constructorName)); * generates an exception.
LuaLib.LuaPushNil (luaState); */
return 1; #if MONOTOUCH
} [MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
static bool IsInteger(double x) { #endif
return Math.Ceiling(x) == x; private static int CallConstructor (LuaState luaState)
} {
var translator = ObjectTranslatorPool.Instance.Find (luaState);
static object GetTargetObject (LuaState luaState, string operation, ObjectTranslator translator) var instance = translator.MetaFunctionsInstance;
{ return instance.CallConstructorInternal (luaState);
Type t; }
object target = translator.GetRawNetObject (luaState, 1);
if (target != null) { private int CallConstructorInternal (LuaState luaState)
t = target.GetType (); {
if (t.HasMethod (operation)) var validConstructor = new MethodCache ();
return target; ProxyType klass;
} object obj = translator.GetRawNetObject (luaState, 1);
target = translator.GetRawNetObject (luaState, 2);
if (target != null) { if (obj == null || !(obj is ProxyType)) {
t = target.GetType (); translator.ThrowError (luaState, "trying to call constructor on an invalid type reference");
if (t.HasMethod (operation)) LuaLib.LuaPushNil (luaState);
return target; return 1;
} } else
return null; klass = (ProxyType)obj;
}
LuaLib.LuaRemove (luaState, 1);
static int MatchOperator (LuaState luaState, string operation, ObjectTranslator translator) var constructors = klass.UnderlyingSystemType.GetConstructors ();
{
var validOperator = new MethodCache (); foreach (var constructor in constructors) {
bool isConstructor = MatchParameters (luaState, constructor, ref validConstructor);
object target = GetTargetObject (luaState, operation, translator);
if (isConstructor) {
if (target == null) { try {
translator.ThrowError (luaState, "Cannot call " + operation + " on a nil object"); translator.Push (luaState, constructor.Invoke (validConstructor.args));
LuaLib.LuaPushNil (luaState); } catch (TargetInvocationException e) {
return 1; ThrowError (luaState, e);
} LuaLib.LuaPushNil (luaState);
} catch {
Type type = target.GetType (); LuaLib.LuaPushNil (luaState);
var operators = type.GetMethods (operation, BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static); }
foreach (var op in operators) { return 1;
bool isOk = translator.MatchParameters (luaState, op, ref validOperator); }
}
if (!isOk)
continue; string constructorName = (constructors.Length == 0) ? "unknown" : constructors [0].Name;
translator.ThrowError (luaState, String.Format ("{0} does not contain constructor({1}) argument match",
object result; klass.UnderlyingSystemType, constructorName));
if (op.IsStatic) LuaLib.LuaPushNil (luaState);
result = op.Invoke (null, validOperator.args); return 1;
else }
result = op.Invoke (target, validOperator.args); static bool IsInteger(double x) {
translator.Push (luaState, result); return Math.Ceiling(x) == x;
return 1; }
}
static object GetTargetObject (LuaState luaState, string operation, ObjectTranslator translator)
translator.ThrowError (luaState, "Cannot call (" + operation + ") on object type " + type.Name); {
LuaLib.LuaPushNil (luaState); Type t;
return 1; object target = translator.GetRawNetObject (luaState, 1);
} if (target != null) {
t = target.GetType ();
if (t.HasMethod (operation))
return target;
internal Array TableToArray (Func<int, object> luaParamValueExtractor, Type paramArrayType, int startIndex, int count) }
{ target = translator.GetRawNetObject (luaState, 2);
Array paramArray; if (target != null) {
t = target.GetType ();
if (count == 0) if (t.HasMethod (operation))
return Array.CreateInstance (paramArrayType, 0); return target;
}
var luaParamValue = luaParamValueExtractor (startIndex); return null;
}
if (luaParamValue is LuaTable) {
LuaTable table = (LuaTable)luaParamValue; static int MatchOperator (LuaState luaState, string operation, ObjectTranslator translator)
IDictionaryEnumerator tableEnumerator = table.GetEnumerator (); {
tableEnumerator.Reset (); var validOperator = new MethodCache ();
paramArray = Array.CreateInstance (paramArrayType, table.Values.Count);
object target = GetTargetObject (luaState, operation, translator);
int paramArrayIndex = 0;
if (target == null) {
while (tableEnumerator.MoveNext ()) { translator.ThrowError (luaState, "Cannot call " + operation + " on a nil object");
LuaLib.LuaPushNil (luaState);
object value = tableEnumerator.Value; return 1;
}
if (paramArrayType == typeof (object)) {
if (value != null && value.GetType () == typeof (double) && IsInteger ((double)value)) Type type = target.GetType ();
value = Convert.ToInt32 ((double)value); var operators = type.GetMethods (operation, BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
}
#if SILVERLIGHT foreach (var op in operators) {
paramArray.SetValue (Convert.ChangeType (value, paramArrayType, System.Globalization.CultureInfo.InvariantCulture), paramArrayIndex); bool isOk = translator.MatchParameters (luaState, op, ref validOperator);
#else
paramArray.SetValue (Convert.ChangeType (value, paramArrayType), paramArrayIndex); if (!isOk)
#endif continue;
paramArrayIndex++;
} object result;
} else { if (op.IsStatic)
result = op.Invoke (null, validOperator.args);
paramArray = Array.CreateInstance (paramArrayType, count); else
result = op.Invoke (target, validOperator.args);
paramArray.SetValue (luaParamValue, 0); translator.Push (luaState, result);
return 1;
for (int i = 1; i < count; i++) { }
startIndex++;
var value = luaParamValueExtractor (startIndex); translator.ThrowError (luaState, "Cannot call (" + operation + ") on object type " + type.Name);
paramArray.SetValue (value, i); LuaLib.LuaPushNil (luaState);
} return 1;
} }
return paramArray;
} internal Array TableToArray (Func<int, object> luaParamValueExtractor, Type paramArrayType, int startIndex, int count)
{
/* Array paramArray;
* Matches a method against its arguments in the Lua stack. Returns
* if the match was successful. It it was also returns the information if (count == 0)
* necessary to invoke the method. return Array.CreateInstance (paramArrayType, 0);
*/
internal bool MatchParameters (LuaState luaState, MethodBase method, ref MethodCache methodCache) var luaParamValue = luaParamValueExtractor (startIndex);
{
ExtractValue extractValue; if (luaParamValue is LuaTable) {
bool isMethod = true; LuaTable table = (LuaTable)luaParamValue;
var paramInfo = method.GetParameters (); IDictionaryEnumerator tableEnumerator = table.GetEnumerator ();
int currentLuaParam = 1; tableEnumerator.Reset ();
int nLuaParams = LuaLib.LuaGetTop (luaState); paramArray = Array.CreateInstance (paramArrayType, table.Values.Count);
var paramList = new List<object> ();
var outList = new List<int> (); int paramArrayIndex = 0;
var argTypes = new List<MethodArgs> ();
while (tableEnumerator.MoveNext ()) {
foreach (var currentNetParam in paramInfo) {
#if !SILVERLIGHT object value = tableEnumerator.Value;
if (!currentNetParam.IsIn && currentNetParam.IsOut) // Skips out params
#else if (paramArrayType == typeof (object)) {
if (currentNetParam.IsOut) // Skips out params if (value != null && value.GetType () == typeof (double) && IsInteger ((double)value))
#endif value = Convert.ToInt32 ((double)value);
{ }
paramList.Add (null); #if SILVERLIGHT
outList.Add (paramList.LastIndexOf (null)); paramArray.SetValue (Convert.ChangeType (value, paramArrayType, System.Globalization.CultureInfo.InvariantCulture), paramArrayIndex);
} else if (IsTypeCorrect (luaState, currentLuaParam, currentNetParam, out extractValue)) { // Type checking #else
var value = extractValue (luaState, currentLuaParam); paramArray.SetValue (Convert.ChangeType (value, paramArrayType), paramArrayIndex);
paramList.Add (value); #endif
int index = paramList.LastIndexOf (value); paramArrayIndex++;
var methodArg = new MethodArgs (); }
methodArg.index = index; } else {
methodArg.extractValue = extractValue;
argTypes.Add (methodArg); paramArray = Array.CreateInstance (paramArrayType, count);
if (currentNetParam.ParameterType.IsByRef) paramArray.SetValue (luaParamValue, 0);
outList.Add (index);
for (int i = 1; i < count; i++) {
currentLuaParam++; startIndex++;
} // Type does not match, ignore if the parameter is optional var value = luaParamValueExtractor (startIndex);
else if (IsParamsArray (luaState, currentLuaParam, currentNetParam, out extractValue)) { paramArray.SetValue (value, i);
}
var paramArrayType = currentNetParam.ParameterType.GetElementType (); }
Func<int, object> extractDelegate = (currentParam) => { return paramArray;
currentLuaParam ++;
return extractValue (luaState, currentParam); }
};
int count = (nLuaParams - currentLuaParam) + 1; /*
Array paramArray = TableToArray (extractDelegate, paramArrayType, currentLuaParam, count); * Matches a method against its arguments in the Lua stack. Returns
* if the match was successful. It it was also returns the information
paramList.Add (paramArray); * necessary to invoke the method.
int index = paramList.LastIndexOf (paramArray); */
var methodArg = new MethodArgs (); internal bool MatchParameters (LuaState luaState, MethodBase method, ref MethodCache methodCache)
methodArg.index = index; {
methodArg.extractValue = extractValue; ExtractValue extractValue;
methodArg.isParamsArray = true; bool isMethod = true;
methodArg.paramsArrayType = paramArrayType; var paramInfo = method.GetParameters ();
argTypes.Add (methodArg); int currentLuaParam = 1;
int nLuaParams = LuaLib.LuaGetTop (luaState);
} else if (currentLuaParam > nLuaParams) { // Adds optional parameters var paramList = new List<object> ();
if (currentNetParam.IsOptional) var outList = new List<int> ();
paramList.Add (currentNetParam.DefaultValue); var argTypes = new List<MethodArgs> ();
else {
isMethod = false; foreach (var currentNetParam in paramInfo) {
break; #if !SILVERLIGHT
} if (!currentNetParam.IsIn && currentNetParam.IsOut) // Skips out params
} else if (currentNetParam.IsOptional) #else
paramList.Add (currentNetParam.DefaultValue); if (currentNetParam.IsOut) // Skips out params
else { // No match #endif
isMethod = false; {
break; paramList.Add (null);
} outList.Add (paramList.LastIndexOf (null));
} } else if (IsTypeCorrect (luaState, currentLuaParam, currentNetParam, out extractValue)) { // Type checking
var value = extractValue (luaState, currentLuaParam);
if (currentLuaParam != nLuaParams + 1) // Number of parameters does not match paramList.Add (value);
isMethod = false; int index = paramList.LastIndexOf (value);
if (isMethod) { var methodArg = new MethodArgs ();
methodCache.args = paramList.ToArray (); methodArg.index = index;
methodCache.cachedMethod = method; methodArg.extractValue = extractValue;
methodCache.outList = outList.ToArray (); argTypes.Add (methodArg);
methodCache.argTypes = argTypes.ToArray ();
} if (currentNetParam.ParameterType.IsByRef)
return isMethod; outList.Add (index);
}
currentLuaParam++;
/// <summary> } // Type does not match, ignore if the parameter is optional
/// CP: Fix for operator overloading failure else if (IsParamsArray (luaState, currentLuaParam, currentNetParam, out extractValue)) {
/// Returns true if the type is set and assigns the extract value
/// </summary> var paramArrayType = currentNetParam.ParameterType.GetElementType ();
/// <param name="luaState"></param>
/// <param name="currentLuaParam"></param> Func<int, object> extractDelegate = (currentParam) => {
/// <param name="currentNetParam"></param> currentLuaParam ++;
/// <param name="extractValue"></param> return extractValue (luaState, currentParam);
/// <returns></returns> };
private bool IsTypeCorrect (LuaState luaState, int currentLuaParam, ParameterInfo currentNetParam, out ExtractValue extractValue) int count = (nLuaParams - currentLuaParam) + 1;
{ Array paramArray = TableToArray (extractDelegate, paramArrayType, currentLuaParam, count);
try {
return (extractValue = translator.typeChecker.CheckLuaType (luaState, currentLuaParam, currentNetParam.ParameterType)) != null; paramList.Add (paramArray);
} catch { int index = paramList.LastIndexOf (paramArray);
extractValue = null; var methodArg = new MethodArgs ();
Debug.WriteLine ("Type wasn't correct"); methodArg.index = index;
return false; methodArg.extractValue = extractValue;
} methodArg.isParamsArray = true;
} methodArg.paramsArrayType = paramArrayType;
argTypes.Add (methodArg);
private bool IsParamsArray (LuaState luaState, int currentLuaParam, ParameterInfo currentNetParam, out ExtractValue extractValue)
{ } else if (currentLuaParam > nLuaParams) { // Adds optional parameters
extractValue = null; if (currentNetParam.IsOptional)
paramList.Add (currentNetParam.DefaultValue);
if (currentNetParam.GetCustomAttributes (typeof(ParamArrayAttribute), false).Any ()) { else {
LuaTypes luaType; isMethod = false;
break;
try { }
luaType = LuaLib.LuaType (luaState, currentLuaParam); } else if (currentNetParam.IsOptional)
} catch (Exception ex) { paramList.Add (currentNetParam.DefaultValue);
Debug.WriteLine ("Could not retrieve lua type while attempting to determine params Array Status."); else { // No match
Debug.WriteLine (ex.Message); isMethod = false;
extractValue = null; break;
return false; }
} }
if (luaType == LuaTypes.Table) { if (currentLuaParam != nLuaParams + 1) // Number of parameters does not match
try { isMethod = false;
extractValue = translator.typeChecker.GetExtractor (typeof(LuaTable)); if (isMethod) {
} catch (Exception/* ex*/) { methodCache.args = paramList.ToArray ();
Debug.WriteLine ("An error occurred during an attempt to retrieve a LuaTable extractor while checking for params array status."); methodCache.cachedMethod = method;
} methodCache.outList = outList.ToArray ();
methodCache.argTypes = argTypes.ToArray ();
if (extractValue != null) { }
return true; return isMethod;
} }
} else {
var paramElementType = currentNetParam.ParameterType.GetElementType (); /// <summary>
/// CP: Fix for operator overloading failure
try { /// Returns true if the type is set and assigns the extract value
extractValue = translator.typeChecker.CheckLuaType (luaState, currentLuaParam, paramElementType); /// </summary>
} catch (Exception/* ex*/) { /// <param name="luaState"></param>
Debug.WriteLine (string.Format ("An error occurred during an attempt to retrieve an extractor ({0}) while checking for params array status.", paramElementType.FullName)); /// <param name="currentLuaParam"></param>
} /// <param name="currentNetParam"></param>
/// <param name="extractValue"></param>
if (extractValue != null) { /// <returns></returns>
return true; private bool IsTypeCorrect (LuaState luaState, int currentLuaParam, ParameterInfo currentNetParam, out ExtractValue extractValue)
} {
} try {
} return (extractValue = translator.typeChecker.CheckLuaType (luaState, currentLuaParam, currentNetParam.ParameterType)) != null;
} catch {
Debug.WriteLine ("Type wasn't Params object."); extractValue = null;
return false; 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 ...@@ -571,6 +571,7 @@ namespace NLua
PushObject (luaState, func, "luaNet_function"); PushObject (luaState, func, "luaNet_function");
} }
/* /*
* Pushes a CLR object into the Lua stack as an userdata * Pushes a CLR object into the Lua stack as an userdata
* with the provided metatable * with the provided metatable
...@@ -651,6 +652,7 @@ namespace NLua ...@@ -651,6 +652,7 @@ namespace NLua
LuaLib.LuaRawSet (luaState, -3); LuaLib.LuaRawSet (luaState, -3);
// Bind C# operator with Lua metamethods (__add, __sub, __mul) // Bind C# operator with Lua metamethods (__add, __sub, __mul)
RegisterOperatorsFunctions (luaState, o.GetType ()); RegisterOperatorsFunctions (luaState, o.GetType ());
RegisterCallMethodForDelegate (luaState, o);
} }
} else } else
LuaLib.LuaLGetMetatable (luaState, metatable); LuaLib.LuaLGetMetatable (luaState, metatable);
...@@ -667,6 +669,16 @@ namespace NLua ...@@ -667,6 +669,16 @@ namespace NLua
LuaLib.LuaRemove (luaState, -2); 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) void RegisterOperatorsFunctions (LuaState luaState, Type type)
{ {
if (type.HasAdditionOpertator ()) { if (type.HasAdditionOpertator ()) {
...@@ -930,8 +942,8 @@ namespace NLua ...@@ -930,8 +942,8 @@ namespace NLua
if (o == null) if (o == null)
LuaLib.LuaPushNil (luaState); LuaLib.LuaPushNil (luaState);
else if (o is sbyte || o is byte || o is short || o is ushort || else if (o is sbyte || o is byte || o is short || o is ushort ||
o is int || o is uint || o is long || o is float || o is int || o is uint || o is long || o is float ||
o is ulong || o is decimal || o is double) { o is ulong || o is decimal || o is double) {
double d = Convert.ToDouble (o); double d = Convert.ToDouble (o);
LuaLib.LuaPushNumber (luaState, d); LuaLib.LuaPushNumber (luaState, d);
} else if (o is char) { } else if (o is char) {
......
using System; using System;
using System.Text; using System.Text;
using System.Collections.Generic; using System.Collections.Generic;
using NLuaTest.Mock; using NLuaTest.Mock;
using System.Reflection; using System.Reflection;
using System.Threading; using System.Threading;
using NLua; using NLua;
using NLua.Exceptions; using NLua.Exceptions;
#if MONOTOUCH #if MONOTOUCH
using MonoTouch.Foundation; using MonoTouch.Foundation;
#endif #endif
#if WINDOWS_PHONE #if WINDOWS_PHONE
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using SetUp = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestInitializeAttribute; using SetUp = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestInitializeAttribute;
using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute; using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute; using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
#else #else
using NUnit.Framework; using NUnit.Framework;
#endif #endif
namespace NLuaTest namespace NLuaTest
{ {
#if MONOTOUCH #if MONOTOUCH
[Preserve (AllMembers = true)] [Preserve (AllMembers = true)]
#endif #endif
public class master public class master
{ {
public static string read() public static string read()
{ {
return "test-master"; return "test-master";
} }
} }
#if MONOTOUCH #if MONOTOUCH
[Preserve (AllMembers = true)] [Preserve (AllMembers = true)]
#endif #endif
public class testClass : master public class testClass : master
{ {
public String strData; public String strData;
public int intData; public int intData;
public static string read2() public static string read2()
{ {
return "test"; return "test";
} }
} }
#if MONOTOUCH #if MONOTOUCH
[Preserve (AllMembers = true)] [Preserve (AllMembers = true)]
#endif
public class DefaultElementModel
{
public Action<double> DrawMe{ get; set; }
}
#if MONOTOUCH
[Preserve (AllMembers = true)]
#endif #endif
public class TestCaseName { public class TestCaseName {
public string name = "name"; public string name = "name";
...@@ -55,1886 +63,1886 @@ namespace NLuaTest ...@@ -55,1886 +63,1886 @@ namespace NLuaTest
return "**" + name + "**"; 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)] * Tests passing a Lua table as an interface and
#endif * calling one of its methods with value-type params
public class Vector */
{ [Test]
public double x; public void NLuaAAValueTypes ()
public double y;
public static Vector operator * (float k, Vector v)
{ {
var r = new Vector (); using (Lua lua = new Lua ()) {
r.x = v.x * k; lua.RegisterLuaClassType (typeof(ITest), typeof(LuaITestClassHandler));
r.y = v.y * k; lua.DoString ("luanet.load_assembly('NLuaTest')");
return r; 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 (); public LuaTable __luaInterface_luaTable;
r.x = v.x * k; public Type[][] __luaInterface_returnTypes;
r.y = v.y * k;
return r; 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 /*
{ * Tests passing a Lua table as an interface and
public static double Lenght (this Vector v) * 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);
}
} }
} /*
* Tests passing a Lua table as an interface and
[TestFixture] * accessing one of its reference type properties
#if MONOTOUCH */
[Preserve (AllMembers = true)] [Test]
#endif public void NLuaReferenceProperty ()
public class LuaTests
{
public static readonly char UnicodeChar = '\uE007';
public static string UnicodeString
{ {
get using (Lua lua = new Lua ()) {
{ lua.DoString ("luanet.load_assembly('NLuaTest')");
return Convert.ToString (UnicodeChar); 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] [Test]
public void TestStructHashesEqual() public void LuaTableBaseMethod ()
{ {
using (Lua lua = new Lua()) using (Lua lua = new Lua ()) {
{ lua.RegisterLuaClassType (typeof(TestClass), typeof(LuaTestClassHandler));
lua.DoString("luanet.load_assembly('NLuaTest')"); lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.DoString("TestStruct=luanet.import_type('NLuaTest.Mock.TestStruct')"); lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
lua.DoString("struct1=TestStruct(0)"); lua.DoString ("test={}");
lua.DoString("struct2=TestStruct(0)"); lua.DoString ("function test:overridableMethod(x,y) print(self[base]); return 6 end");
lua.DoString("struct2.val=1"); lua.DoString ("luanet.make_object(test,'NLuaTest.Mock.TestClass')");
Assert.AreEqual(0, (double)lua["struct1.val"]); 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] [Test]
public void TestCtype () public void TestCtype ()
{ {
using (Lua lua = new Lua ()) { using (Lua lua = new Lua ()) {
lua.LoadCLRPackage (); lua.LoadCLRPackage ();
lua.DoString ("import'System'"); 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"); Assert.AreEqual (x, typeof(String), "#1 String ctype test");
} }
} }
[Test] [Test]
public void TestPrintChars () public void TestPrintChars ()
{ {
using (Lua lua = new Lua ()) { using (Lua lua = new Lua ()) {
lua.DoString (@"print(""waüäq?=()[&]ß"")"); lua.DoString (@"print(""waüäq?=()[&]ß"")");
Assert.IsTrue (true); Assert.IsTrue (true);
} }
} }
[Test] [Test]
public void TestUnicodeChars () public void TestUnicodeChars ()
{ {
using (Lua lua = new Lua ()) { using (Lua lua = new Lua ()) {
...@@ -1965,9 +1973,9 @@ namespace NLuaTest ...@@ -1965,9 +1973,9 @@ namespace NLuaTest
//Console.WriteLine("a="+num); //Console.WriteLine("a="+num);
Assert.AreEqual (num, 2d); Assert.AreEqual (num, 2d);
} }
} }
[Test] [Test]
public void TestDebugHook () public void TestDebugHook ()
{ {
int [] lines = { 1, 2, 1, 3 }; int [] lines = { 1, 2, 1, 3 };
...@@ -1984,9 +1992,9 @@ namespace NLuaTest ...@@ -1984,9 +1992,9 @@ namespace NLuaTest
val = testing_hooks() val = testing_hooks()
val = val + 1"); val = val + 1");
} }
} }
[Test] [Test]
public void TestKeyWithDots () public void TestKeyWithDots ()
{ {
using (Lua lua = new Lua ()) { using (Lua lua = new Lua ()) {
...@@ -1995,9 +2003,9 @@ namespace NLuaTest ...@@ -1995,9 +2003,9 @@ namespace NLuaTest
Assert.AreEqual (42, (int)(double)lua ["g_dot.key\\.with\\.dot"]); Assert.AreEqual (42, (int)(double)lua ["g_dot.key\\.with\\.dot"]);
} }
} }
#if !WINDOWS_PHONE && !NET_3_5 #if !WINDOWS_PHONE && !NET_3_5
[Test] [Test]
public void TestOperatorAdd () public void TestOperatorAdd ()
{ {
using (Lua lua = new Lua ()) { using (Lua lua = new Lua ()) {
...@@ -2070,8 +2078,8 @@ namespace NLuaTest ...@@ -2070,8 +2078,8 @@ namespace NLuaTest
var res = lua.DoString (@"return a ~= b") [0]; var res = lua.DoString (@"return a ~= b") [0];
Assert.AreEqual (x, res); Assert.AreEqual (x, res);
} }
} }
[Test] [Test]
public void TestUnaryMinus () public void TestUnaryMinus ()
{ {
...@@ -2087,9 +2095,9 @@ namespace NLuaTest ...@@ -2087,9 +2095,9 @@ namespace NLuaTest
var res = lua ["c"]; var res = lua ["c"];
Assert.AreEqual (expected, res); Assert.AreEqual (expected, res);
} }
} }
#endif #endif
[Test] [Test]
public void TestCaseFields () public void TestCaseFields ()
{ {
using (Lua lua = new Lua ()) { using (Lua lua = new Lua ()) {
...@@ -2107,9 +2115,9 @@ namespace NLuaTest ...@@ -2107,9 +2115,9 @@ namespace NLuaTest
Assert.AreEqual ("**name**", lua ["Name"]); Assert.AreEqual ("**name**", lua ["Name"]);
Assert.AreEqual ("name", lua ["Name2"]); Assert.AreEqual ("name", lua ["Name2"]);
} }
} }
[Test] [Test]
public void TestStaticOperators () public void TestStaticOperators ()
{ {
using (Lua lua = new Lua ()) { using (Lua lua = new Lua ()) {
...@@ -2132,9 +2140,9 @@ namespace NLuaTest ...@@ -2132,9 +2140,9 @@ namespace NLuaTest
Assert.AreEqual (40, x.x, "#3"); Assert.AreEqual (40, x.x, "#3");
Assert.AreEqual (12, x.y, "#4"); Assert.AreEqual (12, x.y, "#4");
} }
} }
[Test] [Test]
public void TestExtensionMethods () public void TestExtensionMethods ()
{ {
using (Lua lua = new Lua ()) { using (Lua lua = new Lua ()) {
...@@ -2154,9 +2162,9 @@ namespace NLuaTest ...@@ -2154,9 +2162,9 @@ namespace NLuaTest
double len2 = (double)lua ["len2"]; double len2 = (double)lua ["len2"];
Assert.AreEqual (len, len2, "#1"); Assert.AreEqual (len, len2, "#1");
} }
} }
[Test] [Test]
public void TestOverloadedMethods () public void TestOverloadedMethods ()
{ {
using (Lua lua = new Lua ()) { using (Lua lua = new Lua ()) {
...@@ -2171,10 +2179,10 @@ namespace NLuaTest ...@@ -2171,10 +2179,10 @@ namespace NLuaTest
"); ");
Assert.AreEqual (3, obj.CallsToIntFunc,"#integer"); Assert.AreEqual (3, obj.CallsToIntFunc,"#integer");
Assert.AreEqual (2, obj.CallsToStringFunc, "#string"); Assert.AreEqual (2, obj.CallsToStringFunc, "#string");
} }
} }
[Test] [Test]
public void TestGetStack () public void TestGetStack ()
{ {
using (Lua lua = new Lua ()) { using (Lua lua = new Lua ()) {
...@@ -2198,8 +2206,8 @@ namespace NLuaTest ...@@ -2198,8 +2206,8 @@ namespace NLuaTest
"); ");
} }
m_lua = null; m_lua = null;
} }
public static void func() public static void func()
{ {
#if USE_KOPILUA #if USE_KOPILUA
...@@ -2225,21 +2233,83 @@ namespace NLuaTest ...@@ -2225,21 +2233,83 @@ namespace NLuaTest
} }
string x = sb.ToString (); string x = sb.ToString ();
Assert.True (!string.IsNullOrEmpty(x)); Assert.True (!string.IsNullOrEmpty(x));
} }
[Test] [Test]
public void TestCallImplicitBaseMethod () public void TestCallImplicitBaseMethod ()
{ {
using (var l = new Lua ()) { using (var l = new Lua ()) {
l.LoadCLRPackage (); l.LoadCLRPackage ();
l.DoString ("import ('NLuaTest')"); l.DoString ("import ('NLuaTest')");
l.DoString ("res = testClass.read() "); l.DoString ("res = testClass.read() ");
string res = (string)l ["res"]; string res = (string)l ["res"];
Assert.AreEqual (testClass.read (), res); Assert.AreEqual (testClass.read (), res);
} }
} }
static Lua m_lua; [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