带有轻量用户数据的Lua注册表和引用之间有什么区别? [英] What is the difference between Lua registry with light userdata and references?

查看:257
本文介绍了带有轻量用户数据的Lua注册表和引用之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,使用Lua C API,您可以将Lua值保存在注册表中,并在以后检索它.有多种方法可以执行此操作,您可以创建一个变量并将其指针用作注册表中的键,因为它始终是唯一的.您可以将指针作为轻量用户数据推送.

So with the Lua C API you can save a Lua value in the registry and retrieve it later. There are different ways to do it, you can create a variable and use it's pointer as the key in the registry as it's always unique. You would push the pointer as light userdata.

您还可以使用LuaL_ref(L, LUA_REGISTRYINDEX)创建参考.一个相对于另一个的优势是什么?何时使用引用以及何时使用指针?

You can also create a reference using LuaL_ref(L, LUA_REGISTRYINDEX). What is the advantage of one over the other? When to use references and when to use pointers?

还有引用,也称为引用,如果Lua垃圾回收器收集Lua值,注册表中的值是否为nil?如果Lua更新了Lua值,注册表中的值也会更改吗?

Also with references, as it is called a reference, if the Lua garbage collector collects the Lua value, will the value in the registry be nil? What if Lua updates the Lua value, will the value in the registry also change?

推荐答案

Lua注册表只是另一个lua表,可通过预定义的特殊"索引轻松访问.我想您不需要解释Lua表与light userdata有何不同.
只要您可以将注册表项存储在C/C ++端,如何索引注册表表就没有关系.为了方便起见,已经有函数(luaL_ref/luaL_unref)为您提供易于存储和移动的整数键.

Lua registry is just another lua table, easily accessible via predefined "special" index. I guess you don't need explanations on how Lua table is different from light userdata.
It doesn't really matter how you will index registry table, as long as you can store that key on C/C++ side. For your convenience there's already functions (luaL_ref/luaL_unref) giving you integer key that is easy to store and move around.

关于垃圾回收-规则始终相同.只要将值存储在未标记为弱表(注册表不是弱表)的表中,就不会清除该值.您必须从注册表中明确删除值.

About garbage collection - rules are always the same. As long as value is stored in table that wasn't marked as weak table (registry is not weak table), that value won't be cleared. You must explicitly remove value from the registry.

更改值将遵循正常的Lua规则.将新的不可变值分配给某个变量不会更改存储在注册表中的值,即注册表不会跟随对某个变量的更新.但是更改可变值(表等)的内容是可以的,因为注册表和变量将引用相同的值.

Changing value will obey normal Lua rules. Assigning new immutable value to some variable won't change value stored in registry, i.e. registry won't follow updates to some variable. But changing content of mutable value (table etc) is ok, since registry and variable will refer same value.

这篇关于带有轻量用户数据的Lua注册表和引用之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆