Detecting variable type

Hello all,
Currently I am working on a function that creates a 3d box. One aspect that I would like the function to have is the ability to be passed either a table of colors or a single color, then differentiate between the two in the code and set the colors of the mesh accordingly. I have tried all I can think of doing, like indexing a variable(turns out is not nil. Huh.) vs a table, but I cannot find out how to make an if statement that will determine if a variable is a color or a table. Thank you in advance!
-TheSolderKing

@TheSolderKing Try using type, maybe that will help.


function setup()
    tab={}
    c=color(255,0,0)
    print(type(tab))
    print(type(c))
    
    if type(tab)=="table" then
        print("table")
    end
end

Oh ok thank you so much @dave1707! I had no idea about the type() function. Does this work for colors as well? I would assume it would.

type(color) will return ‘userdata’. There are examples of type extention on the forum. Example of my own implementation:

-- this extends type() with userdata and class support
local mt = {}
function typeOf(x,str) 
    if str == nil then -- this is a request
        local typ = type(x)
        if typ == "userdata" or typ == "table" then typ = mt[ getmetatable(x) ] or typ end
        return typ
    else -- this is adding a definition
        mt[ getmetatable(x) ] = str
    end
end
-- populate new entries
typeOf(image(10,10) , "image")
typeOf(color(0) , "color")

you can define type for userdata and your own class definitions too:

typeOf(x) return a string, the type of x
typeOf(x,str) defines that x is of type 'str'; to be done only once, for each type you want.

Hi @TheSolderKing,

I’d get round that by calling the routine with 3 variables. The first is type , the second is table, the third is Colorado. So …

Function 3DFiddle(type, table,Colorado)

Then check type with an if the else query which should ignore the unwanted data type and use that required.

Hope that works/helps.

Bri_G

:smiley:

Thank you! All of your suggestions worked!