Sumar valores de un Array - Forum

Forum Navigation
You need to log in to create posts and topics.

Sumar valores de un Array

Intento sumar los valores dentro de un array sin lograrlo, hago lo siguiente:

ArrayLen [Entrega] [LargoArray]

SetVar [SubTotal] 0

Loop 0 [LargoArray] [x]
Math "[Subtotal]+[Entrega([x])]" 0 [SubTotal]
If [x] == 0
AlertBox "" "[SubTotal]" ""
endif
endloop

Me encuentro que el alertbox me devuelve un valor vacio

@gustavo1973 esto funciona (no entiendo el If que has puesto):

CreateArray [Entrega] 1,2,3,4,5,6,7,8,9
ArrayLen [Entrega] [LargoArray]
SetVar [SubTotal] 0
Loop 0 [LargoArray] [x]
  Math "[Subtotal]+[Entrega([x])]" 0 [SubTotal]
  If [x] == [LargoArray]-1
      AlertBox "" "[SubTotal]" ""
  EndIf
EndLoop

 

Por que no me funciona?? Obvio soy nuevo, pero no logro que funcione la variable [x]... Muchas gracias por la ayuda

OJO=jalo un archivo .txt

LocalFileToVar "FileInput1" [om]
StrParse "[om]" ";" [cadena]
StrLen "[cadena]" [cantidad]
Math "[cantidad]-1" 0 [cuantosHAY]

setvar [inicia] "0"
Loop 0 [cuantosHAY] [x]
SetVar [hay] "[cadena([x])]"
StrParse [hay] "," [am]
setvar [item] [am(0)]
setvar [cod] [am(1)]
setvar [ser] [am(2)]
neoTableSetData [mydata2] [x] "id" [item]
neoTableSetData [mydata2] [x] "Codigo" [cod]
neoTableSetData [mydata2] [x] "Serie" [ser]
neoTableLoadData "tibo2" [mydata2]
EndLoop

neoTableResetColumns "tibo2"

neoTableSetColumn "tibo2" 1 "id" "Id" "" false false false ""
neoTableSetColumn "tibo2" 2 "Codigo" "Codigo" "" false false true ""

neoTableSetColumn "tibo2" 3 "Serie" "Serie" "" true false true ""

neoTableInitTable "tibo2" "" 6 "Table" false true false false false ""

ShowObject "tibo2" "" 0
ObjectToFront "tibo2"

neoTableLoadData "tibo2" [mydata2]

Hola @thibeault911,

Tengo la sensación de que no esperas a que se carguen los datos para hacer las operaciones posteriores y tu variable [om] está vacía cuando empiezas a procesarla. Puedes utilizar Watch para ver cuando se han leido los datos o bien Wait ajustándolo a un tiempo prudencial.
El quid de la cuestión está en entender que LocalFileToVar no detiene la ejecución del código hasta que se ha leido el archivo, sino que las lineas posteriores se siguen ejecutando mientras tanto.

thibeault911 has reacted to this post.
thibeault911

Luis , como estas, Ese código funciona perfectamente en determinadas situaciones
y en otras no.

A ver si logro explicarme,
si lo copio a ese codigo dentro de un boton y
lo ejecuto funciona sin problemas

pero si ese codigo intenta leer el array que fue cargado con datos provenientes  de una consulta hecha en la base de datos
ya no funciona

en mi caso concreto, recibo los datos desde mi base remota y cargo los valores en el array,
puedo verlos en pantalla,

pero el codigo de mas arriba que deberia mostrarme el total de los valores sumados no lo hace,
solo me muestra el ultimo valor del array

Entonces mi pregunta es,
podria a llegar a existir alguna diferencia entre valores de un array cargados mediante una variable como
tu lo haces en el ejemplo :

CreateArray [Entrega] 1,2,3,4,5,6,7,8,9

a que si los datos de ese array provienen de otro lado?

 

Con respecto a lo que pones que no entiendes lo del "if" supongo que es al que pongo para poder terminar el loop, si no lo hago de esa manera no sale nunca del LOOP

¿Podria a llegar a existir alguna diferencia entre valores de un array cargados mediante una variable como tu lo haces en el ejemplo a que si los datos de ese array provienen de otro lado?

No, solo tienes que asegurarte de que los datos se han cargado antes de empezar a procesarlos.
Fíjate que hay algunas aplicaciones de ejemplo para SQLite donde puedes ver como se procesan los datos (en MySQL el proceso es idéntico).

thibeault911 has reacted to this post.
thibeault911

@Gustavo1973

My Chrome browser automatically translates the contents of these posts ... so there might be something lost in translation ... never the less, let me try and elaborate on Luis's response to thibeault911 ...

if I copy it to that code inside a button and
execute it, it works without problems

This is because the second line (ArrayLen) is serviced AFTER the first line (CreateArray) is serviced.

but if that code tries to read the array that was loaded with data from a query made in the database
it does not work anymore

In my specific case, I receive the data from my remote base and I load the values ​​in the array,

If you try and execute Luis's code (minus the CreateArray command) immediately after querying the database, the array variable [Delivery] will not have been populated.

Requests to the remote computer holding your database, are serviced ASYNCHRONOUSLY ... that means that after the request is sent from your computer, your App does NOT wait for the data to be received ... depending on internet traffic, this could be 10 to 100 times what it takes to service one of the VisualNEOWeb commands ... so if you follow your request with lines 2 to 9 of Luis's code, it will be processing the content of the variable [Delivery] BEFORE any data has arrived and been placed in the variable.

I can see them on the screen,

All this happens in the order of milliseconds ... so the human eye can not differentiate the sequence of events ... if you want, you can place an AlertBox command to display the value of [LargoArray] immediately before the Loop command ... it should say 0 (unless there was old data in it).

but the code above that should show me the total of the summed values ​​does not,
only shows me the last value of the array

If you don't wait for the data to arrive, it should show you 0 ... perhaps you had old data in the variable.

So my question is,
could there be any difference between values ​​of an array loaded by a variable like
you do in the example:

CreateArray [Delivery] 1,2,3,4,5,6,7,8,9

What if the data in that array comes from another side?

Use the Watch command ... something like ...

SetVar "[Delivery] ""
Wait [Delivery] "ProcessReceivedData"
... your query command goes here

Now place the other commands in a subroutine called ProcessReceivedData ... plus the CancelWatch command to cancel further unintended processing of changes to this variable.

 

Hope this helps to understand how to receive/process data from a remote machine.

luishp has reacted to this post.
luishp

Muchisimas gracias Luis me funciono correctamente sin embargo obtengo estos errores

No se puede obtener la propiedad '0' de referencia nula o sin definir (main.js?v=50, 265)
Se esperaba un objeto (main.js?v=50, 367)

Pero no comprendo que quiere decir

@thibeault911 para entender el mesaje de error hay que tener en cuenta lo siguiente:
main.js es el archivo donde está toda tu programación traducida a JavaScript.
Donde dice ?v=50,256 significa que el error está en la linea 50, en la posición 256.
Generalmente donde aparece el mensaje de error se puede clicar para abrir el archivo y localizar el error.
Quizá así puedas obtener alguna pista adicional.