Lua学习三


观察全局与局部变量


<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>


string与number之间的转换
<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)


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

MyObject-C

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值