循环输出数组中的项目

我是 Lua 的新手,我有一个打印数组值的问题。

在谷歌搜索后我找到了这个,但它只打印出数组中的最后一个元素 'armor'。我做错了什么?还有,我怎样能在每个元素后面加上逗号?

local items = {'bread', 'shield', 'boots', 'legs', 'armor'}

for i, item in ipairs(items) do
    text = item
end

William:Speak("我对以下物品感兴趣:".. text)
点赞
用户3335551
用户3335551

你是在文本设置为bread、shield、boots、legs和armor之后才打印的。这就是为什么你只能看到“armor”的原因。你的迭代是正确的,但如果你想要列出所有这些,就要这样做...

local items = {'bread', 'shield', 'boots', 'legs', 'armor'}

for i, item in ipairs(items) do
    text = item
    William:speak("I am interested in the following: ".. text)
end

这样每次你循环时他都会讲话。

如果你想要它们在一个单独的字符串中,试试这个...

local items = {'bread', 'shield', 'boots', 'legs', 'armor'}

for i, item in ipairs(items) do
    text = text .. item
end
William:speak("I am interested in the following: ".. text)

我还没有测试过,但它可能会解决你的问题

local items = {'bread', 'shield', 'boots', 'legs', 'armor'}

for i, item in ipairs(items) do
    if item == items.length - 1 then
        text = text .. item
    else
        text = text .. item .. ", "
    end
end
William:speak("I am interested in the following: ".. text)
2015-08-05 19:05:29
用户5190890
用户5190890

另一种更简洁的使用逗号连接的方法是([来源](http://lua-users.org/wiki/SplitJoin)):

local items = {'bread', 'shield', 'boots', 'legs', 'armor'}
conc = table.concat(items, ",")

William:speak("我对以下内容感兴趣:".. conc)
2015-08-05 19:17:10