Lua代码片段收集

时间:2022-05-06
本文章向大家介绍Lua代码片段收集,主要内容包括Lua实现闭包、序列化Lua表、实现Java字符串的Hash算法、树形打印lua table表、基本概念、基础应用、原理机制和需要注意的事项等,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。

Lua实现闭包

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

序列化Lua表

-- Desc : 序列化Lua表(Convert Lua-Table To String)
function serialize(t)
truelocal mark={}
truelocal assign={}

truelocal function ser_table(tbl,parent)
truetruemark[tbl]=parent
truetruelocal tmp={}
truetruefor k,v in pairs(tbl) do
truetruetruelocal key= type(k)=="number" and "["..k.."]" or k
truetruetrueif type(v)=="table" then
truetruetruetruelocal dotkey= parent..(type(k)=="number" and key or "."..key)
truetruetruetrueif mark[v] then
truetruetruetruetruetable.insert(assign,dotkey.."="..mark[v])
truetruetruetrueelse
truetruetruetruetruetable.insert(tmp, key.."="..ser_table(v,dotkey))
truetruetruetrueend
truetruetrueelse
truetruetruetruetable.insert(tmp, key.."="..v)
truetruetrueend
truetrueend
truetruereturn "{"..table.concat(tmp,",").."}"
trueend

truereturn "do local ret="..ser_table(t,"ret")..table.concat(assign," ").." return ret end"
end

实现Java字符串的Hash算法

-- 实现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表

--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表