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

查看:117
本文介绍了如何在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  

推荐答案

这是我编写的用于列出表中项目的函数(电晕将数组称为表").它类似于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.."\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

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

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