如何仅通过写一个名字就能直接调用Lua中的函数而不使用括号?
- 内容介绍
- 文章标签
- 相关推荐
本文共计410个文字,预计阅读时间需要2分钟。
我期待使用像asdf这样的变量,而不是编写名称函数来检查它的返回值(它不会时常变化)。这就是为什么asdf变量应该在每次使用(调用)时更新它的值。在Lua中,您可以使用闭包来实现这一功能。
以下是一个使用Lua闭包实现的方法:
luafunction createUpdater(initialValue) local currentValue=initialValue return function() currentValue=currentValue + 1 -- 或者根据需要更新值 return currentValue endend
local asdf=createUpdater(0)
-- 使用asdfprint(asdf()) -- 输出:1print(asdf()) -- 输出:2
在这个例子中,`createUpdater`函数创建了一个闭包,它包含一个内部变量`currentValue`,该变量初始值由`initialValue`参数提供。每次调用闭包返回的函数时,`currentValue`都会更新,因此每次调用`asdf()`都会返回一个新的值。
我期待使用像“asdf”这样的变量,而不是编写名称函数来检查它的返回(它会不时变化).这就是为什么“asdf”变量应该在我们每次使用(调用)它时更新它的值请问在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 ...
本文共计410个文字,预计阅读时间需要2分钟。
我期待使用像asdf这样的变量,而不是编写名称函数来检查它的返回值(它不会时常变化)。这就是为什么asdf变量应该在每次使用(调用)时更新它的值。在Lua中,您可以使用闭包来实现这一功能。
以下是一个使用Lua闭包实现的方法:
luafunction createUpdater(initialValue) local currentValue=initialValue return function() currentValue=currentValue + 1 -- 或者根据需要更新值 return currentValue endend
local asdf=createUpdater(0)
-- 使用asdfprint(asdf()) -- 输出:1print(asdf()) -- 输出:2
在这个例子中,`createUpdater`函数创建了一个闭包,它包含一个内部变量`currentValue`,该变量初始值由`initialValue`参数提供。每次调用闭包返回的函数时,`currentValue`都会更新,因此每次调用`asdf()`都会返回一个新的值。
我期待使用像“asdf”这样的变量,而不是编写名称函数来检查它的返回(它会不时变化).这就是为什么“asdf”变量应该在我们每次使用(调用)它时更新它的值请问在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 ...

