观察全局与局部变量
<span style="font-size:18px;">function norm (x,y)
--n = x^2 + y^2
local n = x^2 + y^2
return n
end
--[[
print(norm(1,2))
print(n)
--]]
</span>
<span style="font-size:18px;">function fact (n)
if n == 0 then
return 1
else
return n * fact(n-1)
end
end
--a = io.read()
--print(type(a))
a = io.read("*number")
print(fact(a))</span>
<span style="font-size:18px;">dofile("test_na.lua")
print( fact(2))</span>
全局变量不需要声明,赋值后即创建,删除全局变量只需赋值nil
查看类型
<span style="font-size:18px;">print(type("hell"))
print(type(2))
print(type(print))
print(type(type))
print(type(nil))
print(type(true))
print(type(type(nil)))</span>
<span style="font-size:18px;">a = print
a(type(a))</span>
替换
<span style="font-size:18px;">a = "hello word"
b = string.gsub(a,"l","wo")
print(a)
print(b)</span>
page = [[ ... ]],这种格式表示字符串,可以包含多行,可以嵌套且不会解释转义字符
.. 字符串连接,结果为字符串
<span style="font-size:18px;">line = io.read()
n = tonumber(line)
if n == nil then
error(line .. "is not a valid number")
else
print(n*2)
end
print(tostring(10) == "10")
print(10 .. "" == "10")</span>
userdata可以将C数据存放在Lua变量中.后续讲解。
false 和nil 是假,其他为真,学习and or
print(4 and 5)
print(nil and 10)
print(false and 13)
print(4 or 5)
print(false or 5)
x = x or v
--等价
if not x then
x = v
end
c语言中 的 a ? b : c 等价于 (a and b ) or c
not的结果一直返回false或true
print (not nil)
print (not false)
print (not 0)
print (not not nil)
表操作:
days = {"sun","mon","tue"}
print(days[1])
tab = {x = 1,y = 2}
--[[
tab = {}
tab.x = 1
tab.y = 2
--]]
print(tab["x"])
w = {x = 0,y = 0,z = "hello"}
x = {math.sin(0),math.sin(1)}
w[1] = "hello"
x.f = w
print(w["x"])
print(w[1])
print(x.f[1])
w.x = nil --remove field "x"
table每次调用构造函数,Lua都会创建一个新表,list实现:
list = nil
for line in io.lines() do
list = {next = list,val = line}
end
--print list
l = list
while l do
print(l.val)
l = l.next
end
表初始化:
polyline = {
color = "blue",points = 2,
{x = 1,y = 2},
{x = 2,y = 3}
}
print(polyline[1].x)
opt = {["+"] = "add",["-"] = "sub"}
--初始化
pt = {x = 0,y = 0} --{["x"] = 0,["y"] = 0}
clr = {"red","green"} --{[1] = "red",[2] = "green"}
--]]
全局与局部变量
x = 10
local i = 1
print(i)
while i < x do
local x = i*2
print(x) --local x
i = i + 1
end
if i > 20 then
local x --local to the then body
x = 20
print(x + 2)
else
print(x) --global x
end
print(x) --global x
使用局部变量避免命名冲突,访问速度较全局变量快
当你想更好的控制局部变量,do...end很有用。
a = 2
do
local a1 = a * 2
x = a1 + a
print(a1)
end
print(x)