在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中调用未定义的函数时如何收到通知?
解决方法
How do I get a notification when I call an undefined function in lua.
你没有.不是你的意思.
您可以将an __index
metamethod挂钩到您注册的“WindowUI”Metatable(*呻吟*)上.您的Metamethod将只获取调用它的用户数据和使用的密钥.
但是你无法区分函数调用和简单地访问成员变量,因为Lua不区分它们.如果从元方法返回一个函数,并且用户在元方法返回时调用函数调用操作符,则会调用它.否则,他们会得到一个他们认为合适的功能.他们可以存储它,传递它,稍后调用它,无论如何.这是一个价值,就像其他任何一样.