Lua学习笔记-table转为字符串

时间:2023-01-07 15:34:52

1、将table中的成员进行连接,使其成为一个字符串,可以采用table.concat()方法。
例如:
a = {1,’a’,’b’,4}
print(table.concat(a))
打印出的结果是1ab4。
如果是print(table.concat(a,’,’))则打印的结果是1,a,b,4
2、将字符串转table
代码:

t={}
str="text"
str:gsub(".",function(c) table.insert(t,c) end)
function print_r ( t )  
    local print_r_cache={}
    local function sub_print_r(t,indent)
        if (print_r_cache[tostring(t)]) then
            print(indent.."*"..tostring(t))
        else
            print_r_cache[tostring(t)]=true
            if (type(t)=="table") then
                for pos,val in pairs(t) do
                    if (type(val)=="table") then
                        print(indent.."["..pos.."] => "..tostring(t).." {")
                        sub_print_r(val,indent..string.rep(" ",string.len(pos)+8))
                        print(indent..string.rep(" ",string.len(pos)+6).."}")
                    elseif (type(val)=="string") then
                        print(indent.."["..pos..'] => "'..val..'"')
                    else
                        print(indent.."["..pos.."] => "..tostring(val))
                    end
                end
            else
                print(indent..tostring(t))
            end
        end
    end
    if (type(t)=="table") then
        print(tostring(t).." {")
        sub_print_r(t," ")
        print("}")
    else
        sub_print_r(t," ")
    end
    print()
end
print_r(t)
print(#t)