Programming in Lua 4th Edition

5.3 加入 64-bit integer, 以前只有 double-precision floating;
small lua: 32-bit integers and single-precision floats;
Both integer and float values have type "number".

  • math.type

floating-point hexadecimal constants

0xa.bp2 -- (10 + 11/16) * 4, Lua 5.2 引入

string.format("%a", 0.1)

division of two integers does not need to be an integer

5.3 引入 //

modulo always having the same sign as the second argument.

math.pi - math.pi % 0.01

~=

math.min(1, 2)
math.huge -- inf
math.randomseed(os.time())
math.random() -- [0, 1), die [1, n], [l, u]
math.rad
math.deg
floor, ceil, and modf -- modf rounds towards zero
math.modf(-3.3) -- -3, -0.3

-math.mininteger == math.mininteger
math.maxinteger + 2.0 == math.maxinteger + 1.0 -- true

lose precision

2^53 | 0 -- integer
-- number has an exact representation as an integer

math.tointeger(5.01) -- nil, not an integral value
math.tointeger(2^64) -- nil, out of range

^
unary operators (- # ~ not)

  • / // %

.. (concatentation)
<< >> (bitwise shifts)
&
(bitwise AND)
~ (bitwise exclusive OR)
| (bitwise OR)
< > <= >= ~= ==
and
or

All binary operators are left associative,
except for exponentiation and concatenation,
which are right associative.

Lua 5.2 can represent exact integers only up to 2^53 ,
while in Lua 5.3 the limit is 2^63

(2^62|0) + (2^62|0) -1 == math.maxinteger

math.maxinteger * math.maxinteger
math.mininteger * math.mininteger

Strings in Lua are immutable values.

print(#"你h") -- 4, in bytes

'ok' .. 2 -- If any operand is a number, Lua converts this number to a string:

'
"
\ddd \xhh \u{hhh} -- \ddd 是 10 进制

long string, ignore the first character
[[....]]
[===[.......]===]

data = "\x00\x01\z
\x08"

automatic conversions between numbers and strings at run time

"10" + 1 -- 11.0 不完美的 lua
强大的 tonumber 和 math.tointeger(" 10")
tonumber 可以使用进制
tonumber("-ZZ", 36)
tonumber("9", 8) -- nil
tostring, 但是还是建议用 string.format

string.len -- #s
string.rep
string.reverse
string.sub(s, i, j) -- [i, j]
string.char(...)
string.byte(''[, start[, end]]) -- limit stack size

s:sub(i, j)
string.find("hello world", "war") -- nil

string.gsub 返回 2 个值

reverse,upper, lower, byte, and char
do not work for UTF-8 strings,
as all of them assume that one character
is equivalent to one byte.

utf8.len("ab\x93") -- nil 3
utf8.char(0x4f60) -- 你
utf8.codepoint(s, utf8.offset(s, 5))
utf8.codes

nil 不能作为 table 的 key

like global variables,
table fields evaluate to nil when not initialized.

tbl[2] == tbl[2.0]
2 compares equal to 2.0
tbl[1/3] 也是合法的
a = {x = 10, y = 20}
we cannot initialize fields with negative
indices, nor with string indices that are not proper identifiers.

tbl 可以用, 或 ; 分隔

without holes a sequence

The length operator is unreliable for lists with holes (nils)

a table with no numeric keys is a sequence with length zero.

If you really need to handle lists
with holes, you should store the length explicitly somewhere.

io.lines()
table.insert
table.remove

-- insert begin
table.move(a, 1, #a, 2)
a[1] = newElement

-- remove first
table.move(a, 2, #a, 1) -- copy
a[#a] = nil

table.move 从一个到另外一个tbl

function

if the function has
one single argument and that argument is either a literal string or a table constructor, then the parentheses
are optional:

function with a number of arguments different from its number of parameters. Lua adjusts
the number of arguments to the number of parameters by throwing away extra arguments and supplying
nils to extra parameters.

· When we use a call as an expression
(e.g., the operand of an addition), Lua keeps only the first result.
· We get all results only when the call is
the last (or the only) expression in a list of expressions.

print(foo2(), 1) -- a 1
print(foo2() .. 'x') -- ax

t = {foo0(), foo2(), 4} -- t[1] = nil, t[2] = "a", t[3] = 4

We can force a call to return exactly one result by enclosing it in an extra pair of parentheses.

ipairs{...}
local a, b = ...
local arg = table.pack(...) -- arg.n
select(2, "a", "b", "c") -- b c
select('#', a, b, c) -- 3

table.unpack
table.unpack({"Sun", "Mon", "Tue", "Wed"}, 2, 3) -- Mon Tue

io.input(filename)
io.output
避免 io.write(a..b..c)
print automatically applies tostring to its arguments

io.read
a reads the whole file
l drop newline read -- default
L read a line
n read a number
[*]num reads num chars as a string

io.lines()
table.sort

io.read(0) -- test for end of file
local n1, n2, n3 = io.read("n", "n", "n")

io.open -- nil 'error msg'

local f = assert(io.open(filename, "r"))
local t = f:read("a")
f:close()

io.stderr:write(message)
io.input() --
io.input():close()

for block in io.input():lines(2^13) do
io.write(block)
end

io.tmpfile -- read/write
io.flush()

setvbuf(mode[, bufsize])
no
full
line

f:seek(whence, offset)
set, cur, end
return current position of the stream, measured in bytes
from the beginning of the file.

function fsize (file)
local current = file:seek()
local size = file:seek("end")
file:seek("set", current)
return size
end

os.rename
os.remove

os.exit(true, true)
os.getenv("HOME")
os.execute -- true exit/signal return_status

f = io.popen(cmd, "w")
f = io.popen(cmd, "r)
f:close()
f:lines()

local to a control, function, chunk, then
do-end

strict.lua
raises an error if we try to assign to a non-existent global inside a function or to use a non-existent global.

local foo = foo

until terminates repeat structures

Lua has no switch statement

repeat–until statement repeats its body until its condition is true.

for var is local
do return end
::name::

table.sort(network, function (a,b) return (a.name > b.name) end)

Lib = {}
function Lib.foo (x, y) return x + y end

local fact
fact = function (n)
if n == 0 then return 1
else return n * fact(n-1)
end
end

do
Lua sandboxes
end

find, gsub, match, gmatch
string.find("a [word]", "[", 1, true) --> 3 3
string.gsub("all lii", "l", "x", 1)
When in doubt, play safe and use an escape.

balanced strings, %b()

%f[char-set]
string.gsub ("THE (QUICK) brOWN FOx JUMPS", "%f[%a]%u+%f[%A]", print)
"%f[%w]the%f[%W]" -- only as an entire word
d, m, y = string.match(date, "(%d+)/(%d+)/(%d+)")

_G

string.gsub(s, "\(%a+){(.-)}", "<%1>%2</%1>")

function toxml (s)
s = string.gsub(s, "\(%a+)(%b{})", function (tag, body)
body = string.sub(body, 2, -2) -- remove the brackets
body = toxml(body) -- handle nested commands
return string.format("<%s>%s</%s>", tag, body, tag)
end)
return s
end

print(toxml("\title{The \bold{big} example}"))
--> <title>The <bold>big</bold> example</title>

table.concat

print(string.match("hello", "()ll()")) --> 3 5

wday -- one is sunday
yday -- one is january 1st
isdst -- true is daylight saving is in effect

os.time({...})
os.date('*t', 0)
os.date("!%c", 0) -- utc
os.difftime
os.clock

bitwise operators only work on integer values

~ (bitwise exclusive-OR)

Lua does not offeran arithmetic right shift

a >> n is the same as a << -n

If the displacement is equal to or larger than the number of bits in the integer representation (64 in Standard
Lua, 32 in Small Lua), the result is zero, as all bits are shifted out of the result

he standard way to print numbers interprets
them as signed integers. We can use the %u or %x options in string.format to see integers as unsigned

math.ult

flip the signal bit of both operands
(0x7fffffffffffffff ~ mask) < (0x8000000000000000 ~ mask)

f = (u + 0.0) % 2^64 -- do not need 0.0

u = math.tointeger(((f + 2^63) % 2^64) - 2^63)

string.unpack("z", s, i) -- zero-terminated string

b (char),
h (short),
i (int), and l (long);
the option j uses the size of a Lua integer.

i1 - i16

s = table.concat(t, "\n") .. "\n"

string.format('%a', 1/3)
string.format("%q", a) -- works for nil and boolean

loadfile, dofile
f = load('i = i + 1')
-- load always compiles its chunks in the global environment.

A common mistake is to assume that loading a chunk defines functions
f = loadfile("foo.lua")
print(foo) --> nil
f() -- run the chunk
foo("ok") --> ok

luac -o prog.lc prog.lua

string.dump

pcall
xpcall -- debug.debug, debug.traceback

local f = require "mod".foo -- (require("mod")).foo

require

package.loaded
package.path

If require cannot find a Lua file with the module name,
it searches for a C library with that name.

package.cpath

package.loadlib

luaopen_modname

package.loaded[@rep{modname}]

local mod = require "mod".init(0, 0)

LUA_PATH_5_3 -> LUA_PATH -> compiled-defined default path
LUA_PATH_5_3 to "mydir/?.lua;; -- ;; 很重要
LUA_CPATH_5_3 or LUA_CPATH.
package.searchpath

lua -E

package.searchers
package.preload

package.loaded[...] = M

: if a module does not return a value, require will return the current value of
package.loaded[modname] (if it is not nil).

p -- p/init.lua
p.a -- p/a.lua luaopen_a_b

getmetatable
setmetatable

__metatable
__pairs
__index
mt.__index = prototype
rawget
__newindex
rawset(t, k, v)
local mt = {__index = function () return d end}
t[{}] = d

function Account:withdraw (v)
self.balance = self.balance - v
end

getmetatable(a).__index.deposit(a, 100.00)

rawset, which bypasses the metamethod

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,496评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,407评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,632评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,180评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,198评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,165评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,052评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,910评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,324评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,542评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,711评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,424评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,017评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,668评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,823评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,722评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,611评论 2 353

推荐阅读更多精彩内容

  • Lua 5.1 参考手册 by Roberto Ierusalimschy, Luiz Henrique de F...
    苏黎九歌阅读 13,788评论 0 38
  • 1.1程序块:Lua执行的每段代码,例如一个源代码文件或者交互模式中输入的一行代码,都称为一个程序块 1.2注释:...
    c_xiaoqiang阅读 2,587评论 0 9
  • Lua之参考 https://www.yiibai.com/lua/lua_basic_syntax.html[h...
    xiao_mini阅读 637评论 0 0
  • lua基础数据类型 nil 一个变量在第一次赋值前的默认值是 nil, 将nil 赋予给一个全局变量就等同于删除它...
    毛球小二阅读 2,015评论 0 6
  • Lua 全教程 本文目录 Lua 简介 Lua 版本 Lua 环境开发工具软件包管理分析和调试 基础概念常量和标识...
    Hello_Muay阅读 5,477评论 0 2