Lua 基础
注释
-- 单行
--[[
多行
...
--]]
基本类型和类型判断
print(type("Hello world")) --> string
print(type([[ hello world ]])) --> string, 块字符串
print(type(10.4*3)) --> number
print(type(print)) --> function
print(type(type)) --> function
print(type(true)) --> boolean
print(type(nil)) --> nil
print(type(type(1))) --> string
print(type({})) --> table
if 0 then print("then") end --> then, 0 == true
local a = 1;
assert(type(a) == "number");
assert(type(c) == "nil" );
assert(c == nil);
string:
assert(1+1 == 2)
assert("1"+1 == 2)
assert("1"+"1" == 2)
assert("a".."b" == "ab") -- 字符串拼接
assert(#"ajanuw" == 6) -- 长度
function:
-- 没有返回值
local function f1(name)
print("hello "..name)
end
-- 返回一个参数
local function f2(name)
return "hello "..name
end
-- 返回多个参数
local function f3(name)
return "hello "..name,1,2
end
f1("ajanuw")
print(f2("ajanuw"))
local a,b,c = f3("ajanuw")
print(a..b..c)
-- 将函数赋值给变量
f4 = f1
f4("f4")
-- 清理函数
f4 = nil
assert(f4 == nil)
-- 可变参数
local function f1(...)
print(#{...}) -- 3
for i,v in ipairs{...} do
print(i, v)
end
end
f1(1,2,3)
回调函数
local function f1(name, cb)
cb(name)
end
f1("ajanuw", function(name)
print("hello "..name)
end
)
循环
i = 10
while( i >= 0 )
do
print(i)
i = i-1
end
-- init end step
for i = 10, 0, -1
do
print(i) -- 10 .. 0
end
if判断
a = 3
if a == nil then
print(1)
elseif a == 1 then
print(2)
else
print(3)
end
数组
-- 索引从1开始
array = {1, "string.."}
for i = 1, #array do
print(array[i])
end
-- 迭代器
for i,v in ipairs(array) do
print(v)
end
table
local _table = {}
-- 增
_table[1] = 1
_table['key1'] = "value1"
-- 删
_table[1] = nil
-- 改
_table['key1'] = "value11"
-- 查
print(_table['key1'])
-- 迭代
for k,v in pairs(_table) do
print(k .. " : " .. v)
end
模块
创建
hello = {}
hello.version = '0.0.1'
function hello.echo(name)
print("hello " .. name)
end
hello.echo2 = function (name)
print("hello " .. name)
end
-- 导出
return hello
使用
local hello = require "hello"
print(hello.version)
hello.echo("ajanuw")
hello.echo2("ajanuw2")
文件io
-- 追加的方式读写文件,不存在自动创建
hFile = io.open ("a.ini" ,"a+")
-- 设置输出句柄,然后写入
io.output(hFile)
io.write("hello\r\n")
io.write("word\r\n")
io.close(hFile) -- 关闭
hFile = io.open ("a.ini" ,"a+")
io.input(hFile) -- 设置输入句柄
print(io.read('*a')) -- 读取整个文件
io.close(hFile)
class
Klass = {
name = "",
age = 0
}
function Klass:new(name, age)
local o = {name = name, age = age}
setmetatable(o, {__index = Klass})
return o
end
function Klass:hello()
print("hello " .. self.name)
end
k = Klass:new("ajanuw",11)
print(k.name)
k:hello()
print('------------------------------------')
-- 继承 Klass
Klass2 = Klass:new()
function Klass2:new(name,age)
local o = Klass:new(name,age)
setmetatable(o, { __index = self })
return o
end
function Klass2:h()
self:hello()
end
k2 = Klass2:new("ajanuw2",11)
print(k2.name)
k2:h()