Lua.GetFunction 返回空值。

我非常新于lua,这是我第一个使用它的程序。此代码使用Lua文件为我正在制作的游戏创建菜单。

这行在MainMenu屏幕中创建一个按钮,当按下按钮时发送要调用的函数的名称。

Lua:

CreateButton( "mainmenu", "NewGame", "New Game", 50, 120, 150, 32)

function NewGame()
--CODE TO START NEW GAME
end

C#:

public class LuaWrapper
{
    public void Initialize()
    {
        lua = new Lua();
        lua.RegisterFunction("CreateButton", this,
           this.GetType().GetMethod("CreateButton"));

        lua.DoFile("Data/Menus/Main.lua");
    }

    public void CreateButton(string window, string functionName, string text,
         float posx, float posy, float width, float height)
    {
        ButtonControl button = new ButtonControl();
        button.Bounds = new UniRectangle(posx, posy, width, height);
        button.Text = text;
        LuaFunction f = lua.GetFunction(functionName); // <-- RETURNS NULL ?

        ButtonPressEvent pressEvent = new ButtonPressEvent(f);
        button.Pressed += new EventHandler(pressEvent.button_Pressed);

        WindowDictionary[window].Children.Add(button);
    }
}

class ButtonPressEvent
{
    LuaFunction function;

    public ButtonPress(LuaFunction function)
    {
        this.function = function;
    }

    public void button_Pressed(object sender, EventArgs e)
    {
        function.Call();
    }
}

一切都很好,直到按下按钮并尝试调用相关函数。在ButtonPress类中,它会抛出Null Reference Exception错误。我已经使用断点发现问题是

LuaFunction f = lua.GetFunction(functionName);

返回Null。

注意:我也尝试过

LuaFunction f = lua.GetFunction("NewGame");

结果相同。

感谢阅读,希望有人能帮助指出我的错误。

点赞
用户1076553
用户1076553

我有一个想法,尝试改变 Lua 文件的顺序。我猜在执行函数之前创建按钮,是这个问题的原因吗?我不确定,但这似乎已经解决了这个问题。

Lua:

function NewGame()
-- 代码以开始新游戏
end

CreateButton( "mainmenu", "NewGame", "新游戏", 50, 120, 150, 32)
2012-09-01 13:55:13