Lua变量作为函数调用

时间:2016-09-07 11:59:49

标签: function properties lua

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

[[:space:]]*

Lua可以吗?

2 个答案:

答案 0 :(得分:0)

是的,你可以做那样的事情。这实际上是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

答案 1 :(得分:0)

设置_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"