简体   繁体   中英

LuaInterface not calling a method

I'm trying to implement lua scripting in my C#.NET program, but when I execute the code, one of the methods is not been executed.

Here is the class:

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;
        }
   }
}

When I execute this line of lua code "message(pname)" it does not even try to execute the method "playername()" to return some value, so it crashs in the DoString() line because "pname" is "returning" null.

pname is being registered as a function not set as a variable containing a string value.

When message(pname) is executed the message function is being given the value of the pname function instead of being given a string (or the result of calling the pname ) function.

To pass the result of the pname function to message you would need to use message(pname()) .

It depends on where exactly you are trying to create the variable. If you are trying to set some variable in Lua, then lua["somevariable"] = "value"; would work. A more complete example could be:

Passing raw values to the state:

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

Retrieving global values:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM