zoukankan      html  css  js  c++  java
  • lua,修改字符串的某个字符

    function mutstring (s)
      assert(type(s) == "string", "string expected")
      local ms = s or ""
      local u = newproxy(true)
      local mt = getmetatable(u)
      local relatpos = function(p)
        local l = #ms
        if p < 0 then p = l + p + 1 end
        if p < 1 then p = 1 end
        return p, l
      end
      mt.__index = function(_, k)
        assert(type(k) == "number", "number expected as key")
        local k, l = relatpos(k)
        if k <= l then
          return ms:sub(k, k)
        end
      end
      mt.__newindex = function(_, k, v)
        assert(type(k) == "number", "number expected as key")
        assert(type(v) == "string" and #v == 1, "character expected as value")
        local k, l = relatpos(k)
        if k <= l + 1 then
          ms = ms:sub(1, k - 1) .. v .. ms:sub(k + 1, l)
        end
      end
      mt.__len = function(_) return #ms end
      mt.__tostring = function(_) return ms end
      return u
    end
    
    s = mutstring("Lua race")
    print(s[5])
    
    s[5] = "f"
    print(s)
    

    2.

    
    local mt = getmetatable('')
    local index = mt.__index
    	mt.__index = function (str, ...)
        local k = ...
        if 'number' == type(k) then
            return index.sub(str, k, k)
        else
            return index[k]
        end
    end
    
    local a = 'abc'
    
    for k = 1, #a do
        print(a[k])
    end
    
    
    print(a:upper())
    


  • 相关阅读:
    任务18格式化
    任务17分区
    任务16 BIOS与CMOS
    任务15硬件组装过程说明
    任务14选配机箱
    任务13选配电源
    任务12选配显卡
    任务11选配机械硬盘
    任务10选配固态硬盘
    Android自定义控件:动画类(八)----ObjectAnimator基本使用
  • 原文地址:https://www.cnblogs.com/byfei/p/14104369.html
Copyright © 2011-2022 走看看