如何找出lua中对象的所有属性? [英] how to find out all properties of an object in lua?

查看:1469
本文介绍了如何找出lua中对象的所有属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法获取所有非零参数/属性 一个物体?我发现了这一点:getmetadata(self.xxxx),而我正在寻找类似的东西:getalldata(self).

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).

我目前正在从事涉及lua的项目.不幸的是,没有完整的参考,我必须使用预编译的东西.

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.

推荐答案

我将假设当您指代对象"时,您的意思是带有__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.

如果对象结构是由表构成的(即所有__indexes都是表),则可以解析它们"以获得所有属性和继承的属性.

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.

如果您具有__index的功能,那么您提出的要求是不可能的;无法获得函数返回非零值的值列表".

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:

function getAllData(t, prevData)
  -- if prevData == nil, start empty, otherwise start with prevData
  local data = prevData or {}

  -- copy all the attributes from t
  for k,v in pairs(t) do
    data[k] = data[k] or v
  end

  -- get t's metatable, or exit if not existing
  local mt = getmetatable(t)
  if type(mt)~='table' then return data end

  -- get the __index from mt, or exit if not table
  local index = mt.__index
  if type(index)~='table' then return data end

  -- include the data from index into data, recursively, and return
  return getAllData(index, data)
end

但是请记住,如果您的任何__index es是一个函数,则无法获取所有属性.至少不是来自Lua.

But remember, if any of your __indexes is a function, there is no way to get all the properties; at least not from Lua.

这篇关于如何找出lua中对象的所有属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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