Create new empty userdata from pure Lua

半世苍凉 提交于 2019-12-23 09:31:26

问题


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?


回答1:


You may be thinking of newproxy

From: http://lua-users.org/wiki/HiddenFeatures

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.

It was also useful for __gc metamethods, as a hack to get a callback when the newproxy instance becomes free.

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.




回答2:


Actually no, in pure Lua.

The type userdata is provided to allow arbitrary C data to be stored in Lua variables. … Userdata values cannot be created or modified in Lua, only through the C API. This guarantees the integrity of data owned by the host program.

link

If you embed luaVM in host C/C++ application, you can export some function to create userdata to Lua, but it's not a good practice. UD is designed to be a blackbox for Lua scripts.



来源:https://stackoverflow.com/questions/23592388/create-new-empty-userdata-from-pure-lua

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!