Jump to content




Trying to understand Tables


  • You cannot reply to this topic
3 replies to this topic

#1 Obsidia

  • Members
  • 36 posts

Posted 11 August 2016 - 02: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 by Obsidia, 11 August 2016 - 02:31 PM.


#2 Admicos

  • Members
  • 207 posts
  • LocationTurkey

Posted 11 August 2016 - 03:38 PM

Quote

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 by Admicos, 11 August 2016 - 03:38 PM.


#3 Bomb Bloke

    Hobbyist Coder

  • Moderators
  • 7,099 posts
  • LocationTasmania (AU)

Posted 13 August 2016 - 12: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.

#4 H4X0RZ

  • Members
  • 1,315 posts
  • LocationGermany

Posted 13 August 2016 - 10: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 by H4X0RZ, 13 August 2016 - 10:37 PM.






1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users