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

Trying to understand Tables

Started by Obsidia, 11 August 2016 - 01:30 PM
Obsidia #1
Posted 11 August 2016 - 03:30 PM
Im currently trying to understand Tables work on my own but I cant figure out how to use them. :D/>

Ive just wrote a simple adder to test it out


sum = 0	
print("Press 'E' to add a digit, 'X' to exit!")
print("Current count: "..sum)

local Table = {10,20,30,40,50}		   [color=#008000]---  The Table with the list of digits I want to use  [/color]

local function Blue()  
term.setTextColor( colors.blue )
end
local function White()	
term.setTextColor( colors.white )
end

while true do
  loca event, key = os.pullEvent("key")
	if key == keys.e then
	sum = sum + 1
	print("Current count: "..sum)
	elseif key == keys.x then
	break
	end

  if sum == Table then				[color=#008000] ---  This where I need help[/color]
  Blue()
  print("---- E to add, X to exit! ---")
  end
end



So basically I want it to take a look at the digits in the table and if its one of them it should print out the options again
but currently its doing nothing at all. :P/>

Tables are used to shorten Code as far as I understood, but how do I use it?
What part of tables did I missunderstand or is my thought of what it is and what its used for completly wrong?
Edited on 11 August 2016 - 01:31 PM
Admicos #2
Posted 11 August 2016 - 04:38 PM
So basically I want it to take a look at the digits in the table and if its one of them it should print out the options again
Try the following (not tested)

for index, value in ipairs(Table) do
  if sum == value then
    print("found " .. sum .. " in table!")  
  end
end
also, i wouldn't recommend calling your table variable "Table" as it might get confused with the table api.

Other than that, just search for Lua tables to find info about them.
Edited on 11 August 2016 - 02:38 PM
Bomb Bloke #3
Posted 13 August 2016 - 01:28 PM
A key point is that you're not interested in the table itself, so much as you're interested in its contents. Admicos' example above uses ipairs to get at those contents.
H4X0RZ #4
Posted 13 August 2016 - 11:34 PM
although I would suggest a lookup table instead of looping over the table every time.


local tbl = {[10]=true, [20]=true}
local sum = 10
print((tbl[sum] and "" or "not ") .. "in the table")
Edited on 13 August 2016 - 09:37 PM