Lua实现闭包

1
2
3
4
5
6
7
8
9
10
11
12
--[[@Func :实现闭包
@Desc : 当一个函数内部嵌套另一个函数定义时,内部的函数体可以访问外部的函数的局部变量,这种特征我们称作词法定界]]
function fuck()
local i = 0
return function()
i = i + 1
return i
end
end
c1 = fuck()
print(c1())
print(c1())

序列化Lua表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
-- Desc : 序列化Lua表(Convert Lua-Table To String)
function serialize(t)
local mark={}
local assign={}
local function ser_table(tbl,parent)
mark[tbl]=parent
local tmp={}
for k,v in pairs(tbl) do
local key= type(k)=="number" and "["..k.."]" or k
if type(v)=="table" then
local dotkey= parent..(type(k)=="number" and key or "."..key)
if mark[v] then
table.insert(assign,dotkey.."="..mark[v])
else
table.insert(tmp, key.."="..ser_table(v,dotkey))
end
else
table.insert(tmp, key.."="..v)
end
end
return "{"..table.concat(tmp,",").."}"
end
return "do local ret="..ser_table(t,"ret")..table.concat(assign," ").." return ret end"
end


实现Java字符串的Hash算法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
-- 实现Java字符串的Hash算法
hash = function(input)
input = tostring(input);
local h = 0
local len = string.len(input)
local max = 2147483647
local min = -2147483648
local cycle = 4294967296
for i=1, len do
h = 31 * h + string.byte(string.sub(input, i, i));
while h > max do
h = h - cycle
end
while h < min do
h = h + cycle
end
end
return h
end

树形打印lua table表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
--Desc: 树形打印lua table表
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

具体更加详细的内容可参见树形打印lua table表


静晴轩 ~ 晚晴幽草轩
个人微信公众号晚晴幽草轩;名字取自:“天意怜幽草,人间重晚晴”。
专注互联网开发(Web 大前端、快应用、小程序),以及分享优质网站、AI 应用、效率工具、心得感悟等内容。

文章目录
  1. 1. Lua实现闭包
  2. 2. 序列化Lua表
  3. 3. 实现Java字符串的Hash算法
  4. 4. 树形打印lua table表