1.Lua安装包官方下载地址:
http://www.lua.org/download.html
2.安装步骤:
tar zxf lua-5.4.3.tar.gz cd lua-5.4.3 make linux test make intall
3.helloWord
① 交互模式

② 脚本模式
创建一个helloWorld.lua文件
添加内容:print("helloWorld") 并保存
运行:lua helloWorld.lua
4.Lua数据类型及变量定义
Lua变量有三种类型:全局变量、局部变量、表中的域。
Lua中的变量全是全局变量,除非用local声明的为局部变量。局部变量的作用域为从声明位置开始到所在语句块结束。变量的默认值为nil。

5.注释
单行注释:--注释内容
多行注释:--[[ 注释内容 ---]]
6.lua运算符
① 赋值运算符
str="hello".."word" -- ..lua中的字符连接
a,b=10,20 --print(a,b) 结果:10 20
a,b,c=10,20 --print(a,b) 结果:10 20 nil
a,b=10,20,30 --print(a,b) 结果:10 20
② 算术运算符
加、减、乘、除、求余、乘方:+、-、*、/、%、^
③ 逻辑运算符
大于、小于、等于、不等于:> 、<、==、~=
与、或、非:and、or、not
④ 其他运算符
..字符串 拼接字符串
#字符串 获取字符串长度
7.流程控制
① 条件语句
-- if
if(true)
then
print("ok")
end
-- if else
if(true)
then
print("ok")
else
print("notOk")
end
-- if嵌套
c=20
if(c>10)
then
if(c<30)
then
print(c.."的值在10到30之间")
end
end② 循环语句
-- while循环
a=10
while(a>0)
do
print(a)
a=a-1
end
输出结果:10 9 8 7 6 5 4 3 2 1
--repeat util 重复循环执行(repeat)直到指定的条件(util)为真时执行
b=10
repeat
print(b)
b=b-1
util(b>0)
输出结果:10
--数值for循环 第一个1是初始值 第二个10是条件 第三个1是步长
for a=1,10,1 do
print(a)
end
输出结果:1 2 3 4 5 6 7 8 9 108.lua数组
--lua的数组大小不固定,注意:下标从1开始,与很多语言不同
--定义一个数组
arr = {"aaa","bbb","ccc"}
--遍历数组
--方式一 普通for循环
for index=1,#arr do
print(arr[index])
end
--方式二 泛型for ipairs(数组变量)迭代器函数
for i,v in ipairs(arr) do
print(i,v)
end9.lua函数
--函数
function fun(a,b,c)
return a+b+c
end
value=fun(1,2,3)
print(value)
输出结果:6
-- 注意:lua函数是可以一次返回多个结果
function fun(a,b,c)
return a,b,c
end
value1,value2,value3=fun(1,2)
print(value1,value2,value3)
输出结果:1,2,nil
--function前可加作用域,未设置默认为全局函数,如果设置函数为局部函数需要使用关键字local10.lua table
table是Lua的一种数据结构用来帮助我们创建不同的数据类型,如:数字、字典等,像是java中的对象。
--声明一个table
mytable={}
mytable.first="tom"
mytable.second="james"
print(mytable[1])
print(mytable.first)
print(mytable["second"])
输出结果:nil tom james11.模块和包
模块类似于一个封装库,把一些公用的代码放在一个文件里,以api的接口形式供其他地方调用,有利于代码的重用和降低代码的耦合度。一个模块很简单,就是创建一个table,然后把需要导出的变量、函数放入其中,最后返回这个table就行。
module.lua
--创建一个模块,提供变量和方法给其他代码调用
module={}
module.index=1
function module.sum(a,b)
return a+b
endtest.lua
--引入模块 注意 require中的值要对应到需要导入的那个lua文件名
require "module"
print(module.index)
print(module.sum(10,20))
















