IsValid() not working with tables

Hi, I’m setting up a file client-side that contains tables created like this at the top of the file:



local mat = {}

mat["abc"] = {name = "image1", width = 100, height = 100, material = Material("materials/images/img1.png", "unlitgeneric")}
mat["def"] = {name = "image2", width = 100, height = 100, material = Material("materials/images/img2.png", "unlitgeneric")}
mat["ghi"] = {name = "image3", width = 100, height = 100, material = Material("materials/images/img3.png", "unlitgeneric")}
mat["jkl"] = {name = "image4", width = 100, height = 100, material = Material("materials/images/img4.png", "unlitgeneric")}


I want to be able to draw the images on a HUD if the user’s name contains/starts with “abc”, “def”, “ghi”, or “jkl.” We have it set up so the user does not start with one of these at the beginning but gets a prefix later on as he progresses and gains more XP. Because some users do not have the prefix early on, we need to validate the table with this code:



prefix = string.lower(string.sub(LocalPlayer():Nick(), 0, 3))

if !IsValid(mat[prefix]) then return end


We then tested with this code:



local function bringToLife()
	if not IsValid(LocalPlayer()) then return end

	print(IsValid(mat[prefix]))
end

hook.Add("HUDPaint", "DrawTheHUD", bringToLife)


But our problem lies within the fact that it seems to return “false” each time, even if I manually change the “prefix” part to a string that is in the table, such as “abc” or “ghi”. If anyone can tell me why this is happening, please do so! It’s been getting on our nerves for days now.

IsValid()



lua_run print( IsValid( {} )  )
false


Don’t use IsValid on tables, that’s not its purpose. Just do


if !mat[prefix] then return end

to check for nil indexes.

Wow thanks, didn’t know it would be that simple. On https://wiki.garrysmod.com/page/Global/IsValid it says that the argument you supply can be a table or class, so I thought it would work. Thanks a lot!

It’s referring to metatables/userdata. I’ll update the wiki.