如何仅用名字而非括号调用Lua中的函数?

更新于
2026-09-16 18:40:38
42阅读来源:SEO教程
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计442个文字,预计阅读时间需要2分钟。

如何仅用名字而非括号调用Lua中的函数?

在Lua中,为了确保变量`asdf`每次使用时都是最新的值,可以使用局部变量和闭包来实现。以下是一个简单的示例:

lua-- 定义一个函数,它返回一个新的闭包function createUpdater() local value=0 -- 初始化局部变量value

-- 返回一个闭包,闭包可以访问并修改局部变量value return function() value=value + 1 -- 更新value的值 return value -- 返回更新后的value endend

-- 创建一个更新器local updater=createUpdater()

-- 每次调用updater时,都会更新value的值print(updater()) -- 输出1print(updater()) -- 输出2print(updater()) -- 输出3

在这个例子中,`createUpdater`函数创建并返回一个闭包,该闭包可以访问并修改`value`变量。每次调用`updater()`时,都会更新`value`的值,并返回更新后的结果。这样,每次使用`asdf`变量时,都能得到最新的值。

我期待使用像“asdf”这样的变量,而不是编写名称函数来检查它的返回(它会不时变化).这就是为什么“asdf”变量应该在我们每次使用(调用)它时更新它的值

如何仅用名字而非括号调用Lua中的函数?

请问在Lua有什么办法吗?

asdf == getFunction() --we define it here (...) --some code if asdf < 10 then ... --here we call the variable (so it should get/update again the result of getFunction())

谢谢

--we define it here local asdf = function () return getFunction() end --some code (...) --here we call the variable --(so it should get/update again the result of getFunction()) if asdf() < 10 then ...

UPD:
没有括号的解决方案

--we define it here asdf = nil setmetatable(_G, {__index = function(t, k) if k == 'asdf' then return getFunction() end end }) --some code (...) --here we call the variable --(so it should get/update again the result of getFunction()) if asdf < 10 then ...

本文共计442个文字,预计阅读时间需要2分钟。

如何仅用名字而非括号调用Lua中的函数?

在Lua中,为了确保变量`asdf`每次使用时都是最新的值,可以使用局部变量和闭包来实现。以下是一个简单的示例:

lua-- 定义一个函数,它返回一个新的闭包function createUpdater() local value=0 -- 初始化局部变量value

-- 返回一个闭包,闭包可以访问并修改局部变量value return function() value=value + 1 -- 更新value的值 return value -- 返回更新后的value endend

-- 创建一个更新器local updater=createUpdater()

-- 每次调用updater时,都会更新value的值print(updater()) -- 输出1print(updater()) -- 输出2print(updater()) -- 输出3

在这个例子中,`createUpdater`函数创建并返回一个闭包,该闭包可以访问并修改`value`变量。每次调用`updater()`时,都会更新`value`的值,并返回更新后的结果。这样,每次使用`asdf`变量时,都能得到最新的值。

我期待使用像“asdf”这样的变量,而不是编写名称函数来检查它的返回(它会不时变化).这就是为什么“asdf”变量应该在我们每次使用(调用)它时更新它的值

如何仅用名字而非括号调用Lua中的函数?

请问在Lua有什么办法吗?

asdf == getFunction() --we define it here (...) --some code if asdf < 10 then ... --here we call the variable (so it should get/update again the result of getFunction())

谢谢

--we define it here local asdf = function () return getFunction() end --some code (...) --here we call the variable --(so it should get/update again the result of getFunction()) if asdf() < 10 then ...

UPD:
没有括号的解决方案

--we define it here asdf = nil setmetatable(_G, {__index = function(t, k) if k == 'asdf' then return getFunction() end end }) --some code (...) --here we call the variable --(so it should get/update again the result of getFunction()) if asdf < 10 then ...