将Lua表格显示到控制台,通过将其连接成字符串。

3

我想知道是否可以在控制台中显示表格,类似于:

player[1] = {}
player[1].Name   = { "Comp_uter15776", "maciozo" }

InputConsole("msg Player names are: " .. player[1].Name)

然而,这显然是错误的,因为我收到了关于无法连接表值的错误。有没有解决这个问题的方法?提前谢谢!
2个回答

4
把类数组的表转换为字符串,可以使用table.concat:
InputConsole("msg Player names are: " .. table.concat(player[1].Name, " "))

第二个参数是放置在每个元素之间的字符串;默认为空字符串 ""

非常感谢,furq!正是我需要的 :) - Talisman

1

為了讓您更輕鬆地處理這個問題...我建議您也給內部表命名元素。當您需要讀取對某些目的有意義的特定表格值時,這會使上面的代碼更易於閱讀。

-- this will return a new instance of a 'player' table each time you call it.  
-- if you need to add or remove attributes, you only need to do it in one place.
function getPlayerTable()
    return {FirstName = "", LastName = ""}
end

local players = {}

local player = getPlayerTable()
player.FirstName = "Comp_uter15776"
player.LastName = "maciozo"
table.insert(players, player)

... more code to add players ...

local specific_player = players[1]
local specific_playerName = specific_player.FirstName.. 
                            " ".. specific_player.LastName
InputConsole("msg Some message ".. specific_playerName)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接