Categories

Tags

Table of Contents

  1. 表元素的插入和移除
  2. 表元素的拼接
  3. 表的格式化显示

表元素的插入和移除

table.insert(table,[pos],value) []中的参数可选;[pos]为插入位置;value插入元素值

table.remove(table,[pos]) []中的参数可选;[pos]为删除位置,默认为表的长度

table.remove 操作删除并返回序列指定位置的元素,然后将该位置后的所有位置往前移动补齐空洞。不指定位置时,默认删除最后一个元素。

实现简单栈

  • Pop: table.remove(t)
  • 在栈的顶部插入: table.insert(t,1,x)
  • 在栈的顶部移除: table.remove(t,1)

表元素的拼接

table.concat(table,[sep],[start],[end]) []中的参数可选;[sep]为拼接分隔符;[start]是起始位置;[end]是结束位置

a = {1,2,3,4,5,6}

str = table.concat( a, ";" )
print(str) -- => 1;2;3;4;5;6

str = table.concat( a, ";",1,3 )
print(str) -- => 1;2;3

表的格式化显示

以对齐,比较美观的方式来打印输出表的数据结构

--========================================
-- 打印并格式化输出表
--========================================
 table.print = function(t,tableName)
	print((tableName or "unknown").." = "..LogUtil.FormatTable(t))
end

function LogUtil.FormatTable(t, prefix, tableList)
	prefix = prefix or "";
	tableList = tableList or {};

	if tableList[t] then
		return "[ReFormat:"..tostring(t).."]";
	end

	tableList[t] = true;

	local str = "{\n"

	for k, v in pairs(t) do
		str = str..LogUtil.FormatField(k, v, prefix.."\t", tableList).."\n";
	end

	str = str..prefix.."}";

	return str;
end

function LogUtil.FormatField(key, value, prefix, tableList)
	return prefix..LogUtil.FormatKey(key, prefix, tableList) .." = "..LogUtil.FormatValue(value, prefix, tableList)..";";
end

function LogUtil.FormatKey(key, prefix, tableList)
	local keyType = type(key);
	if keyType == "string" then
		return key;
	elseif keyType == "number" then
		return "["..key.."]";
	end

	return "["..tostring(key).."]";
end

function LogUtil.FormatValue(value, prefix, tableList)
	local valueType = type(value);
	if valueType == "string" then
		return "\""..value.."\"";
	elseif valueType == "number" or valueType == "boolean" then
		return tostring(value)
	elseif valueType == "table" then
		return LogUtil.FormatTable(value, prefix, tableList);
	end

	return "["..tostring(value).."]";
end