Talisman
Talisman

Reputation: 388

Displaying Lua tables to console by concatenating to string

I was wondering whether it is possible to display tables in the console. Something like:

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

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

However, this is obviously wrong as I receive the error about it not being able to concatenate a table value. Is there a workaround for this?

Much thanks in advance!

Upvotes: 3

Views: 448

Answers (2)

Mike Corcoran
Mike Corcoran

Reputation: 14565

to make life easier on yourself for this... i'd recommend naming elements in the inner tables as well. this makes the code above easier to read when you need to get at specific values in a table that are meaningful for some purpose.

-- 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)

Upvotes: 1

furq
furq

Reputation: 5788

To turn an array-like table into a string, use table.concat:

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

The second argument is the string placed between each element; it defaults to "".

Upvotes: 4

Related Questions