在Lua中跟踪变量以读取访问以启动用户定义的C++方法/函数。

我正在评估嵌入式于 C++ 应用程序中的脚本语言解释器。我目前关注 TCL/cpptcl 和 Lua 。TCL 有一个很好的功能,使我能够“跟踪变量访问”。因此,每当我读取一个定义好的变量时,我的读取回调函数就会被触发:

int read_trace(const int& v, void *) {
  cout << "read trace triggered" << endl;
  return v;
}
...
void tclInterpreter() {
  std::cout << ": Starting TCL interpreter!" << std::endl;

  // new TCL
  Tcl::interpreter i;

  i.def_read_trace("tracedVar", "read", read_trace);

  // load the script
  ifstream script("helloworld.tcl");

  // run the script with the given arguments
  i.eval(script);
}

那么,如果我现在从我的 C++ 应用程序执行以下 TCL:

set tracedVar 10
for { set i 0 } { $i <= 5 } { incr i } {
  puts $tracedVar
}

我会收到输出:

read trace triggered
10
read trace triggered
10
read trace triggered
10
read trace triggered
10
read trace triggered
10
read trace triggered
10

因此,我得到了我的变量读取回调的执行,然后是 var 的 puts 值。

问题: 我是否可以在 Lua 中做到这一点?如果是,怎么做?我没有找到任何关于此的直接主题。唯一引起我注意的是关于调试 Lua 的内容,其中调试器(调试API)将监视变量的值。但我不想监视值的更改,而是想监视值的访问。

点赞
用户258523
用户258523

我认为在 Lua 中最接近这个的东西是在表格上的 __index 元方法(如果你只想在一个特定的键上触发,则需要检查该键)。

如果需要,甚至可以在默认的全局表格 (_G) 上执行此操作。

2014-07-24 13:02:55