1

我正在尝试使用 Lua Metatables 为一些内部 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")

到目前为止还好。我想做的下一点是对表的函数调用,如下所示:

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

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

这是my.get.

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.
  }
}
4

1 回答 1

2

通过一个小小的改动,我得到了一些有用的东西:推送一个 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 读取前两个参数。

于 2015-08-12T15:59:52.773 回答