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

问题描述 投票:1回答:1

我关注了this tutorial in Corona SDK documentation

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

在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 ) -- prints out "_class table, _proxy userdata"
end
print( myRectangle.x, myRectangle.width ) -- but this prints out "0, 120"

-- But if I were to add something to the table, then the loop finds that as well, e.g.

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

所以,如何打印显示对象中包含的所有内容?显然,这两种方法不会在主显示对象表中获取条目。

lua corona
1个回答
0
投票

通常,您不能这样做,因为您可能有一个与该表相关联的元表,该元表将“动态”生成字段的结果。在这种情况下,您会得到类似ShapeObject的东西,该对象提供了fillpathsetFillColor等方法,但是这些方法隐藏在userdata对象的后面。它还提供继承,因此您可以查询“属于”其他类的某些字段。您可以使用对/对来获取表中键的列表,这就是您在示例中获得的键(设置secret将向表中添加新键)。

© www.soinside.com 2019 - 2024. All rights reserved.