�Ʒ� �� www.codingnow.com
Copyright © 2006 Lua.org, PUC-Rio. All rights reserved.
Lua ��һ����չʽ����������ԣ�������Ƴ�֧��ͨ�õĹ���ʽ��̣��������������������ʩ�� Lua Ҳ�ܶ���������̣�����ʽ��̣���������ʽ����ṩ�ܺõ�֧�֡� ��������Ϊһ��ǿ�������Ľű����ԣ����κ���Ҫ�ij���ʹ�á� Lua ��һ���� clean C д�ɵĿ���ʽ�ṩ������ν Clean C ��ָ�� ANSI C �� C++ �й�ͨ��һ���Ӽ���
��Ϊһ����չʽ���ԣ�Lua û�� "main" ����ĸ����ֻ�� Ƕ�� һ�����������й������������������
embedding program ����Ϊ host ��
�����������ͨ�����ú���ִ��һС�� Lua ���룬���Զ�д Lua ����������ע�� C ������ Lua ������á�
��Щ��չ�� C ���������Դ�����չ�� Lua ���Դ�����������������Ϳ��Զ��Ƴ��������ԣ�
�����ǹ���һ��ͳһ�ľ䷨��ʽ�Ŀ�ܡ�
Lua �Ĺٷ�������Ͱ�����һ������ lua �ļ������������� Lua ���ṩ��һ����֤������ Lua ��������
Lua ��һ����������������ʹ�����ɾ����˶�����ʹ�ù���һ��û���κα�֤��
����ֲ��������Ķ�����ʵ�֣������� Lua �Ĺٷ���վ www.lua.org �ҵ���
������������ο��ֲ�һ��������ĵ���Щ�ط��ȽϿ�� ���� Lua ������뷨��̽�֣����Կ��� Lua ��վ���ṩ�ļ������ġ� �й��� Lua ��̵�ϸ�ڽ��ܣ����Զ�һ�� Roberto ���飬Programming in Lua (Second Edition) ��
��һ�ڴӴʷ�������䷨������ Lua �� ���仰˵����һ����������Щ token �����ǣ�����Ч�ģ�������α������������Щ��Ϸ�ʽ��ʲô���塣
�������ԵĹ��ɸ���ó�������չ BNF ����ʽд����Ҳ����������ӣ� {a} ��˼�� 0 ���� a �� [a] ��˼��һ����ѡ�� a �� �����յķ��Żᱣ��ԭ�������ӣ��ؼ��������������� kword �� �������յķ�����д�� `=´ �� ������ Lua ������ڱ��ֲ�����ҵ���
Lua ���õ��� ������Ҳ���� ��ʶ�����������κη����ֿ�ͷ����ĸ�����֡��»�����ɵ��ַ����� ����ϼ������б�������й������ֵĶ��塣 ����ĸ�Ķ��������ڵ�ǰ������ϵͳ�����ж������ĸ���е���ĸ�����Ա����ڱ�ʶ������ ��ʶ��������������������Ϊ����������
����Ĺؼ����DZ����ģ������������֣�
and break do else elseif
end false for function if
in local nil not or
repeat return then true until while
Lua ��һ����Сд���е����ԣ�
and ��һ�������֣����� And �� AND ����������ͬ�ĺϷ������֡�
һ��Լ�������»��߿�ͷ����һ����д��ĸ�����֣����� _VERSION������������ Lua �ڲ�ȫ�ֱ�����
�������������� token ��
+ - * / % ^ #
== ~= <= >= < > =
( ) { } [ ]
; : , . .. ...
�ַ����ȿ�����һ�Ե���������Ҳ������˫���ţ����滹���������� C ��ת�����
'\a' �����壩��
'\b' ���˸�
'\f' ����������
'\n' ��������
'\r' ���س�����
'\t' �������Ʊ�����
'\v' �������Ʊ�����
'\\' ����б�ܣ���
'\"' ��˫���ţ���
�Լ� '\'' ��������)��
���ң������һ����б�ܺ����һ�������Ļ��з��������������ַ����в���һ�����з���
���ǻ������÷�б�ܼ����ֵ���ʽ \ddd ������һ���ַ������
ddd ��һ�������λ��ʮ�������֡���ע�⣬�����Ҫ�����������������һ�������ֵ��ַ���
��ô��б�ܺ����д���������֡���Lua �е��ַ����������κ� 8 λ��ֵ�������� '\0' ��ʾ���㡣
ֻ��������Ҫ�Ѳ�ͬ�����š����С���б�ܡ��������������Щ�ַ������ַ���ʱ�� ��ű���ʹ��ת���������κ��ַ�������ֱ��д���ı����һЩ���Ʒ����Ի�Ӱ���ļ�ϵͳ���ijЩ���⣬ ���Dz������� Lua ���κ����⡣��
�ַ�����������һ�ֳ������������ķ�ʽ���塣
���ǰ��������ķ����ż���� n ���ȺŶ���Ϊ�� n ���������š�
����˵��0 �����ij�����д�� [[ ��
һ�����ij�����д�� [=[ ����˵ȵȡ�
���ij���չҲ�����ƶ��壻
�ٸ����ӣ�4 �����ij�����д�� ]====] ��
һ�����ַ����������κ�һ�������ij����ſ�ʼ�����ɵ�һ��������ͬ�����ij����Ž�����
�����ʷ��������̽����ܷ������ƣ��������κ�ת��������Һ��Ե��κβ�ͬ����ij����š�
���ַ�ʽ�������ַ����������κζ�������Ȼ�ض�����ķ������ų��⡣
��һ��Լ���ǣ������ij����ź�����������һ�����з���
������з��Ͳ�����������ַ����ڡ�
�ٸ����ӣ�����һ��ϵͳʹ�� ASCII ��
����ʱ��'a' ����Ϊ 97 �����з�����Ϊ 10 ��'1' ����Ϊ 49 ����
�������ַ�ʽ��������ȫ��ͬ���ַ�����
a = 'alo\n123"'
a = "alo\n123\""
a = '\97lo\10\04923"'
a = [[alo
123"]]
a = [==[
alo
123"]==]
���ֳ������Է�������д��ʮ���Ƶ������ֺ�ʮ���Ƶ�ָ�����֡�ָ�������ǿ�ѡ�ġ�
Lua Ҳ֧��ʮ����������������ֻ��Ҫ��ǰ�����ǰ 0x ��
������һЩ�Ϸ������ֳ��������ӣ�
3 3.0 3.1416 314.16e-2 0.31416E1 0xff 0x56
ע�Ϳ����ڳ��ַ����ڵ��κεط��������� (--) ��ʼ��
��������������IJ���һ�������ţ������һ����ע�ͣ��������÷�Χֱ����ĩ��
�������һ����ע�ͣ������÷�Χֱ���������ij����š�
��ע��ͨ����������ʱ���δ���顣
Lua ��һ�� ��̬���������� ����ζ�ű���û�����ͣ�ֻ��ֵ�������͡� �����в��������Ͷ��塣�����е�ֵ����Я�������Լ���������Ϣ��
Lua �е�����ֵ����һ�� (first-class) �ġ� ����ζ�����е�ֵ�����Ա����ڱ���������������ݵ���һ�������У�����������Ϊ������ء�
Lua ���а��ֻ������ͣ�
nil, boolean, number,
string, function, userdata,
thread, and table.
Nil ����ֻ��һ��ֵ nil ��������Ҫ��;���ڱ��ʶ�ͱ���κ�ֵ�IJ��죻
ͨ��������Ҫ����һ���������ֵʱ���õ�����
Boolean ����ֻ������ֵ��false �� true��
nil �� false ���ܵ�������Ϊ�٣����������е�ֵ���������档
Number ��ʾʵ����˫���ȸ���������
������һ�������ڲ��������͵� Lua �������Ǽ��������£�������ڲ�����������
�����ȸ����������͡��μ��ļ� luaconf.h ����
String ��ʾһ���ַ������顣
Lua �� 8-bit clean �ģ�
�ַ����������κ� 8 λ�ַ���
����������� ('\0') ���μ� §2.1����
Lua ���Ե��ã��ʹ������� Lua д�ĺ����Լ��� C д�ĺ������μ� §2.5.8��.
userdata �������������� C ���ݱ����� Lua �����С� ��������൱��һ��ԭ�����ڴ棬���˸�ֵ����ͬ���жϣ�Lua û��Ϊ֮Ԥ�����κβ����� Ȼ����ͨ��ʹ�� metatable ��Ԫ���� ������Ա����Ϊ userdata �Զ���һ����� ���μ� §2.8���� userdata ������ Lua �д���������Ҳ������ Lua ���ġ������IJ���ֻ��ͨ�� C API�� ��һ�㱣֤������������ȫ�ƹ����е����ݡ�
thread �����������������ִ���̣߳���������ʵ�� coroutine ��Эͬ���̣����μ� §2.11���� ��Ҫ�� Lua �̸߳�����ϵͳ���̸߳�졣 Lua ���������е�ϵͳ���ṩ�� coroutine ��֧�֣���ʹϵͳ����֧���̡߳�
table ����ʵ����һ���������顣Ҳ����˵��
����������κζ���������nil���������������������֡�
table �����Բ�ͬ���͵�ֵ���ɣ������������е����͵�ֵ���� nil �⣩��
table �� lua ��Ψһ��һ�����ݽṹ����������������ԭʼ�����顢���ű������ϡ�
��¼��ͼ�������ȵȡ�
���ڱ�����¼ʱ��lua ʹ��������Ϊ������
���Ա�������һ����ǣ�֧���� a.name ����ʽ��ʾ a["name"]��
�кܶ���ʽ������ lua �д���һ�� table ���μ� §2.5.7����
������һ���� table ÿ�����е�ֵҲ�������κ����ͣ��� nil�⣩�� �ر�ģ���Ϊ��������Ҳ��ֵ������ table ������Ҳ���Էź����� ���� table �оͿ�����һЩ methods �� ���μ�see §2.5.9����
table�� function ��thread ���� (full) userdata ��Щ���͵�ֵ����ν�Ķ��� �������������������Ĵ�����ǵ�ֵ����ֻ�Ƿ���һ���Զ�������á� ��ֵ���������ݣ��������أ����Ƕ���Щ��������ý��в����� ��Щ�������������������κ����ʵĿ�����
�⺯�� type ���Է���һ����������ֵ�����͵��ַ�����
Lua �ṩ����ʱ�ַ��������ֵ��Զ�ת����
�κζ��ַ�������ѧ����������᳢����һ���ת�����������ַ���ת����һ�����֡�
�෴�����ۺ�ʱ��һ��������Ҫ��Ϊ�ַ�����ʹ��ʱ�����ֶ����Ժ����ĸ�ʽת��Ϊ�ַ�����
��Ҫ��ȫ������������ת��Ϊ�ַ���������ʹ���ַ������е� format ����
���μ� string.format����
д�ϱ����ĵط���ζ�ŵ����䱣���ֵ�����֮�� Lua �������������ȫ�ֱ������ֲ����������� table ����
һ����һ�����ֿ��Ա�ʾһ��ȫ�ֱ�����Ҳ���Ա�ʾһ���ֲ����� ��������һ�������IJ���������һ��������ʽ�ľֲ���������
var ::= Name
Name ���� §2.1 ��������ı�ʶ����
�κα��������ٶ�Ϊȫ�ֱ�����������ʽ���� local ���ζ��� ���μ� §2.4.7���� �ֲ������������÷�Χ�� �ֲ��������Ա������������÷�Χ�еĺ�������ʹ�� ���μ� §2.6����
�ڱ������״θ�ֵ֮ǰ��������ֵ��Ϊ nil��
�����ű������� table ��������
var ::= prefixexp `[´ exp `]´
��ȫ�ֱ����Լ� table ��֮���ʵĺ������ͨ�� metatable ���ı䡣
��ȡһ�������±�ָ����� t[i] �ȼ��ڵ��� gettable_event(t,i)��
���μ� §2.8 ����һ�������Ĺ���
gettable_event ������˵����
���������û���� lua �ж��������Ҳ������ lua �е��á�
�������ǰ����г���ֻ�Ƿ���˵������
var.Name �����ֻ��һ����ǣ�������ʾ
var["Name"]��
var ::= prefixexp `.´ Name
���е�ȫ�ֱ������Ƿ���һ���ض� lua table ��������У�����ض��� table
���� environment ��������table �����Ϊ
���� ���μ� §2.9����
ÿ���������ж�һ�����������ã�
����һ�������пɼ�������ȫ�ֱ���������������������õĻ�������environment table���С�
��һ����������������������Ӵ������ĺ����м̳��价��������Ե���
getfenv ȡ���价����
�����ı价�������Ե��� setfenv��
������ C ��������ֻ��ͨ�� debug �����ı��价����
�μ� §5.9����
��һ��ȫ�ֱ��� x �ķ���
�ȼ��� _env.x�������ֿ��Եȼ���
gettable_event(_env, "x")
���_env �ǵ�ǰ���еĺ����Ļ�����
������ gettable_event ������˵���μ� §2.8��
���������û���� lua �ж��������Ҳ���ܵ��á�
��Ȼ��_env �������Ҳͬ��û���� Lua �ж��������
����������ʹ�����ǣ�����ֻ�Ƿ�����Ͷ��ѡ���
Lua ֧�ֹ�����ʽ�����Σ����� Pascal ���� C ������ ������ϰ�����ֵ�����ƽṹ���������ã����б���������
Lua ��һ��ִ�е�Ԫ������ chunk�� һ�� chunk ����һ�����Σ����ǻᱻѭ���ִ�С� ÿ�����ο�����һ���ֺŽ�����
chunk ::= {stat [`;´]}
����������пյ����Σ����� ';;' �ǷǷ��ġ�
lua ��һ�� chunk ����һ��ӵ�в����������������� ���μ� §2.5.9�������� ����������chunk �ڿ��Զ���ֲ����������ղ��������ҷ���ֵ��
chunk ���Ա�������һ���ļ��У�Ҳ���Ա��������������һ���ַ����С� ��һ�� chunk ��ִ�У��������ᱻԤ�����������е�ָ�����У� Ȼ�����������������Щָ�
chunk Ҳ���Ա�Ԥ����ɶ�������ʽ��ϸ�ڲο����� luac��
��Դ����ʽ�ṩ�ij���ͱ�������Ķ�������ʽ�ij����ǿ�����滻�ģ�
Lua ���Զ�ʶ���ļ����Ͳ�����ȷ�Ĵ�����
������һ�����Σ��������˵��һ�������һ�� chunk ��ͬ��
block ::= chunk
һ��������Ա���ʽ��д��һ�����������Σ�
stat ::= do block end
��ʽ��������ڿ��Ʊ��������÷�Χ�����á� ��ʱ����ʽ�����鱻��������һ�������в��� return ���� break ���μ� §2.4.4����
Lua �������ظ�ֵ�� ��ˣ���ֵ��������ǵȺ���߷�һϵ�б����� ���Ⱥ��ұ߷�һϵ�еı���ʽ�� ���ߵ�Ԫ�ض��ö��ż俪��
stat ::= varlist1 `=´ explist1
varlist1 ::= var {`,´ var}
explist1 ::= exp {`,´ exp}
����ʽ���� §2.5 �����ۡ�
������ֵ����֮ǰ�� ��һϵ�е���ֵ�ᱻ���뵽��߱�����Ҫ�ĸ����� �����ֵ����Ҫ�ĸ���Ļ��������ֵ�ͱ��ӵ��� �����ֵ�������������� ���ᰴ������չ���ɸ� nil�� �������ʽ�б���һ���������ý����� ������������ص�����ֵ�����ڶ������֮ǰ��������ֵ�����С� ����������������ñ������������������μ� §2.5����
��ֵ�����Ȼ������������еı���ʽ��Ȼ���������ֵ������ ��ˣ�������δ���
i = 3
i, a[i] = i+1, 20
��� a[3] ����Ϊ 20��������Ӱ�쵽 a[4] ��
������Ϊ a[i] �е� i �ڱ���ֵΪ 4 ֮ǰ�ͱ��ó����ˣ���ʱ�� 3 ����
��˵ ������һ��
x, y = y, x
������������ x �� y �е�ֵ��
��ȫ�ֱ����Լ� table �е���ĸ�ֵ�����ĺ������ͨ�� metatable ���ı䡣
�Ա����±�ָ��ĸ�ֵ���� t[i] = val �ȼ���
settable_event(t,i,val)��
�����ں��� settable_event ����ϸ˵�����μ� §2.8��
���������û���� Lua �ж��������Ҳ�����Ա����á�
���������г������������ڷ�����͵�Ŀ�ģ�
����ȫ�ֱ����ĸ�ֵ x = val
�ȼ���
_env.x = val������ֿ��Եȼ���
settable_event(_env, "x", val)
���_env ָ�������������еĺ����Ļ�����
������ _env ��û���� Lua �ж��������
���ǽ������ڽ��͵�Ŀ��������д��������
if�� while���Լ� repeat ��Щ���ƽṹ����ͨ�������壬����Ҳ�����Ƶ����
stat ::= while exp do block end
stat ::= repeat block until exp
stat ::= if exp then block {elseif exp then block} [else block] end
Lua Ҳ��һ�� for ��䣬����������ʽ���μ� §2.4.5����
���ƽṹ�е���������ʽ���Է����κ�ֵ�� false �� nil ���߶�����Ϊ�Ǽ������� ���в�ͬ�� nil �� false ������ֵ������Ϊ���� ���ر���Ҫע����ǣ����� 0 �Ϳ��ַ���Ҳ����Ϊ���棩��
�� repeat–until ѭ���У� �ڲ�����Ľ����㲻���� until ����ؼ��ִ��� ����������������������ʽ�� ��ˣ���������ʽ�п���ʹ��ѭ���ڲ������еĶ���ľֲ�������
return �����ڴӺ������� chunk����ʵ������һ���������� ����ֵ�� ������ chunk ���Է��ز�ֻһ��ֵ�� ���� return ���Ϊ
stat ::= return [explist1]
break ���������� while�� repeat���� for ѭ���� �������Ե�ѭ������������ε����У�
stat ::= break
break �������ڲ��ѭ����
return �� break ֻ�ܱ�д��һ����������һ�䡣
����������Ҫ��������м� return ���� break ��
�����ʹ����ʽ������һ���ڲ����顣
һ��д�� do return end ���� do break end��
��������д����Ϊ���� return �� break ������һ����������һ���ˡ�
for ��������ʽ��һ����������ʽ����һ����һ����ʽ��
������ʽ�� for ѭ����ͨ��һ����ѧ���㲻�ϵ������ڲ��Ĵ���顣 �������������
stat ::= for Name `=´ exp `,´ exp [`,´ exp] do block end
block ���� name ��ѭ���������ӵ�һ�� exp ��ʼ��ֱ���ڶ��� exp ��ֵΪֹ���䲽��Ϊ ������ exp �� ��ȷ�е�˵��һ�� for ѭ�����������������
for v = e1, e2, e3 do block end
��ȼ��ڴ��룺
do
local var, limit, step = tonumber(e1), tonumber(e2), tonumber(e3)
if not (var and limit and step) then error() end
while (step > 0 and var <= limit) or (step <= 0 and var >= limit) do
local v = var
block
var = var + step
end
end
ע�������⼸�㣺
var ��limit ���Լ� step ����һЩ���ɼ��ı�����
���������������ֶ��������ڽ��ͷ��㡣
v ��һ��ѭ���ڲ��ľֲ�������
�� for ѭ����������Ͳ�����ʹ������
�������Ҫ���ֵ�����˳�ѭ��ǰ����������һ��������
һ����ʽ�� for ͨ��һ��������������iterators���ĺ��������� ÿ�ε������������������ᱻ�����Բ���һ���µ�ֵ�� �����ֵΪ nil ʱ��ѭ��ֹͣ�� һ����ʽ�� for ѭ��������£�
stat ::= for namelist in explist1 do block end
namelist ::= Name {`,´ Name}
for ����������
for var_1, ···, var_n in explist do block end
���ȼ�������һ�δ��룺
do
local f, s, var = explist
while true do
local var_1, ···, var_n = f(s, var)
var = var_1
if var == nil then break end
block
end
end
ע�����¼��㣺
explist ֻ�ᱻ����һ�Ρ�
����������ֵ�� һ��������������һ��״̬��һ���������ij�ʼֵ��
f�� s�� �Լ� var ���Dz��ɼ��ı�����
���������������ֶ�ֻ��Ϊ�˽�˵���㡣
var_i ����ѭ����˵��һ���ֲ�������
�㲻������ for ѭ�����������ʹ�á�
�������Ҫ������Щֵ����ô����ѭ������ǰ��ֵ����ı�����ȥ��
Ϊ������ʹ�ÿ��ܵĸ����ã� �������ÿ��Ա���Ϊһ������ִ�У�
stat ::= functioncall
����������£����еķ���ֵ���������� ���������� §2.5.8 �н��͡�
�ֲ������������������κεط������� ����������һ����ʼ����ֵ������
stat ::= local namelist [`=´ explist1]
����еĻ�����ʼ����ֵ��������Ϊ��ͬ�ڸ�ֵ�������μ� §2.4.3���� �������еı���������ʼ��Ϊ nil��
һ�� chunk ͬʱҲ��һ�����飨�μ� §2.4.1���� ���Ծֲ��������Է��� chunk ����Щ��ʽע��������֮�⡣ ��Щ�ֲ����������÷�Χ��������һֱ���쵽 chunk ĩβ��
�ֲ������Ŀɼ������� §2.6 �н��͡�
Lua ������Щ��������ʽ��
exp ::= prefixexp exp ::= nil | false | true exp ::= Number exp ::= String exp ::= function exp ::= tableconstructor exp ::= `...´ exp ::= exp binop exp exp ::= unop exp prefixexp ::= var | functioncall | `(´ exp `)´
���ֺ��ַ����� §2.1 �н��ͣ�
������ §2.3 �н��ͣ�
���������� §2.5.9 �н��ͣ�
���������� §2.5.8 �н��ͣ�
table �Ĺ����� §2.5.7 �н��ͣ�
�ɱ�����ı���ʽд�������� ('...') ����ֻ�ܱ������пɱ�����ĺ����У�
��Щ�� §2.5.9 �н��͡�
��Ԫ��������������ѧ������������μ� §2.5.1���� �Ƚϲ��������μ� §2.5.2���������������μ� §2.5.3���� �Լ����Ӳ��������μ� §2.5.4���� һԪ�������������ţ��μ�see §2.5.1���� ȡ�� not���μ� §2.5.3���� ��ȡ���Ȳ��������μ� §2.5.5����
�������úͿɱ��������ʽ�����Է��ڶ��ط���ֵ�С� �������ʽ��Ϊһ���������γ��֣��μ� §2.4.6�� ����ֻ����һ���������ã��� ���ǵķ����б��������뵽���Ԫ�أ�Ҳ���Ǻ������з���ֵ�� �������ʽ���ڱ���ʽ�б����������Ψһ����Ԫ�أ� �Ͳ������κεĶ�����������Ǻ����������������������� ���κ�����������£�Lua ���ѱ���ʽ������ɵ�һԪ�أ� ���Գ���һ��֮����κ�ֵ��
������һЩ���ӣ�
f() -- ������ 0 �����
g(f(), x) -- f() ��������һ�����
g(x, f()) -- g ������ x �������� f() �ķ���ֵ
a,b,c = f(), x -- f() ��������һ����� �� c �����ﱻ��Ϊ nil ��
a,b = ... -- a ����ֵΪ�ɱ�����еĵ�һ����
-- b ����ֵΪ�ڶ��� ������ɱ�����в�û�ж�Ӧ��ֵ��
-- ���� a �� b ���п��ܱ���Ϊ nil��
a,b,c = x, f() -- f() �������������
a,b,c = f() -- f() �������������
return f() -- ���� f() ���ص����н��
return ... -- �������дӿɱ�����н�������ֵ
return x,y,f() -- ���� x, y, �Լ����� f() �ķ���ֵ
{f()} -- �� f() �����з���ֵ����һ���б�
{...} -- �ÿɱ�����е�����ֵ����һ���б�
{f(), nil} -- f() ������Ϊһ�����
�������������ı���ʽ��Զ������һ��ֵ�����ԣ�
(f(x,y,z)) ��ʹ f ���ض��ֵ���������ʽ��Զ��һ����һֵ��
��(f(x,y,z)) ��ֵ�� f ���صĵ�һ��ֵ����� f
������ֵ�Ļ�����ô����ֵ���� nil ����
Lua ֧�ֳ�������ѧ�����������
��Ԫ���� + ���ӷ�����
- ����������* ���˷�����
/ ���������� % ��ȡģ�����Լ� ^ ���ݣ���
��һԪ���� - ��ȡ������
��������ֲ��������ǿ���ת��Ϊ���ֵ��ַ������μ� §2.2.1����
������Щ������������ͨ���ĺ��塣
�ݲ������Զ��κ���ֵ���������������磬
x^(-0.5) ������� x ƽ�����ĵ�����
ȡģ����������Ϊ
a % b == a - math.floor(a/b)*b
�����˵������������Ը�����Բ���������������ע������������ȡģ�Ľ��Ϊ������
Lua �еıȽϲ�������
== ~= < > <= >=
��Щ�����Ľ������ false ���� true��
���ڲ��� (==) ���ȱȽϲ����������͡�
������Ͳ�ͬ��������� false��
�������Ƚ�ֵ��
���ֺ��ַ������ó���ķ�ʽ�Ƚϡ�
���� ��table ��userdata ��thread ���Լ������������õ���ʽ�Ƚϣ�
��������ֻ��������ָ��ͬһ������ʱ����Ϊ��ȡ�
ÿ���㴴��һ���¶���һ�� table ���� userdata ��thread ��������
���Ƕ�������ͬ������ͬ���ϴδ����Ķ�����
����Ըı� Lua �Ƚ� table �� userdata �ķ�ʽ������Ҫʹ�� "eq" ���ԭ���� ���μ� §2.8����
§2.2.1 ���ἰ��ת�����������ڱȽϲ�����
���ԣ� "0"==0 ���� false��
���� t[0] �� t["0"] �������� table �в�ͬ����
������ ~= ��ȫ�ȼ��� (==) �����ķ�ֵ��
��С�Ƚϲ��������·�ʽ���С� ��������������֣���ô��ֱ�������ֱȽϡ� ����������������ַ����������ַ����Ƚϵķ�ʽ���С� ����Lua �����ŵ��� "lt" ���� "le" Ԫ���� ���μ� §2.8����
Lua �е����������� and, or, �Լ� not�� �Ϳ��ƽṹ���μ� §2.4.4��һ���� ���е����������� false �� nil ����Ϊ�٣� ��������һ�ж������档
ȡ������ not ���Ƿ��� false �� true �е�һ���� ������� and �ڵ�һ������Ϊ false �� nil ʱ �������һ�������� ����and ���صڶ��������� ������� or �ڵ�һ��������Ϊ nil Ҳ��Ϊ false ʱ�� �������һ�����������صڶ��������� and �� or ����ѭ��·���� Ҳ����˵���ڶ���������ֻ����Ҫ��ʱ��ȥ��ֵ�� ������һЩ���ӣ�
10 or 20 --> 10
10 or error() --> 10
nil or "a" --> "a"
nil and 10 --> nil
false and error() --> false
false and nil --> false
false or nil --> nil
10 and 20 --> 20
�����Ȿ�ֲ��У� --> ָǰ�����ʽ�Ľ������
Lua ���ַ��������Ӳ�����д�������� ('..')��
������������������ַ����������֣����Ӳ������� §2.2.1 ���ᵽ�Ĺ������ת��Ϊ�ַ�����
����ȡ����Ԫ���� "concat" ���μ� §2.8����
ȡ���Ȳ�����д��һԪ���� #��
�ַ����ij����������ֽ�����������һ���ַ�һ���ֽڼ�����ַ������ȣ���
table t �ij��ȱ������һ�������±� n ��
������ t[n] ���� nil �� t[n+1] Ϊ nil��
���⣬��� t[1] Ϊ nil ��n �Ϳ������㡣
���ڳ�������飬����� 1 �� n ����һЩ�ǿյ�ֵ��ʱ��
���ij��Ⱦ;�ȷ��Ϊ n�������һ��ֵ���±ꡣ
���������һ�����ն��� ������˵��nil ֵ�����ڷǿ�ֵ֮�䣩��
��ô #t ������ָ���κ�һ���� nil ֵ��ǰһ��λ�õ��±�
������˵���κ�һ�� nil ֵ���п��ܱ���������Ľ�������
Lua �в����������ȼ�д���±��У��ӵ͵������ȼ�����
or
and
< > <= >= ~= ==
..
+ -
* / %
not # - (unary)
^
ͨ������������������ı��������
���Ӳ����� ('..') ���ݲ��� ('^') �Ǵ�������ġ�
�������еIJ������Ǵ������ҡ�
table ��������һ������ table �ı���ʽ�� ÿ�ι����ӱ�ִ�У����ṹ���һ���µ� table �� �����ӿ��Ա���������һ���յ� table�� Ҳ������������һ�� table ����ʼ�����е�һЩ�� һ��Ĺ����ӵ������
tableconstructor ::= `{´ [fieldlist] `}´
fieldlist ::= field {fieldsep field} [fieldsep]
field ::= `[´ exp `]´ `=´ exp | Name `=´ exp | exp
fieldsep ::= `,´ | `;´
ÿ������ [exp1] = exp2 ������ table �������µ�һ�
���ֵΪ exp1 ��ֵΪ exp2��
���� name = exp ����ȼ���
["name"] = exp��
������� exp ����ȼ���
[i] = exp �� ����� i ��һ���� 1 ��ʼ�������������֡�
�������ʽ�е��������ƻ��������
�ٸ����ӣ�
a = { [f(1)] = g; "x", "y"; x = 1, f(x), [30] = 23; 45 }
�ȼ���
do
local t = {}
t[f(1)] = g
t[1] = "x" -- 1st exp
t[2] = "y" -- 2nd exp
t.x = 1 -- t["x"] = 1
t[3] = f(x) -- 3rd exp
t[30] = 23
t[4] = 45 -- 4th exp
a = t
end
������������һ�������ʽ�� exp ��
���������ʽ��һ���������û�����һ���ɱ������
��ô�������ʽ���еķ���ֵ�������Ľ����б�
���μ� §2.5.8����
Ϊ�˱�����һ�㣬����������ŰѺ������ã����ǿɱ������������
���μ� §2.5����
��ʼ���������������һ���ָ���� ������ƿ��Է����ɻ������ɴ��롣
Lua �еĺ������õ�����£�
functioncall ::= prefixexp args
��������ʱ����һ����prefixexp �� args �ȱ���ֵ�� ��� prefixexp ��ֵ�������� function�� ��ô��������ͱ��ø����IJ������á� ���� prefixexp ��Ԫ���� "call" �ͱ����ã� ��һ���������� prefixexp ��ֵ������������ԭ���ĵ��ò��� ���μ� §2.8����
��������ʽ
functioncall ::= prefixexp `:´ Name args
������������ "����"��
���� Lua ֧�ֵ�һ����ǡ��� v:name(args)
������ӣ������ͳ� v.name(v,args)��
���� v ֻ�ᱻ��ֵһ�Ρ�
����������£�
args ::= `(´ [explist1] `)´ args ::= tableconstructor args ::= String
���в����ı���ʽ��ֵ���ں�������֮ǰ��
�����ĵ�����ʽ f{fields} ��һ��������ڱ�ʾ
f({fields})��
����ָ�����б���һ����һ���´����������б���
����������ʽ f'string'
������ f"string" ����� f[[string]]��
Ҳ��һ����ǣ����ڱ�ʾ f('string')��
����ָ�����б���һ���������ַ�����
��Ϊ����ʽ��� Lua �бȽ����ɣ�
�����㲻���ں������õ� '(' ǰ���С�
������ƿ��Ա��������е�һЩ���塣
����������д
a = f
(g).x(a)
Lua ����������һ����һ���Σ� a = f(g).x(a) ��
��ˣ�������������Ϊ���������Σ������������֮��д��һ���ֺš�
������������� f��
������ (g) ǰ��ȥ���С�
����һ�ֵ�����ʽ��return functioncall ������һ��β���á�
Lua ʵ�����ʵ���β�����ã������ʵ���β�ݹ飩��
��β�����У�
�����õĺ������õ������ĺ����Ķ�ջ�
��ˣ����ڳ���ִ�е�Ƕ��β���õIJ�����û�����Ƶġ�
Ȼ����β���ý�ɾ���������ĺ������κε�����Ϣ��
ע�⣬β����ֻ�������ض�����£�
��ʱ�� return ֻ�е�һ����������Ϊ������
�����ʹ�õ��ú����Ľ�����Ծ�ȷ���ء�
��ˣ�������Щ���Ӷ�����β���ã�
return (f(x)) -- ����ֵ������Ϊһ��
return 2 * f(x)
return x, f(x) -- ������ɷ���ֵ
f(x); return -- ����ֵ
return x or f(x) -- ����ֵ������Ϊһ��
�������������£�
function ::= function funcbody funcbody ::= `(´ [parlist1] `)´ block end
���ⶨ����һЩ��Ǽ��������д����
stat ::= function funcname funcbody
stat ::= local function Name funcbody
funcname ::= Name {`.´ Name} [`:´ Name]
���������
function f () body end
��ת����
f = function () body end
���������
function t.a.b.c.f () body end
��ת����
t.a.b.c.f = function () body end
���������
local function f () body end
��ת����
local f; f = function () body end
ע�⣬������ת����
local f = function () body end
��������ֻ�ں���������Ҫ���� f ʱ���С���
һ������������һ����ִ�еı���ʽ�� ִ�н����һ������Ϊ function ��ֵ�� �� Lua Ԥ����һ�� chunk ��ʱ�� chunk ��Ϊһ������������������Ҳ�ͱ�Ԥ�����ˡ� ��ô�����ۺ�ʱ Lua ִ���˺������壬 ������������ͱ�ʵ�����ˣ�����˵�ǹر��ˣ��� ���������ʵ��������˵�� closure���հ����� �DZ���ʽ������ֵ�� ��ͬ�����IJ�ͬʵ���п������ò�ͬ���ⲿ�ֲ������� Ҳ����ӵ�в�ͬ�Ļ�������
�βΣ�����������Ҫ�IJ�������һЩ��ʵ�Σ�ʵ�ʴ����������ֵ��ʼ���ľֲ�������
parlist1 ::= namelist [`,´ `...´] | `...´
��һ�����������ã�
�������û�б�����Ϊ���ղ����������������β��б���ĩβע�������� ('...')��
��ôʵ���б��ͻᱻ�������β��б��ij��ȣ�
�䳤���������������ʵ���б���
ȡ����֮���ǣ����������ж���IJ�������һ��ͨ���䳤��������ʽ���ݸ�������
��д�������������㡣
�������ʽ��ֵ��һ��ʵ��ֵ���б�����������һ�����Է��ض������ĺ���һ����
���һ���䳤��������ʽ������һ������ʽ��ʹ�ã����Ƿ�����һ������ʽ���м䣬
��ô���ķ���ֵ�ͻᱻ����Ϊ����ֵ��
���������ʽ������һϵ�б���ʽ�����һ�����Ͳ����������ˣ����������Ÿ�������������
�����������¶��壬Ȼ��������һ�����ӣ�
function f(a, b) end
function g(a, b, ...) end
function r() return 1,2,3 end
���濴��ʵ�ε��β����Լ��ɱ䳤������ӳ���ϵ��
CALL PARAMETERS
f(3) a=3, b=nil
f(3, 4) a=3, b=4
f(3, 4, 5) a=3, b=4
f(r(), 10) a=1, b=10
f(r()) a=1, b=2
g(3) a=3, b=nil, ... --> (nothing)
g(3, 4) a=3, b=4, ... --> (nothing)
g(3, 4, 5, 8) a=3, b=4, ... --> 5 8
g(5, r()) a=5, b=1, ... --> 2 3
����� return �����أ��μ� §2.4.4���� ���ִ�е�����ĩβ����û�������κ� return ��䣬 �����Ͳ��᷵���κν����
ð��������������巽����
����˵������������һ����ʽ���β� self��
��ˣ�����д����
function t.a.b.c:f (params) body end
������һ��д������ǣ�
t.a.b.c.f = function (self, params) body end
Lua ��һ���дʷ����÷�Χ�����ԡ� ���������÷�Χ��ʼ����������֮��ĵ�һ�����Σ� �����ڰ���������������ڲ�����Ľ����㡣 ��������Щ���ӣ�
x = 10 -- ȫ�ֱ���
do -- �µ�����
local x = x -- �µ�һ�� 'x', ����ֵ������ 10
print(x) --> 10
x = x+1
do -- ��һ������
local x = x+1 -- ��һ�� 'x'
print(x) --> 12
end
print(x) --> 11
end
print(x) --> 10 ��ȡ������ȫ�ֵ���һ����
ע��������� local x = x ������������
�µ� x ���ڱ����������ǻ�û�н����������÷�Χ��
���Եڶ��� x ָ���������һ��ı�����
��Ϊ������һ���ʷ����÷�Χ�Ĺ��� ���Կ����ں����ڲ����ɵĶ���ֲ�������ʹ�����ǡ� ��һ���ֲ����������ڲ�ĺ�����ʹ�õ�ʱ�� �����ڲ㺯������ upvalue����ֵ�������� �ⲿ�ֲ�������
ע�⣬ÿ��ִ�е�һ�� local ��䶼�ᶨ���һ���µľֲ������� ��������һ�����ӣ�
a = {}
local x = 20
for i=1,10 do
local y = 0
a[i] = function () y=y+1; return x+y end
end
���ѭ��������ʮ�� closure����ָʮ������������ʵ������
��Щ closure �е�ÿһ����ʹ���˲�ͬ�� y ������
�������ֹ�����ͬһ�� x��
��Ϊ Lua ��һ��Ƕ��ʽ����չ���ԣ�
���е� Lua �������Ǵ���������� C ������� Lua ��
���μ� lua_pcall���е�һ��������ʼ�ġ�
�� Lua ��������е��κ�ʱ�����˴�����Ȩ���ύ���� C ��
�� C ��������һЩǡ���Ĵ�ʩ�������ӡ��һ��������Ϣ����
Lua ���������ʽ�ĵ��� error ����������һ������
�������Ҫ�� Lua �в������Ĵ���
�����ʹ�� pcall ������
Lua �е�ÿ��ֵ��������һ�� metatable��
��� metatable ����һ��ԭʼ�� Lua table ��
����������ԭʼֵ���ض������µ���Ϊ��
�����ͨ���� metatable �е��ض�����һЩֵ���ı�ӵ����� metatable ��ֵ
��ָ������֮��Ϊ��
������˵����һ�������ֵ�ֵ���ӷ�������ʱ��
Lua �������� metatable �� "__add" ���е��Ƿ���һ��������
�������ôһ�������Ļ���Lua �������������ִ��һ�μӷ���
���ǽ� metatable �еļ���Ϊ �¼� (event) �������е�ֵ���� Ԫ���� (metamethod)��
���ϸ������У��¼��� "add" ��Ԫ���������Ǹ�ִ�мӷ������ĺ�����
�����ͨ�� getmetatable ��������ѯ���κ�һ��ֵ�� metatable��
�����ͨ�� setmetatable �������滻�� table �� metatable ��
�㲻�ܴ� Lua �иı������κ����͵�ֵ�� metatable ��ʹ�� debug �����⣩��
Ҫ�������Ļ�����ʹ�� C API ��
ÿ�� table �� userdata ӵ�ж����� metatable ����Ȼ��� table �� userdata ���Թ���һ����ͬ�ı������ǵ� metatable���� �����������͵�ֵ��ÿ�����Ͷ��ֱ���Ψһ��һ�� metatable�� ��ˣ����е�����һ��ֻ��һ�� metatable �����е��ַ���Ҳ�ǣ��ȵȡ�
һ�� metatable ���Կ���һ����������ѧ����������Ƚϲ��������Ӳ�����ȡ���Ȳ�����ȡ�±����ʱ����Ϊ�� metatable �л����Զ���һ���������� userdata �������ռ�ʱ�������� ������Щ������Lua �����������һ���������¼���ָ������ �� Lua ��Ҫ��һ��ֵ������Щ�����е�һ��ʱ�� ����ȥ���ֵ�� metatable ���Ƿ��ж�Ӧ�¼��� ����еĻ���������Ӧ��ֵ��Ԫ������������ Lua ���������������
metatable ���Կ��ƵIJ������������г�����
ÿ������������Ӧ���������֡�
ÿ�������ļ��������ò������ּ��������»��� '__' ǰ���ַ�����
������˵��"add" �����ļ��������ַ��� "__add"��
��Щ������������һ�� Lua �������������������ִ�и�Ϊǡ����
����չʾ���� Lua д�Ĵ��������˵�ã�
ʵ�ʵ���Ϊ�Ѿ�Ӳ�����ڽ������У���ִ��Ч��ҪԶ������Щģ����롣
��Щ���������ĵĴ������õ��ĺ���
�� rawget �� tonumber ���ȵȡ���
�������� §5.1 ���ҵ���
�ر�ע�⣬����ʹ������һ������ʽ���Ӹ�����������ȡԪ����
metatable(obj)[event]
���Ӧ�ñ������
rawget(getmetatable(obj) or {}, event)
�����˵������һ��Ԫ�������ٻᴥ���κε�Ԫ������ ���ҷ���һ��û�� metatable �Ķ���Ҳ����ʧ�ܣ���ֻ�Ǽ��� nil����
+ ������
������� getbinhandler ���������� Lua ����ѡ��һ��������������Ԫ������
���ȣ�Lua ���Ե�һ����������
����������������û�ж�����������Ĵ�������Ȼ�� Lua �᳢�Եڶ�����������
function getbinhandler (op1, op2, event)
return metatable(op1)[event] or metatable(op2)[event]
end
ͨ����������� op1 + op2 ����Ϊ����
function add_event (op1, op2)
local o1, o2 = tonumber(op1), tonumber(op2)
if o1 and o2 then -- �����������������֣�
return o1 + o2 -- ����� '+' ��ԭ���� 'add'
else -- ����һ����������������ʱ
local h = getbinhandler(op1, op2, "__add")
if h then
-- ��������������������
return h(op1, op2)
else -- û�д�������ȱʡ��Ϊ
error(···)
end
end
end
- ������
���������� "add" ������
* ������
���������� "add" ������
/ ������
���������� "add" ������
% ������
���������� "add" ������
����ԭ��������������
o1 - floor(o1/o2)*o2
^ ���ݣ�������
���������� "add" ������
����ԭ�������ǵ��� pow ������ͨ�� C math �⣩��
- ������
function unm_event (op)
local o = tonumber(op)
if o then -- �����������֣�
return -o -- ����� '-' ��һ��ԭ���� 'unm'
else -- �������������֡�
-- ���ԴӲ������еõ�������
local h = metatable(op).__unm
if h then
-- �Բ�����Ϊ�������ô�����
return h(op)
else -- û�д�������ȱʡ��Ϊ
error(···)
end
end
end
.. �����ӣ�������
function concat_event (op1, op2)
if (type(op1) == "string" or type(op1) == "number") and
(type(op2) == "string" or type(op2) == "number") then
return op1 .. op2 -- ԭ���ַ�������
else
local h = getbinhandler(op1, op2, "__concat")
if h then
return h(op1, op2)
else
error(···)
end
end
end
# ������
function len_event (op)
if type(op) == "string" then
return strlen(op) -- ԭ����ȡ�ַ�������
elseif type(op) == "table" then
return #op -- ԭ����ȡ table ����
else
local h = metatable(op).__len
if h then
-- ���ò������Ĵ�����
return h(op)
else -- û�д�������ȱʡ��Ϊ
error(···)
end
end
end
���� table �ij��Ȳμ� §2.5.5 ��
== ������
���� getcomphandler ������ Lua ����ѡ��һ�������������Ƚϲ�����
Ԫ���������ڲ��ڱȽϵ���������������ͬ���ж�Ӧ������ͬ��Ԫ����ʱ����Ч��
function getcomphandler (op1, op2, event)
if type(op1) ~= type(op2) then return nil end
local mm1 = metatable(op1)[event]
local mm2 = metatable(op2)[event]
if mm1 == mm2 then return mm1 else return nil end
end
"eq" �¼������·�ʽ���壺
function eq_event (op1, op2)
if type(op1) ~= type(op2) then -- ��ͬ�����ͣ�
return false -- ��ͬ�Ķ���
end
if op1 == op2 then -- ԭ������ȱȽϽ����
return true -- �������
end
-- ����ʹ��Ԫ����
local h = getcomphandler(op1, op2, "__eq")
if h then
return h(op1, op2)
else
return false
end
end
a ~= b �ȼ��� not (a == b) ��
< ������
function lt_event (op1, op2)
if type(op1) == "number" and type(op2) == "number" then
return op1 < op2 -- ���ֱȽ�
elseif type(op1) == "string" and type(op2) == "string" then
return op1 < op2 -- �ַ��������ַ��Ƚ�
else
local h = getcomphandler(op1, op2, "__lt")
if h then
return h(op1, op2)
else
error(···);
end
end
end
a > b �ȼ��� b < a.
<= ������
function le_event (op1, op2)
if type(op1) == "number" and type(op2) == "number" then
return op1 <= op2 -- ���ֱȽ�
elseif type(op1) == "string" and type(op2) == "string" then
return op1 <= op2 -- �ַ��������ַ��Ƚ�
else
local h = getcomphandler(op1, op2, "__le")
if h then
return h(op1, op2)
else
h = getcomphandler(op1, op2, "__lt")
if h then
return not h(op2, op1)
else
error(···);
end
end
end
end
a >= b �ȼ��� b <= a ��
ע�⣬���Ԫ���� "le" û���ṩ��Lua �ͳ��� "lt" ��
���ٶ� a <= b �ȼ��� not (b < a) ��
table[key] ��
function gettable_event (table, key)
local h
if type(table) == "table" then
local v = rawget(table, key)
if v ~= nil then return v end
h = metatable(table).__index
if h == nil then return nil end
else
h = metatable(table).__index
if h == nil then
error(···);
end
end
if type(h) == "function" then
return h(table, key) -- ������
else return h[key] -- �����ظ���������
end
end
table[key] = value ��
function settable_event (table, key, value)
local h
if type(table) == "table" then
local v = rawget(table, key)
if v ~= nil then rawset(table, key, value); return end
h = metatable(table).__newindex
if h == nil then rawset(table, key, value); return end
else
h = metatable(table).__newindex
if h == nil then
error(···);
end
end
if type(h) == "function" then
return h(table, key,value) -- ������
else h[key] = value -- �����ظ���������
end
end
function function_event (func, ...)
if type(func) == "function" then
return func(...) -- ԭ���ĵ���
else
local h = metatable(func).__call
if h then
return h(func, ...)
else
error(···)
end
end
end
����Ϊ thread ��function ���Լ� userdata �Ķ����� metatable �����������һ����֮�����ı����� ���ǵĻ�����һ������ �� metatable һ��������Ҳ��һ������� table �����������Թ��� ͬһ��������
userdata �Ļ����� Lua ��û�����塣 �������ֻ��Ϊ���ڳ���Ա���һ����������һ�� userdata ��ʱ�ṩ������
�������߳��ϵĻ���������ȫ�ֻ�����
ȫ�ֻ��������������е��߳��Լ��̴߳����ķ�Ƕ����
��ͨ�� loadfile �� loadstring ����
load ����ȱʡ������
���������Ա� C ����ֱ�ӷ��ʣ��μ� §3.3����
������ C �����ϵĻ�������ֱ�ӱ� C ������ʣ��μ� §3.3���� ���ǻ���Ϊ��� C �����д���������������ȱʡ������
������ Lua �����ϵĻ��������ӹ��ں����ڶ�ȫ�ֱ������μ� §2.3�������з��ʡ� ����Ҳ����Ϊ��������ڴ���������������ȱʡ������
�����ͨ������ setfenv ���ı�һ�� Lua ����
�������������е��̵߳Ļ�����
����ٿ���������userdata��C �����������̣߳��Ļ����Ļ����ͱ���ʹ�� C API ��
Lua �ṩ��һ���Զ����ڴ������ �����˵�㲻��Ҫ���Ĵ����¶���ķ����ڴ������Ҳ����Ҫ����Щ��������Ҫʱ�������ͷ��ڴ档 Lua ͨ������һ�������ռ������Զ������ڴ棬�Դ�һ����һ��Ļ��������Ķ��� ������ָ Lua �в��ٷ��ʵĵ��Ķ���ռ�õ��ڴ档 Lua �����ж����Զ������������� table, userdata�� �������̡߳����ַ�����
Lua ʵ����һ���������������ռ����� �����������������������ռ����ڣ� garbage-collector pause �� garbage-collector step multiplier ��
garbage-collector pause �������ռ����ڿ�ʼһ���µ��ռ�����֮ǰҪ�ȴ���á� �������ֵ�����͵����ռ������������IJ���ô������ С�� 1 ��ֵ��ζ���ռ������µ����ڿ�ʼʱ���ٵȴ��� ��ֵΪ 2 ��ʱ����ζ������ʹ���ڴ������ﵽԭ��������ʱ�ٿ����µ����ڡ�
step multiplier �������ռ�������ڴ������ٶȡ� ��������ֽ������ռ��������ĸ�������ͬʱ��Ҳʹÿ���ռ��ijߴ����ӡ� С�� 1 ��ֵ��ʹ�ռ��������ķdz��������ܵ����ռ�����Զ���������˵�ǰ���ڡ� ȱʡֵΪ 2 ������ζ���ռ��������ڴ�����������������С�
�����ͨ���� C �е��� lua_gc ������ Lua �е���
collectgarbage ���ı���Щ���֡�
���߶����ܰٷֱ���ֵ����˴������ 100 ��ζ��ʵ��ֵ 1 ����
ͨ����Щ��������Ҳ����ֱ�ӿ����ռ��������磬ֹͣ������������
ʹ�� C API���� ����Ը� userdata ���μ� §2.8������һ�������ռ���Ԫ������ ���Ԫ����Ҳ����Ϊ�����ӡ� �������������ö������Դ�������� Lua ���ڴ������Эͬ���� ������ر��ļ����������ӡ��������ݿ����ӣ�Ҳ����˵�ͷ����Լ����ڴ棩��
һ�� userdata �ɱ����գ������� metatable ���� __gc �����
�����ռ����Ͳ������ջ�����
ȡ����֮���ǣ�Lua �����Ƿŵ�һ���б��С�
���ռ�������Lua ����б��е�ÿ�� userdata ִ����������������ĵȼ۲�����
function gc_event (udata)
local h = metatable(udata).__gc
if h then
h(udata)
end
end
��ÿ�������ռ����ڵĽ�β��ÿ���ڵ�ǰ���ڱ��ռ������� userdata �Ľ����ӻ��� ���ǹ���ʱ���������ε��á� Ҳ����˵���ռ��б��У����һ���ڳ����б������� userdata �� �����ӻᱻ��һ�����á�
weak table ��һ�������� table�������е�Ԫ�ض��������á� �����ý��������ռ������Ե��� ���仰˵�� �����һ�����������ֻ�������ã� �����ռ����������������
weak table �ļ���ֵ�������� weak �ġ�
���һ�� table ֻ�м��� weak �ģ���ô�������ռ����������ǵļ���
���ǻ���ֹ���������ն�Ӧ��ֵ��
��һ�� table �ļ���ֵ���� weak ʱ���ͼ������ռ������ռ��������ջ�ֵ��
�κ�����£��������ֵ����һ���������ˣ�������ֵ�Ծͻ�� table ���õ���
table �� weak ���Կ���ͨ�������� metatable ������ __mode �����ı䡣
��� __mode ������һ���������ַ� 'k' ���ַ���ʱ��
table �ļ����� weak �ġ�
��� __mode ������һ���������ַ� 'v' ���ַ���ʱ��
table ��ֵ���� weak �ġ�
�����һ�� table ����һ�� metatable ʹ��֮��
�Ͳ������� __mode ���ֵ��
��������� metatable ���Ƶ� table �� weak ��Ϊ�ͳ���δ����ġ�
Lua ֧�� coroutine ���������Ҳ����ΪЭͬʽ���߳� (collaborative multithreading)���� Lua Ϊÿ�� coroutine �ṩһ��������������·�� Ȼ���Ͷ��߳�ϵͳ�е��̲߳�ͬ��coroutine ֻ����ʽ�ĵ����� yield ����ʱ�Ż����
����һ�� coroutine ��Ҫ����һ�� coroutine.create ��
��ֻ���յ������������������ coroutine ����������
create ������������һ���µ� coroutine Ȼ�����Ŀ�����
��һ������Ϊ thread �Ķ���
������������ coroutine ������
�����һ�ε��� coroutine.resume ʱ��
���贫��ĵ�һ���������� coroutine.create �ķ���ֵ��
��ʱ��coroutine ���������ĵ�һ�п�ʼ���С�
���������� coroutine.resume �IJ����������� coroutine ����������
�� coroutine ��ʼ���к��������е�������ֹ��������һ�� yields ��
coroutine ����ͨ�����ַ�ʽ����ֹ���У�
һ���������˳���ָ�������������أ����һ��ָ����к�������û����ʽ�ķ���ָ�;
��һ���Ƿ������˳�����������δ�����Ĵ�������ʱ��
��һ������У� coroutine.resume ���� true ��
����������� coroutine ��������һϵ�з���ֵ��
�ڶ��ַ������������£� coroutine.resume ���� false ��
��������һ��������Ϣ��
coroutine ���л���ȥ�����Ե��� coroutine.yield��
�� coroutine �г�����֮��ϵ� coroutine.resume ���������أ�
������ yield �������ڲ�ĺ���������Ҳ���ԣ�����˵��
�ⲻ���ڷ������������У�Ҳ������������ֱ�ӻ��ӵ��õ�ij���������
�� yield ������£�coroutine.resume Ҳ�Ƿ��� true��
�������������� coroutine.yield �IJ�����
�ȵ��´����ڼ���ͬ���� coroutine �����ӵ��� yield �Ķϵ㴦������ȥ��
�ϵ㴦 yield �ķ���ֵ���� coroutine.resume ����IJ�����
���� coroutine.create ��
coroutine.wrap �������Ҳ������һ�� coroutine ��
�������������� coroutine ���������Ƿ���һ������ȡ����֮��һ�������������غ������ͻ����� coroutine ���С�
���д�����������IJ�����ͬ�ڴ��� coroutine.resume �IJ�����
coroutine.wrap �᷵������Ӧ���ɳ���һ�������������Ǹ���������
֮����� coroutine.resume ���ص�ֵ��
�� coroutine.resume ��ͬ��
coroutine.wrap �������κδ���
���еĴ���Ӧ���ɵ������Լ����ݡ�
��������δ���չʾ��һ�����ӣ�
function foo (a)
print("foo", a)
return coroutine.yield(2*a)
end
co = coroutine.create(function (a,b)
print("co-body", a, b)
local r = foo(a+1)
print("co-body", r)
local r, s = coroutine.yield(a+b, a-b)
print("co-body", r, s)
return b, "end"
end)
print("main", coroutine.resume(co, 1, 10))
print("main", coroutine.resume(co, "r"))
print("main", coroutine.resume(co, "x", "y"))
print("main", coroutine.resume(co, "x", "y"))
���������������õ�������������
co-body 1 10
foo 2
main true 4
co-body r
main true 11 -9
co-body x y
main true 10 end
main false cannot resume dead coroutine
������������� Lua �� C API ��
Ҳ������������� Lua ͨѶ�õ�һ�� C ������
���е� API ��������ص������Լ�������������ͷ�ļ�
lua.h �С�
��Ȼ����˵���ǡ�����������һ���ּ� API ���Ժ����ʽ�ṩ�ġ� ���е���Щ�궼ֻʹ�����ǵIJ���һ�� �����˵�һ��������Ҳ���� lua ״̬������ ����㲻�赣����Щ���չ��������һЩ�����á�
�����е� C ���У�Lua API ��������ȥ����������Ч�Ժͼ���ԡ�
Ȼ����������ڱ��� Lua ʱ���ϴ�һ���꿪����
���� luaconf.h �ļ��еĺ� luai_apicheck
�Ըı������Ϊ��
Lua ʹ��һ������ջ���� C ����ֵ�� ջ�ϵĵ�ÿ��Ԫ�ض���һ�� Lua ֵ ��nil�����֣��ַ������ȵȣ���
���ۺ�ʱ Lua ���� C�������õĺ������õ�һ���µ�ջ��
���ջ������ C ���������Ķ�ջ��Ҳ��������ǰ��ջ��
����ע���� C ������� Lua API ���ܷ��ʵ� Lua ״̬���б��ε���֮��Ķ�ջ�е����ݣ�
����������� Lua ���ݸ� C ���������в�����
�� C �������Ҫ���صĽ��Ҳ�����ջ�Է��ظ�������
���μ� lua_CFunction����
����������������ջ�� API ��ѯ���������ϸ���ѭջ�IJ�������
���ǿ�����һ��������ָ��ջ�ϵ��κ�Ԫ�أ�
��������ָ����ջ�ϵľ���λ�ã���һ��ʼ����
����������ָ��ջ����ʼ��ƫ������
����ϸ��˵��һ�£������ջ�� n ��Ԫ�أ�
��ô���� 1 ��ʾ��һ��Ԫ�أ�Ҳ�������ȱ�ѹ���ջ��Ԫ�أ�
������ n ��ָ���һ��Ԫ�أ�
���� -1 Ҳ��ָ���һ��Ԫ�أ���ջ����Ԫ�أ���
���� -n ��ָ��һ��Ԫ�ء�
��������� 1 ��ջ��֮�䣨Ҳ���ǣ�1 ≤ abs(index) ≤ top��
���Ǿ�˵���Ǹ���Ч��������
����ʹ�� Lua API ʱ���������α�֤�����ԡ�
�ر���Ҫע����ǣ��������ο��Ʋ�Ҫ��ջ�����
�����ʹ�� lua_checkstack ���������������ö�ջ�ijߴ硣
���ۺ�ʱ Lua ���� C ��
����ֻ��֤ LUA_MINSTACK ��ô��Ķ�ջ�ռ����ʹ�á�
LUA_MINSTACK һ�㱻����Ϊ 20����
��ˣ�ֻҪ�㲻�Dz��ϵİ�����ѹջ��ͨ���㲻�ù��Ķ�ջ��С��
���еIJ�ѯ���������Խ���һ��������ֻҪ����������κ�ջ�ṩ�Ŀռ��е�ֵ��
ջ���ṩ�����ռ���ͨ�� lua_checkstack �����õġ�
��Щ�����������ɽ��ܵ�������ͨ�����ǰ�������Ϊ��
(index < 0 && abs(index) <= top) ||
(index > 0 && index <= stackspace)
ע�⣬0 ��Զ������һ���ɽ��ܵ�����������ע�������з��ᵽ��������û���ر�ע���Ļ�����ָ�ɽ��ܵ���������
�����ر������⣬�κ�һ�����������Խ�����һ����Ч�����������DZ�������α�������� ��������� C �������һЩ������ջ�ϵ� Lua ֵ�� α���������������̵߳Ļ����������Ļ�����ע��������� C ������ upvalue ���μ� §3.4����
�̵߳Ļ�����Ҳ����ȫ�ֱ����ŵĵط���ͨ����α���� LUA_GLOBALSINDEX ����
�������е� C �����Ļ��������α���� LUA_ENVIRONINDEX ֮����
������ó���� table ���������ʺı�ȫ�ֱ�����ֵ��ֻ��Ҫָ����������λ�á� �������ԣ�Ҫ����ȫ�ֱ�����ֵ����������
lua_getfield(L, LUA_GLOBALSINDEX, varname);
�� C ���������������������п��ܻ��һЩֵ������һ��
Ҳ���Ǵ���һ�� C closure ��
��Щ������������ֵ������ upvalue ��
���ǿ����ں��������õ�ʱ����ʵĵ���
���μ� lua_pushcclosure����
���ۺ�ʱȥ���� C ������������ upvalue ��������ָ����α��������
���ǿ����� lua_upvalueindex �������������Щα������
��һ��������������ֵ���� lua_upvalueindex(1) λ�ô����������ơ�
�κ�����¶������� lua_upvalueindex(n) ����һ�� upvalue ��������
��ʹ��n ����ʵ�ʵ� upvalue ����Ҳ���ԡ��������Բ���һ���ɽ��ܵ���һ����Ч��������
Lua �ṩ��һ��ע���������һ��Ԥ��������ı����������������κ� C �����뱣��� Lua ֵ��
�������������� LUA_REGISTRYINDEX �����
�κ� C �ⶼ���������ű��ﱣ�����ݣ�Ϊ�˷�ֹ��ͻ������Ҫ�ر�С�ĵ�ѡ�������
һ����÷��ǣ��������һ��������Ŀ������ַ�����Ϊ���������߿���ȡ���Լ� C ����
�е�һ����ַ���� light userdata ����ʽ������
ע�����������������ڲ������ʵ�ֵ�����ϵͳ�Ĺ�����һ��˵����Ҫ���������ڱ����;��
���ڲ�ʵ���У�Lua ʹ���� C �� longjmp ��������������
�������ʹ�� C++ �Ļ���Ҳ����ѡ�����쳣���μ� luaconf.h �ļ�����
�� Lua �����κδ������ڴ����������ʹ����������һЩ����ʱ����
���������һ�������ȥ��
Ҳ���ǵ���һ�� long jump ��
�ڱ��������£�Lua ʹ�� setjmp ������һ���ָ��㣻
�κη����Ĵ��ἤ�������һ���ָ��㡣
�������е� API ���������ܲ������������ڴ�������
�������һЩ���������ڱ��������У�Ҳ����˵���Ǵ�����һ���������������������У���
������Dz���������������
lua_newstate, lua_close, lua_load,
lua_pcall, and lua_cpcall��
�� C �������Ҳ����ͨ������ lua_error ����һ������
���������ǰ���ĸ�����г������� C API �еĺ��������͡�
lua_Alloctypedef void * (*lua_Alloc) (void *ud,
void *ptr,
size_t osize,
size_t nsize);
Lua ״̬����ʹ�õ��ڴ���������������͡�
�ڴ���亯�������ṩһ������������ realloc ���ֲ���ȫ��ͬ�ĺ�����
���IJ�����
ud ��һ���� lua_newstate ��������ָ�룻
ptr ��һ��ָ���ѷ���������ǽ������·������Ҫ�ͷŵ��ڴ��ָ�룻
osize ���ڴ��ԭ���ijߴ磻
nsize �����ڴ��ijߴ硣
�����ֻ�� osize ����ʱ��ptr Ϊ NULL ��
�� nsize ���㣬���������뷵�� NULL��
��� osize �����㣬������Ӧ���ͷŵ� ptr ָ����ڴ�顣
�� nsize �����㣬��������������������ʱ������������ NULL ��
�� nsize ������� osize ����ʱ��������Ӧ�ú� malloc
����ͬ����Ϊ��
�� nsize �� osize ��������ʱ����������Ӧ�� realloc
����һ������Ϊ��
Lua ����������� osize >= nsize ʱ��Զ����ʧ�ܡ�
������һ���ķ�����������ʵ�֡�
���ʵ�ֱ����ڲ�����У��� luaL_newstate �ṩ��
static void *l_alloc (void *ud, void *ptr, size_t osize,
size_t nsize) {
(void)ud; (void)osize; /* not used */
if (nsize == 0) {
free(ptr);
return NULL;
}
else
return realloc(ptr, nsize);
}
��δ������ free(NULL) ɶҲ��Ӱ�죬����
realloc(NULL, size) �ȼ��� malloc(size)��
�������� ANSI C ��֤����Ϊ��
lua_atpaniclua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf);
����һ���µ� panic ���ֻţ� ������������ǰһ����
����ڱ�������֮�ⷢ�����κδ���
Lua �ͻ����һ�� panic ���������ŵ��� exit(EXIT_FAILURE)��
�����Ϳ�ʼ�˳���������
��� panic ����������Զ�����أ�������һ�γ���ת������������˳���
panic �������Դ�ջ��ȡ��������Ϣ��
lua_callvoid lua_call (lua_State *L, int nargs, int nresults);
����һ��������
Ҫ����һ����������ѭ����Э�飺
���ȣ�Ҫ���õĺ���Ӧ�ñ�ѹ���ջ��
���ţ�����Ҫ���ݸ���������IJ���������ѹջ��
����ָ��һ����������ѹջ��
������һ�� lua_call��
nargs ����ѹ���ջ�IJ���������
������������Ϻ����еIJ����Լ��������������ջ��
�������ķ���ֵ��ʱ��ѹ���ջ��
����ֵ�ĸ�����������Ϊ nresults ����
���� nresults �����ó� LUA_MULTRET��
����������£����еķ���ֵ����ѹ���ջ�С�
Lua �ᱣ֤����ֵ������ջ�ռ��С�
��������ֵ��������ѹջ����һ������ֵ����ѹջ����
����ڵ��ý��������һ������ֵ��������ջ����
�����ú����ڷ����Ĵ���ͨ�� longjmp��һֱ���ס�
����������У����� Lua ����ȼ��������������� C ������һЩ������
a = f("how", t.x, 14)
������ C ��Ĵ��룺
lua_getfield(L, LUA_GLOBALSINDEX, "f"); /* �����õĺ��� */
lua_pushstring(L, "how"); /* ��һ������ */
lua_getfield(L, LUA_GLOBALSINDEX, "t"); /* table ������ */
lua_getfield(L, -1, "x"); /* ѹ�� t.x ��ֵ���� 2 ��������*/
lua_remove(L, -2); /* �Ӷ�ջ����ȥ 't' */
lua_pushinteger(L, 14); /* �� 3 ������ */
lua_call(L, 3, 1); /* ���� 'f'������ 3 ������������ȡ 1 ������ֵ */
lua_setfield(L, LUA_GLOBALSINDEX, "a"); /* ����ȫ�ֱ��� 'a' */
ע��������δ����ǡ�ƽ�⡱�ģ� �������ջ�ָ���ԭ�ɵ����á� ����һ�����õı��ϰ�ߡ�
lua_CFunctiontypedef int (*lua_CFunction) (lua_State *L);
C ���������͡�
Ϊ����ȷ�ĺ� Lua ͨѶ��C ��������ʹ������
�����˲����Լ�����ֵ���ݷ�����Э�飺
C ����ͨ�� Lua �еĶ�ջ�����ܲ�����������������ջ����һ������������ջ����
��ˣ���������ʼ��ʱ��
lua_gettop(L) ���Է��غ����յ��IJ���������
��һ������������еĻ��������� 1 �ĵط��������һ������������ lua_gettop(L) ����
����Ҫ�� Lua ����ֵ��ʱ��C ����ֻ��Ҫ������������ѹ����ջ�ϣ���һ������ֵ����ѹ�룩��
Ȼ����Щ����ֵ�ĸ�����
����Щ����ֵ֮�µģ���ջ�ϵĶ������ᱻ Lua ������
�� Lua ����һ������ Lua �е��� C ����Ҳ�����кܶ��ֵ��
������������еĺ����������������ֲ��������������ǵ�ƽ������ͣ�
static int foo (lua_State *L) {
int n = lua_gettop(L); /* �����ĸ��� */
lua_Number sum = 0;
int i;
for (i = 1; i <= n; i++) {
if (!lua_isnumber(L, i)) {
lua_pushstring(L, "incorrect argument");
lua_error(L);
}
sum += lua_tonumber(L, i);
}
lua_pushnumber(L, sum/n); /* ��һ������ֵ */
lua_pushnumber(L, sum); /* �ڶ�������ֵ */
return 2; /* ����ֵ�ĸ��� */
}
lua_checkstackint lua_checkstack (lua_State *L, int extra);
ȷ����ջ�������� extra ����λ��
������ܰѶ�ջ��չ����Ӧ�ijߴ磬�������� false ��
���������Զ������С��ջ��
�����ջ�Ѿ�����Ҫ�Ĵ��ˣ���ô�ͷ������ﲻ������仯��
lua_closevoid lua_close (lua_State *L);
����ָ�� Lua ״̬���е����ж�������������ռ���ص�Ԫ�����Ļ�����������ǣ��� �����ͷ�״̬����ʹ�õ����ж�̬�ڴ档 ��һЩƽ̨�ϣ�����Բ��ص������������ ��Ϊ���������������ʱ�����е���������Ȼ���ͷŵ��ˡ� ��һ���棬�������еij�����һ����̨�������һ�� web �������� ��������Ҫ���ǵ�ʱ���Ӧ���ͷŵ����״̬�����������Ա���״̬�����ŵĹ���
lua_concatvoid lua_concat (lua_State *L, int n);
����ջ���� n ��ֵ��
Ȼ����Щֵ��ջ�����ѽ������ջ����
��� n Ϊ 1 ���������һ���ַ�������ջ�ϣ���������ʲô����������
��� n Ϊ 0 �������һ���մ���
�������� Lua �д���������ɣ��μ� §2.5.4 ����
lua_cpcallint lua_cpcall (lua_State *L, lua_CFunction func, void *ud);
�Ա���ģʽ���� C ���� func ��
func ֻ���ܴӶ�ջ���õ�һ�����������ǰ����� ud �� light userdata��
���д���ʱ��
lua_cpcall ���غ� lua_pcall ��ͬ�Ĵ�����룬
����ջ�����´������
�����������㣬�������Ķ�ջ��
���д� func �ڷ��ص�ֵ���ᱻ�ӵ���
lua_createtablevoid lua_createtable (lua_State *L, int narr, int nrec);
����һ���µĿ� table ѹ���ջ��
����� table ����Ԥ���� narr ��Ԫ�ص�����ռ�
�Լ� nrec ��Ԫ�صķ�����ռ䡣
������ȷ֪��������Ҫ���ٸ�Ԫ��ʱ��Ԥ����ͷdz����á�
����㲻֪��������ʹ�ú��� lua_newtable��
lua_dumpint lua_dump (lua_State *L, lua_Writer writer, void *data);
�Ѻ��� dump �ɶ����� chunk ��
��������ջ���� Lua ������������Ȼ���������Ķ����� chunk ��
���� dump �����Ķ������ٴμ��أ����صĽ�����൱��ԭ���ĺ�����
�����ڲ��� chunk ��ʱ��lua_dump
ͨ�����ú��� writer ���μ� lua_Writer��
��д�����ݣ������ data �����ᱻ���� writer ��
���һ����д���� (writer) ����ֵ����Ϊ��������ķ���ֵ���أ� 0 ��ʾû�д���
������������ Lua ���ص�����ջ��
lua_equalint lua_equal (lua_State *L, int index1, int index2);
������� Lua �� == ���������壬���� index1 �� index2
�е�ֵ��ͬ�Ļ������� 1 ��
���� 0 ��
����κ�һ��������ЧҲ�᷵�� 0��
lua_errorint lua_error (lua_State *L);
����һ�� Lua ����
������Ϣ��ʵ���Ͽ������κ����͵� Lua ֵ�����뱻����ջ����
�����������һ�γ���ת������������ٷ��ء�
���μ� luaL_error����
lua_gcint lua_gc (lua_State *L, int what, int data);
���������ռ�����
���������������� what �����ֲ�ͬ������
LUA_GCSTOP:
ֹͣ�����ռ�����
LUA_GCRESTART:
���������ռ�����
LUA_GCCOLLECT:
����һ�������������ռ�ѭ����
LUA_GCCOUNT:
���� Lua ʹ�õ��ڴ��������� K �ֽ�Ϊ��λ����
LUA_GCCOUNTB:
���ص�ǰ�ڴ�ʹ�������� 1024 ��������
LUA_GCSTEP:
����һ�����������ռ���
������ data ���ƣ�Խ���ֵ��ζ��Խ�ಽ����
������庬�壨�������ֱ�ʾ�˶��٣���δ������
�����������������������ʵ���ԵIJ���
data ��ֵ��
�����һ��������һ�������ռ����ڣ����ط��� 1 ��
LUA_GCSETPAUSE:
�� data/100 ����Ϊ garbage-collector pause ����ֵ���μ� §2.10����
����������ǰ��ֵ��
LUA_GCSETSTEPMUL:
�� arg/100 ���ó� step multiplier ���μ� §2.10����
����������ǰ��ֵ��
lua_getallocflua_Alloc lua_getallocf (lua_State *L, void **ud);
���ظ���״̬�����ڴ������������
��� ud ���� NULL ��Lua �ѵ���
lua_newstate ʱ������Ǹ�ָ����� *ud ��
lua_getfenvvoid lua_getfenv (lua_State *L, int index);
��������ֵ�Ļ�����ѹ���ջ��
lua_getfieldvoid lua_getfield (lua_State *L, int index, const char *k);
�� t[k] ֵѹ���ջ��
����� t ��ָ��Ч���� index ָ���ֵ��
�� Lua �У�����������ܴ�����Ӧ "index" �¼���Ԫ����
���μ� §2.8����
lua_getglobalvoid lua_getglobal (lua_State *L, const char *name);
��ȫ�ֱ��� name ���ֵѹ���ջ��
�������һ���궨������ģ�
#define lua_getglobal(L,s) lua_getfield(L, LUA_GLOBALSINDEX, s)
lua_getmetatableint lua_getmetatable (lua_State *L, int index);
�Ѹ�������ָ���ֵ��Ԫ��ѹ���ջ�� ���������Ч���������ֵû��Ԫ���� ���������� 0 ���Ҳ�����ջ��ѹ�κζ�����
lua_gettablevoid lua_gettable (lua_State *L, int index);
�� t[k] ֵѹ���ջ��
����� t ��ָ��Ч���� index ָ���ֵ��
�� k ����ջ���ŵ�ֵ��
��������ᵯ����ջ�ϵ� key ���ѽ������ջ����ͬλ�ã��� �� Lua �У�����������ܴ�����Ӧ "index" �¼���Ԫ���� ���μ� §2.8����
lua_gettopint lua_gettop (lua_State *L);
����ջ��Ԫ�ص������� ��Ϊ�����Ǵ� 1 ��ʼ��ŵģ� �������������ڶ�ջ�ϵ�Ԫ�ظ�������˷��� 0 ��ʾ��ջΪ�գ���
lua_insertvoid lua_insert (lua_State *L, int index);
��ջ��Ԫ�ز���ָ������Ч�������� �������ƶ��������֮�ϵ�Ԫ�ء� ��Ҫ��α������������������� ��Ϊα������������ָ���ջ�ϵ�λ�á�
lua_Integertypedef ptrdiff_t lua_Integer;
������ͱ����� Lua API ��������ֵ��
ȱʡʱ���������Ϊ ptrdiff_t ��
�������ͨ���ǻ����ܴ���������������͡�
lua_isbooleanint lua_isboolean (lua_State *L, int index);
������������ֵ����Ϊ boolean ʱ������ 1 ������ 0 ��
lua_iscfunctionint lua_iscfunction (lua_State *L, int index);
������������ֵ��һ�� C ����ʱ������ 1 ������ 0 ��
lua_isfunctionint lua_isfunction (lua_State *L, int index);
������������ֵ��һ�������� C �� Lua �������ɣ�ʱ������ 1 ������ 0 ��
lua_islightuserdataint lua_islightuserdata (lua_State *L, int index);
������������ֵ��һ�� light userdata ʱ������ 1 ������ 0 ��
lua_isnilint lua_isnil (lua_State *L, int index);
������������ֵ�� nil ʱ������ 1 ������ 0 ��
lua_isnumberint lua_isnumber (lua_State *L, int index);
������������ֵ��һ�����֣�����һ����ת��Ϊ���ֵ��ַ���ʱ������ 1 ������ 0 ��
lua_isstringint lua_isstring (lua_State *L, int index);
������������ֵ��һ���ַ�������һ�����֣���������ת�����ַ�����ʱ������ 1 ������ 0 ��
lua_istableint lua_istable (lua_State *L, int index);
������������ֵ��һ�� table ʱ������ 1 ������ 0 ��
lua_isthreadint lua_isthread (lua_State *L, int index);
������������ֵ��һ�� thread ʱ������ 1 ������ 0 ��
lua_isuserdataint lua_isuserdata (lua_State *L, int index);
������������ֵ��һ�� userdata �������������� userdata ���� light userdata ��ʱ������ 1 ������ 0 ��
lua_lessthanint lua_lessthan (lua_State *L, int index1, int index2);
������� index1 ����ֵС��
���� index2 ����ֵʱ������ 1 ��
���� 0 ��
��������ѭ Lua �е� < ������������˵���п��ܵ���Ԫ��������
����κ�һ��������Ч��Ҳ�᷵�� 0 ��
lua_loadint lua_load (lua_State *L,
lua_Reader reader,
void *data,
const char *chunkname);
����һ�� Lua chunk ��
���û�д���
lua_load ��һ������õ� chunk ��Ϊһ��
Lua ����ѹ���ջ��
����ѹ�������Ϣ��
lua_load �ķ���ֵ�����ǣ�
LUA_ERRSYNTAX:
��Ԥ����ʱ���������LUA_ERRMEM:
�ڴ���������������������� chunk ��������ȥ��������
lua_load ���Զ���� chunk ���ı��Ļ��Ƕ����Ƶģ�
Ȼ������Ӧ�ļ��ز������μ����� luac����
lua_load ����ʹ��һ���û��ṩ�� reader ������
��ȡ chunk ���μ� lua_Reader����
data �����ᱻ�����ȡ��������
chunkname ����������Ը��� chunk һ�����֣�
������ֱ����ڳ�����Ϣ�͵�����Ϣ���μ� §3.8����
lua_newstatelua_State *lua_newstate (lua_Alloc f, void *ud);
������һ���µĶ�����״̬����
����������ˣ���Ϊ�ڴ����⣩���� NULL ��
���� f ��һ��������������
Lua ��ͨ�����������״̬�������е��ڴ���������
�ڶ������� ud �����ָ�뽫��ÿ�ε��÷�����ʱ��ֱ�Ӵ��롣
lua_newtablevoid lua_newtable (lua_State *L);
����һ���� table ������֮ѹ���ջ��
���ȼ��� lua_createtable(L, 0, 0) ��
lua_newthreadlua_State *lua_newthread (lua_State *L);
����һ�����̣߳�������ѹ���ջ��
������ά������̵߳� lua_State ָ�롣
����������ص���״̬������ԭ��״̬���е����ж�����һЩ table����
�������ж�����ִ�ж�ջ��
û����ʽ�ĺ������������رջ����ٵ�һ���̡߳� �̸߳����� Lua ����һ���������ռ�����Ŀ֮һ��
lua_newuserdatavoid *lua_newuserdata (lua_State *L, size_t size);
��������������һ��ָ����С���ڴ�飬 ���ڴ���ַ��Ϊһ�������� userdata ѹ���ջ�������������ַ��
userdata ���� Lua �е� C ֵ�� ������ userdata ����һ���ڴ档 ����һ�������� table �����Ķ��� ����봴�������������Լ���Ԫ�����������ڱ�����ʱ�����Ա����� һ�������� userdata ֻ�����Լ���ȣ��ڵ��ڵ�ԭ�������£���
�� Lua ͨ�� gc Ԫ��������һ�������� userdata ʱ��
Lua �������Ԫ�������� userdata ���Ϊ����ֹ��
�ȵ���� userdata �ٴα��ռ���ʱ��Lua ���ͷŵ���ص��ڴ档
lua_nextint lua_next (lua_State *L, int index);
��ջ�ϵ���һ�� key��������
Ȼ�������ָ���ı��� key-value����ֵ����ѹ���ջ
��ָ�� key �������һ (next) �ԣ���
�������������Ԫ�أ�
��ô lua_next ������ 0 ��ʲôҲ��ѹ���ջ����
���͵ı��������������ģ�
/* table �������� 't' �� */
lua_pushnil(L); /* ��һ�� key */
while (lua_next(L, t) != 0) {
/* ��һ�� 'key' �������� -2 ���� �� 'value' �������� -1 ���� */
printf("%s - %s\n",
lua_typename(L, lua_type(L, -2)),
lua_typename(L, lua_type(L, -1)));
/* �Ƴ� 'value' ������ 'key' ����һ�ε��� */
lua_pop(L, 1);
}
�ڱ���һ�ű���ʱ��
��Ҫֱ�Ӷ� key ���� lua_tolstring ��
������֪����� key һ����һ���ַ�����
���� lua_tolstring �п��ܸı��������λ�õ�ֵ��
������һ�ε��� lua_next ���Ӱ�졣
lua_Numbertypedef double lua_Number;
Lua �����ֵ����͡�
ȷʡ�� double ������������� luaconf.h ��������
ͨ���������ļ�����Ըı� Lua �������������������ͣ����磺float ���� long ����
lua_objlensize_t lua_objlen (lua_State *L, int index);
����ָ������������ֵ�ij��ȡ�
���� string ���Ǿ����ַ����ij��ȣ�
���� table ����ȡ���Ȳ����� ('#') �Ľ����
���� userdata ������Ϊ�������ڴ��ijߴ磻
��������ֵ��Ϊ 0 ��
lua_pcalllua_pcall (lua_State *L, int nargs, int nresults, int errfunc);
�Ա���ģʽ����һ��������
nargs �� nresults �����
lua_call �е���ͬ��
����ڵ��ù�����û�з�������
lua_pcall ����Ϊ�� lua_call ��ȫһ�¡�
���ǣ�����д������Ļ���
lua_pcall �Ჶ������
Ȼ��ѵ�һ��ֵ��������Ϣ��ѹ���ջ��Ȼ�ش����롣
ͬ lua_call һ����
lua_pcall ���ǰѺ������������IJ�����ջ���Ƴ���
��� errfunc �� 0 ��
������ջ���Ĵ�����Ϣ�ͺ�ԭʼ������Ϣ��ȫһ�¡�
����errfunc �ͱ������Ǵ�����������ջ�ϵ�������
���ڵ�ǰ��ʵ����������������α��������
�ڷ�������ʱ����ʱ��
��������ᱻ���ö��������Ǵ�����Ϣ��
�����������ķ���ֵ���� lua_pcall ��Ϊ������Ϣ�����ڶ�ջ�ϡ�
���͵��÷��У������������������ڳ�����Ϣ�ϼ��ϸ���ĵ�����Ϣ������ջ������Ϣ (stack traceback) ��
��Щ��Ϣ�� lua_pcall ���غ���Ϊջ�Ѿ�չ�� (unwound) ��
�����ռ������ˡ�
lua_pcall �����ڵ��óɹ�ʱ���� 0 ��
�������£������� lua.h �еģ���������е�һ����
LUA_ERRRUN:
����ʱ����
LUA_ERRMEM:
�ڴ�������
�������ִ���Lua ���ò��˴�����������
LUA_ERRERR:
�����д���������ʱ�����Ĵ���
lua_popvoid lua_pop (lua_State *L, int n);
�Ӷ�ջ�е��� n ��Ԫ�ء�
lua_pushbooleanvoid lua_pushboolean (lua_State *L, int b);
�� b ��Ϊһ�� boolean ֵѹ���ջ��
lua_pushcclosurevoid lua_pushcclosure (lua_State *L, lua_CFunction fn, int n);
��һ���µ� C closure ѹ���ջ��
��������һ�� C ����������Ը�������һЩֵ�����������ڴ���һ�� C closure
���μ� §3.4����
���������ۺ�����ʱ�����ã���Щֵ�����Ա�����������ʵ���
Ϊ�˽�һЩֵ������һ�� C �����ϣ�
������Щֵ��Ҫ�ȱ�ѹ���ջ������ж��ֵ����һ����ѹ����
���������� lua_pushcclosure
�������� closure ������� C ����ѹ����ջ�ϡ�
���� n ��֮�����ж��ٸ�ֵ��Ҫ�����������ϡ�
lua_pushcclosure Ҳ�����Щֵ��ջ�ϵ�����
lua_pushcfunctionvoid lua_pushcfunction (lua_State *L, lua_CFunction f);
��һ�� C ����ѹ���ջ��
�����������һ�� C ����ָ�룬����һ������Ϊ function �� Lua ֵ
ѹ���ջ�������ջ����ֵ������ʱ����������Ӧ�� C ������
ע�ᵽ Lua �е��κκ�����������ѭ��ȷ��Э�������ղ����ͷ���ֵ
���μ� lua_CFunction����
lua_pushcfunction ����Ϊһ���궨����ֵģ�
#define lua_pushcfunction(L,f) lua_pushcclosure(L,f,0)
lua_pushfstringconst char *lua_pushfstring (lua_State *L, const char *fmt, ...);
��һ����ʽ�������ַ���ѹ���ջ��Ȼ������ַ�����ָ�롣
���� C ���� sprintf �Ƚ�������һЩ��Ҫ������
%%' ������һ�� '%'����
'%s' ������һ��������ֹ�����ַ�����û�г������ƣ���
'%f' ������һ�� lua_Number����
'%p' ������һ��ָ�����һ��ʮ������������
'%d' ������һ�� int)��
'%c' ����һ�� int ��Ϊһ���ַ����룩��
lua_pushintegervoid lua_pushinteger (lua_State *L, lua_Integer n);
�� n ��Ϊһ������ѹջ��
lua_pushlightuserdatavoid lua_pushlightuserdata (lua_State *L, void *p);
��һ�� light userdata ѹջ��
userdata �� Lua �б�ʾһ�� C ֵ�� light userdata ��ʾһ��ָ�롣 ����һ��������һ����ֵ�� �㲻��Ҫר�Ŵ���������Ҳû�ж����� metatable �� ����Ҳ���ᱻ�ռ�����Ϊ��������Ҫ�������� ֻҪ��ʾ�� C ��ַ��ͬ������ light userdata ����ȡ�
lua_pushlstringvoid lua_pushlstring (lua_State *L, const char *s, size_t len);
��ָ�� s ָ��ij���Ϊ len ���ַ���ѹջ��
Lua ������ַ�����һ���ڴ濽�������Ǹ���һ����������
��� s �����ڴ��ں������غ����ͷŵ�����������������;��
�ַ����ڿ��Ա��������ַ���
lua_pushnilvoid lua_pushnil (lua_State *L);
��һ�� nil ѹջ��
lua_pushnumbervoid lua_pushnumber (lua_State *L, lua_Number n);
��һ������ n ѹջ��
lua_pushstringvoid lua_pushstring (lua_State *L, const char *s);
��ָ�� s ָ��������β���ַ���ѹջ��
Lua ������ַ�����һ���ڴ濽�������Ǹ���һ����������
��� s �����ڴ��ں������غ����ͷŵ�����������������;��
�ַ����в��ܰ��������ַ�����һ�����������ַ�����Ϊ���ַ����Ľ�����
lua_pushthreadint lua_pushthread (lua_State *L);
�� L ���ṩ���߳�ѹջ��
�������߳��ǵ�ǰ״̬�������̵߳Ļ������� 1 ��
lua_pushvaluevoid lua_pushvalue (lua_State *L, int index);
�Ѷ�ջ�ϸ�����Ч����������Ԫ����һ������ѹջ��
lua_pushvfstringconst char *lua_pushvfstring (lua_State *L,
const char *fmt,
va_list argp);
�ȼ��� lua_pushfstring��
�������� va_list ���ղ������������ÿɱ�������ʵ�ʲ�����
lua_rawequalint lua_rawequal (lua_State *L, int index1, int index2);
����������� index1 �� index2 ����ֵ�����
��������Ԫ�������� 1 ��
���� 0 ��
����κ�һ��������ЧҲ���� 0 ��
lua_rawgetvoid lua_rawget (lua_State *L, int index);
������ lua_gettable��
������һ��ֱ�ӷ��ʣ�������Ԫ��������
lua_rawgetivoid lua_rawgeti (lua_State *L, int index, int n);
�� t[n] ��ֵѹջ��
����� t ��ָ�������� index ����һ��ֵ��
����һ��ֱ�ӷ��ʣ�����˵�������ᴥ��Ԫ������
lua_rawsetvoid lua_rawset (lua_State *L, int index);
������ lua_settable��
��������һ��ֱ�Ӹ�ֵ��������Ԫ��������
lua_rawsetivoid lua_rawseti (lua_State *L, int index, int n);
�ȼ��� t[n] = v��
����� t ��ָ�������� index ����һ��ֵ��
�� v ��ջ����ֵ��
�����������ֵ����ջ�� ��ֵ������ֱ�ӵģ�����˵�����ᴥ��Ԫ������
lua_Readertypedef const char * (*lua_Reader) (lua_State *L,
void *data,
size_t *size);
lua_load �õ��Ķ�ȡ��������
ÿ������Ҫһ���µ� chunk ��ʱ��
lua_load �͵��ö�ȡ����
ÿ�ζ��ᴫ��һ������ data ��
��ȡ����Ҫ���غ����µ� chunk ��һ���ڴ��ָ�룬
���� size ��Ϊ����ڴ�Ĵ�С��
�ڴ���������һ�κ���������֮ǰһֱ���ڡ�
��ȡ������ͨ������һ�� NULL ��ָʾ chunk ������
��ȡ�����ܷ��ض���飬ÿ�������������Ĵ�����ijߴ硣
lua_registervoid lua_register (lua_State *L,
const char *name,
lua_CFunction f);
�� C ���� f �赽ȫ�ֱ��� name �С�
��ͨ��һ���궨�壺
#define lua_register(L,n,f) \
(lua_pushcfunction(L, f), lua_setglobal(L, n))
lua_removevoid lua_remove (lua_State *L, int index);
�Ӹ�����Ч�������Ƴ�һ��Ԫ�أ� ���������֮�ϵ�����Ԫ����������������϶�� ������α������������������� ��Ϊα��������ָ����ʵ��ջ�ϵ�λ�á�
lua_replacevoid lua_replace (lua_State *L, int index);
��ջ��Ԫ���ƶ�������λ�ã����Ұ����ջ��Ԫ�ص������� ���ƶ��κ�Ԫ�أ�������Ǹ�λ�ô���ֵ�����ǵ�����
lua_resumeint lua_resume (lua_State *L, int narg);
�ڸ����߳������������һ�� coroutine ��
Ҫ����һ�� coroutine �Ļ���������Ҫ����һ�����߳�
���μ� lua_newthread ����
Ȼ��������������ɲ���ѹ�����̵߳Ķ�ջ�ϣ�
������ lua_resume ��
�� narg ��Ϊ�����ĸ�����
��ε��û��� coroutine ����ʱ���ǽ������кء�
����������ʱ����ջ�л��д��� lua_yield ������ֵ��
���������������з���ֵ��
��� coroutine �л�ʱ��lua_resume ����
LUA_YIELD ��
���� coroutine ����������û���κδ���ʱ������ 0 ��
����д��ش�����루�μ� lua_pcall����
�ڷ������������£�
��ջû��չ����
��������ʹ�� debug API ����������
������Ϣ����ջ����
Ҫ��������һ�� coroutine �Ļ��������Ҫ���� yield
������ķ���ֵѹ���ջ��Ȼ����� lua_resume ��
lua_setallocfvoid lua_setallocf (lua_State *L, lua_Alloc f, void *ud);
��ָ��״̬���ķ������������ɴ���ָ�� ud �� f ��
lua_setfenvint lua_setfenv (lua_State *L, int index);
�Ӷ�ջ�ϵ���һ�� table ��������Ϊָ��������ֵ���»�����
���ָ����������ֵ�����Ǻ����ֲ����̻߳��� userdata ��
lua_setfenv �᷵�� 0 ��
���� 1 ��
lua_setfieldvoid lua_setfield (lua_State *L, int index, const char *k);
��һ���ȼ��� t[k] = v �IJ�����
���� t �Ǹ�������Ч���� index ����ֵ��
�� v ��ջ�����Ǹ�ֵ��
��������������ֵ������ջ�� ���� Lua ��һ��������������ܴ���һ�� "newindex" �¼���Ԫ���� ���μ� §2.8����
lua_setglobalvoid lua_setglobal (lua_State *L, const char *name);
�Ӷ�ջ�ϵ���һ��ֵ���������赽ȫ�ֱ��� name �С�
����һ���궨�������
#define lua_setglobal(L,s) lua_setfield(L, LUA_GLOBALSINDEX, s)
lua_setmetatableint lua_setmetatable (lua_State *L, int index);
��һ�� table ������ջ����������Ϊ������������ֵ�� metatable ��
lua_settablevoid lua_settable (lua_State *L, int index);
��һ���ȼ��� t[k] = v �IJ�����
���� t ��һ��������Ч���� index ����ֵ��
v ָջ����ֵ��
�� k ��ջ��֮�µ��Ǹ�ֵ��
���������Ѽ���ֵ���Ӷ�ջ�е����� ���� Lua ��һ��������������ܴ��� "newindex" �¼���Ԫ���� ���μ� §2.8����
lua_settopvoid lua_settop (lua_State *L, int index);
�������������κοɽ��ܵ������Լ� 0 ��
�����Ѷ�ջ��ջ����Ϊ���������
����µ�ջ����ԭ���Ĵ������ֵ���Ԫ�ؽ�����Ϊ nil ��
��� index Ϊ 0 ����ջ������Ԫ���Ƴ���
lua_Statetypedef struct lua_State lua_State;
һ�������Ľṹ�������������� Lua ��������״̬�� Lua ������ȫ������ģ� ��û���κ�ȫ�ֱ����� ����ע���� C �����˵��Ҳ����Ȼ�����磬�� table ��ʵ���� ����һ����̬ȫ�ֱ��� dummynode_ ����������ȷʹ��ʱ����Ӱ��������ԡ� ֻ����һ����������� lua �⣬��С����ͬһ���̿ռ��д������� lua ��ʵ�ֵĴ���Ļ��� ��� dummynode_ ��ͬ�ĵ�ַ�ᵼ��һЩ���⡣�� ���е���Ϣ������������ṹ�С�
���״̬����ָ�������Ϊ��һ���������ݸ�ÿһ���⺯����
lua_newstate ��һ�����⣬
����������ͷ����һ�� Lua ״̬����
lua_statusint lua_status (lua_State *L);
�����߳� L ��״̬��
�������߳�״̬�� 0 ��
���߳�ִ����ϻ���һ������ʱ��״ֵ̬�Ǵ����롣
����̱߳�����״̬Ϊ LUA_YIELD ��
lua_tobooleanint lua_toboolean (lua_State *L, int index);
��ָ�����������ĵ� Lua ֵת��Ϊһ�� C �е� boolean ֵ�� 0 ���� 1 ����
�� Lua ���������в���һ����
lua_toboolean ����κ�
��ͬ�� false �� nil ��ֵ���� 1 ���أ�
����ͷ��� 0 ��
�����һ����Ч����ȥ����Ҳ�᷵�� 0 ��
���������ֻ���������� boolean ֵ������Ҫʹ��
lua_isboolean ������ֵ�����͡���
lua_tocfunctionlua_CFunction lua_tocfunction (lua_State *L, int index);
�Ѹ����������� Lua ֵת��Ϊһ�� C ������
���ֵ������һ�� C ������������Ǿͷ���
NULL ��
lua_tointegerlua_Integer lua_tointeger (lua_State *L, int idx);
�Ѹ����������� Lua ֵת��Ϊ lua_Integer
����һ���з����������͡�
��� Lua ֵ������һ�����ֻ���һ������ת��Ϊ���ֵ��ַ���
���μ� §2.2.1����
����lua_tointeger ���� 0 ��
������ֲ���һ�������� �ض�С�����ֵķ�ʽû�б���ȷ���塣
lua_tolstringconst char *lua_tolstring (lua_State *L, int index, size_t *len);
�Ѹ����������� Lua ֵת��Ϊһ�� C �ַ�����
��� len ��Ϊ NULL ��
�������ַ��������赽 *len �С�
��� Lua ֵ������һ���ַ�������һ�����֣�
���ط��� NULL ��
���ֵ��һ�����֣�lua_tolstring
����Ѷ�ջ�е��Ǹ�ֵ��ʵ������ת��Ϊһ���ַ�����
��������һ������ʱ�� lua_tolstring
�����ڼ��ϣ����ת���п��ܵ��� lua_next Ū������
lua_tolstring ���� Lua ״̬����
�ַ������Զ���ָ�롣
����ַ������ܱ�֤ �� C Ҫ��ģ����һ���ַ�Ϊ�� ('\0') ��
�������������ַ����ڰ�������������㡣
��Ϊ Lua �п��ܷ��������ռ���
���Բ���֤ lua_tolstring ���ص�ָ�룬
�ڶ�Ӧ��ֵ�Ӷ�ջ���Ƴ�����Ȼ��Ч��
lua_tonumberlua_Number lua_tonumber (lua_State *L, int index);
�Ѹ����������� Lua ֵת��Ϊ lua_Number
����һ�� C ���ͣ��μ� lua_Number ����
��� Lua ֵ������һ�����ֻ���һ����ת��Ϊ���ֵ��ַ���
���μ� §2.2.1 ����
����lua_tonumber ���� 0 ��
lua_topointerconst void *lua_topointer (lua_State *L, int index);
�Ѹ�����������ֵת��Ϊһ��� C ָ�� (void*) ��
���ֵ������һ�� userdata ��table ��thread ����һ�� function ��
����lua_topointer ���� NULL ��
��ͬ�Ķ����в�ͬ��ָ�롣
�����ڰ�ָ����ת��ԭ�����͵ķ�����
�������ͨ��ֻΪ���� debug ��Ϣ�á�
lua_tostringconst char *lua_tostring (lua_State *L, int index);
�ȼ��� lua_tolstring �������� len ��Ϊ NULL ��
lua_tothreadlua_State *lua_tothread (lua_State *L, int index);
�Ѹ�����������ֵת��Ϊһ�� Lua �̣߳��� lua_State* ��������
���ֵ������һ���̣߳����������� NULL ��
lua_touserdatavoid *lua_touserdata (lua_State *L, int index);
���������������ֵ��һ�������� userdata �����������ڴ��ĵ�ַ��
���ֵ��һ�� light userdata ����ô�ͷ�������ʾ��ָ�롣
������ NULL ��
lua_typeint lua_type (lua_State *L, int index);
���ظ�����������ֵ�����ͣ�
��������Чʱ�� LUA_TNONE
������ָһ��ָ���ջ�ϵĿ�λ�õ���������
lua_type ���ص�������һЩ���� lua.h �ж���ij�����
LUA_TNIL ��
LUA_TNUMBER ��
LUA_TBOOLEAN ��
LUA_TSTRING ��
LUA_TTABLE ��
LUA_TFUNCTION ��
LUA_TUSERDATA ��
LUA_TTHREAD ��
LUA_TLIGHTUSERDATA ��
lua_typenameconst char *lua_typename (lua_State *L, int tp);
���� tp ��ʾ����������
��� tp ������ lua_type ���ܷ��ص�ֵ��֮һ��
lua_Writertypedef int (*lua_Writer) (lua_State *L,
const void* p,
size_t sz,
void* ud);
�� lua_dump �õ���д����������
ÿ�� lua_dump ������һ���µ� chunk �����������д������
����Ҫд��Ļ��� (p) �����ijߴ� (sz) ��
���� lua_dump �IJ��� data ��
д�����᷵��һ�������룺
0 ��ʾû�д���
���ֵ����ʾһ�������һ��� lua_dump ֹͣ�ٴε���д������
lua_xmovevoid lua_xmove (lua_State *from, lua_State *to, int n);
���� ͬһ�� ȫ��״̬���²�ͬ�߳��е�ֵ��
���������� from �Ķ�ջ�е��� n ��ֵ��
Ȼ�������ѹ�� to �Ķ�ջ�С�
lua_yieldint lua_yield (lua_State *L, int nresults);
�г�һ�� coroutine ��
�������ֻ����һ�� C �����ķ��ر���ʽ�е��á����£�
return lua_yield (L, nresults);
��һ�� C ������������ lua_yield ��
���������е� coroutine ���������й���
Ȼ��������� coroutine �õ��Ǵζ� lua_resume �ĵ��þͷ����ˡ�
���� nresults ָ���Ƕ�ջ����Ҫ���صĽ����������Щ����ֵ�������ݸ�
lua_resume ��
Lua û���ڽ��ĵ�����ʩ�� ȡ����֮�����ṩ��һЩ�����ӿں��ӡ� ������Щ�ӿڣ���������һЩ��ͬ���͵ĵ������� ���ܷ���������������һЩ��Ҫ�ӽ�������ȡ�����ڲ���Ϣ���Ĺ��ߡ�
lua_Debugtypedef struct lua_Debug {
int event;
const char *name; /* (n) */
const char *namewhat; /* (n) */
const char *what; /* (S) */
const char *source; /* (S) */
int currentline; /* (l) */
int nups; /* (u) upvalue ���� */
int linedefined; /* (S) */
int lastlinedefined; /* (S) */
char short_src[LUA_IDSIZE]; /* (S) */
/* ˽�в��� */
������
} lua_Debug;
һ������Я����к����ĸ�����Ϣ�Ľṹ��
lua_getstack ����д����ṹ�е�˽�в��֣�
��Щ�����Ժ���õ���
���� lua_getinfo ���������
lua_Debug
��������Ϣ����Щ��
lua_Debug �еĸ����������к��壺
source:
��������Ƕ�����һ���ַ����У�source ��������ַ�����
�������������һ���ļ��У�
source ��һ���� '@' ��ͷ���ļ�����
short_src:
һ�����ɴ�ӡ�汾���� source�����ڳ�����Ϣ��
linedefined:
�������忪ʼ�����кš�
lastlinedefined:
����������������кš�
what:
���������һ�� Lua ��������Ϊһ���ַ��� "Lua" ��
�����һ�� C ��������Ϊ "C"��
�������һ�� chunk �����岿�֣���Ϊ "main"��
�����һ������β���õĺ�������Ϊ "tail" ��
�������£�Lua û�й��ں����ı����Ϣ��
currentline:
������������ִ�е���һ�С�
���ṩ�����к���Ϣ��ʱ��currentline ����Ϊ -1 ��
name:
����������һ�����������֡�
��Ϊ Lua �еĺ���Ҳ��һ��ֵ��
��������û�й̶������֣�
һЩ����������ȫ�ָ��ϱ�����ֵ��
��һЩ���ܽ���ֻ�DZ�������һ�� table �С�
lua_getinfo �������麯�������������õģ��Դ����ҵ�һ���ʺϵ����֡�
������Ҳ������֣�name �ͱ�����Ϊ NULL ��
namewhat:
��ʵ name ��
namewhat ��ֵ������
"global", "local", "method",
"field", "upvalue", ���� "" ���մ�����
��ȡ���ں������������á�
��Lua �ÿմ���ʾ����ѡ������ϣ�
nups:
������ upvalue �ĸ�����
lua_gethooklua_Hook lua_gethook (lua_State *L);
���ص�ǰ�Ĺ��Ӻ�����
lua_gethookcountint lua_gethookcount (lua_State *L);
���ص�ǰ���Ӽ�����
lua_gethookmaskint lua_gethookmask (lua_State *L);
���ص�ǰ�Ĺ������� (mask) ��
lua_getinfoint lua_getinfo (lua_State *L, const char *what, lua_Debug *ar);
����һ��ָ���ĺ����������õ���Ϣ��
������ȡ��һ�κ������õ���Ϣʱ��
���� ar ������һ����Ч�Ļ�ļ�¼��
������¼������ǰһ�ε��� lua_getstack �õ��ģ�
����һ������ ���μ� lua_Hook���õ��IJ�����
���ڻ�ȡһ����������Ϣʱ�������������ѹ���ջ��
Ȼ��� what �ַ������ַ� '>' ��ͷ��
���������£�lua_getinfo ��ջ���ϵ�����������
���磬��֪������ f ����һ�ж���ģ�
����������д��룺
lua_Debug ar;
lua_getfield(L, LUA_GLOBALSINDEX, "f"); /* ȡ��ȫ�ֱ��� 'f' */
lua_getinfo(L, ">S", &ar);
printf("%d\n", ar.linedefined);
what �ַ����е�ÿ���ַ���ɸѡ���ṹ ar
�ṹ��һЩ��������䣬���ǰ�һ��ֵѹ���ջ��
n': ��� name �� namewhat ��
S':
��� source�� short_src��
linedefined�� lastlinedefined���Լ� what ��
l': ��� currentline ��
u': ��� nups ��
f':
������������ָ��������ѹ���ջ��
����ע��һ�����ڻ�ȡ���������е���Ϣ��
�������� ar �е�˽�в������ṩ��
������ڻ�ȡ��̬��������ô��ֱ�Ӱ�ָ����������ѹ�ض�ջ��
��������ͨ���������塣��
L':
ѹһ�� table ��ջ����� table �е�������������������������Щ������Ч�С�
����Ч��ָ��ʵ�ʴ�����У�
�����������ϵ���С�
��Ч�а������к�ֻ��ע�͵��С���
������������᷵�� 0
�����磬what ����һ����Чѡ���
lua_getlocalconst char *lua_getlocal (lua_State *L, lua_Debug *ar, int n);
�Ӹ������¼�л�ȡһ���ֲ���������Ϣ��
���� ar ������һ����Ч�Ļ�ļ�¼��
������¼������ǰһ�ε��� lua_getstack �õ��ģ�
����һ������ ���μ� lua_Hook���õ��IJ�����
���� n ����ѡ��Ҫ�����ĸ��ֲ�����
�� 1 ��ʾ��һ���������Ǽ���ĵ�һ���ֲ��������Դ����ƣ�ֱ�����һ���ֲ���������
lua_getlocal �ѱ�����ֵѹ���ջ�������������֡�
�� '(' ����С���ţ���ʼ�ı���ָ�ڲ����� ��ѭ�����Ʊ�������ʱ������C �����ֲ���������
���������ھֲ������ĸ���ʱ������ NULL ��ʲôҲ��ѹ�룩��
lua_getstackint lua_getstack (lua_State *L, int level, lua_Debug *ar);
��ȡ������������ʱջ����Ϣ��
������������������еĸ������ĺ����Ļ��¼����д
lua_Debug �ṹ��һ���֡�
0 ����ʾ��ǰ���еĺ�����
�� n+1 �����ĺ������ǵ��õ� n ����������һ����
���û�д���lua_getstack ���� 1 ��
�����ô���ļ�����ڶ�ջ��ȵ�ʱ���� 0 ��
lua_getupvalueconst char *lua_getupvalue (lua_State *L, int funcindex, int n);
��ȡһ�� closure �� upvalue ��Ϣ��
������ Lua ������upvalue �Ǻ�����Ҫʹ�õ��ⲿ�ֲ�������
����������������� closure ����
lua_getupvalue ��ȡ�� n �� upvalue ��
����� upvalue ��ֵѹ���ջ�����ҷ����������֡�
funcindex ָ���ջ�� closure ��λ�á�
�� ��Ϊ upvalue �����������ж���Ч����������û���ر�Ĵ���
��ˣ���������ĸ��������š���
�������ű� upvalue �������ʱ���� NULL �����Ҳ���ѹ���κζ�����
���� C ��������������ÿմ� "" ��ʾ���� upvalue �����֡�
lua_Hooktypedef void (*lua_Hook) (lua_State *L, lua_Debug *ar);
���ڵ��ԵĹ��Ӻ������͡�
���ۺ�ʱ���ӱ����ã����IJ��� ar �е� event ��
������Ϊ�������ӵ��¼���
Lua ����Щ�¼�����Ϊ���³�����
LUA_HOOKCALL�� LUA_HOOKRET,
LUA_HOOKTAILRET�� LUA_HOOKLINE��
and LUA_HOOKCOUNT��
����֮�⣬���� line �¼���currentline ��Ҳ�����á�
Ҫ���� ar �е�������
���ӱ������ lua_getinfo��
���ڷ����¼���event ������ֵ������ LUA_HOOKRET��
������ LUA_HOOKTAILRET ��
���ں�һ�������Lua ���һ����������β����Ҳģ���һ�������¼�������
�������ģ��ķ����¼������� lua_getinfo û��ʲô���á�
�� Lua ������һ�������ڲ�ʱ���������ε������Թ��ӵĵ��á� Ҳ����˵�����һ�����Ӻ������ٵ��� Lua ��ִ��һ����������һ�� chunk �� ���ִ�в������ᴥ���κεĹ��ӡ�
lua_sethookint lua_sethook (lua_State *L, lua_Hook f, int mask, int count);
����һ�������ù��Ӻ�����
���� f �ǹ��Ӻ�����
mask ָ������Щ�¼�ʱ����ã�
��������һ��λ��������
LUA_MASKCALL��
LUA_MASKRET��
LUA_MASKLINE��
�Լ� LUA_MASKCOUNT��
���� count ֻ�� mask �а����� LUA_MASKCOUNT �������塣
����ÿ���¼������ӱ����õ�����������£�
count ��ָ����á�
������¼������� Lua ִ��һ�� Lua ����ʱ��������
���ӿ���ͨ������ mask Ϊ�����Ρ�
lua_setlocalconst char *lua_setlocal (lua_State *L, lua_Debug *ar, int n);
���ø������¼�еľֲ�������ֵ��
���� ar �� n �� lua_getlocal �е�һ��
���μ� lua_getlocal����
lua_setlocal ��ջ����ֵ��������Ȼ�ر��������֡�
���Ὣֵ��ջ��������
���������ھֲ������ĸ���ʱ������ NULL ��ʲôҲ����������
lua_setupvalueconst char *lua_setupvalue (lua_State *L, int funcindex, int n);
���� closure �� upvalue ��ֵ��
����ջ����ֵ���������� upvalue ������ upvalue �����֡�
���� funcindex �� n �� lua_getupvalue �е�һ��
���μ� lua_getupvalue����
���������� upvalue �ĸ���ʱ������ NULL ��ʲôҲ����������
The auxiliary library provides several convenient functions to interface C with Lua. While the basic API provides the primitive functions for all interactions between C and Lua, the auxiliary library provides higher-level functions for some common tasks.
All functions from the auxiliary library
are defined in header file lauxlib.h and
have a prefix luaL_.
All functions in the auxiliary library are built on top of the basic API, and so they provide nothing that cannot be done with this API.
Several functions in the auxiliary library are used to
check C function arguments.
Their names are always luaL_check* or luaL_opt*.
All of these functions raise an error if the check is not satisfied.
Because the error message is formatted for arguments
(e.g., "bad argument #1"),
you should not use these functions for other stack values.
Here we list all functions and types from the auxiliary library in alphabetical order.
luaL_addcharvoid luaL_addchar (luaL_Buffer *B, char c);
Adds the character c to the buffer B
(see luaL_Buffer).
luaL_addlstringvoid luaL_addlstring (luaL_Buffer *B, const char *s, size_t l);
Adds the string pointed to by s with length l to
the buffer B
(see luaL_Buffer).
The string may contain embedded zeros.
luaL_addsizevoid luaL_addsize (luaL_Buffer *B, size_t n);
Adds to the buffer B (see luaL_Buffer)
a string of length n previously copied to the
buffer area (see luaL_prepbuffer).
luaL_addstringvoid luaL_addstring (luaL_Buffer *B, const char *s);
Adds the zero-terminated string pointed to by s
to the buffer B
(see luaL_Buffer).
The string may not contain embedded zeros.
luaL_addvaluevoid luaL_addvalue (luaL_Buffer *B);
Adds the value at the top of the stack
to the buffer B
(see luaL_Buffer).
Pops the value.
This is the only function on string buffers that can (and must) be called with an extra element on the stack, which is the value to be added to the buffer.
luaL_argcheckvoid luaL_argcheck (lua_State *L,
int cond,
int narg,
const char *extramsg);
Checks whether cond is true.
If not, raises an error with the following message,
where func is retrieved from the call stack:
bad argument #<narg> to <func> (<extramsg>)
luaL_argerrorint luaL_argerror (lua_State *L, int narg, const char *extramsg);
Raises an error with the following message,
where func is retrieved from the call stack:
bad argument #<narg> to <func> (<extramsg>)
This function never returns,
but it is an idiom to use it in C functions
as return luaL_argerror(args).
luaL_Buffertypedef struct luaL_Buffer luaL_Buffer;
Type for a string buffer.
A string buffer allows C code to build Lua strings piecemeal. Its pattern of use is as follows:
b of type luaL_Buffer.luaL_buffinit(L, &b).luaL_add* functions.
luaL_pushresult(&b).
This call leaves the final string on the top of the stack.
During its normal operation,
a string buffer uses a variable number of stack slots.
So, while using a buffer, you cannot assume that you know where
the top of the stack is.
You can use the stack between successive calls to buffer operations
as long as that use is balanced;
that is,
when you call a buffer operation,
the stack is at the same level
it was immediately after the previous buffer operation.
(The only exception to this rule is luaL_addvalue.)
After calling luaL_pushresult the stack is back to its
level when the buffer was initialized,
plus the final string on its top.
luaL_buffinitvoid luaL_buffinit (lua_State *L, luaL_Buffer *B);
Initializes a buffer B.
This function does not allocate any space;
the buffer must be declared as a variable
(see luaL_Buffer).
luaL_callmetaint luaL_callmeta (lua_State *L, int obj, const char *e);
Calls a metamethod.
If the object at index obj has a metatable and this
metatable has a field e,
this function calls this field and passes the object as its only argument.
In this case this function returns 1 and pushes onto the
stack the value returned by the call.
If there is no metatable or no metamethod,
this function returns 0 (without pushing any value on the stack).
luaL_checkanyvoid luaL_checkany (lua_State *L, int narg);
Checks whether the function has an argument
of any type (including nil) at position narg.
luaL_checkintint luaL_checkint (lua_State *L, int narg);
Checks whether the function argument narg is a number
and returns this number cast to an int.
luaL_checkintegerlua_Integer luaL_checkinteger (lua_State *L, int narg);
Checks whether the function argument narg is a number
and returns this number cast to a lua_Integer.
luaL_checklonglong luaL_checklong (lua_State *L, int narg);
Checks whether the function argument narg is a number
and returns this number cast to a long.
luaL_checklstringconst char *luaL_checklstring (lua_State *L, int narg, size_t *l);
Checks whether the function argument narg is a string
and returns this string;
if l is not NULL fills *l
with the string's length.
luaL_checknumberlua_Number luaL_checknumber (lua_State *L, int narg);
Checks whether the function argument narg is a number
and returns this number.
luaL_checkoptionint luaL_checkoption (lua_State *L,
int narg,
const char *def,
const char *const lst[]);
Checks whether the function argument narg is a string and
searches for this string in the array lst
(which must be NULL-terminated).
Returns the index in the array where the string was found.
Raises an error if the argument is not a string or
if the string cannot be found.
If def is not NULL,
the function uses def as a default value when
there is no argument narg or if this argument is nil.
This is a useful function for mapping strings to C enums. (The usual convention in Lua libraries is to use strings instead of numbers to select options.)
luaL_checkstackvoid luaL_checkstack (lua_State *L, int sz, const char *msg);
Grows the stack size to top + sz elements,
raising an error if the stack cannot grow to that size.
msg is an additional text to go into the error message.
luaL_checkstringconst char *luaL_checkstring (lua_State *L, int narg);
Checks whether the function argument narg is a string
and returns this string.
luaL_checktypevoid luaL_checktype (lua_State *L, int narg, int t);
Checks whether the function argument narg has type t.
luaL_checkudatavoid *luaL_checkudata (lua_State *L, int narg, const char *tname);
Checks whether the function argument narg is a userdata
of the type tname (see luaL_newmetatable).
luaL_dofileint luaL_dofile (lua_State *L, const char *filename);
Loads and runs the given file. It is defined as the following macro:
(luaL_loadfile(L, filename) || lua_pcall(L, 0, LUA_MULTRET, 0))
It returns 0 if there are no errors or 1 in case of errors.
luaL_dostringint luaL_dostring (lua_State *L, const char *str);
Loads and runs the given string. It is defined as the following macro:
(luaL_loadstring(L, str) || lua_pcall(L, 0, LUA_MULTRET, 0))
It returns 0 if there are no errors or 1 in case of errors.
luaL_errorint luaL_error (lua_State *L, const char *fmt, ...);
Raises an error.
The error message format is given by fmt
plus any extra arguments,
following the same rules of lua_pushfstring.
It also adds at the beginning of the message the file name and
the line number where the error occurred,
if this information is available.
This function never returns,
but it is an idiom to use it in C functions
as return luaL_error(args).
luaL_getmetafieldint luaL_getmetafield (lua_State *L, int obj, const char *e);
Pushes onto the stack the field e from the metatable
of the object at index obj.
If the object does not have a metatable,
or if the metatable does not have this field,
returns 0 and pushes nothing.
luaL_getmetatablevoid luaL_getmetatable (lua_State *L, const char *tname);
Pushes onto the stack the metatable associated with name tname
in the registry (see luaL_newmetatable).
luaL_gsubconst char *luaL_gsub (lua_State *L,
const char *s,
const char *p,
const char *r);
Creates a copy of string s by replacing
any occurrence of the string p
with the string r.
Pushes the resulting string on the stack and returns it.
luaL_loadbufferint luaL_loadbuffer (lua_State *L,
const char *buff,
size_t sz,
const char *name);
Loads a buffer as a Lua chunk.
This function uses lua_load to load the chunk in the
buffer pointed to by buff with size sz.
This function returns the same results as lua_load.
name is the chunk name,
used for debug information and error messages.
luaL_loadfileint luaL_loadfile (lua_State *L, const char *filename);
Loads a file as a Lua chunk.
This function uses lua_load to load the chunk in the file
named filename.
If filename is NULL,
then it loads from the standard input.
The first line in the file is ignored if it starts with a #.
This function returns the same results as lua_load,
but it has an extra error code LUA_ERRFILE
if it cannot open/read the file.
As lua_load, this function only loads the chunk;
it does not run it.
luaL_loadstringint luaL_loadstring (lua_State *L, const char *s);
Loads a string as a Lua chunk.
This function uses lua_load to load the chunk in
the zero-terminated string s.
This function returns the same results as lua_load.
Also as lua_load, this function only loads the chunk;
it does not run it.
luaL_newmetatableint luaL_newmetatable (lua_State *L, const char *tname);
If the registry already has the key tname,
returns 0.
Otherwise,
creates a new table to be used as a metatable for userdata,
adds it to the registry with key tname,
and returns 1.
In both cases pushes onto the stack the final value associated
with tname in the registry.
luaL_newstatelua_State *luaL_newstate (void);
Creates a new Lua state.
It calls lua_newstate with an
allocator based on the standard C realloc function
and then sets a panic function (see lua_atpanic) that prints
an error message to the standard error output in case of fatal
errors.
Returns the new state,
or NULL if there is a memory allocation error.
luaL_openlibsvoid luaL_openlibs (lua_State *L);
Opens all standard Lua libraries into the given state.
luaL_optintint luaL_optint (lua_State *L, int narg, int d);
If the function argument narg is a number,
returns this number cast to an int.
If this argument is absent or is nil,
returns d.
Otherwise, raises an error.
luaL_optintegerlua_Integer luaL_optinteger (lua_State *L,
int narg,
lua_Integer d);
If the function argument narg is a number,
returns this number cast to a lua_Integer.
If this argument is absent or is nil,
returns d.
Otherwise, raises an error.
luaL_optlonglong luaL_optlong (lua_State *L, int narg, long d);
If the function argument narg is a number,
returns this number cast to a long.
If this argument is absent or is nil,
returns d.
Otherwise, raises an error.
luaL_optlstringconst char *luaL_optlstring (lua_State *L,
int narg,
const char *d,
size_t *l);
If the function argument narg is a string,
returns this string.
If this argument is absent or is nil,
returns d.
Otherwise, raises an error.
If l is not NULL,
fills the position *l with the results's length.
luaL_optnumberlua_Number luaL_optnumber (lua_State *L, int narg, lua_Number d);
If the function argument narg is a number,
returns this number.
If this argument is absent or is nil,
returns d.
Otherwise, raises an error.
luaL_optstringconst char *luaL_optstring (lua_State *L,
int narg,
const char *d);
If the function argument narg is a string,
returns this string.
If this argument is absent or is nil,
returns d.
Otherwise, raises an error.
luaL_prepbufferchar *luaL_prepbuffer (luaL_Buffer *B);
Returns an address to a space of size LUAL_BUFFERSIZE
where you can copy a string to be added to buffer B
(see luaL_Buffer).
After copying the string into this space you must call
luaL_addsize with the size of the string to actually add
it to the buffer.
luaL_pushresultvoid luaL_pushresult (luaL_Buffer *B);
Finishes the use of buffer B leaving the final string on
the top of the stack.
luaL_refint luaL_ref (lua_State *L, int t);
Creates and returns a reference,
in the table at index t,
for the object at the top of the stack (and pops the object).
A reference is a unique integer key.
As long as you do not manually add integer keys into table t,
luaL_ref ensures the uniqueness of the key it returns.
You can retrieve an object referred by reference r
by calling lua_rawgeti(L, t, r).
Function luaL_unref frees a reference and its associated object.
If the object at the top of the stack is nil,
luaL_ref returns the constant LUA_REFNIL.
The constant LUA_NOREF is guaranteed to be different
from any reference returned by luaL_ref.
luaL_Regtypedef struct luaL_Reg {
const char *name;
lua_CFunction func;
} luaL_Reg;
Type for arrays of functions to be registered by
luaL_register.
name is the function name and func is a pointer to
the function.
Any array of luaL_Reg must end with an sentinel entry
in which both name and func are NULL.
luaL_registervoid luaL_register (lua_State *L,
const char *libname,
const luaL_Reg *l);
Opens a library.
When called with libname equal to NULL,
it simply registers all functions in the list l
(see luaL_Reg) into the table on the top of the stack.
When called with a non-null libname,
luaL_register creates a new table t,
sets it as the value of the global variable libname,
sets it as the value of package.loaded[libname],
and registers on it all functions in the list l.
If there is a table in package.loaded[libname] or in
variable libname,
reuses this table instead of creating a new one.
In any case the function leaves the table on the top of the stack.
luaL_typenameconst char *luaL_typename (lua_State *L, int idx);
Returns the name of the type of the value at index idx.
luaL_typerrorint luaL_typerror (lua_State *L, int narg, const char *tname);
Generates an error with a message like the following:
location: bad argument narg to 'func' (tname expected, got rt)
where location is produced by luaL_where,
func is the name of the current function,
and rt is the type name of the actual argument.
luaL_unrefvoid luaL_unref (lua_State *L, int t, int ref);
Releases reference ref from the table at index t
(see luaL_ref).
The entry is removed from the table,
so that the referred object can be collected.
The reference ref is also freed to be used again.
If ref is LUA_NOREF or LUA_REFNIL,
luaL_unref does nothing.
luaL_wherevoid luaL_where (lua_State *L, int lvl);
Pushes onto the stack a string identifying the current position
of the control at level lvl in the call stack.
Typically this string has the following format:
chunkname:currentline:
Level 0 is the running function, level 1 is the function that called the running function, etc.
This function is used to build a prefix for error messages.
The standard Lua libraries provide useful functions
that are implemented directly through the C API.
Some of these functions provide essential services to the language
(e.g., type and getmetatable);
others provide access to "outside" services (e.g., I/O);
and others could be implemented in Lua itself,
but are quite useful or have critical performance requirements that
deserve an implementation in C (e.g., sort).
All libraries are implemented through the official C API and are provided as separate C modules. Currently, Lua has the following standard libraries:
Except for the basic and package libraries, each library provides all its functions as fields of a global table or as methods of its objects.
To have access to these libraries,
the C host program should call the luaL_openlibs function,
which opens all standard libraries.
Alternatively,
it can open them individually by calling
luaopen_base (for the basic library),
luaopen_package (for the package library),
luaopen_string (for the string library),
luaopen_table (for the table library),
luaopen_math (for the mathematical library),
luaopen_io (for the I/O and the Operating System libraries),
and luaopen_debug (for the debug library).
These functions are declared in lualib.h
and should not be called directly:
you must call them like any other Lua C function,
e.g., by using lua_call.
The basic library provides some core functions to Lua. If you do not include this library in your application, you should check carefully whether you need to provide implementations for some of its facilities.
assert (v [, message])v is false (i.e., nil or false);
otherwise, returns all its arguments.
message is an error message;
when absent, it defaults to "assertion failed!"
collectgarbage (opt [, arg])
This function is a generic interface to the garbage collector.
It performs different functions according to its first argument, opt:
arg
(larger values mean more steps) in a non-specified way.
If you want to control the step size
you must experimentally tune the value of arg.
Returns true if the step finished a collection cycle.
arg/100 as the new value for the pause of
the collector (see §2.10).
arg/100 as the new value for the step multiplier of
the collector (see §2.10).
dofile (filename)dofile executes the contents of the standard input (stdin).
Returns all values returned by the chunk.
In case of errors, dofile propagates the error
to its caller (that is, dofile does not run in protected mode).
error (message [, level])message as the error message.
Function error never returns.
Usually, error adds some information about the error position
at the beginning of the message.
The level argument specifies how to get the error position.
With level 1 (the default), the error position is where the
error function was called.
Level 2 points the error to where the function
that called error was called; and so on.
Passing a level 0 avoids the addition of error position information
to the message.
_G_G._G = _G).
Lua itself does not use this variable;
changing its value does not affect any environment,
nor vice-versa.
(Use setfenv to change environments.)
getfenv (f)f can be a Lua function or a number
that specifies the function at that stack level:
Level 1 is the function calling getfenv.
If the given function is not a Lua function,
or if f is 0,
getfenv returns the global environment.
The default for f is 1.
getmetatable (object)
If object does not have a metatable, returns nil.
Otherwise,
if the object's metatable has a "__metatable" field,
returns the associated value.
Otherwise, returns the metatable of the given object.
ipairs (t)
Returns three values: an iterator function, the table t, and 0,
so that the construction
for i,v in ipairs(t) do body end
will iterate over the pairs (1,t[1]), (2,t[2]), ···,
up to the first integer key absent from the table.
load (func [, chunkname])
Loads a chunk using function func to get its pieces.
Each call to func must return a string that concatenates
with previous results.
A return of nil (or no value) signals the end of the chunk.
If there are no errors, returns the compiled chunk as a function; otherwise, returns nil plus the error message. The environment of the returned function is the global environment.
chunkname is used as the chunk name for error messages
and debug information.
loadfile ([filename])
Similar to load,
but gets the chunk from file filename
or from the standard input,
if no file name is given.
loadstring (string [, chunkname])
Similar to load,
but gets the chunk from the given string.
To load and run a given string, use the idiom
assert(loadstring(s))()
next (table [, index])
Allows a program to traverse all fields of a table.
Its first argument is a table and its second argument
is an index in this table.
next returns the next index of the table
and its associated value.
When called with nil as its second argument,
next returns an initial index
and its associated value.
When called with the last index,
or with nil in an empty table,
next returns nil.
If the second argument is absent, then it is interpreted as nil.
In particular,
you can use next(t) to check whether a table is empty.
The order in which the indices are enumerated is not specified,
even for numeric indices.
(To traverse a table in numeric order,
use a numerical for or the ipairs function.)
The behavior of next is undefined if,
during the traversal,
you assign any value to a non-existent field in the table.
You may however modify existing fields.
In particular, you may clear existing fields.
pairs (t)
Returns three values: the next function, the table t, and nil,
so that the construction
for k,v in pairs(t) do body end
will iterate over all key–value pairs of table t.
See function next for the caveats of modifying
the table during its traversal.
pcall (f, arg1, ···)
Calls function f with
the given arguments in protected mode.
This means that any error inside f is not propagated;
instead, pcall catches the error
and returns a status code.
Its first result is the status code (a boolean),
which is true if the call succeeds without errors.
In such case, pcall also returns all results from the call,
after this first result.
In case of any error, pcall returns false plus the error message.
print (···)stdout,
using the tostring function to convert them to strings.
print is not intended for formatted output,
but only as a quick way to show a value,
typically for debugging.
For formatted output, use string.format.
rawequal (v1, v2)v1 is equal to v2,
without invoking any metamethod.
Returns a boolean.
rawget (table, index)table[index],
without invoking any metamethod.
table must be a table;
index may be any value.
rawset (table, index, value)table[index] to value,
without invoking any metamethod.
table must be a table,
index any value different from nil,
and value any Lua value.
This function returns table.
select (index, ···)
If index is a number,
returns all arguments after argument number index.
Otherwise, index must be the string "#",
and select returns the total number of extra arguments it received.
setfenv (f, table)
Sets the environment to be used by the given function.
f can be a Lua function or a number
that specifies the function at that stack level:
Level 1 is the function calling setfenv.
setfenv returns the given function.
As a special case, when f is 0 setfenv changes
the environment of the running thread.
In this case, setfenv returns no values.
setmetatable (table, metatable)
Sets the metatable for the given table.
(You cannot change the metatable of other types from Lua, only from C.)
If metatable is nil,
removes the metatable of the given table.
If the original metatable has a "__metatable" field,
raises an error.
This function returns table.
tonumber (e [, base])tonumber returns this number;
otherwise, it returns nil.
An optional argument specifies the base to interpret the numeral.
The base may be any integer between 2 and 36, inclusive.
In bases above 10, the letter 'A' (in either upper or lower case)
represents 10, 'B' represents 11, and so forth,
with 'Z' representing 35.
In base 10 (the default), the number may have a decimal part,
as well as an optional exponent part (see §2.1).
In other bases, only unsigned integers are accepted.
tostring (e)string.format.
If the metatable of e has a "__tostring" field,
then tostring calls the corresponding value
with e as argument,
and uses the result of the call as its result.
type (v)nil" (a string, not the value nil),
"number",
"string",
"boolean",
"table",
"function",
"thread",
and "userdata".
unpack (list [, i [, j]])return list[i], list[i+1], ···, list[j]
except that the above code can be written only for a fixed number
of elements.
By default, i is 1 and j is the length of the list,
as defined by the length operator (see §2.5.5).
_VERSIONLua 5.1".
xpcall (f, err)
This function is similar to pcall,
except that you can set a new error handler.
xpcall calls function f in protected mode,
using err as the error handler.
Any error inside f is not propagated;
instead, xpcall catches the error,
calls the err function with the original error object,
and returns a status code.
Its first result is the status code (a boolean),
which is true if the call succeeds without errors.
In this case, xpcall also returns all results from the call,
after this first result.
In case of any error,
xpcall returns false plus the result from err.
The operations related to coroutines comprise a sub-library of
the basic library and come inside the table coroutine.
See §2.11 for a general description of coroutines.
coroutine.create (f)
Creates a new coroutine, with body f.
f must be a Lua function.
Returns this new coroutine,
an object with type "thread".
coroutine.resume (co [, val1, ···])
Starts or continues the execution of coroutine co.
The first time you resume a coroutine,
it starts running its body.
The values val1, ··· are passed
as the arguments to the body function.
If the coroutine has yielded,
resume restarts it;
the values val1, ··· are passed
as the results from the yield.
If the coroutine runs without any errors,
resume returns true plus any values passed to yield
(if the coroutine yields) or any values returned by the body function
(if the coroutine terminates).
If there is any error,
resume returns false plus the error message.
coroutine.running ()Returns the running coroutine, or nil when called by the main thread.
coroutine.status (co)
Returns the status of coroutine co, as a string:
"running",
if the coroutine is running (that is, it called status);
"suspended", if the coroutine is suspended in a call to yield,
or if it has not started running yet;
"normal" if the coroutine is active but not running
(that is, it has resumed another coroutine);
and "dead" if the coroutine has finished its body function,
or if it has stopped with an error.
coroutine.wrap (f)
Creates a new coroutine, with body f.
f must be a Lua function.
Returns a function that resumes the coroutine each time it is called.
Any arguments passed to the function behave as the
extra arguments to resume.
Returns the same values returned by resume,
except the first boolean.
In case of error, propagates the error.
coroutine.yield (···)
Suspends the execution of the calling coroutine.
The coroutine cannot be running a C function,
a metamethod, or an iterator.
Any arguments to yield are passed as extra results to resume.
The package library provides basic
facilities for loading and building modules in Lua.
It exports two of its functions directly in the global environment:
require and module.
Everything else is exported in a table package.
module (name [, ···])
Creates a module.
If there is a table in package.loaded[name],
this table is the module.
Otherwise, if there is a global table t with the given name,
this table is the module.
Otherwise creates a new table t and
sets it as the value of the global name and
the value of package.loaded[name].
This function also initializes t._NAME with the given name,
t._M with the module (t itself),
and t._PACKAGE with the package name
(the full module name minus last component; see below).
Finally, module sets t as the new environment
of the current function and the new value of package.loaded[name],
so that require returns t.
If name is a compound name
(that is, one with components separated by dots),
module creates (or reuses, if they already exist)
tables for each component.
For instance, if name is a.b.c,
then module stores the module table in field c of
field b of global a.
This function may receive optional options after the module name, where each option is a function to be applied over the module.
require (modname)
Loads the given module.
The function starts by looking into the package.loaded table
to determine whether modname is already loaded.
If it is, then require returns the value stored
at package.loaded[modname].
Otherwise, it tries to find a loader for the module.
To find a loader,
first require queries package.preload[modname].
If it has a value,
this value (which should be a function) is the loader.
Otherwise require searches for a Lua loader using the
path stored in package.path.
If that also fails, it searches for a C loader using the
path stored in package.cpath.
If that also fails,
it tries an all-in-one loader (see below).
When loading a C library,
require first uses a dynamic link facility to link the
application with the library.
Then it tries to find a C function inside this library to
be used as the loader.
The name of this C function is the string "luaopen_"
concatenated with a copy of the module name where each dot
is replaced by an underscore.
Moreover, if the module name has a hyphen,
its prefix up to (and including) the first hyphen is removed.
For instance, if the module name is a.v1-b.c,
the function name will be luaopen_b_c.
If require finds neither a Lua library nor a
C library for a module,
it calls the all-in-one loader.
This loader searches the C path for a library for
the root name of the given module.
For instance, when requiring a.b.c,
it will search for a C library for a.
If found, it looks into it for an open function for
the submodule;
in our example, that would be luaopen_a_b_c.
With this facility, a package can pack several C submodules
into one single library,
with each submodule keeping its original open function.
Once a loader is found,
require calls the loader with a single argument, modname.
If the loader returns any value,
require assigns the returned value to package.loaded[modname].
If the loader returns no value and
has not assigned any value to package.loaded[modname],
then require assigns true to this entry.
In any case, require returns the
final value of package.loaded[modname].
If there is any error loading or running the module,
or if it cannot find any loader for the module,
then require signals an error.
package.cpath
The path used by require to search for a C loader.
Lua initializes the C path package.cpath in the same way
it initializes the Lua path package.path,
using the environment variable LUA_CPATH
(plus another default path defined in luaconf.h).
package.loaded
A table used by require to control which
modules are already loaded.
When you require a module modname and
package.loaded[modname] is not false,
require simply returns the value stored there.
package.loadlib (libname, funcname)
Dynamically links the host program with the C library libname.
Inside this library, looks for a function funcname
and returns this function as a C function.
(So, funcname must follow the protocol (see lua_CFunction)).
This is a low-level function.
It completely bypasses the package and module system.
Unlike require,
it does not perform any path searching and
does not automatically adds extensions.
libname must be the complete file name of the C library,
including if necessary a path and extension.
funcname must be the exact name exported by the C library
(which may depend on the C compiler and linker used).
This function is not supported by ANSI C.
As such, it is only available on some platforms
(Windows, Linux, Mac OS X, Solaris, BSD,
plus other Unix systems that support the dlfcn standard).
package.path
The path used by require to search for a Lua loader.
At start-up, Lua initializes this variable with
the value of the environment variable LUA_PATH or
with a default path defined in luaconf.h,
if the environment variable is not defined.
Any ";;" in the value of the environment variable
is replaced by the default path.
A path is a sequence of templates separated by semicolons.
For each template, require will change each interrogation
mark in the template by filename,
which is modname with each dot replaced by a
"directory separator" (such as "/" in Unix);
then it will try to load the resulting file name.
So, for instance, if the Lua path is
"./?.lua;./?.lc;/usr/local/?/init.lua"
the search for a Lua loader for module foo
will try to load the files
./foo.lua, ./foo.lc, and
/usr/local/foo/init.lua, in that order.
package.preload
A table to store loaders for specific modules
(see require).
package.seeall (module)
Sets a metatable for module with
its __index field referring to the global environment,
so that this module inherits values
from the global environment.
To be used as an option to function module.
This library provides generic functions for string manipulation, such as finding and extracting substrings, and pattern matching. When indexing a string in Lua, the first character is at position 1 (not at 0, as in C). Indices are allowed to be negative and are interpreted as indexing backwards, from the end of the string. Thus, the last character is at position -1, and so on.
The string library provides all its functions inside the table
string.
It also sets a metatable for strings
where the __index field points to the string table.
Therefore, you can use the string functions in object-oriented style.
For instance, string.byte(s, i)
can be written as s:byte(i).
string.byte (s [, i [, j]])s[i],
s[i+1], ···, s[j].
The default value for i is 1;
the default value for j is i.
Note that numerical codes are not necessarily portable across platforms.
string.char (···)Note that numerical codes are not necessarily portable across platforms.
string.dump (function)
Returns a string containing a binary representation of the given function,
so that a later loadstring on this string returns
a copy of the function.
function must be a Lua function without upvalues.
string.find (s, pattern [, init [, plain]])pattern in the string s.
If it finds a match, then find returns the indices of s
where this occurrence starts and ends;
otherwise, it returns nil.
A third, optional numerical argument init specifies
where to start the search;
its default value is 1 and may be negative.
A value of true as a fourth, optional argument plain
turns off the pattern matching facilities,
so the function does a plain "find substring" operation,
with no characters in pattern being considered "magic".
Note that if plain is given, then init must be given as well.
If the pattern has captures, then in a successful match the captured values are also returned, after the two indices.
string.format (formatstring, ···)printf family of
standard C functions.
The only differences are that the options/modifiers
*, l, L, n, p,
and h are not supported
and that there is an extra option, q.
The q option formats a string in a form suitable to be safely read
back by the Lua interpreter:
the string is written between double quotes,
and all double quotes, newlines, embedded zeros,
and backslashes in the string
are correctly escaped when written.
For instance, the call
string.format('%q', 'a string with "quotes" and \n new line')
will produce the string:
"a string with \"quotes\" and \
new line"
The options c, d, E, e, f,
g, G, i, o, u, X, and x all
expect a number as argument,
whereas q and s expect a string.
This function does not accept string values containing embedded zeros.
string.gmatch (s, pattern)pattern over string s.
If pattern specifies no captures,
then the whole match is produced in each call.
As an example, the following loop
s = "hello world from Lua"
for w in string.gmatch(s, "%a+") do
print(w)
end
will iterate over all the words from string s,
printing one per line.
The next example collects all pairs key=value from the
given string into a table:
t = {}
s = "from=world, to=Lua"
for k, v in string.gmatch(s, "(%w+)=(%w+)") do
t[k] = v
end
string.gsub (s, pattern, repl [, n])s
in which all occurrences of the pattern have been
replaced by a replacement string specified by repl,
which may be a string, a table, or a function.
gsub also returns, as its second value,
the total number of substitutions made.
If repl is a string, then its value is used for replacement.
The character % works as an escape character:
any sequence in repl of the form %n,
with n between 1 and 9,
stands for the value of the n-th captured substring (see below).
The sequence %0 stands for the whole match.
The sequence %% stands for a single %.
If repl is a table, then the table is queried for every match,
using the first capture as the key;
if the pattern specifies no captures,
then the whole match is used as the key.
If repl is a function, then this function is called every time a
match occurs, with all captured substrings passed as arguments,
in order;
if the pattern specifies no captures,
then the whole match is passed as a sole argument.
If the value returned by the table query or by the function call is a string or a number, then it is used as the replacement string; otherwise, if it is false or nil, then there is no replacement (that is, the original match is kept in the string).
The optional last parameter n limits
the maximum number of substitutions to occur.
For instance, when n is 1 only the first occurrence of
pattern is replaced.
Here are some examples:
x = string.gsub("hello world", "(%w+)", "%1 %1")
--> x="hello hello world world"
x = string.gsub("hello world", "%w+", "%0 %0", 1)
--> x="hello hello world"
x = string.gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1")
--> x="world hello Lua from"
x = string.gsub("home = $HOME, user = $USER", "%$(%w+)", os.getenv)
--> x="home = /home/roberto, user = roberto"
x = string.gsub("4+5 = $return 4+5$", "%$(.-)%$", function (s)
return loadstring(s)()
end)
--> x="4+5 = 9"
local t = {name="lua", version="5.1"}
x = string.gsub("$name%-$version.tar.gz", "%$(%w+)", t)
--> x="lua-5.1.tar.gz"
string.len (s)"" has length 0.
Embedded zeros are counted,
so "a\000bc\000" has length 5.
string.lower (s)
string.match (s, pattern [, init])pattern in the string s.
If it finds one, then match returns
the captures from the pattern;
otherwise it returns nil.
If pattern specifies no captures,
then the whole match is returned.
A third, optional numerical argument init specifies
where to start the search;
its default value is 1 and may be negative.
string.rep (s, n)n copies of
the string s.
string.reverse (s)s reversed.
string.sub (s, i [, j])s that
starts at i and continues until j;
i and j may be negative.
If j is absent, then it is assumed to be equal to -1
(which is the same as the string length).
In particular,
the call string.sub(s,1,j) returns a prefix of s
with length j,
and string.sub(s, -i) returns a suffix of s
with length i.
string.upper (s)A character class is used to represent a set of characters. The following combinations are allowed in describing a character class:
^$()%.[]*+-?)
represents the character x itself.
.: (a dot) represents all characters.%a: represents all letters.%c: represents all control characters.%d: represents all digits.%l: represents all lowercase letters.%p: represents all punctuation characters.%s: represents all space characters.%u: represents all uppercase letters.%w: represents all alphanumeric characters.%x: represents all hexadecimal digits.%z: represents the character with representation 0.%x: (where x is any non-alphanumeric character)
represents the character x.
This is the standard way to escape the magic characters.
Any punctuation character (even the non magic)
can be preceded by a '%'
when used to represent itself in a pattern.
[set]:
represents the class which is the union of all
characters in set.
A range of characters may be specified by
separating the end characters of the range with a '-'.
All classes %x described above may also be used as
components in set.
All other characters in set represent themselves.
For example, [%w_] (or [_%w])
represents all alphanumeric characters plus the underscore,
[0-7] represents the octal digits,
and [0-7%l%-] represents the octal digits plus
the lowercase letters plus the '-' character.
The interaction between ranges and classes is not defined.
Therefore, patterns like [%a-z] or [a-%%]
have no meaning.
[^set]:
represents the complement of set,
where set is interpreted as above.
For all classes represented by single letters (%a, %c, etc.),
the corresponding uppercase letter represents the complement of the class.
For instance, %S represents all non-space characters.
The definitions of letter, space, and other character groups
depend on the current locale.
In particular, the class [a-z] may not be equivalent to %l.
A pattern item may be
*',
which matches 0 or more repetitions of characters in the class.
These repetition items will always match the longest possible sequence;
+',
which matches 1 or more repetitions of characters in the class.
These repetition items will always match the longest possible sequence;
-',
which also matches 0 or more repetitions of characters in the class.
Unlike '*',
these repetition items will always match the shortest possible sequence;
?',
which matches 0 or 1 occurrence of a character in the class;
%n, for n between 1 and 9;
such item matches a substring equal to the n-th captured string
(see below);
%bxy, where x and y are two distinct characters;
such item matches strings that start with x, end with y,
and where the x and y are balanced.
This means that, if one reads the string from left to right,
counting +1 for an x and -1 for a y,
the ending y is the first y where the count reaches 0.
For instance, the item %b() matches expressions with
balanced parentheses.
A pattern is a sequence of pattern items.
A '^' at the beginning of a pattern anchors the match at the
beginning of the subject string.
A '$' at the end of a pattern anchors the match at the
end of the subject string.
At other positions,
'^' and '$' have no special meaning and represent themselves.
A pattern may contain sub-patterns enclosed in parentheses;
they describe captures.
When a match succeeds, the substrings of the subject string
that match captures are stored (captured) for future use.
Captures are numbered according to their left parentheses.
For instance, in the pattern "(a*(.)%w(%s*))",
the part of the string matching "a*(.)%w(%s*)" is
stored as the first capture (and therefore has number 1);
the character matching "." is captured with number 2,
and the part matching "%s*" has number 3.
As a special case, the empty capture () captures
the current string position (a number).
For instance, if we apply the pattern "()aa()" on the
string "flaaap", there will be two captures: 3 and 5.
A pattern cannot contain embedded zeros. Use %z instead.
This library provides generic functions for table manipulation.
It provides all its functions inside the table table.
Most functions in the table library assume that the table represents an array or a list. For these functions, when we talk about the "length" of a table we mean the result of the length operator.
table.concat (table [, sep [, i [, j]]])table[i]..sep..table[i+1] ··· sep..table[j].
The default value for sep is the empty string,
the default for i is 1,
and the default for j is the length of the table.
If i is greater than j, returns the empty string.
table.insert (table, [pos,] value)
Inserts element value at position pos in table,
shifting up other elements to open space, if necessary.
The default value for pos is n+1,
where n is the length of the table (see §2.5.5),
so that a call table.insert(t,x) inserts x at the end
of table t.
table.maxn (table)Returns the largest positive numerical index of the given table, or zero if the table has no positive numerical indices. (To do its job this function does a linear traversal of the whole table.)
table.remove (table [, pos])
Removes from table the element at position pos,
shifting down other elements to close the space, if necessary.
Returns the value of the removed element.
The default value for pos is n,
where n is the length of the table,
so that a call table.remove(t) removes the last element
of table t.
table.sort (table [, comp])table[1] to table[n],
where n is the length of the table.
If comp is given,
then it must be a function that receives two table elements,
and returns true
when the first is less than the second
(so that not comp(a[i+1],a[i]) will be true after the sort).
If comp is not given,
then the standard Lua operator < is used instead.
The sort algorithm is not stable; that is, elements considered equal by the given order may have their relative positions changed by the sort.
This library is an interface to the standard C math library.
It provides all its functions inside the table math.
math.abs (x)
Returns the absolute value of x.
math.acos (x)
Returns the arc cosine of x (in radians).
math.asin (x)
Returns the arc sine of x (in radians).
math.atan (x)
Returns the arc tangent of x (in radians).
math.atan2 (x, y)
Returns the arc tangent of x/y (in radians),
but uses the signs of both parameters to find the
quadrant of the result.
(It also handles correctly the case of y being zero.)
math.ceil (x)
Returns the smallest integer larger than or equal to x.
math.cos (x)
Returns the cosine of x (assumed to be in radians).
math.cosh (x)
Returns the hyperbolic cosine of x.
math.deg (x)
Returns the angle x (given in radians) in degrees.
math.exp (x)Returns the the value ex.
math.floor (x)
Returns the largest integer smaller than or equal to x.
math.fmod (x, y)
Returns the remainder of the division of x by y.
math.frexp (x)
Returns m and e such that x = m2e,
e is an integer and the absolute value of m is
in the range [0.5, 1)
(or zero when x is zero).
math.huge
The value HUGE_VAL,
a value larger than or equal to any other numerical value.
math.ldexp (m, e)
Returns m2e (e should be an integer).
math.log (x)
Returns the natural logarithm of x.
math.log10 (x)
Returns the base-10 logarithm of x.
math.max (x, ···)Returns the maximum value among its arguments.
math.min (x, ···)Returns the minimum value among its arguments.
math.modf (x)
Returns two numbers,
the integral part of x and the fractional part of x.
math.piThe value of pi.
math.pow (x, y)
Returns xy.
(You can also use the expression x^y to compute this value.)
math.rad (x)
Returns the angle x (given in degrees) in radians.
math.random ([m [, n]])
This function is an interface to the simple
pseudo-random generator function rand provided by ANSI C.
(No guarantees can be given for its statistical properties.)
When called without arguments,
returns a pseudo-random real number
in the range [0,1).
When called with a number m,
math.random returns
a pseudo-random integer in the range [1, m].
When called with two numbers m and n,
math.random returns a pseudo-random
integer in the range [m, n].
math.randomseed (x)
Sets x as the "seed"
for the pseudo-random generator:
equal seeds produce equal sequences of numbers.
math.sin (x)
Returns the sine of x (assumed to be in radians).
math.sinh (x)
Returns the hyperbolic sine of x.
math.sqrt (x)
Returns the square root of x.
(You can also use the expression x^0.5 to compute this value.)
math.tan (x)
Returns the tangent of x (assumed to be in radians).
math.tanh (x)
Returns the hyperbolic tangent of x.
The I/O library provides two different styles for file manipulation. The first one uses implicit file descriptors; that is, there are operations to set a default input file and a default output file, and all input/output operations are over these default files. The second style uses explicit file descriptors.
When using implicit file descriptors,
all operations are supplied by table io.
When using explicit file descriptors,
the operation io.open returns a file descriptor
and then all operations are supplied as methods of the file descriptor.
The table io also provides
three predefined file descriptors with their usual meanings from C:
io.stdin, io.stdout, and io.stderr.
Unless otherwise stated, all I/O functions return nil on failure (plus an error message as a second result) and some value different from nil on success.
io.close ([file])
Equivalent to file:close().
Without a file, closes the default output file.
io.flush ()
Equivalent to file:flush over the default output file.
io.input ([file])When called with a file name, it opens the named file (in text mode), and sets its handle as the default input file. When called with a file handle, it simply sets this file handle as the default input file. When called without parameters, it returns the current default input file.
In case of errors this function raises the error, instead of returning an error code.
io.lines ([filename])Opens the given file name in read mode and returns an iterator function that, each time it is called, returns a new line from the file. Therefore, the construction
for line in io.lines(filename) do body end
will iterate over all lines of the file. When the iterator function detects the end of file, it returns nil (to finish the loop) and automatically closes the file.
The call io.lines() (with no file name) is equivalent
to io.input():lines();
that is, it iterates over the lines of the default input file.
In this case it does not close the file when the loop ends.
io.open (filename [, mode])
This function opens a file,
in the mode specified in the string mode.
It returns a new file handle,
or, in case of errors, nil plus an error message.
The mode string can be any of the following:
The mode string may also have a 'b' at the end,
which is needed in some systems to open the file in binary mode.
This string is exactly what is used in the
standard C function fopen.
io.output ([file])
Similar to io.input, but operates over the default output file.
io.popen (prog [, mode])
Starts program prog in a separated process and returns
a file handle that you can use to read data from this program
(if mode is "r", the default)
or to write data to this program
(if mode is "w").
This function is system dependent and is not available on all platforms.
io.read (···)
Equivalent to io.input():read.
io.tmpfile ()Returns a handle for a temporary file. This file is opened in update mode and it is automatically removed when the program ends.
io.type (obj)
Checks whether obj is a valid file handle.
Returns the string "file" if obj is an open file handle,
"closed file" if obj is a closed file handle,
or nil if obj is not a file handle.
io.write (···)
Equivalent to io.output():write.
file:close ()
Closes file.
Note that files are automatically closed when
their handles are garbage collected,
but that takes an unpredictable amount of time to happen.
file:flush ()
Saves any written data to file.
file:lines ()Returns an iterator function that, each time it is called, returns a new line from the file. Therefore, the construction
for line in file:lines() do body end
will iterate over all lines of the file.
(Unlike io.lines, this function does not close the file
when the loop ends.)
file:read (···)
Reads the file file,
according to the given formats, which specify what to read.
For each format,
the function returns a string (or a number) with the characters read,
or nil if it cannot read data with the specified format.
When called without formats,
it uses a default format that reads the entire next line
(see below).
The available formats are
file:seek ([whence] [, offset])
Sets and gets the file position,
measured from the beginning of the file,
to the position given by offset plus a base
specified by the string whence, as follows:
In case of success, function seek returns the final file position,
measured in bytes from the beginning of the file.
If this function fails, it returns nil,
plus a string describing the error.
The default value for whence is "cur",
and for offset is 0.
Therefore, the call file:seek() returns the current
file position, without changing it;
the call file:seek("set") sets the position to the
beginning of the file (and returns 0);
and the call file:seek("end") sets the position to the
end of the file, and returns its size.
file:setvbuf (mode [, size])Sets the buffering mode for an output file. There are three available modes:
flush the file
(see io.flush)).
For the last two cases, sizes
specifies the size of the buffer, in bytes.
The default is an appropriate size.
file:write (···)
Writes the value of each of its arguments to
the file.
The arguments must be strings or numbers.
To write other values,
use tostring or string.format before write.
This library is implemented through table os.
os.clock ()Returns an approximation of the amount in seconds of CPU time used by the program.
os.date ([format [, time]])
Returns a string or a table containing date and time,
formatted according to the given string format.
If the time argument is present,
this is the time to be formatted
(see the os.time function for a description of this value).
Otherwise, date formats the current time.
If format starts with '!',
then the date is formatted in Coordinated Universal Time.
After this optional character,
if format is the string "*t",
then date returns a table with the following fields:
year (four digits), month (1--12), day (1--31),
hour (0--23), min (0--59), sec (0--61),
wday (weekday, Sunday is 1),
yday (day of the year),
and isdst (daylight saving flag, a boolean).
If format is not "*t",
then date returns the date as a string,
formatted according to the same rules as the C function strftime.
When called without arguments,
date returns a reasonable date and time representation that depends on
the host system and on the current locale
(that is, os.date() is equivalent to os.date("%c")).
os.difftime (t2, t1)
Returns the number of seconds from time t1 to time t2.
In POSIX, Windows, and some other systems,
this value is exactly t2-t1.
os.execute ([command])
This function is equivalent to the C function system.
It passes command to be executed by an operating system shell.
It returns a status code, which is system-dependent.
If command is absent, then it returns nonzero if a shell is available
and zero otherwise.
os.exit ([code])
Calls the C function exit,
with an optional code,
to terminate the host program.
The default value for code is the success code.
os.getenv (varname)
Returns the value of the process environment variable varname,
or nil if the variable is not defined.
os.remove (filename)Deletes the file or directory with the given name. Directories must be empty to be removed. If this function fails, it returns nil, plus a string describing the error.
os.rename (oldname, newname)
Renames file or directory named oldname to newname.
If this function fails, it returns nil,
plus a string describing the error.
os.setlocale (locale [, category])
Sets the current locale of the program.
locale is a string specifying a locale;
category is an optional string describing which category to change:
"all", "collate", "ctype",
"monetary", "numeric", or "time";
the default category is "all".
The function returns the name of the new locale,
or nil if the request cannot be honored.
When called with nil as the first argument, this function only returns the name of the current locale for the given category.
os.time ([table])
Returns the current time when called without arguments,
or a time representing the date and time specified by the given table.
This table must have fields year, month, and day,
and may have fields hour, min, sec, and isdst
(for a description of these fields, see the os.date function).
The returned value is a number, whose meaning depends on your system.
In POSIX, Windows, and some other systems, this number counts the number
of seconds since some given start time (the "epoch").
In other systems, the meaning is not specified,
and the number returned by time can be used only as an argument to
date and difftime.
os.tmpname ()Returns a string with a file name that can be used for a temporary file. The file must be explicitly opened before its use and explicitly removed when no longer needed.
This library provides the functionality of the debug interface to Lua programs. You should exert care when using this library. The functions provided here should be used exclusively for debugging and similar tasks, such as profiling. Please resist the temptation to use them as a usual programming tool: they can be very slow. Moreover, several of its functions violate some assumptions about Lua code (e.g., that variables local to a function cannot be accessed from outside or that userdata metatables cannot be changed by Lua code) and therefore can compromise otherwise secure code.
All functions in this library are provided
inside the debug table.
All functions that operate over a thread
have an optional first argument which is the
thread to operate over.
The default is always the current thread.
debug.debug ()
Enters an interactive mode with the user,
running each string that the user enters.
Using simple commands and other debug facilities,
the user can inspect global and local variables,
change their values, evaluate expressions, and so on.
A line containing only the word cont finishes this function,
so that the caller continues its execution.
Note that commands for debug.debug are not lexically nested
within any function, and so have no direct access to local variables.
debug.getfenv (o)o.
debug.gethook ([thread])
Returns the current hook settings of the thread, as three values:
the current hook function, the current hook mask,
and the current hook count
(as set by the debug.sethook function).
debug.getinfo ([thread,] function [, what])
Returns a table with information about a function.
You can give the function directly,
or you can give a number as the value of function,
which means the function running at level function of the call stack
of the given thread:
level 0 is the current function (getinfo itself);
level 1 is the function that called getinfo;
and so on.
If function is a number larger than the number of active functions,
then getinfo returns nil.
The returned table may contain all the fields returned by lua_getinfo,
with the string what describing which fields to fill in.
The default for what is to get all information available,
except the table of valid lines.
If present,
the option 'f'
adds a field named func with the function itself.
If present,
the option 'L'
adds a field named activelines with the table of
valid lines.
For instance, the expression debug.getinfo(1,"n").name returns
a name of the current function, if a reasonable name can be found,
and the expression debug.getinfo(print)
returns a table with all available information
about the print function.
debug.getlocal ([thread,] level, local)
This function returns the name and the value of the local variable
with index local of the function at level level of the stack.
(The first parameter or local variable has index 1, and so on,
until the last active local variable.)
The function returns nil if there is no local
variable with the given index,
and raises an error when called with a level out of range.
(You can call debug.getinfo to check whether the level is valid.)
Variable names starting with '(' (open parentheses)
represent internal variables
(loop control variables, temporaries, and C function locals).
debug.getmetatable (object)
Returns the metatable of the given object
or nil if it does not have a metatable.
debug.getregistry ()Returns the registry table (see §3.5).
debug.getupvalue (func, up)
This function returns the name and the value of the upvalue
with index up of the function func.
The function returns nil if there is no upvalue with the given index.
debug.setfenv (object, table)
Sets the environment of the given object to the given table.
Returns object.
debug.sethook ([thread,] hook, mask [, count])
Sets the given function as a hook.
The string mask and the number count describe
when the hook will be called.
The string mask may have the following characters,
with the given meaning:
"c": The hook is called every time Lua calls a function;"r": The hook is called every time Lua returns from a function;"l": The hook is called every time Lua enters a new line of code.
With a count different from zero,
the hook is called after every count instructions.
When called without arguments,
debug.sethook turns off the hook.
When the hook is called, its first parameter is a string
describing the event that has triggered its call:
"call", "return" (or "tail return"),
"line", and "count".
For line events,
the hook also gets the new line number as its second parameter.
Inside a hook,
you can call getinfo with level 2 to get more information about
the running function
(level 0 is the getinfo function,
and level 1 is the hook function),
unless the event is "tail return".
In this case, Lua is only simulating the return,
and a call to getinfo will return invalid data.
debug.setlocal ([thread,] level, local, value)
This function assigns the value value to the local variable
with index local of the function at level level of the stack.
The function returns nil if there is no local
variable with the given index,
and raises an error when called with a level out of range.
(You can call getinfo to check whether the level is valid.)
Otherwise, it returns the name of the local variable.
debug.setmetatable (object, table)
Sets the metatable for the given object to the given table
(which can be nil).
debug.setupvalue (func, up, value)
This function assigns the value value to the upvalue
with index up of the function func.
The function returns nil if there is no upvalue
with the given index.
Otherwise, it returns the name of the upvalue.
debug.traceback ([thread,] [message] [, level])
Returns a string with a traceback of the call stack.
An optional message string is appended
at the beginning of the traceback.
An optional level number tells at which level
to start the traceback
(default is 1, the function calling traceback).
Although Lua has been designed as an extension language,
to be embedded in a host C program,
it is also frequently used as a stand-alone language.
An interpreter for Lua as a stand-alone language,
called simply lua,
is provided with the standard distribution.
The stand-alone interpreter includes
all standard libraries, including the debug library.
Its usage is:
lua [options] [script [args]]
The options are:
-e stat: executes string stat;-l mod: "requires" mod;-i: enters interactive mode after running script;-v: prints version information;--: stops handling options;-: executes stdin as a file and stops handling options.
After handling its options, lua runs the given script,
passing to it the given args as string arguments.
When called without arguments,
lua behaves as lua -v -i
when the standard input (stdin) is a terminal,
and as lua - otherwise.
Before running any argument,
the interpreter checks for an environment variable LUA_INIT.
If its format is @filename,
then lua executes the file.
Otherwise, lua executes the string itself.
All options are handled in order, except -i.
For instance, an invocation like
$ lua -e'a=1' -e 'print(a)' script.lua
will first set a to 1, then print the value of a (which is '1'),
and finally run the file script.lua with no arguments.
(Here $ is the shell prompt. Your prompt may be different.)
Before starting to run the script,
lua collects all arguments in the command line
in a global table called arg.
The script name is stored at index 0,
the first argument after the script name goes to index 1,
and so on.
Any arguments before the script name
(that is, the interpreter name plus the options)
go to negative indices.
For instance, in the call
$ lua -la b.lua t1 t2
the interpreter first runs the file a.lua,
then creates a table
arg = { [-2] = "lua", [-1] = "-la",
[0] = "b.lua",
[1] = "t1", [2] = "t2" }
and finally runs the file b.lua.
The script is called with arg[1], arg[2], ···
as arguments;
it can also access these arguments with the vararg expression '...'.
In interactive mode, if you write an incomplete statement, the interpreter waits for its completion by issuing a different prompt.
If the global variable _PROMPT contains a string,
then its value is used as the prompt.
Similarly, if the global variable _PROMPT2 contains a string,
its value is used as the secondary prompt
(issued during incomplete statements).
Therefore, both prompts can be changed directly on the command line.
For instance,
$ lua -e"_PROMPT='myprompt> '" -i
(the outer pair of quotes is for the shell,
the inner pair is for Lua),
or in any Lua programs by assigning to _PROMPT.
Note the use of -i to enter interactive mode; otherwise,
the program would just end silently right after the assignment to _PROMPT.
To allow the use of Lua as a
script interpreter in Unix systems,
the stand-alone interpreter skips
the first line of a chunk if it starts with #.
Therefore, Lua scripts can be made into executable programs
by using chmod +x and the #! form,
as in
#!/usr/local/bin/lua
(Of course,
the location of the Lua interpreter may be different in your machine.
If lua is in your PATH,
then
#!/usr/bin/env lua
is a more portable solution.)
Here we list the incompatibilities that you may found when moving a program
from Lua 5.0 to Lua 5.1.
You can avoid most of the incompatibilities compiling Lua with
appropriate options (see file luaconf.h).
However,
all these compatibility options will be removed in the next version of Lua.
arg with a
table with the extra arguments to the vararg expression.
(See compile-time option LUA_COMPAT_VARARG in luaconf.h.)
[[string]])
does not allow nesting.
You can use the new syntax ([=[string]=]) in these cases.
(See compile-time option LUA_COMPAT_LSTR in luaconf.h.)
string.gfind was renamed string.gmatch.
(See compile-time option LUA_COMPAT_GFIND in luaconf.h.)
string.gsub is called with a function as its
third argument,
whenever this function returns nil or false the
replacement string is the whole match,
instead of the empty string.
table.setn was deprecated.
Function table.getn corresponds
to the new length operator (#);
use the operator instead of the function.
(See compile-time option LUA_COMPAT_GETN in luaconf.h.)
loadlib was renamed package.loadlib.
(See compile-time option LUA_COMPAT_LOADLIB in luaconf.h.)
math.mod was renamed math.fmod.
(See compile-time option LUA_COMPAT_MOD in luaconf.h.)
table.foreach and table.foreachi are deprecated.
You can use a for loop with pairs or ipairs instead.
require due to
the new module system.
However, the new behavior is mostly compatible with the old,
but require gets the path from package.path instead
of from LUA_PATH.
collectgarbage has different arguments.
Function gcinfo is deprecated;
use collectgarbage("count") instead.
luaopen_* functions (to open libraries)
cannot be called directly,
like a regular C function.
They must be called through Lua,
like a Lua function.
lua_open was replaced by lua_newstate to
allow the user to set a memory-allocation function.
You can use luaL_newstate from the standard library to
create a state with a standard allocation function
(based on realloc).
luaL_getn and luaL_setn
(from the auxiliary library) are deprecated.
Use lua_objlen instead of luaL_getn
and nothing instead of luaL_setn.
luaL_openlib was replaced by luaL_register.
luaL_checkudata now throws an error when the given value
is not a userdata of the expected type.
(In Lua 5.0 it returned NULL.)
Here is the complete syntax of Lua in extended BNF. (It does not describe operator precedences.)
chunk ::= {stat [`;´]} [laststat [`;´]]
block ::= chunk
stat ::= varlist1 `=´ explist1 |
functioncall |
do block end |
while exp do block end |
repeat block until exp |
if exp then block {elseif exp then block} [else block] end |
for Name `=´ exp `,´ exp [`,´ exp] do block end |
for namelist in explist1 do block end |
function funcname funcbody |
local function Name funcbody |
local namelist [`=´ explist1]
laststat ::= return [explist1] | break
funcname ::= Name {`.´ Name} [`:´ Name]
varlist1 ::= var {`,´ var}
var ::= Name | prefixexp `[´ exp `]´ | prefixexp `.´ Name
namelist ::= Name {`,´ Name}
explist1 ::= {exp `,´} exp
exp ::= nil | false | true | Number | String | `...´ | function |
prefixexp | tableconstructor | exp binop exp | unop exp
prefixexp ::= var | functioncall | `(´ exp `)´
functioncall ::= prefixexp args | prefixexp `:´ Name args
args ::= `(´ [explist1] `)´ | tableconstructor | String
function ::= function funcbody
funcbody ::= `(´ [parlist1] `)´ block end
parlist1 ::= namelist [`,´ `...´] | `...´
tableconstructor ::= `{´ [fieldlist] `}´
fieldlist ::= field {fieldsep field} [fieldsep]
field ::= `[´ exp `]´ `=´ exp | Name `=´ exp | exp
fieldsep ::= `,´ | `;´
binop ::= `+´ | `-´ | `*´ | `/´ | `^´ | `%´ | `..´ |
`<´ | `<=´ | `>´ | `>=´ | `==´ | `~=´ |
and | or
unop ::= `-´ | not | `#´