【问题标题】:LuaInterface not calling a methodLuaInterface 没有调用方法
【发布时间】:2015-01-21 15:49:19
【问题描述】:

我试图在我的 C#.NET 程序中实现 lua 脚本,但是当我执行代码时,其中一种方法没有被执行。

这是课程:

namespace Program1
{
    public class LuaFunctions
    {
        Client Client { get; set; }
        private Lua lua { get; set; }

        public LuaFunctions(Client c) {
            this.Client = c;
            this.lua = new Lua();

            registerFunctions();
        }

        public void ExecuteCode(string code)
        {
            this.lua.DoString(code);
        }

        private void registerFunctions()
        {
            lua.RegisterFunction("message", this, this.GetType().GetMethod("Message"));
            lua.RegisterFunction("pname", this, this.GetType().GetMethod("playername"));
        }

        public void Message(string s)
        {
            System.Windows.Forms.MessageBox.Show(s);
        }

        public string playername()
        {
            return Client.Player.Name;
        }
   }
}

当我执行这行 lua 代码“message(pname)”时,它甚至没有尝试执行方法“playername()”来返回一些值,所以它在 DoString() 行中崩溃,因为“pname”是“返回”为空。

【问题讨论】:

  • 如果您尝试调用pname 函数,那么您需要message(pname())message(pname) 将使用pname 函数 作为message 函数的值。
  • 你说得对,我试图创建一些“自定义变量”来使用,比如 $name,所以我可以使用 if($name == "Kyore")那么,你知道怎么可能吗?
  • 如果您试图让变量自动更新/等。你必须看看 LuaInterface 是否支持。如果您只想能够设置变量,那么您只需要在调用要使用它的代码之前设置一个全局或本地/环境变量。而不是注册一个函数。

标签: c# .net lua luainterface


【解决方案1】:

pname 正在注册为函数,未设置为包含字符串值的变量。

message(pname)被执行时,message函数被赋予pname函数的值而不是被赋予一个字符串(或调用pname的结果)函数.

要将pname 函数的结果传递给message,您需要使用message(pname())

【讨论】:

  • 谢谢你的解释,你知道如何创建一个变量而不是一个函数来返回一个值吗?
  • @Kyore 我不知道。应该有一种方法来创建一个应该很容易找到的全局变量(我认为)。话虽这么说,LuaInterface 目前不是“暂停”吗? github页面似乎建议使用NLua而不是它。
【解决方案2】:

这取决于您尝试创建变量的确切位置。如果你想在 Lua 中设置一些变量,那么lua["somevariable"] = "value"; 会起作用。一个更完整的例子可能是:

将原始值传递给状态:

double val = 12.0;
lua["x"] = val; // Create a global value 'x' 
var res = lua.DoString ("return 10 + x*(5 + 2)")[0] as double;

检索全局值:

lua.DoString ("y = 10 + x*(5 + 2)");
var y = lua["y"] as double; // Retrieve the value of y

【讨论】:

    猜你喜欢
    • 2014-09-15
    • 2011-02-20
    • 1970-01-01
    • 2023-03-09
    • 2012-03-13
    • 2012-08-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多