加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

lua函数引用可以用作表键吗?

发布时间:2020-12-15 00:16:45 所属栏目:大数据 来源:网络整理
导读:这是一个Lua新手.我可以将函数引用存储为Lua表中的键吗?与此类似的东西: local fn = function() print('hello') endlocal my_table = {}my_table[fn] = 123 这似乎工作正常,但我不知道我是否可以依赖函数引用的唯一性. Lua可以在超出范围时重用函数引用吗
这是一个Lua新手.我可以将函数引用存储为Lua表中的键吗?与此类似的东西:
local fn = function() print('hello') end
local my_table = {}
my_table[fn] = 123

这似乎工作正常,但我不知道我是否可以依赖函数引用的唯一性. Lua可以在超出范围时重用函数引用吗?这会产生任何问题,还是由于某种原因被认为是不好的做法?

解决方法

是啊.我在lua遇到过的最好的事情之一是作为引用属性的东西.

您在表格中使用密钥的方式没有任何问题.

从Lua PiL起

Tables in Lua are neither values nor variables; they are objects.You may think of a table as a dynamically allocated object; your program only manipulates references (or pointers) to them. There are no hidden copies or creation of new tables behind the scenes.

在您的示例中,您尚未向函数传递任何参数,因此基本上,在您的情况下,在程序中将函数作为引用将毫无用处.另一方面,这样的事情:

fn1 = function(x) print(x) end
fn2 = function(x) print("bar") end
t[fn1] = "foo"
t[fn2] = "foo"
for i,v in pairs(t) do i(v) end

确实有它的用途.

Can Lua reuse function references once they are out of scope?

只要你的父表在范围内,是的.由于表是创建和操作但未复制的,因此不可能从表索引内存中弃用函数引用.我会在实际尝试之后编辑这个答案.

Can this create any issues or is it considered a bad practice due to some reason?

这被认为是一种不好的做法,因为熟悉其他语言的用户,如C,python等,在阅读表时往往会考虑数组.在lua你没有这样的担忧,程序将完美.

I don’t know if I can rely on the uniqueness of the function references.

为什么?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读