我正在评估要嵌入到 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
所以我执行变量读取回调,然后执行变量的 puts 值。
问题:我可以用 Lua 做这个吗?如果可以,怎么做?我没有找到任何直接的话题。唯一引起我注意的是关于调试 Lua,其中调试器(调试 API)将监视变量的值。但我不想关注值(value)的变化,而是关注值(value)的获取。
最佳答案
我认为在 lua 中最接近这个的是 __index
metamethod在 table 上(如果您只想触发一个,请检查特定键)。
如果需要,这甚至可以在默认全局表 (_G
) 上完成。
关于c++ - 跟踪 Lua 中的变量以读取访问权限以启动用户定义的 C++ 方法/函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24933901/