Birk
Birk

Reputation: 211

How to print all values in a Lua table?

If I have a table like this, how would I print all the values?

local Buyers = {
    {[Name] = "Birk", [SecName] = "Birk2nd", [ThirdName] = "Birk3nd"},
    {[Name] = "Bob", [SecName] = "Bob2nd", [ThirdName] = "Bob3nd"},
}

It should end up printing:

First Name: Birk
Second Name: Birk2nd
Third Name: Birk3nd

FirstName: Bob
Second Name: Bob2nd
Third Name: Bob3nd

Upvotes: 2

Views: 5776

Answers (2)

Foxie Flakey
Foxie Flakey

Reputation: 420

what i can think of

local Buyers = {
  {["Name"] = "Birk", ["SecName"] = "Birk2nd", ["ThirdName"] = "Birk3nd"},
  {["Name"] = "Bob", ["SecName"] = "Bob2nd", ["ThirdName"] = "Bob3nd"},
}

for _, person in pairs(Buyers) do
  print("First name: "..person.Name)
  print("Second name: "..person.SecName)
  print("Third name: "..person.ThirdName)
  print()
end

Upvotes: 3

Alexander Mashin
Alexander Mashin

Reputation: 4539

For your case, like this:

local function serialise_buyer (buyer)
    return ('First Name: ' .. (buyer.Name or '')) .. '\n'
        .. ('Second Name: ' .. (buyer.SecName or '')) .. '\n'
        .. ('Third Name: ' .. (buyer.ThirdName or '')) .. '\n'
end

local Buyers = {
    {Name = "Birk", SecName = "Birk2nd", ThirdName = "Birk3rd"},
    {Name = "Bob", SecName = "Bob2nd", ThirdName = "Bob3rd"},
}

for _, buyer in ipairs (Buyers) do
    print (serialise_buyer (buyer))
end

A more generic solution, with sorting:

local sort, rep, concat = table.sort, string.rep, table.concat

local function serialise (var, sorted, indent)
    if type (var) == 'string' then
        return "'" .. var .. "'"
    elseif type (var) == 'table' then
        local keys = {}
        for key, _ in pairs (var) do
            keys[#keys + 1] = key
        end
        if sorted then
            sort (keys, function (a, b)
                if type (a) == type (b) and (type (a) == 'number' or type (a) == 'string') then
                    return a < b
                elseif type (a) == 'number' and type (b) ~= 'number' then
                    return true
                else
                    return false
                end
            end)
        end
        local strings = {}
        local indent = indent or 0
        for _, key in ipairs (keys) do
            strings [#strings + 1]
                = rep ('\t', indent + 1)
               .. serialise (key, sorted, indent + 1)
               .. ' = '
               .. serialise (var [key], sorted, indent + 1)
        end
        return 'table (\n' .. concat (strings, '\n') .. '\n' .. rep ('\t', indent) .. ')'
    else
        return tostring (var)
    end
end

local Buyers = {
    {Name = "Birk", SecName = "Birk2nd", ThirdName = "Birk3rd"},
    {Name = "Bob", SecName = "Bob2nd", ThirdName = "Bob3rd"},
    [function () end] = 'func',
    [{'b', 'd'}] = {'e', 'f'}
}
print (serialise (Buyers, true))

Upvotes: 1

Related Questions