4

在 C++ 代码中:

class CWindowUI {
  public CWindowUI(const char* title,int width,int height);
  .....
};

static int CreateWindow(lua_State *l)
{
    int          width,height;
    char        *title;
    CWindowUI  **winp, *win;

    name = (char *) luaL_checkstring(l, 1);
    width= lua_tounsigned(l, 2);
    height= lua_tounsigned(l, 3);

    win = new CWindowUI(title,width,height);
    if (win == NULL) {
        lua_pushboolean(l, 0);
        return 1;
    }

    winp = (CWindowUI **) lua_newuserdata(l, sizeof(CWindowUI *));
    luaL_getmetatable(l, "WindowUI");
    lua_setmetatable(l, -2);
    *winp = win;

    return 1;
}

在 Lua 代码中:

local win = CreateWindow("title", 480, 320);
win:resize(800, 600);

现在我的问题是:

函数CreateWindow将返回一个名为win且函数resize未定义的对象。在 Lua 中调用未定义函数时如何获得通知?

通知应包括字符串"resize"和参数800,600。我想修改源以将未定义的函数映射到回调函数,但它不正确。

4

1 回答 1

2

在 lua 中调用未定义函数时如何获得通知。

你没有。不是你的意思。

You can hook an __index metamethod onto your registered "WindowUI" metatable (*groan*). Your metamethod will only get the userdata it was called on and the key that was used.

But you cannot differentiate between a function call and simply accessing a member variable, since Lua doesn't differentiate between these. If you return a function from your metamethod, and the user invokes the function-call operator on the return from the metamethod, then it will be called. Otherwise, they get a function to play with as they see fit. They can store it, pass it around, call it later, whatever. It's a value, like any other.

于 2012-10-24T04:26:57.093 回答