Get table item from function return value

Hello developers, i’ve got a quick question!

I’ve been working on a small project, and for that project i will need to get a specific item of a return value from a function that returns a table.

e.g:

function foo()
	-- do something
	return {Value1 = x, Value 2 = y}
end

if [[item Value2 of foo()]] == 1 then
	--- do something
end

what i’ve tried:

if foo().Value1 == 1 then
if foo()["Value1"] == 1 then

I’ve also looked around the documentation for functions and tables for a bit, bit couldn’t find anything.

I know i could store the result of the function in a seperate variable and then acces it that way, but for my purpose that isnt really feasible. Is there any better way to do this?

Try this :

function foo()
	local x = math.random(1,20)
	local y = math.random(1,40)
	
	return {["Value1"] = x, ["Value2"] = y}
end

local fooTable = foo()

if fooTable["Value1"] == 1 then
	print("X = 1 !")
else
	print("X is equal to "..fooTable["Value1"])
end

yeah, thats what i described in the last part, but for my purpose that idea isn’t really feasible, although i think ive already found a good solution:

function foo(Type)
	if Type then return table[Type] else return table end
end

Now i have to call the function using

foo("Type_name")

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