如何在Nlua中使用C#静态字符串

时间:2014-03-26 15:42:38

标签: c# lua nlua

我正在使用NLua与我的应用程序进行脚本接口。 我想将LUA语言的键盘输入发送到我的C#代码。

我使用这个C#代码。

   using (Lua lua = new Lua())
   {
      lua.LoadCLRPackage();

      lua.RegisterFunction("keypressC", null, typeof(TestNLUA).GetMethod("keypressC"));
      lua.RegisterFunction("keypressS", null, typeof(TestNLUA).GetMethod("keypressS"));

      lua["Key"] = new SpecialKey();
   }

    public class SpecialKey
    {
        public static readonly char EnterC = '\uE007'; 
        public static readonly string EnterS = Convert.ToString(EnterC);
    }

   public class TestNLUA
   {
      public static void keypressC(char key)
      {
         // key = 57351 => OK
      }

      public static void keypressS(string key)
      {
         char[] akey = key.ToCharArray();
         // akey[0] = 63 = ? (question mark) => KO
      }
   }

在LUA Script中我做了

keypressC(Key.EnterC)
keypressS(Key.EnterS)

在keypressC中,Nlua将值57351传递给关键参数。没关系。

在keypressS中,Nlua passe值"?"到关键参数。这是KO。 我不知道为什么会有角色"?"。 看起来像NLua中的编组错误(即LuaInterface)?

你能帮助我吗?

1 个答案:

答案 0 :(得分:1)

这是nLua / LuaInterface中的编组问题。

它使用Marshal.StringToHGlobalAnsi来编组从C#到Lua的字符串 它使用Marshal.PtrToStringAnsi来编组从Lua到C#的字符串。

如果您通过这些函数往返示例字符串,您可以看到它再现了您的问题:

 string test = "\uE007";

 Console.WriteLine(test);
 Console.WriteLine("{0}: {1}", test[0], (int) test[0]);

 IntPtr ptr = Marshal.StringToHGlobalAnsi(test);
 string roundTripped = Marshal.PtrToStringAnsi(ptr, test.Length);

 Console.WriteLine(roundTripped);
 Console.WriteLine("{0}: {1}", roundTripped[0], (int) roundTripped[0]);

输出:

?
?: 57351
?
?: 63

如果您将编组功能更改为使用Uni而不是Ansi,则问题就会消失,但您需要从源代码构建nLua / LuaInterface。