从纯Lua创建新的空用户数据 [英] Create new empty userdata from pure Lua
问题描述
我想我在Lua的某个地方看到了一个本机函数,可以返回新的userdata.是否存在?是否可以通过普通的Lua脚本创建自定义用户数据?
I think I saw somewhere a native function in Lua that can return a new userdata. Does it exist? Is it possible to create custom userdata from normal Lua script?
推荐答案
您可能会想到newproxy
来自: http://lua-users.org/wiki/HiddenFeatures
newproxy
是Lua库中不受支持且未记录的功能 图书馆.从Lua代码中,只能使用setmetatable
函数 在表类型的对象上.newproxy
函数规避了 通过创建大小为零的用户数据并设置新的, 它上的空元表或使用另一个newproxy
的元表 实例.然后,我们可以自由地从Lua修改元表.这是 从Lua创建代理对象的唯一方法 元方法,例如__len
.
newproxy
is an unsupported and undocumented function in the Lua base library. From Lua code, thesetmetatable
function may only be used on objects of table type. Thenewproxy
function circumvents that limitation by creating a zero-size userdata and setting either a new, empty metatable on it or using the metatable of anothernewproxy
instance. We are then free to modify the metatable from Lua. This is the only way to create a proxy object from Lua which honors certain metamethods, such as__len
.
对于__gc
元方法也很有用,因为当newproxy
实例变为免费时,它可以作为黑客获取回调的方法.
It was also useful for __gc
metamethods, as a hack to get a callback when the newproxy
instance becomes free.
该功能在Lua 5.1中存在,但在5.2中已删除.在Lua 5.2中,可以在大小为零的表上设置__gc
元方法,因此newproxy
的主要动力就消失了.
This feature was present in Lua 5.1, but removed in 5.2. In Lua 5.2, __gc
metamethods can be set on zero sized tables, so the main impetus for newproxy
went away.
这篇关于从纯Lua创建新的空用户数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!