Question

In C++ code:

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

In Lua code:

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

Now my question is:

Function CreateWindow will return a object named win and the function resize is not defined. How do I get a notification when I call an undefined function in Lua?

The notification shall include the string "resize" and the arguments 800,600. I want to modify the source to map the undefined function onto the callback function but it is incorrect .

Était-ce utile?

La solution

How do I get a notification when I call an undefined function in lua.

You don't. Not in the way that you mean it.

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top