- 测试代码 (一)
function string.split(str, delimiter)
if str == nil or str == '' or delimiter == nil then
return nil
end
local results = {}
for match in (str .. delimiter):gmatch('(.-)' .. delimiter) do
print(match)
table.insert(results, match)
end
return results
end
for i,v in pairs(string.split('a,b,c',',')) do print(i, v) end
把这段代码运行到测试地址进行测试,得到如图所示的结果
其中
(str .. delimiter):gmatch('(.-)' .. delimiter)
其实是用到string.gmatch(s, pattern)
,而这里换成了冒号用法s:gmatch(pattern)
,string.gmatch(s, pattern)
的用法可以参照Lua的字符串匹配与正则表达式。此例中(.-)
用到了匹配前一字符0次或多次
- 测试代码(二)
local test = {}
function test:func( arg1, arg2)
print(arg1, arg2, self)
end
function test.func1( arg1, arg2)
print(arg1, arg2, self)
end
test:func(1,2)
test.func(1,2)
test:func1(1,2)
test.func1(1,2)
从结果开始看出,点号相当于静态方法,冒号相当于成员方法,他们之间可以相互转换。冒号方法相当于省略了第一个
self
参数,内部可以直接方法。具体可以这样分析:
test:func(1,2)
,属直接使用 ,self
内部可以直接方法,所以结果是1 2 table
test.func(1,2)
,属转换使用,self
为arg1,此例即为 1,2
为arg1
,arg2未赋值, 所以结果是2 nil 1
test:func1(1,2)
,属转换使用,self
参数隐藏,table
为arg1
,1
为arg2
,所以结果是table 1 nil
test.func1(1,2)
,属直接使用,self
未赋值,所有结果是1 2 nil