如何打印 Lua 表中的所有值?

假设我有这样一个表,如何打印出所有的值?

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

将会打印出以下内容:

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

FirstName: Bob
Second Name: Bob2nd
Third Name: Bob3nd
点赞
用户6632736
用户6632736

对于你的情况,可以像这样:

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

一个更通用的解决方案,带有排序:

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))
2020-12-29 02:50:48
用户13447666
用户13447666
我能想到的:

本地买家 = {
  {["姓名"] = "Birk", ["中间名"] = "Birk2nd", ["第三个名字"] = "Birk3nd"},
  {["姓名"] = "Bob", ["中间名"] = "Bob2nd", ["第三个名字"] = "Bob3nd"},
}

对于 _, 个人 在 ipairs(买家)做
  打印("名字:" .. 个人.姓名)
  打印("中间名:" .. 个人.中间名)
  打印("第三个名字:" .. 个人.第三个名字)
  打印()
结束
2020-12-29 07:00:01