6

Click here to load reader

Programación de Sistemas - LUA: Gramática

Embed Size (px)

Citation preview

Page 1: Programación de Sistemas - LUA: Gramática

2011

Antonio Acosta Murillo

Instituto Tecnológico de Culiacán

03/09/2011

LUA: Gramática

Page 2: Programación de Sistemas - LUA: Gramática

Programación de Sistemas

Ing. Sistemas Computacionales

Antes de comenzar a desarrollar la gramática del lenguaje de programación Lua, haré una

breve introducción para conocer un poco sobre las bondades de este lenguaje de

programación que rápidamente está escalando posiciones en el ranking de los lenguajes

de programación según la encuesta de la página web Tiobe1.

Lua es un lenguaje de programación imperativa, estructurada y bastante ligero que fue

diseñado como un lenguaje interpretado con una semántica que se pudiera extender. El

nombre significa "luna" en portugués y gallego.

Lua fue creado en 1993 por Roberto Ierusalimschy, Luiz Henrique de Figueiredo y

Waldemar Celes, miembros del Grupo de Tecnología en Computación Gráfica (Tecgraf)

en la Pontificia Universidad Católica de Río de Janeiro. Las versiones de Lua anteriores a

la 5.0 fueron distribuidas bajo una licencia similar a la BSD, de la versión 5.0 en adelante

se utiliza la licencia MIT, compatible con la GPL.

Lua ha sido usado en muchas aplicaciones comerciales y no comerciales, cuyo número

incrementa cada año.

Lua es un lenguaje de extensión, suficientemente compacto para usarse en diferentes

plataformas. En lua las variables no tienen tipo, sólo los datos y pueden ser lógicos,

enteros, números de coma flotante o cadenas. Estructuras de datos como vectores,

conjuntos, tablas hash, listas y registros pueden ser representadas utilizando la única

estructura de datos de Lua: la tabla.

TIOBE Programming Community Index

1 The TIOBE Programming Community index is an indicator of the popularity of programming

languages. The index is updated once a month. The ratings are based on the number of skilled engineers world-wide, courses and third party vendors.

Page 3: Programación de Sistemas - LUA: Gramática

Programación de Sistemas

Ing. Sistemas Computacionales

Lua 5.1 Gramática %fallback OPEN '(' . chunk ::= block . semi ::= ';' . semi ::= . block ::= scope statlist . block ::= scope statlist laststat semi . ublock ::= block 'until' exp . scope ::= . scope ::= scope statlist binding semi. statlist ::= . statlist ::= statlist stat semi . stat ::= 'do' block 'end' . stat ::= 'while' exp 'do' block 'end' . stat ::= repetition 'do' block 'end' . stat ::= 'repeat' ublock . stat ::= 'if' conds 'end' . stat ::= 'function' funcname funcbody . stat ::= setlist '=' explist1 . stat ::= functioncall . repetition ::= 'for' NAME '=' explist23 . repetition ::= 'for' namelist 'in' explist1 . conds ::= condlist . conds ::= condlist 'else' block . condlist ::= cond . condlist ::= condlist 'elseif' cond . cond ::= exp 'then' block . laststat ::= 'break' . laststat ::= 'return' . laststat ::= 'return' explist1 . binding ::= 'local' namelist . binding ::= 'local' namelist '=' explist1 . binding ::= 'local' 'function' NAME funcbody . funcname ::= dottedname . funcname ::= dottedname ':' NAME . dottedname ::= NAME . dottedname ::= dottedname '.' NAME . namelist ::= NAME . namelist ::= namelist ',' NAME . explist1 ::= exp . explist1 ::= explist1 ',' exp . explist23 ::= exp ',' exp . explist23 ::= exp ',' exp ',' exp . %left 'or' . %left 'and' . %left '<' '<=' '>' '>=' '==' '~=' .

%right '..' . %left '+' '-' . %left '*' '/' '%' . %right 'not' '#' . %right '^' . exp ::= 'nil'|'true'|'false'|NUMBER|STRING|'...' . exp ::= function . exp ::= prefixexp . exp ::= tableconstructor . exp ::= 'not'|'#'|'-' exp . ['not'] exp ::= exp 'or' exp . exp ::= exp 'and' exp . exp ::= exp '<'|'<='|'>'|'>='|'=='|'~=' exp . exp ::= exp '..' exp . exp ::= exp '+'|'-' exp . exp ::= exp '*'|'/'|'%' exp . exp ::= exp '^' exp . setlist ::= var . setlist ::= setlist ',' var . var ::= NAME . var ::= prefixexp '[' exp ']' . var ::= prefixexp '.' NAME . prefixexp ::= var . prefixexp ::= functioncall . prefixexp ::= OPEN exp ')' . functioncall ::= prefixexp args . functioncall ::= prefixexp ':' NAME args . args ::= '(' ')' . args ::= '(' explist1 ')' . args ::= tableconstructor . args ::= STRING . function ::= 'function' funcbody . funcbody ::= params block 'end' . params ::= '(' parlist ')' . parlist ::= . parlist ::= namelist . parlist ::= '...' . parlist ::= namelist ',' '...' . tableconstructor ::= '{' '}' . tableconstructor ::= '{' fieldlist '}' . tableconstructor ::= '{' fieldlist ','|';' '}' . fieldlist ::= field . fieldlist ::= fieldlist ','|';' field . field ::= exp . field ::= NAME '=' exp . field ::= '[' exp ']' '=' exp .

Page 4: Programación de Sistemas - LUA: Gramática

Programación de Sistemas

Ing. Sistemas Computacionales

Lua Sintaxis

chunk ::= {sentencia [';']} [última_sentencia[';']] bloque ::= chunk sentencia ::= varlist '=' explist | llamada_a_func | do bloque end | while exp do bloque end | repeat bloque until exp | if exp then bloque {elseif exp then bloque} [else bloque] end | for nombre '=' exp ',' exp [',' exp] do bloque end | for lista_de_nombres in explist do bloque end | function nombre_de_func cuerpo_de_func | local function nombre cuerpo_de_func | local lista_de_nombres ['=' explist] última_sentencia ::= return [explist] | break nombre_de_func ::= nombre {'.' nombre} [':' nombre] varlist ::= var {',' var} var ::= nombre | prefixexp '[' exp ']' | prefixexp '.' nombre lista_de_nombres ::= nombre {',' nombre} explist ::= {exp ','} exp exp ::= nil | false | true | número | string | '...' | func | prefixexp | constructor_de_tabla | exp operador_binario exp | operador_unario exp prefixexp ::= var | llamada_a_func | '(' exp ')' llamada_a_func ::= prefixexp arg_actuales | prefixexp ':' nombre args_actuales args_actuales ::= '(' [explist] ')' | constructor_de_tabla | string func ::= function cuerpo_de_func cuerpo_de_func ::= '(' [args_formal_list] ')' bloque end args_formal_list ::= lista_de_nombres [',' '...'] | '...' constructor_de_tabla ::= '{' [lista_de_campos] '}' lista_de_campos ::= campo {separador_de_campo campo} [separador_de_campo] campo ::= '[' exp ']' '=' exp | nombre '=' exp | exp separador_de_campo ::= ',' | ';' operador_binario ::= '+' | '-' | '*' | '/' | '^' | '%' | '..' | '<' | '<=' | '>' | '>=' | '==' | '~=' | and | or operador_unario ::= '-' | not | '#'

Page 5: Programación de Sistemas - LUA: Gramática

Programación de Sistemas

Ing. Sistemas Computacionales

Ejemplos de programas en Lua

--Wrap a string at a given margin

This is intended for strings without newlines in them (i.e. after reflowing the text and breaking it into paragraphs.) function wrap(str, limit, indent, indent1) indent = indent or "" indent1 = indent1 or indent limit = limit or 72 local here = 1-#indent1 return indent1..str:gsub("(%s+)()(%S+)()", function(sp, st, word, fi) if fi-here > limit then here = st - #indent return "\n"..indent..word end end) end

-- Bisect.lua

-- bisection method for solving non-linear equations delta=1e-6 -- tolerance function bisect(f,a,b,fa,fb) local c=(a+b)/2 io.write(n," c=",c," a=",a," b=",b,"\n") if c==a or c==b or math.abs(a-b)<delta then return c,b-a end n=n+1 local fc=f(c) if fa*fc<0 then return bisect(f,a,c,fa,fc) else return bisect(f,c,b,fc,fb) end end -- find root of f in the inverval [a,b]. needs f(a)*f(b)<0 function solve(f,a,b) n=0 local z,e=bisect(f,a,b,f(a),f(b)) io.write(string.format("after %d steps, root is %.17g with error %.1e, f=%.1e\n",n,z,e,f(z))) end -- our function function f(x) return x*x*x-x-1 end -- find zero in [1,2] solve(f,1,2)

Page 6: Programación de Sistemas - LUA: Gramática

Programación de Sistemas

Ing. Sistemas Computacionales

Output Bisect.lua

0 c=1.5 a=1 b=2

1 c=1.25 a=1 b=1.5

2 c=1.375 a=1.25 b=1.5

3 c=1.3125 a=1.25 b=1.375

4 c=1.34375 a=1.3125 b=1.375

5 c=1.328125 a=1.3125 b=1.34375

6 c=1.3203125 a=1.3125 b=1.328125

7 c=1.32421875 a=1.3203125 b=1.328125

8 c=1.326171875 a=1.32421875 b=1.328125

9 c=1.3251953125 a=1.32421875 b=1.326171875

10 c=1.32470703125 a=1.32421875 b=1.3251953125

11 c=1.324951171875 a=1.32470703125 b=1.3251953125

12 c=1.3248291015625 a=1.32470703125 b=1.324951171875

13 c=1.3247680664062 a=1.32470703125 b=1.3248291015625

14 c=1.3247375488281 a=1.32470703125 b=1.3247680664062

15 c=1.3247222900391 a=1.32470703125 b=1.3247375488281

16 c=1.3247146606445 a=1.32470703125 b=1.3247222900391

17 c=1.3247184753418 a=1.3247146606445 b=1.3247222900391

18 c=1.3247165679932 a=1.3247146606445 b=1.3247184753418

19 c=1.3247175216675 a=1.3247165679932 b=1.3247184753418

20 c=1.3247179985046 a=1.3247175216675 b=1.3247184753418

after 20 steps, root is 1.3247179985046387 with error 9.5e-07, f=1.8e-07