如何查找 Corona SDK 显示对象 Lua 表中的所有条目?

我按照这篇 Corona SDK 文档中的教程

我正在尝试打印所有条目和子表中的条目,以及那些子表中的条目,从一个显示对象中。

在 Corona SDK 中,显示对象是一个 Lua 表,所以我尝试了基本的事情,如教程中所列出的。

for k,v in pairs(myTable) do
    print( k,v )
end

还有一个更复杂的函数,应该输出所有子表,即:

local function printTable( t )

    local printTable_cache = {}

    local function sub_printTable( t, indent )

        if ( printTable_cache[tostring(t)] ) then
            print( indent .. "*" .. tostring(t) )
        else
            printTable_cache[tostring(t)] = true
            if ( type( t ) == "table" ) then
                for pos,val in pairs( t ) do
                    if ( type(val) == "table" ) then
                        print( indent .. "[" .. pos .. "] => " .. tostring( t ).. " {" )
                        sub_printTable( val, indent .. string.rep( " ", string.len(pos)+8 ) )
                        print( indent .. string.rep( " ", string.len(pos)+6 ) .. "}" )
                    elseif ( type(val) == "string" ) then
                        print( indent .. "[" .. pos .. '] => "' .. val .. '"' )
                    else
                        print( indent .. "[" .. pos .. "] => " .. tostring(val) )
                    end
                end
            else
                print( indent..tostring(t) )
            end
        end
    end

    if ( type(t) == "table" ) then
        print( tostring(t) .. " {" )
        sub_printTable( t, "  " )
        print( "}" )
    else
        sub_printTable( t, "  " )
    end
end

但是,这两种方式都无法打印出这些表中的所有条目。如果我创建一个简单的矩形,并尝试使用任一函数,我只会得到两个表,但我知道那里还有更多的内容:

local myRectangle = display.newRect( 0, 0, 120, 40 )
for k,v in pairs(myRectangle) do
    print( k,v ) -- 输出 "_class table, _proxy userdata"
end
print( myRectangle.x, myRectangle.width ) -- 但这输出 "0, 120"

-- 但是,如果我将一些东西添加到表中,那么循环也会找到它,例如:

local myRectangle = display.newRect( 0, 0, 120, 40 )
myRectangle.secret = "hello"
for k,v in pairs(myRectangle) do
    print( k,v ) -- 输出 "_class table, _proxy userdata, secret hello"
end

那么,如何打印出显示对象中包含的所有内容?显然,这两种方法都无法获取主显示对象表中的条目。

点赞
用户1442917
用户1442917

通常情况下你不能,因为表格可能会有一个元表,该元表将为“按需” 字段生成结果。在这种情况下,你得到的是一个 ShapeObject 类型的对象,它提供了像 fillpathsetFillColor 等方法,但是这些方法被隐藏在 userdata 对象的后面。它还提供了继承功能,因此您可以查询“属于”其他类的某些字段。您可以使用 pairs/ipairs 来获取表格中的键列表,这就是您在示例中获取的内容(并设置 secret 添加了一个新的键到表格中)。

2019-12-13 03:28:46
用户5331361
用户5331361

关于显示对象的属性(非方法) - 在 Corona 中,显示对象具有特殊的属性 displayObject._properties 文档

_properties 将返回一个字符串,因此您有两种打印它的方法:

local myRectangle = display.newRect( 0, 0, 120, 40 )

-- 方法 1:
-- 在此处美化以使 json 更易于阅读
local json = require("json")
print("myRectangle._properties: ", json.prettify( myRectangle._properties ) )

-- 方法 2:
local json = require("json")
local myRectangleProps = json.decode(myRectangle._properties) -- 这里我省略了错误处理,因为不应该有任何错误
for k,v in pairs(myRectangleProps) do
    print( k,v ) -- 打印 x 0、width 120 等等
end
2020-01-08 12:03:49