通过连接到字符串将Lua表显示到控制台

时间:2012-07-29 09:06:53

标签: lua lua-table

我想知道是否可以在控制台中显示表格。类似的东西:

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

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

然而,这显然是错误的,因为我收到关于它无法连接表值的错误。有解决方法吗?

提前多多谢谢!

2 个答案:

答案 0 :(得分:4)

要将类似数组的表转换为字符串,请使用table.concat

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

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

答案 1 :(得分: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)