Commit 75df6585 authored by Megax's avatar Megax
Browse files

* Tobb dolog is vissza lett alakitva LuaLIb-ben s gfoot-tol lettek atveve...

* Tobb dolog is vissza lett alakitva LuaLIb-ben s gfoot-tol lettek atveve otletek. Most jol mukodik a LuaInterface a kopiluaval.
parent 05ba53d3
Error:
- TestLua.exe -> TestThreading() ==Problem with threading!==
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">x86</Platform>
<ProductVersion>9.0.30729</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{F97A7B76-AD92-49F9-B733-F347B7C8439F}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>LuaInterface.Test</RootNamespace>
<AssemblyName>LuaInterface.Test</AssemblyName>
<ReleaseVersion>2.x</ReleaseVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>..\..\Run\Debug</OutputPath>
<DefineConstants>DEBUG</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<PlatformTarget>x86</PlatformTarget>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
<DebugType>none</DebugType>
<Optimize>true</Optimize>
<OutputPath>..\..\Run\Release</OutputPath>
<DefineConstants>RELEASE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<PlatformTarget>x86</PlatformTarget>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x64' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>..\..\Run\Debug_x64</OutputPath>
<DefineConstants>DEBUG</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<PlatformTarget>x64</PlatformTarget>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x64' ">
<DebugType>none</DebugType>
<Optimize>true</Optimize>
<OutputPath>..\..\Run\Release_x64</OutputPath>
<DefineConstants>RELEASE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<PlatformTarget>x64</PlatformTarget>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="xunit">
<HintPath>..\..\Dependencies\xunit.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="Mock\Entity.cs" />
<Compile Include="Mock\TestLua.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="LuaTests.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\Core\LuaInterface\LuaInterface.csproj">
<Project>{F55CABBB-4108-4A39-94E1-581FD46DC021}</Project>
<Name>LuaInterface</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<None Include="test.lua">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
<ItemGroup>
<BootstrapperPackage Include=".NETFramework,Version=v4.0">
<Visible>False</Visible>
<ProductName>Microsoft .NET Framework 4 %28x86 and x64%29</ProductName>
<Install>true</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Client.3.5">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>
<Install>false</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1</ProductName>
<Install>false</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Windows.Installer.3.1">
<Visible>False</Visible>
<ProductName>Windows Installer 3.1</ProductName>
<Install>true</Install>
</BootstrapperPackage>
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<PropertyGroup>
<PreBuildEvent>$(SolutionDir)tools\nuget install $(ProjectDir)packages.config -o $(SolutionDir)packages</PreBuildEvent>
</PropertyGroup>
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
\ No newline at end of file
using System;
using System.Linq;
using System.Text;
using System.Threading;
using System.Reflection;
using System.Collections.Generic;
using Xunit;
using LuaInterface.Exceptions;
using LuaInterface.Test.Mock;
namespace LuaInterface.Test
{
public class LuaTests
{
/*
* Tests capturing an exception
*/
[Fact]
public void ThrowException()
{
using (Lua lua = new Lua())
{
lua.DoString("luanet.load_assembly('mscorlib')");
lua.DoString("luanet.load_assembly('LuaInterface.Test')");
lua.DoString("TestClass=luanet.import_type('LuaInterface.Test.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.False(err);
Assert.NotNull(errMsg.InnerException);
Assert.Equal("exception test", errMsg.InnerException.Message);
}
}
/*
* Tests capturing an exception
*/
[Fact]
public void ThrowUncaughtException()
{
using (Lua lua = new Lua())
{
lua.DoString("luanet.load_assembly('mscorlib')");
lua.DoString("luanet.load_assembly('LuaInterface.Test')");
lua.DoString("TestClass=luanet.import_type('LuaInterface.Test.Mock.TestClass')");
lua.DoString("test=TestClass()");
try
{
lua.DoString("test:exceptionMethod()");
//failed
Assert.True(false);
}
catch (Exception/* e*/)
{
//passed
Assert.True(true);
}
}
}
/*
* Tests nullable fields
*/
[Fact]
public void TestNullable()
{
using (Lua lua = new Lua())
{
lua.DoString("luanet.load_assembly('mscorlib')");
lua.DoString("luanet.load_assembly('LuaInterface.Test')");
lua.DoString("TestClass=luanet.import_type('LuaInterface.Test.Mock.TestClass')");
lua.DoString("test=TestClass()");
lua.DoString("val=test.NullableBool");
Assert.Null((object)lua["val"]);
lua.DoString("test.NullableBool = true");
lua.DoString("val=test.NullableBool");
Assert.True((bool)lua["val"]);
}
}
/*
* Tests structure assignment
*/
[Fact]
public void TestStructs()
{
using (Lua lua = new Lua())
{
lua.DoString("luanet.load_assembly('LuaInterface.Test')");
lua.DoString("TestClass=luanet.import_type('LuaInterface.Test.Mock.TestClass')");
lua.DoString("test=TestClass()");
lua.DoString("TestStruct=luanet.import_type('LuaInterface.Test.Mock.TestStruct')");
lua.DoString("struct=TestStruct(2)");
lua.DoString("test.Struct = struct");
lua.DoString("val=test.Struct.val");
Assert.Equal(2.0d, (double)lua["val"]);
}
}
[Fact]
public void TestMethodOverloads()
{
using (Lua lua = new Lua())
{
lua.DoString("luanet.load_assembly('mscorlib')");
lua.DoString("luanet.load_assembly('LuaInterface.Test')");
lua.DoString("TestClass=luanet.import_type('LuaInterface.Test.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)");
}
}
[Fact]
public void TestDispose()
{
System.GC.Collect();
long startingMem = System.Diagnostics.Process.GetCurrentProcess().WorkingSet64;
for (int i = 0; i < 10000; 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");
}
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");
/*Object[] ret = */lf.Call(i, 20);
}
[Fact]
public void TestThreading()
{
using (Lua lua = new Lua())
{
DoWorkClass doWork = new DoWorkClass();
lua.RegisterFunction("dowork", doWork, typeof(DoWorkClass).GetMethod("DoWork"));
bool failureDetected = false;
int completed = 0;
int iterations = 500;
for (int i = 0; i < iterations; i++)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(delegate(object o)
{
try
{
lua.DoString("dowork()");
}
catch
{
failureDetected = true;
}
completed++;
}));
}
while (completed < iterations && !failureDetected)
Thread.Sleep(50);
Assert.False(failureDetected);
}
}
[Fact]
public void TestPrivateMethod()
{
using (Lua lua = new Lua())
{
lua.DoString("luanet.load_assembly('mscorlib')");
lua.DoString("luanet.load_assembly('LuaInterface.Test')");
lua.DoString("TestClass=luanet.import_type('LuaInterface.Test.Mock.TestClass')");
lua.DoString("test=TestClass()");
try
{
lua.DoString("test:_PrivateMethod()");
}
catch
{
Assert.True(true);
return;
}
Assert.True(false);
}
}
/*
* Tests functions
*/
[Fact]
public void TestFunctions()
{
using (Lua lua = new Lua())
{
lua.DoString("luanet.load_assembly('mscorlib')");
lua.DoString("luanet.load_assembly('LuaInterface.Test')");
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.
*/
[Fact]
public void LuaTableOverridedMethod()
{
using (Lua lua = new Lua())
{
lua.DoString("luanet.load_assembly('LuaInterface.Test')");
lua.DoString("TestClass=luanet.import_type('LuaInterface.Test.Mock.TestClass')");
lua.DoString("test={}");
lua.DoString("function test:overridableMethod(x,y) return x*y; end");
lua.DoString("luanet.make_object(test,'LuaInterface.Test.Mock.TestClass')");
lua.DoString("a=TestClass.callOverridable(test,2,3)");
int a = (int)lua.GetNumber("a");
lua.DoString("luanet.free_object(test)");
Assert.Equal(6, a);
}
}
/*
* Tests making an object from a Lua table and calling a method
* the table does not override.
*/
[Fact]
public void LuaTableInheritedMethod()
{
using (Lua lua = new Lua())
{
lua.DoString("luanet.load_assembly('LuaInterface.Test')");
lua.DoString("TestClass=luanet.import_type('LuaInterface.Test.Mock.TestClass')");
lua.DoString("test={}");
lua.DoString("function test:overridableMethod(x,y) return x*y; end");
lua.DoString("luanet.make_object(test,'LuaInterface.Test.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.Equal(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;
}
[Fact]
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);
//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, we)\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.True(false);
}
catch (LuaException/* e*/)
{
//passed
Assert.True(true);
}
}
}
[Fact]
public void TestExceptionWithChunkOverload()
{
using (Lua lua = new Lua())
{
try
{
lua.DoString("thiswillthrowanerror", "MyChunk");
}
catch (Exception e)
{
Assert.True(e.Message.StartsWith("[string \"MyChunk\"]"));
}
}
}
[Fact]
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();
lua.RegisterFunction("genericMethod2", classWithGenericMethod, typeof(TestClassWithGenericMethod).GetMethod("GenericMethod"));
try
{
lua.DoString("genericMethod2(100)");
}
catch { }
Assert.True(classWithGenericMethod.GenericMethodSuccess);
Assert.True(classWithGenericMethod.Validate<double>(100)); //note the gotcha: numbers are all being passed to generic methods as doubles
try
{
lua.DoString("luanet.load_assembly('LuaInterface.Test')");
lua.DoString("TestClass=luanet.import_type('LuaInterface.Test.Mock.TestClass')");
lua.DoString("test=TestClass(56)");
lua.DoString("genericMethod2(test)");
}
catch { }
Assert.True(classWithGenericMethod.GenericMethodSuccess);
Assert.Equal(56, (classWithGenericMethod.PassedValue as TestClass).val);
}
}
[Fact]
public void RegisterFunctionStressTest()
{
const int Count = 200; // it seems to work with 41
using (Lua lua = new Lua())
{
LuaFunction fc = null;
MyClass t = new MyClass();
for (int i = 1; i < Count - 1; ++i)
{
fc = lua.RegisterFunction("func" + i, t, typeof(MyClass).GetMethod("Func1"));
}
fc = lua.RegisterFunction("func" + (Count - 1), t, typeof(MyClass).GetMethod("Func1"));
lua.DoString("print(func1())");
}
}
[Fact]
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.Equal(2, a);
Assert.NotNull(b);
Assert.NotNull(c);
}
}
[Fact]
public void TestLoadStringLeak()
{
//Test to prevent stack overflow
//See: http://code.google.com/p/luainterface/issues/detail?id=5
//number of iterations to test
int count = 10000;
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
}
[Fact]
public void TestLoadFileLeak()
{
//Test to prevent stack overflow
//See: http://code.google.com/p/luainterface/issues/detail?id=5
//number of iterations to test
int count = 10000;
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
}
[Fact]
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.Equal(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.Equal(5.0f, Convert.ToSingle(vals1[0]));
}
}
/*
* Tests if DoString is correctly returning values
*/
[Fact]
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.Equal(res[0], 2d);
Assert.Equal(res[1], 3d);
}
}
/*
* Tests getting of global numeric variables
*/
[Fact]
public void GetGlobalNumber()
{
using (Lua lua = new Lua())
{
lua.DoString("a=2");
double num = lua.GetNumber("a");
//Console.WriteLine("a="+num);
Assert.Equal(num, 2d);
}
}
/*
* Tests setting of global numeric variables
*/
[Fact]
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.Equal(num, 3d);
}
}
/*
* Tests getting of numeric variables from tables
* by specifying variable path
*/
[Fact]
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.Equal(num, 2d);
}
}
/*
* Tests setting of numeric variables from tables
* by specifying variable path
*/
[Fact]
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.Equal(num, 3d);
}
}
/*
* Tests getting of global string variables
*/
[Fact]
public void GetGlobalString()
{
using (Lua lua = new Lua())
{
lua.DoString("a=\"test\"");
string str = lua.GetString("a");
//Console.WriteLine("a="+str);
Assert.Equal(str, "test");
}
}
/*
* Tests setting of global string variables
*/
[Fact]
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.Equal(str, "new test");
}
}
/*
* Tests getting of string variables from tables
* by specifying variable path
*/
[Fact]
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.Equal(str, "test");
}
}
/*
* Tests setting of string variables from tables
* by specifying variable path
*/
[Fact]
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.Equal(str, "new test");
}
}
/*
* Tests getting and setting of global table variables
*/
[Fact]
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.Equal(num, 3d);
}
}
/*
* Tests getting of numeric field of a table
*/
[Fact]
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.Equal(num, 2d);
}
}
/*
* Tests getting of numeric field of a table
* (the field is inside a subtable)
*/
[Fact]
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.Equal(num, 2d);
}
}
/*
* Tests setting of numeric field of a table
*/
[Fact]
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.Equal(num, 3d);
}
}
/*
* Tests setting of numeric field of a table
* (the field is inside a subtable)
*/
[Fact]
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.Equal(num, 3d);
}
}
/*
* Tests getting of string field of a table
*/
[Fact]
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.Equal(str, "test");
}
}
/*
* Tests getting of string field of a table
* (the field is inside a subtable)
*/
[Fact]
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.Equal(str, "test");
}
}
/*
* Tests setting of string field of a table
*/
[Fact]
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.Equal(str, "new test");
}
}
/*
* Tests setting of string field of a table
* (the field is inside a subtable)
*/
[Fact]
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.Equal(str, "new test");
}
}
/*
* Tests calling of a global function with zero arguments
*/
[Fact]
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.Equal(num, 3d);
}
}
/*
* Tests calling of a global function with one argument
*/
[Fact]
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.Equal(num, 3d);
}
}
/*
* Tests calling of a global function with two arguments
*/
[Fact]
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.Equal(num, 4d);
}
}
/*
* Tests calling of a global function that returns one value
*/
[Fact]
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.Equal(1, ret.Length);
Assert.Equal(5, (double)ret[0]);
}
}
/*
* Tests calling of a global function that returns two values
*/
[Fact]
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.Equal(2, ret.Length);
Assert.Equal(3, (double)ret[0]);
Assert.Equal(5, (double)ret[1]);
}
}
/*
* Tests calling of a function inside a table
*/
[Fact]
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.Equal(2, ret.Length);
Assert.Equal(3, (double)ret[0]);
Assert.Equal(5, (double)ret[1]);
}
}
/*
* Tests setting of a global variable to a CLR object value
*/
[Fact]
public void SetGlobalObject()
{
using (Lua lua = new Lua())
{
TestClass t1 = new TestClass();
t1.testval = 4;
lua["netobj"] = t1;
object o = lua["netobj"];
TestClass t2 = (TestClass)lua["netobj"];
Assert.Equal(t2.testval, 4);
Assert.True(t1 == t2);
}
}
///*
// * Tests if CLR object is being correctly collected by Lua
// */
//[Fact]
//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
*/
[Fact]
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.Equal(t2.testval, 4);
Assert.True(t1 == t2);
}
}
/*
* Tests reading and writing of an object's field
*/
[Fact]
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.Equal(4, var);
lua.DoString("netobj.val=3");
Assert.Equal(3, t1.val);
//Console.WriteLine("new val (from Lua)="+t1.val);
}
}
/*
* Tests reading and writing of an object's non-indexed
* property
*/
[Fact]
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.Equal(4, var);
lua.DoString("netobj.testval=3");
Assert.Equal(3, t1.testval);
//Console.WriteLine("new val (from Lua)="+t1.testval);
}
}
/*
* Tests calling of an object's method with no overloads
*/
[Fact]
public void CallObjectMethod()
{
using (Lua lua = new Lua())
{
TestClass t1 = new TestClass();
t1.testval = 4;
lua["netobj"] = t1;
lua.DoString("netobj:setVal(3)");
Assert.Equal(3, t1.testval);
//Console.WriteLine("new val(from C#)="+t1.testval);
lua.DoString("val=netobj:getVal()");
int val = (int)lua.GetNumber("val");
Assert.Equal(3, val);
//Console.WriteLine("new val(from Lua)="+val);
}
}
/*
* Tests calling of an object's method with overloading
*/
[Fact]
public void CallObjectMethodByType()
{
using (Lua lua = new Lua())
{
TestClass t1 = new TestClass();
lua["netobj"] = t1;
lua.DoString("netobj:setVal('str')");
Assert.Equal("str", t1.getStrVal());
//Console.WriteLine("new val(from C#)="+t1.getStrVal());
}
}
/*
* Tests calling of an object's method with no overloading
* and out parameters
*/
[Fact]
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.Equal(3, a);
Assert.Equal(5, b);
//Console.WriteLine("function returned (from lua)="+a+","+b);
}
}
/*
* Tests calling of an object's method with overloading and
* out params
*/
[Fact]
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.Equal(2, a);
Assert.Equal(5, b);
//Console.WriteLine("function returned (from lua)="+a+","+b);
}
}
/*
* Tests calling of an object's method with ref params
*/
[Fact]
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.Equal(2, a);
Assert.Equal(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
*/
[Fact]
public void CallObjectMethodDistinctInterfaces()
{
using (Lua lua = new Lua())
{
TestClass t1 = new TestClass();
lua["netobj"] = t1;
lua.DoString("a=netobj:foo()");
lua.DoString("b=netobj['LuaInterface.Test.Mock.IFoo1.foo'](netobj)");
int a = (int)lua.GetNumber("a");
int b = (int)lua.GetNumber("b");
Assert.Equal(5, a);
Assert.Equal(3, b);
//Console.WriteLine("function returned (from lua)="+a+","+b);
}
}
/*
* Tests instantiating an object with no-argument constructor
*/
[Fact]
public void CreateNetObjectNoArgsCons()
{
using (Lua lua = new Lua())
{
lua.DoString("luanet.load_assembly(\"LuaInterface.Test\")");
lua.DoString("TestClass=luanet.import_type(\"LuaInterface.Test.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.Equal(3, test.testval);
}
}
/*
* Tests instantiating an object with one-argument constructor
*/
[Fact]
public void CreateNetObjectOneArgCons()
{
using (Lua lua = new Lua())
{
lua.DoString("luanet.load_assembly(\"LuaInterface.Test\")");
lua.DoString("TestClass=luanet.import_type(\"LuaInterface.Test.Mock.TestClass\")");
lua.DoString("test=TestClass(3)");
object[] res = lua.DoString("return test");
TestClass test = (TestClass)res[0];
//Console.WriteLine("returned: "+test.testval);
Assert.Equal(3, test.testval);
}
}
/*
* Tests instantiating an object with overloaded constructor
*/
[Fact]
public void CreateNetObjectOverloadedCons()
{
using (Lua lua = new Lua())
{
lua.DoString("luanet.load_assembly(\"LuaInterface.Test\")");
lua.DoString("TestClass=luanet.import_type(\"LuaInterface.Test.Mock.TestClass\")");
lua.DoString("test=TestClass('str')");
object[] res = lua.DoString("return test");
TestClass test = (TestClass)res[0];
//Console.WriteLine("returned: "+test.getStrVal());
Assert.Equal("str", test.getStrVal());
}
}
/*
* Tests getting item of a CLR array
*/
[Fact]
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.Equal("str2", val);
//Console.WriteLine("new val(from array to Lua)="+val);
}
}
/*
* Tests setting item of a CLR array
*/
[Fact]
public void WriteArrayField()
{
using (Lua lua = new Lua())
{
string[] arr = new string[] { "str1", "str2", "str3" };
lua["netobj"] = arr;
lua.DoString("netobj[1]='test'");
Assert.Equal("test", arr[1]);
//Console.WriteLine("new val(from Lua to array)="+arr[1]);
}
}
/*
* Tests creating a new CLR array
*/
[Fact]
public void CreateArray()
{
using (Lua lua = new Lua())
{
lua.DoString("luanet.load_assembly(\"LuaInterface.Test\")");
lua.DoString("TestClass=luanet.import_type(\"LuaInterface.Test.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.Equal(arr[1].testval, 2);
}
}
/*
* Tests passing a Lua function to a delegate
* with value-type arguments
*/
[Fact]
public void LuaDelegateValueTypes()
{
using (Lua lua = new Lua())
{
lua.DoString("luanet.load_assembly('LuaInterface.Test')");
lua.DoString("TestClass=luanet.import_type('LuaInterface.Test.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.Equal(5, a);
//Console.WriteLine("delegate returned: "+a);
}
}
/*
* Tests passing a Lua function to a delegate
* with value-type arguments and out params
*/
[Fact]
public void LuaDelegateValueTypesOutParam()
{
using (Lua lua = new Lua())
{
lua.DoString("luanet.load_assembly('LuaInterface.Test')");
lua.DoString("TestClass=luanet.import_type('LuaInterface.Test.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.Equal(6, a);
//Console.WriteLine("delegate returned: "+a);
}
}
/*
* Tests passing a Lua function to a delegate
* with value-type arguments and ref params
*/
[Fact]
public void LuaDelegateValueTypesByRefParam()
{
using (Lua lua = new Lua())
{
lua.DoString("luanet.load_assembly('LuaInterface.Test')");
lua.DoString("TestClass=luanet.import_type('LuaInterface.Test.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.Equal(5, a);
//Console.WriteLine("delegate returned: "+a);
}
}
/*
* Tests passing a Lua function to a delegate
* with value-type arguments that returns a reference type
*/
[Fact]
public void LuaDelegateValueTypesReturnReferenceType()
{
using (Lua lua = new Lua())
{
lua.DoString("luanet.load_assembly('LuaInterface.Test')");
lua.DoString("TestClass=luanet.import_type('LuaInterface.Test.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.Equal(5, a);
//Console.WriteLine("delegate returned: "+a);
}
}
/*
* Tests passing a Lua function to a delegate
* with reference type arguments
*/
[Fact]
public void LuaDelegateReferenceTypes()
{
using (Lua lua = new Lua())
{
lua.DoString("luanet.load_assembly('LuaInterface.Test')");
lua.DoString("TestClass=luanet.import_type('LuaInterface.Test.Mock.TestClass')");
lua.DoString("test=TestClass()");
lua.DoString("function func(x,y) return x.testval+y.testval; end");
lua.DoString("test=TestClass()");
lua.DoString("a=test:callDelegate5(func)");
int a = (int)lua.GetNumber("a");
Assert.Equal(5, a);
//Console.WriteLine("delegate returned: "+a);
}
}
/*
* Tests passing a Lua function to a delegate
* with reference type arguments and an out param
*/
[Fact]
public void LuaDelegateReferenceTypesOutParam()
{
using (Lua lua = new Lua())
{
lua.DoString("luanet.load_assembly('LuaInterface.Test')");
lua.DoString("TestClass=luanet.import_type('LuaInterface.Test.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.Equal(6, a);
//Console.WriteLine("delegate returned: "+a);
}
}
/*
* Tests passing a Lua function to a delegate
* with reference type arguments and a ref param
*/
[Fact]
public void LuaDelegateReferenceTypesByRefParam()
{
using (Lua lua = new Lua())
{
lua.DoString("luanet.load_assembly('LuaInterface.Test')");
lua.DoString("TestClass=luanet.import_type('LuaInterface.Test.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.Equal(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
*/
[Fact]
public void LuaInterfaceValueTypes()
{
using (Lua lua = new Lua())
{
lua.DoString("luanet.load_assembly('LuaInterface.Test')");
lua.DoString("TestClass=luanet.import_type('LuaInterface.Test.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.Equal(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
*/
[Fact]
public void LuaInterfaceValueTypesOutParam()
{
using (Lua lua = new Lua())
{
lua.DoString("luanet.load_assembly('LuaInterface.Test')");
lua.DoString("TestClass=luanet.import_type('LuaInterface.Test.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.Equal(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
*/
[Fact]
public void LuaInterfaceValueTypesByRefParam()
{
using (Lua lua = new Lua())
{
lua.DoString("luanet.load_assembly('LuaInterface.Test')");
lua.DoString("TestClass=luanet.import_type('LuaInterface.Test.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.Equal(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
*/
[Fact]
public void LuaInterfaceValueTypesReturnReferenceType()
{
using (Lua lua = new Lua())
{
lua.DoString("luanet.load_assembly('LuaInterface.Test')");
lua.DoString("TestClass=luanet.import_type('LuaInterface.Test.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.Equal(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
*/
[Fact]
public void LuaInterfaceReferenceTypes()
{
using (Lua lua = new Lua())
{
lua.DoString("luanet.load_assembly('LuaInterface.Test')");
lua.DoString("TestClass=luanet.import_type('LuaInterface.Test.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.Equal(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
*/
[Fact]
public void LuaInterfaceReferenceTypesOutParam()
{
using (Lua lua = new Lua())
{
lua.DoString("luanet.load_assembly('LuaInterface.Test')");
lua.DoString("TestClass=luanet.import_type('LuaInterface.Test.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.Equal(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
*/
[Fact]
public void LuaInterfaceReferenceTypesByRefParam()
{
using (Lua lua = new Lua())
{
lua.DoString("luanet.load_assembly('LuaInterface.Test')");
lua.DoString("TestClass=luanet.import_type('LuaInterface.Test.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.Equal(5, a);
//Console.WriteLine("interface returned: "+a);
}
}
/*
* Tests passing a Lua table as an interface and
* accessing one of its value-type properties
*/
[Fact]
public void LuaInterfaceValueProperty()
{
using (Lua lua = new Lua())
{
lua.DoString("luanet.load_assembly('LuaInterface.Test')");
lua.DoString("TestClass=luanet.import_type('LuaInterface.Test.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.Equal(3, a);
//Console.WriteLine("interface returned: "+a);
}
}
/*
* Tests passing a Lua table as an interface and
* accessing one of its reference type properties
*/
[Fact]
public void LuaInterfaceReferenceProperty()
{
using (Lua lua = new Lua())
{
lua.DoString("luanet.load_assembly('LuaInterface.Test')");
lua.DoString("TestClass=luanet.import_type('LuaInterface.Test.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.Equal(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.
*/
[Fact]
public void LuaTableBaseMethod()
{
using (Lua lua = new Lua())
{
lua.DoString("luanet.load_assembly('LuaInterface.Test')");
lua.DoString("TestClass=luanet.import_type('LuaInterface.Test.Mock.TestClass')");
lua.DoString("test={}");
lua.DoString("function test:overridableMethod(x,y) return 2*self.base:overridableMethod(x,y); end");
lua.DoString("luanet.make_object(test,'LuaInterface.Test.Mock.TestClass')");
lua.DoString("a=TestClass:callOverridable(test,2,3)");
int a = (int)lua.GetNumber("a");
lua.DoString("luanet.free_object(test)");
Assert.Equal(10, a);
//Console.WriteLine("interface returned: "+a);
}
}
/*
* Tests getting an object's method by its signature
* (from object)
*/
[Fact]
public void GetMethodBySignatureFromObj()
{
using (Lua lua = new Lua())
{
lua.DoString("luanet.load_assembly('mscorlib')");
lua.DoString("luanet.load_assembly('LuaInterface.Test')");
lua.DoString("TestClass=luanet.import_type('LuaInterface.Test.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.Equal("test", test.getStrVal());
//Console.WriteLine("interface returned: "+test.getStrVal());
}
}
/*
* Tests getting an object's method by its signature
* (from type)
*/
[Fact]
public void GetMethodBySignatureFromType()
{
using (Lua lua = new Lua())
{
lua.DoString("luanet.load_assembly('mscorlib')");
lua.DoString("luanet.load_assembly('LuaInterface.Test')");
lua.DoString("TestClass=luanet.import_type('LuaInterface.Test.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.Equal("test", test.getStrVal());
//Console.WriteLine("interface returned: "+test.getStrVal());
}
}
/*
* Tests getting a type's method by its signature
*/
[Fact]
public void GetStaticMethodBySignature()
{
using (Lua lua = new Lua())
{
lua.DoString("luanet.load_assembly('mscorlib')");
lua.DoString("luanet.load_assembly('LuaInterface.Test')");
lua.DoString("TestClass=luanet.import_type('LuaInterface.Test.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.Equal("test", test.getStrVal());
//Console.WriteLine("interface returned: "+test.getStrVal());
}
}
/*
* Tests getting an object's constructor by its signature
*/
[Fact]
public void GetConstructorBySignature()
{
using (Lua lua = new Lua())
{
lua.DoString("luanet.load_assembly('mscorlib')");
lua.DoString("luanet.load_assembly('LuaInterface.Test')");
lua.DoString("TestClass=luanet.import_type('LuaInterface.Test.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.Equal("test", test.getStrVal());
//Console.WriteLine("interface returned: "+test.getStrVal());
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LuaInterface.Test.Mock
{
public class Entity
{
public event EventHandler<EventArgs> Clicked;
protected virtual void OnEntityClicked(EventArgs e)
{
EventHandler<EventArgs> handler = Clicked;
if (handler != null)
{
// Use the () operator to raise the event.
handler(this, e);
}
}
public Entity()
{
}
public void Click()
{
OnEntityClicked(new EventArgs());
}
}
}
//note: this should be cleaned up and replaced with moq mocks where possible
namespace LuaInterface.Test.Mock
{
using System;
using LuaInterface;
using System.Threading;
using System.Diagnostics;
using System.Reflection;
/*
* Delegates used for testing Lua function -> delegate translation
*/
public delegate int TestDelegate1(int a, int b);
public delegate int TestDelegate2(int a, out int b);
public delegate void TestDelegate3(int a, ref int b);
public delegate TestClass TestDelegate4(int a, int b);
public delegate int TestDelegate5(TestClass a, TestClass b);
public delegate int TestDelegate6(int a, out TestClass b);
public delegate void TestDelegate7(int a, ref TestClass b);
/*
* Interface used for testing Lua table -> interface translation
*/
public interface ITest
{
int intProp
{
get;
set;
}
TestClass refProp
{
get;
set;
}
int test1(int a, int b);
int test2(int a, out int b);
void test3(int a, ref int b);
TestClass test4(int a, int b);
int test5(TestClass a, TestClass b);
int test6(int a, out TestClass b);
void test7(int a, ref TestClass b);
}
public interface IFoo1
{
int foo();
}
public interface IFoo2
{
int foo();
}
class MyClass
{
public int Func1() { return 1; }
}
/// <summary>
/// Use to test threading
/// </summary>
class DoWorkClass
{
//private object _Lock = new object();
public void DoWork()
{
//lock (_Lock)
//{
//simulate work by sleeping
//Console.WriteLine("Started to do work on thread: " + Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(new Random().Next(0, 1000));
//Console.WriteLine("Finished work on thread: " + Thread.CurrentThread.ManagedThreadId);
//}
}
}
/// <summary>
/// test structure passing
/// </summary>
public struct TestStruct
{
public TestStruct(float val)
{
v = val;
}
public float v;
public float val
{
get { return v; }
set { v = value; }
}
}
/// <summary>
/// Generic class with generic and non-generic methods
/// </summary>
/// <typeparam name="T"></typeparam>
public class TestClassGeneric<T>
{
private object _PassedValue;
private bool _RegularMethodSuccess;
public bool RegularMethodSuccess
{
get { return _RegularMethodSuccess; }
}
private bool _GenericMethodSuccess;
public bool GenericMethodSuccess
{
get { return _GenericMethodSuccess; }
}
public void GenericMethod(T value)
{
_PassedValue = value;
_GenericMethodSuccess = true;
}
public void RegularMethod()
{
_RegularMethodSuccess = true;
}
/// <summary>
/// Returns true if the generic method was successfully passed a matching value
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public bool Validate(T value)
{
return value.Equals(_PassedValue);
}
}
/// <summary>
/// Normal class containing a generic method
/// </summary>
public class TestClassWithGenericMethod
{
private object _PassedValue;
public object PassedValue
{
get { return _PassedValue; }
}
private bool _GenericMethodSuccess;
public bool GenericMethodSuccess
{
get { return _GenericMethodSuccess; }
}
public void GenericMethod<T>(T value)
{
_PassedValue = value;
_GenericMethodSuccess = true;
}
internal bool Validate<T>(T value)
{
return value.Equals(_PassedValue);
}
}
public class TestClass2
{
public static int func(int x, int y)
{
return x + y;
}
public int funcInstance(int x, int y)
{
return x + y;
}
}
/*
* Sample class used in several test cases to check if
* Lua scripts are accessing objects correctly
*/
public class TestClass : IFoo1, IFoo2
{
public int val;
private string strVal;
public TestClass()
{
val = 0;
}
public TestClass(int val)
{
this.val = val;
}
public TestClass(string val)
{
this.strVal = val;
}
public static TestClass makeFromString(String str)
{
return new TestClass(str);
}
bool? nb2 = null;
public bool? NullableBool
{
get { return nb2; }
set { nb2 = value; }
}
TestStruct s = new TestStruct();
public TestStruct Struct
{
get { return s; }
set { s = (TestStruct)value; }
}
public int testval
{
get
{
return this.val;
}
set
{
this.val = value;
}
}
public int this[int index]
{
get { return 1; }
set { }
}
public int this[string index]
{
get { return 1; }
set { }
}
public int sum(int x, int y)
{
return x + y;
}
public void setVal(int newVal)
{
val = newVal;
}
public void setVal(string newVal)
{
strVal = newVal;
}
public int getVal()
{
return val;
}
public string getStrVal()
{
return strVal;
}
public int outVal(out int val)
{
val = 5;
return 3;
}
public int outVal(out int val, int val2)
{
val = 5;
return val2;
}
public int outVal(int val, ref int val2)
{
val2 = val + val2;
return val;
}
public int outValMutiple(int arg, out string arg2, out string arg3)
{
arg2 = Guid.NewGuid().ToString();
arg3 = Guid.NewGuid().ToString();
return arg;
}
public int callDelegate1(TestDelegate1 del)
{
return del(2, 3);
}
public int callDelegate2(TestDelegate2 del)
{
int a = 3;
int b = del(2, out a);
return a + b;
}
public int callDelegate3(TestDelegate3 del)
{
int a = 3;
del(2, ref a);
//Console.WriteLine(a);
return a;
}
public int callDelegate4(TestDelegate4 del)
{
return del(2, 3).testval;
}
public int callDelegate5(TestDelegate5 del)
{
return del(new TestClass(2), new TestClass(3));
}
public int callDelegate6(TestDelegate6 del)
{
TestClass test = new TestClass();
int a = del(2, out test);
return a + test.testval;
}
public int callDelegate7(TestDelegate7 del)
{
TestClass test = new TestClass(3);
del(2, ref test);
return test.testval;
}
public int callInterface1(ITest itest)
{
return itest.test1(2, 3);
}
public int callInterface2(ITest itest)
{
int a = 3;
int b = itest.test2(2, out a);
return a + b;
}
public int callInterface3(ITest itest)
{
int a = 3;
itest.test3(2, ref a);
//Console.WriteLine(a);
return a;
}
public int callInterface4(ITest itest)
{
return itest.test4(2, 3).testval;
}
public int callInterface5(ITest itest)
{
return itest.test5(new TestClass(2), new TestClass(3));
}
public int callInterface6(ITest itest)
{
TestClass test = new TestClass();
int a = itest.test6(2, out test);
return a + test.testval;
}
public int callInterface7(ITest itest)
{
TestClass test = new TestClass(3);
itest.test7(2, ref test);
return test.testval;
}
public int callInterface8(ITest itest)
{
itest.intProp = 3;
return itest.intProp;
}
public int callInterface9(ITest itest)
{
itest.refProp = new TestClass(3);
return itest.refProp.testval;
}
public void exceptionMethod()
{
throw new Exception("exception test");
}
public virtual int overridableMethod(int x, int y)
{
return x + y;
}
public static int callOverridable(TestClass test, int x, int y)
{
return test.overridableMethod(x, y);
}
int IFoo1.foo()
{
return 3;
}
public int foo()
{
return 5;
}
private void _PrivateMethod()
{
Console.WriteLine("Private method called");
}
public void MethodOverload()
{
Console.WriteLine("Method with no params");
}
public void MethodOverload(TestClass testClass)
{
Console.WriteLine("Method with testclass param");
}
public void MethodOverload(int i, int j, int k)
{
Console.WriteLine("Overload without out param: " + i + ", " + j + ", " + k);
}
public void MethodOverload(int i, int j, out int k)
{
k = 5;
Console.WriteLine("Overload with out param" + i + ", " + j);
}
}
}
\ No newline at end of file
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("LuaInterface.Test")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("LuaInterface.Test")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2009")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM componenets. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("9a3029b1-b0a5-40fc-8b04-a4f471f69afc")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
width=100
height=200
message="Hello World!"
color={r=100,g=20,b=50}
tree={branch1={leaf1=10,leaf2="leaf2"},leaf3="leaf3"}
function func(x,y)
return x,x+y
end
\ No newline at end of file
/*
* This file is part of LuaInterface.
*
* Copyright (C) 2003-2005 Fabio Mascarenhas de Queiroz.
* Copyright (C) 2012 Megax <http://megax.yeahunter.hu/>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System; using System;
using System.Collections.Generic;
using System.Text; using System.Text;
using System.Collections.Generic;
namespace LuaInterface.Tests namespace LuaInterface.Tests
{ {
public class Entity public class Entity
{ {
public event EventHandler<EventArgs> Clicked; public event EventHandler<EventArgs> Clicked;
protected virtual void OnEntityClicked(EventArgs e)
{
EventHandler<EventArgs> handler = Clicked;
if (handler != null) protected virtual void OnEntityClicked(EventArgs e)
{ {
// Use the () operator to raise the event. var handler = Clicked;
handler(this, e);
}
}
public Entity() if(handler != null)
{ handler(this, e); // Use the () operator to raise the event.
}
} public Entity()
{
}
public void Click() public void Click()
{ {
OnEntityClicked(new EventArgs()); OnEntityClicked(new EventArgs());
} }
} }
} }
\ No newline at end of file
/*
* This file is part of LuaInterface.
*
* Copyright (C) 2003-2005 Fabio Mascarenhas de Queiroz.
* Copyright (C) 2012 Megax <http://megax.yeahunter.hu/>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Reflection; using System.Reflection;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using LuaInterface.Config;
// // Information about this assembly is defined by the following attributes.
// General Information about an assembly is controlled through the following // Change them to the values specific to your project.
// set of attributes. Change these attribute values to modify the information
// associated with an assembly. [assembly: AssemblyTitle("TestLuaInterface")]
// [assembly: AssemblyDescription(Consts.LuaInterfaceDescription)]
[assembly: AssemblyTitle("")] [assembly: AssemblyConfiguration(Consts.LuaInterfaceConfiguration)]
[assembly: AssemblyDescription("")] [assembly: AssemblyCompany(Consts.LuaInterfaceCompany)]
[assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct(Consts.LuaInterfaceProduct)]
[assembly: AssemblyCompany("")] [assembly: AssemblyCopyright(Consts.LuaInterfaceCopyright)]
[assembly: AssemblyProduct("")] [assembly: AssemblyTrademark(Consts.LuaInterfaceTrademark)]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")] // Setting ComVisible to false makes the types in this assembly not visible
[assembly: AssemblyCulture("")] // to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//
// Version information for an assembly consists of the following four values: // Version information for an assembly consists of the following four values:
// //
// Major Version // Major Version
...@@ -23,38 +52,8 @@ using System.Runtime.CompilerServices; ...@@ -23,38 +52,8 @@ using System.Runtime.CompilerServices;
// Build Number // Build Number
// Revision // Revision
// //
// You can specify all the values or you can default the Revision and Build Numbers // You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below: // by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion(Consts.LuaInterfaceVersion)]
[assembly: AssemblyFileVersion(Consts.LuaInterfaceFileVersion)]
// \ No newline at end of file
// In order to sign your assembly you must specify a key to use. Refer to the
// Microsoft .NET Framework documentation for more information on assembly signing.
//
// Use the attributes below to control which key is used for signing.
//
// Notes:
// (*) If no key is specified, the assembly is not signed.
// (*) KeyName refers to a key that has been installed in the Crypto Service
// Provider (CSP) on your machine. KeyFile refers to a file which contains
// a key.
// (*) If the KeyFile and the KeyName values are both specified, the
// following processing occurs:
// (1) If the KeyName can be found in the CSP, that key is used.
// (2) If the KeyName does not exist and the KeyFile does exist, the key
// in the KeyFile is installed into the CSP and used.
// (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility.
// When specifying the KeyFile, the location of the KeyFile should be
// relative to the project output directory which is
// %Project Directory%\obj\<configuration>. For example, if your KeyFile is
// located in the project directory, you would specify the AssemblyKeyFile
// attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")]
// (*) Delay Signing is an advanced option - see the Microsoft .NET Framework
// documentation for more information on this.
//
[assembly: AssemblyDelaySign(false)]
[assembly: AssemblyKeyFile("")]
[assembly: AssemblyKeyName("")]
/*
* This file is part of LuaInterface.
*
* Copyright (C) 2003-2005 Fabio Mascarenhas de Queiroz.
* Copyright (C) 2012 Megax <http://megax.yeahunter.hu/>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Threading;
using System.Reflection;
using System.Diagnostics;
using LuaInterface;
namespace LuaInterface.Tests namespace LuaInterface.Tests
{ {
using System;
using LuaInterface;
using System.Threading;
using System.Diagnostics;
using System.Reflection;
/* /*
* Delegates used for testing Lua function -> delegate translation * Delegates used for testing Lua function -> delegate translation
*/ */
...@@ -52,352 +76,352 @@ namespace LuaInterface.Tests ...@@ -52,352 +76,352 @@ namespace LuaInterface.Tests
int foo(); int foo();
} }
class MyClass class MyClass
{ {
public int Func1() { return 1;} public int Func1() { return 1;}
} }
/// <summary> /// <summary>
/// Use to test threading /// Use to test threading
/// </summary> /// </summary>
class DoWorkClass class DoWorkClass
{ {
//private object _Lock = new object(); //private object _Lock = new object();
public void DoWork() public void DoWork()
{ {
//lock (_Lock) //lock (_Lock)
//{ //{
//simulate work by sleeping //simulate work by sleeping
//Console.WriteLine("Started to do work on thread: " + Thread.CurrentThread.ManagedThreadId); //Console.WriteLine("Started to do work on thread: " + Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(new Random().Next(0, 1000)); Thread.Sleep(new Random().Next(0, 1000));
//Console.WriteLine("Finished work on thread: " + Thread.CurrentThread.ManagedThreadId); //Console.WriteLine("Finished work on thread: " + Thread.CurrentThread.ManagedThreadId);
//} //}
} }
} }
/// <summary> /// <summary>
/// test structure passing /// test structure passing
/// </summary> /// </summary>
public struct TestStruct public struct TestStruct
{ {
public TestStruct(float val) public TestStruct(float val)
{ {
v = val; v = val;
} }
public float v; public float v;
public float val public float val
{ {
get { return v; } get { return v; }
set { v = value; } set { v = value; }
} }
} }
/// <summary> /// <summary>
/// Generic class with generic and non-generic methods /// Generic class with generic and non-generic methods
/// </summary> /// </summary>
/// <typeparam name="T"></typeparam> /// <typeparam name="T"></typeparam>
public class TestClassGeneric<T> public class TestClassGeneric<T>
{ {
private object _PassedValue; private object _PassedValue;
private bool _RegularMethodSuccess; private bool _RegularMethodSuccess;
public bool RegularMethodSuccess public bool RegularMethodSuccess
{ {
get { return _RegularMethodSuccess; } get { return _RegularMethodSuccess; }
} }
private bool _GenericMethodSuccess; private bool _GenericMethodSuccess;
public bool GenericMethodSuccess public bool GenericMethodSuccess
{ {
get { return _GenericMethodSuccess; } get { return _GenericMethodSuccess; }
} }
public void GenericMethod(T value) public void GenericMethod(T value)
{ {
_PassedValue = value; _PassedValue = value;
_GenericMethodSuccess = true; _GenericMethodSuccess = true;
} }
public void RegularMethod() public void RegularMethod()
{ {
_RegularMethodSuccess = true; _RegularMethodSuccess = true;
} }
/// <summary> /// <summary>
/// Returns true if the generic method was successfully passed a matching value /// Returns true if the generic method was successfully passed a matching value
/// </summary> /// </summary>
/// <param name="value"></param> /// <param name="value"></param>
/// <returns></returns> /// <returns></returns>
public bool Validate(T value) public bool Validate(T value)
{ {
return value.Equals(_PassedValue); return value.Equals(_PassedValue);
} }
} }
/// <summary> /// <summary>
/// Normal class containing a generic method /// Normal class containing a generic method
/// </summary> /// </summary>
public class TestClassWithGenericMethod public class TestClassWithGenericMethod
{ {
private object _PassedValue; private object _PassedValue;
public object PassedValue public object PassedValue
{ {
get { return _PassedValue; } get { return _PassedValue; }
} }
private bool _GenericMethodSuccess; private bool _GenericMethodSuccess;
public bool GenericMethodSuccess public bool GenericMethodSuccess
{ {
get { return _GenericMethodSuccess; } get { return _GenericMethodSuccess; }
} }
public void GenericMethod<T>(T value) public void GenericMethod<T>(T value)
{ {
_PassedValue = value; _PassedValue = value;
_GenericMethodSuccess = true; _GenericMethodSuccess = true;
} }
internal bool Validate<T>(T value) internal bool Validate<T>(T value)
{ {
return value.Equals(_PassedValue); return value.Equals(_PassedValue);
} }
} }
/* /*
* Sample class used in several test cases to check if * Sample class used in several test cases to check if
* Lua scripts are accessing objects correctly * Lua scripts are accessing objects correctly
*/ */
public class TestClass : IFoo1, IFoo2 public class TestClass : IFoo1, IFoo2
{ {
public int val; public int val;
private string strVal; private string strVal;
public TestClass() public TestClass()
{ {
val = 0; val = 0;
} }
public TestClass(int val) public TestClass(int val)
{ {
this.val = val; this.val = val;
} }
public TestClass(string val) public TestClass(string val)
{ {
this.strVal = val; this.strVal = val;
} }
public static TestClass makeFromString(String str) public static TestClass makeFromString(String str)
{ {
return new TestClass(str); return new TestClass(str);
} }
bool? nb2 = null; bool? nb2 = null;
public bool? NullableBool public bool? NullableBool
{ {
get { return nb2; } get { return nb2; }
set { nb2 = value; } set { nb2 = value; }
} }
TestStruct s = new TestStruct(); TestStruct s = new TestStruct();
public TestStruct Struct public TestStruct Struct
{ {
get { return s; } get { return s; }
set { s = (TestStruct)value; } set { s = (TestStruct)value; }
} }
public int testval public int testval
{ {
get get
{ {
return this.val; return this.val;
} }
set set
{ {
this.val = value; this.val = value;
} }
} }
public int this[int index] public int this[int index]
{ {
get { return 1; } get { return 1; }
set { } set { }
} }
public int this[string index] public int this[string index]
{ {
get { return 1; } get { return 1; }
set { } set { }
} }
public int sum(int x, int y) public int sum(int x, int y)
{ {
return x + y; return x + y;
} }
public void setVal(int newVal) public void setVal(int newVal)
{ {
val = newVal; val = newVal;
} }
public void setVal(string newVal) public void setVal(string newVal)
{ {
strVal = newVal; strVal = newVal;
} }
public int getVal() public int getVal()
{ {
return val; return val;
} }
public string getStrVal() public string getStrVal()
{ {
return strVal; return strVal;
} }
public int outVal(out int val) public int outVal(out int val)
{ {
val = 5; val = 5;
return 3; return 3;
} }
public int outVal(out int val, int val2) public int outVal(out int val, int val2)
{ {
val = 5; val = 5;
return val2; return val2;
} }
public int outVal(int val, ref int val2) public int outVal(int val, ref int val2)
{ {
val2 = val + val2; val2 = val + val2;
return val; return val;
} }
public int callDelegate1(TestDelegate1 del) public int callDelegate1(TestDelegate1 del)
{ {
return del(2, 3); return del(2, 3);
} }
public int callDelegate2(TestDelegate2 del) public int callDelegate2(TestDelegate2 del)
{ {
int a = 3; int a = 3;
int b = del(2, out a); int b = del(2, out a);
return a + b; return a + b;
} }
public int callDelegate3(TestDelegate3 del) public int callDelegate3(TestDelegate3 del)
{ {
int a = 3; int a = 3;
del(2, ref a); del(2, ref a);
//Console.WriteLine(a); //Console.WriteLine(a);
return a; return a;
} }
public int callDelegate4(TestDelegate4 del) public int callDelegate4(TestDelegate4 del)
{ {
return del(2, 3).testval; return del(2, 3).testval;
} }
public int callDelegate5(TestDelegate5 del) public int callDelegate5(TestDelegate5 del)
{ {
return del(new TestClass(2), new TestClass(3)); return del(new TestClass(2), new TestClass(3));
} }
public int callDelegate6(TestDelegate6 del) public int callDelegate6(TestDelegate6 del)
{ {
TestClass test = new TestClass(); TestClass test = new TestClass();
int a = del(2, out test); int a = del(2, out test);
return a + test.testval; return a + test.testval;
} }
public int callDelegate7(TestDelegate7 del) public int callDelegate7(TestDelegate7 del)
{ {
TestClass test = new TestClass(3); TestClass test = new TestClass(3);
del(2, ref test); del(2, ref test);
return test.testval; return test.testval;
} }
public int callInterface1(ITest itest) public int callInterface1(ITest itest)
{ {
return itest.test1(2, 3); return itest.test1(2, 3);
} }
public int callInterface2(ITest itest) public int callInterface2(ITest itest)
{ {
int a = 3; int a = 3;
int b = itest.test2(2, out a); int b = itest.test2(2, out a);
return a + b; return a + b;
} }
public int callInterface3(ITest itest) public int callInterface3(ITest itest)
{ {
int a = 3; int a = 3;
itest.test3(2, ref a); itest.test3(2, ref a);
//Console.WriteLine(a); //Console.WriteLine(a);
return a; return a;
} }
public int callInterface4(ITest itest) public int callInterface4(ITest itest)
{ {
return itest.test4(2, 3).testval; return itest.test4(2, 3).testval;
} }
public int callInterface5(ITest itest) public int callInterface5(ITest itest)
{ {
return itest.test5(new TestClass(2), new TestClass(3)); return itest.test5(new TestClass(2), new TestClass(3));
} }
public int callInterface6(ITest itest) public int callInterface6(ITest itest)
{ {
TestClass test = new TestClass(); TestClass test = new TestClass();
int a = itest.test6(2, out test); int a = itest.test6(2, out test);
return a + test.testval; return a + test.testval;
} }
public int callInterface7(ITest itest) public int callInterface7(ITest itest)
{ {
TestClass test = new TestClass(3); TestClass test = new TestClass(3);
itest.test7(2, ref test); itest.test7(2, ref test);
return test.testval; return test.testval;
} }
public int callInterface8(ITest itest) public int callInterface8(ITest itest)
{ {
itest.intProp = 3; itest.intProp = 3;
return itest.intProp; return itest.intProp;
} }
public int callInterface9(ITest itest) public int callInterface9(ITest itest)
{ {
itest.refProp = new TestClass(3); itest.refProp = new TestClass(3);
return itest.refProp.testval; return itest.refProp.testval;
} }
public void exceptionMethod() public void exceptionMethod()
{ {
throw new Exception("exception test"); throw new Exception("exception test");
} }
public virtual int overridableMethod(int x, int y) public virtual int overridableMethod(int x, int y)
{ {
return x + y; return x + y;
} }
public static int callOverridable(TestClass test, int x, int y) public static int callOverridable(TestClass test, int x, int y)
{ {
return test.overridableMethod(x, y); return test.overridableMethod(x, y);
} }
int IFoo1.foo() int IFoo1.foo()
{ {
return 3; return 3;
} }
public int foo() public int foo()
{ {
return 5; return 5;
} }
private void _PrivateMethod() private void _PrivateMethod()
{ {
Console.WriteLine("Private method called"); Console.WriteLine("Private method called");
} }
public void MethodOverload() public void MethodOverload()
{ {
Console.WriteLine("Method with no params"); Console.WriteLine("Method with no params");
} }
public void MethodOverload(TestClass testClass) public void MethodOverload(TestClass testClass)
{ {
Console.WriteLine("Method with testclass param"); Console.WriteLine("Method with testclass param");
} }
public void MethodOverload(int i, int j, int k) public void MethodOverload(int i, int j, int k)
{ {
Console.WriteLine("Overload without out param: " + i + ", " + j + ", " + k); Console.WriteLine("Overload without out param: " + i + ", " + j + ", " + k);
} }
public void MethodOverload(int i, int j, out int k) public void MethodOverload(int i, int j, out int k)
{ {
k = 5; k = 5;
Console.WriteLine("Overload with out param" + i + ", " + j); Console.WriteLine("Overload with out param" + i + ", " + j);
} }
} }
} }
\ No newline at end of file
using System; /*
using System.Collections.Generic; * This file is part of LuaInterface.
*
* Copyright (C) 2003-2005 Fabio Mascarenhas de Queiroz.
* Copyright (C) 2012 Megax <http://megax.yeahunter.hu/>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Text; using System.Text;
using System.Threading; using System.Threading;
using System.Reflection; using System.Reflection;
using System.Collections.Generic;
using LuaInterface.Exceptions; using LuaInterface.Exceptions;
namespace LuaInterface.Tests namespace LuaInterface.Tests
{ {
/* /*
* Automated test cases for LuaInterface * Automated test cases for LuaInterface
* *
* Author: Fabio Mascarenhas * Author: Fabio Mascarenhas
* Version: 1.0 * Version: 1.0
*/ */
public class TestLuaInterface public class TestLuaInterface
{ {
private Lua _Lua; private Lua _Lua;
/*
* Executed before each test case /*
*/ * Executed before each test case
public void Init() */
{ public void Init()
_Lua = new Lua(); {
_Lua = new Lua();
GC.Collect(); // runs GC to expose unprotected delegates GC.Collect(); // runs GC to expose unprotected delegates
} }
/*
* Executed after each test case /*
*/ * Executed after each test case
public void Destroy() */
{ public void Destroy()
_Lua = null; {
} _Lua = null;
}
#if false #if false
// I've commented out the nunit based tests until they can run standalone - so that users don't need nunit to run TestLua // I've commented out the nunit based tests until they can run standalone - so that users don't need nunit to run TestLua
/* /*
* Tests if DoString is correctly returning values * Tests if DoString is correctly returning values
...@@ -956,581 +982,553 @@ namespace LuaInterface.Tests ...@@ -956,581 +982,553 @@ namespace LuaInterface.Tests
//Console.WriteLine("interface returned: "+test.getStrVal()); //Console.WriteLine("interface returned: "+test.getStrVal());
} }
#endif #endif
void TestOk(bool flag)
{
if(flag)
Console.WriteLine("Test Passed.");
else
Console.WriteLine("Test Failed!!!!");
}
/*
* Tests capturing an exception
*/
public void ThrowException()
{
Init();
_Lua.DoString("luanet.load_assembly('mscorlib')");
_Lua.DoString("luanet.load_assembly('TestLua')");
_Lua.DoString("TestClass=luanet.import_type('LuaInterface.Tests.TestClass')");
_Lua.DoString("test=TestClass()");
_Lua.DoString("err,errMsg=pcall(test.exceptionMethod,test)");
bool err = (bool)_Lua["err"];
Exception errMsg = (Exception)_Lua["errMsg"];
TestOk(!err);
TestOk(errMsg.InnerException != null);
if(errMsg.InnerException != null)
TestOk("exception test" == errMsg.InnerException.Message);
//Console.WriteLine("interface returned: "+errMsg.ToString());
Destroy();
}
/*
* Tests capturing an exception
*/
public void ThrowUncaughtException()
{
Init();
_Lua.DoString("luanet.load_assembly('mscorlib')");
_Lua.DoString("luanet.load_assembly('TestLua')");
_Lua.DoString("TestClass=luanet.import_type('LuaInterface.Tests.TestClass')");
_Lua.DoString("test=TestClass()");
try
{
_Lua.DoString("test:exceptionMethod()");
Console.WriteLine("Test failed!!! Should have thrown an exception all the way out of Lua");
}
catch (Exception)
{
Console.WriteLine("Uncaught exception success");
}
Destroy();
}
/*
* Tests nullable fields
*/
public void TestNullable()
{
Init();
_Lua.DoString("luanet.load_assembly('mscorlib')");
_Lua.DoString("luanet.load_assembly('TestLua')");
_Lua.DoString("TestClass=luanet.import_type('LuaInterface.Tests.TestClass')");
_Lua.DoString("test=TestClass()");
_Lua.DoString("val=test.NullableBool");
TestOk(((object)_Lua["val"]) == null);
_Lua.DoString("test.NullableBool = true");
_Lua.DoString("val=test.NullableBool");
TestOk(((bool)_Lua["val"]) == true);
Destroy();
}
/*
* Tests structure assignment
*/
public void TestStructs()
{
Init();
_Lua.DoString("luanet.load_assembly('TestLua')");
_Lua.DoString("TestClass=luanet.import_type('LuaInterface.Tests.TestClass')");
_Lua.DoString("test=TestClass()");
_Lua.DoString("TestStruct=luanet.import_type('LuaInterface.Tests.TestStruct')");
_Lua.DoString("struct=TestStruct(2)");
_Lua.DoString("test.Struct = struct");
_Lua.DoString("val=test.Struct.val");
TestOk(((double)_Lua["val"]) == 2.0);
Destroy();
}
public void TestMethodOverloads()
{
Init();
_Lua.DoString("luanet.load_assembly('mscorlib')");
_Lua.DoString("luanet.load_assembly('TestLua')");
_Lua.DoString("TestClass=luanet.import_type('LuaInterface.Tests.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)");
}
private void TestDispose()
{
GC.Collect();
long startingMem = System.Diagnostics.Process.GetCurrentProcess().WorkingSet64;
for(int i = 0; i < 10000; i++)
{
using (Lua lua = new Lua())
{
_Calc(lua, i);
}
}
Console.WriteLine("Was using " + startingMem / 1024 / 1024 + "MB, now using: " + System.Diagnostics.Process.GetCurrentProcess().WorkingSet64 / 1024 / 1024 + "MB");
}
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");
/*Object[] ret = */lf.Call(i, 20);
}
private void TestThreading()
{
Init();
var doWork = new DoWorkClass();
_Lua.RegisterFunction("dowork", doWork, typeof(DoWorkClass).GetMethod("DoWork"));
bool failureDetected = false;
int completed = 0;
int iterations = 500;
for(int i = 0; i < iterations; i++)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(delegate(object o)
{
try
{
_Lua.DoString("dowork()");
}
catch
{
failureDetected = true;
}
completed++;
}));
}
while(completed < iterations && !failureDetected)
Thread.Sleep(50);
if(failureDetected)
Console.WriteLine("==Problem with threading!==");
}
private void TestPrivateMethod()
{
Init();
_Lua.DoString("luanet.load_assembly('mscorlib')");
_Lua.DoString("luanet.load_assembly('TestLua')");
_Lua.DoString("TestClass=luanet.import_type('LuaInterface.Tests.TestClass')");
_Lua.DoString("test=TestClass()");
try
{
_Lua.DoString("test:_PrivateMethod()");
}
catch
{
Console.WriteLine("Test Passed");
return;
}
Console.WriteLine("Test Failed");
}
void TestOk(bool flag) /*
{ * Tests functions
if (flag) */
Console.WriteLine("Test Passed."); public void TestFunctions()
else {
Console.WriteLine("Test Failed!!!!"); Init();
} _Lua.DoString("luanet.load_assembly('mscorlib')");
_Lua.DoString("luanet.load_assembly('TestLua')");
_Lua.RegisterFunction("p", null, typeof(System.Console).GetMethod("WriteLine", new Type[] { typeof(String) }));
/*
* Tests capturing an exception /// Lua command that works (prints to console)
*/ _Lua.DoString("p('Foo')");
public void ThrowException()
{ /// Yet this works...
Init(); _Lua.DoString("string.gsub('some string', '(%w+)', function(s) p(s) end)");
_Lua.DoString("luanet.load_assembly('mscorlib')"); /// This fails if you don't fix Lua5.1 lstrlib.c/add_value to treat LUA_TUSERDATA the same as LUA_FUNCTION
_Lua.DoString("luanet.load_assembly('TestLua')"); _Lua.DoString("string.gsub('some string', '(%w+)', p)");
_Lua.DoString("TestClass=luanet.import_type('LuaInterface.Tests.TestClass')"); Destroy();
_Lua.DoString("test=TestClass()"); }
_Lua.DoString("err,errMsg=pcall(test.exceptionMethod,test)");
bool err = (bool)_Lua["err"]; /*
Exception errMsg = (Exception)_Lua["errMsg"]; * Tests making an object from a Lua table and calling one of
TestOk(!err); * methods the table overrides.
TestOk(errMsg.InnerException != null); */
if (errMsg.InnerException != null) public void LuaTableOverridedMethod()
{ {
TestOk("exception test" == errMsg.InnerException.Message); Init();
} _Lua.DoString("luanet.load_assembly('TestLua')");
//Console.WriteLine("interface returned: "+errMsg.ToString()); _Lua.DoString("TestClass=luanet.import_type('LuaInterface.Tests.TestClass')");
_Lua.DoString("test={}");
Destroy(); _Lua.DoString("function test:overridableMethod(x,y) return x*y; end");
} _Lua.DoString("luanet.make_object(test,'LuaInterface.Tests.TestClass')");
_Lua.DoString("a=TestClass.callOverridable(test,2,3)");
/* int a = (int)_Lua.GetNumber("a");
* Tests capturing an exception _Lua.DoString("luanet.free_object(test)");
*/ TestOk(6 == a);
public void ThrowUncaughtException() //Console.WriteLine("interface returned: "+a);
{ }
Init();
/*
_Lua.DoString("luanet.load_assembly('mscorlib')"); * Tests making an object from a Lua table and calling a method
_Lua.DoString("luanet.load_assembly('TestLua')"); * the table does not override.
_Lua.DoString("TestClass=luanet.import_type('LuaInterface.Tests.TestClass')"); */
_Lua.DoString("test=TestClass()"); public void LuaTableInheritedMethod()
{
try Init();
{ _Lua.DoString("luanet.load_assembly('TestLua')");
_Lua.DoString("test:exceptionMethod()"); _Lua.DoString("TestClass=luanet.import_type('LuaInterface.Tests.TestClass')");
_Lua.DoString("test={}");
Console.WriteLine("Test failed!!! Should have thrown an exception all the way out of Lua"); _Lua.DoString("function test:overridableMethod(x,y) return x*y; end");
} _Lua.DoString("luanet.make_object(test,'LuaInterface.Tests.TestClass')");
catch (Exception) _Lua.DoString("test:setVal(3)");
{ _Lua.DoString("a=test.testval");
Console.WriteLine("Uncaught exception success"); int a = (int)_Lua.GetNumber("a");
} _Lua.DoString("luanet.free_object(test)");
TestOk(3 == a);
Destroy(); //Console.WriteLine("interface returned: "+a);
} }
/// <summary>
/* /// Basic multiply method which expects 2 floats
* Tests nullable fields /// </summary>
*/ /// <param name="val"></param>
public void TestNullable() /// <param name="val2"></param>
{ /// <returns></returns>
Init(); private float _TestException(float val, float val2)
{
_Lua.DoString("luanet.load_assembly('mscorlib')"); return val * val2;
_Lua.DoString("luanet.load_assembly('TestLua')"); }
_Lua.DoString("TestClass=luanet.import_type('LuaInterface.Tests.TestClass')");
_Lua.DoString("test=TestClass()"); public void TestEventException()
{
_Lua.DoString("val=test.NullableBool"); Init();
TestOk(((object)_Lua["val"]) == null);
_Lua.DoString("test.NullableBool = true"); //Register a C# function
_Lua.DoString("val=test.NullableBool"); MethodInfo testException = this.GetType().GetMethod("_TestException", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Instance, null, new Type[] { typeof(float), typeof(float) }, null);
TestOk(((bool)_Lua["val"]) == true); _Lua.RegisterFunction("Multiply", this, testException);
Destroy(); //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, we)\r\n" +
* Tests structure assignment "end");
*/
public void TestStructs() //create the lua event handler code for the entity
{ //good code
Init(); //lua.DoString("function OnClick(sender, eventArgs)\r\n" +
// "--Multiply expects 2 floats\r\n" +
_Lua.DoString("luanet.load_assembly('TestLua')"); // "Multiply(2, 50)\r\n" +
_Lua.DoString("TestClass=luanet.import_type('LuaInterface.Tests.TestClass')"); // "end");
_Lua.DoString("test=TestClass()");
_Lua.DoString("TestStruct=luanet.import_type('LuaInterface.Tests.TestStruct')"); //Create the event handler script
_Lua.DoString("function SubscribeEntity(e)\r\ne.Clicked:Add(OnClick)\r\nend");
_Lua.DoString("struct=TestStruct(2)");
_Lua.DoString("test.Struct = struct"); //Create the entity object
_Lua.DoString("val=test.Struct.val"); var entity = new Entity();
TestOk(((double)_Lua["val"]) == 2.0);
//Register the entity object with the event handler inside lua
Destroy(); LuaFunction lf = _Lua.GetFunction("SubscribeEntity");
} lf.Call(new object[1] { entity });
public void TestMethodOverloads() try
{ {
Init(); //Cause the event to be fired
entity.Click();
_Lua.DoString("luanet.load_assembly('mscorlib')");
_Lua.DoString("luanet.load_assembly('TestLua')"); Console.WriteLine("Test failed!!! Should have thrown an exception all the way out of Lua");
_Lua.DoString("TestClass=luanet.import_type('LuaInterface.Tests.TestClass')"); }
_Lua.DoString("test=TestClass()"); catch (LuaException)
_Lua.DoString("test:MethodOverload()"); {
_Lua.DoString("test:MethodOverload(test)"); Console.WriteLine("Event exception success");
_Lua.DoString("test:MethodOverload(1,1,1)"); }
_Lua.DoString("test:MethodOverload(2,2,i)\r\nprint(i)"); }
}
public void TestExceptionWithChunkOverload()
private void TestDispose() {
{ Init();
System.GC.Collect();
long startingMem = System.Diagnostics.Process.GetCurrentProcess().WorkingSet64; try
{
for (int i = 0; i < 10000; i++) _Lua.DoString("thiswillthrowanerror", "MyChunk");
{ }
using (Lua lua = new Lua()) catch(Exception e)
{ {
_Calc(lua, i); if (e.Message.StartsWith("[string \"MyChunk\"]"))
} Console.WriteLine("Chunk overload passed");
} else
Console.WriteLine("Chunk overload failed");
Console.WriteLine("Was using " + startingMem / 1024 / 1024 + "MB, now using: " + System.Diagnostics.Process.GetCurrentProcess().WorkingSet64 / 1024 / 1024 + "MB"); }
} }
private void _Calc(Lua lua, int i) public void TestGenerics()
{ {
lua.DoString( Init();
"sqrt = math.sqrt;" +
"sqr = function(x) return math.pow(x,2); end;" + //Im not sure support for generic classes is possible to implement, see: http://msdn.microsoft.com/en-us/library/system.reflection.methodinfo.containsgenericparameters.aspx
"log = math.log;" + //specifically the line that says: "If the ContainsGenericParameters property returns true, the method cannot be invoked"
"log10 = math.log10;" +
"exp = math.exp;" + //TestClassGeneric<string> genericClass = new TestClassGeneric<string>();
"sin = math.sin;" +
"cos = math.cos;" + //_Lua.RegisterFunction("genericMethod", genericClass, typeof(TestClassGeneric<>).GetMethod("GenericMethod"));
"tan = math.tan;" + //_Lua.RegisterFunction("regularMethod", genericClass, typeof(TestClassGeneric<>).GetMethod("RegularMethod"));
"abs = math.abs;"
); //try
//{
lua.DoString("function calcVP(a,b) return a+b end"); // _Lua.DoString("genericMethod('thestring')");
//}
LuaFunction lf = lua.GetFunction("calcVP"); //catch { }
/*Object[] ret = */lf.Call(i, 20);
} //try
//{
private void TestThreading() // _Lua.DoString("regularMethod()");
{ //}
Init(); //catch { }
DoWorkClass doWork = new DoWorkClass(); //if (genericClass.GenericMethodSuccess && genericClass.RegularMethodSuccess && genericClass.Validate("thestring"))
_Lua.RegisterFunction("dowork", doWork, typeof(DoWorkClass).GetMethod("DoWork")); // Console.WriteLine("Generic class passed");
//else
bool failureDetected = false; // Console.WriteLine("Generic class failed");
int completed = 0;
int iterations = 500; bool passed = true;
TestClassWithGenericMethod classWithGenericMethod = new TestClassWithGenericMethod();
for (int i = 0; i < iterations; i++)
{ _Lua.RegisterFunction("genericMethod2", classWithGenericMethod, typeof(TestClassWithGenericMethod).GetMethod("GenericMethod"));
ThreadPool.QueueUserWorkItem(new WaitCallback(delegate(object o)
{ try
try {
{ _Lua.DoString("genericMethod2(100)");
_Lua.DoString("dowork()"); }
} catch
catch {
{
failureDetected = true; }
}
completed++; if(!classWithGenericMethod.GenericMethodSuccess || !classWithGenericMethod.Validate<double>(100)) //note the gotcha: numbers are all being passed to generic methods as doubles
})); passed = false;
}
try
while (completed < iterations && !failureDetected) {
Thread.Sleep(50); _Lua.DoString("luanet.load_assembly('TestLua')");
_Lua.DoString("TestClass=luanet.import_type('LuaInterface.Tests.TestClass')");
if (failureDetected) _Lua.DoString("test=TestClass(56)");
Console.WriteLine("==Problem with threading!=="); _Lua.DoString("genericMethod2(test)");
} }
catch
private void TestPrivateMethod() {
{
Init(); }
_Lua.DoString("luanet.load_assembly('mscorlib')"); if(!classWithGenericMethod.GenericMethodSuccess || (classWithGenericMethod.PassedValue as TestClass).val != 56)
_Lua.DoString("luanet.load_assembly('TestLua')"); passed = false;
_Lua.DoString("TestClass=luanet.import_type('LuaInterface.Tests.TestClass')");
_Lua.DoString("test=TestClass()"); if(passed)
try Console.WriteLine("Class with generic method passed");
{ else
_Lua.DoString("test:_PrivateMethod()"); Console.WriteLine("Class with generic method failed");
} }
catch
{ public static int func(int x, int y)
Console.WriteLine("Test Passed"); {
return; return x + y;
} }
Console.WriteLine("Test Failed"); public int funcInstance(int x, int y)
} {
return x + y;
/* }
* Tests functions
*/ public void RegisterFunctionStressTest()
public void TestFunctions() {
{ LuaFunction fc = null;
Init(); const int Count = 200; // it seems to work with 41
_Lua.DoString("luanet.load_assembly('mscorlib')"); Init();
_Lua.DoString("luanet.load_assembly('TestLua')"); var t = new MyClass();
_Lua.RegisterFunction("p", null, typeof(System.Console).GetMethod("WriteLine", new Type[] { typeof(String) }));
for(int i = 1; i < Count - 1; ++i)
/// Lua command that works (prints to console) fc = _Lua.RegisterFunction("func" + i, t, typeof(MyClass).GetMethod("Func1"));
_Lua.DoString("p('Foo')");
fc = _Lua.RegisterFunction("func" + (Count - 1), t, typeof(MyClass).GetMethod("Func1"));
/// Yet this works... _Lua.DoString("print(func1())");
_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)"); * Sample test script that shows some of the capabilities of
* LuaInterface
Destroy(); */
} public static void Main()
{
Console.WriteLine("Starting interpreter...");
var l = new Lua();
/* // Pause so we can connect with the debugger
* Tests making an object from a Lua table and calling one of // Thread.Sleep(30000);
* methods the table overrides. Console.WriteLine("Reading test.lua file...");
*/ l.DoFile("test.lua");
public void LuaTableOverridedMethod() double width = l.GetNumber("width");
{ double height = l.GetNumber("height");
Init(); string message = l.GetString("message");
double color_r = l.GetNumber("color.r");
_Lua.DoString("luanet.load_assembly('TestLua')"); double color_g = l.GetNumber("color.g");
_Lua.DoString("TestClass=luanet.import_type('LuaInterface.Tests.TestClass')"); double color_b = l.GetNumber("color.b");
_Lua.DoString("test={}"); Console.WriteLine("Printing values of global variables width, height and message...");
_Lua.DoString("function test:overridableMethod(x,y) return x*y; end"); Console.WriteLine("width: " + width);
_Lua.DoString("luanet.make_object(test,'LuaInterface.Tests.TestClass')"); Console.WriteLine("height: " + height);
_Lua.DoString("a=TestClass.callOverridable(test,2,3)"); Console.WriteLine("message: " + message);
int a = (int)_Lua.GetNumber("a"); Console.WriteLine("Printing values of the 'color' table's fields...");
_Lua.DoString("luanet.free_object(test)"); Console.WriteLine("color.r: " + color_r);
TestOk(6 == a); Console.WriteLine("color.g: " + color_g);
//Console.WriteLine("interface returned: "+a); Console.WriteLine("color.b: " + color_b);
} width = 150;
Console.WriteLine("Changing width's value and calling Lua function print to show it...");
l["width"] = width;
/* l.GetFunction("print").Call(width);
* Tests making an object from a Lua table and calling a method message = "LuaNet Interface Test";
* the table does not override. Console.WriteLine("Changing message's value and calling Lua function print to show it...");
*/ l["message"] = message;
public void LuaTableInheritedMethod() l.GetFunction("print").Call(message);
{ color_r = 30;
Init(); color_g = 10;
color_b = 200;
_Lua.DoString("luanet.load_assembly('TestLua')"); Console.WriteLine("Changing color's fields' values and calling Lua function print to show it...");
_Lua.DoString("TestClass=luanet.import_type('LuaInterface.Tests.TestClass')"); l["color.r"] = color_r;
_Lua.DoString("test={}"); l["color.g"] = color_g;
_Lua.DoString("function test:overridableMethod(x,y) return x*y; end"); l["color.b"] = color_b;
_Lua.DoString("luanet.make_object(test,'LuaInterface.Tests.TestClass')"); l.DoString("print(color.r,color.g,color.b)");
_Lua.DoString("test:setVal(3)"); Console.WriteLine("Printing values of the tree table's fields...");
_Lua.DoString("a=test.testval"); double leaf1 = l.GetNumber("tree.branch1.leaf1");
int a = (int)_Lua.GetNumber("a"); string leaf2 = l.GetString("tree.branch1.leaf2");
_Lua.DoString("luanet.free_object(test)"); string leaf3 = l.GetString("tree.leaf3");
TestOk(3 == a); Console.WriteLine("leaf1: " + leaf1);
//Console.WriteLine("interface returned: "+a); Console.WriteLine("leaf2: " + leaf2);
} Console.WriteLine("leaf3: " + leaf3);
leaf1 = 30; leaf2 = "new leaf2";
Console.WriteLine("Changing tree's fields' values and calling Lua function print to show it...");
/// <summary> l["tree.branch1.leaf1"] = leaf1; l["tree.branch1.leaf2"] = leaf2;
/// Basic multiply method which expects 2 floats l.DoString("print(tree.branch1.leaf1,tree.branch1.leaf2)");
/// </summary> Console.WriteLine("Returning values from Lua with 'return'...");
/// <param name="val"></param> object[] vals = l.DoString("return 2,3");
/// <param name="val2"></param> Console.WriteLine("Returned: " + vals[0] + " and " + vals[1]);
/// <returns></returns> Console.WriteLine("Calling a Lua function that returns multiple values...");
private float _TestException(float val, float val2) object[] vals1 = l.GetFunction("func").Call(2, 3);
{ Console.WriteLine("Returned: " + vals1[0] + " and " + vals1[1]);
return val * val2; Console.WriteLine("Creating a table and filling it from C#...");
} l.NewTable("tab");
l.NewTable("tab.tab");
l["tab.a"] = "a!";
public void TestEventException() l["tab.b"] = 5.5;
{ l["tab.tab.c"] = 6.5;
Init(); l.DoString("print(tab.a,tab.b,tab.tab.c)");
Console.WriteLine("Setting a table as another table's field...");
//Register a C# function l["tab.a"] = l["tab.tab"];
MethodInfo testException = this.GetType().GetMethod("_TestException", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Instance, null, new Type[] { typeof(float), typeof(float) }, null); l.DoString("print(tab.a.c)");
_Lua.RegisterFunction("Multiply", this, testException); Console.WriteLine("Registering a C# static method and calling it from Lua...");
//create the lua event handler code for the entity // Pause so we can connect with the debugger
//includes the bad code! // Thread.Sleep(30000);
_Lua.DoString("function OnClick(sender, eventArgs)\r\n" + l.RegisterFunction("func1", null, typeof(TestLuaInterface).GetMethod("func"));
"--Multiply expects 2 floats, but instead receives 2 strings\r\n" + vals1 = l.GetFunction("func1").Call(2, 3);
"Multiply(asd, we)\r\n" + Console.WriteLine("Returned: " + vals1[0]);
"end"); TestLuaInterface obj = new TestLuaInterface();
Console.WriteLine("Registering a C# instance method and calling it from Lua...");
//create the lua event handler code for the entity l.RegisterFunction("func2", obj, typeof(TestLuaInterface).GetMethod("funcInstance"));
//good code vals1 = l.GetFunction("func2").Call(2, 3);
//lua.DoString("function OnClick(sender, eventArgs)\r\n" + Console.WriteLine("Returned: " + vals1[0]);
// "--Multiply expects 2 floats\r\n" +
// "Multiply(2, 50)\r\n" + Console.WriteLine("Testing throwing an exception...");
// "end"); obj.ThrowUncaughtException();
//Create the event handler script Console.WriteLine("Testing catching an exception...");
_Lua.DoString("function SubscribeEntity(e)\r\ne.Clicked:Add(OnClick)\r\nend"); obj.ThrowException();
//Create the entity object Console.WriteLine("Testing inheriting a method from Lua...");
Entity entity = new Entity(); obj.LuaTableInheritedMethod();
//Register the entity object with the event handler inside lua Console.WriteLine("Testing overriding a C# method with Lua...");
LuaFunction lf = _Lua.GetFunction("SubscribeEntity"); obj.LuaTableOverridedMethod();
lf.Call(new object[1] { entity });
Console.WriteLine("Stress test RegisterFunction (based on a reported bug)..");
try obj.RegisterFunctionStressTest();
{
//Cause the event to be fired Console.WriteLine("Test structures...");
entity.Click(); obj.TestStructs();
Console.WriteLine("Test failed!!! Should have thrown an exception all the way out of Lua"); Console.WriteLine("Test Nullable types...");
} obj.TestNullable();
catch (LuaException)
{ Console.WriteLine("Test functions...");
Console.WriteLine("Event exception success"); obj.TestFunctions();
}
Console.WriteLine("Test method overloads...");
} obj.TestMethodOverloads();
public void TestExceptionWithChunkOverload() Console.WriteLine("Test accessing private method...");
{ obj.TestPrivateMethod();
Init();
Console.WriteLine("Test event exceptions...");
try obj.TestEventException();
{
_Lua.DoString("thiswillthrowanerror", "MyChunk"); Console.WriteLine("Test chunk overload exception...");
} obj.TestExceptionWithChunkOverload();
catch (Exception e)
{ Console.WriteLine("Test generics...");
if (e.Message.StartsWith("[string \"MyChunk\"]")) obj.TestGenerics();
Console.WriteLine("Chunk overload passed");
else Console.WriteLine("Test threading...");
Console.WriteLine("Chunk overload failed"); obj.TestThreading();
}
} Console.WriteLine("Test memory leakage...");
obj.TestDispose();
public void TestGenerics()
{ Console.WriteLine("Press enter to exit.");
Init(); Console.ReadLine();
}
//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" }
\ No newline at end of file
//TestClassGeneric<string> genericClass = new TestClassGeneric<string>();
//_Lua.RegisterFunction("genericMethod", genericClass, typeof(TestClassGeneric<>).GetMethod("GenericMethod"));
//_Lua.RegisterFunction("regularMethod", genericClass, typeof(TestClassGeneric<>).GetMethod("RegularMethod"));
//try
//{
// _Lua.DoString("genericMethod('thestring')");
//}
//catch { }
//try
//{
// _Lua.DoString("regularMethod()");
//}
//catch { }
//if (genericClass.GenericMethodSuccess && genericClass.RegularMethodSuccess && genericClass.Validate("thestring"))
// Console.WriteLine("Generic class passed");
//else
// Console.WriteLine("Generic class failed");
bool passed = true;
TestClassWithGenericMethod classWithGenericMethod = new TestClassWithGenericMethod();
_Lua.RegisterFunction("genericMethod2", classWithGenericMethod, typeof(TestClassWithGenericMethod).GetMethod("GenericMethod"));
try
{
_Lua.DoString("genericMethod2(100)");
}
catch { }
if (!classWithGenericMethod.GenericMethodSuccess || !classWithGenericMethod.Validate<double>(100)) //note the gotcha: numbers are all being passed to generic methods as doubles
passed = false;
try
{
_Lua.DoString("luanet.load_assembly('TestLua')");
_Lua.DoString("TestClass=luanet.import_type('LuaInterface.Tests.TestClass')");
_Lua.DoString("test=TestClass(56)");
_Lua.DoString("genericMethod2(test)");
}
catch { }
if (!classWithGenericMethod.GenericMethodSuccess || (classWithGenericMethod.PassedValue as TestClass).val != 56)
passed = false;
if (passed)
Console.WriteLine("Class with generic method passed");
else
Console.WriteLine("Class with generic method failed");
}
public static int func(int x, int y)
{
return x + y;
}
public int funcInstance(int x, int y)
{
return x + y;
}
public void RegisterFunctionStressTest()
{
LuaFunction fc = null;
const int Count = 200; // it seems to work with 41
Init();
MyClass t = new MyClass();
for (int i = 1; i < Count - 1; ++i)
{
fc = _Lua.RegisterFunction("func" + i, t, typeof(MyClass).GetMethod("Func1"));
}
fc = _Lua.RegisterFunction("func" + (Count - 1), t, typeof(MyClass).GetMethod("Func1"));
_Lua.DoString("print(func1())");
}
/*
* Sample test script that shows some of the capabilities of
* LuaInterface
*/
public static void Main()
{
Console.WriteLine("Starting interpreter...");
Lua l = new Lua();
// Pause so we can connect with the debugger
// Thread.Sleep(30000);
Console.WriteLine("Reading test.lua file...");
l.DoFile("test.lua");
double width = l.GetNumber("width");
double height = l.GetNumber("height");
string message = l.GetString("message");
double color_r = l.GetNumber("color.r");
double color_g = l.GetNumber("color.g");
double color_b = l.GetNumber("color.b");
Console.WriteLine("Printing values of global variables width, height and message...");
Console.WriteLine("width: " + width);
Console.WriteLine("height: " + height);
Console.WriteLine("message: " + message);
Console.WriteLine("Printing values of the 'color' table's fields...");
Console.WriteLine("color.r: " + color_r);
Console.WriteLine("color.g: " + color_g);
Console.WriteLine("color.b: " + color_b);
width = 150;
Console.WriteLine("Changing width's value and calling Lua function print to show it...");
l["width"] = width;
l.GetFunction("print").Call(width);
message = "LuaNet Interface Test";
Console.WriteLine("Changing message's value and calling Lua function print to show it...");
l["message"] = message;
l.GetFunction("print").Call(message);
color_r = 30;
color_g = 10;
color_b = 200;
Console.WriteLine("Changing color's fields' values and calling Lua function print to show it...");
l["color.r"] = color_r;
l["color.g"] = color_g;
l["color.b"] = color_b;
l.DoString("print(color.r,color.g,color.b)");
Console.WriteLine("Printing values of the tree table's fields...");
double leaf1 = l.GetNumber("tree.branch1.leaf1");
string leaf2 = l.GetString("tree.branch1.leaf2");
string leaf3 = l.GetString("tree.leaf3");
Console.WriteLine("leaf1: " + leaf1);
Console.WriteLine("leaf2: " + leaf2);
Console.WriteLine("leaf3: " + leaf3);
leaf1 = 30; leaf2 = "new leaf2";
Console.WriteLine("Changing tree's fields' values and calling Lua function print to show it...");
l["tree.branch1.leaf1"] = leaf1; l["tree.branch1.leaf2"] = leaf2;
l.DoString("print(tree.branch1.leaf1,tree.branch1.leaf2)");
Console.WriteLine("Returning values from Lua with 'return'...");
object[] vals = l.DoString("return 2,3");
Console.WriteLine("Returned: " + vals[0] + " and " + vals[1]);
Console.WriteLine("Calling a Lua function that returns multiple values...");
object[] vals1 = l.GetFunction("func").Call(2, 3);
Console.WriteLine("Returned: " + vals1[0] + " and " + vals1[1]);
Console.WriteLine("Creating a table and filling it from C#...");
l.NewTable("tab");
l.NewTable("tab.tab");
l["tab.a"] = "a!";
l["tab.b"] = 5.5;
l["tab.tab.c"] = 6.5;
l.DoString("print(tab.a,tab.b,tab.tab.c)");
Console.WriteLine("Setting a table as another table's field...");
l["tab.a"] = l["tab.tab"];
l.DoString("print(tab.a.c)");
Console.WriteLine("Registering a C# static method and calling it from Lua...");
// Pause so we can connect with the debugger
// Thread.Sleep(30000);
l.RegisterFunction("func1", null, typeof(TestLuaInterface).GetMethod("func"));
vals1 = l.GetFunction("func1").Call(2, 3);
Console.WriteLine("Returned: " + vals1[0]);
TestLuaInterface obj = new TestLuaInterface();
Console.WriteLine("Registering a C# instance method and calling it from Lua...");
l.RegisterFunction("func2", obj, typeof(TestLuaInterface).GetMethod("funcInstance"));
vals1 = l.GetFunction("func2").Call(2, 3);
Console.WriteLine("Returned: " + vals1[0]);
Console.WriteLine("Testing throwing an exception...");
obj.ThrowUncaughtException();
Console.WriteLine("Testing catching an exception...");
obj.ThrowException();
Console.WriteLine("Testing inheriting a method from Lua...");
obj.LuaTableInheritedMethod();
Console.WriteLine("Testing overriding a C# method with Lua...");
obj.LuaTableOverridedMethod();
Console.WriteLine("Stress test RegisterFunction (based on a reported bug)..");
obj.RegisterFunctionStressTest();
Console.WriteLine("Test structures...");
obj.TestStructs();
Console.WriteLine("Test Nullable types...");
obj.TestNullable();
Console.WriteLine("Test functions...");
obj.TestFunctions();
Console.WriteLine("Test method overloads...");
obj.TestMethodOverloads();
Console.WriteLine("Test accessing private method...");
obj.TestPrivateMethod();
Console.WriteLine("Test event exceptions...");
obj.TestEventException();
Console.WriteLine("Test chunk overload exception...");
obj.TestExceptionWithChunkOverload();
Console.WriteLine("Test generics...");
obj.TestGenerics();
Console.WriteLine("Test threading...");
obj.TestThreading();
Console.WriteLine("Test memory leakage...");
obj.TestDispose();
Console.WriteLine("Press enter to exit.");
Console.ReadLine();
}
}
}
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