Jump to content

[HELP] if with table


BusDunk

Recommended Posts

Hello, I'm currently learning how to script by myself and i'm running into difficulties. My problem is that I cannot put a table into a condition. I would like my variable to be equal to one of my table's datas.

Here is what I've done :

table = {1,2,3,4,5} 

variable = guiCreateEdit(50, 50, 50, 21, "", false) 

if variable == table then 
  outputChatBox("test",125,0,0) 
else outputChatBox("problem",125,0,0) end 

ChatBox shows : problem

Link to comment
if variable == table then 

Means in this case: If 'guiCreateEdit(50, 50, 50, 21, "", false)' == '{1,2,3,4,5}', in other words, it's not the same so it failed.

To add your variable to the table, you can do for example:

variable = guiCreateEdit(50, 50, 50, 21, "", false) 
table.insert(table, variable) 

Link to comment

== operator checks if the values are the same, which they're not in this case. To check if the value inside the GUI element matches any value inside such table, you would need to through it:

local gui_text = guiGetText(variable) -- stores the contents of the edit box into 'gui_text' 
local matches = false 
  
for key, value in ipairs(table) do -- loop through table, executing the following block of code for each value 
    if tostring(value) == gui_text then 
        matches = true 
        break 
    end 
end 
  
if matches then 
    -- edit box content mathces a value inside the table 
else 
    -- no table value is the same as the content of edit box 
end 

But it would be much simpler if you used the values as the keys of the table:

table = {["1"] = true, ["2"] = true, ["3"] = true, ["4"] = true, ["5"] = true} 
----------------- 
local gui_text = guiGetText(variable) 
if table[gui_text] then 
    -- value of 'gui_text' is inside the table 
else 
    -- value of 'gui_text' is not inside the table 
end 

Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...