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

标签 c++ callback lua

我正在评估要嵌入到 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/

相关文章:

java - Java中的回调是同步的吗?

c++ - 模板函数在模板对象上执行成员回调而不提供它的实例

php - 使用像 filter_var_array() 这样的 PHP 过滤器函数有没有办法检查输入字符串的长度是否小于某个值

c++ - Qt 进程事件

c++ - 如何在 Visual Studio 中使用 g++ 编译器

c++ - 如何从 std::string 获取可写的 C 缓冲区?

error-handling - Lua : pcall() doesn't work with coroutine as expected

c++ - 跳过模板参数

lua - 检查目录是否存在于lua中?

data-structures - 如何在 Lua 中创建 HashMap<Int, Int[]> 的等效项