1、lua实现深拷贝
function DeepCopy( obj )
local InTable = {};
local function Func(obj)
if type(obj) ~= "table" then --判断表中是否有表
return obj;
end
local NewTable = {}; --定义一个新表
InTable[obj] = NewTable; --若表中有表,则先把表给InTable,再用NewTable去接收内嵌的表
for k,v in pairs(obj) do --把旧表的key和Value赋给新表
NewTable[Func(k)] = Func(v);
end
return setmetatable(NewTable, getmetatable(obj))--赋值元表
end
return Func(obj) --若表中有表,则把内嵌的表也复制了
end
2、lua实现打印table结构
local function intentstr(level)
local str=" "
for i=1,level do
str = str.." "
end
return str
end
local function printTable(tb,last_tb,level)
if level>3 then return end
if level==0 then print("{") end
local str = intentstr(level)
for k,v in pairs(tb) do
if type(v)~='table' then
print(str..k.."="..tostring(v))
else
print(str..k.."={")
if next(v) and tostring(v)==tostring(last_tb) then
printTable(v,{},level+1)
end
last_tb = tb
printTable(v,last_tb,level+1)
print(str.."}")
end
end
if level==0 then print("}") end
end
test = {tb={'aa','bb'}}
rawset(test,'AA','aaa')
printTable(test,{},0)
3、生成唯一长度为len字符串
function e_utility_getuid(len)
local template = string.rep('x',len-5)
d = io.open("/dev/urandom", "r"):read(4)
math.randomseed(os.time() + d:byte(1) + (d:byte(2) * 256) + (d:byte(3) * 65536) + (d:byte(4) * 4294967296))
local rdmstr = string.gsub(template, "x", function (c)
local v = (c == "x") and math.random(0, 0xf) or math.random(8, 0xb)
return string.format("%x", v)
end)
return string.sub(TIME,6,10)..rdmstr
end
4、lua实现sleep
local function sleep(n)
os.execute("sleep "..n)
end
local socket = require("socket")
local function ssleep(n)
socket.select(nil,nil,n)
end
local i=0
while true do
sleep(1)
print("time:"..os.time())
ssleep(1)
print("time:"..os.time())
end
5、清除table数组中重复元素
function e_utility_del_dup_elem(tb)
local tmp={}
for key,val in pairs(tb) do
tmp[val]=true
end
local new_tb = {}
for key,val in pairs(tmp) do
table.insert(new_tb,key)
end
return new_tb
end
6、数组删除指定元素 包含重复的情况
function e_utility_array_del(array, elem)
if not next(array) then return end
table.sort(array)
local pos=1
while true do
if not array[pos] then break end
if array[pos]==elem then table.remove(array,pos)
else pos = pos +1 end
end
end