[Snippet] Objects from Meta-Class
stableDescription
Here's one for the advanced scripters who will love this when they find it.
Creating objects from an instance of a meta-class without the native table commands.
Use this framework to define classes, create objects from classes and check objects against class.
HaasScript
--- Define a class object
local Class = {{name="OrderStatus"}, {types = {UnKnown = 0,
Open = 3,
Completed = 5,
Canceled = 7 }}}
--- Assign the class as a meta index
local meta = {__index=Class}
--- Define the object creation function
function Class:New()
local table = {}
table[#table+1] = meta
self = table
return self
end
--- Define the Set Meta Method
function Class:__Set( index, value )
if index != nil then
if self[index] != nil then
Save(self[index], value)
end
end
end
--- Define the Get Meta Method
function Class:__Get( index )
if index != nil then
return Load(self[index])
end
end
--- Define the Check Meta Method
function Class.is_instance(tab)
return ArrayGet(IfNull(tab, {}), 1) == meta
end
--- Define the Set function
function Set( key, value )
Save(key, IfNull(value, ''))
return Load(key, IfNull(value, ''))
end
--- Define the Get function
function Get( key, value )
return Load(key, IfNull(value, ''))
end
--- Examples of use
--- Create an object from the class using the real meta method
object = Class:New()
--- Create other object but not of the class
fake = {}
array = {key='test', value={something='this', thing='that'}}
--- Check the output and types
Log(object)
Log(GetType(object))
Log(GetType(fake))
--- Testing the Get and Set functions
Log(Set('test', 'value'))
Log(Get('test'))
--- Checking and confirming class inheritance
Log(Class.is_instance(object))
Log(Class.is_instance(fake))
Log(Class.is_instance(Class))
Log(Class.is_instance(nil))
Log(Class.is_instance("a string"))
Log(Class.is_instance(array))
--- mic drop.... walks away
0 Comments
Sign in to leave a comment.
No comments yet. Be the first!