[英]Lua Metatables for function call trapping
I'm trying to use Lua Metatables to make a prettier interface to some internal C++ functions. 我正在尝试使用Lua Metatables为一些内部C ++函数建立一个漂亮的接口。
Here's my code that's working so far. 到目前为止,这是我的代码。 (
my.get
and my.set
are implemented in C++) (
my.get
和my.set
在C ++中实现)
function setDefault(t)
local mt = {
__index = function(tab,k) return my.get(t,k) end,
__newindex = function(tab,k,v) return my.set(t,k,v) end
}
_G[t] = {}
setmetatable(_G[t],mt)
end
setDefault("LABEL")
LABEL.Text = "wibble" -- evaluates as my.set("LABEL","Text","wibble")
foo = LABEL.Text -- foo = my.get("LABEL","Text")
Fine so far. 到目前为止很好。 The next bit I want to make work is function calls on the table, like this:
我要处理的下一点是表上的函数调用 ,如下所示:
LABEL.Flash(500) --must evaluate my.execute("LABEL","Flash", 500)
I know this invokes my.get("LABEL","Flash")
— and I can make that return a C++ function (using lua_pushcfunction
), but when the C++ function is called, it's missing the LABEL and Flash parameters. 我知道这会调用
my.get("LABEL","Flash")
,并且我可以使它返回一个C ++函数(使用lua_pushcfunction
),但是当调用C ++函数时,它缺少LABEL和Flash参数。
Here's the C++ snippet of my.get
. 这是
my.get
的C ++代码段。
static int myGet(lua_State * l)
{
std::string p1(luaGetString(l, 1)); // table
std::string p2(luaGetString(l, 2)); // 'method'
if (isMethod(p1,p2))
{
lua_pushcfunction(l, myExec);
lua_pushvalue(l, 1); // re-push table
lua_pushvalue(l, 2); // re-push method
return 3;
}
else
{
// do my.get stuff here.
}
}
With a small change, I've got something that works: Push a C closure instead of a C function . 进行一点改动,就可以使用:推动C 闭包而不是C 函数 。
if (isMethod(p1,p2))
{
lua_pushvalue(l, 1); // re-push table
lua_pushvalue(l, 2); // re-push method
lua_pushcclosure(l, myExecClosure,2);
return 1;
}
myExecClosure
is like myExec
, but it reads the first two parameters via upvalues (eg luaupvaluindex(1)
) rather than from stack indexes 1 and 2. myExecClosure
类似于myExec
,但是它通过升值(例如luaupvaluindex(1)
)而不是从堆栈索引1和2读取前两个参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.