如何在 Lua 中显示数组元素? [英] How do I display array elements in Lua?

查看:19
本文介绍了如何在 Lua 中显示数组元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在用 Lua 编程语言显示数组元素时遇到问题.基本上,我创建了一个包含 3 个元素的数组,并且我试图在 corona sdk 模拟器上的 for 循环中显示其内容.发生的情况是,如果我显示单个数组元素(没有循环),它们显示正常;一旦我将它们放入 for 循环中,屏幕上就不再显示任何内容

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

这是我的代码:

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

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

推荐答案

这是我编写的一个函数,用于列出表格中的项目(corona 将数组称为表格").类似于PHP的print_r,所以我叫它print_r

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

您可以将其称为:

print_r(myTable)

功能:

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.."	"
    end

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

这篇关于如何在 Lua 中显示数组元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆