Lua Functions Checking argument types


Some functions only work on a certain type of argument:

function foo(tab)
--> returns nil if tab has no field bar, which is acceptable
--> returns 'attempt to index a number value' if tab is, for example, 3
--> which is unacceptable

function kungfoo(tab)
    if type(tab) ~= "table" then
        return nil, "take your useless " .. type(tab) .." somewhere else!"


this has several implications:

print(kungfoo(20)) --> prints 'nil, take your useless number somewhere else!'

if kungfoo(20) then print "good" else print "bad" end --> prints bad

foo = kungfoo(20) or "bar" --> sets foo to "bar"

now we can call the function with whatever parameter we want, and it won't crash the program.

-- if we actually WANT to abort execution on error, we can still do
result = assert(kungfoo({bar=20})) --> this will return 20
result = assert(kungfoo(20)) --> this will throw an error

So, what if we have a function that does something with an instance of a specific class? This is difficult, because classes and objects are usually tables, so the type function will return 'table'.

local Class = {data="important"}
local meta = {__index=Class}

    return setmetatable({}, meta)
-- this is just a very basic implementation of an object class in lua

object =
fake = {}

print(type(object)), print(type(fake)) --> prints 'table' twice

Solution: compare the metatables

-- continuation of previous code snippet
    return getmetatable(tab) == meta

Class.is_instance(object) --> returns true
Class.is_instance(fake) --> returns false
Class.is_instance(Class) --> returns false
Class.is_instance("a string") --> returns false, doesn't crash the program
Class.is_instance(nil) --> also returns false, doesn't crash either