nil
a = {[0]="123","32","23"};
_
---[[
可以注销掉块注释type
函数永远返回一个字符串false
和nil
视为假,将0
和空字符串视为真4
,0.4
,4.58e-3
,0.3e12
,5e+20
\
表达数值转义,[[ ]]
,[===[ ]===]
界定换行字符串,(类似的界定注释)tonumber
, tostring
不成功返回nil
#a
获取字符串a的长度,table.maxn
对于nil更加安全a ={},b=a
b保持了一个对于a所指向table的引用a.x
和a["x"]
是一样的,点作为记录,key暗示任意字符串x - x%1
取整x,y=y,x
交换do end
构成基本块(local
)a = io.read("*number")
print(a)
do return end
(...)
, 获取arg
goto
(用来编写状态机)function foo(x) return 2 * x end
==
foo = function (x) return 2 * x end
--
function derivative(f, delta)
delta = delta or 1e-4
return function(x)
return (f(x+delta) - f(x))/delta
end
end
table.sort(tb, function(a,b) return (a.name > b.name) end
-- 对于and来说第一个操作数为真,返回第二个操作数
-- or第一个操作数为假,返回第二个操作数
(a and b) or c -- a ? b : c, b不可以为false
foo = function(x) return 2 * x end
需要先定义局部变量
local fact -- 这一句和下一句要求分开【bug主要在这里】
fact = function(n)
if n == 0 then return 1
else return n * fact(n-1)
end
end
or
local function fact(n)
if n==0 then return 1
else return n * fact(n-1)
end
end
内部的函数体可以访问外部函数的局部变量(upvalue)
domo 重定义限制程序打开文件
do
local oldOpen = io.open
io.open = function(filename, mode)
if access_OK(filename, mode) then
return oldOpen(filename, mode)
else
return nil, "access denied"
end
end
end
-- g can use f here
local f = function(...)
end
local g = function(...)
f()
end
需要先声明
local fact
fact = function(n)
if n == 0 then
return 1
else
return n * fact(n-1)
end
end
a = {}; a.x = 1;
b = {}; b.x = 1;
a ~= b
a.foo = function(x,y) return x + y end
unpack(a)-- 分离一层
do
local i = 1
end
do return end -- 用于调试
if conditions then
elseif conditions then
end
while condition do
end
repeat
statements;
until conditions;
for var = beg,end,step do -- 如果为表达式一次性求职
end
for i,v in ipairs(a)
do
end
for key in pairs(v)
do
end
-- 死循环
for i = 1,math.huge do
end
function list_iter(t)
local i = 0
local n = table.getn(t)
return function()
i = i + 1
if i <= n then return t[i] end
end
end
t = {1,2,3}
iter = list_iter(t)
while true do
local element = iter()
if element == nil then break end
print(element)
for in do end
for i,v in ipairs(a) do end
require
会搜索目录加载文件,避免同一个文件lua
local path = "/xxxx/xxx.so"
loacl f= loadlib(path, "luaopen_socket")
if n then error("123") end
assert(io.read("*number"), "123")
function foo()
error()
end
if pcall(foo) then
-- no error
else
-- error
print(debug.traceback())
-- or next way
local status, err = pcall(xxx):
print(err)
end
Lua将所有关于协同程序的函数放置在一个名为coroutine的table里面
fco = coroutine.create(f) -- 创建,处于挂起状态
coroutine.resume(fco) -- 启动或者再次启动
coroutine.status(co) -- suspended/running/dead/normal
coroutine.yield() -- 函数内部挂起,yield(1,2)将返回1,2
非抢占式多线程
管道,迭代器
co = coroutine.create(func)
-- print(co)
-- print(coroutine.status(co))
-- suspended(创建成功,yeild), running, dead
-- coroutine.resume(co)
-- coroutine.yield()
- 第一,加载 LuaSocket 库
require “luasocket”- 第二,定义远程主机和需要下载的文件名
host = “www.w3.org”
file = “/TR/REC-html32.html”- 第三,打开一个 TCP 连接到远程主机的 80 端口(http 服务的标准端口)
c = assert(socket.connect(host, 80))
上面这句返回一个连接对象,我们可以使用这个连接对象请求发送文件
c:send(“GET ” .. file .. ” HTTP/1.0\r\n\r\n”)
receive 函数返回他送接收到的数据加上一个表示操作状态的字符串。当主机断开连接时,我们退出循环。- 第四,关闭连接
c:close()
-- t.__tostring = xxx
-- set:
local mt = { __index = t}
setmetatable(proxy, mt)
__tostring -- 打印
__index -- t[x] getter
__newindex -- t[x] setter
_G[x]
-- 创建
a = 1 -- create a global variable
-- change current environment
setfenv(1, {_G = _G})
_G.print(a) --> nil
_G.print(_G.a) --> 1
-- 继承
a = 1
local newgt = {} -- create new environment
setmetatable(newgt, {__index = _G})
setfenv(1, newgt) -- set it
print(a) --> 1
function Account:withdraw(v) -- a:withdraw
function withdraw(self, v) -- a.withdraw(可以互相通用)
__add
,__mul
,__sub
,__div
,__unm
,__mod
,__pow
,关系方法包括__eq
,__lt
,__le
表中找不到会访问__index(t,k)
方法,更新为__newindex(t,k,v)
方法
function setDefault(t,d)
local mt = {__index=function() return d end}
setmetatable(t,mt)
end
local key = {} -- trick, 唯一索引
local mt = {__index = function(t) return t[key] end}
fuction setDefault(t,d)
t[key] = d
setmetatable(t,mt)
end
lua
function c:new(o)
o = o or {}
setmetatable(o,c)
return o
end
SpecialAccount = Account:new()
s = SpecialAccount:new{limit=1000.00}
-- 多重继承
function createClass(...)
local c = {}
setmetatable(c, {__index=function(t,k) return search(k,arg) end })
end
weak
引用 metatable
的__mode
域来制定的,k
指key
是weak
,v
指value
是weak
a, b = {}, {}
setmetatable(a,b)
b.__mode = \"k\"
collectgarbage()
用途: 记忆函数,对象的属性关联
function newzxx(xxx):
local f = functionxx
return {f=f}
end
解析
setfenv(f, table):设置一个函数的环境
(1)当第一个参数为一个函数时,表示设置该函数的环境
(2)当第一个参数为一个数字时,为1代表当前函数,2代表调用自己的函数,3代表调用自己的函数的函数,以此类推
数学库由算术函数的标准集合组成,比如三角函数库(sin, cos, tan, asin, acos, etc.),
幂指函数(exp, log, log10),舍入函数(floor, ceil)、max、min,加上一个变量 pi。数学
库也定义了一个幂操作符(^)。
所有的三角函数都在弧度单位下工作。(Lua4.0 以前在度数下工作。)你可以使用 deg
和 rad 函数在度和弧度之间转换。
math.random 用来产生伪随机数,有三种调用方式:
+ 第一:不带参数,将产生 [0,1)范围内的随机数.
+ 第二:带一个参数 n,将产生 1 <= x <= n 范围内的随机数 x.
+ 第三:带两个参数 a 和 b,将产生 a <= x <= b 范围内的随机数 x.
math.randomseed(os.time())
lua 假定array在最后一个非nil位置结束
table.getn -- memory search
table.setn
table.insert(a,x) -- push
table.remove(a) -- pop
table.insert(a,1,x), table.remove(a,1)
table.sort
string.len(s)
string.rep(s,n) -- repeat s for n times
string.lower(s) -- upper
string.sub(s,i,j) -- begin with 1. end as -1
i, j = string.find(s, "hello", [beg pos])
s, count = string.gsub(ori, mod, replace[, time])
简单模式/完全模式
io.input(filename), io.output(filename)
io.read() -- a line
io.read(*all)
io.read(*number)
io.read(*line)
io.read(*num) -- char num
io.read(0) -- whether EOF
io.write("",math.sin(3),"")
f = assert(io.open("xxx.xxx", "r"))
local lines, rest = f:read(BUFISIZE,"*line")
outf:flush
os.time(year=x, month=x, day=x)
<-->
os.date("*t",1233)
string.format(fmt.."%q", unpack(arg), "1234")
table.sort(tb1, function(a,b) return (a.name>b.name) end)
io.read(*all)