Escolar Documentos
Profissional Documentos
Cultura Documentos
Optimizacin de Uso de i
variables locales k
i
Buscar
Visin de conjunto
Las variables locales son muy rpidos, ya que se accede a ellos por el ndice.
"Las variables locales son muy rpidos ya que residen en los registros de la
mquina virtual, y se puede acceder directamente por el ndice. Las variables
globales, por otra parte, residen en una tabla lua y como tal se accede por una
bsqueda de hash". -- Thomas Jefferson
Las variables locales son muy rpidos, ya que se accede a ellos por el ndice. Si
es posible, hacer que las variables globales local (raro, eh?). En serio, funciona
muy bien y el acceso indexado siempre va a ser ms rpido que una bsqueda de
hash. Si una variable, por ejemplo GameState, las necesidades de alcance mundial
para acceso de C, hacer una variable secundaria que se parece a ' local GSLocal
= GameState' y use GSLocaldentro del mdulo. Esta tcnica tambin se puede
utilizar para funciones que son llamadas de forma repetitiva, tambin. p.ej.
x = {a = 1, b = 2}
la funcin foo ()
locales y = x
impresin (xa)
impresin (YB) - ms rpido que la letra anterior puesto que y es
una tabla local
fin
Tenga en cuenta, esto tambin trabajar con funciones globales (incluyendo
funciones de la librera estndar), por ejemplo.
(Steve DeKorte) Yo slo llegu a jugar con esto y funciona muy bien. Por
ejemplo, este cdigo:
i locales, v = siguiente (t, nil)
mientras que lo que hago lo, v = siguiente (t, i) final
Es 10% ms rpido si haces nextun local de:
= local al lado prximo
i locales, v = siguiente (t, nil)
mientras que lo que hago lo, v = siguiente (t, i) final
Tambin hice algunas otras pruebas y se encontr que foreach () es ~ 20% ms
rpido que el equivalente bucle while, mientras foreachi () fue ~ 20% ms lento
que un bucle while.
para i, v en t do final - aproximadamente 5 veces ms rpido que un
tiempo
Tenga en cuenta que lo que Steve est midiendo en sus pruebas de una
sobrecarga de bucle (el cuerpo del bucle est vaca). En realidad hay algunas
declaraciones provistas en el cuerpo as que la prdida no es tan significativa. -
Juan Belmonte
RecentChanges preferencias
de edicin historia
ltima edicin 28 de de octubre de, el ao 2015 21:24 GMT (dif)
w
Optimising Using Local i
Variables k
i
Search
Overview
Local variables are very quick, since they are accessed by index.
"Local variables are very fast as they reside in virtual machine registers, and are
accessed directly by index. Global variables on the other hand, reside in a lua
table and as such are accessed by a hash lookup." -- Thomas Jefferson
Local variables are very quick, since they are accessed by index. If possible,
make global variables local (weird, eh?). Seriously, it works great and indexed
access is always going to be faster than a hash lookup. If a variable,
say GameState, needs global scope for access from C, make a secondary variable
that looks like 'local GSLocal = GameState' and use GSLocal within the module.
This technique can also be used for functions that are called repetitively, too. eg.
x = { a=1,b=2 }
function foo()
local y=x
print( x.a )
print( y.b ) -- faster than the print above since y is a local
table
end
Note, this will also work with global functions (including standard library
functions), eg.
(Steve Dekorte) I just got around to playing with this and it works great. For
example this code:
local i, v = next(t, nil)
while i do i, v = next(t, i) end
Is 10% faster if you make next a local:
local next = next
local i, v = next(t, nil)
while i do i, v = next(t, i) end
I also did some other tests and found that foreach() is ~20% faster than the
equivalent while loop, while foreachi() was ~20% slower than a while loop.
for i, v in t do end -- about 5x as fast as a while
Keep in mind that what Steve is measuring in his tests is loop overhead (the loop
body is empty). In reality there are some statments in the body so the overhead is
not so significant. -- John Belmonte
RecentChanges preferences
edit history
Last edited October 28, 2015 9:24 pm GMT (diff)
Introduction
Garbage collection of your system can cause performance problems if a large
number of objects have been generated. This page discusses the issues involved
and ideas for avoiding the problem.
(ET) No. Local variables are kept on a stack and will not affect the GC. These
constructs will create a new garbage collected object:
a..b (example only; any string generating construct i.e. strsub() [*1]
or lua_pushstring().)
Each new string creates a new object. Lua has unique strings, that means
that each possible string exists only once within Lua. If a new string
occurs Lua first checks if it already exists within the string pool. If it does,
a reference to that older string is used. If it does not exist, a new string
object is created and put into the string pool. The GC checks the string
pool for unused strings and frees them. So creating a lot of unique strings
will trash the GC. I.e. this is bad GC-wise:
for i=1,100 do x="foo"..tostring(i) end -- 100 new strings
Note: Code segments hold references to strings constants (a la "foo"
above). So the string will exist in the string pool as long as the function
exists; it does not have to be created each time the function is executed.
{ ... }
Each time a table constructor is executed a new table is created. Try to
reuse tables if possible. You could even go as far as creating and using
newtable/freetable functions that manage a pool of unused tables. That
way you get old style memory management for tables but you'll also get
the old problems too ;-)
Vararg functions create a table for the ellipsis (stored in ' arg') each time the
function is called. (Note: No longer true as of Lua 5.2, or if using LuaJIT.)
userdata objects
In Lua 4.0 (and 3.x) userdata objects are handled similar to strings. They
are equal if the pointer value and the tag are equal. What about Lua5?
dofile/dostring
Well, these load/compile new code and will create strings and (GCed)
code segments.
Variables are a place to store objects (In fact, except for numbers it only holds
pointers to the objects). Whether the stored object is a number or a table or
anything else doesn't bother the variable. And local variables are not garbage
collected objects themselves. So you may use them without creating intermediate
objects. I think, that was what the original poster meant.
"So you may use them without creating intermediate objects." Does this
need clarification? The variable itself doesnt create a GC object but its
value could. You can use local variables which reference other existing
objects without creating objects that need to be collected. But, you can't
create new objects which are locals without creating an object that needs
to be collected later.
About the objects stored within local variables: at the moment the local variable
is no longer active the GC may collect the object that was stored there. The actual
freeing of the object has nothing to do with function scopes or variable live
times. The GC runs at certain times and frees all objects that are no longer
accessible by any L
RecentChanges preferences
edit history
Last edited April 18, 2014 6:12 pm GMT (diff)
Introduccin
La recoleccin de basura de su sistema puede causar problemas de rendimiento si
se han generado un gran nmero de objetos. Esta pgina discute las cuestiones
planteadas y las ideas para evitar el problema.
{ ... }
Funciones vararg crear una mesa para los puntos suspensivos (almacenado
en ' arg') cada vez que la funcin se llama . (Nota: Ya no son ciertas en
Lua 5.2, o si est usando LuaJIT.)
objetos userdata
En Lua 4.0 (3.x) objetos userdata se manejan similares a cuerdas. Ellos
son iguales si el valor del puntero y la etiqueta son iguales. Qu hay de
Lua5?
dofile/dostring
Las variables son un lugar para guardar objetos (De hecho, a excepcin de los
nmeros que slo se mantiene punteros a los objetos). Si el objeto almacenado es
un nmero o una mesa o cualquier otra cosa no molesta a la variable. Y las
variables locales no son basura y posteriormente objetos mismos. Por lo que
puede utilizarlos sin crear objetos intermedios. Creo, eso era lo que quera decir
el cartel original.
"Por lo que puede usarlos sin crear objetos intermedios." Esto necesita
una aclaracin? La variable si misma no crear un objeto de GC pero su
valor poda. Puede utilizar variables locales que hacen referencia a otros
objetos existentes sin crear objetos que necesitan ser recogidos. Sin
embargo, no se puede crear nuevos objetos que son locales sin crear un
objeto que necesita ser recogido ms tarde.
Acerca de los objetos que contiene las variables locales: en el momento en que la
variable local ya no est activa la GC puede recoger el objeto que se almacena
all. La liberacin real del objeto no tiene nada que ver con los mbitos de
funcin o tiempos en vivo variables. El GC se ejecuta en ciertos momentos y
libera todos los objetos que ya no estn a disposicin de cualquier L
RecentChanges preferencias
de edicin historia
ltima edicin 18 de de abril de, 2014 18:12 GMT (dif)
w
Vararg The Second Class i
Citizen k
i
Search
Lua varargs "..." [1] are not [first class] objects in Lua 5.1, and this leads to
some limitations in expression. Some of these issues and their workarounds are
given here.
You might want to use such a function to temporarily store away the return
values of a function call, do some other work, and then retrieve those stored
return values again. The following function would use this
hypothetical tuple function to add trace statements around a given function:
--Wraps a function with trace statements.
function trace(f)
return function(...)
print("begin", f)
local result = tuple(f(...))
print("end", f)
return result()
end
end
You could instead implement trace with the table construct {...} and unpack:
--Wraps a function with trace statements.
function trace(f)
return function(...)
print("begin", f)
local result = {f(...)}
print("end", f)
return unpack(result)
end
end
The following approach swaps the nil's with placeholders that can be stored in
tables. It's probably less optimal here, but the approach might be usable
elsewhere.
local NIL = {} -- placeholder value for nil, storable in table.
function pack2(...)
local n = select('#', ...)
local t = {}
for i = 1,n do
local v = select(i, ...)
t[i] = (v == nil) and NIL or v
end
return t
end
function unpack2(t, k, n)
k = k or 1
n = n or #t
if k > n then return end
local v = t[k]
if v == NIL then v = nil end
return v, unpack2(t, k + 1, n)
end
As a good side effect, now unpack2 can operate on range of indexes [k, n] instead
of whole table. If you don't specify the range, whole table is unpacked.--Sergey
Rozhenko, 2009, Lua 5.1
The CPS approach was also used in the RiciLake's string split function
(LuaList:2006-12/msg00414.html).
build_constructor = Memoize(build_constructor)
The code building/memoization technique and the above Memoize function are
based on some previous related examples by RiciLake such as [Re: The Curry
Challenge].
Note also that if your wrapped function raises exceptions, you would want
to pcall as well (LuaList:2007-02/msg00165.html).
The following approach is purely functional (no tables) and avoids code
generation. It's not necessarily the most efficient as it creates a function per tuple
element.
function helper(n, first, ...)
if n == 1 then
return function() return first end
else
local rest = helper(n-1, ...)
return function() return first, rest() end
end
end
function tuple(...)
local n = select('#', ...)
return (n == 0) and function() end or helper(n, ...)
end
-- TEST
local function join(...)
local t = {n=select('#', ...), ...}
for i=1,t.n do t[i] = tostring(t[i]) end
return table.concat(t, ",")
end
local t = tuple()
assert(join(t()) == "")
t = tuple(2,3,nil,4,nil)
assert(join(t()) == "2,3,nil,4,nil")
print "done"
Solution: Coroutines
It is not necessary to create a new coroutine on each call. The following approach
is rather efficient, and the recursion uses a tail call:
local yield = coroutine.yield
local resume = coroutine.resume
local function helper(...)
yield(); return helper(yield(...))
end
local function make_stack() return coroutine.create(helper) end
-- Example
local stack = make_stack()
local function trace(f)
return function(...)
print("begin", f)
resume(stack, f(...))
print("end", f)
return select(2, resume(stack))
end
end
Solution: Upvalues in C Closure
Benchmarks
The speeds of the above solutions are compared in the following benchmark.
-- Avoid global table accesses in benchmark.
local time = os.time
local unpack = unpack
local select = select
do -- This is a base-line.
local function trace(f)
return function(...) return f(...) end
end
local f = trace(function() return 11,12,13,14,15 end)
print_bench("(control)", duration, nbase, ntrials, f, 1,2,3,4,5)
end
do
local function trace(f)
local function helper(...)
return ...
end
return function(...)
return helper(f(...))
end
end
local f = trace(function() return 11,12,13,14,15 end)
print_bench("CPS", duration, nbase, ntrials, f, 1,2,3,4,5)
end
do
local yield = coroutine.yield
local resume = coroutine.resume
local function helper(...)
yield(); return helper(yield(...))
end
local function make_stack() return coroutine.create(helper) end
local stack = make_stack()
local function trace(f)
return function(...)
resume(stack, f(...))
return select(2, resume(stack))
end
end
local f = trace(function() return 11,12,13,14,15 end)
print_bench("Coroutine", duration, nbase, ntrials, f, 1,2,3,4,5)
end
do
local function trace(f)
return function(...)
local t = {f(...)}
return unpack(t)
end
end
local f = trace(function() return 11,12,13,14,15 end)
print_bench("{...} and unpack", duration, nbase, ntrials, f,
1,2,3,4,5)
end
do
local function trace(f)
return function(...)
local n = select('#', ...)
local t = {f(...)}
return unpack(t, 1, n)
end
end
local f = trace(function() return 11,12,13,14,15 end)
print_bench("{...} and unpack with n", duration, nbase, ntrials,
f, 1,2,3,4,5)
end
do
local NIL = {}
local function pack2(...)
local n = select('#', ...)
local t = {...}
for i=1,n do
local v = t[i]
if t[i] == nil then t[i] = NIL end
end
return t
end
local function unpack2(t)
local n = #t
for i=1,n do
local v = t[i]
if t[i] == NIL then t[i] = nil end
end
return unpack(t, 1, n)
end
local function trace(f)
return function(...)
local t = pack2(f(...))
return unpack2(t)
end
end
local f = trace(function() return 11,12,13,14,15 end)
print_bench("nil Placeholder", duration, nbase, ntrials,
f, 1,2,3,4,5)
end
do
-- This is a simplified version of Code Generation for
comparison.
local function tuple(a1,a2,a3,a4,a5)
return function() return a1,a2,a3,a4,a5 end
end
local function trace(f)
return function(...)
local t = tuple(f(...))
return t()
end
end
local f = trace(function() return 11,12,13,14,15 end)
print_bench("Closure", duration, nbase, ntrials, f, 1,2,3,4,5)
end
do
local function build_constructor(n)
local t = {}; for i = 1,n do t[i] = "a" .. i end
local arglist = table.concat(t, ',')
local src = "return function(" .. arglist ..
") return function() return " .. arglist .. " end
end"
return assert(loadstring(src))()
end
local cache = {}
local function tuple(...)
local n = select('#', ...)
local construct = cache[n]
if not construct then
construct = build_constructor(n)
cache[n] = construct
end
return construct(...)
end
local function trace(f)
return function(...)
local t = tuple(f(...))
return t()
end
end
local f = trace(function() return 11,12,13,14,15 end)
print_bench("Code Generation", duration, nbase, ntrials,
f, 1,2,3,4,5)
end
do
local function helper(n, first, ...)
if n == 1 then
return function() return first end
else
local rest = helper(n-1, ...)
return function() return first, rest() end
end
end
local function tuple(...)
local n = select('#', ...)
return (n == 0) and function() end or helper(n, ...)
end
local function trace(f)
return function(...)
local t = tuple(f(...))
return t()
end
end
local f = trace(function() return 11,12,13,14,15 end)
print_bench("Functional, Recursive", duration, nbase, ntrials,
f, 1,2,3,4,5)
end
print "done"
end
test_suite(10, 1000000, 3)
test_suite(10, 1000000, 1) -- recheck
Results:
(Pentium4/3GHz)
name, t, t, t (times in sec)
(control): 3.8e-007 3.8e-007 4.0e-007
CPS: 5.6e-007 6.3e-007 5.9e-007
Coroutine: 1.7e-006 1.7e-006 1.7e-006
{...} and unpack: 2.2e-006 2.2e-006 2.4e-006
{...} and unpack with n: 2.5e-006 2.5e-006 2.5e-006
nil Placeholder: 5.0e-006 4.7e-006 4.7e-006
Closure: 5.0e-006 5.0e-006 5.0e-006
Code Generation: 5.5e-006 5.5e-006 5.5e-006
Functional, Recursive: 1.3e-005 1.3e-005 1.3e-005
done
The CPS is the fastest, followed by coroutines (both operated on the stack).
Tables take a bit more time than the coroutine approach, though coroutines could
be even faster if we didn't have the the select on the resume. Use of closures are
a few times slower still (including when generalized with code generation) to an
order of magnitude slower (if generalized with Functional, Recursive).
Notice that the times for table construction methods differ relatively little with
respect to tuple size (due to the initial overhead of constructing a table). In
contrast, use of closures entails run times that vary more significantly with tuple
size.
Issue #2: Combining Lists
Problem: given two variable length lists (e.g. the return values of two
functions, f and g, that each return multiple values), combine them into a single
list.
This can be a problem because of the behavior of Lua to discard all but the first
return value of a function unless it is the last item in a list:
local function f() return 1,2,3 end
local function g() return 4,5,6 end
print(f(), g()) -- prints 1 4 5 6
Besides the obvious solutions of converting the lists into objects such as tables
(via the methods in Issue #1 above), there are ways to do this with only function
calls.
Solution
-- TEST
local function join(...)
local t = {n=select('#', ...), ...}
for i=1,t.n do t[i] = tostring(t[i]) end
return table.concat(t, ",")
end
local function f0() return end
local function f1() return 1 end
local function g1() return 2 end
local function f3() return 1,2,3 end
local function g3() return 4,5,6 end
assert(join(combine(f0, f0())) == "")
assert(join(combine(f0, f1())) == "1")
assert(join(combine(f1, f0())) == "1")
assert(join(combine(g1, f1())) == "1,2")
assert(join(combine(g3, f3())) == "1,2,3,4,5,6")
print "done"
Issue #3: Selecting the First N Elements in List
Problem: Return a list consisting of the first N elements in another list.
The select function allows selecting the last N elements in a list, but there is no
built-in function for selecting the first N elements.
Solution
local function helper(n, a, ...)
if n == 0 then return end
return a, helper(n-1, ...)
end
local function first(k, ...)
local n = select('#', ...)
return helper(k, ...)
end
-- TEST
local function join(...)
local t = {n=select('#', ...), ...}
for i=1,t.n do t[i] = tostring(t[i]) end
return table.concat(t, ",")
end
local function f0() return end
local function f1() return 1 end
local function f8() return 1,2,3,4,5,6,7,8 end
assert(join(first(0, f0())) == "")
assert(join(first(0, f1())) == "")
assert(join(first(1, f1())) == "1")
assert(join(first(0, f8())) == "")
assert(join(first(1, f8())) == "1")
assert(join(first(2, f8())) == "1,2")
assert(join(first(8, f8())) == "1,2,3,4,5,6,7,8")
print "done"
Solution
local function helper(n, a, ...)
if n > 0 then return append(a, helper(n-1, ...)) end
end
local function reverse(...)
return helper(select('#', ...), ...)
end
Solution
local function helper(f, n, a, ...)
if n > 0 then return f(a), helper(f, n-1, ...) end
end
local function map(f, ...)
return helper(f, select('#', ...), ...)
end
Solution
for n=1,select('#',...) do
local e = select(n,...)
end
If you do not need nil elements, you can also use the following:
for _, e in ipairs({...}) do
-- something with e
end
If you wish to use an iterator function without creating a garbage table every
time, you can use the following:
do
local i, t, l = 0, {}
local function iter(...)
i = i + 1
if i > l then return end
return i, t[i]
end
function vararg(...)
i = 0
l = select("#", ...)
for n = 1, l do
t[n] = select(n, ...)
end
for n = l+1, #t do
t[n] = nil
end
return iter
end
end
for i, v in vararg(1, "a", false, nil) do print(i, v) end -- test
-- Output:
-- 1 1
-- 2 "a"
-- 3 false
-- 4 nil
Other Comments
w
Vararg El ciudadano de i
segunda clase k
i
Buscar
Lua varargs " ..." [1] no son [de primera clase] objetos en Lua 5.1, y esto lleva a
algunas limitaciones en la expresin. Algunos de estos problemas y sus
soluciones se dan aqu.
Es posible que desee utilizar una funcin para almacenar temporalmente los
valores de retorno de distancia de una llamada de funcin, hacer algn otro
trabajo, y luego recuperar los valores de retorno almacenados de nuevo. La
siguiente funcin utilizara esta hipottica tuplefuncin para aadir instrucciones
de seguimiento en torno a una funcin determinada:
--Wraps Una funcin con instrucciones de seguimiento.
la funcin trace (f)
de retorno de funcin (...)
de impresin ( "iniciar" , f)
local, resultado = tupla (f (...))
de impresin ( "fin" , f)
de retorno resultado ()
final
final
Las tablas pueden ser evitados si utilizamos el estilo Continuacin paso (CPS)
( [Wikipedia] ) de la siguiente manera. Podramos esperar que esto sea un poco
ms eficiente.
la funcin trace (f)
locales ayudante = funcin (...)
de impresin ( "fin" , f)
de retorno ...
finales
de retorno de funcin (...)
de impresin ( "iniciar" , f)
de retorno auxiliar (f (... ))
final
final
- PRUEBA
local de la funcin join ( ...)
locales t = {n = seleccionar ( '#' , ...), ...}
para i = 1, tn hacer t [i] = toString (t [i]) extremo
de retorno table.concat ( t, "" )
terminar
locales t = tupla ()
afirman (join (t ()) == "" )
t = tupla (2,3, nula , 4, nil )
afirman (join (t ()) == "2,3, nil, 4, nulo" )
print "hecho"
Solucin: corrutinas
- Ejemplo
local de pila = make_stack ()
local de la funcin trace (f)
de retorno de funcin (...)
de impresin ( "begin " , f)
curriculum vitae (pila, f (...)) de impresin ( " fin " , f)
volver selecto (2, curriculum vitae (pila))
final final
Las tuplas pueden ser implementadas en C como un cierre que contiene los
elementos de tupla como upvalues. Esto se demuestra en la Seccin 27.3 de la
programacin en Lua, 2 Ed [2] .
Tenga en cuenta que los tiempos de los mtodos de construccin de mesa difieren
relativamente poco con respecto al tamao tupla (debido a la sobrecarga inicial
de la construccin de una mesa). En contraste, el uso de cierres implica tiempos
que varan ms significativamente con el tamao tupla ejecutar.
Solucin
- PRUEBA
local de la funcin join (...)
locales t = {n = seleccionar ( '#' ,. ..), ...}
para i = 1, tn do t [i] = toString (t [i]) extremo
de retorno table.concat (t, "" )
terminar
local de la funcin f0 () de retorno termino
local de la funcin f1 () de retorno 1 extremo
local de la funcin g1 () de retorno 2 extremo
local de la funcin F3 () volver 1,2,3 extremo
local de la funcin g3 () volver 4,5,6 final
asercin (join (combinar (f0, f0 ())) == "" )
afirman (join (combinar (f0, f1 ())) == "1" )
afirman (join (combinar (f1, f0 ())) == "1" )
afirman (join (cosechadora (G1 , f1 ())) == "1,2" )
afirman (join (combinar (g3, f3 ())) == "1,2,3,4,5,6" )
print "hecho"
Solucin
local de la funcin auxiliar (n, a, ...)
si n == 0 y luego volver extremo
de regreso a, ayudante de (n-1, ...)
terminar
local de la funcin primero (k, ...)
locales n = seleccionar ( ' # ' , ...)
de retorno auxiliar (k, ...)
final
- PRUEBA
local de la funcin join (...)
locales t = {n = seleccionar ( ' # ' , ...), ...}
de i = 1, tn do t [i] = toString (t [i]) extremo
de retorno table.concat (t, "" )
terminar
local de la funcin f0 () de retorno terminar
local de la funcin f1 () de retorno 1 extremo
local de la funcin f8 ( ) volver 1,2,3,4,5,6,7,8 final
asercin (join (primero (0, f0 ())) == "" )
afirman (join (primero (0, f 1 ())) = = "" )
valer (join (primero (1, f1 ())) == "1" )
afirman (join (primero (0, f8 ())) == "" )
afirman (join (primero (1, f8 ())) == "1" )
valer (join (primero (2, f8 ())) == "1,2" )
afirman (join (primero (8, f8 ())) == "1,2 , 3,4,5,6,7,8 " )
print " hecho "
Tenga en cuenta que anteponiendo un elemento a una lista es simple: {a, ...}
Solucin
local de la funcin auxiliar (a, n, b, ...)
si n == 0 y luego regresar una
persona de retorno b, ayudante (a, n-1, ...) extremo
final
local de la funcin de agregacin (a, ...)
retorno ayudante (a, seleccione ( '#' , ...), ...)
final
Solucin
local de la funcin auxiliar (n, a, ...)
si n> 0 entonces volver append (a, ayudante de (n-1, ...)) final
final
local de la funcin inversa (...)
de retorno auxiliar ( seleccionar ( '# ' , ...), ...)
final
Solucin
local de la funcin auxiliar (f, n, a, ...)
si n> 0 entonces volver f (a), el ayudante (f, n-1, ...) extremo
final
local de la funcin de mapa (f, ...)
de retorno helper (f, seleccione ( '#' , ...), ...)
final
Solucin
local de la funcin auxiliar (f, n, a, ...)
si n> 0 entonces
si f (a) a continuacin, volver a, helper (f, n-1, ...)
ms retorno helper (f, n-1, ...) extremo
final
terminar
local de la funcin grep (f, ...)
de retorno auxiliar (f, seleccione ( '#' , ...), ...)
final
Solucin
para n = 1, seleccione ( '#' , ...) hacer
locales e = selecciona (n, ...)
final
Si usted no necesita elementos nulos, tambin se puede utilizar lo siguiente:
para _, e en ipairs ({...}) hacen
- algo con e
fin
Si desea utilizar una funcin de iterador sin crear una mesa de basura cada vez,
puede utilizar lo siguiente:
hacer
local, i, t, l = 0, {}
local de la funcin iter (...)
i = i + 1 si i> l y luego vuelva finales de retorno i, t [i]
finales funcin vararg (...)
i = 0
l = select ( "#" , ...)
para n = 1, l do
t [n] = seleccionar (n, ...)
final para n = l + 1, #t hacen
t [n] = nil final volver iter
extremo final de i, v en vararg (1, "a" , falsa , nil ) no
impresin (i, v) final - prueba - salida: - 1 1 - 2 "a" - 3 falsa - 4
nil
Otros comentarios
(ninguna)
Tutorial ediscrip
fin
Qu aprendemos de esto?
algo de instruccin
fin
En nuestro ejemplo, la funcin es una funcin estndar de
Lua, llamado "on.paint". Usted lo ver en la mayora (si no
todos) los scripts Lua se mire, y se entrega con claridad lo
que promete: "en" ejecutar esta funcin, el contenido se
"pint" a la pantalla.
2. En la segunda parte de
esta leccin, aprender a
controlar el tamao de
letra, color y estilo, y
cmo fcilmente el texto
en una lnea de centro o,
de hecho, en el centro de
la ventana. En Lua
tenemos un control
significativo sobre la
forma de visualizacin
de nuestro texto - mucho
ms que para las
instalaciones de texto
usando las TI-Nspire
nativas. En trminos de
color, usted tiene acceso
inmediato a millones de
colores, y el tamao es
igualmente sin
restricciones. Tmese un
momento para ver el
vdeo de demostracin
corta a la derecha,
"Deducir la frmula
cuadrtica". Se ilustra
algunas de las
posibilidades de
utilizacin de Lua.
fin
Una vez ms, el estudio de estos nuevos comandos y ver lo que hacen -
tienen un juego y probar diferentes valores. Rpidamente se apreciar
que setFont lleva tres entradas (familia ( "serif" o "sanserif"), estilo ( "b"
para negrita, "r" para regular, "i" para cursiva o "bi" para negrita itlica)
y , por supuesto, el tamao).
Si usted todava est con nosotros, entonces usted est haciendo muy
bien en sus primeros pasos con Lua. Vamos a terminar esta primera
leccin por aprender a centrar ese texto, y al hacerlo, introducir la idea
importante de variables locales y globales. En este caso, nos enteramos
de que Lua suministra todo tipo de comandos tiles, tales
como platform.window: altura () y platform.window: Ancho () . Como el
nombre sugiere, estos comandos se pueden utilizar para entregar a
usted los valores para la ventana actual. Si definimos estos como
variables, como w y h, entonces podemos hacer algunos clculos
simples para determinar el mejor lugar para poner nuestro texto! Vamos
a definir estas variables como local, pero colocndolos fuera de
cualquier funcin, estn a disposicin de todo el guin. Note que incluso
podemos definir un nombre de variable, como "pantalla" para
reemplazar el "platform.window" ms voluminosos? Tiene ms sentido
para m ...
local de la pantalla
= platform.window
local de h = pantalla: altura () Haga clic en cualquier lugar de esta imagen para un vdeo de
demostracin
local de la pantalla w =: Ancho
()
funcin on.paint (GC)
fin
Ahora que?
The focus here will be on using Lua initially to display text. Dynamic
graphs and images will follow later.
function on.paint(gc)
end
The indenting of the second line is optional, but often helpful when
working with longer scripts. The case of the text is NOT optional - Lua is
a case-sensitive language and you must enter all commands exactly as
shown here. So everything in this example is in lower case, except the
"S" in "drawString".
While most of the Lua scripts that you will see in the wild look
enormously complicated (and, in fact, they can be and usually are!) a
successful Lua script can be as simple as this!
function name(argument)
some instruction
end
In our example, the function is a standard Lua function,
called "on.paint". You will see it in most (if not all) Lua scripts
you look at, and it clearly delivers what it promises: "on"
running this function, the contents are "painted" to the
screen.
The coordinate system begins from the top left corner as the
origin. So this text will begin at the left side of the window
and 20 units down (yes, an x-y coordinate system just like
we are used to, only the top of the screen is 0 and you count
up to go down!)
You should now take a few moments and play! Change the text, and
change the x and y coordinates. Try to place the text in the center of the
window - what does this teach you about the window dimensions? If you
are on the software, switch between Computer and HandHeld views -
you will see that, centering for one does NOT center for the other!
But Why?
It is perhaps timely to stop for a moment and ask - Why bother? There
are much easier ways to put text on a screen.
function on.paint(gc)
gc:setColorRGB(158, 5, 8)
end
Once again, study these new commands and see what they do - have a
play and try different values. You will quickly appreciate
that setFont takes three inputs (family ("serif" or "sanserif"), style ("b"
for bold, "r" for regular, "i" for italic, or "bi" for bold italic) and, of course,
size).
If you are still with us, then you are doing very well in your first steps
with Lua. We will finish this first lesson by learning how to center that
text, and in doing so introduce the important idea of local and global
variables. In this case, we learn that Lua supplies all sort of useful
commands, such
as platform.window:height() and platform.window:width(). As the names
suggest, these commands may be used to deliver to you the values for
the current window. If we define these as variables, like w and h, then we
can do some simple calculations to determine the best place to put our
text! We will define these variables as local, but by placing them outside
any functions, they are available to the entire script. Notice we can even
define a variable name, like "screen" to replace the more bulky
"platform.window"? Makes more sense to me...
local h=screen:height()
Click anywhere on this image for a video demonstration
local w=screen:width()
function on.paint(gc)
gc:setColorRGB(158, 5, 8)
local sw
= gc:getStringWidth("This is
my text")
local sh
= gc:getStringHeight("This is
my text")
gc:drawString("This is my text",
w/2 - sw/2, h/2 + sh/2)
end
What Now?
Why not try to align your text to the right? Have a look at the centering
that was just done and think about how that approach might be used for
left and right alignment.
How about placing your text at the top of the page - or down the
bottom?
In the next lesson, we learn how to make this text start to come alive,
and how to use a table to organize multiple lines of text nicely laid out
on your page!
ms
negcolour = CLR
fin
Reiniciar()
platform.window: invalidar ( )
fin
menu = {
{ "Color positivo:",
},
{ "Color Negativo:",
},
}
toolpalette.register ( men)
Color = {
menu = {
{ "monedas",
},
{"Acerca de",
},
}
toolpalette.register ( men)
menu = {
{"Modo",
},
{"Reiniciar",
},
{"Acerca de",
toolpalette.register ( men)
Vamos a ver cmo las lneas de unos pocos local de la pantalla w =: anchura ()
que se necesita para obtener un cuadro de
local de h = pantalla: altura ()
texto en la pgina de funcionamiento. Nada
del otro mundo - que vendr un poco ms locales TBox = D2Editor.newRichText ()
tarde. Una cosa que usted notar que parece
bastante extrao en este punto es que en
realidad podemos conseguir cosas en nuestra
pgina - y funcional - sin ningn signo de funcin on.resize ()
una funcin de "on.paint"! Asombroso!
w = pantalla: anchura ()
En la parte superior de nuestro script - y de
todos nuestros scripts de ahora en adelante! - h = pantalla: altura ()
Es la APIlevel. Si la secuencia de comandos
utiliza OS 3.2 funcionalidad (como
on.construction), entonces se define como
TBox: move ( 0.05 * w, 0.05 * h)
platform.apilevel = "2.0". Guiones anteriores
fueron el nivel "1.0". Documentos que
incluyen por ejemplo la nueva
funcionalidad no se abrirn en versiones
anteriores a la 3.2. Nota bien: si el guin es
el nivel 2.0 a continuacin, los estudiantes
con un sistema operativo anterior incluso no
ser capaz de abrir el documento!
Estudiar el cdigo -
especialmente
el on.timer funcin. Pu
edes ver que todo lo que
tenemos que hacer es
aadir la
lnea TextBox2:
setExpression
(entrada) despus de
que nos hemos
asegurado de que
realmente existe de
entrada? (Tenga en
cuenta que los
trminos getText y getE
xpression ,
y setText y setExpressi
on se consideran
intercambiables)
As que ahora
reemplazar esta lnea
con: TextBox2:
setExpression ( "\\
1keyword" ..Input) y
ver qu pasa. El
comando "\\
1keyword" es uno de
los pocos comandos
interesantes disponibles
para jugar aqu - como
se ve, el efecto es tomar
la siguiente palabra y
para que sea negrita .
Una palabra de
precaucin al utilizar
estos comandos estilo
de texto: no hay
ninguna garanta de que
no va a cambiar en
futuras actualizaciones
del sistema
operativo! As que tal
vez evitar el uso de ellos
en nada crtico, ya que
puede no funcionar
como se espera en el
futuro.
El crdito por el
descubrimiento de estos
comandos no
documentados
maravillosos va al
equipo de Inspired-
Lua . Muchas gracias a
Jeremy y Adrien de
todos sus esfuerzos
para ayudar a aquellos
de nosotros aprender a
hacer el mejor uso de
Lua en la TI-Nspire!
En el ejemplo que he creado, he tomado de entrada = entrada: gsub ( "segmento", "\\ 1lineseg")
secuencias de comandos HTML, por lo que
este tipo de comandos especiales se definen entrada = entrada: gsub ( "RTRI:", "\\ 1rtri")
de una manera particular (en este caso,
seguido de dos puntos). Cuando descubrieron entrada = entrada: gsub ( "vector", "\\ 1vector")
que llevan a cabo su funcin definida, ya sea
insertando un smbolo (crculo, tringulo) o entrada = entrada: gsub ( "u", "\\ 1title")
la creacin de la notacin especial para
entrada = entrada: gsub ( "b", "\\ 1keyword")
rayos, o lnea, o la mejora de la siguiente
palabra. Copiar y pegar la funcin en su
entrada = entrada: gsub ( "sup", "\\ 1supersc")
pgina, y luego simplemente hacer un
cambio a la lnea que ha introducido entrada = entrada: gsub ( "sub", "\\ 1subscrp")
previamente en la funcin de
temporizador: TextBox2: setText (bastante) entrada = entrada: gsub ( "i", "\\ 1subhead")
(entrada) . Luego probar sus nuevos talentos
de copiar y pegar el siguiente texto en
TextBox 1:
regresar de entrada
u: Subrayado se pueden mezclar con b:
negrita, i: cursiva y sup: superndice con fin
substitucin: subndice. b: los smbolos de
la geometra del tringulo incluyen: ABC,
crculo: P, RTRI: ABC, lnea lnea: AB,
segmento segmento: AB y Ray Ray: AB y
el vector vector: ABC.
Volver arriba
Afterthoughts
Pero sigue siendo un par de cosas que me gustara cubrir aqu que no
subiese o no fueron adecuadamente cubierto en las lecciones 1 - 15, por
lo que colgar en l slo un poco ms de tiempo.
Encontrar
Si quieres saber si una cadena contiene una subcadena, y donde la
subcadena es, a continuacin, utilizar encontrar . Se devuelve dos
nmeros, de inicio y fin, ndices de inicio y final de la primera
coincidencia. Devuelve nil si la subcadena no est contenida en la
cadena. El mtodo de bsqueda tiene un patrn de capacidad de
adaptacin verstil que es posible que desee comprobar hacia fuera. Por
ejemplo str: encontrar ( "% b ()") devuelve el comienzo y el final de
los ndices del primer conjunto de parntesis equilibrados que
encuentra.
Reemplazar
Si desea reemplazar la subcadena por otra cadena, usar algo como:
= cadena-nueva oldstring: gsub ( "=", "->")
Esto devuelve una nueva cadena con todas las ocurrencias de "="
sustituye con "->". Si desea slo la primera aparicin para ser sustituido,
llame oldstring: gsub ( "=", "->", 1). Si no se encuentra ninguna
ocurrencia de la subcadena, la cadena de entrada original se devuelve
sin cambios. El mtodo gsub utiliza el mismo patrn de coincidencia
instalacin como hallazgo.
Estudiar la funcin que sigue y ver lo que logra cada lnea - esto sera
convertir una cuadrtica como "-1x ^ 2 + + -0x -4" en "-x 2 -4". (Para
una funcin Bastante ms completa, descargar y estudiar cualquiera de
los documentos adjuntos, pretty.tns o pretty.lua)
funcin bastante (entrada) Haga clic en cualquier lugar de esta imagen para un
vdeo de demostracin
entrada = toString ( entrada)
regresar de entrada
fin
Divisin
Si desea dividir una cadena en las partes antes y despus del signo
igual, usar algo como:
Volver arriba
NOTA: A pesar de que debe volver a introducir imgenes cada vez que
se requieren para un nuevo guin / pgina, slo una nica copia de esa
imagen se almacena dentro del documento! Esto reduce el tamao
general del documento de manera significativa en comparacin con el
mtodo anterior, donde se repitieron las cadenas largas de la imagen en
cada secuencia de comandos. Tan comnmente utilizados repetidas
imgenes (imgenes de los botones, por ejemplo) deben volver a
introducir en la ficha Recursos cada vez que se usan, sino que se
almacenan slo una vez en un documento.
fin
Esto es grande si nuestra imagen se ajusta razonablemente bien a la ventana. Pero lo que si es demasiado gran
El mtodo ms simple aqu es obligar a la imagen para que quepa dentro de sus dimensiones de la pantalla: he
fcilmente en este espacio: image = Imagen : copia (w, h) crear una copia de la imagen que se ajuste exacta
Observamos que hacemos esto dentro de la escala on.resize funcin, en lugar de la on.paint funcin. La funci
cambio de tamao se llama una vez cuando la pgina est configurado, y solo cuando cambia de tamao (que
imagen puede tener un impacto en el rendimiento, especialmente en la computadora de mano y de imgenes d
Hasta aqu todo bien. Usted podra parar aqu y ser capaz de insertar una imagen y jugar con la escala hasta qu
La definicin de las variables utilizadas en general (variables "globales") como local para el guin es realment
carga el guin.
La funcin de cambio de tamao tambin se denomina generalmente slo una vez, por lo que este es un buen l
como un restablecimiento funcin). Si las dimensiones de la imagen son diferentes de las de la pantalla, esto p
pantalla, y la altura de la imagen como la mitad de la altura de la pantalla.
A continuacin, defina una funcin "Cambiar la escala", que se puede llamar como sea necesario. Se define un
que esta funcin toma como argumentos la imagen que se reajustarn, y el valor actual de la escala. Tambin i
Observe, tambin, que nuestra funcin "reescalar" incluye una pantalla: invalidar () de comandos, as que e
Este script va a funcionar bien en la unidad TI-Nspire, y en el software de escritorio, pero qu pasa con el iPa
Una solucin sencilla es aadir un control deslizante, y utilizar esta variable para cambiar nuestra escala.
Para aadir esta caracterstica, tenemos que hacer dos cambios en nuestra secuencia de comandos:
1. Tenemos que "escuchar" a los cambios en la variable de control deslizante (que llamaremos "escala").
2. Tenemos que enviar nuestras flechas cambios clave para el control deslizante.
Para detectar un cambio en una variable Nspire, utilizamos var.monitor y on.varChange () . La primera de es
vamos a agarrar el nuevo valor de escala utilizando var.recall y utilizarlo para establecer el valor actual de am
Tambin tiene sentido tener arrowkey cambios en nuestro guin reflejan en cambios en la variable fuera (y su
utilizando var.store .
Nuestro truco final es definir varias imgenes y utilice las teclas de flecha izquierda y derecha para cambiar en
Como acabamos de hacer de la escala, definimos las teclas de flecha izquierda y derecha para incrementar los
Tambin puede crear una variable de control deslizante, llamado elegir en una ventana de geometra, y estable
Felicitaciones! Ahora tiene todos los ingredientes que necesita para digitalizar, definir, insertar, escala y mani
Leccin 7.5: Adicin de imgenes mltiples - la manera fcil
Si tiene varias imgenes para aadir a su documento, no es una manera rpida y fcil de hacer esto. Supongam
bridge2.jpg y bridge3.jpg en una carpeta llamada, por ejemplo, script7. En mi Mac, coloqu esta carpeta en la
Crear una hoja de clculo de Excel y en la columna A, escriba los nombres de cada imagen (sin el sufijo): por
celda A2 y A3 est en Bridge3.
Columna B tiene el nombre de ruta para cada imagen. En el Mac, esto va a tomar la forma de:
Guarde este documento en formato CSV (valores separados por comas) y ahora vamos a la pestaa Recursos d
lugar de aadir un archivo de imagen, aadir la hoja de clculo y las tres imgenes se aadirn al instante!
Una hoja de clculo preparada y las imgenes adjuntas para este tutorial se incluye dentro del archivo comprim
Esto se demuestra en
la shuttlecock.tns archivo que
se incluye con descargas de esta
leccin. Incluya tambin se
encuentra la imagen que se
utiliza y la secuencia de
comandos Lua para su
estudio. En el problema 2 de
este archivo TNS, el punto P
est vinculada a una parbola de
modo que el movimiento del
volante puede ser modelado e
incluso animado!
Tmese un momento para ver la Haga clic en cualquier lugar de esta imagen para un vdeo de
pelcula de acompaamiento y demostracin
luego tener un juego con este
documento usando el
reproductor para tener una idea
de las posibilidades y de algunas
de las opciones de diseo que se
han hecho. Por ejemplo, si bien
es grande utilizar las teclas de
flecha y entrar, escapar e incluso
teclas de ficha para hacer el
control tanto por equipo y mano
de forma sencilla, si queremos
que nuestros documentos que
puedan utilizar con el jugador
entonces vale la pena salir de las
correderas.
En el ejemplo mostrado,
presionando flechas arriba y
abajo controla el valor de n ,
aumentando y disminuyendo el
nmero en estudio. Las flechas
izquierda y derecha muestran
las tres opciones - cuadrada,
rectangular y nmeros
triangulares. Presionando enter
muestra diferentes puntos de
vista - la forma creada usando
crculos, con un borde, y el uso
de las plazas. Por ltimo,
presionando los pasos clave de
la ficha a travs de la
construccin de ese modelo, por
lo que es fcil de ver las
relaciones implicadas - nmeros
cuadrados son las sumas de los
nmeros impares, nmeros
rectangulares, la suma de los
nmeros pares, y porque cada
rectngulo es el doble de la
correspondiente tringulo , los
nmeros triangulares se
construyen mediante la adicin
de los nmeros
contables. Presionando escape
le lleva de vuelta a travs de
esta progresin.
fin
y + m * altura)
GC: drawLine (
x + k * longitud,
Y,
El tringulo sigue - la variacin principal
x + k * longitud,
de las dos formas anteriores es que, en
lugar de la segunda funcionamiento
altura y + * nmero)
variable de 0 o 1, que comienza en el
valor actual de k, por lo tanto el
fin
sangrado de cada lnea para formar el
tringulo. Con el fin de cerrar la figura,
fin
que era necesario aadir una lnea
adicional en la parte superior y otra en el
fin
lado derecho - de ah las cuatro lneas en
este script donde los dems slo dos
tenan.
ms
fin
En el tutorial final de esta serie esta
secuencia de comandos se mejora an fin
ms el uso de los crculos para crear
dinmicamente cada uno de los patrones, fin
y ser aadido a nuestros controles de
tecla de flecha de costumbre.
It is time to try and put together everything that we have learned so far.
In this lesson and lesson 10 we will use Lua's graphic commands along
with many of the enhancements we have learned to create documents
that are both useful, clear and easy to use. We will begin with the
graphical display of shape numbers - square, rectangular and triangular
numbers.
Take a moment to watch the
accompanying movie and then
have a play with this document
using the Player to get a feel for
the possibilities and for some of
the design choices that have
been made. For example, while
it is great to use arrow keys and
enter, escape and even tab keys
to make control by both
computer and handheld easy, if
we want our documents to be Click anywhere on this image for a video demonstration
usable with the Player then it is
worth leaving in the sliders.
end
Lesson 9.2: Varying our Grid Pattern
So we have a square grid - we function drawArray(number, x, y, length, height, gc)
would like to have two variations
on this theme: a rectangular grid types=(var.recall("type") or 1)
(with one side one longer than the
other) and a triangular grid. We if types == 1 then
will control these with a slider
variable we will call type. ... (as above)
y + height * m)
gc:drawLine(
x + length * k,
y,
The triangle follows - the main
variation from the two previous
x + length * k,
forms is that, instead of the second
variable running from 0 or 1, it y + height * number)
begins at the current value for k,
thus indenting each line to form end
the triangle. In order to close the
figure, it was necessary to add an end
additional line at top and another
at the right side - hence the four end
lines in this script where the others
had only two.
else
for k = 1, number do
for m = k, number do
Add the line which defines the
variable types from type and the gc:drawLine(x + length*(m-1), y + height * m, x +
first condition (if types == 1 then) length * number, y + height * m)
at the start of the function
definition, and this script will gc:drawLine(x + length * (k-1), y, x + length * (k-1), y
deliver the three shapes drawn + height * k)
using a grid.
end
In the final tutorial in this
series this script is further end
enhanced using circles to
dynamically build each of the end
patterns, and our usual arrow key
controls will be added.
In order to realize this goal, we need to move into the next level of
Lua scripting and introduce the important and powerful tool
of classes.
Back to Top
Next, the class must be initialized. The function Square:init(x, y, width, height)
various properties that this class is to possess
are defined here. Our class Square has self.x = x
position (x and y coordinates), dimensions
(width and height), color and the knowledge self.y = y
of whether it has been selected or not (this
will become clearer soon.) self.width = width or 20
red = {0xFF, 0x00, 0x00}, y >= self.y - sh/2 and y <= self.y + sh/2
De hecho, es posible que haya Haga clic para ver qu tal documento podra ser
notado que un componente de similar
Despus, la clase debe ser inicializado. Las funcin de la plaza: init ( x, y, ancho, altura)
diversas propiedades que esta clase es poseer
se definen aqu. Nuestra clase Square tiene la self.x = x
posicin (coordenadas X e Y), las
dimensiones (anchura y altura), el color y el self.y = y
conocimiento de si se ha seleccionado o no
(esto quedar ms claro pronto.) self.width = anchura o 20
}
fin
Dado que ya se ha especificado el color de la
plaza (en la funcin init),
el desempaquetado de comandos
simplemente agarra la definicin del RGB
para el verde de la mesa, el color. (En ms
detalle: La funcin "desempaquetar" toma funcin de la plaza: pintura ( GC)
como entrada una tabla y devuelve cada
elemento de la tabla como mltiples valores GC: setColorRGB (desempaquetado
de retorno. "GC: setColorRGB" espera tres ( self.color))
parmetros para el rojo, verde y azul, pero
Color.green es un valor, una mesa de tres GC: fillRect ( self.x - self.width / 2, self.y -
elementos. "desempaquetar" convierte los self.height / 2, self.width, self.height)
elementos de la tabla en los tres parmetros
que espera setColorRGB.) si self.selected continuacin,
Volver arriba
W = platform.window: Ancho ( )
H = platform.window: altura ( )
fontSize = W / 32
y esto resultar en un tamao de fuente cerca de 10 en el
dispositivo porttil. El valor se redondea automticamente a
un nmero entero para su uso en el comando setFont, pero
el uso de la funcin de Math.floor se asegurar de que se
producir un valor entero (y la adicin de 0,5 asegura que el
valor es siempre ms cercano a la original). Hay un valor
mnimo de 6 de tamao de la fuente (y un mximo de
255). Con el fin de protegerse contra el primero, a
continuacin, una mejor definicin podra ser
locales iW = 318
locales iH = 212
sf = 1 locales
on.paint = OnPaint
on.resize = onResize
OnPaint (GC)
fin
Adems de lo que otras variables iniciales u objetos que
necesitan ser definidos desde el principio, una insercin
crtica en esta funcin de cambio de tamao es la definicin
del factor de escala en trminos de las dimensiones de la
ventana plataforma (gracias a Nevil Hopley por el gran
enfoque sugerido se muestra a continuacin ). Yo
probablemente incluir la definicin de la fuente en este
punto tambin. A continuacin, una sencilla funcin de
escala se aplica esto a travs de la secuencia de comandos.
fontSize = 10 * sf
fin
funcin s (a)
fin
x = s locales
(IW / 4)
y = s locales
(Ih / 4)
locales w = s
(IW / 2)
Local H = s
(ai / 2)
- Dibujar el
fondo
GC:
setColorRGB
( 200, 200,
250)
GC: fillRect
( x, y, w, h)
-- Dibujar
lneas
GC:
setColorRGB
( 150, 150,
250)
GC:
drawRect ( x,
y, w, h)
GC:
drawLine ( x,
y, x + w, y +
h)
GC:
drawLine ( x,
y + h, x + w,
y)
- Dibujar
Mensajes
GC:
setColorRGB
( 150, 30, 30)
GC: setFont
( "sansserif",
"b", fontSize)
str locales =
"Ponemos la
tecnologa en
sus manos"
Local Sw
= gc:
GetStringWid
th ( str)
GC:
drawString
( str, s (IW /
2) - SW / 2, s
(IH * 0,9),
"inferior")
fin
cursor.show ( )
fin
o Al pulsar Haga clic en cualquier lugar de esta imagen para un vdeo de demostracin
el tabKey (o
Shift-Tab)
selecciona cada
objeto a su vez.
o El uso de
las teclas con
flechas en primer
lugar clonar el
objeto
seleccionado y
luego moverla
por la pantalla de
forma rpida y
sencilla.
o Como
alternativa,
utilice el tabKey
para seleccionar
un objeto, y
luego
simplemente
mueva el ratn -
el objeto se
"salta" a donde
est el ratn!
o Para
liberar un objeto
seleccionado,
pulse Escape.
o Para
restablecer, haga
clic en el botn
proporcionado,
Pulse ENTER o
"r" (o "R").
El ejemplo de lgebra Haga clic en cualquier lugar de esta imagen para un vdeo de demostracin
Azulejos incluido ofrece
un ejemplar nivel
bastante alto de todos los
principios que hemos
discutido aqu. La
solucin adoptada para
los seis tipos de objetos
diferentes era utilizar el
teclado para seleccionar
un objeto escribiendo una
carta: tipo "x" y y x-placa
est seleccionado, listo
para saltar a donde est el
ratn. Pulse la tecla "s"
para x-cuadrado y "u"
para una unidad de
baldosas. Para los
negativos, pulse "n" y
luego la letra
deseada. Este enfoque ha
demostrado ser al menos
tan eficaz como el uso del
ratn, en general, y sin
duda ms eficaz en el
dispositivo porttil.
Estudio de otras
caractersticas de este
documento. Prensa "?" o
"a" para que aparezca un
multi-pgina "Acerca de"
pantalla con instrucciones
detalladas. nmeros Pulse
para cambiar el valor de
x, o pulse "+" y "-" para
cambiar los valores en
incrementos de 0,1.
Siempre que sea posible, Haga clic en cualquier lugar de esta imagen para un vdeo de demostracin
los documentos deben
estar diseados de
manera que el
movimiento de los puntos
se puede controlar
utilizando las teclas de
flecha, adems de
agarrar y arrastrar con
el ratn.
Esto se logra fcilmente
utilizando las funciones
arrowkey, sobre todo
cuando hay un solo punto
"conductor". Si hay
varios puntos, a
continuacin, es
necesario considerar que
debe darse a las tcnicas
efectivas para la seleccin
de estos. Una vez ms,
relativamente fcil de
lograr el uso de clases,
pero igualmente posible
sin. En el ejemplo
mostrado (de nuevo, a
partir de Matemticas
nspired con gracias esta
vez a Daniel Ilaria), hay
tres puntos "controlador",
a, b, c, y stos existen
dentro de una ventana
nativa grfico, por lo que
las clases no son una
opcin. El tabKey se
utiliza para saltar de una a
la siguiente (las
coordenadas se
almacenan en una tabla /
lista de Lua y
simplemente pestaa
pasos a travs de esta
tabla). Con el fin de
indicar visualmente el
punto seleccionado en ese
momento, un pequeo
segmento rojo se une a
otro punto, controlados
de manera similar.
Volver arriba