Receive any notifications when calling undefined function in lua

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 the Lua code:

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

Now my question is:

The CreateWindow will return an object named win , and the resize function is undefined. How to get notified when I call undefined function in Lua?

The notification must contain the string "resize" and arguments 800,600 . I want to change the source to map the undefined function to a callback function, but it is incorrect.

+4
source share
1 answer

How to get notified when I call the undefined function in lua.

No. Not the way you understand it.

You can move the __index metamethod to your registered "WindowUI" metatable (* groan *). Your metamethod will only receive user data on which it was called, and the key that was used.

But you cannot distinguish a function call and just access a member variable, since Lua does not distinguish between them. If you return a function from your metamethod, and the user invokes a function call operator when returning from the metamethod, then it will be called. Otherwise, they get a function with which they will match. They can store it, transmit it, call it later, whatever. This value is just like any other.

+2
source

Source: https://habr.com/ru/post/1441716/


All Articles