Detect if table in dictionary exists?

Hello, how would I detect if a table in a dictionary exists without using a bunch of if statements?

In this case, I want to detect if ProjectileInfo exists in SwordInfo so that I don’t get this error:

image
Is there any way to do this without plastering if statements everywhere or pcalls? Please let me know.

This is for my sword creation system which sometimes has projectileinfo and sometimes doesn’t.


I’m quite desperate for help, its probably a very simple answer that I haven’t figured out yet.

Just have an if statement check for the ProjectileInfo. Since values that don’t exist in a table or dictionary return nil, you can just do

if SwordInfo.ProjectileInfo ~= nil then
-- put here all the variables that depend on ProjectileInfo's existence
end
1 Like

if statements were the exact thing I was avoiding really, is there not a way to make one if statement work on all instances of this? its hard to explain but


Do I need a seperate if statement for both of these? or can I just make a single if statement to somehow work on all of the variables.

if SwordInfo[ProjectileInfo] then
    -- stuff
end

What i like to do is use or

local projectileInfo = SwordInfo.ProjectileInfo or {} --if first value is nil instead use an empty table so it doesn't error

newSword.ProjectileType = projectileInfo.ProjectileType or 1 --if it's nil then use a default value instead
--and so on
1 Like

You can just put them all in one scope, it’s what I would do. Declare a variable outside so that it has a default value.

local cooldown = 0
local velocity = 0
if SwordInfo.ProjectileInfo ~= nil then
    cooldown = SwordInfo.ProjectileInfo.projectileCooldown
    velocity = SwordInfo.ProjectileInfo.projectileVelocity
    -- put all variables that depend on it's existence
end

Use the outside variables in further uses

1 Like
if (swordInfo['ProjectileInfo'] ~= nil) then
  if (swordInfo['ProjectileInfo']['ProjectileType'] ~= nil and swordInfo['ProjectileInfo']['ProjectileCooldown'] ~= nil swordInfo['ProjectileInfo']['ProjectileVelocity'] ~= nil) then
    --// whatever here
  end
end

I did try that before and it did work, however if I did this for every variable that i’m going to have, then its gonna take up a lot of space and make the code less readable (in my opinion), thanks for replying though!

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