Table["%w+"] returns false?

local Table = {
	Name = ""
}

if Table["%w+"] then
	print("Has items")
end

I want to know why Table["%w+"] returns false when it should return true.
I want a fix for this.

So that Table["%w+"] returns true.

If you want to see if a dictionary has items, use pairs.

for _ in pairs(dict) do
    print("has items")
    break
end

table indexing does not use pattern matching like gsub and gmatch does. It is very expensive to do such pattern matching

1 Like

You can’t use string patterns when indexing a table.

You could do something like this:

local Table = {
	Name = ""
}

local found = {}
for key,val in pairs(Table) do
    if key:match("%w+") then
        table.insert(found, {key, val})
    end
end

print(found)

to get all keys that match a string pattern.

But if you just want to check if a table has atleast one key, then you can just do this:

If you had this table:

local Table = {
	Name = "my name",
    ["%w+"] = false,
    ["someone elses Name"] = "not my name"
}

-- and you did this:
print(Table["%w+"])

then what should it print?

local t = {}

function t.__index(self, key)
  if type(key) == "string" then
    local s = string.gsub(key, "(%w+)", function(w)
      return self[w]
    end)
    return self[s]
  else
    return rawget(self, key)
  end
end

setmetatable(t, t)