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

我想知道是否可能在控制台中显示表格。就像这样:

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

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

然而,很明显这是错的,因为我收到了一个有关不能连接表格值的错误。有没有解决方法?

非常感谢!

点赞
用户1516484
用户1516484

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

InputConsole("msg 玩家名称为: " .. table.concat(player[1].Name, " "))

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

2012-07-29 09:33:08
用户1208078
用户1208078

为了让代码更易于阅读…我建议在内部表中也给元素命名。当你需要获取表中有意义的特定值时,这样做可以使上面的代码更易于阅读。

--每次调用它都会返回一个新的“player”表实例。
--如果需要添加或删除属性,只需在一个地方完成即可。
function getPlayerTable()
    return {FirstName = "", LastName = ""}
end

local players = {}

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

…更多代码添加玩家…

local specific_player = players[1]
local specific_playerName = specific_player.FirstName..
                            " " .. specific_player.LastName
InputConsole("msg Some message " .. specific_playerName)
2012-07-29 14:50:40