【问题标题】:Lua variable as a function callLua 变量作为函数调用
【发布时间】:2017-01-15 02:43:35
【问题描述】:

我需要在 lua 中定义一些变量,这些变量在访问时会导致调用 C++ 函数:

Lua:
var rootname = root.name; // 'root' acts as a call to c++ function defined below

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

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

在 Lua 中可以吗?

【问题讨论】:

  • 是的。检查 lua api。
  • 访问root 时,您正在访问索引root_G 表。你想要做的已经可以在 vanilla Lua 中实现了。

标签: function properties lua


【解决方案1】:

是的,您可以这样做。这实际上是 Lua 最常见的用例之一。虽然正确的 Lua 语法应该是 local a = prop(),如果你希望 a 为 5。

阅读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

【讨论】:

  • 对,但在你的情况下,我必须添加一个括号,但我想避免这种情况
  • 如果你不想直行,你可以到处走。在具有元表集的单独环境中运行您的脚本。然后,您可以读取未初始化的全局变量,并将其转换为对本机函数的调用。
  • 我已经添加了更多细节,以便您更清楚地了解我需要什么,请看一下
  • 您可以在“根”表而不是全局环境表上设置相同的元表。
【解决方案2】:

设置 _G 的元表可能不是“Lua 最佳实践”的一部分,但您可以这样做:

setmetatable(_G, {
  __index = function(t, k)
    if k == "root" then
      return root_function() -- Call your C function here.
    end
    return rawget(t, k)
  end
})

-- This function is just for a quick test. Call C function instead of this.
function root_function()
  print("in root_function")
  return { name = "hello" }
end
--

-- Test
rootname = root.name
print(rootname) -- Prints "hello"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-08
    • 1970-01-01
    • 2013-02-13
    相关资源
    最近更新 更多