推荐参考1的法一的打印方法,因为“挺符合一般人的心里预期”~
顺便写一个math.clamp的实现
local print = print
local tconcat = table.concat
local tinsert = table.insert
local srep = string.rep
local type = type
local pairs = pairs
local tostring = tostring
local next = next
function print_lua_table (lua_table, indent)
if not lua_table or type(lua_table) ~= "table" then
return;
end
indent = indent or 0
for k, v in pairs(lua_table) do
if type(k) == "string" then
k = string.format("%q", k)
end
local szSuffix = ""
if type(v) == "table" then
szSuffix = "{"
end
local szPrefix = string.rep(" ", indent)
formatting = szPrefix.."["..k.."]".." = "..szSuffix
if type(v) == "table" then
print(formatting)
print_lua_table(v, indent + 1)
print(szPrefix.."},")
else
local szValue = ""
if type(v) == "string" then
szValue = string.format("%q", v)
else
szValue = tostring(v)
end
print(formatting..szValue..",")
end
end
end
function pt(lua_table)
print("print table: ")
print_lua_table (lua_table, 1)
end
function print_r(root)
local cache = { [root] = "." }
local function _dump(t,space,name)
local temp = {}
for k,v in pairs(t) do
local key = tostring(k)
if cache[v] then
tinsert(temp,"+" .. key .. " {" .. cache[v].."}")
elseif type(v) == "table" then
local new_key = name .. "." .. key
cache[v] = new_key
tinsert(temp,"+" .. key .. _dump(v,space .. (next(t,k) and "|" or " " ).. srep(" ",#key),new_key))
else
tinsert(temp,"+" .. key .. " [" .. tostring(v).."]")
end
end
return tconcat(temp,"\n"..space)
end
print(_dump(root, "",""))
end
-- 序列化tablle表--將表轉化成string
function serialize(obj)
local lua = ""
local t = type(obj)
if t == "number" then
lua = lua .. obj
elseif t == "boolean" then
lua = lua .. tostring(obj)
elseif t == "string" then
lua = lua .. string.format("%q", obj)
elseif t == "table" then
lua = lua .. "{\n"
for k, v in pairs(obj) do
lua = lua .. "[" .. serialize(k) .. "]=" .. serialize(v) .. ",\n"
end
local metatable = getmetatable(obj)
if metatable ~= nil and type(metatable.__index) == "table" then
for k, v in pairs(metatable.__index) do
lua = lua .. "[" .. serialize(k) .. "]=" .. serialize(v) .. ",\n"
end
end
lua = lua .. "}"
elseif t == "nil" then
return nil
else
return "-nil-"
--error("can not serialize a " .. t .. " type.")
end
return lua
end
-----------------------------------------------------------
function math.clamp(v, minValue, maxValue)
return math.max(minValue, math.min(v, maxValue))
end
-----------------------------------------------------------
local t = {{10, 20}, {30, 40}}
pt(t)
local a = math.clamp(0, 10, 15)
print("a: ", a)
local b = math.clamp(20, 10, 15)
print("b: ", b)
Output:
print table:
[1] = {
[1] = 10,
[2] = 20,
},
[2] = {
[1] = 30,
[2] = 40,
},
a: 10
b: 15
为什么Lua语言自己不提供语言层面的打印表(table)的方法?
参考:
1.
《树形打印lua table表》
https://www.cnblogs.com/jadeboy/p/3972524.html
2.
《Lua的math函数库及一些自定义扩展》
https://blog.csdn.net/david_dai_1108/article/details/50740214