Jump to content




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


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

#1 domi21801

  • Members
  • 3 posts

Posted 10 August 2013 - 11:01 PM

So I have this code, here it is

function tableCheck(yolo, swag)
tries = 0
for i = 1, #yolo do
if yolo[i] ~= 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.

#2 Bubba

    Use Code Tags!

  • Moderators
  • 1,142 posts
  • LocationRHIT

Posted 11 August 2013 - 08:05 AM

Split into new topic.

#3 domi21801

  • Members
  • 3 posts

Posted 11 August 2013 - 02: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[i] ~= 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] 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.

#4 MysticT

    Lua Wizard

  • Members
  • 1,597 posts

Posted 11 August 2013 - 03: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


#5 domi21801

  • Members
  • 3 posts

Posted 11 August 2013 - 05:17 PM

:D oh, i should have though about not cycling all the way throught the table, and just done that, thats genius thanks!





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users