lua中如何找出对象的所有属性?
有没有办法获取所有非零参数/属性 一个物体的?我发现了这个:getmetadata(self.xxxx)
,我正在寻找类似的东西:getalldata(self)。
我目前正在开发一个涉及lua的项目。不幸的是,没有完整的参考,我必须使用预编译的东西。
我希望你能够理解我想说的。
Is there any way of getting all the non-nil parameters / properties
of an object? I found this: getmetadata(self.xxxx)
and i am looking for something like: getalldata(self).
I'm currently working on a project where lua is involved. Unfortunately, there is no complete reference and i have to use precompiled stuff.
I hope you are able to understand what I am trying to say.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我假设当你提到“对象”时,你的意思是“带有指向其他表的
__index
元表的 lua 表”。如果不是这种情况,这个答案对你没有帮助。如果您的对象结构是由表组成的(也就是说,所有
__indexes
都是表),那么您可以“解析它们”以获得所有属性和继承的属性。如果你有任何函数作为
__index
那么你的要求是不可能的;无法获取“函数返回非零值的值列表”。在第一种情况下,代码将如下所示:
但请记住,如果您的任何
__index
是一个函数,则无法获取所有属性;至少不是来自 Lua。I'm going to assume that when you are referring to "objects" you are meaning "lua tables with an
__index
metatable pointing to other tables". If that is not the case, this answer will not help you.If your object structure is made with tables (this is, all
__indexes
are tables) then you can "parse them up" to obtain all the properties and inherited properties.If you have any function as
__index
then what you ask is impossible; there's no way to get the "list of values for which a function returns a non-nil value".In the first case, the code would look like this:
But remember, if any of your
__index
es is a function, there is no way to get all the properties; at least not from Lua.我编写了自己的 printObject 代码..这就是
这与之前使用的帖子相反的方法。
遍历表中的所有键值对。如果一个索引的值是一张表,则遍历这张表。
这个解决方案不会像其他帖子那样获得向上的元表
I wrote my own printObject code.. here it is
This is the opposite approach then the post before used.
Go through all key value pairs in the table. If the value of one index is a table, go through this table.
This solution will not get the upwards metatables like the other post did
我相信对象只是一个表,因此您应该能够像任何其他表一样迭代属性:
I believe objects are just a table, so you should be able to iterate over the properties as any other table: