从纯Lua创建新的空用户数据 [英] Create new empty userdata from pure Lua

查看:137
本文介绍了从纯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, the setmetatable function may only be used on objects of table type. The newproxy function circumvents that limitation by creating a zero-size userdata and setting either a new, empty metatable on it or using the metatable of another newproxy 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屋!

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