Skip to content

Instantly share code, notes, and snippets.

@Tyderion
Last active December 20, 2015 17:58
Show Gist options
  • Save Tyderion/6172117 to your computer and use it in GitHub Desktop.
Save Tyderion/6172117 to your computer and use it in GitHub Desktop.
Some Lua Stuff

##Closure / Table hybrid classes

Features:

  • Public/Private instance fields
  • Public/Private instance methods
  • public class methods/fields
  • inheritance (only 1 parent)

##Closure/table hybrid switch function

Features:

  • Possible to mix functions/values
  • Default value
  • Kinda switch-like syntax
local Base = {}
Base.foo = function()
return "Class Method Base"
end
Base.new = function(var)
local self = {
public_field = var
}
local private = 5
function self.foo()
return "Base private: " .. private .. " - public: " .. self.public_field
end
return self
end
local SubClass = {}
SubClass.new = function(initbase, initsub)
local self = Base.new(initbase)
self.new_public = initsub
function self.bar()
return "SubClass Bar, public: " .. initsub
end
return self
end
local t = SubClass.new("hey", "there")
local t2 = SubClass.new("second", "try")
print(t.foo()) -- Base private: 5 - public: hey
print(t.bar()) -- SubClass Bar, public: there
print(t2.foo()) -- Base private: 5 - public: second
print(t2.bar()) -- SubClass Bar, public: try
print(Base.foo()) -- Class Method Base
-- Public fields (in the self-object) can be seen from outside, private variables (locals) cannot
print(t.public_field) -- hey
print(t.private) -- error
local function switch( config )
local cases = config.cases
local default = config.default
wrapper = function(access)
result = cases[access]
if result == nil then
if type(default) == "function" then
return default()
else
return default
end
end
if type(result) == "function" then
return result()
else
return result
end
end
return wrapper
end
local test = 17
testswitch = switch(
{
["cases"] = {
["test"] = "YES", -- value case, can also be afunction
["fail"] = function() return "Fail " .. test*2 -- function case, can also be a value
},
["default"] = function() return "Default function" .. 5*3 end -- Function default, can be value
}
)
print(testswitch("test")) -- "YES"
print(testswitch("fail")) -- "Fail 34"
print(testswitch("missing")) -- "Default Function 15"
-- Simple Switch Statement without default/missing, respectively default == nil
switch = {
["Case 0"] = "Case 0 element",
["Case 1"]= "Case 1 element"
}
print(switch["Case 0"]) -- "Case 0 element"
print(switch["haha"]) -- nil
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment