How do I display array elements in Lua?

前端 未结 3 916
Happy的楠姐
Happy的楠姐 2021-01-14 03:35

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

3条回答
  •  失恋的感觉
    2021-01-14 03:51

    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
    

提交回复
热议问题