本文整理汇总了C#中NLua.Lua.RegisterFunction方法的典型用法代码示例。如果您正苦于以下问题:C# Lua.RegisterFunction方法的具体用法?C# Lua.RegisterFunction怎么用?C# Lua.RegisterFunction使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类NLua.Lua
的用法示例。
在下文中一共展示了Lua.RegisterFunction方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Init
public void Init()
{
if (IsInitialized)
throw new InvalidOperationException("Already Initialized!");
if (_state != null) _state.Dispose();
_state = new Lua();
_state.LoadCLRPackage();
_state.DoString(@"luanet.load_assembly('WGestures.Core');
luanet.load_assembly('WindowsInput');
luanet.load_assembly('WGestures.Common');
GestureModifier=luanet.import_type('WGestures.Core.GestureModifier');
VK=luanet.import_type('WindowsInput.Native.VirtualKeyCode');
Native=luanet.import_type('WGestures.Common.OsSpecific.Windows.Native');
", "_init");
_state["Input"] = Sim.Simulator;
_state.RegisterFunction("ReportStatus", this, typeof(ScriptCommand).GetMethod("OnReportStatus"));
if(InitScript != null)
{
DoString(InitScript, "Init");
}
IsInitialized = true;
}
示例2: Start
void Start()
{
lua = new NLua.Lua();
lua.LoadCLRPackage();
var method = typeof(Debug).GetMethod("Log", new Type[] { typeof(object) });
lua.RegisterFunction("print", method);
}
示例3: Task
public Task(Lua lua)
{
this.lua = lua;
name = this.GetType ().Name.ToLower ();
MethodInfo method = this.GetType ().GetMethod ("Run");
All[name] = this;
lua.RegisterFunction(name, this, method);
}
示例4: ScriptMan
/// <summary>Creates a new instance of ScriptMan.</summary>
/// <param name="world">The world that this script manager belongs to.</param>
public ScriptMan(World world)
{
lua = new Lua();
map = world;
lua.RegisterFunction("showMessage", this, this.GetType().GetMethod("showMessage"));
lua.RegisterFunction("loadWorld", this, this.GetType().GetMethod("loadWorld"));
lua.RegisterFunction("getOpenNodeIDs", this, this.GetType().GetMethod("getOpenNodeIDs"));
lua.RegisterFunction("getNumOpenSegs", this, this.GetType().GetMethod("getNumOpenSegs"));
lua.RegisterFunction("buildSeg", this, this.GetType().GetMethod("buildSeg"));
lua.RegisterFunction("destroyNode", this, this.GetType().GetMethod("destroyNode"));
lua.RegisterFunction("nodeExists", this, this.GetType().GetMethod("nodeExists"));
lua.RegisterFunction("nodeActive", this, this.GetType().GetMethod("nodeActive"));
lua.RegisterFunction("getConnectedNodes", this, this.GetType().GetMethod("getConnectedNodes"));
}
示例5: Setup
public void Setup()
{
lua = new Lua ();
lua.RegisterFunction ("WriteLineString", typeof (Console).GetMethod ("WriteLine", new Type [] { typeof (String) }));
lua.DoString (@"
function print (param)
WriteLineString (tostring(param))
end
");
}
示例6: RegisterNLuaBox
public static void RegisterNLuaBox(Lua context)
{
context.RegisterLuaDelegateType (typeof (EventHandler<EventArgs>), typeof (LuaEventArgsHandler));
context.RegisterLuaDelegateType (typeof (EventHandler), typeof (LuaEventArgsHandler));
context.RegisterLuaDelegateType (typeof (EventHandler<UIButtonEventArgs>), typeof (LuaButtonEventArgsHandler));
context.RegisterLuaDelegateType (typeof(NSAction), typeof(LuaNSActionHandler));
context.RegisterLuaClassType (typeof (UIViewController), typeof (NLuaBoxUIViewControllerBinder));
context.RegisterLuaClassType (typeof (UITableViewSource), typeof (NLuaBoxUITableViewSourceBinder));
context.RegisterLuaClassType (typeof (JLTextViewController), typeof (NLuaBoxDetailLuaViewController));
context.RegisterLuaClassType (typeof (DialogViewController), typeof (NLuaBoxDialogViewControllerBinder));
context.RegisterLuaClassType (typeof (UITableViewController), typeof (NLuaBoxUITableViewControllerBinder));
context.RegisterFunction ("CreateListString", typeof (NLuaBoxBinder).GetMethod ("CreateListString"));
}
示例7: TestGenerics
public void TestGenerics ()
{
//Im not sure support for generic classes is possible to implement, see: http://msdn.microsoft.com/en-us/library/system.reflection.methodinfo.containsgenericparameters.aspx
//specifically the line that says: "If the ContainsGenericParameters property returns true, the method cannot be invoked"
//TestClassGeneric<string> genericClass = new TestClassGeneric<string>();
//lua.RegisterFunction("genericMethod", genericClass, typeof(TestClassGeneric<>).GetMethod("GenericMethod"));
//lua.RegisterFunction("regularMethod", genericClass, typeof(TestClassGeneric<>).GetMethod("RegularMethod"));
using (Lua lua = new Lua ()) {
TestClassWithGenericMethod classWithGenericMethod = new TestClassWithGenericMethod ();
////////////////////////////////////////////////////////////////////////////
/// ////////////////////////////////////////////////////////////////////////
/// IMPORTANT: Use generic method with the type you will call or generic methods will fail with iOS
/// ////////////////////////////////////////////////////////////////////////
classWithGenericMethod.GenericMethod<double>(99.0);
classWithGenericMethod.GenericMethod<TestClass>(new TestClass (99));
////////////////////////////////////////////////////////////////////////////
/// ////////////////////////////////////////////////////////////////////////
lua.RegisterFunction ("genericMethod2", classWithGenericMethod, typeof(TestClassWithGenericMethod).GetMethod ("GenericMethod"));
try {
lua.DoString ("genericMethod2(100)");
} catch {
}
Assert.AreEqual (true, classWithGenericMethod.GenericMethodSuccess);
Assert.AreEqual (true, classWithGenericMethod.Validate<double> (100)); //note the gotcha: numbers are all being passed to generic methods as doubles
try {
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
lua.DoString ("test=TestClass(56)");
lua.DoString ("genericMethod2(test)");
} catch {
}
Assert.AreEqual (true, classWithGenericMethod.GenericMethodSuccess);
Assert.AreEqual (56, (classWithGenericMethod.PassedValue as TestClass).val);
}
}
示例8: TestEventException
public void TestEventException ()
{
using (Lua lua = new Lua ()) {
//Register a C# function
MethodInfo testException = this.GetType ().GetMethod ("_TestException", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Instance, null, new Type [] {
typeof(float),
typeof(float)
}, null);
lua.RegisterFunction ("Multiply", this, testException);
lua.RegisterLuaDelegateType (typeof(EventHandler<EventArgs>), typeof(LuaEventArgsHandler));
//create the lua event handler code for the entity
//includes the bad code!
lua.DoString ("function OnClick(sender, eventArgs)\r\n" +
"--Multiply expects 2 floats, but instead receives 2 strings\r\n" +
"Multiply(asd, es)\r\n" +
"end");
//create the lua event handler code for the entity
//good code
//lua.DoString("function OnClick(sender, eventArgs)\r\n" +
// "--Multiply expects 2 floats\r\n" +
// "Multiply(2, 50)\r\n" +
// "end");
//Create the event handler script
lua.DoString ("function SubscribeEntity(e)\r\ne.Clicked:Add(OnClick)\r\nend");
//Create the entity object
Entity entity = new Entity ();
//Register the entity object with the event handler inside lua
LuaFunction lf = lua.GetFunction ("SubscribeEntity");
lf.Call (new object [1] { entity });
try {
//Cause the event to be fired
entity.Click ();
//failed
Assert.AreEqual(true, false);
} catch (LuaException) {
//passed
Assert.AreEqual (true, true);
}
}
}
示例9: TestFunctions
public void TestFunctions ()
{
using (Lua lua = new Lua ()) {
lua.DoString ("luanet.load_assembly('mscorlib')");
lua.DoString ("luanet.load_assembly('NLuaTest')");
lua.RegisterFunction ("p", null, typeof(System.Console).GetMethod ("WriteLine", new Type [] { typeof(String) }));
/// Lua command that works (prints to console)
lua.DoString ("p('Foo')");
/// Yet this works...
lua.DoString ("string.gsub('some string', '(%w+)', function(s) p(s) end)");
/// This fails if you don't fix Lua5.1 lstrlib.c/add_value to treat LUA_TUSERDATA the same as LUA_FUNCTION
lua.DoString ("string.gsub('some string', '(%w+)', p)");
}
}
示例10: TestThreading
public void TestThreading ()
{
using (Lua lua = new Lua ()) {
object lua_locker = new object ();
DoWorkClass doWork = new DoWorkClass ();
lua.RegisterFunction ("dowork", doWork, typeof(DoWorkClass).GetMethod ("DoWork"));
bool failureDetected = false;
int completed = 0;
int iterations = 10;
for (int i = 0; i < iterations; i++) {
ThreadPool.QueueUserWorkItem (new WaitCallback (delegate (object o) {
try {
lock (lua_locker) {
lua.DoString ("dowork()");
}
} catch (Exception e) {
Console.Write (e);
failureDetected = true;
}
completed++;
}));
}
while (completed < iterations && !failureDetected)
Thread.Sleep (50);
Assert.AreEqual (false, failureDetected);
}
}
示例11: TestCoroutine
public void TestCoroutine ()
{
using (Lua lua = new Lua ()) {
lua.LoadCLRPackage ();
lua.RegisterFunction ("func1", null, typeof (TestClass2).GetMethod ("func"));
lua.DoString ("function yielder() " +
"a=1;" + "coroutine.yield();" +
"func1(3,2);" + "coroutine.yield();" + // This line triggers System.NullReferenceException
"a=2;" + "coroutine.yield();" +
"end;" +
"co_routine = coroutine.create(yielder);" +
"while coroutine.resume(co_routine) do end;");
double num = lua.GetNumber ("a");
//Console.WriteLine("a="+num);
Assert.AreEqual (num, 2d);
}
}
示例12: Run
public static void Run(string scriptname, params string[] args)
{
try
{
using (Lua lua = new Lua())
{
GlobalSteamLuaFunctions steamFunc = new GlobalSteamLuaFunctions();
lua.RegisterFunction("kickPlayer", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("kickPlayer"));
lua.RegisterFunction("notImplemented", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("notImplemented"));
lua.RegisterFunction("getPermissions", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("getPermissions"));
lua.RegisterFunction("sendRoomMessage", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("sendRoomMessage"));
lua.RegisterFunction("sendFriendMessage", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("sendFriendMessage"));
lua.RegisterFunction("getPersonaName", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("getPersonaName"));
lua.RegisterFunction("addRow", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("addRow"));
lua.RegisterFunction("getRow", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("getRow"));
lua.RegisterFunction("bindCommand", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("bindCommand"));
lua.RegisterFunction("unbindCommand", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("unbindCommand"));
lua.RegisterFunction("changePermissions", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("changePermissions"));
lua.RegisterFunction("changeName", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("changeName"));
lua.RegisterFunction("likeRow", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("likeRow"));
lua.RegisterFunction("getCustomURL", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("getCustomURL"));
lua.RegisterFunction("banPlayer", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("banPlayer"));
lua.RegisterFunction("createTable", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("createTable"));
lua.RegisterFunction("setLoginCredentials", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("setLoginCredentials"));
lua.RegisterFunction("joinChat", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("joinChat"));
lua.RegisterFunction("setAuthCode", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("setAuthCode"));
lua.RegisterFunction("connect", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("connect"));
lua["args"] = args;
for (int i = 1; i < args.Count(); i++)
{
if (i == 1)
{
argsJoined = args[i];
}
else
{
argsJoined = argsJoined + " " + args[i];
}
}
lua["argsJoined"] = argsJoined;
lua.DoFile("lua/scripts/" + scriptname + ".lua");
}
}
catch (Exception e)
{
Log.addLog(Log.types.WARNING, "Lua", "You have an error in your command!", e.ToString());
}
}
示例13: Run
public override void Run(string[] arguments)
{
// Correcting path => base path is package path
arguments[0] = Path.Combine(Package.Directory.FullName + Path.DirectorySeparatorChar, arguments[0]);
using (Lua lua = new Lua())
{
lua.LoadCLRPackage();
lua.DoString("import(\"craftitude\")"); // Load craftitude assembly into Lua.
lua.RegisterFunction("GetPlatformString", this, this.GetType().GetMethod("GetPlatformString"));
lua.RegisterFunction("GetProfile", this, this.GetType().GetMethod("GetProfile"));
lua.RegisterFunction("GetPackage", this, this.GetType().GetMethod("GetPackage"));
lua.RegisterFunction("GetProfilePath", this, this.GetType().GetMethod("GetProfilePath"));
lua.RegisterFunction("GetPackagePath", this, this.GetType().GetMethod("GetPackagePath"));
lua.DoString(@"
local mt = { }
local methods = { }
function mt.__index(userdata, k)
if methods[k] then
return methods[k]
else
return rawget(userdata, ""_array"")[k]
end
end
function mt.__newindex(userdata, k, v)
if methods[k] then
error ""can't assign to method!""
else
rawget(userdata, ""_array"")[k] = v
end
end");
lua.DoString(@"
function import_plugin(assemblyName, namespace)
import(Path.Combine(GetPluginsDir(), assemblyName))
import(namespace)
end");
lua.DoString(@"function install_plugin(dllPath, assemblyName)
System.IO.File.Copy(dllPath, Path.Combine(GetPluginsDir(), assemblyName .. "".dll""))
end");
lua.DoString(@"function uninstall_plugin(assemblyName)
System.IO.File.Delete(Path.Combine(GetPluginsDir(), assemblyName .. "".dll""))
end");
lua.DoFile(Path.Combine(Package.Path + Path.DirectorySeparatorChar, arguments[0].Replace('/', Path.DirectorySeparatorChar)));
lua.GetFunction(arguments[1]).Call();
}
}
示例14: WrapObject
/// <summary>
/// Wraps an object to prepare it for passing to LuaInterface. If no name is specified, a
/// random one with the default length is used.
/// </summary>
public static object WrapObject(object toWrap, Lua state, string name = null)
{
if (toWrap is DynamicArray)
{
//Someone passed an DynamicArray diretly back to Lua.
//He wanted to pass the value in the array, so we extract it.
//When there is more than one value, this method will ignore these extra value.
//This could happen in a situation like this: lua.tmp = lua("return a,b");, but
//that doesn't make sense.
toWrap = (toWrap as dynamic)[0];
}
if (toWrap is MulticastDelegate)
{
//We have to deal with a problem here: RegisterFunction does not really create
//a new function, but a userdata with a __call metamethod. This works fine in all
//except two cases: When Lua looks for an __index or __newindex metafunction and finds
//a table or userdata, Lua tries to redirect the read/write operation to that table/userdata.
//In case of our function that is in reality a userdata this fails. So we have to check
//for these function and create a very thin wrapper arround this to make Lua see a function instead
//the real userdata. This is no problem for the other metamethods, these are called independent
//from their type. (If they are not nil ;))
MulticastDelegate function = (toWrap as MulticastDelegate);
if (name != null && (name.EndsWith("__index") || name.EndsWith("__newindex")))
{
string tmpName = LuaHelper.GetRandomString();
state.RegisterFunction(tmpName, function.Target, function.Method);
state.DoString(String.Format("function {0}(...) return {1}(...) end", name, tmpName), "DynamicLua internal operation");
}
else
{
if (name == null)
name = LuaHelper.GetRandomString();
state.RegisterFunction(name, function.Target, function.Method);
}
return null;
}
else if (toWrap is DynamicLuaTable)
{
dynamic dlt = toWrap as DynamicLuaTable;
return (LuaTable)dlt;
}
else
return toWrap;
}
示例15: Run
public static void Run(string commandname, string[] args, bool fromGroup, string ChatterID, string ChatRoomID)
{
try
{
using (Lua lua = new Lua())
{
GlobalSteamLuaFunctions steamFunc = new GlobalSteamLuaFunctions();
lua.RegisterFunction("kickPlayer", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("kickPlayer"));
lua.RegisterFunction("notImplemented", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("notImplemented"));
lua.RegisterFunction("getPermissions", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("getPermissions"));
lua.RegisterFunction("sendRoomMessage", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("sendRoomMessage"));
lua.RegisterFunction("sendFriendMessage", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("sendFriendMessage"));
//lua.RegisterFunction("convertChatIDtoSteamKit", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("convertChatIDtoSteamKit"));
lua.RegisterFunction("getPersonaName", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("getPersonaName"));
lua.RegisterFunction("addRow", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("addRow"));
lua.RegisterFunction("getRow", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("getRow"));
lua.RegisterFunction("bindCommand", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("bindCommand"));
lua.RegisterFunction("unbindCommand", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("unbindCommand"));
lua.RegisterFunction("changePermissions", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("changePermissions"));
lua.RegisterFunction("changeName", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("changeName"));
lua.RegisterFunction("likeRow", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("likeRow"));
lua.RegisterFunction("getCustomURL", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("getCustomURL"));
lua.RegisterFunction("banPlayer", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("banPlayer"));
lua.RegisterFunction("createTable", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("createTable"));
lua.RegisterFunction("silentFail", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("silentFail"));
lua["ChatterID"] = ChatterID;
lua["fromGroup"] = fromGroup;
lua["ChatRoomID"] = ChatRoomID;
lua["args"] = args;
for(int i = 1; i < args.Count(); i++)
{
if (i == 1)
{
argsJoined = args[i];
}
else
{
argsJoined = argsJoined + " " + args[i];
}
}
lua["argsJoined"] = argsJoined;
lua.DoFile("lua/commands/" + commandname.Substring(1) + ".lua");
}
}
catch (Exception e)
{
Log.addLog(Log.types.WARNING, "Lua", "You have an error in your command!", e.ToString());
}
}