This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
Micheal Pearce's profile picture

Arrays/tables

Started by Micheal Pearce, 17 July 2013 - 10:51 AM
Micheal Pearce #1
Posted 17 July 2013 - 12:51 PM
so i've been trying to use table lately and i don't understand why this is not working i swear it work sometime ago but now it doesn't


ex = {
   a = 1,
   A = 10,
}
print(ex[a])

and this doesn't work and i know i could do ex.a and it would work but need it so it can take a user inputted letter so like


ex = {
a = 1,
A = 10,
b = 2,
B = 20,
c = 3,
C = 30,
}
input = read()
print(ex[input])

and if it would work the way i think it should it should print out 10 if the use inputted A, but this doesn't it doesn't return anything but a blank line another thing is when i try to get how many values are in the table/array like print(#ex) would return 0

Thank you for reading this and thanks for you comments
MysticT #2
Posted 17 July 2013 - 01:10 PM
so i've been trying to use table lately and i don't understand why this is not working i swear it work sometime ago but now it doesn't


ex = {
   a = 1,
   A = 10,
}
print(ex[a])

and this doesn't work and i know i could do ex.a and it would work but need it so it can take a user inputted letter so like
You need to add quotes there:

print(ex["a"])
wich is the same as:

print(ex.a)

another thing is when i try to get how many values are in the table/array like print(#ex) would return 0
Using the lenght operator only returns
the largest positive numerical index of the given table, or zero if the table has no positive numerical indices.
To get the size of a table with string (or any other type of) keys, you can use a function like this:

local function getTableSize(t)
  local size = 0
  for k,v in pairs(t) do
	size = size + 1
  end
  return size
end
Micheal Pearce #3
Posted 17 July 2013 - 01:56 PM
You need to add quotes there:

print(ex["a"])
so how would i be able to get use input and use it to get one of the values in the ex table?
Bubba #4
Posted 17 July 2013 - 02:41 PM
You need to add quotes there:

print(ex["a"])
so how would i be able to get use input and use it to get one of the values in the ex table?


local ex = {
  stuff = "hello";
  ["tables are versatile"] = "sup";
}

local input = read()
if ex[input] then --#You are inputting the /value/ of input, not trying to get a field called "input" in the ex table
  print(ex[input])
end

So if I input "stuff" to the prompt, the program would print out "hello".
Micheal Pearce #5
Posted 17 July 2013 - 03:45 PM
Thanks guys!