How do I display array elements in Lua?
Asked Answered
M

3

9

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  
Mackinaw answered 1/9, 2011 at 17:53 Comment(1)
Don't you mean for i = 1, #myText do ?Braynard
T
17

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

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

hello, world, there

Technician answered 1/5, 2018 at 5:9 Comment(0)
A
11

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
Abaxial answered 15/11, 2012 at 13:54 Comment(2)
That sir made my day, simple and elegant!Expertism
I'm having a devil of a time trying to debug a mod for Don't Starve Together: The LUA interpreter there throws a hissy fit every time I dare try to concatenate things like "boolean", "userdata", etc (as happens when print_r-ing all kinds of interesting tables). Is there any simple way to amend the above function? Do I have to write cases for every possible type?Samaria
V
10

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
Velamen answered 1/9, 2011 at 18:17 Comment(4)
I was missing the # sign in front of the array, that worked thank you very much for your help AlexMackinaw
Would it be possible to transform this into an answer?Immolate
phresnel, what do you mean? This is an answer.Velamen
@Velamen he probably meant: "accepted answer"Loosejointed

© 2022 - 2024 — McMap. All rights reserved.