从纯 Lua 创建新的空用户数据 [英] Create new empty userdata from pure Lua
问题描述
我想我在 Lua 中的某个地方看到了一个可以返回新用户数据的本机函数.它存在吗?是否可以从普通的 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屋!