求助:在lua用table.insert()向表中插入元素时发生的奇怪现象,有的元素有key,有的没有?

notno 2008-11-29 10:14:45
搞不懂下面这几行代码的输出:

str = "welcome to lua world \13y"
str_table = {}
for line in str:gmatch('([^\n]+)') do
print(line,type(line))
table.insert(str_table, line)
end

print("##############")
for k,v in pairs(str_table) do
print(k,v)
end
print("##############")

print(#str_table)

输出为:
welcome to lua world --为什么这个“字符串”的类型是空的?
y string
##############
1 welcome to lua world
y --为什么这行没有序号?
##############
1


附:
table.insert (table, [pos,] value)
Inserts element value at position pos in table, shifting up other elements to open space, if necessary. The default value for pos is n+1, where n is the length of the table (see §2.5.5), so that a call table.insert(t,x) inserts x at the end of table t.
...全文
1592 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
notno 2008-11-29
  • 打赏
  • 举报
回复
呵呵,我已经找到答案了,跟楼上说的差不多:
str:gmatch('([^\n]+)') -- 这一句里,不应该用\n,而应该用%c
在lua使用的正则表达式里,%c代表所有控制字符,而\n被当作了两个普通的字符。
iambic 2008-11-29
  • 打赏
  • 举报
回复
不明白你为什么要用\13?13是回车符。改成换行符试下:
[code=Lua]str = "welcome to lua world \ny" [/code]

37,719

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧