How do I display array elements in Lua?

徘徊边缘 提交于 2019-12-08 02:50:15

问题


I'm having an issue displaying the elements of an array in Lua programming language. Basically, i created an array with 3 elements, and i'm trying to display its contents in a for loop on the corona sdk emulator. What happens is that if i display the individual array elements (without the loop), they display fine; as soon as I put them in a for loop, nothing shows up on the screen anymore

this is my code:

myText = {"hello", "world", "there"}

for i = 1, myText do
     local myText = display.newText( myText[i], 0, 0, native.systemFont, 35 )
end  

回答1:


Here is a function I wrote to list the items in a table (corona calls arrays as "tables"). It is similar to PHP's print_r, so I called it print_r

You can call it as:

print_r(myTable)

Function:

function print_r(arr, indentLevel)
    local str = ""
    local indentStr = "#"

    if(indentLevel == nil) then
        print(print_r(arr, 0))
        return
    end

    for i = 0, indentLevel do
        indentStr = indentStr.."\t"
    end

    for index,value in pairs(arr) do
        if type(value) == "table" then
            str = str..indentStr..index..": \n"..print_r(value, (indentLevel + 1))
        else 
            str = str..indentStr..index..": "..value.."\n"
        end
    end
    return str
end



回答2:


What happens when you change your loop to this:

for i = 1, #myText do
    local myText = display.newText( myText[i], 0, 0, native.systemFont, 35 )
end

Or this:

for i, v in ipairs(myText) do
    local myText = display.newText( v, 0, 0, native.systemFont, 35 )
end



回答3:


Why not just print the table in "table.concat" function?

myText = {"hello", "world", "there"}
print(table.concat(myText,", "))

hello, world, there



来源:https://stackoverflow.com/questions/7274380/how-do-i-display-array-elements-in-lua

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!