Get value from table using variable?

You can write your topic however you want, but you need to answer these questions:

  1. What do you want to achieve? I want to retrieve the values of my rarity table from this module

  2. What is the issue? Include screenshots / videos if possible! keeps saying its nil

script 1

	local CrateType = "CommonCrate"
			local modifiedItemTypes = contents:GetItemTypes(CrateType)

script 2

print(itemTypes["CommonCrate"]) --This works
	print(itemTypes[CrateType]) -- This doesnt even though it is putting in the same name???

It works, If you have a Variable Assigned as a String the same as a key within a table, it will work as the value of the Variable is the exact name as the index, if it isn’t it will likely print another index, or print nil if there is no index at all

local ex = "example" -- string

-- adding an index

t = { -- table
    example = {}  -- Method 1 (add index inside the table)
}
t.example = {}    -- Method 2 (another way of adding an index)
t["example"] = {} -- Method 3 (alternate to Method 2)
t[ex] = {}        -- Method 4 (key created using variable, same as Method 3)

-- printing an index
-- (if there is a Key under the same string (or name), it will work. otherwise it will print 'nil')

print(t.example) --> value or nil
print(t[ex])     --> value or nil

This means that you are attempting to iterate over a nil value, as in the table you are providing doesnt exist. If you are doing a Recursive Search with a function, That is likely why you are getting this error, one of the Values may be returning as nil.

1 Like