lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Weak Type is a small type library that I made. It can be found here:

https://gist.github.com/andrewstarks/6199229

````

local type = require'weak_type'

-- Works like normal.
print(type(nil))
--> nil
print(type("Hello!"))
--> string
print(type({}))
--> table

-- Additional arguments are type names.
print(type({}, "number"))
--> false
print(type(false, "boolean"))
--> boolean, boolean

-- make a type and assign it to an object (any table)
-- this will clobber the __type field in your metatable. It will
-->also make a metatable if you need one.

local o = type.assign({}, {"my_object_type", "number"})

-- Remember, weak_type works like normal type
 print(type(o))
-- table

--To get the type name, you can do a number of things:
print(type.tostring(o))
--> my_object_type
print(type.check(o))
--> my_object_type
print(type.get(o))
--> my_object_type (a type object that can be compared with other
types, it `tostring`s to this, however.)

-- If an object can impersonate a number, this construct is nice.
print(type(o, "number"))
-->my_object_type, number -- first the primary name, then the match.

-- What if we want to know if it's an object or a table?
print(type(o, "my_object_type", "table"))
--> my_object_type, my_object_type
print(type({}, "my_object_type", "table"))
--> table, table

local o2 = type.assign({}, {"another_type", "number", "foo", "my_object_type"})

print(type.is_contained(o, o2))
--> true
print(type.is_contained(o2, o))
--> false

````
There's more. Instructions, such as they are, can be found in the text
surrounding the tests at the bottom of the file.

Some met goals were:

- doesn't create tables when types are checked.
- works like type, except that if it doesn't receive any arguments it
doesn't error:
````
print(type((function() return end)()))
--> nil, invalid key
````
- works for my needs. :)

My goal in posting this is much more about getting your constructive
criticisms than a belief that this is a unique contribution to the Lua
world. Of course, pointing out the parts that I got right is nice,
too. :)

I'm still quite inexperienced and daylight has a way of (sometimes
painfully) helping to educating.

Thanks!

-Andrew