1. lua 字符串添加扩展方法

在lua的strlib中,字符串创建时生成了一个元表,因此实现了字符串调用元表方法的功能,例如:

local s = "Hello World"
print(s:len())

-- output --
11

基于此,我们可以方便的向任意字符串添加方法:

local s = "Hello World"
local s_mt = getmetatable(s)
s_mt.__index.len_wo_space = function(s)
    local count = 0
    for i = 1, #s do
        if s:sub(i, i) ~= " " then
            count = count + 1
        end
    end
    return count
end

print(s:len())
print(s:len_wo_space())

-- output --
11
10

2. lua 的 string 类添加扩展方法

string 类我们可以简单认为是一个 table,向 string 类添加方法和向 table 添加方法相同:

local s = "Hello World"

string.len_wo_space = function(s)
    local count = 0
    for i = 1, #s do
        if s:sub(i, i) ~= " " then
            count = count + 1
        end
    end
    return count
end

print(s:len())
print(string.len_wo_space(s))
print(s:len_wo_space())

-- output --
11
10
10