underpop

http://underpop.online.fr 2009-02-07  

Qual LAPTOP - NOTEBOOK comprar?

laptop
[lQpta-t] [Ingl., lit., 'sobre o colo', por analogia com desktop (q. v.).]
Substantivo masculino.

1.
Inform. Microcomputador portátil, dotado de bateria e com monitor plano e teclado acoplados a um gabinete compacto, próprio para uso em situações de locomoção, como durante viagens. [Cf. desktop e notebook.]


Em geral, um Laptop funciona como um computador convencional; a diferença está no fato de ser menor e mais fácil de transportar. As mesmas considerações feitas quanto à escolha de um Laptop se aplicam à compra de um Laptop: você quer equilibrar custo e taxa de desempenho. Os fornecedores oferecem garantias semelhantes para computadores portáteis e convencionais, variando de 3 meses a 3 anos ou mais.

Há algumas considerações especiais para computadores portáteis que ajudam a utilizar melhor seu PC. Falaremos detalhadamente sobre isso e também sobre como aplicar melhor o seu dinheiro ao comprar um novo Laptop.

Tenha em mente o uso que ele terá - pessoas que viajam com freqüência precisam transportá-lo e ele precisa ser leve, mas usuários comerciais não podem prejudicar a potência. Ao substituir o Laptop, o Laptop precisará ter mais potência e capacidade de armazenamento. Caso este seja seu segundo ou terceiro computador, você desejará transportá-lo, mas não precisará de todo aquele espaço extra de memória RAM e disco rígido.

Como comprar um Laptop?

Primeiramente, você deve decidir para que seu Laptop será utilizado. Ele será usado basicamente para digitar informações e acessar a Internet? Considere um Laptop leve e fino que seja fácil de carregar e não ocupe muito espaço ou então uma combinação de um Laptop/tablet PC com tela sensível a toque e um teclado. Você precisa de um sistema de substituição de Laptop que lide com tudo, desde Projeto Assistido pelo Computador (CAD) até jogos? Então, será necessário ter um processador mais potente e gráficos high-end. Talvez você queira um Laptop que possa realizar todas as tarefas de multimídia, desde edição de vídeo e gravação de DVDs até trabalho como gravador de vídeo portátil para seus programas de TV favoritos. Felizmente há computadores que atendem a todas essas classificações e a maioria dos fornecedores irá instrui-lo corretamente em relação a como eles classificam as linhas do sistema. No entanto, é bom ter algumas coisas específicas em mente ao planejar a compra de um Laptop.

Assim como acontece com desktops, o processador é o centro da potência de um Laptop. Quanto mais rápido for o processador, melhor será o desempenho apresentado em cada aplicativo que executar. Enquanto alguns sistemas de substituição apresentam processadores de computadores de mesa reais, a maioria dos novos Laptops oferece versões móveis de CPUs de computadores de mesa. Por exemplo, a classe Centrino de processadores Intel oferece desempenho de CPU semelhante ao de Laptop, mas também libera menos calor e utiliza menos potência, dois recursos que realmente beneficiam os usuários de computadores portáteis. A AMD também oferece versões móveis dos processadores. As duas empresas apresentam CPUs móveis top de linha e CPUs que reduzem o custo, mas também diminuem o nível de desempenho. Obtenha o máximo de potência de processador que puder, pois isso aumentará a duração do Laptop - ao contrário do que acontece com os computadores de mesa, não será possível atualizar o processador da maioria dos computadores portáteis posteriormente. Uma boa opção é escolher níveis duas ou três vezes abaixo do processador mais rápido em sua classe de computadores portáteis para obter a melhor taxa de preço pelo desempenho.

A importância da memória é a mesma tanto para computadores portáteis quanto para os de mesa. Você irá precisar de, no mínimo, 1 GB de memória RAM para Windows Vista e aumentar isso para 2GB não será prejudicial. Ao contrário dos processadores, você poderá incluir mais memória em seu Laptop posteriormente (embora dependa do número de soquetes disponíveis e da configuração de memória atual, talvez você precise substituir parte da memória RAM inicial). Verifique quantos soquetes de memória abertos estão disponíveis no seu sistema para saber quais são as opções de atualização à disposição.

O espaço do disco rígido é outro ponto fundamental a ser considerado para a maioria dos usuários. Tenha bastante espaço para seu arquivos. Caso seu Laptop seja seu único sistema, você precisará de tanto espaço de armazenamento quanto precisaria em um Laptop. A maioria dos novos computadores portáteis apresenta discos rígidos de pelo menos 80GB. Caso você vá executar jogos ou utilizar vários arquivos de multimídia em seu sistema, opte por uma unidade maior. Assim como acontece com os computadores de mesa, preste atenção aos RPMs (rotações por minuto) na unidade. Isso indica a velocidade com que a unidade lê e grava os dados. A maioria dos usuários prefere disco rígido de 5.400rpm ou mais no Laptop.

Embora sejam mis finos, as unidades ópticas executam a mesma gama em computadores portáteis e sistemas dos de mesa. Você pode realizar tudo desde uma unidade básica de CD-ROM que apenas leia CDs até unidades DVD+/-RW Double Layer (duas camadas) que grave DVDs normais, bem como mídia DL de 8,5GB de alta capacidade. Se precisar gravar DVDs, uma unidade de CD-RW/DVD-ROM é uma boa opção para a maioria dos usuários. Isso permite que você assista aos DVDs em seu Laptop e grave seus próprios CDs de áudio e dados na mesma unidade.

A escolha do melhor monitor é outra grande decisão a ser tomada pelos proprietários de computadores portáteis. Muitos dos novos sistemas de multimídia apresentam telas widescreen que permitem manter vários documentos abertos para que possa visualizá-los lado-a-lado ou assistir a filmes em DVD no formato widescreen. Sistemas finos e leves possuem telas menores, evidentemente. Sendo assim, verifique se a tela do seu Laptop é do tamanho correto para atender às suas necessidades. Não confie apenas nos números que vê online - vá a uma loja local de computadores e veja o tamanho das telas de computadores portáteis. Tela de doze polegadas pode ser muito pequena para reproduzir jogos ou editar um documento, mas pode ser boa para navegar na Internet. Muitos fornecedores oferecem melhores telas aos computadores portáteis para que você tenha uma imagem mais nítida e clara. Sendo assim, para alguns usuários compensa o custo extra.

As unidades de disquete tornaram-se inúteis na maioria dos novos computadores portáteis. Caso precise de uma, verifique atentamente as especificações do produto. No entanto, a maioria dos usuários acredita que o uso de uma unidade rápida de USB é algo mais rápido e mais fácil de manusear do que a mídia de disquete tradicional.

Por falar em USB, a maioria dos novos Laptops apresenta várias portas USB 2.0, permitindo, assim, conectar tudo, desde mouse até câmeras para videoconferência. A maioria dos computadores portáteis oferece uma porta Firewire, outra conexão de alta velocidade para seus dispositivos digitais. Embora quase não existam mais, as portas PCMCIA ainda são comuns em computadores portáteis, permitindo que você conecte acessórios com base no cartão de PC. Outra opção é o leitor de cartão de mídia, com soquetes para CompactFlash, Secure Digital e outros cartões de memória rápida para poder facilmente transferir arquivos e fotos do seu PDA, da sua câmera digital ou do MP3 player.

Tudo está incorporado ao Laptop. Sendo assim, teste o teclado e o dispositivo de entrada antes da compra. Embora seja fácil conectar um mouse (e há vários modelos de mouse criados especificamente para computadores portáteis), você estará preso ao teclado fornecido. Se for utilizar o computador por muito tempo seguido, verifique se o teclado é confortável o suficiente. A maioria dos computadores portáteis utiliza um touch pad para controle do cursor do mouse, mas alguns ainda utilizam uma bolinha de borracha no meio do teclado. Tenha a certeza de obter o que realmente quer.

Graças às baterias recarregáveis (a maioria de íon de lítio), os computadores portáteis podem funcionar por um período de duas a seis horas ou mais até que precisem de nova recarga. A duração do armazenamento das baterias é medida em "células". A maioria dos Laptops apresenta baterias de seis ou oito células, embora você possa conseguir baterias de até 12 células. Quanto mais células, maior será a duração da carga.

Os computadores portáteis se conectam à Internet de maneira tanto semelhante quanto diferente dos computadores de mesa. A maioria dos novos Laptops possui uma porta Ethernet incorporada, permitindo conexão discada, de banda larga ou em uma rede de alta velocidade. No entanto, muitos computadores portáteis também oferecem conectividade sem fio. O padrão mais comum é o 802.11 (geralmente com um "b" ou "g" atrás). Isso permite que o Laptop se conecte à Internet em uma lista crescente de pontos de conexão sem fio, desde lanchonetes até redes domésticas. Enquanto a maioria dos novos computadores portáteis apresenta recursos sem fio incorporados, alguns não o possuem. Sendo assim, será necessário comprar um cartão de atualização para adicionar o recurso.

Caso você utilize o Laptop para trabalho, também considera importante a segurança. Afinal, esse é um dispositivo caro e fácil de ser implementado. Muitos novos Laptops oferecem um soquete de bloqueio Kensington, permitindo que você segure seu Laptop para evitar roubo. Talvez você encontre recursos avançados de segurança de dados, como verificadores de impressão digital ou leitores de cartão inteligente em modelos mais novos, mantendo os olhares indesejados longe de seus arquivos.

Os gráficos são uma área defasada das cópias de computadores de mesa, mas mesmo os gráficos de Laptop têm evoluído bem. Se estiver utilizando seu Laptop para jogos ou edição de vídeo, procure um processador gráfico com memória de vídeo dedicada. Isso não irá retirar memória do sistema principal de memória RAM e oferece melhor desempenho gráfico. A qualidade de áudio também não é tão impressionante quant à dos alto-falantes do Laptop, mas se isso for importante a você, é possível encontrar computadores portáteis com excelente saída de alto-falante - mesmo com as caixas de som incorporadas.

Há vários recursos extras que podem ser encontrados em computadores portáteis, como sintonizadores de TV para assistir a e gravar seus programas de TV favoritos, portas adicionais de mídia, como S-video, que permite reproduzir sinal de vídeo em uma TV compatível, e Bluetooth. Essa tecnologia sem fio recente permite que seu Laptop se sincronize a outros dispositivos Bluetooth, como celulares e PDAs, sem precisar ligar qualquer fio..

As opções de sistemas operacionais e software que você encontrará nos computadores portáteis são semelhantes aos encontrados em computadores de mesa. Qualquer aplicativo executado em computadores de mesa pode ser executado em portáteis. Sendo assim, se quiser levar seu Office com você, não haveria problema algum.

Em geral, os computadores portáteis são mais caros do que os de mesa com potência semelhante devido ao fato de serem portáteis. Caso o orçamento seja sua prioridade, será possível encontrar computadores portáteis muito bons por preços excelentes.





Marcadores: , , , , , , , , , , , ,



2009-02-03  

What is Lua?

Description: Lua is a powerful, light-weight programming language designed for extending applications. Coupled with it being relatively fast and having a very lenient license, it has gained a following among game developers for providing a viable scripting interface. It has been used in games such as World of Warcraft and Far Cry, and in applications such as Adobe Photoshop Lightroom and Snort.

  1. What is Lua?
  2. Getting Started
  3. Identifiers, Types, and Values
  4. Variables and Expressions
  5. Operators
  6. Statements and Assignments
  7. Control Structures
  8. File I/O

What is Lua?

Lua is a powerful, light-weight programming language designed for extending applications. Lua is also frequently used as a general-purpose, stand-alone language. It is dynamically typed, interpreted from opcodes, great facility to handle strings and other kinds of data with dynamic size, and has automatic memory management with garbage collection, making it ideal for configuration, scripting, and rapid prototyping.

Lua is easily extended not only with software written in Lua itself, but also with software written in other languages, such as C and C++. Lua is also a glue language. Lua supports a component-based approach to software development, where we create an application by gluing together existing high-level components, written in a compiled, statically typed language, such as C or C++; Lua is the glue that we use to compose and connect those components. However, unlike other glue technologies, Lua is a full-fledged language as well. Therefore, we can use Lua not only to glue components, but also to adapt and reshape them, or even to create whole new components.

When to use Lua?

Lua is not the only scripting language around. There are other languages that you can use for more or less the same purposes, such as Perl, Tcl, Ruby, Forth, and Python. The following features set Lua apart from these languages; although other languages share some of these features with Lua, no other language offers a similar profile:

  • Extensibility: Lua's extensibility is so remarkable that many people regard Lua not as a language, but as a kit for building domain-specific languages. Lua has been designed from scratch to be extended, both through Lua code and through external C code. As a proof of concept, it implements most of its own basic functionality through external libraries. It is really easy to interface Lua with C/C++ and other languages, such as Fortran, Java, Smalltalk, Ada, and even with other scripting languages.
  • Simplicity: Lua is a simple and small language. It has few (but powerful) concepts. This simplicity makes Lua easy to learn and contributes for a small implementation. Its complete distribution (source code, manual, plus binaries for some platforms) fits comfortably in a floppy disk.
  • Efficiency: Lua has a quite efficient implementation. Independent benchmarks show Lua as one of the fastest languages in the realm of scripting (interpreted) languages.
  • Portability: When we talk about portability, we are not talking about running Lua both on Windows and on Unix platforms. We are talking about running Lua on all platforms we have ever heard about: NextStep, OS/2, PlayStation II (Sony), Mac OS-9 and OS X, BeOS, MS-DOS, IBM mainframes, EPOC, PalmOS, MCF5206eLITE Evaluation Board, RISC OS, plus of course all flavors of Unix and Windows. The source code for each of these platforms is virtually the same. Lua does not use conditional compilation to adapt its code to different machines; instead, it sticks to the standard ANSI (ISO) C. That way, usually you do not need to adapt it to a new environment: If you have an ANSI C compiler, you just have to compile Lua, out of the box.

For detailed information on Lua, please refer to the book Programming in Lua by Roberto Ierusalimschy, and Lua’s official site www.lua.org.



what is lua - XOOPS Blogger
Reblog this post [with Zemanta]

Marcadores: , ,



 

lua - getting started

Getting Started

Let's start with the traditional program to print "Hello, world" in Lua:

print("Hello, world")

To run the program, call the Lua interpreter (usually named lua) with the file name that contains the program. For example, if the above program resides in hello.lua, you can run it with:

prompt> lua hello.lua

or you can type the statements directly in the Lua interpreter by invoking the lua without any argument.

Now, let us go further to learn the elements of Lua language by writing a simple program to compute the square of a given number:

-- File mySqr.lua
function mySqr(x) -- Define a Function
return x*x; -- ';' is optional
end

print("Square Calculator")

--[[
Read a number from the user and
print the square value of that number
]]

print("Enter a number :")
n = io.read("*number")
print(mySqr(n))

Chunks and Blocks

A chunk is simply a sequence of statements that are executed sequentially. It is the unit of execution in Lua. It could be as simple as a singe statement, as in the "Hello, World" example or a group of statements, optionally separated by a semicolon as in mySqr.lua. A chunk may be stored in a file or in a string in the host program.

A block is a list of statements useful in controlling the scope of the variables. It can be a body of a control structure, body of a function or a chunk.

Comments

Anything that follows the double hyphen, --, is interpreted as a comment in Lua and runs till the end of the line. Line 1 in mySqr.lua is a short/single line comment.

If the double hyphen -- is immediately followed by [[, then it is a long comment that may span multiple lines till the matching ]]. Lines 6 through 9 in mySqr.lua represent a long comment. Long comments may contain nested [[ ... ]] pairs.

Standard Libraries

Lua comes with standard libraries that contain useful functions, as io.read in the above example. These libraries include functions for string manipulation, input & output, mathematical calculations, table manipulation, operating system and debug facilities in addition to the core functions. Please refer to the Lua Reference manual at http://www.lua.org/manual/ for the list of library functions available.

Reblog this post [with Zemanta]

Marcadores: , , , , , ,



 

Lua - Identifiers, Types, and Values

  1. What is Lua?
  2. Getting Started
  3. Identifiers, Types, and Values
  4. Variables and Expressions
  5. Operators
  6. Statements and Assignments
  7. Control Structures
  8. File I/O


Identifiers

Identifiers in Lua can be any string of letter, digits, and underscored, not beginning with a digit. This aligns with the identifier definition of most other languages. Some examples for valid identifier are sum, i, l21n, avg_marks, _mark, _MARK. However identifiers starting with an underscore followed by one or more uppercase letters should be avoided, as they are reserved for internal variables used in Lua.
The following are reserved and could not be used as identifiers in Lua:

andbreakdoelseelseif
endfalseforfunctionif
inlocalnilnotor
repeatreturnthentrueuntilwhile
Lua is case-sensitive, which means sum and SUM are two different identifiers.
Numerical constants may be written with an optional decimal part and an optional decimal exponent. Examples of valid numerical constants are 2, 3.0, 5.76, 0.576e1, 576E-2.

Types and Values

Lua is a dynamically typed language. The variables do not have a type associated with them, but the values do. The values carry their own types. The following types are the basic types in Lua:

nilRepresents the absence of a useful value. When a variable is not initialized, it is automatically set to nil in Lua. A value of nil makes a condition false.
booleanRepresents the types of true and false values. A value of false makes a condition false.
numberRepresents the real, double precision floating point, numbers.
stringRepresents an array of characters. Lua is 8 bit clean and strings may contain any 8-bit character. Strings can be delimited by double or single quotes.
functionFunctions are first class values in Lua. That means, functions can be stored in a variable, passed as argument to other functions and returned from a function.
userdataRepresents the block of raw memory. This type is provided to allow arbitrary C data to be stored in the Lua variables.
threadRepresents the independent threads of execution, used to implement the coroutines.
tableRepresents the associative arrays that can be indexed with any value, except nil. That is, you can index a table with a number or a string or any value except nil.
The type library function returns a string describing the type of a given value. The following chunk illustrates the type function:
print(type(a)) -- nil , as a is not assigned any value yet
print(type(nil)) -- nil
a=true
print(type(a)) -- boolean
a=10
print(type(a)) -- number
a="hello"
print(type(a)) -- string
print(type(print)) -– function
Reblog this post [with Zemanta]

Marcadores: , , , , , , , , , , , , , , , , , ,



 

lua - variables and expressions

Variables

There are 2 kinds of variables in Lua, global variables, and local variables.
A variable should be explicitly declared local, otherwise it is global. The local variables are lexically scoped and are accessible by the functions defined inside their scope. On the other hand, the global variable is available for use till the end of the program from the point where they are created.
The visibility rules for local and global variables can be easily understood from the example below:
x=5 -- Global Variable
do -- Start of a block 1
local x=x -- Local Variable
print (x) -- Prints 5
x=x+2 -- Modifies local x
print (x) -- Prints 7
do -- Start of block 2
local x=x+4 -- Yet another local x :)
print (x) -- prints 11
end -- End of block 2
print (x) -- Prints 7
end -- End of block 1
print (x) -- Prints 5, global variable 
Notice that we assign the value of x in the previous block to the x in the next block. This is possible because the local variables can be freely accessed by the functions defined inside their scope. The local variable used by the inner function is called an upvalue or external local variable, inside the inner function.

Expressions

Expressions yield values. It includes the numeric and string constants (literals), variables, binary & unary operations, function definitions & calls, and table constructors.
Reblog this post [with Zemanta]

Marcadores: , , , , , , , , , ,



 

lua - arithmetic operators

Arithmetic Operators

Lua provides the usual operators: the binary '+' (addition), '-' (subtraction), '*' (multiplication), '/' (division), and '^' exponentiation; and unary '-' (negation).

The operand can be numbers or strings that can be converted to numbers. All the operators except exponentiation have the usual meaning. The exponentiation operator calls the math.pow function in the standard mathematical library.

-- Arithmetic Operators
a=5
b=3
print(a+b) -- 8
print(a-b) -- 2
print(a*b) -- 15
print(a/b) -- 1.667
print(a^b) -- 125 calls the math.pow function
print(-a) -- -5

Relational Operators

The relational operators allow two values to be compared and always result in true or false values. Lua provides the following operators: '==' (equality), '~=' (inequality), '<' (less than), '>' (greater than), '<=' (less than or equal to) and '>=' (greater than or equal to).

The == and ~= operators first compares the types of the operands. It the types are different, the result of the expression is false. If the types are same, then the values of the operands are compared for numbers and strings in the usual way. However, the automatic conversion of string and number values do not apply to equality comparison, as 0 and "0" are two different types. Objects (tables, userdata, threads, and functions) are compared by reference. Two objects are equal only if they are the same object.

-- Equality Operators
a=7; b=5; c="a string"
print(a==c) -- false, as a holds a number and c a string
print(a~=c) -- false here too for the same reason
print(a==b) -- false as 7 is not equal to 5
print(a~=5) -- true as 7 is not equal to 5

The <, >, <=, >= operators work in the usual way.

Logical Operators

The logical operators in Lua are and, or and not. All logical operators consider nil and false as false, and anything else as true (in particular, the number 0 and empty string are also true).

The operator not always returns false or true.

The and operator returns its first argument if this value is false or nil, otherwise it returns its second argument. The or operator returns its first argument if this value is true, otherwise it returns its second argument. Both the and and or operators use short-cut evaluation, that is, the second argument is evaluated only if necessary. For example, consider the code below:

a=5;b=3 
print(nil and (c=a+b)) -- nil, as the first argument is nil
print(c) -- nil, as the second argument is
-- evaluated by and operator

The expression c=a+b is not evaluated as the first argument is nil. Few more expressions here would help you understand the logical operators:

-- Logical Operators
print(0 and false) -- false, as 0 yields true
print(false and 5) -- false
print(4 and nil) -- 4
print(4 or 7) -- 7
print(nil or 3) -- 3
print(false or nil) -- nil
print(false and nil) -- false
print(not false) -- true
print(not nil) -- true
print(not 56) -- false

Concatenation

Lua provides '..' as the concatenation operator to concatenate two strings. If the operands are numbers, they are automatically converted to strings.

-- Concatenation
print("Learning " .. "Lua!") -- Learning Lua!

Operator Precedence and Associativity

Precedence controls the order of evaluation of operators in an expression and associativity controls the order of evaluation of operators with same precedence level. The precedence of operators is given below, from lower to higher priority: or
and
< > <= >= ~= ==
..
+ -
* /
not – (unary)
^

The concatenation (..) and exponentiation (^) operators are right associative and rest of the operators are left associative.

Marcadores: , , , , , ,



 

lua - statements and assignments

Statements

Like many programming languages, Lua supports a conventional set of statements for assignment, control structures, function calls, variable declarations. In addition, Lua supports multiple assignments, table constructors and local declarations.

Assignment

Assignment statement allows you to give a value to a variable. Most programming languages allow single assignment as below:

a = 7

But, Lua allows multiple assignments, that is, a list of variables can be assigned with a list values in one statement. Consider the example here:

a, b, c = 1, 7, "hello"

Here a is assigned 1, b gets 7 and c gets "hello". The lists on either side of = are separated by comma. Lua evaluates all the expressions before performing assignment. For example, in

i = 3
i, a[i] = i+1, 20

20 is assigned to a[3], without affecting a[4]. This is because, the i in a[i] is evaluated before it is assigned to 4. Similarly, the statement

x, y = y, x

swaps the values of x and y.

Now, what happens if the number of values in the list is not equal to the number of variables? In that case, Lua adjusts the number of values to the number of variables. When the number of values is less than the list of variables, the list of values is extended with as many nil's as needed. Similarly, when the length of the list of values is more than the list of variables, the excess values are discarded or thrown away.

-- Multiple Assignments
a, b, c = 1, true, 5
print(a,b,c) -- 1 true 5
a, b, c = 10
print(a,b,c) -- 10 nil nil
a, b, c = 1, 2, 3, 4 -- 4 is discarded
print(a,b,c) -- 1 2 3

In Lua, a function call can return multiple values. So when a function call is placed in the list of values, the return values are adjusted depending on the position of the function call in the list.

Marcadores: , , , , , ,



 

lua - control structures

Control Structures

The control structure statements allow you to control/alter the execution of the statements based on some condition. Lua provides if for conditional and while, repeat and for for iteration/looping. The conditional expression in a control structure may return any value. nil and false makes the condition fail, any other value results in true satisfying the condition.

Condition - if then else

The if statement tests the condition and executes the then block on true or else block on false. The else block is optional. In case of nested if-else statements, elseif can be used to nest them.

-- if then else
a, b = 2, 6
if a < style="color: rgb(6, 0, 255);">then
print("a less than b")
elseif a > b then
print("a greater than b")
else
print("a equal to b")
end

Loops – while, repeat, for

The while statement allows the execution of a block of code until the condition is true.

-- while loop
i = 1
while i <= 10 do
print(i)
i = i + 1
end

The repeat statement also allows the execution of a block of code until the condition is true. But, the condition is tested after the execution of the block, so the block is always executed at least once.

-- repeat loop
i = 1
repeat
print(i)
i = i + 1
until i <= 10

The for statement has two forms: one numeric and one generic.

The numeric form has the following syntax:

for var = exp1, exp2, exp3 do block end

The loop will execute the statements in the block for each value of var from exp1 to exp2, using exp3 as the step to increment var. exp3 is optional and when absent, Lua assumes one as the step value.

-- Numeric for loop printing odd nums from 1 to 10
for i = 1, 10, 2
do
print(i)
end
-- i is not defined here, so its value is nil

In the above example, the loop control variable (i), is initialized to 1 and the loop continues till its value is less than 10. At the end of each iteration, i is incremented by 2.

One point to note here is that, the loop control variable i is a local variable and is not accessible or visible outside the for loop so there is no way to access its value outside of the loop. The value of such variables might be stored in a separate variable before exiting the for loop, if necessary.

The generic for loop allows you to traverse all values returned by an iterator function. For each iteration, it calls its iteration function to produce a new value, stopping when the new value is nil. Its general syntax is:

for  in  do  end

Where could be a list of variables (with the same scoping rules of the 'i' control loop variable mentioned above). The exp results in an iterator function, a state and an initial value for the first iterator variable.

-- Numeric Iterator
for i in io.lines("mySqr.lua")
do
print(i)
end

The io.lines is a standard library function that opens the file given as its argument and returns an iterator function that reads one line at a time from the file. The above chunk prints the mySqrt.lua program discussed earlier in this tutorial.

break and return

The break and return statements allow you to jump out from an inner block. While a return statement allows you to return results from a function, the break statement allows you to terminate a loop. break breaks the inner loop that contain it.

-- break example
i = 0
while i < 10 do
if i == 5 then break end
i = i + 1
end

For syntactic reasons, break and return can appear only as the last statement of a block. If you need to return or break in the middle, you need to enclose the break and return statement in an explicit block.

-- return example
function fun()
print("Inside fun")
print("Enter a number:")
local num = io.read()
if (tonumber(num) == 10) then
print("You have entered 10");
do return 10 end
print("This statement is not executed")
end
return num
end

Marcadores: , , , ,



 

lua - file io

Basic Input and Output

Lua provides functions for basic input and output through its standard I/O library. The I/O library provides two different styles for file manipulation with implicit and explicit file descriptors. A file descriptor is a handle that allows you to manipulate the file which it corresponds to.

Implicit Descriptors

Lua always assume a default set of file descriptors for I/O: the process's standard input for input, and the process's standard output for output. When you don't specify any file descriptors, the file operations will be performed with these standard default descriptors. As you might have seen in the earlier examples, the call to io.read() reads the data from the process's standard input, typically the keyboard.

You can change the default descriptor for I/O with the io.input() and io.output() functions. These functions take the file name as the argument and from this point any input/output will be to these respective files, until another call is made to io.input() to change the input file or io.output() to change the output file.

-- Implicit Descriptor Example
io.write("Enter a number:") -- Writes to process's std output
a = io.read() -- Reads from process's std input
print("Value of a is", a) -- Always writes to std output
io.input("mySqrt.lua") -- Change the input to mySqrt.lua
io.output("mySqrtDup.lua") -- Change the output to new file
local lineCount = 0
while true do
local line = io.read() -- Reads a line from mySqrt.lua
if (line == nil) then break end -- Jump out of loop on EOF
io.write(line) -- Write to the new file
lineCount = lineCount + 1
end
print("Number of lines copied =", lineCount)

The io.read() function reads strings from the current input file. Its argument controls what is being read:

"*all"reads the whole file
"*line"reads the next line
"*number"reads a number
numreads a string with up to num characters

The call io.read("*all") returns the whole input file from its current position. It returns an empty string if the file is empty or the current position is EOF (end of file).

The call io.read("*line") returns the next line from the file, without the newline character. It returns a nil on EOF. Lua defaults to io.read("*line") when no argument is passed to io.read(). The iterator io.lines() might also be used to read a file line by line.

The io.read("*number") returns a number from the current input file. This is the only case where read returns a number instead of a string. It returns a nil, if it cannot find a number at the current position.

Explicit Descriptors

Explicit descriptors give you the full control on I/O. The central concept in this model is the file handle which represent an open file with a current position. To open a file, you use the io.open() function, that takes the filename and open mode as its argument. The different modes are 'r' for read, 'w' for write and 'a' for append (appending 'b' to the modes, causes the file to be opened for read, write and append in binary mode).

The read and write operations are performed subsequently with the read and write functions, scoped by the file handle using the colon syntax. For example, to open a file and read all its content,

-- Explicit Descriptor/handle
f = io.open(filename, "r")
if (f ~= nil) then
local t = f:read("*all")
f:close()
else
print("Cannot not open", filename)
end

With explicit file descriptor method, you can have multiple input files and output files open simultaneously.

Marcadores: , , , ,