练习5.1
monday sunday sunday
练习5.2
一样,都指向该表。
a.a.a.a=3,执行的是该表的索引 a 赋值为3,之后的a.a.a.a将会引发异常,因现a.a=3,而非表。
练习5.3
在方括号里写索引值
tab={["\n"]=1,["\n\t\a"]=666,["lisper"]="lua"}
for i,j in pairs(tab) do
io.write(">",i,">>",j,"\n")
end
练习5.4
function ans_s(t,x)
local sp=t[1]
for i=2,#t do
sp=sp+t[i]*x^(i-1)
end
return sp
end
练习5.5
function ans(t,x)
local sp=t[1]
local dp=x
for i=2,#t do
sp=sp+dp*t[i]
dp=dp*x
end
return sp
end
练习5.6
对比ipairs和pairs迭代器循环次数
function ispair(t)
local x,y
for i in pairs(t) do
x=i
end
for i in ipairs(t) do
y=i
end
if x~=y then
return false
else
return true
end
end
练习5.7
function movetable(t1,t2,n)
table.move(t1,1,#t1,n,t2)
return t2
end
练习5.8
简单二分优化实现表字符串元素连接函数
function tabconcat(tab)
local len,con=0,0
len=#tab
repeat
if len%2==1 then
len=len-1
con=1
else
con=0
end
for i=1,len/2,1 do
tab[i]=tab[2*i-1]..tab[2*i]
end
if con==1 then
tab[len/2+1]=tab[len+1]
len=len/2+1
else
len=len/2
end
until len==1
return tab[1]
end
与标准库table.concat函数进行对比测试。
function test(tm)
print(">> ",tm," * a concat")
tab1={}
for i=1,tm do
tab1[i]="a"
end
time=os.clock()
str1=tabconcat(tab1)
print(os.clock()-time,#str1)
tab2={}
for i=1,tm do
tab2[i]="a"
end
time=os.clock()
str2=table.concat(tab2)
print(os.clock()-time,#str2)
end
test(1000000)
test(10000000)
test(100000000)
测试结果:
>> 1000000 * a concat
0.384 1000000
0.191 1000000
>> 10000000 * a concat
4.168 10000000
1.981 10000000
>> 100000000 * a concat
43.36 100000000
19.721 100000000
时间大约是标准库的二倍。