【发布时间】:2020-04-06 11:25:51
【问题描述】:
我关注了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
那么,如何打印显示对象中包含的所有内容?显然这两种方法都没有得到主显示对象表中的条目。
【问题讨论】: