How to search for a variable in a table with a string?

Basically, I need to just search a table for variables, I know “table.find()” exists, but that searches for strings, here is an example of what I’m trying to achieve:

local test_table = {
	["test_variable"] = "testing"
}

print(table.find(test_table, "test_variable")) -- I want this to output "testing"

Its probably an easy solution, the only thing I could think of is looping through everything in the table, and turn everything into a table and just check if “variable[1]” is “test_variable”, but that would kind of be innifiecient.

Ways:

local test_table = {
	["test_variable"] = function()
        print("Testing")
    end
}

test_table["test_variable"]()

Second way:

local test_table = {
	["test_variable"] = "Testing"
}

print(test_table["test_variable"])

There others way
I recommend the second one if it’s just to print the variable’s value, if it’s something longer, do the first one, which is functions.

1 Like

I’m a little confused on what you’re trying to achieve here, table.find returns an index of where the element is found, however your table is a dictionary, and so it does not have number indexes

When you have something like

test_table = {'a','b','c'}

what you actually have is

test_table = {
	[1] = 'a',
	[2] = 'b',
	[3] = 'c'
}

and so table.find() would return the number index of the element

If what you want is a find function for dictionarys, i.e, key value pairs, you could do the following:

local test_table = {
	["test_variable"] = "testing"
}

function dict_find(tbl:{},value:any)
	local found = nil
	for key,val in pairs(tbl) do
		if val == value then
			found = key
			break
		end	
	end
	return found
end

print(dict_find(test_table,'testing'))
-->> prints "test_variable"

--and so:
local findkey = dict_find(test_table,'testing')
print(test_table[findkey])
-->> prints "testing"
1 Like

Thank you! I ended up doing something like this:

local test_table = {
	["test_variable"] = "testing"
}

print(table.find(test_table, "test_variable")) -- I want this to output "testing"

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.