美文网首页
lua 字符串管理(String Manipulation)

lua 字符串管理(String Manipulation)

作者: 玻璃缸里的自游 | 来源:发表于2019-01-20 15:15 被阅读0次

    1、When indexing a string in Lua, the first character is at position 1 (not at 0, as in C). Indices are allowed to be negative and are interpreted as indexing backwards, from the end of the string. Thus, the last character is at position -1, and so on.

    例子:

    
    local str = "abcdefg"
    
    local str_forward = ""
    
    local str_backward = ""
    
    local str_len = str:len()
    
    for i=1,str_len do
    
    str_forward = str_forward..str:sub(i,i)
    
    end
    
    for i=-1,-str_len,-1 do
    
    str_backward = str_backward..str:sub(i,i)
    
    end
    
    print(str_len)
    
    print(str_backward)
    
    print(str_forward)
    

    2、string.dump(function [, strip]) 函数序列化与反序列化

    Returns a string containing a binary representation (a binary chunk) of the given function, so that a later load on this string returns a copy of the function (but with new upvalues). If strip is a true value, the binary representation may not include all debug information about the function, to save space.

    例子:

    
    function add( a,b )
    
        return a+b
    
    end
    
    --序列化
    
    str_dump = string.dump(add)
    
    print(str_dump)            --
    
    --反序列化
    
    addfunc = load(str_dump)   
    
    --调用函数
    
    print(addfunc(1,2))
    

    说明:strip是boolean值。如果是ture,在dump函数为序列的时候,会忽略此函数的debug信息而节省空间。

    3、对string.char(...)的扩展string.xchar(argtable)

    
    function string.xchar(argtable)
    
    local boarder = #argtable
    
    local argstr=""
    
    if boarder>0 then
    
    argstr = argtable[1]
    
    for i=2,boarder do
    
    argstr = argstr..','..argtable[i]
    
    end
    
    end
    
    f = load("return string.char("..argstr..")")
    
    return f()
    
    end
    
    arg1 = {97,98,99}
    
    print(string.xchar(arg1))
    
    print(string.char(97,98,99))
    

    说明:argtable是ascii码表。

    4、For convenience, when the opening long bracket is immediately followed by a newline, the newline is not included in the string

    例子:

        a = 'alo\n123"'
    
        a = "alo\n123\""
    
        a = '\97lo\10\04923"'
    
        a = [[alo
    
        123"]]
    
        a = [==[
    
        alo
    
        123"]==]
    

    它们是相同的字符串

    相关文章

      网友评论

          本文标题:lua 字符串管理(String Manipulation)

          本文链接:https://www.haomeiwen.com/subject/eevxjqtx.html