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

Figuring out how to set the number this is in a table to a variable

Started by domi21801, 10 August 2013 - 10:01 PM
domi21801 #1
Posted 11 August 2013 - 12:01 AM
So I have this code, here it is

function tableCheck(yolo, swag)
tries = 0
for i = 1, #yolo do
if yolo ~= swag then
tries = tries + 1
end
end
end


now, i thought that doing a print(tries) would output the number of swag in the table yolo, but it only seems to output the second to last number in the table. what should I do to accomplish my goal of having a variable to represent the number of swag in table yolo?

also, I edit this code to return false if tries == #yolo else return true, so i know this works, this lets me check a table for a variable. that way
I can check entire tables of variables for another variable and that way i can update player detector doors easily :D/>/> its pretty cool. anyway please help me solve this problem.
Bubba #2
Posted 11 August 2013 - 09:05 AM
Split into new topic.
domi21801 #3
Posted 11 August 2013 - 03:46 PM
Here is another example of what im trying to do, I worked this up last night

function tableCheck(yolo, swag)
tries = 0
for i = 1, #yolo do
if yolo ~= swag then
tries = tries + 1
end
end
end
sample = {"one", "two", "three"}
write("input: ")
input = read()
tableCheck(sample, input)
print(tries)


what I want to do is print the number it is in the table, as in if you were to call upon a var in a table you would do this table I want to search for a variable in the table and figure out what i is, supposing the var is in the table. This would be of great help. thanks.
MysticT #4
Posted 11 August 2013 - 04:28 PM
Ok, let me see if I understood what you want. You need a function that returns the key (or index) of a certain value inside a table. So, if you have the table { "some value", aVariable, 6, "my value" }, and you search for "my value", it would return 4.
If that's what you need, here's a function that does that:

local function tableCheck(t, val)
  for i = 1, #t do --# loop through the table. If you need non-numerical keys, you need to use pairs.
	if t[i] == val then --# check if the value matches
	  return i --# return the key/position of the value in the table
	end
  end
end
You can then use it like this:

local t = { "some value", aVariable, 6, "my value" }
local i = tableCheck("my value")
print(i) --# this should print 4
domi21801 #5
Posted 11 August 2013 - 06:17 PM
:D/> oh, i should have though about not cycling all the way throught the table, and just done that, thats genius thanks!