Lua 变量作为函数调用

我需要在 Lua 中定义一些变量,当访问它们时会调用 C++ 函数:

Lua:
var rootname = root.name; // 'root' 作为下面定义的 C++ 函数的调用

C++:
class Node
{
    std::string name;
}

Node * root()
{
   return MyNodeGraph->GetRoot();
}

这在 Lua 中是否可行?

点赞
用户2858170
用户2858170

是的,你可以做类似的事情。实际上,这是 Lua 中最常见的用例之一。尽管如果你想让 a 成为 5,正确的 Lua 语法应该是 local a = prop()

阅读https://www.lua.org/manual/5.3/https://www.lua.org/pil/24.html https://www.lua.org/pil/25.html https://www.lua.org/pil/26.html

2016-09-07 14:07:46
用户2138872
用户2138872
给 \_G 设置元表可能不是“Lua 最佳实践”的一部分,但是在这里我们可以这样做:

setmetatable(_G, { __index = function(t, k) if k == "root" then return root_function() -- 在这里调用你的 C 函数。 end return rawget(t, k) end })

-- 这个函数只是用于快速测试。实际使用时应该调用 C 函数而不是这个函数。 function root_function() print("in root_function") return { name = "hello" } end --

-- 测试 rootname = root.name print(rootname) -- 输出 "hello"

```

2016-09-09 06:43:42