微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何打印 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

解决方法

对于您的情况,如下所示:

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,indent + 1)
               .. ' = '
               .. serialise (var [key],indent + 1)
        end
        return 'table (\n' .. concat (strings,'\n') .. '\n' .. rep ('\t',indent) .. ')'
    else
        return tostring (var)
    end
end

local Buyers = {
    {Name = "Birk",[function () end] = 'func',[{'b','d'}] = {'e','f'}
}
print (serialise (Buyers,true))
,

我能想到什么

local Buyers = {
  {["Name"] = "Birk",["SecName"] = "Birk2nd",["ThirdName"] = "Birk3nd"},{["Name"] = "Bob",["SecName"] = "Bob2nd",["ThirdName"] = "Bob3nd"},person in pairs(Buyers) do
  print("First name: "..person.Name)
  print("Second name: "..person.SecName)
  print("Third name: "..person.ThirdName)
  print()
end

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。