gpt4 book ai didi

c++ - 用于函数调用捕获的 Lua 元表

转载 作者:行者123 更新时间:2023-11-30 03:50:14 25 4
gpt4 key购买 nike

我正在尝试使用 Lua Metatables 为一些内部 C++ 函数创建一个更漂亮的接口(interface)。

这是我目前运行的代码。 (my.getmy.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")

到目前为止还不错。接下来我要做的是在 table 上进行函数调用,如下所示:

LABEL.Flash(500) --must evaluate my.execute("LABEL","Flash", 500)

我知道这会调用 my.get("LABEL","Flash") — 我可以让它返回一个 C++ 函数(使用 lua_pushcfunction),但是当调用了 C++ 函数,它缺少 LABELFlash 参数。

这是 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.
}
}

最佳答案

通过一个小改动,我得到了一些有用的东西:推送一个 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 类似于 myExec,但它通过上值(例如 luaupvaluindex(1))而不是从堆栈索引读取前两个参数1 和 2。

关于c++ - 用于函数调用捕获的 Lua 元表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31968524/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com