基础语法
原创大约 3 分钟
数据类型
虽然官方强调Lua是一种动态类型的语言,它没有类型定义,所有的值都有自己的类型。但Lua的值依然没有脱离八种基本类型的范围。
数据类型 | 描述 |
---|---|
nil | 表示一个缺失的值(相等于null),因为nil和false都可以使条件为假,所以它们统称为假值 |
boolean | 只有true和false两个值 |
number | 既表示64位整数,又表示64位浮点数 |
string | 是一个不可变的8位字节序列 |
function | C 或Lua 编写的函数 |
userdata | 任意一个存储在变量中的C 数据结构。它有两种类型:完整用户数据(full userdata ,是一块内存对象)和轻量用户数据 (light userdata ,表示C 指针的值) |
thread | 表示独立的执行线程,用于实现协程 |
table | 表示关联数组,以除了nil 和NaN 之外的任何Lua 值作为索引,可用于表示普通数组、列表、符号表、集合、记录、图形、树等 |
-- 这是行注释
--[[
这是块注释
--]]
-- string
print("type('Hello world') ==> " .. type("Hello world"))
-- number,1/0的结果是1.#INF
-- 字符串使用 .. 连接,而不是 + 号
print("type(1 / 0) ==> 类型:" .. type(1 / 0) .. " ==> 值:" .. (1 / 0))
-- number
print("type(10.4 * 3) ==> " .. type(10.4 * 3))
-- number
print("type(1.23456789e-16) ==> 类型:" .. type(1.23456789e-16).." => 值:".. 1.23456789e-16)
-- print()是一个function
print("type(print) ==> " .. type(print))
-- type()也是一个function
print("type(type) ==> " .. type(type))
-- boolean
print("type(true) ==> " .. type(true))
-- nil
print("type(nil) ==> " .. type(nil))
-- table
print("type({}) ==> " .. type({}))
-- 任何沒有赋值的变量都是nil
print("type(a) ==> " .. type(a))
-- string,type(a)返回的值其实是一个字符串
print("type(type(a)) ==> " .. type(type(a)))
变量
除了用local
关键字声明的变量是局部变量以外,其他的变量都是全局变量,即使在语句块或是函数里也一样。
-- 全局变量
a = 5
-- 局部变量
local b = 5
function joke()
-- 全局变量
c = 5
-- 局部变量
local d = 6
end
-- 给c赋值5
joke()
-- 5 5 5 nil
print(a, b, c, d)
e, f, g, h = 3.14, 2, "hello", true
-- 3.14 2 hello true
print(e, f, g, h)
-- 这相当于交换了两个变量的值
e, g = g, e
-- hello 3.14
print(e, g)
a, b, c = 1, 2, 3, 4
-- 1 2 3
print(a, b, c)
a, b, c = 1, 2
-- 1 2 nil
print(a, b, c)
条件判断
Lua只能通过if...else
实现条件判断,因为它没有switch...case
。
-- false和nil为假,true和非nil为真
-- 因为a=nil,所以执行else
if(a)
then
print("结果为true")
else
print("结果不为true")
end
-- 条件永远是false
if(nil)
then
print("结果为nil")
end
循环语句
Lua提供了三种循环方式:while
、for
和repeat...until
。
-- while循环和if一样:false和nil为假,true和非nil为真
-- while(1)
-- do
-- print("循环将永远执行下去")
-- end
-- for循环
-- 相当于 for int i = 1; i <= 10; i++
-- 最后的1表示步长,不设置的话默认为1
for i = 1, 10, 1 do
if i > 5 then
break
end
print(i)
end
-- 使用默认步长
for j = 1, 10 do
if j > 3 then
break
end
print(j)
end
-- 自定义步长
for k = 1, 10, 3 do
if k > 5 then
break
end
print(k)
end
-- for...in
a = {"hello", "lua", "world"}
for k, v in ipairs(a) do
-- 也可以不输出k只输出v:print(v)
print(k, v)
end
-- repeat...until
a = 1
repeat
print(a)
a = a + 1
until(a > 5)
运算符
除了+
、-
、*
、/
、%
,Lua还有^
(幂运算)和//
(整除,需要Lua5.3
版本以上)两个运算符。
a = 13
b = 6
print("a的平方值为:", a ^ 2)
-- lua5.3以上版本才有
-- print("a整除b的值为:", a//b)
-- lua的不等于不是!=,而是~=
print(1 ~= 2)
-- lua也没有&&、||和!,只有 and、or、not
a = true
b = false
if a and b then
print("a and b 条件为true")
end
if a or b then
print("a or b 条件为true")
end
if not b then
print("not b 条件为true")
end
感谢支持
更多内容,请移步《超级个体》。