In a table I keep all the values that the user tells me with a for cycle, but at the moment of printing they only return nils
for i=1,n do
io.write("Por favor deme el valor de a" .. i .. ": ")
a = io.stdin:read("*n")
tablaA[i] = a
end
In a table I keep all the values that the user tells me with a for cycle, but at the moment of printing they only return nils
for i=1,n do
io.write("Por favor deme el valor de a" .. i .. ": ")
a = io.stdin:read("*n")
tablaA[i] = a
end
Hello Giovanni, maybe your problem was the way you printed the values, I do not know exactly how you did it but here I leave an implementation.
io.write("Ingrese la cantidad de valores a ingresar ")
local n=io.stdin:read("*n")
local tablaA={}
for i=1,n do
io.write("Por favor deme el valor de a" .. i .. ": ")
tablaA[i] = io.stdin:read("*n")
end
for i,number in ipairs(tablaA) do io.write(number.." ") end
It is preferable that you add the data with table.insert to add them by rank, first I leave you the clearest and shortest code:
io.read() -- lee valores
table.insert(tabla, elemento) -- inserta elementos por indice
tonumber(valor) -- podemos validar si es númerico y evitarnos errores.
tabla = {} -- estamos declarando una tabla
The code could be like this:
elementos = {} -- declaramos una tabla como lista
num = nil -- declaramos num como nulo
while(not tonumber(num)) do -- hacemos un bucle mientras no sea númerico, recuerda la función "tonumber()"
if (not num) then -- si es nulo imprimimos un mensaje
print("Ingresa un NUMERO:")
else -- y si no, el siguiente, y salir del bucle hasta que obligatoriamente sea un número
print("No ingresaste un número:")
end
num = io.read() -- leemos el dato durante el bucle hasta obtener el númerico
end
for i=1, tonumber(num) do -- recuerda que las listas en Lua inician desde 1, ponemos que lea desde uno siempre y cuando no alcanze el tamaño del número, io.read() retorna una cadena(string) así que lo convertimos a númerico
print("Ingresa el elemento "..i.." para añadir:") -- leemos los datos
table.insert(elementos, io.read()) -- insertamos los datos que se lean en la tabla 'elementos'
end
lista = '{' -- una simple vista para que el usuario vea que elementos insertó
for i,v in pairs(elementos) do
lista = lista..'"'..v..'"'
if not (i == #elementos) then
lista = lista..', ' -- si no es el limite, inserta una coma y espacio separandolos
end
end
lista = lista..'}' -- seramos nuestra "lista" creada que en realidad es una cadena
print("Los elementos en la tabla son los siguientes:\n"..lista) -- le damos al usuario los datos que insertó