123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141 |
- function percentOf(val1, val2)
- return math.ceil(val2 * (val1 / 100))
- end
-
- function expect(var1, var2)
- if var1 ~= var2 then
- error("Expected "..tostring(var2)..", got "..tostring(var1))
- end
- end
-
- function printTable(tbl, depth)
- if depth == nil then
- depth = 0
- end
-
- local pre = ""
- for i = 1, depth do
- pre = pre .. " "
- end
-
- local str = ""
- for key, val in pairs(tbl) do
- if type(val) == "table" then
- str = str .. pre .. key .. ": {\n"
- .. printTable(val, depth + 1)
- .. pre .. "}\n"
- else
- str = str .. pre .. key .. ": " .. tostring(val) .. "\n"
- end
- end
-
- return str
- end
-
- function writeFile(path, str)
- local h = fs.open(path, "w")
- h.write(str)
- h.close()
- end
- function appendFile(path, str)
- local h = fs.open(path, "a")
- h.write(str)
- h.close()
- end
-
- function newObject()
- local self = {}
-
- self.getset = function(name, getter, setter)
- self[name] = function(val)
- if val == nil then
- if getter == nil then
- error("No getter.")
- end
- return getter()
- else
- if setter == nil then
- error("No setter.")
- end
- setter(val)
- return self
- end
- end
- end
-
- return self
- end
-
- function makeEventListener(self)
- util.expect(type(self), "table")
-
- local callbacks = {}
- local anyListeners = {}
-
- self.emit = function(name, ...)
- local funcs = callbacks[name]
- if funcs == nil then
- return
- end
-
- for key, func in pairs(funcs) do
- func(...)
- end
-
- for key, func in pairs(anyListeners) do
- func(name, ...)
- end
-
- return self
- end
-
- self.on = function(name, func)
- if callbacks[name] == nil then
- callbacks[name] = {}
- end
- table.insert(callbacks[name], func)
-
- return self
- end
-
- self.onany = function(func)
- table.insert(anyListeners, func)
-
- return self
- end
-
- self.removeListener = function(name, listener)
- local funcs = callbacks[name]
- if funcs == nil then
- return
- end
-
- for key, func in pairs(funcs) do
- if func == listener then
- table.remove(funcs, key)
- end
- end
-
- return self
- end
-
- self.once = function(name, func)
- self.on(name, function(...)
- func(...)
- self.removeListener(name, func)
- end)
-
- return self
- end
-
- self.removeAllListeners = function()
- callbacks = {}
- anyListeners = {}
-
- return self
- end
- end
-
- function abstract()
- error("This method is abstract and must be overridden.")
- end
|