lua 基础 2 类型和值

2022-12-04,,

-- 类型 和 值
--[[ 8中类型 滚动类nil、boolean、 number、string、userdata、
function、thread 和 table。]]

print (type("Hello World"))
print (type(10.4*3))
print (type(print))
print (type(print))
print (type(true))
print (type(nil))
print (type(type(x)))

--变量没有预定义的类型,每一个变量都可能包含任一种类型的值。
print ("++++++")
print (type(a))
a = 10
print (type(a))
a = "a string "
print (type(a))
a = print -- a 是变量
a(type(a)) --print(type(print))

--2.1 Nil 一个全局变量没有被赋值以前默认值为 nil;
--给全局变量负 nil 可以删除该变量。

--2.2 Booleans false ture lua只有false和nil是假的 所以lua 0和空都是真的

--2.3 Numbers 不多说

--2.4 Strings 指字符的序列 lua中字符串是不可以修改的 可以创建新的变量存放
print ("=========")
a= "one string"
b = string.gsub(a,"one","another")
print (a)
print (b)

-- lua 自动进行内存分配和释放,
-- 可以使用单引号或者双引号表示字符串
a= "a line"
b= 'another line'

--Lua 中的转义序列
--[[

\a bell
\b back space
\f form feed
\n newline
\r carriage return
\t horizontal tab
\v vertical tab
\\ backslash
\" double quote
\' single quote
-- 后退 -- 换页 -- 换行 -- 回车 -- 制表
-- "\" -- 双引号 -- 单引号
\[ left square bracket -- 左中括号
\] right square bracket -- 右中括号
]]
print('==========')

print ("one line\nnext line\n\"in quotes\", 'in quotes'")
--[[
输出

one line
next line
"in quotes", 'in quotes'
]]

print ('a backslash inside quotes: \'\\\'') --a backslash inside quotes: '\'
print("a simpler way: '\\'")--a simpler way: '\'

-- 在字符串中使用\ddd(ddd 为三位十进制数字)方式表示字母。

--使用[[...]]表示字符串 可以包含多行

page = [[
<HTML>
<HEAD>
<TITLE>An HTML Page</TITLE>
</HEAD>
<BODY>
Lua
[[a text between double brackets] ]
</BODY>
</HTML>
]]

io.write(page)

-- string 转化
print ("10"+1)--11
print ("10+1")--10+1
--print ("-5.3e - 10" * "2") ---1.06e-09
--print ("Hello" +1) --错

-- 数字转成 string
print (10 .. 20) --1020
-- ..在 Lua 中是字符串连接符,当在一个数字后面写..时,必须加上空格以防止被解释 错。
--[[
line = io.read()
n = tonumber(line)
if n == nil then
error (line .. "is not a valid number")
else
print (n*2)
end
]]

-- tostring() 将数字转成字符串
print ( tostring(10) == "10")
print (10 .. "" == "10")

-- 2.5 Functions
--[[

函数是第一类值(和其他变量相同),意味着函数可以存储在变量中,
可以作为函数 的参数,也可以作为函数的返回值。

Lua 可以调用 lua 或者 C 实现的函数,Lua 所有标准库都是用 C 实现的。

]]

--2.6 Userdata and Threads
--[[
userdata 可以将 C 数据存放在 Lua 变量中,userdata 在 Lua 中除了赋值和相等比较外 没有预定义的操作。
userdata 用来描述应用程序或者使用 C 实现的库创建的新类型。

]]

--[[

Lua 中的表达式包括数字常量、字符串常量、变量、一元和二元运算符、
函数调用。还可以是非传统的函数定义和表构造。

]]

--[[
上面例子的输出

string
number
function
function
boolean
nil
string
++++++
nil
number
string
function
=========
one string
another string
==========
one line
next line
"in quotes", 'in quotes'
a backslash inside quotes: '\'
a simpler way: '\'
<HTML>
<HEAD>
<TITLE>An HTML Page</TITLE>
</HEAD>
<BODY>
Lua
[[a text between double brackets] ]
</BODY>
</HTML>
11
10+1
1020
true
true

]]

lua 基础 2 类型和值的相关教程结束。

《lua 基础 2 类型和值.doc》

下载本文的Word格式文档,以方便收藏与打印。