2.类型与值

来源:互联网 发布:js判断是否在数组中 编辑:程序博客网 时间:2024/06/05 04:12
8种基础类型
nil、boolean、number、string、userdata、function、thread、table

1.nil
只有一个值nil

2.boolean
有两个值false、true
只有false、nil为假
0、空串为真

3.number
表示的是实数

4.string
lua中string不可改
eg:
a="one string"
b=string.gsub(a,"one","another")
print(a,b)

长字符串的处理
--如果这中间有字符]]这种之类的要在[[中间加入=,且与]]中间加入=数量相同
--在[[    ]]之中--失效
page=[==[
<html>
<head>
<title>long string handle</title>
</head>
<body>
<a href="http://www.google.com">Google</a>
<br>
what a fuck string:
<font color=#FF0000>a=b[c[i]]</font>
<br><br>
Attention two ]] here!So need to add = between ]],like following
<br>
[=[
<br>
a=b[c[i]], now it can show normally.
<br>
]=]
</body>
</html>
]==]
--写文件
file=io.open("link.html", "w")
file:write(page)
file:close()
--直接输出
io.write(page)

..字符串连接操作符
eg:
print(10 .. 20)

类型转换
但一般还是用tonumber() tostring()
来显式转换
eg1:
line = io.read()
n = tonumber(line)
if n == nil then 
error(line .. " is not a valid number")
else
print(n^3)
end

eg2:
print(tostring(10) == "10") -->true
print(10 .. "" == "10") -->true

length operator
字符串前置操作符 # 可获取该字符串的长度
eg:
a = "hello"
print(#a) -->5
print(#"good\0bye") -->8

5.table
talbe是一个关联数组,可以使用除了nil的值作为key

初始化空表再添加/添加式
eg:
t={}
t['x']=100
t[999]="abcd\tabcd"
for key,value in pairs(t) do
print(value .. '\t')
end

初始化数组/列表式
eg://初始化后以1-#days的index访问
days = {"Sunday","Monday","Tuesday","Wednesday",
"Thursday","Friday","Saturday"}
days[1] == "Sunday"

初始化记录/记录式
为了表示一条记录,可将字段名作为索引
对于 t['x'] or t["x"]可以写成t.x
a={x=10,y=20}    --相当于a.x=10; a.y=20

混合列表式/记录式
eg:
polyline={color="blue",thickness=2,npoints=4,
                {x=0,y=0},
                {x=-10,y=0},
                {x=-10,y=1},
                {x=0,y=1}
                }
print(polyline.color)    --blue
print(polyline[1].x .. '\t' .. polyline[1].y)
print(polyline[4].x .. '\t' .. polyline[4].y)

通用构造式
eg://在方括号中显式用表达式来初始化index值
opnames={
    ["+"]="add",
    ["-"]="sub",
    ["*"]="mul",
    ["/"]="div",
    [1]=100
}

两个tips
1.可在最后一个元素后面写一个逗号
eg:
a={[1]="red", [2]="green", [3]="blue",}    --这样无需把最后一个元素特殊处理

2.可以把列表式与记录式明显地区分开
eg:
t={x=10,y=45; "one","two","three"}

惯用实例
print(a[#a])    --打印最后一个值
a[#a]=nil        --删除最后一个值
a[#a+1]=v      --将v插入到末尾

table取得最大索引
eg://用于table中有hole
t={}
t[10000]=1
print(table.maxn(t))
原创粉丝点击