repo stringclasses 245
values | file_path stringlengths 29 241 | code stringlengths 100 233k | tokens int64 14 69.4k |
|---|---|---|---|
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Client/UI/Modern/Components/Packages/_Index/csqrl_sift@0.0.3/sift/Set/isSubset.luau | --!strict
--[=[
@function isSubset
@within Set
@param subset { [any]: boolean } -- The subset to check.
@param superset { [any]: boolean } -- The superset to check against.
@return boolean -- Whether the subset is a subset of the superset.
Checks whether a set is a subset of another set.
```lua
local set = { hello = true, world = true }
local subset = { hello = true }
local isSubset = IsSubset(subset, set) -- true
```
]=]
local function isSubset(subset: { [any]: boolean }, superset: { [any]: boolean }): boolean
for key, value in pairs(subset) do
if superset[key] ~= value then
return false
end
end
return true
end
return isSubset
| 188 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Client/UI/Modern/Components/Packages/_Index/csqrl_sift@0.0.3/sift/Set/isSuperset.luau | --!strict
local isSubset = require(script.Parent.isSubset)
--[=[
@function isSuperset
@within Set
@param superset { [any]: boolean } -- The superset to check.
@param subset { [any]: boolean } -- The subset to check against.
@return boolean -- Whether the superset is a superset of the subset.
Checks whether a set is a superset of another set.
```lua
local set = { hello = true, world = true }
local subset = { hello = true }
local isSuperset = IsSuperset(set, subset) -- true
```
]=]
local function isSuperset<any>(superset: { [any]: boolean }, subset: { [any]: boolean }): boolean
return isSubset(subset, superset)
end
return isSuperset
| 181 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Client/UI/Modern/Components/Packages/_Index/csqrl_sift@0.0.3/sift/Set/map.luau | --!strict
--[=[
@function map
@within Set
@param set { [T]: boolean } -- The set to map.
@param mapper (T, {[T]: boolean}) -> U -- The mapper function.
@return {[U]: boolean} -- The mapped set.
Iterates over a set, calling a mapper function for each item.
```lua
local set = { hello = true, world = true }
local mappedSet = Map(set, function(value)
return value .. "!"
end) -- { ["hello!"] = true, ["world!"] = true }
```
]=]
local function map<T, U>(set: { [T]: boolean }, mapper: (T, { [T]: boolean }) -> U): { [U]: boolean }
local result = {}
for key, _ in pairs(set) do
local mappedKey = mapper(key, set)
if mappedKey ~= nil then
result[mappedKey] = true
end
end
return result
end
return map
| 225 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Client/UI/Modern/Components/Packages/_Index/csqrl_sift@0.0.3/sift/Set/merge.luau | --!strict
--[=[
@function merge
@within Set
@param ... ...any -- The sets to merge.
@return { [T]: boolean } -- The merged set.
Combines one or more sets into a single set.
Aliases: `join`, `union`
```lua
local set1 = { hello = true, world = true }
local set2 = { cat = true, dog = true, hello = true }
local merge = Merge(set1, set2) -- { hello = true, world = true, cat = true, dog = true }
```
]=]
local function merge<T>(...: any): { [T]: boolean }
local result = {}
for setIndex = 1, select("#", ...) do
local set = select(setIndex, ...)
if type(set) ~= "table" then
continue
end
for key, _ in pairs(set) do
result[key] = true
end
end
return result
end
return merge
| 223 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Client/UI/Modern/Components/Packages/_Index/csqrl_sift@0.0.3/sift/Set/toArray.luau | --!strict
--[=[
@function toArray
@within Set
@param set { [T]: boolean } -- The set to convert to an array.
@return {T} -- The array.
Converts a set to an array.
```lua
local set = { hello = true, world = true }
local array = ToArray(set) -- { "hello", "world" }
```
]=]
local function toArray<T>(set: { [T]: boolean }): { T }
local result = {}
for key, _ in pairs(set) do
table.insert(result, key)
end
return result
end
return toArray
| 138 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Client/UI/Modern/Components/Packages/_Index/csqrl_sift@0.0.3/sift/Types.luau | local None = require(script.Parent.None)
--[=[
@type None None
@within Sift
]=]
export type None = typeof(None)
export type Dictionary<K, V> = { [K]: V }
export type Array<T> = Dictionary<number, T>
export type Set<T> = Dictionary<T, boolean>
export type Table = Dictionary<any, any>
export type AnyDictionary = Dictionary<any, any>
return nil
| 89 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Client/UI/Modern/Components/Packages/_Index/csqrl_sift@0.0.3/sift/Util/equalObjects.luau | --!strict
local _T = require(script.Parent.Parent.Types)
--[=[
@function equalObjects
@within Sift
@param ... ...table -- The tables to compare.
@return boolean -- Whether or not the tables are equal.
Compares two or more tables to see if they are equal.
```lua
local a = { hello = "world" }
local b = { hello = "world" }
local equal = EqualObjects(a, b) -- true
```
]=]
local function equalObjects(...: _T.Table): boolean
local firstItem = select(1, ...)
for i = 2, select("#", ...) do
if firstItem ~= select(i, ...) then
return false
end
end
return true
end
return equalObjects
| 169 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Client/UI/Modern/Components/Packages/_Index/csqrl_sift@0.0.3/sift/Util/func.luau | local function truthy()
return true
end
local function noop() end
local function returned(...)
return ...
end
return {
truthy = truthy,
noop = noop,
returned = returned,
}
| 44 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Client/UI/Modern/Components/Packages/_Index/csqrl_sift@0.0.3/sift/Util/init.luau | return {
equalObjects = require(script.equalObjects),
func = require(script.func),
isEmpty = require(script.isEmpty),
}
| 25 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Client/UI/Modern/Components/Packages/_Index/csqrl_sift@0.0.3/sift/Util/isEmpty.luau | --!strict
local _T = require(script.Parent.Parent.Types)
--[=[
@function isEmpty
@within Sift
@since v0.0.1
@param table table -- The table to check.
@return boolean -- Whether or not the table is empty.
Checks whether or not a table is empty.
```lua
local a = {}
local b = { hello = "world" }
local value = isEmpty(a) -- true
local value = isEmpty(b) -- false
```
]=]
local function isEmpty(table: _T.Table): boolean
return next(table) == nil
end
return isEmpty
| 138 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Client/UI/Modern/Components/Packages/_Index/reselim_flipper@2.0.0/flipper/BaseMotor.luau | local RunService = game:GetService("RunService")
local Signal = require(script.Parent.Signal)
local noop = function() end
local BaseMotor = {}
BaseMotor.__index = BaseMotor
function BaseMotor.new()
return setmetatable({
_onStep = Signal.new(),
_onStart = Signal.new(),
_onComplete = Signal.new(),
}, BaseMotor)
end
function BaseMotor:onStep(handler)
return self._onStep:connect(handler)
end
function BaseMotor:onStart(handler)
return self._onStart:connect(handler)
end
function BaseMotor:onComplete(handler)
return self._onComplete:connect(handler)
end
function BaseMotor:start()
if not self._connection then
self._connection = RunService.RenderStepped:Connect(function(deltaTime)
self:step(deltaTime)
end)
end
end
function BaseMotor:stop()
if self._connection then
self._connection:Disconnect()
self._connection = nil
end
end
BaseMotor.destroy = BaseMotor.stop
BaseMotor.step = noop
BaseMotor.getValue = noop
BaseMotor.setGoal = noop
function BaseMotor:__tostring()
return "Motor"
end
return BaseMotor
| 250 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Client/UI/Modern/Components/Packages/_Index/reselim_flipper@2.0.0/flipper/GroupMotor.luau | local BaseMotor = require(script.Parent.BaseMotor)
local SingleMotor = require(script.Parent.SingleMotor)
local isMotor = require(script.Parent.isMotor)
local GroupMotor = setmetatable({}, BaseMotor)
GroupMotor.__index = GroupMotor
local function toMotor(value)
if isMotor(value) then
return value
end
local valueType = typeof(value)
if valueType == "number" then
return SingleMotor.new(value, false)
elseif valueType == "table" then
return GroupMotor.new(value, false)
end
error(("Unable to convert %q to motor; type %s is unsupported"):format(value, valueType), 2)
end
function GroupMotor.new(initialValues, useImplicitConnections)
assert(initialValues, "Missing argument #1: initialValues")
assert(typeof(initialValues) == "table", "initialValues must be a table!")
assert(not initialValues.step, "initialValues contains disallowed property \"step\". Did you mean to put a table of values here?")
local self = setmetatable(BaseMotor.new(), GroupMotor)
if useImplicitConnections ~= nil then
self._useImplicitConnections = useImplicitConnections
else
self._useImplicitConnections = true
end
self._complete = true
self._motors = {}
for key, value in pairs(initialValues) do
self._motors[key] = toMotor(value)
end
return self
end
function GroupMotor:step(deltaTime)
if self._complete then
return true
end
local allMotorsComplete = true
for _, motor in pairs(self._motors) do
local complete = motor:step(deltaTime)
if not complete then
-- If any of the sub-motors are incomplete, the group motor will not be complete either
allMotorsComplete = false
end
end
self._onStep:fire(self:getValue())
if allMotorsComplete then
if self._useImplicitConnections then
self:stop()
end
self._complete = true
self._onComplete:fire()
end
return allMotorsComplete
end
function GroupMotor:setGoal(goals)
assert(not goals.step, "goals contains disallowed property \"step\". Did you mean to put a table of goals here?")
self._complete = false
self._onStart:fire()
for key, goal in pairs(goals) do
local motor = assert(self._motors[key], ("Unknown motor for key %s"):format(key))
motor:setGoal(goal)
end
if self._useImplicitConnections then
self:start()
end
end
function GroupMotor:getValue()
local values = {}
for key, motor in pairs(self._motors) do
values[key] = motor:getValue()
end
return values
end
function GroupMotor:__tostring()
return "Motor(Group)"
end
return GroupMotor
| 604 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Client/UI/Modern/Components/Packages/_Index/reselim_flipper@2.0.0/flipper/Instant.luau | local Instant = {}
Instant.__index = Instant
function Instant.new(targetValue)
return setmetatable({
_targetValue = targetValue,
}, Instant)
end
function Instant:step()
return {
complete = true,
value = self._targetValue,
}
end
return Instant
| 62 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Client/UI/Modern/Components/Packages/_Index/reselim_flipper@2.0.0/flipper/Linear.luau | local Linear = {}
Linear.__index = Linear
function Linear.new(targetValue, options)
assert(targetValue, "Missing argument #1: targetValue")
options = options or {}
return setmetatable({
_targetValue = targetValue,
_velocity = options.velocity or 1,
}, Linear)
end
function Linear:step(state, dt)
local position = state.value
local velocity = self._velocity -- Linear motion ignores the state's velocity
local goal = self._targetValue
local dPos = dt * velocity
local complete = dPos >= math.abs(goal - position)
position = position + dPos * (goal > position and 1 or -1)
if complete then
position = self._targetValue
velocity = 0
end
return {
complete = complete,
value = position,
velocity = velocity,
}
end
return Linear
| 187 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Client/UI/Modern/Components/Packages/_Index/reselim_flipper@2.0.0/flipper/Signal.luau | local Connection = {}
Connection.__index = Connection
function Connection.new(signal, handler)
return setmetatable({
signal = signal,
connected = true,
_handler = handler,
}, Connection)
end
function Connection:disconnect()
if self.connected then
self.connected = false
for index, connection in pairs(self.signal._connections) do
if connection == self then
table.remove(self.signal._connections, index)
return
end
end
end
end
local Signal = {}
Signal.__index = Signal
function Signal.new()
return setmetatable({
_connections = {},
_threads = {},
}, Signal)
end
function Signal:fire(...)
for _, connection in pairs(self._connections) do
connection._handler(...)
end
for _, thread in pairs(self._threads) do
coroutine.resume(thread, ...)
end
self._threads = {}
end
function Signal:connect(handler)
local connection = Connection.new(self, handler)
table.insert(self._connections, connection)
return connection
end
function Signal:wait()
table.insert(self._threads, coroutine.running())
return coroutine.yield()
end
return Signal
| 241 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Client/UI/Modern/Components/Packages/_Index/reselim_flipper@2.0.0/flipper/SingleMotor.luau | local BaseMotor = require(script.Parent.BaseMotor)
local SingleMotor = setmetatable({}, BaseMotor)
SingleMotor.__index = SingleMotor
function SingleMotor.new(initialValue, useImplicitConnections)
assert(initialValue, "Missing argument #1: initialValue")
assert(typeof(initialValue) == "number", "initialValue must be a number!")
local self = setmetatable(BaseMotor.new(), SingleMotor)
if useImplicitConnections ~= nil then
self._useImplicitConnections = useImplicitConnections
else
self._useImplicitConnections = true
end
self._goal = nil
self._state = {
complete = true,
value = initialValue,
}
return self
end
function SingleMotor:step(deltaTime)
if self._state.complete then
return true
end
local newState = self._goal:step(self._state, deltaTime)
self._state = newState
self._onStep:fire(newState.value)
if newState.complete then
if self._useImplicitConnections then
self:stop()
end
self._onComplete:fire()
end
return newState.complete
end
function SingleMotor:getValue()
return self._state.value
end
function SingleMotor:setGoal(goal)
self._state.complete = false
self._goal = goal
self._onStart:fire()
if self._useImplicitConnections then
self:start()
end
end
function SingleMotor:__tostring()
return "Motor(Single)"
end
return SingleMotor
| 306 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Client/UI/Modern/Components/Packages/_Index/reselim_flipper@2.0.0/flipper/init.luau | local Flipper = {
SingleMotor = require(script.SingleMotor),
GroupMotor = require(script.GroupMotor),
Instant = require(script.Instant),
Linear = require(script.Linear),
Spring = require(script.Spring),
isMotor = require(script.isMotor),
}
return Flipper
| 58 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Client/UI/Modern/Components/Packages/_Index/reselim_flipper@2.0.0/flipper/isMotor.luau | local function isMotor(value)
local motorType = tostring(value):match("^Motor%((.+)%)$")
if motorType then
return true, motorType
else
return false
end
end
return isMotor
| 49 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Client/UI/Modern/Components/Packages/_Index/roblox_roact@1.4.4/roact/Binding.luau | local createSignal = require(script.Parent.createSignal)
local Symbol = require(script.Parent.Symbol)
local Type = require(script.Parent.Type)
local config = require(script.Parent.GlobalConfig).get()
local BindingImpl = Symbol.named("BindingImpl")
local BindingInternalApi = {}
local bindingPrototype = {}
function bindingPrototype:getValue()
return BindingInternalApi.getValue(self)
end
function bindingPrototype:map(predicate)
return BindingInternalApi.map(self, predicate)
end
local BindingPublicMeta = {
__index = bindingPrototype,
__tostring = function(self)
return string.format("RoactBinding(%s)", tostring(self:getValue()))
end,
}
function BindingInternalApi.update(binding, newValue)
return binding[BindingImpl].update(newValue)
end
function BindingInternalApi.subscribe(binding, callback)
return binding[BindingImpl].subscribe(callback)
end
function BindingInternalApi.getValue(binding)
return binding[BindingImpl].getValue()
end
function BindingInternalApi.create(initialValue)
local impl = {
value = initialValue,
changeSignal = createSignal(),
}
function impl.subscribe(callback)
return impl.changeSignal:subscribe(callback)
end
function impl.update(newValue)
impl.value = newValue
impl.changeSignal:fire(newValue)
end
function impl.getValue()
return impl.value
end
return setmetatable({
[Type] = Type.Binding,
[BindingImpl] = impl,
}, BindingPublicMeta), impl.update
end
function BindingInternalApi.map(upstreamBinding, predicate)
if config.typeChecks then
assert(Type.of(upstreamBinding) == Type.Binding, "Expected arg #1 to be a binding")
assert(typeof(predicate) == "function", "Expected arg #1 to be a function")
end
local impl = {}
function impl.subscribe(callback)
return BindingInternalApi.subscribe(upstreamBinding, function(newValue)
callback(predicate(newValue))
end)
end
function impl.update(_newValue)
error("Bindings created by Binding:map(fn) cannot be updated directly", 2)
end
function impl.getValue()
return predicate(upstreamBinding:getValue())
end
return setmetatable({
[Type] = Type.Binding,
[BindingImpl] = impl,
}, BindingPublicMeta)
end
function BindingInternalApi.join(upstreamBindings)
if config.typeChecks then
assert(typeof(upstreamBindings) == "table", "Expected arg #1 to be of type table")
for key, value in pairs(upstreamBindings) do
if Type.of(value) ~= Type.Binding then
local message = ("Expected arg #1 to contain only bindings, but key %q had a non-binding value"):format(
tostring(key)
)
error(message, 2)
end
end
end
local impl = {}
local function getValue()
local value = {}
for key, upstream in pairs(upstreamBindings) do
value[key] = upstream:getValue()
end
return value
end
function impl.subscribe(callback)
local disconnects = {}
for key, upstream in pairs(upstreamBindings) do
disconnects[key] = BindingInternalApi.subscribe(upstream, function(_newValue)
callback(getValue())
end)
end
return function()
if disconnects == nil then
return
end
for _, disconnect in pairs(disconnects) do
disconnect()
end
disconnects = nil :: any
end
end
function impl.update(_newValue)
error("Bindings created by joinBindings(...) cannot be updated directly", 2)
end
function impl.getValue()
return getValue()
end
return setmetatable({
[Type] = Type.Binding,
[BindingImpl] = impl,
}, BindingPublicMeta)
end
return BindingInternalApi
| 789 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Client/UI/Modern/Components/Packages/_Index/roblox_roact@1.4.4/roact/ComponentLifecyclePhase.luau | local Symbol = require(script.Parent.Symbol)
local strict = require(script.Parent.strict)
local ComponentLifecyclePhase = strict({
-- Component methods
Init = Symbol.named("init"),
Render = Symbol.named("render"),
ShouldUpdate = Symbol.named("shouldUpdate"),
WillUpdate = Symbol.named("willUpdate"),
DidMount = Symbol.named("didMount"),
DidUpdate = Symbol.named("didUpdate"),
WillUnmount = Symbol.named("willUnmount"),
-- Phases describing reconciliation status
ReconcileChildren = Symbol.named("reconcileChildren"),
Idle = Symbol.named("idle"),
}, "ComponentLifecyclePhase")
return ComponentLifecyclePhase
| 133 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Client/UI/Modern/Components/Packages/_Index/roblox_roact@1.4.4/roact/Config.luau | --[[
Exposes an interface to set global configuration values for Roact.
Configuration can only occur once, and should only be done by an application
using Roact, not a library.
Any keys that aren't recognized will cause errors. Configuration is only
intended for configuring Roact itself, not extensions or libraries.
Configuration is expected to be set immediately after loading Roact. Setting
configuration values after an application starts may produce unpredictable
behavior.
]]
-- Every valid configuration value should be non-nil in this table.
local defaultConfig = {
-- Enables asserts for internal Roact APIs. Useful for debugging Roact itself.
["internalTypeChecks"] = false,
-- Enables stricter type asserts for Roact's public API.
["typeChecks"] = false,
-- Enables storage of `debug.traceback()` values on elements for debugging.
["elementTracing"] = false,
-- Enables validation of component props in stateful components.
["propValidation"] = false,
}
-- Build a list of valid configuration values up for debug messages.
local defaultConfigKeys = {}
for key in pairs(defaultConfig) do
table.insert(defaultConfigKeys, key)
end
local Config = {}
function Config.new()
local self = {}
self._currentConfig = setmetatable({}, {
__index = function(_, key)
local message = ("Invalid global configuration key %q. Valid configuration keys are: %s"):format(
tostring(key),
table.concat(defaultConfigKeys, ", ")
)
error(message, 3)
end,
})
-- We manually bind these methods here so that the Config's methods can be
-- used without passing in self, since they eventually get exposed on the
-- root Roact object.
self.set = function(...)
return Config.set(self, ...)
end
self.get = function(...)
return Config.get(self, ...)
end
self.scoped = function(...)
return Config.scoped(self, ...)
end
self.set(defaultConfig)
return self
end
function Config:set(configValues)
-- Validate values without changing any configuration.
-- We only want to apply this configuration if it's valid!
for key, value in pairs(configValues) do
if defaultConfig[key] == nil then
local message = ("Invalid global configuration key %q (type %s). Valid configuration keys are: %s"):format(
tostring(key),
typeof(key),
table.concat(defaultConfigKeys, ", ")
)
error(message, 3)
end
-- Right now, all configuration values must be boolean.
if typeof(value) ~= "boolean" then
local message = (
"Invalid value %q (type %s) for global configuration key %q. Valid values are: true, false"
):format(tostring(value), typeof(value), tostring(key))
error(message, 3)
end
self._currentConfig[key] = value
end
end
function Config:get()
return self._currentConfig
end
function Config:scoped(configValues, callback)
local previousValues = {}
for key, value in pairs(self._currentConfig) do
previousValues[key] = value
end
self.set(configValues)
local success, result = pcall(callback)
self.set(previousValues)
assert(success, result)
end
return Config
| 703 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Client/UI/Modern/Components/Packages/_Index/roblox_roact@1.4.4/roact/ElementKind.luau | --[[
Contains markers for annotating the type of an element.
Use `ElementKind` as a key, and values from it as the value.
local element = {
[ElementKind] = ElementKind.Host,
}
]]
local Symbol = require(script.Parent.Symbol)
local strict = require(script.Parent.strict)
local Portal = require(script.Parent.Portal)
local ElementKind = newproxy(true)
local ElementKindInternal = {
Portal = Symbol.named("Portal"),
Host = Symbol.named("Host"),
Function = Symbol.named("Function"),
Stateful = Symbol.named("Stateful"),
Fragment = Symbol.named("Fragment"),
}
function ElementKindInternal.of(value)
if typeof(value) ~= "table" then
return nil
end
return value[ElementKind]
end
local componentTypesToKinds = {
["string"] = ElementKindInternal.Host,
["function"] = ElementKindInternal.Function,
["table"] = ElementKindInternal.Stateful,
}
function ElementKindInternal.fromComponent(component)
if component == Portal then
return ElementKind.Portal
else
return componentTypesToKinds[typeof(component)]
end
end
getmetatable(ElementKind).__index = ElementKindInternal
strict(ElementKindInternal, "ElementKind")
return ElementKind
| 264 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Client/UI/Modern/Components/Packages/_Index/roblox_roact@1.4.4/roact/GlobalConfig.luau | --[[
Exposes a single instance of a configuration as Roact's GlobalConfig.
]]
local Config = require(script.Parent.Config)
return Config.new()
| 31 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Client/UI/Modern/Components/Packages/_Index/roblox_roact@1.4.4/roact/Logging.luau | --[[
Centralized place to handle logging. Lets us:
- Unit test log output via `Logging.capture`
- Disable verbose log messages when not debugging Roact
This should be broken out into a separate library with the addition of
scoping and logging configuration.
]]
-- Determines whether log messages will go to stdout/stderr
local outputEnabled = true
-- A set of LogInfo objects that should have messages inserted into them.
-- This is a set so that nested calls to Logging.capture will behave.
local collectors = {}
-- A set of all stack traces that have called warnOnce.
local onceUsedLocations = {}
--[[
Indent a potentially multi-line string with the given number of tabs, in
addition to any indentation the string already has.
]]
local function indent(source, indentLevel)
local indentString = ("\t"):rep(indentLevel)
return indentString .. source:gsub("\n", "\n" .. indentString)
end
--[[
Indents a list of strings and then concatenates them together with newlines
into a single string.
]]
local function indentLines(lines, indentLevel)
local outputBuffer = {}
for _, line in ipairs(lines) do
table.insert(outputBuffer, indent(line, indentLevel))
end
return table.concat(outputBuffer, "\n")
end
local logInfoMetatable = {}
--[[
Automatic coercion to strings for LogInfo objects to enable debugging them
more easily.
]]
function logInfoMetatable:__tostring()
local outputBuffer = { "LogInfo {" }
local errorCount = #self.errors
local warningCount = #self.warnings
local infosCount = #self.infos
if errorCount + warningCount + infosCount == 0 then
table.insert(outputBuffer, "\t(no messages)")
end
if errorCount > 0 then
table.insert(outputBuffer, ("\tErrors (%d) {"):format(errorCount))
table.insert(outputBuffer, indentLines(self.errors, 2))
table.insert(outputBuffer, "\t}")
end
if warningCount > 0 then
table.insert(outputBuffer, ("\tWarnings (%d) {"):format(warningCount))
table.insert(outputBuffer, indentLines(self.warnings, 2))
table.insert(outputBuffer, "\t}")
end
if infosCount > 0 then
table.insert(outputBuffer, ("\tInfos (%d) {"):format(infosCount))
table.insert(outputBuffer, indentLines(self.infos, 2))
table.insert(outputBuffer, "\t}")
end
table.insert(outputBuffer, "}")
return table.concat(outputBuffer, "\n")
end
local function createLogInfo()
local logInfo = {
errors = {},
warnings = {},
infos = {},
}
setmetatable(logInfo, logInfoMetatable)
return logInfo
end
local Logging = {}
--[[
Invokes `callback`, capturing all output that happens during its execution.
Output will not go to stdout or stderr and will instead be put into a
LogInfo object that is returned. If `callback` throws, the error will be
bubbled up to the caller of `Logging.capture`.
]]
function Logging.capture(callback)
local collector = createLogInfo()
local wasOutputEnabled = outputEnabled
outputEnabled = false
collectors[collector] = true
local success, result = pcall(callback)
collectors[collector] = nil
outputEnabled = wasOutputEnabled
assert(success, result)
return collector
end
--[[
Issues a warning with an automatically attached stack trace.
]]
function Logging.warn(messageTemplate, ...)
local message = messageTemplate:format(...)
for collector in pairs(collectors) do
table.insert(collector.warnings, message)
end
-- debug.traceback inserts a leading newline, so we trim it here
local trace = debug.traceback("", 2):sub(2)
local fullMessage = ("%s\n%s"):format(message, indent(trace, 1))
if outputEnabled then
warn(fullMessage)
end
end
--[[
Issues a warning like `Logging.warn`, but only outputs once per call site.
This is useful for marking deprecated functions that might be called a lot;
using `warnOnce` instead of `warn` will reduce output noise while still
correctly marking all call sites.
]]
function Logging.warnOnce(messageTemplate, ...)
local trace = debug.traceback()
if onceUsedLocations[trace] then
return
end
onceUsedLocations[trace] = true
Logging.warn(messageTemplate, ...)
end
return Logging
| 950 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Client/UI/Modern/Components/Packages/_Index/roblox_roact@1.4.4/roact/None.luau | local Symbol = require(script.Parent.Symbol)
-- Marker used to specify that the value is nothing, because nil cannot be
-- stored in tables.
local None = Symbol.named("None")
return None
| 40 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Client/UI/Modern/Components/Packages/_Index/roblox_roact@1.4.4/roact/NoopRenderer.luau | --[[
Reference renderer intended for use in tests as well as for documenting the
minimum required interface for a Roact renderer.
]]
local NoopRenderer = {}
function NoopRenderer.isHostObject(target)
-- Attempting to use NoopRenderer to target a Roblox instance is almost
-- certainly a mistake.
return target == nil
end
function NoopRenderer.mountHostNode(_reconciler, _node) end
function NoopRenderer.unmountHostNode(_reconciler, _node) end
function NoopRenderer.updateHostNode(_reconciler, node, _newElement)
return node
end
return NoopRenderer
| 137 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Client/UI/Modern/Components/Packages/_Index/roblox_roact@1.4.4/roact/PropMarkers/Change.luau | --[[
Change is used to generate special prop keys that can be used to connect to
GetPropertyChangedSignal.
Generally, Change is indexed by a Roblox property name:
Roact.createElement("TextBox", {
[Roact.Change.Text] = function(rbx)
print("The TextBox", rbx, "changed text to", rbx.Text)
end,
})
]]
local Type = require(script.Parent.Parent.Type)
local Change = {}
local changeMetatable = {
__tostring = function(self)
return ("RoactHostChangeEvent(%s)"):format(self.name)
end,
}
setmetatable(Change, {
__index = function(_self, propertyName)
local changeListener = {
[Type] = Type.HostChangeEvent,
name = propertyName,
}
setmetatable(changeListener, changeMetatable)
Change[propertyName] = changeListener
return changeListener
end,
})
return Change
| 199 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Client/UI/Modern/Components/Packages/_Index/roblox_roact@1.4.4/roact/PropMarkers/Children.luau | local Symbol = require(script.Parent.Parent.Symbol)
local Children = Symbol.named("Children")
return Children
| 20 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Client/UI/Modern/Components/Packages/_Index/roblox_roact@1.4.4/roact/PropMarkers/Event.luau | --[[
Index into `Event` to get a prop key for attaching to an event on a Roblox
Instance.
Example:
Roact.createElement("TextButton", {
Text = "Hello, world!",
[Roact.Event.MouseButton1Click] = function(rbx)
print("Clicked", rbx)
end
})
]]
local Type = require(script.Parent.Parent.Type)
local Event = {}
local eventMetatable = {
__tostring = function(self)
return ("RoactHostEvent(%s)"):format(self.name)
end,
}
setmetatable(Event, {
__index = function(_self, eventName)
local event = {
[Type] = Type.HostEvent,
name = eventName,
}
setmetatable(event, eventMetatable)
Event[eventName] = event
return event
end,
})
return Event
| 189 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Client/UI/Modern/Components/Packages/_Index/roblox_roact@1.4.4/roact/PureComponent.luau | --[[
A version of Component with a `shouldUpdate` method that forces the
resulting component to be pure.
]]
local Component = require(script.Parent.Component)
local PureComponent = Component:extend("PureComponent")
-- When extend()ing a component, you don't get an extend method.
-- This is to promote composition over inheritance.
-- PureComponent is an exception to this rule.
PureComponent.extend = Component.extend
function PureComponent:shouldUpdate(newProps, newState)
-- In a vast majority of cases, if state updated, something has updated.
-- We don't bother checking in this case.
if newState ~= self.state then
return true
end
if newProps == self.props then
return false
end
for key, value in pairs(newProps) do
if self.props[key] ~= value then
return true
end
end
for key, value in pairs(self.props) do
if newProps[key] ~= value then
return true
end
end
return false
end
return PureComponent
| 217 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Client/UI/Modern/Components/Packages/_Index/roblox_roact@1.4.4/roact/RobloxRenderer.luau | --[[
Renderer that deals in terms of Roblox Instances. This is the most
well-supported renderer after NoopRenderer and is currently the only
renderer that does anything.
]]
local Binding = require(script.Parent.Binding)
local Children = require(script.Parent.PropMarkers.Children)
local ElementKind = require(script.Parent.ElementKind)
local SingleEventManager = require(script.Parent.SingleEventManager)
local getDefaultInstanceProperty = require(script.Parent.getDefaultInstanceProperty)
local Ref = require(script.Parent.PropMarkers.Ref)
local Type = require(script.Parent.Type)
local internalAssert = require(script.Parent.internalAssert)
local config = require(script.Parent.GlobalConfig).get()
local applyPropsError = [[
Error applying props:
%s
In element:
%s
]]
local updatePropsError = [[
Error updating props:
%s
In element:
%s
]]
local function identity(...)
return ...
end
local function applyRef(ref, newHostObject)
if ref == nil then
return
end
if typeof(ref) == "function" then
ref(newHostObject)
elseif Type.of(ref) == Type.Binding then
Binding.update(ref, newHostObject)
else
-- TODO (#197): Better error message
error(("Invalid ref: Expected type Binding but got %s"):format(typeof(ref)))
end
end
local function setRobloxInstanceProperty(hostObject, key, newValue)
if newValue == nil then
local hostClass = hostObject.ClassName
local _, defaultValue = getDefaultInstanceProperty(hostClass, key)
newValue = defaultValue
end
-- Assign the new value to the object
hostObject[key] = newValue
return
end
local function removeBinding(virtualNode, key)
local disconnect = virtualNode.bindings[key]
disconnect()
virtualNode.bindings[key] = nil
end
local function attachBinding(virtualNode, key, newBinding)
local function updateBoundProperty(newValue)
local success, errorMessage = xpcall(function()
setRobloxInstanceProperty(virtualNode.hostObject, key, newValue)
end, identity)
if not success then
local source = virtualNode.currentElement.source
if source == nil then
source = "<enable element tracebacks>"
end
local fullMessage = updatePropsError:format(errorMessage, source)
error(fullMessage, 0)
end
end
if virtualNode.bindings == nil then
virtualNode.bindings = {}
end
virtualNode.bindings[key] = Binding.subscribe(newBinding, updateBoundProperty)
updateBoundProperty(newBinding:getValue())
end
local function detachAllBindings(virtualNode)
if virtualNode.bindings ~= nil then
for _, disconnect in pairs(virtualNode.bindings) do
disconnect()
end
virtualNode.bindings = nil
end
end
local function applyProp(virtualNode, key, newValue, oldValue)
if newValue == oldValue then
return
end
if key == Ref or key == Children then
-- Refs and children are handled in a separate pass
return
end
local internalKeyType = Type.of(key)
if internalKeyType == Type.HostEvent or internalKeyType == Type.HostChangeEvent then
if virtualNode.eventManager == nil then
virtualNode.eventManager = SingleEventManager.new(virtualNode.hostObject)
end
local eventName = key.name
if internalKeyType == Type.HostChangeEvent then
virtualNode.eventManager:connectPropertyChange(eventName, newValue)
else
virtualNode.eventManager:connectEvent(eventName, newValue)
end
return
end
local newIsBinding = Type.of(newValue) == Type.Binding
local oldIsBinding = Type.of(oldValue) == Type.Binding
if oldIsBinding then
removeBinding(virtualNode, key)
end
if newIsBinding then
attachBinding(virtualNode, key, newValue)
else
setRobloxInstanceProperty(virtualNode.hostObject, key, newValue)
end
end
local function applyProps(virtualNode, props)
for propKey, value in pairs(props) do
applyProp(virtualNode, propKey, value, nil)
end
end
local function updateProps(virtualNode, oldProps, newProps)
-- Apply props that were added or updated
for propKey, newValue in pairs(newProps) do
local oldValue = oldProps[propKey]
applyProp(virtualNode, propKey, newValue, oldValue)
end
-- Clean up props that were removed
for propKey, oldValue in pairs(oldProps) do
local newValue = newProps[propKey]
if newValue == nil then
applyProp(virtualNode, propKey, nil, oldValue)
end
end
end
local RobloxRenderer = {}
function RobloxRenderer.isHostObject(target)
return typeof(target) == "Instance"
end
function RobloxRenderer.mountHostNode(reconciler, virtualNode)
local element = virtualNode.currentElement
local hostParent = virtualNode.hostParent
local hostKey = virtualNode.hostKey
if config.internalTypeChecks then
internalAssert(ElementKind.of(element) == ElementKind.Host, "Element at given node is not a host Element")
end
if config.typeChecks then
assert(element.props.Name == nil, "Name can not be specified as a prop to a host component in Roact.")
assert(element.props.Parent == nil, "Parent can not be specified as a prop to a host component in Roact.")
end
local instance = Instance.new(element.component)
virtualNode.hostObject = instance
local success, errorMessage = xpcall(function()
applyProps(virtualNode, element.props)
end, identity)
if not success then
local source = element.source
if source == nil then
source = "<enable element tracebacks>"
end
local fullMessage = applyPropsError:format(errorMessage, source)
error(fullMessage, 0)
end
instance.Name = tostring(hostKey)
local children = element.props[Children]
if children ~= nil then
reconciler.updateVirtualNodeWithChildren(virtualNode, virtualNode.hostObject, children)
end
instance.Parent = hostParent
virtualNode.hostObject = instance
applyRef(element.props[Ref], instance)
if virtualNode.eventManager ~= nil then
virtualNode.eventManager:resume()
end
end
function RobloxRenderer.unmountHostNode(reconciler, virtualNode)
local element = virtualNode.currentElement
applyRef(element.props[Ref], nil)
for _, childNode in pairs(virtualNode.children) do
reconciler.unmountVirtualNode(childNode)
end
detachAllBindings(virtualNode)
virtualNode.hostObject:Destroy()
end
function RobloxRenderer.updateHostNode(reconciler, virtualNode, newElement)
local oldProps = virtualNode.currentElement.props
local newProps = newElement.props
if virtualNode.eventManager ~= nil then
virtualNode.eventManager:suspend()
end
-- If refs changed, detach the old ref and attach the new one
if oldProps[Ref] ~= newProps[Ref] then
applyRef(oldProps[Ref], nil)
applyRef(newProps[Ref], virtualNode.hostObject)
end
local success, errorMessage = xpcall(function()
updateProps(virtualNode, oldProps, newProps)
end, identity)
if not success then
local source = newElement.source
if source == nil then
source = "<enable element tracebacks>"
end
local fullMessage = updatePropsError:format(errorMessage, source)
error(fullMessage, 0)
end
local children = newElement.props[Children]
if children ~= nil or oldProps[Children] ~= nil then
reconciler.updateVirtualNodeWithChildren(virtualNode, virtualNode.hostObject, children)
end
if virtualNode.eventManager ~= nil then
virtualNode.eventManager:resume()
end
return virtualNode
end
return RobloxRenderer
| 1,669 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Client/UI/Modern/Components/Packages/_Index/roblox_roact@1.4.4/roact/SingleEventManager.luau | --[[
A manager for a single host virtual node's connected events.
]]
local Logging = require(script.Parent.Logging)
local CHANGE_PREFIX = "Change."
local EventStatus = {
-- No events are processed at all; they're silently discarded
Disabled = "Disabled",
-- Events are stored in a queue; listeners are invoked when the manager is resumed
Suspended = "Suspended",
-- Event listeners are invoked as the events fire
Enabled = "Enabled",
}
local SingleEventManager = {}
SingleEventManager.__index = SingleEventManager
function SingleEventManager.new(instance)
local self = setmetatable({
-- The queue of suspended events
_suspendedEventQueue = {},
-- All the event connections being managed
-- Events are indexed by a string key
_connections = {},
-- All the listeners being managed
-- These are stored distinctly from the connections
-- Connections can have their listeners replaced at runtime
_listeners = {},
-- The suspension status of the manager
-- Managers start disabled and are "resumed" after the initial render
_status = EventStatus.Disabled,
-- If true, the manager is processing queued events right now.
_isResuming = false,
-- The Roblox instance the manager is managing
_instance = instance,
}, SingleEventManager)
return self
end
function SingleEventManager:connectEvent(key, listener)
self:_connect(key, self._instance[key], listener)
end
function SingleEventManager:connectPropertyChange(key, listener)
local success, event = pcall(function()
return self._instance:GetPropertyChangedSignal(key)
end)
if not success then
error(("Cannot get changed signal on property %q: %s"):format(tostring(key), event), 0)
end
self:_connect(CHANGE_PREFIX .. key, event, listener)
end
function SingleEventManager:_connect(eventKey, event, listener)
-- If the listener doesn't exist we can just disconnect the existing connection
if listener == nil then
if self._connections[eventKey] ~= nil then
self._connections[eventKey]:Disconnect()
self._connections[eventKey] = nil
end
self._listeners[eventKey] = nil
else
if self._connections[eventKey] == nil then
self._connections[eventKey] = event:Connect(function(...)
if self._status == EventStatus.Enabled then
self._listeners[eventKey](self._instance, ...)
elseif self._status == EventStatus.Suspended then
-- Store this event invocation to be fired when resume is
-- called.
local argumentCount = select("#", ...)
table.insert(self._suspendedEventQueue, { eventKey, argumentCount, ... })
end
end)
end
self._listeners[eventKey] = listener
end
end
function SingleEventManager:suspend()
self._status = EventStatus.Suspended
end
function SingleEventManager:resume()
-- If we're already resuming events for this instance, trying to resume
-- again would cause a disaster.
if self._isResuming then
return
end
self._isResuming = true
local index = 1
-- More events might be added to the queue when evaluating events, so we
-- need to be careful in order to preserve correct evaluation order.
while index <= #self._suspendedEventQueue do
local eventInvocation = self._suspendedEventQueue[index]
local listener = self._listeners[eventInvocation[1]]
local argumentCount = eventInvocation[2]
-- The event might have been disconnected since suspension started; in
-- this case, we drop the event.
if listener ~= nil then
-- Wrap the listener in a coroutine to catch errors and handle
-- yielding correctly.
local listenerCo = coroutine.create(listener)
local success, result = coroutine.resume(
listenerCo,
self._instance,
unpack(eventInvocation, 3, 2 + argumentCount)
)
-- If the listener threw an error, we log it as a warning, since
-- there's no way to write error text in Roblox Lua without killing
-- our thread!
if not success then
Logging.warn("%s", result)
end
end
index = index + 1
end
self._isResuming = false
self._status = EventStatus.Enabled
self._suspendedEventQueue = {}
end
return SingleEventManager
| 963 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Client/UI/Modern/Components/Packages/_Index/roblox_roact@1.4.4/roact/Symbol.luau | --!strict
--[[
A 'Symbol' is an opaque marker type.
Symbols have the type 'userdata', but when printed to the console, the name
of the symbol is shown.
]]
local Symbol = {}
--[[
Creates a Symbol with the given name.
When printed or coerced to a string, the symbol will turn into the string
given as its name.
]]
function Symbol.named(name)
assert(type(name) == "string", "Symbols must be created using a string name!")
local self = newproxy(true)
local wrappedName = ("Symbol(%s)"):format(name)
getmetatable(self).__tostring = function()
return wrappedName
end
return self
end
return Symbol
| 149 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Client/UI/Modern/Components/Packages/_Index/roblox_roact@1.4.4/roact/Type.luau | --[[
Contains markers for annotating objects with types.
To set the type of an object, use `Type` as a key and the actual marker as
the value:
local foo = {
[Type] = Type.Foo,
}
]]
local Symbol = require(script.Parent.Symbol)
local strict = require(script.Parent.strict)
local Type = newproxy(true)
local TypeInternal = {}
local function addType(name)
TypeInternal[name] = Symbol.named("Roact" .. name)
end
addType("Binding")
addType("Element")
addType("HostChangeEvent")
addType("HostEvent")
addType("StatefulComponentClass")
addType("StatefulComponentInstance")
addType("VirtualNode")
addType("VirtualTree")
function TypeInternal.of(value)
if typeof(value) ~= "table" then
return nil
end
return value[Type]
end
getmetatable(Type).__index = TypeInternal
getmetatable(Type).__tostring = function()
return "RoactType"
end
strict(TypeInternal, "Type")
return Type
| 221 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Client/UI/Modern/Components/Packages/_Index/roblox_roact@1.4.4/roact/assertDeepEqual.luau | --!strict
--[[
A utility used to assert that two objects are value-equal recursively. It
outputs fairly nicely formatted messages to help diagnose why two objects
would be different.
This should only be used in tests.
]]
local function deepEqual(a: any, b: any): (boolean, string?)
if typeof(a) ~= typeof(b) then
local message = ("{1} is of type %s, but {2} is of type %s"):format(typeof(a), typeof(b))
return false, message
end
if typeof(a) == "table" then
local visitedKeys = {}
for key, value in pairs(a) do
visitedKeys[key] = true
local success, innerMessage = deepEqual(value, b[key])
if not success and innerMessage then
local message = innerMessage
:gsub("{1}", ("{1}[%s]"):format(tostring(key)))
:gsub("{2}", ("{2}[%s]"):format(tostring(key)))
return false, message
end
end
for key, value in pairs(b) do
if not visitedKeys[key] then
local success, innerMessage = deepEqual(value, a[key])
if not success and innerMessage then
local message = innerMessage
:gsub("{1}", ("{1}[%s]"):format(tostring(key)))
:gsub("{2}", ("{2}[%s]"):format(tostring(key)))
return false, message
end
end
end
return true, nil
end
if a == b then
return true, nil
end
local message = "{1} ~= {2}"
return false, message
end
local function assertDeepEqual(a, b)
local success, innerMessageTemplate = deepEqual(a, b)
if not success and innerMessageTemplate then
local innerMessage = innerMessageTemplate:gsub("{1}", "first"):gsub("{2}", "second")
local message = ("Values were not deep-equal.\n%s"):format(innerMessage)
error(message, 2)
end
end
return assertDeepEqual
| 466 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Client/UI/Modern/Components/Packages/_Index/roblox_roact@1.4.4/roact/assign.luau | local None = require(script.Parent.None)
--[[
Merges values from zero or more tables onto a target table. If a value is
set to None, it will instead be removed from the table.
This function is identical in functionality to JavaScript's Object.assign.
]]
local function assign(target, ...)
for index = 1, select("#", ...) do
local source = select(index, ...)
if source ~= nil then
for key, value in pairs(source) do
if value == None then
target[key] = nil
else
target[key] = value
end
end
end
end
return target
end
return assign
| 143 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Client/UI/Modern/Components/Packages/_Index/roblox_roact@1.4.4/roact/createContext.luau | local Symbol = require(script.Parent.Symbol)
local createFragment = require(script.Parent.createFragment)
local createSignal = require(script.Parent.createSignal)
local Children = require(script.Parent.PropMarkers.Children)
local Component = require(script.Parent.Component)
--[[
Construct the value that is assigned to Roact's context storage.
]]
local function createContextEntry(currentValue)
return {
value = currentValue,
onUpdate = createSignal(),
}
end
local function createProvider(context)
local Provider = Component:extend("Provider")
function Provider:init(props)
self.contextEntry = createContextEntry(props.value)
self:__addContext(context.key, self.contextEntry)
end
function Provider:willUpdate(nextProps)
-- If the provided value changed, immediately update the context entry.
--
-- During this update, any components that are reachable will receive
-- this updated value at the same time as any props and state updates
-- that are being applied.
if nextProps.value ~= self.props.value then
self.contextEntry.value = nextProps.value
end
end
function Provider:didUpdate(prevProps)
-- If the provided value changed, after we've updated every reachable
-- component, fire a signal to update the rest.
--
-- This signal will notify all context consumers. It's expected that
-- they will compare the last context value they updated with and only
-- trigger an update on themselves if this value is different.
--
-- This codepath will generally only update consumer components that has
-- a component implementing shouldUpdate between them and the provider.
if prevProps.value ~= self.props.value then
self.contextEntry.onUpdate:fire(self.props.value)
end
end
function Provider:render()
return createFragment(self.props[Children])
end
return Provider
end
local function createConsumer(context)
local Consumer = Component:extend("Consumer")
function Consumer.validateProps(props)
if type(props.render) ~= "function" then
return false, "Consumer expects a `render` function"
else
return true
end
end
function Consumer:init(_props)
-- This value may be nil, which indicates that our consumer is not a
-- descendant of a provider for this context item.
self.contextEntry = self:__getContext(context.key)
end
function Consumer:render()
-- Render using the latest available for this context item.
--
-- We don't store this value in state in order to have more fine-grained
-- control over our update behavior.
local value
if self.contextEntry ~= nil then
value = self.contextEntry.value
else
value = context.defaultValue
end
return self.props.render(value)
end
function Consumer:didUpdate()
-- Store the value that we most recently updated with.
--
-- This value is compared in the contextEntry onUpdate hook below.
if self.contextEntry ~= nil then
self.lastValue = self.contextEntry.value
end
end
function Consumer:didMount()
if self.contextEntry ~= nil then
-- When onUpdate is fired, a new value has been made available in
-- this context entry, but we may have already updated in the same
-- update cycle.
--
-- To avoid sending a redundant update, we compare the new value
-- with the last value that we updated with (set in didUpdate) and
-- only update if they differ. This may happen when an update from a
-- provider was blocked by an intermediate component that returned
-- false from shouldUpdate.
self.disconnect = self.contextEntry.onUpdate:subscribe(function(newValue)
if newValue ~= self.lastValue then
-- Trigger a dummy state update.
self:setState({})
end
end)
end
end
function Consumer:willUnmount()
if self.disconnect ~= nil then
self.disconnect()
self.disconnect = nil
end
end
return Consumer
end
local Context = {}
Context.__index = Context
function Context.new(defaultValue)
return setmetatable({
defaultValue = defaultValue,
key = Symbol.named("ContextKey"),
}, Context)
end
function Context:__tostring()
return "RoactContext"
end
local function createContext(defaultValue)
local context = Context.new(defaultValue)
return {
Provider = createProvider(context),
Consumer = createConsumer(context),
}
end
return createContext
| 959 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Client/UI/Modern/Components/Packages/_Index/roblox_roact@1.4.4/roact/createElement.luau | local Children = require(script.Parent.PropMarkers.Children)
local ElementKind = require(script.Parent.ElementKind)
local Logging = require(script.Parent.Logging)
local Type = require(script.Parent.Type)
local config = require(script.Parent.GlobalConfig).get()
local multipleChildrenMessage = [[
The prop `Roact.Children` was defined but was overridden by the third parameter to createElement!
This can happen when a component passes props through to a child element but also uses the `children` argument:
Roact.createElement("Frame", passedProps, {
child = ...
})
Instead, consider using a utility function to merge tables of children together:
local children = mergeTables(passedProps[Roact.Children], {
child = ...
})
local fullProps = mergeTables(passedProps, {
[Roact.Children] = children
})
Roact.createElement("Frame", fullProps)]]
--[[
Creates a new element representing the given component.
Elements are lightweight representations of what a component instance should
look like.
Children is a shorthand for specifying `Roact.Children` as a key inside
props. If specified, the passed `props` table is mutated!
]]
local function createElement(component, props, children)
if config.typeChecks then
assert(component ~= nil, "`component` is required")
assert(typeof(props) == "table" or props == nil, "`props` must be a table or nil")
assert(typeof(children) == "table" or children == nil, "`children` must be a table or nil")
end
if props == nil then
props = {}
end
if children ~= nil then
if props[Children] ~= nil then
Logging.warnOnce(multipleChildrenMessage)
end
props[Children] = children
end
local elementKind = ElementKind.fromComponent(component)
local element = {
[Type] = Type.Element,
[ElementKind] = elementKind,
component = component,
props = props,
}
if config.elementTracing then
-- We trim out the leading newline since there's no way to specify the
-- trace level without also specifying a message.
element.source = debug.traceback("", 2):sub(2)
end
return element
end
return createElement
| 475 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Client/UI/Modern/Components/Packages/_Index/roblox_roact@1.4.4/roact/createFragment.luau | local ElementKind = require(script.Parent.ElementKind)
local Type = require(script.Parent.Type)
local function createFragment(elements)
return {
[Type] = Type.Element,
[ElementKind] = ElementKind.Fragment,
elements = elements,
}
end
return createFragment
| 60 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Client/UI/Modern/Components/Packages/_Index/roblox_roact@1.4.4/roact/createReconciler.luau | --!nonstrict
local Type = require(script.Parent.Type)
local ElementKind = require(script.Parent.ElementKind)
local ElementUtils = require(script.Parent.ElementUtils)
local Children = require(script.Parent.PropMarkers.Children)
local Symbol = require(script.Parent.Symbol)
local internalAssert = require(script.Parent.internalAssert)
local config = require(script.Parent.GlobalConfig).get()
local InternalData = Symbol.named("InternalData")
--[[
The reconciler is the mechanism in Roact that constructs the virtual tree
that later gets turned into concrete objects by the renderer.
Roact's reconciler is constructed with the renderer as an argument, which
enables switching to different renderers for different platforms or
scenarios.
When testing the reconciler itself, it's common to use `NoopRenderer` with
spies replacing some methods. The default (and only) reconciler interface
exposed by Roact right now uses `RobloxRenderer`.
]]
local function createReconciler(renderer)
local reconciler
local mountVirtualNode
local updateVirtualNode
local unmountVirtualNode
--[[
Unmount the given virtualNode, replacing it with a new node described by
the given element.
Preserves host properties, depth, and legacyContext from parent.
]]
local function replaceVirtualNode(virtualNode, newElement)
local hostParent = virtualNode.hostParent
local hostKey = virtualNode.hostKey
local depth = virtualNode.depth
local parent = virtualNode.parent
-- If the node that is being replaced has modified context, we need to
-- use the original *unmodified* context for the new node
-- The `originalContext` field will be nil if the context was unchanged
local context = virtualNode.originalContext or virtualNode.context
local parentLegacyContext = virtualNode.parentLegacyContext
-- If updating this node has caused a component higher up the tree to re-render
-- and updateChildren to be re-entered then this node could already have been
-- unmounted in the previous updateChildren pass.
if not virtualNode.wasUnmounted then
unmountVirtualNode(virtualNode)
end
local newNode = mountVirtualNode(newElement, hostParent, hostKey, context, parentLegacyContext)
-- mountVirtualNode can return nil if the element is a boolean
if newNode ~= nil then
newNode.depth = depth
newNode.parent = parent
end
return newNode
end
--[[
Utility to update the children of a virtual node based on zero or more
updated children given as elements.
]]
local function updateChildren(virtualNode, hostParent, newChildElements)
if config.internalTypeChecks then
internalAssert(Type.of(virtualNode) == Type.VirtualNode, "Expected arg #1 to be of type VirtualNode")
end
virtualNode.updateChildrenCount = virtualNode.updateChildrenCount + 1
local currentUpdateChildrenCount = virtualNode.updateChildrenCount
local removeKeys = {}
-- Changed or removed children
for childKey, childNode in pairs(virtualNode.children) do
local newElement = ElementUtils.getElementByKey(newChildElements, childKey)
local newNode = updateVirtualNode(childNode, newElement)
-- If updating this node has caused a component higher up the tree to re-render
-- and updateChildren to be re-entered for this virtualNode then
-- this result is invalid and needs to be disgarded.
if virtualNode.updateChildrenCount ~= currentUpdateChildrenCount then
if newNode and newNode ~= virtualNode.children[childKey] then
unmountVirtualNode(newNode)
end
return
end
if newNode ~= nil then
virtualNode.children[childKey] = newNode
else
removeKeys[childKey] = true
end
end
for childKey in pairs(removeKeys) do
virtualNode.children[childKey] = nil
end
-- Added children
for childKey, newElement in ElementUtils.iterateElements(newChildElements) do
local concreteKey = childKey
if childKey == ElementUtils.UseParentKey then
concreteKey = virtualNode.hostKey
end
if virtualNode.children[childKey] == nil then
local childNode = mountVirtualNode(
newElement,
hostParent,
concreteKey,
virtualNode.context,
virtualNode.legacyContext
)
-- If updating this node has caused a component higher up the tree to re-render
-- and updateChildren to be re-entered for this virtualNode then
-- this result is invalid and needs to be discarded.
if virtualNode.updateChildrenCount ~= currentUpdateChildrenCount then
if childNode then
unmountVirtualNode(childNode)
end
return
end
-- mountVirtualNode can return nil if the element is a boolean
if childNode ~= nil then
childNode.depth = virtualNode.depth + 1
childNode.parent = virtualNode
virtualNode.children[childKey] = childNode
end
end
end
end
local function updateVirtualNodeWithChildren(virtualNode, hostParent, newChildElements)
updateChildren(virtualNode, hostParent, newChildElements)
end
local function updateVirtualNodeWithRenderResult(virtualNode, hostParent, renderResult)
if Type.of(renderResult) == Type.Element or renderResult == nil or typeof(renderResult) == "boolean" then
updateChildren(virtualNode, hostParent, renderResult)
else
error(
("%s\n%s"):format(
"Component returned invalid children:",
virtualNode.currentElement.source or "<enable element tracebacks>"
),
0
)
end
end
--[[
Unmounts the given virtual node and releases any held resources.
]]
function unmountVirtualNode(virtualNode)
if config.internalTypeChecks then
internalAssert(Type.of(virtualNode) == Type.VirtualNode, "Expected arg #1 to be of type VirtualNode")
end
virtualNode.wasUnmounted = true
local kind = ElementKind.of(virtualNode.currentElement)
-- selene: allow(if_same_then_else)
if kind == ElementKind.Host then
renderer.unmountHostNode(reconciler, virtualNode)
elseif kind == ElementKind.Function then
for _, childNode in pairs(virtualNode.children) do
unmountVirtualNode(childNode)
end
elseif kind == ElementKind.Stateful then
virtualNode.instance:__unmount()
elseif kind == ElementKind.Portal then
for _, childNode in pairs(virtualNode.children) do
unmountVirtualNode(childNode)
end
elseif kind == ElementKind.Fragment then
for _, childNode in pairs(virtualNode.children) do
unmountVirtualNode(childNode)
end
else
error(("Unknown ElementKind %q"):format(tostring(kind)), 2)
end
end
local function updateFunctionVirtualNode(virtualNode, newElement)
local children = newElement.component(newElement.props)
updateVirtualNodeWithRenderResult(virtualNode, virtualNode.hostParent, children)
return virtualNode
end
local function updatePortalVirtualNode(virtualNode, newElement)
local oldElement = virtualNode.currentElement
local oldTargetHostParent = oldElement.props.target
local targetHostParent = newElement.props.target
assert(renderer.isHostObject(targetHostParent), "Expected target to be host object")
if targetHostParent ~= oldTargetHostParent then
return replaceVirtualNode(virtualNode, newElement)
end
local children = newElement.props[Children]
updateVirtualNodeWithChildren(virtualNode, targetHostParent, children)
return virtualNode
end
local function updateFragmentVirtualNode(virtualNode, newElement)
updateVirtualNodeWithChildren(virtualNode, virtualNode.hostParent, newElement.elements)
return virtualNode
end
--[[
Update the given virtual node using a new element describing what it
should transform into.
`updateVirtualNode` will return a new virtual node that should replace
the passed in virtual node. This is because a virtual node can be
updated with an element referencing a different component!
In that case, `updateVirtualNode` will unmount the input virtual node,
mount a new virtual node, and return it in this case, while also issuing
a warning to the user.
]]
function updateVirtualNode(virtualNode, newElement, newState: { [any]: any }?): { [any]: any }?
if config.internalTypeChecks then
internalAssert(Type.of(virtualNode) == Type.VirtualNode, "Expected arg #1 to be of type VirtualNode")
end
if config.typeChecks then
assert(
Type.of(newElement) == Type.Element or typeof(newElement) == "boolean" or newElement == nil,
"Expected arg #2 to be of type Element, boolean, or nil"
)
end
-- If nothing changed, we can skip this update
if virtualNode.currentElement == newElement and newState == nil then
return virtualNode
end
if typeof(newElement) == "boolean" or newElement == nil then
unmountVirtualNode(virtualNode)
return nil
end
if virtualNode.currentElement.component ~= newElement.component then
return replaceVirtualNode(virtualNode, newElement)
end
local kind = ElementKind.of(newElement)
local shouldContinueUpdate = true
if kind == ElementKind.Host then
virtualNode = renderer.updateHostNode(reconciler, virtualNode, newElement)
elseif kind == ElementKind.Function then
virtualNode = updateFunctionVirtualNode(virtualNode, newElement)
elseif kind == ElementKind.Stateful then
shouldContinueUpdate = virtualNode.instance:__update(newElement, newState)
elseif kind == ElementKind.Portal then
virtualNode = updatePortalVirtualNode(virtualNode, newElement)
elseif kind == ElementKind.Fragment then
virtualNode = updateFragmentVirtualNode(virtualNode, newElement)
else
error(("Unknown ElementKind %q"):format(tostring(kind)), 2)
end
-- Stateful components can abort updates via shouldUpdate. If that
-- happens, we should stop doing stuff at this point.
if not shouldContinueUpdate then
return virtualNode
end
virtualNode.currentElement = newElement
return virtualNode
end
--[[
Constructs a new virtual node but not does mount it.
]]
local function createVirtualNode(element, hostParent, hostKey, context, legacyContext)
if config.internalTypeChecks then
internalAssert(
renderer.isHostObject(hostParent) or hostParent == nil,
"Expected arg #2 to be a host object"
)
internalAssert(typeof(context) == "table" or context == nil, "Expected arg #4 to be of type table or nil")
internalAssert(
typeof(legacyContext) == "table" or legacyContext == nil,
"Expected arg #5 to be of type table or nil"
)
end
if config.typeChecks then
assert(hostKey ~= nil, "Expected arg #3 to be non-nil")
assert(
Type.of(element) == Type.Element or typeof(element) == "boolean",
"Expected arg #1 to be of type Element or boolean"
)
end
return {
[Type] = Type.VirtualNode,
currentElement = element,
depth = 1,
parent = nil,
children = {},
hostParent = hostParent,
hostKey = hostKey,
updateChildrenCount = 0,
wasUnmounted = false,
-- Legacy Context API
-- A table of context values inherited from the parent node
legacyContext = legacyContext,
-- A saved copy of the parent context, used when replacing a node
parentLegacyContext = legacyContext,
-- Context API
-- A table of context values inherited from the parent node
context = context or {},
-- A saved copy of the unmodified context; this will be updated when
-- a component adds new context and used when a node is replaced
originalContext = nil,
}
end
local function mountFunctionVirtualNode(virtualNode)
local element = virtualNode.currentElement
local children = element.component(element.props)
updateVirtualNodeWithRenderResult(virtualNode, virtualNode.hostParent, children)
end
local function mountPortalVirtualNode(virtualNode)
local element = virtualNode.currentElement
local targetHostParent = element.props.target
local children = element.props[Children]
assert(renderer.isHostObject(targetHostParent), "Expected target to be host object")
updateVirtualNodeWithChildren(virtualNode, targetHostParent, children)
end
local function mountFragmentVirtualNode(virtualNode)
local element = virtualNode.currentElement
local children = element.elements
updateVirtualNodeWithChildren(virtualNode, virtualNode.hostParent, children)
end
--[[
Constructs a new virtual node and mounts it, but does not place it into
the tree.
]]
function mountVirtualNode(element, hostParent, hostKey, context, legacyContext)
if config.internalTypeChecks then
internalAssert(
renderer.isHostObject(hostParent) or hostParent == nil,
"Expected arg #2 to be a host object"
)
internalAssert(
typeof(legacyContext) == "table" or legacyContext == nil,
"Expected arg #5 to be of type table or nil"
)
end
if config.typeChecks then
assert(hostKey ~= nil, "Expected arg #3 to be non-nil")
assert(
Type.of(element) == Type.Element or typeof(element) == "boolean",
"Expected arg #1 to be of type Element or boolean"
)
end
-- Boolean values render as nil to enable terse conditional rendering.
if typeof(element) == "boolean" then
return nil
end
local kind = ElementKind.of(element)
local virtualNode = createVirtualNode(element, hostParent, hostKey, context, legacyContext)
if kind == ElementKind.Host then
renderer.mountHostNode(reconciler, virtualNode)
elseif kind == ElementKind.Function then
mountFunctionVirtualNode(virtualNode)
elseif kind == ElementKind.Stateful then
element.component:__mount(reconciler, virtualNode)
elseif kind == ElementKind.Portal then
mountPortalVirtualNode(virtualNode)
elseif kind == ElementKind.Fragment then
mountFragmentVirtualNode(virtualNode)
else
error(("Unknown ElementKind %q"):format(tostring(kind)), 2)
end
return virtualNode
end
--[[
Constructs a new Roact virtual tree, constructs a root node for
it, and mounts it.
]]
local function mountVirtualTree(element, hostParent, hostKey)
if config.typeChecks then
assert(Type.of(element) == Type.Element, "Expected arg #1 to be of type Element")
assert(renderer.isHostObject(hostParent) or hostParent == nil, "Expected arg #2 to be a host object")
end
if hostKey == nil then
hostKey = "RoactTree"
end
local tree = {
[Type] = Type.VirtualTree,
[InternalData] = {
-- The root node of the tree, which starts into the hierarchy of
-- Roact component instances.
rootNode = nil,
mounted = true,
},
}
tree[InternalData].rootNode = mountVirtualNode(element, hostParent, hostKey)
return tree
end
--[[
Unmounts the virtual tree, freeing all of its resources.
No further operations should be done on the tree after it's been
unmounted, as indicated by its the `mounted` field.
]]
local function unmountVirtualTree(tree)
local internalData = tree[InternalData]
if config.typeChecks then
assert(Type.of(tree) == Type.VirtualTree, "Expected arg #1 to be a Roact handle")
assert(internalData.mounted, "Cannot unmounted a Roact tree that has already been unmounted")
end
internalData.mounted = false
if internalData.rootNode ~= nil then
unmountVirtualNode(internalData.rootNode)
end
end
--[[
Utility method for updating the root node of a virtual tree given a new
element.
]]
local function updateVirtualTree(tree, newElement)
local internalData = tree[InternalData]
if config.typeChecks then
assert(Type.of(tree) == Type.VirtualTree, "Expected arg #1 to be a Roact handle")
assert(Type.of(newElement) == Type.Element, "Expected arg #2 to be a Roact Element")
end
internalData.rootNode = updateVirtualNode(internalData.rootNode, newElement)
return tree
end
reconciler = {
mountVirtualTree = mountVirtualTree,
unmountVirtualTree = unmountVirtualTree,
updateVirtualTree = updateVirtualTree,
createVirtualNode = createVirtualNode,
mountVirtualNode = mountVirtualNode,
unmountVirtualNode = unmountVirtualNode,
updateVirtualNode = updateVirtualNode,
updateVirtualNodeWithChildren = updateVirtualNodeWithChildren,
updateVirtualNodeWithRenderResult = updateVirtualNodeWithRenderResult,
}
return reconciler
end
return createReconciler
| 3,862 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Client/UI/Modern/Components/Packages/_Index/roblox_roact@1.4.4/roact/createReconcilerCompat.luau | --[[
Contains deprecated methods from Reconciler. Broken out so that removing
this shim is easy -- just delete this file and remove it from init.
]]
local Logging = require(script.Parent.Logging)
local reifyMessage = [[
Roact.reify has been renamed to Roact.mount and will be removed in a future release.
Check the call to Roact.reify at:
]]
local teardownMessage = [[
Roact.teardown has been renamed to Roact.unmount and will be removed in a future release.
Check the call to Roact.teardown at:
]]
local reconcileMessage = [[
Roact.reconcile has been renamed to Roact.update and will be removed in a future release.
Check the call to Roact.reconcile at:
]]
local function createReconcilerCompat(reconciler)
local compat = {}
function compat.reify(...)
Logging.warnOnce(reifyMessage)
return reconciler.mountVirtualTree(...)
end
function compat.teardown(...)
Logging.warnOnce(teardownMessage)
return reconciler.unmountVirtualTree(...)
end
function compat.reconcile(...)
Logging.warnOnce(reconcileMessage)
return reconciler.updateVirtualTree(...)
end
return compat
end
return createReconcilerCompat
| 258 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Client/UI/Modern/Components/Packages/_Index/roblox_roact@1.4.4/roact/createRef.luau | --[[
A ref is nothing more than a binding with a special field 'current'
that maps to the getValue method of the binding
]]
local Binding = require(script.Parent.Binding)
local function createRef()
local binding, _ = Binding.create(nil)
local ref = {}
--[[
A ref is just redirected to a binding via its metatable
]]
setmetatable(ref, {
__index = function(_self, key)
if key == "current" then
return binding:getValue()
else
return binding[key]
end
end,
__newindex = function(_self, key, value)
if key == "current" then
error("Cannot assign to the 'current' property of refs", 2)
end
binding[key] = value
end,
__tostring = function(_self)
return ("RoactRef(%s)"):format(tostring(binding:getValue()))
end,
})
return ref
end
return createRef
| 213 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Client/UI/Modern/Components/Packages/_Index/roblox_roact@1.4.4/roact/createSignal.luau | --[[
This is a simple signal implementation that has a dead-simple API.
local signal = createSignal()
local disconnect = signal:subscribe(function(foo)
print("Cool foo:", foo)
end)
signal:fire("something")
disconnect()
]]
local function createSignal()
local connections = {}
local suspendedConnections = {}
local firing = false
local function subscribe(_self, callback)
assert(typeof(callback) == "function", "Can only subscribe to signals with a function.")
local connection = {
callback = callback,
disconnected = false,
}
-- If the callback is already registered, don't add to the suspendedConnection. Otherwise, this will disable
-- the existing one.
if firing and not connections[callback] then
suspendedConnections[callback] = connection
end
connections[callback] = connection
local function disconnect()
assert(not connection.disconnected, "Listeners can only be disconnected once.")
connection.disconnected = true
connections[callback] = nil
suspendedConnections[callback] = nil
end
return disconnect
end
local function fire(_self, ...)
firing = true
for callback, connection in pairs(connections) do
if not connection.disconnected and not suspendedConnections[callback] then
callback(...)
end
end
firing = false
for callback, _ in pairs(suspendedConnections) do
suspendedConnections[callback] = nil
end
end
return {
subscribe = subscribe,
fire = fire,
}
end
return createSignal
| 343 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Client/UI/Modern/Components/Packages/_Index/roblox_roact@1.4.4/roact/forwardRef.luau | local assign = require(script.Parent.assign)
local None = require(script.Parent.None)
local Ref = require(script.Parent.PropMarkers.Ref)
local config = require(script.Parent.GlobalConfig).get()
local excludeRef = {
[Ref] = None,
}
--[[
Allows forwarding of refs to underlying host components. Accepts a render
callback which accepts props and a ref, and returns an element.
]]
local function forwardRef(render)
if config.typeChecks then
assert(typeof(render) == "function", "Expected arg #1 to be a function")
end
return function(props)
local ref = props[Ref]
local propsWithoutRef = assign({}, props, excludeRef)
return render(propsWithoutRef, ref)
end
end
return forwardRef
| 156 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Client/UI/Modern/Components/Packages/_Index/roblox_roact@1.4.4/roact/getDefaultInstanceProperty.luau | --[[
Attempts to get the default value of a given property on a Roblox instance.
This is used by the reconciler in cases where a prop was previously set on a
primitive component, but is no longer present in a component's new props.
Eventually, Roblox might provide a nicer API to query the default property
of an object without constructing an instance of it.
]]
local Symbol = require(script.Parent.Symbol)
local Nil = Symbol.named("Nil")
local _cachedPropertyValues = {}
local function getDefaultInstanceProperty(className, propertyName)
local classCache = _cachedPropertyValues[className]
if classCache then
local propValue = classCache[propertyName]
-- We have to use a marker here, because Lua doesn't distinguish
-- between 'nil' and 'not in a table'
if propValue == Nil then
return true, nil
end
if propValue ~= nil then
return true, propValue
end
else
classCache = {}
_cachedPropertyValues[className] = classCache
end
local created = Instance.new(className)
local ok, defaultValue = pcall(function()
return created[propertyName]
end)
created:Destroy()
if ok then
if defaultValue == nil then
classCache[propertyName] = Nil
else
classCache[propertyName] = defaultValue
end
end
return ok, defaultValue
end
return getDefaultInstanceProperty
| 303 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Client/UI/Modern/Components/Packages/_Index/roblox_roact@1.4.4/roact/init.luau | --~strict
--[[
Packages up the internals of Roact and exposes a public API for it.
]]
local GlobalConfig = require(script.GlobalConfig)
local createReconciler = require(script.createReconciler)
local createReconcilerCompat = require(script.createReconcilerCompat)
local RobloxRenderer = require(script.RobloxRenderer)
local strict = require(script.strict)
local Binding = require(script.Binding)
local robloxReconciler = createReconciler(RobloxRenderer)
local reconcilerCompat = createReconcilerCompat(robloxReconciler)
local Roact = strict({
Component = require(script.Component),
createElement = require(script.createElement),
createFragment = require(script.createFragment),
oneChild = require(script.oneChild),
PureComponent = require(script.PureComponent),
None = require(script.None),
Portal = require(script.Portal),
createRef = require(script.createRef),
forwardRef = require(script.forwardRef),
createBinding = Binding.create,
joinBindings = Binding.join,
createContext = require(script.createContext),
Change = require(script.PropMarkers.Change),
Children = require(script.PropMarkers.Children),
Event = require(script.PropMarkers.Event),
Ref = require(script.PropMarkers.Ref),
mount = robloxReconciler.mountVirtualTree,
unmount = robloxReconciler.unmountVirtualTree,
update = robloxReconciler.updateVirtualTree,
reify = reconcilerCompat.reify,
teardown = reconcilerCompat.teardown,
reconcile = reconcilerCompat.reconcile,
setGlobalConfig = GlobalConfig.set,
-- APIs that may change in the future without warning
UNSTABLE = {},
})
return Roact
| 349 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Client/UI/Modern/Components/Packages/_Index/roblox_roact@1.4.4/roact/internalAssert.luau | local function internalAssert(condition, message)
if not condition then
error(message .. " (This is probably a bug in Roact!)", 3)
end
end
return internalAssert
| 40 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Client/UI/Modern/Components/Packages/_Index/roblox_roact@1.4.4/roact/oneChild.luau | --[[
Retrieves at most one child from the children passed to a component.
If passed nil or an empty table, will return nil.
Throws an error if passed more than one child.
]]
local function oneChild(children)
if not children then
return nil
end
local key, child = next(children)
if not child then
return nil
end
local after = next(children, key)
if after then
error("Expected at most child, had more than one child.", 2)
end
return child
end
return oneChild
| 118 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Client/UI/Modern/Components/Packages/_Index/sleitnick_signal@1.2.1/signal/init.luau | -- -----------------------------------------------------------------------------
-- Batched Yield-Safe Signal Implementation --
-- This is a Signal class which has effectively identical behavior to a --
-- normal RBXScriptSignal, with the only difference being a couple extra --
-- stack frames at the bottom of the stack trace when an error is thrown. --
-- This implementation caches runner coroutines, so the ability to yield in --
-- the signal handlers comes at minimal extra cost over a naive signal --
-- implementation that either always or never spawns a thread. --
-- --
-- API: --
-- local Signal = require(THIS MODULE) --
-- local sig = Signal.new() --
-- local connection = sig:Connect(function(arg1, arg2, ...) ... end) --
-- sig:Fire(arg1, arg2, ...) --
-- connection:Disconnect() --
-- sig:DisconnectAll() --
-- local arg1, arg2, ... = sig:Wait() --
-- --
-- License: --
-- Licensed under the MIT license. --
-- --
-- Authors: --
-- stravant - July 31st, 2021 - Created the file. --
-- sleitnick - August 3rd, 2021 - Modified for Knit. --
-- -----------------------------------------------------------------------------
-- The currently idle thread to run the next handler on
local freeRunnerThread = nil
-- Function which acquires the currently idle handler runner thread, runs the
-- function fn on it, and then releases the thread, returning it to being the
-- currently idle one.
-- If there was a currently idle runner thread already, that's okay, that old
-- one will just get thrown and eventually GCed.
local function acquireRunnerThreadAndCallEventHandler(fn, ...)
local acquiredRunnerThread = freeRunnerThread
freeRunnerThread = nil
fn(...)
-- The handler finished running, this runner thread is free again.
freeRunnerThread = acquiredRunnerThread
end
-- Coroutine runner that we create coroutines of. The coroutine can be
-- repeatedly resumed with functions to run followed by the argument to run
-- them with.
local function runEventHandlerInFreeThread(...)
acquireRunnerThreadAndCallEventHandler(...)
while true do
acquireRunnerThreadAndCallEventHandler(coroutine.yield())
end
end
--[=[
@within Signal
@interface SignalConnection
.Connected boolean
.Disconnect (SignalConnection) -> ()
Represents a connection to a signal.
```lua
local connection = signal:Connect(function() end)
print(connection.Connected) --> true
connection:Disconnect()
print(connection.Connected) --> false
```
]=]
-- Connection class
local Connection = {}
Connection.__index = Connection
function Connection.new(signal, fn)
return setmetatable({
Connected = true,
_signal = signal,
_fn = fn,
_next = false,
}, Connection)
end
function Connection:Disconnect()
if not self.Connected then
return
end
self.Connected = false
-- Unhook the node, but DON'T clear it. That way any fire calls that are
-- currently sitting on this node will be able to iterate forwards off of
-- it, but any subsequent fire calls will not hit it, and it will be GCed
-- when no more fire calls are sitting on it.
if self._signal._handlerListHead == self then
self._signal._handlerListHead = self._next
else
local prev = self._signal._handlerListHead
while prev and prev._next ~= self do
prev = prev._next
end
if prev then
prev._next = self._next
end
end
end
Connection.Destroy = Connection.Disconnect
-- Make Connection strict
setmetatable(Connection, {
__index = function(_tb, key)
error(("Attempt to get Connection::%s (not a valid member)"):format(tostring(key)), 2)
end,
__newindex = function(_tb, key, _value)
error(("Attempt to set Connection::%s (not a valid member)"):format(tostring(key)), 2)
end,
})
--[=[
@within Signal
@type ConnectionFn (...any) -> ()
A function connected to a signal.
]=]
--[=[
@class Signal
Signals allow events to be dispatched and handled.
For example:
```lua
local signal = Signal.new()
signal:Connect(function(msg)
print("Got message:", msg)
end)
signal:Fire("Hello world!")
```
]=]
local Signal = {}
Signal.__index = Signal
--[=[
Constructs a new Signal
@return Signal
]=]
function Signal.new()
local self = setmetatable({
_handlerListHead = false,
_proxyHandler = nil,
}, Signal)
return self
end
--[=[
Constructs a new Signal that wraps around an RBXScriptSignal.
@param rbxScriptSignal RBXScriptSignal -- Existing RBXScriptSignal to wrap
@return Signal
For example:
```lua
local signal = Signal.Wrap(workspace.ChildAdded)
signal:Connect(function(part) print(part.Name .. " added") end)
Instance.new("Part").Parent = workspace
```
]=]
function Signal.Wrap(rbxScriptSignal)
assert(
typeof(rbxScriptSignal) == "RBXScriptSignal",
"Argument #1 to Signal.Wrap must be a RBXScriptSignal; got " .. typeof(rbxScriptSignal)
)
local signal = Signal.new()
signal._proxyHandler = rbxScriptSignal:Connect(function(...)
signal:Fire(...)
end)
return signal
end
--[=[
Checks if the given object is a Signal.
@param obj any -- Object to check
@return boolean -- `true` if the object is a Signal.
]=]
function Signal.Is(obj)
return type(obj) == "table" and getmetatable(obj) == Signal
end
--[=[
@param fn ConnectionFn
@return SignalConnection
Connects a function to the signal, which will be called anytime the signal is fired.
```lua
signal:Connect(function(msg, num)
print(msg, num)
end)
signal:Fire("Hello", 25)
```
]=]
function Signal:Connect(fn)
local connection = Connection.new(self, fn)
if self._handlerListHead then
connection._next = self._handlerListHead
self._handlerListHead = connection
else
self._handlerListHead = connection
end
return connection
end
--[=[
@param fn ConnectionFn
@return SignalConnection
Connects a function to the signal, which will be called the next time the signal fires. Once
the connection is triggered, it will disconnect itself.
```lua
signal:ConnectOnce(function(msg, num)
print(msg, num)
end)
signal:Fire("Hello", 25)
signal:Fire("This message will not go through", 10)
```
]=]
function Signal:ConnectOnce(fn)
local connection
local done = false
connection = self:Connect(function(...)
if done then
return
end
done = true
connection:Disconnect()
fn(...)
end)
return connection
end
function Signal:GetConnections()
local items = {}
local item = self._handlerListHead
while item do
table.insert(items, item)
item = item._next
end
return items
end
-- Disconnect all handlers. Since we use a linked list it suffices to clear the
-- reference to the head handler.
--[=[
Disconnects all connections from the signal.
```lua
signal:DisconnectAll()
```
]=]
function Signal:DisconnectAll()
local item = self._handlerListHead
while item do
item.Connected = false
item = item._next
end
self._handlerListHead = false
end
-- Signal:Fire(...) implemented by running the handler functions on the
-- coRunnerThread, and any time the resulting thread yielded without returning
-- to us, that means that it yielded to the Roblox scheduler and has been taken
-- over by Roblox scheduling, meaning we have to make a new coroutine runner.
--[=[
@param ... any
Fire the signal, which will call all of the connected functions with the given arguments.
```lua
signal:Fire("Hello")
-- Any number of arguments can be fired:
signal:Fire("Hello", 32, {Test = "Test"}, true)
```
]=]
function Signal:Fire(...)
local item = self._handlerListHead
while item do
if item.Connected then
if not freeRunnerThread then
freeRunnerThread = coroutine.create(runEventHandlerInFreeThread)
end
task.spawn(freeRunnerThread, item._fn, ...)
end
item = item._next
end
end
--[=[
@param ... any
Same as `Fire`, but uses `task.defer` internally & doesn't take advantage of thread reuse.
```lua
signal:FireDeferred("Hello")
```
]=]
function Signal:FireDeferred(...)
local item = self._handlerListHead
while item do
task.defer(item._fn, ...)
item = item._next
end
end
--[=[
@return ... any
@yields
Yields the current thread until the signal is fired, and returns the arguments fired from the signal.
Yielding the current thread is not always desirable. If the desire is to only capture the next event
fired, using `ConnectOnce` might be a better solution.
```lua
task.spawn(function()
local msg, num = signal:Wait()
print(msg, num) --> "Hello", 32
end)
signal:Fire("Hello", 32)
```
]=]
function Signal:Wait()
local waitingCoroutine = coroutine.running()
local connection
local done = false
connection = self:Connect(function(...)
if done then
return
end
done = true
connection:Disconnect()
task.spawn(waitingCoroutine, ...)
end)
return coroutine.yield()
end
--[=[
Cleans up the signal.
Technically, this is only necessary if the signal is created using
`Signal.Wrap`. Connections should be properly GC'd once the signal
is no longer referenced anywhere. However, it is still good practice
to include ways to strictly clean up resources. Calling `Destroy`
on a signal will also disconnect all connections immediately.
```lua
signal:Destroy()
```
]=]
function Signal:Destroy()
self:DisconnectAll()
local proxyHandler = rawget(self, "_proxyHandler")
if proxyHandler then
proxyHandler:Disconnect()
end
end
-- Make signal strict
setmetatable(Signal, {
__index = function(_tb, key)
error(("Attempt to get Signal::%s (not a valid member)"):format(tostring(key)), 2)
end,
__newindex = function(_tb, key, _value)
error(("Attempt to set Signal::%s (not a valid member)"):format(tostring(key)), 2)
end,
})
return Signal
| 2,360 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Client/UI/Modern/Components/Packages/t.luau | -- t: a runtime typechecker for Roblox
local t = {}
function t.type(typeName)
return function(value)
local valueType = type(value)
if valueType == typeName then
return true
else
return false, string.format("%s expected, got %s", typeName, valueType)
end
end
end
function t.typeof(typeName)
return function(value)
local valueType = typeof(value)
if valueType == typeName then
return true
else
return false, string.format("%s expected, got %s", typeName, valueType)
end
end
end
--[[**
matches any type except nil
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
function t.any(value)
if value ~= nil then
return true
else
return false, "any expected, got nil"
end
end
--Lua primitives
--[[**
ensures Lua primitive boolean type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.boolean = t.typeof("boolean")
--[[**
ensures Lua primitive thread type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.thread = t.typeof("thread")
--[[**
ensures Lua primitive callback type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.callback = t.typeof("function")
t["function"] = t.callback
--[[**
ensures Lua primitive none type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.none = t.typeof("nil")
t["nil"] = t.none
--[[**
ensures Lua primitive string type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.string = t.typeof("string")
--[[**
ensures Lua primitive table type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.table = t.typeof("table")
--[[**
ensures Lua primitive userdata type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.userdata = t.type("userdata")
--[[**
ensures value is a number and non-NaN
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
function t.number(value)
local valueType = typeof(value)
if valueType == "number" then
if value == value then
return true
else
return false, "unexpected NaN value"
end
else
return false, string.format("number expected, got %s", valueType)
end
end
--[[**
ensures value is NaN
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
function t.nan(value)
local valueType = typeof(value)
if valueType == "number" then
if value ~= value then
return true
else
return false, "unexpected non-NaN value"
end
else
return false, string.format("number expected, got %s", valueType)
end
end
-- roblox types
--[[**
ensures Roblox Axes type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.Axes = t.typeof("Axes")
--[[**
ensures Roblox BrickColor type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.BrickColor = t.typeof("BrickColor")
--[[**
ensures Roblox CatalogSearchParams type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.CatalogSearchParams = t.typeof("CatalogSearchParams")
--[[**
ensures Roblox CFrame type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.CFrame = t.typeof("CFrame")
--[[**
ensures Roblox Color3 type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.Color3 = t.typeof("Color3")
--[[**
ensures Roblox ColorSequence type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.ColorSequence = t.typeof("ColorSequence")
--[[**
ensures Roblox ColorSequenceKeypoint type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.ColorSequenceKeypoint = t.typeof("ColorSequenceKeypoint")
--[[**
ensures Roblox DateTime type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.DateTime = t.typeof("DateTime")
--[[**
ensures Roblox DockWidgetPluginGuiInfo type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.DockWidgetPluginGuiInfo = t.typeof("DockWidgetPluginGuiInfo")
--[[**
ensures Roblox Enum type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.Enum = t.typeof("Enum")
--[[**
ensures Roblox EnumItem type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.EnumItem = t.typeof("EnumItem")
--[[**
ensures Roblox Enums type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.Enums = t.typeof("Enums")
--[[**
ensures Roblox Faces type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.Faces = t.typeof("Faces")
--[[**
ensures Roblox Instance type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.Instance = t.typeof("Instance")
--[[**
ensures Roblox NumberRange type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.NumberRange = t.typeof("NumberRange")
--[[**
ensures Roblox NumberSequence type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.NumberSequence = t.typeof("NumberSequence")
--[[**
ensures Roblox NumberSequenceKeypoint type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.NumberSequenceKeypoint = t.typeof("NumberSequenceKeypoint")
--[[**
ensures Roblox PathWaypoint type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.PathWaypoint = t.typeof("PathWaypoint")
--[[**
ensures Roblox PhysicalProperties type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.PhysicalProperties = t.typeof("PhysicalProperties")
--[[**
ensures Roblox Random type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.Random = t.typeof("Random")
--[[**
ensures Roblox Ray type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.Ray = t.typeof("Ray")
--[[**
ensures Roblox RaycastParams type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.RaycastParams = t.typeof("RaycastParams")
--[[**
ensures Roblox RaycastResult type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.RaycastResult = t.typeof("RaycastResult")
--[[**
ensures Roblox RBXScriptConnection type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.RBXScriptConnection = t.typeof("RBXScriptConnection")
--[[**
ensures Roblox RBXScriptSignal type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.RBXScriptSignal = t.typeof("RBXScriptSignal")
--[[**
ensures Roblox Rect type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.Rect = t.typeof("Rect")
--[[**
ensures Roblox Region3 type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.Region3 = t.typeof("Region3")
--[[**
ensures Roblox Region3int16 type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.Region3int16 = t.typeof("Region3int16")
--[[**
ensures Roblox TweenInfo type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.TweenInfo = t.typeof("TweenInfo")
--[[**
ensures Roblox UDim type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.UDim = t.typeof("UDim")
--[[**
ensures Roblox UDim2 type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.UDim2 = t.typeof("UDim2")
--[[**
ensures Roblox Vector2 type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.Vector2 = t.typeof("Vector2")
--[[**
ensures Roblox Vector2int16 type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.Vector2int16 = t.typeof("Vector2int16")
--[[**
ensures Roblox Vector3 type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.Vector3 = t.typeof("Vector3")
--[[**
ensures Roblox Vector3int16 type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.Vector3int16 = t.typeof("Vector3int16")
--[[**
ensures value is a given literal value
@param literal The literal to use
@returns A function that will return true iff the condition is passed
**--]]
function t.literal(...)
local size = select("#", ...)
if size == 1 then
local literal = ...
return function(value)
if value ~= literal then
return false, string.format("expected %s, got %s", tostring(literal), tostring(value))
end
return true
end
else
local literals = {}
for i = 1, size do
local value = select(i, ...)
literals[i] = t.literal(value)
end
return t.union(table.unpack(literals, 1, size))
end
end
--[[**
DEPRECATED
Please use t.literal
**--]]
t.exactly = t.literal
--[[**
Returns a t.union of each key in the table as a t.literal
@param keyTable The table to get keys from
@returns True iff the condition is satisfied, false otherwise
**--]]
function t.keyOf(keyTable)
local keys = {}
local length = 0
for key in pairs(keyTable) do
length = length + 1
keys[length] = key
end
return t.literal(table.unpack(keys, 1, length))
end
--[[**
Returns a t.union of each value in the table as a t.literal
@param valueTable The table to get values from
@returns True iff the condition is satisfied, false otherwise
**--]]
function t.valueOf(valueTable)
local values = {}
local length = 0
for _, value in pairs(valueTable) do
length = length + 1
values[length] = value
end
return t.literal(table.unpack(values, 1, length))
end
--[[**
ensures value is an integer
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
function t.integer(value)
local success, errMsg = t.number(value)
if not success then
return false, errMsg or ""
end
if value % 1 == 0 then
return true
else
return false, string.format("integer expected, got %s", value)
end
end
--[[**
ensures value is a number where min <= value
@param min The minimum to use
@returns A function that will return true iff the condition is passed
**--]]
function t.numberMin(min)
return function(value)
local success, errMsg = t.number(value)
if not success then
return false, errMsg or ""
end
if value >= min then
return true
else
return false, string.format("number >= %s expected, got %s", min, value)
end
end
end
--[[**
ensures value is a number where value <= max
@param max The maximum to use
@returns A function that will return true iff the condition is passed
**--]]
function t.numberMax(max)
return function(value)
local success, errMsg = t.number(value)
if not success then
return false, errMsg
end
if value <= max then
return true
else
return false, string.format("number <= %s expected, got %s", max, value)
end
end
end
--[[**
ensures value is a number where min < value
@param min The minimum to use
@returns A function that will return true iff the condition is passed
**--]]
function t.numberMinExclusive(min)
return function(value)
local success, errMsg = t.number(value)
if not success then
return false, errMsg or ""
end
if min < value then
return true
else
return false, string.format("number > %s expected, got %s", min, value)
end
end
end
--[[**
ensures value is a number where value < max
@param max The maximum to use
@returns A function that will return true iff the condition is passed
**--]]
function t.numberMaxExclusive(max)
return function(value)
local success, errMsg = t.number(value)
if not success then
return false, errMsg or ""
end
if value < max then
return true
else
return false, string.format("number < %s expected, got %s", max, value)
end
end
end
--[[**
ensures value is a number where value > 0
@returns A function that will return true iff the condition is passed
**--]]
t.numberPositive = t.numberMinExclusive(0)
--[[**
ensures value is a number where value < 0
@returns A function that will return true iff the condition is passed
**--]]
t.numberNegative = t.numberMaxExclusive(0)
--[[**
ensures value is a number where min <= value <= max
@param min The minimum to use
@param max The maximum to use
@returns A function that will return true iff the condition is passed
**--]]
function t.numberConstrained(min, max)
assert(t.number(min))
assert(t.number(max))
local minCheck = t.numberMin(min)
local maxCheck = t.numberMax(max)
return function(value)
local minSuccess, minErrMsg = minCheck(value)
if not minSuccess then
return false, minErrMsg or ""
end
local maxSuccess, maxErrMsg = maxCheck(value)
if not maxSuccess then
return false, maxErrMsg or ""
end
return true
end
end
--[[**
ensures value is a number where min < value < max
@param min The minimum to use
@param max The maximum to use
@returns A function that will return true iff the condition is passed
**--]]
function t.numberConstrainedExclusive(min, max)
assert(t.number(min))
assert(t.number(max))
local minCheck = t.numberMinExclusive(min)
local maxCheck = t.numberMaxExclusive(max)
return function(value)
local minSuccess, minErrMsg = minCheck(value)
if not minSuccess then
return false, minErrMsg or ""
end
local maxSuccess, maxErrMsg = maxCheck(value)
if not maxSuccess then
return false, maxErrMsg or ""
end
return true
end
end
--[[**
ensures value matches string pattern
@param string pattern to check against
@returns A function that will return true iff the condition is passed
**--]]
function t.match(pattern)
assert(t.string(pattern))
return function(value)
local stringSuccess, stringErrMsg = t.string(value)
if not stringSuccess then
return false, stringErrMsg
end
if string.match(value, pattern) == nil then
return false, string.format("%q failed to match pattern %q", value, pattern)
end
return true
end
end
--[[**
ensures value is either nil or passes check
@param check The check to use
@returns A function that will return true iff the condition is passed
**--]]
function t.optional(check)
assert(t.callback(check))
return function(value)
if value == nil then
return true
end
local success, errMsg = check(value)
if success then
return true
else
return false, string.format("(optional) %s", errMsg or "")
end
end
end
--[[**
matches given tuple against tuple type definition
@param ... The type definition for the tuples
@returns A function that will return true iff the condition is passed
**--]]
function t.tuple(...)
local checks = { ... }
return function(...)
local args = { ... }
for i, check in ipairs(checks) do
local success, errMsg = check(args[i])
if success == false then
return false, string.format("Bad tuple index #%s:\n\t%s", i, errMsg or "")
end
end
return true
end
end
--[[**
ensures all keys in given table pass check
@param check The function to use to check the keys
@returns A function that will return true iff the condition is passed
**--]]
function t.keys(check)
assert(t.callback(check))
return function(value)
local tableSuccess, tableErrMsg = t.table(value)
if tableSuccess == false then
return false, tableErrMsg or ""
end
for key in pairs(value) do
local success, errMsg = check(key)
if success == false then
return false, string.format("bad key %s:\n\t%s", tostring(key), errMsg or "")
end
end
return true
end
end
--[[**
ensures all values in given table pass check
@param check The function to use to check the values
@returns A function that will return true iff the condition is passed
**--]]
function t.values(check)
assert(t.callback(check))
return function(value)
local tableSuccess, tableErrMsg = t.table(value)
if tableSuccess == false then
return false, tableErrMsg or ""
end
for key, val in pairs(value) do
local success, errMsg = check(val)
if success == false then
return false, string.format("bad value for key %s:\n\t%s", tostring(key), errMsg or "")
end
end
return true
end
end
--[[**
ensures value is a table and all keys pass keyCheck and all values pass valueCheck
@param keyCheck The function to use to check the keys
@param valueCheck The function to use to check the values
@returns A function that will return true iff the condition is passed
**--]]
function t.map(keyCheck, valueCheck)
assert(t.callback(keyCheck))
assert(t.callback(valueCheck))
local keyChecker = t.keys(keyCheck)
local valueChecker = t.values(valueCheck)
return function(value)
local keySuccess, keyErr = keyChecker(value)
if not keySuccess then
return false, keyErr or ""
end
local valueSuccess, valueErr = valueChecker(value)
if not valueSuccess then
return false, valueErr or ""
end
return true
end
end
--[[**
ensures value is a table and all keys pass valueCheck and all values are true
@param valueCheck The function to use to check the values
@returns A function that will return true iff the condition is passed
**--]]
function t.set(valueCheck)
return t.map(valueCheck, t.literal(true))
end
do
local arrayKeysCheck = t.keys(t.integer)
--[[**
ensures value is an array and all values of the array match check
@param check The check to compare all values with
@returns A function that will return true iff the condition is passed
**--]]
function t.array(check)
assert(t.callback(check))
local valuesCheck = t.values(check)
return function(value)
local keySuccess, keyErrMsg = arrayKeysCheck(value)
if keySuccess == false then
return false, string.format("[array] %s", keyErrMsg or "")
end
-- # is unreliable for sparse arrays
-- Count upwards using ipairs to avoid false positives from the behavior of #
local arraySize = 0
for _ in ipairs(value) do
arraySize = arraySize + 1
end
for key in pairs(value) do
if key < 1 or key > arraySize then
return false, string.format("[array] key %s must be sequential", tostring(key))
end
end
local valueSuccess, valueErrMsg = valuesCheck(value)
if not valueSuccess then
return false, string.format("[array] %s", valueErrMsg or "")
end
return true
end
end
--[[**
ensures value is an array of a strict makeup and size
@param check The check to compare all values with
@returns A function that will return true iff the condition is passed
**--]]
function t.strictArray(...)
local valueTypes = { ... }
assert(t.array(t.callback)(valueTypes))
return function(value)
local keySuccess, keyErrMsg = arrayKeysCheck(value)
if keySuccess == false then
return false, string.format("[strictArray] %s", keyErrMsg or "")
end
-- If there's more than the set array size, disallow
if #valueTypes < #value then
return false, string.format("[strictArray] Array size exceeds limit of %d", #valueTypes)
end
for idx, typeFn in pairs(valueTypes) do
local typeSuccess, typeErrMsg = typeFn(value[idx])
if not typeSuccess then
return false, string.format("[strictArray] Array index #%d - %s", idx, typeErrMsg)
end
end
return true
end
end
end
do
local callbackArray = t.array(t.callback)
--[[**
creates a union type
@param ... The checks to union
@returns A function that will return true iff the condition is passed
**--]]
function t.union(...)
local checks = { ... }
assert(callbackArray(checks))
return function(value)
for _, check in ipairs(checks) do
if check(value) then
return true
end
end
return false, "bad type for union"
end
end
--[[**
Alias for t.union
**--]]
t.some = t.union
--[[**
creates an intersection type
@param ... The checks to intersect
@returns A function that will return true iff the condition is passed
**--]]
function t.intersection(...)
local checks = { ... }
assert(callbackArray(checks))
return function(value)
for _, check in ipairs(checks) do
local success, errMsg = check(value)
if not success then
return false, errMsg or ""
end
end
return true
end
end
--[[**
Alias for t.intersection
**--]]
t.every = t.intersection
end
do
local checkInterface = t.map(t.any, t.callback)
--[[**
ensures value matches given interface definition
@param checkTable The interface definition
@returns A function that will return true iff the condition is passed
**--]]
function t.interface(checkTable)
assert(checkInterface(checkTable))
return function(value)
local tableSuccess, tableErrMsg = t.table(value)
if tableSuccess == false then
return false, tableErrMsg or ""
end
for key, check in pairs(checkTable) do
local success, errMsg = check(value[key])
if success == false then
return false, string.format("[interface] bad value for %s:\n\t%s", tostring(key), errMsg or "")
end
end
return true
end
end
--[[**
ensures value matches given interface definition strictly
@param checkTable The interface definition
@returns A function that will return true iff the condition is passed
**--]]
function t.strictInterface(checkTable)
assert(checkInterface(checkTable))
return function(value)
local tableSuccess, tableErrMsg = t.table(value)
if tableSuccess == false then
return false, tableErrMsg or ""
end
for key, check in pairs(checkTable) do
local success, errMsg = check(value[key])
if success == false then
return false, string.format("[interface] bad value for %s:\n\t%s", tostring(key), errMsg or "")
end
end
for key in pairs(value) do
if not checkTable[key] then
return false, string.format("[interface] unexpected field %q", tostring(key))
end
end
return true
end
end
end
--[[**
ensure value is an Instance and it's ClassName matches the given ClassName
@param className The class name to check for
@returns A function that will return true iff the condition is passed
**--]]
function t.instanceOf(className, childTable)
assert(t.string(className))
local childrenCheck
if childTable ~= nil then
childrenCheck = t.children(childTable)
end
return function(value)
local instanceSuccess, instanceErrMsg = t.Instance(value)
if not instanceSuccess then
return false, instanceErrMsg or ""
end
if value.ClassName ~= className then
return false, string.format("%s expected, got %s", className, value.ClassName)
end
if childrenCheck then
local childrenSuccess, childrenErrMsg = childrenCheck(value)
if not childrenSuccess then
return false, childrenErrMsg
end
end
return true
end
end
t.instance = t.instanceOf
--[[**
ensure value is an Instance and it's ClassName matches the given ClassName by an IsA comparison
@param className The class name to check for
@returns A function that will return true iff the condition is passed
**--]]
function t.instanceIsA(className, childTable)
assert(t.string(className))
local childrenCheck
if childTable ~= nil then
childrenCheck = t.children(childTable)
end
return function(value)
local instanceSuccess, instanceErrMsg = t.Instance(value)
if not instanceSuccess then
return false, instanceErrMsg or ""
end
if not value:IsA(className) then
return false, string.format("%s expected, got %s", className, value.ClassName)
end
if childrenCheck then
local childrenSuccess, childrenErrMsg = childrenCheck(value)
if not childrenSuccess then
return false, childrenErrMsg
end
end
return true
end
end
--[[**
ensures value is an enum of the correct type
@param enum The enum to check
@returns A function that will return true iff the condition is passed
**--]]
function t.enum(enum)
assert(t.Enum(enum))
return function(value)
local enumItemSuccess, enumItemErrMsg = t.EnumItem(value)
if not enumItemSuccess then
return false, enumItemErrMsg
end
if value.EnumType == enum then
return true
else
return false, string.format("enum of %s expected, got enum of %s", tostring(enum), tostring(value.EnumType))
end
end
end
do
local checkWrap = t.tuple(t.callback, t.callback)
--[[**
wraps a callback in an assert with checkArgs
@param callback The function to wrap
@param checkArgs The function to use to check arguments in the assert
@returns A function that first asserts using checkArgs and then calls callback
**--]]
function t.wrap(callback, checkArgs)
assert(checkWrap(callback, checkArgs))
return function(...)
assert(checkArgs(...))
return callback(...)
end
end
end
--[[**
asserts a given check
@param check The function to wrap with an assert
@returns A function that simply wraps the given check in an assert
**--]]
function t.strict(check)
return function(...)
assert(check(...))
end
end
do
local checkChildren = t.map(t.string, t.callback)
--[[**
Takes a table where keys are child names and values are functions to check the children against.
Pass an instance tree into the function.
If at least one child passes each check, the overall check passes.
Warning! If you pass in a tree with more than one child of the same name, this function will always return false
@param checkTable The table to check against
@returns A function that checks an instance tree
**--]]
function t.children(checkTable)
assert(checkChildren(checkTable))
return function(value)
local instanceSuccess, instanceErrMsg = t.Instance(value)
if not instanceSuccess then
return false, instanceErrMsg or ""
end
local childrenByName = {}
for _, child in ipairs(value:GetChildren()) do
local name = child.Name
if checkTable[name] then
if childrenByName[name] then
return false, string.format("Cannot process multiple children with the same name %q", name)
end
childrenByName[name] = child
end
end
for name, check in pairs(checkTable) do
local success, errMsg = check(childrenByName[name])
if not success then
return false, string.format("[%s.%s] %s", value:GetFullName(), name, errMsg or "")
end
end
return true
end
end
end
return t
| 6,881 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Client/UI/Modern/Hint.luau | client = nil
service = nil
local Components = script.Parent.Components.AdonisModernComponents
local Packages = Components.Parent.Packages
local Maid = require(Packages.Maid)
local Signal = require(Packages.Signal)
local Roact = require(Packages.Roact)
local new = Roact.createElement
local FadeInOutAnimationWrapper = require(Components.FadeInOutAnimationWrapper)
local Hint = require(Components.Hint)
return function(Data)
local AppMaid = Maid.new()
local FadeInSignal = Signal.new()
local FadeOutSignal = Signal.new()
AppMaid.FadeInSignal = FadeInSignal
AppMaid.FadeOutSignal = FadeOutSignal
-- ////////// Create Message App
local App = new("ScreenGui", {
DisplayOrder = Data.DisplayOrder or 100,
IgnoreGuiInset = true,
ZIndexBehavior = Enum.ZIndexBehavior.Sibling,
}, {
AnimationContainer = new(FadeInOutAnimationWrapper, {
FadeInSignal = FadeInSignal,
FadeOutSignal = FadeOutSignal,
FadeInVelocity = 3,
FadeOutVelocity = 4,
OnFadeOutCompleted = function()
AppMaid:Destroy()
end,
}, {
Hint = new(Hint, {
BodyText = Data.Message,
Image = Data.Image,
TitleText = Data.Title,
}),
}),
})
-- ////////// Perform Animation Tasks
local Handle = Roact.mount(App, service.UnWrap(service.PlayerGui), "AdonisUI.Hint")
AppMaid.RemoveHandle = function()
Handle = Roact.unmount(Handle)
end
FadeInSignal:Fire()
if Data.Time then
task.wait(Data.Time)
else
-- Estimated read time
task.wait((("%s%s"):format(Data.Message or "", Data.Title or ""):len() / 19) + 2.5)
end
FadeOutSignal:Fire()
end | 417 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Client/UI/Modern/YesNoPrompt.luau | client, service = nil
local Packages = script.Parent.Components.Packages
local Signal = require(Packages.Signal)
local Winro = require(Packages.Winro)
local Roact = require(Packages.Roact)
local new = Roact.createElement
local Dialog = Winro.App.Window.Dialog
export type YesNoPromptProps = {
Delay: number?,
Icon: string?,
Name: string,
Question: string,
Size: {number},
Title: string
}
return function(data: YesNoPromptProps, env): "No" | "Yes"
local Variables = client.Variables
local themeData = Variables.LastServerTheme or {Desktop = "Default"; Mobile = "Mobilius"}
local theme = Variables.CustomTheme or (service.IsMobile() and themeData.Mobile) or themeData.Desktop
local answerSignal = Signal.new()
local app = new("ScreenGui", {
ZIndexBehavior = Enum.ZIndexBehavior.Sibling,
DisplayOrder = 500,
}, {
Dialog = new(Dialog, {
TitleText = data.Name,
BodyText = data.Question,
Size = UDim2.new(0, 400, 0, 100),
AutomaticSize = Enum.AutomaticSize.Y,
Buttons = {
[1] = {
Text = 'Yes',
Style = 'Accent',
[Roact.Event.Activated] = function()
answerSignal:Fire(true)
end,
},
[2] = {
Text = 'No',
Style = 'Standard',
[Roact.Event.Activated] = function()
answerSignal:Fire(false)
end,
},
},
TitleBarProps = {
Icon = data.Icon and {
Image = data.Icon;
ImageRectSize = Vector2.new();
ImageRectOffset = Vector2.new();
} or nil,
Text = data.Name or "Confirmation",
CanClose = false
},
WindowProps = {
FooterHeight = 80,
}
})
})
local handle = Roact.mount(new(Winro.Theme.Provider, {
Theme = theme == "Modern" and Winro.Theme.Themes.DarkTheme or Winro.Theme.Themes.LightTheme,
}, app), service.UnWrap(service.PlayerGui), "Adonis.YesNoPrompt")
local answer = answerSignal:Wait()
Roact.unmount(handle)
return if answer then "Yes" else "No"
end | 527 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Server/Dependencies/Assets/AnimateAvatar.server.luau | local AvatarTypes = {
Snoop = {0.05, {
131395838,
131395847,
131395855,
131395860,
131395868,
131395884,
131395884,
131395891,
131395897,
131395901,
131395946,
131395957,
131395966,
131395972,
131395979,
131395986,
131395989,
131395993,
131395997,
131396003,
131396007,
131396012,
131396016,
131396019,
131396024,
131396029,
131396037,
131396042,
131396044,
131396046,
131396054,
131396063,
131396068,
131396072,
131396078,
131396091,
131396098,
131396102,
131396108,
131396110,
131396113,
131396116,
131396121,
131396125,
131396133,
131396137,
131396142,
131396146,
131396156,
131396162,
131396164,
131396169,
131396173,
131396176,
131396181,
131396185,
131396188,
131396192
}},
Fr0g = {0.1, {
185945467,
185945486,
185945493,
185945515,
185945527,
185945553,
185945573,
185945586,
185945612,
185945634
}},
Kitty = {0.1, {
280224764,
280224790,
280224800,
280224820,
280224830,
280224844,
280224861,
280224899,
280224924,
280224955
}},
Nyan1 = {0.1, {
332277948,
332277937,
332277919,
332277904,
332277885,
332277870,
332277851,
332277835,
332277820,
332277809,
332277789,
332277963
}},
Nyan2 = {0.1, {
332288373,
332288356,
332288314,
332288287,
332288276,
332288249,
332288224,
332288207,
332288184,
332288163,
332288144,
332288125
}},
Shia = {0.1, {
286117283;
286117453;
286117512;
286117584;
286118200;
286118256;
--286118366;
286118468;
286118598;
286118637;
286118670;
286118709;
286118755;
286118810;
286118862;
}},
Sp00ks = {0.05, {
183747849,
183747854,
183747863,
183747870,
183747877,
183747879,
183747885,
183747890
}}
}
for _, child in ipairs(script.Parent:GetChildren()) do
local data = AvatarTypes[child.Name]
local delta, avatarTypeForChild = data and data[1], data and data[2]
if child:IsA("Decal") and avatarTypeForChild then
local max = #avatarTypeForChild
task.spawn(function()
while true do
child.Texture = `rbxassetid://{avatarTypeForChild[math.floor(os.clock() / delta) % max + 1]}`
task.wait(0.05)
end
end)
end
end
| 964 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Server/Dependencies/Assets/BunnyHop.client.luau | local hum = script.Parent:FindFirstChildOfClass("Humanoid")
hum.Jump = true
hum:GetPropertyChangedSignal("Jump"):Connect(function()
hum.Jump = true
end)
hum.Jump = not hum.Jump -- in some unreliable cases this line might be needed to make GetPropertyChangedSignal trigger immediately
| 64 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Server/Dependencies/Assets/ClickTeleport/init.client.lua | task.wait()
local Players = game:GetService("Players")
local UserInputService = game:GetService("UserInputService")
local mode = script.Mode.Value--"Teleport"
local name = script.Target.Value
local localplayer = Players.LocalPlayer
local mouse = localplayer:GetMouse()
local tool = script.Parent
local use = false
local holding = false
local target = Players:WaitForChild(name)
local char = target.Character
local humanoid = char:FindFirstChildOfClass("Humanoid")
if not humanoid then tool:Destroy() return end
tool.Name = `{mode} {target.Name}`
local function onButton1Down(mouse)
if not target.Character or not target.Character:FindFirstChildOfClass("Humanoid") then
return
elseif mode == "Teleport" then
local rootPart = humanoid.RootPart
if not rootPart then return end
local FlightPos, FlightGyro = rootPart:FindFirstChild("ADONIS_FLIGHT_POSITION"), rootPart:FindFirstChild("ADONIS_FLIGHT_GYRO")
local pos = mouse.Hit.Position
if FlightPos and FlightGyro then
FlightPos.Position = rootPart.Position
FlightGyro.CFrame = rootPart.CFrame
end
task.wait()
rootPart:PivotTo(CFrame.new(Vector3.new(pos.X, pos.Y + 4, pos.Z)))
if FlightPos and FlightGyro then
FlightPos.Position = rootPart.Position
FlightGyro.CFrame = rootPart.CFrame
end
elseif mode == "Walk" then
humanoid:MoveTo(mouse.Hit.Position)
end
end
local function rotate()
local char, rootPart = target.Character, humanoid.RootPart
if not rootPart then return end
repeat
rootPart:PivotTo(CFrame.new(rootPart.Position, Vector3.new(mouse.Hit.Position.X, rootPart.Position.Y, mouse.Hit.Position.Z)))
task.wait()
until not holding or not use
end
local function onEquipped(mouse)
use = true
mouse.Icon = "rbxasset://textures//ArrowCursor.png"
end
UserInputService.InputBegan:Connect(function(InputObject, gpe)
if InputObject.UserInputType == Enum.UserInputType.Keyboard and not gpe then
if InputObject.KeyCode == Enum.KeyCode.R then
holding = true
rotate()
elseif InputObject.KeyCode == Enum.KeyCode.X then
tool:Destroy()
end
end
end)
UserInputService.InputEnded:Connect(function(InputObject)
if InputObject.UserInputType == Enum.UserInputType.Keyboard then
if InputObject.KeyCode == Enum.KeyCode.R then
holding = false
end
end
end)
tool.Activated:Connect(function() if use then onButton1Down(mouse) end end)
tool.Equipped:Connect(onEquipped)
tool.Unequipped:Connect(function() use, holding = false, false end)
humanoid.Died:Connect(function() tool:Destroy() end)
| 635 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Server/Dependencies/Assets/FlyClipper.client.luau | task.wait()
local players = game:GetService("Players")
local localplayer = players.LocalPlayer
local torso = localplayer.Character.HumanoidRootPart
local hum = localplayer.Character:FindFirstChildOfClass("Humanoid")
local mouse = localplayer:GetMouse()
local enabled = script.Enabled
local running = true
local dir = {w = 0, s = 0, a = 0, d = 0}
local spd = 2
local moos = mouse.KeyDown:Connect(function(key)
if key:lower() == "w" then
dir.w = 1
elseif key:lower() == "s" then
dir.s = 1
elseif key:lower() == "a" then
dir.a = 1
elseif key:lower() == "d" then
dir.d = 1
elseif key:lower() == "q" then
spd = spd + 1
elseif key:lower() == "e" then
spd = spd - 1
end
end)
local moos1 = mouse.KeyUp:Connect(function(key)
if key:lower() == "w" then
dir.w = 0
elseif key:lower() == "s" then
dir.s = 0
elseif key:lower() == "a" then
dir.a = 0
elseif key:lower() == "d" then
dir.d = 0
end
end)
torso.Anchored = true
hum.PlatformStand = true
local macka = hum.Changed:Connect(function()
hum.PlatformStand = true
end)
repeat
if enabled == nil or enabled.Parent == nil or enabled.Value == false then
running = false
break
end
task.wait()
torso.CFrame = CFrame.new(torso.Position, workspace.CurrentCamera.CFrame.p) * CFrame.Angles(0,math.rad(180),0) * CFrame.new((dir.d-dir.a)*spd,0,(dir.s-dir.w)*spd)
until not running or hum.Parent == nil or torso.Parent == nil or script.Parent == nil or not enabled or not enabled.Value or not enabled.Parent
moos:Disconnect()
moos1:Disconnect()
macka:Disconnect()
torso.Anchored = false
hum.PlatformStand = false
| 505 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Server/Dependencies/Assets/Freecam/Freecam.client.lua | --!nonstrict
------------------------------------------------------------------------
-- Freecam
-- Cinematic free camera for spectating and video production.
------------------------------------------------------------------------
local pi = math.pi
local abs = math.abs
local clamp = math.clamp
local exp = math.exp
local rad = math.rad
local sign = math.sign
local sqrt = math.sqrt
local tan = math.tan
local ContextActionService = game:GetService("ContextActionService")
local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
local StarterGui = game:GetService("StarterGui")
local UserInputService = game:GetService("UserInputService")
local Workspace = game:GetService("Workspace")
local Settings = UserSettings()
local GameSettings = Settings.GameSettings
local Lighting = game:GetService("Lighting")
local Debris = game:GetService('Debris')
local RF = script.Parent:FindFirstChildOfClass("RemoteFunction")
local LocalPlayer = Players.LocalPlayer
if not LocalPlayer then
Players:GetPropertyChangedSignal("LocalPlayer"):Wait()
LocalPlayer = Players.LocalPlayer
end
local Camera = Workspace.CurrentCamera
Workspace:GetPropertyChangedSignal("CurrentCamera"):Connect(function()
local newCamera = Workspace.CurrentCamera
if newCamera then
Camera = newCamera
end
end)
local FreecamDepthOfField = nil
local FFlagUserExitFreecamBreaksWithShiftlock
do
local success, result = pcall(function()
return UserSettings():IsUserFeatureEnabled("UserExitFreecamBreaksWithShiftlock")
end)
FFlagUserExitFreecamBreaksWithShiftlock = success and result
end
local FFlagUserShowGuiHideToggles
do
local success, result = pcall(function()
return UserSettings():IsUserFeatureEnabled("UserShowGuiHideToggles")
end)
FFlagUserShowGuiHideToggles = success and result
end
local FFlagUserFixFreecamDeltaTimeCalculation
do
local success, result = pcall(function()
return UserSettings():IsUserFeatureEnabled("UserFixFreecamDeltaTimeCalculation")
end)
FFlagUserFixFreecamDeltaTimeCalculation = success and result
end
local FFlagUserFixFreecamGuiChangeVisibility
do
local success, result = pcall(function()
return UserSettings():IsUserFeatureEnabled("UserFixFreecamGuiChangeVisibility")
end)
FFlagUserFixFreecamGuiChangeVisibility = success and result
end
local FFlagUserFreecamControlSpeed
do
local success, result = pcall(function()
return UserSettings():IsUserFeatureEnabled("UserFreecamControlSpeed")
end)
FFlagUserFreecamControlSpeed = success and result
end
local FFlagUserFreecamTiltControl
do
local success, result = pcall(function()
return UserSettings():IsUserFeatureEnabled("UserFreecamTiltControl")
end)
FFlagUserFreecamTiltControl = success and result
end
local FFlagUserFreecamSmoothnessControl
do
local success, result = pcall(function()
return UserSettings():IsUserFeatureEnabled("UserFreecamSmoothnessControl")
end)
FFlagUserFreecamSmoothnessControl = success and result
end
local FFlagUserFreecamGuiDestabilization
do
local success, result = pcall(function()
return UserSettings():IsUserFeatureEnabled("UserFreecamGuiDestabilization")
end)
FFlagUserFreecamGuiDestabilization = success and result
end
local FFlagUserFreecamDepthOfFieldEffect
do
local success, result = pcall(function()
return UserSettings():IsUserFeatureEnabled("UserFreecamDepthOfFieldEffect")
end)
FFlagUserFreecamDepthOfFieldEffect = success and result
end
------------------------------------------------------------------------
local FREECAM_ENABLED_ATTRIBUTE_NAME = "FreecamEnabled"
local TOGGLE_INPUT_PRIORITY = Enum.ContextActionPriority.Low.Value
local INPUT_PRIORITY = Enum.ContextActionPriority.High.Value
local FREECAM_MACRO_KB = { Enum.KeyCode.LeftShift, Enum.KeyCode.P }
local FREECAM_TILT_RESET_KB = {
[Enum.KeyCode.Z] = true,
[Enum.KeyCode.C] = true,
}
local FREECAM_TILT_RESET_GP = {
[Enum.KeyCode.ButtonL1] = true,
[Enum.KeyCode.ButtonR1] = true,
}
local FREECAM_DOF_TOGGLE = {
[Enum.KeyCode.BackSlash] = true,
}
local NAV_GAIN = Vector3.new(1, 1, 1) * 64
local PAN_GAIN = Vector2.new(0.75, 1) * 8
local FOV_GAIN = 300
local ROLL_GAIN = -pi / 2
local PITCH_LIMIT = rad(90)
local VEL_STIFFNESS = 1.5
local PAN_STIFFNESS = 1.0
local FOV_STIFFNESS = 4.0
local ROLL_STIFFNESS = 1.0
local VEL_ADJ_STIFFNESS = 0.75
local PAN_ADJ_STIFFNESS = 0.75
local FOV_ADJ_STIFFNESS = 0.75
local ROLL_ADJ_STIFFNESS = 0.75
local VEL_MIN_STIFFNESS = 0.01
local PAN_MIN_STIFFNESS = 0.01
local FOV_MIN_STIFFNESS = 0.01
local ROLL_MIN_STIFFNESS = 0.01
local VEL_MAX_STIFFNESS = 10.0
local PAN_MAX_STIFFNESS = 10.0
local FOV_MAX_STIFFNESS = 10.0
local ROLL_MAX_STIFFNESS = 10.0
local lastPressTime = {}
local lastResetTime = 0
local DOUBLE_TAP_TIME_THRESHOLD = 0.25
local DOUBLE_TAP_DEBOUNCE_TIME = 0.1
local postEffects = {}
------------------------------------------------------------------------
local Spring = {}
do
Spring.__index = Spring
function Spring.new(freq, pos)
local self = setmetatable({}, Spring)
self.f = freq
self.p = pos
self.v = pos * 0
return self
end
function Spring:Update(dt, goal)
local f = self.f * 2 * pi
local p0 = self.p
local v0 = self.v
local offset = goal - p0
local decay = exp(-f * dt)
local p1 = goal + (v0 * dt - offset * (f * dt + 1)) * decay
local v1 = (f * dt * (offset * f - v0) + v0) * decay
self.p = p1
self.v = v1
return p1
end
function Spring:SetFreq(freq)
self.f = freq
end
function Spring:Reset(pos)
self.p = pos
self.v = pos * 0
end
end
------------------------------------------------------------------------
local cameraPos = Vector3.new()
local cameraRot
if FFlagUserFreecamTiltControl then
cameraRot = Vector3.new()
else
cameraRot = Vector2.new()
end
local cameraFov = 0
local velSpring = Spring.new(VEL_STIFFNESS, Vector3.new())
local panSpring = Spring.new(PAN_STIFFNESS, Vector2.new())
local fovSpring = Spring.new(FOV_STIFFNESS, 0)
local rollSpring = Spring.new(ROLL_STIFFNESS, 0)
------------------------------------------------------------------------
local Input = {}
do
local thumbstickCurve
do
local K_CURVATURE = 2.0
local K_DEADZONE = 0.15
local function fCurve(x)
return (exp(K_CURVATURE * x) - 1) / (exp(K_CURVATURE) - 1)
end
local function fDeadzone(x)
return fCurve((x - K_DEADZONE) / (1 - K_DEADZONE))
end
function thumbstickCurve(x)
return sign(x) * clamp(fDeadzone(abs(x)), 0, 1)
end
end
local gamepad = {
ButtonX = 0,
ButtonY = 0,
DPadDown = 0,
DPadUp = 0,
DPadLeft = 0,
DPadRight = 0,
ButtonL2 = 0,
ButtonR2 = 0,
ButtonL1 = 0,
ButtonR1 = 0,
Thumbstick1 = Vector2.new(),
Thumbstick2 = Vector2.new(),
}
local keyboard = {
W = 0,
A = 0,
S = 0,
D = 0,
E = 0,
Q = 0,
U = 0,
H = 0,
J = 0,
K = 0,
I = 0,
Y = 0,
Up = 0,
Down = 0,
Left = 0,
Right = 0,
LeftShift = 0,
RightShift = 0,
Z = 0,
C = 0,
Comma = 0,
Period = 0,
LeftBracket = 0,
RightBracket = 0,
Semicolon = 0,
Quote = 0,
V = 0,
B = 0,
N = 0,
M = 0,
BackSlash = 0,
Minus = 0,
Equals = 0,
}
local mouse = {
Delta = Vector2.new(),
MouseWheel = 0,
}
local DEFAULT_FPS = 60
local NAV_GAMEPAD_SPEED = Vector3.new(1, 1, 1)
local NAV_KEYBOARD_SPEED = Vector3.new(1, 1, 1)
local PAN_MOUSE_SPEED = Vector2.new(1, 1) * (pi / 64)
local PAN_MOUSE_SPEED_DT = PAN_MOUSE_SPEED / DEFAULT_FPS
local PAN_GAMEPAD_SPEED = Vector2.new(1, 1) * (pi / 8)
local FOV_WHEEL_SPEED = 1.0
local FOV_WHEEL_SPEED_DT = FOV_WHEEL_SPEED / DEFAULT_FPS
local FOV_GAMEPAD_SPEED = 0.25
local ROLL_GAMEPAD_SPEED = 1.0
local ROLL_KEYBOARD_SPEED = 1.0
local NAV_ADJ_SPEED = 0.75
local NAV_MIN_SPEED = 0.01
local NAV_MAX_SPEED = 4.0
local NAV_SHIFT_MUL = 0.25
local FOV_ADJ_SPEED = 0.75
local FOV_MIN_SPEED = 0.01
local FOV_MAX_SPEED = 4.0
local ROLL_ADJ_SPEED = 0.75
local ROLL_MIN_SPEED = 0.01
local ROLL_MAX_SPEED = 4.0
local DoFConstants = {
FarIntensity = {
ADJ = 0.1,
MIN = 0.0,
MAX = 1.0,
},
NearIntensity = {
ADJ = 0.1,
MIN = 0.0,
MAX = 1.0,
},
FocusDistance = {
ADJ = 20.0,
MIN = 0.0,
MAX = 200.0,
},
FocusRadius = {
ADJ = 5.0,
MIN = 0.0,
MAX = 50.0,
},
}
local navSpeed = 1
local rollSpeed = 1
local fovSpeed = 1
function Input.Vel(dt)
if FFlagUserFreecamControlSpeed then
navSpeed = clamp(
navSpeed + dt * (keyboard.Up - keyboard.Down + gamepad.DPadUp - gamepad.DPadDown) * NAV_ADJ_SPEED,
NAV_MIN_SPEED,
NAV_MAX_SPEED
)
else
navSpeed = clamp(navSpeed + dt * (keyboard.Up - keyboard.Down) * NAV_ADJ_SPEED, 0.01, 4)
end
local kGamepad = Vector3.new(
thumbstickCurve(gamepad.Thumbstick1.X),
thumbstickCurve(gamepad.ButtonR2) - thumbstickCurve(gamepad.ButtonL2),
thumbstickCurve(-gamepad.Thumbstick1.Y)
) * NAV_GAMEPAD_SPEED
local kKeyboard = Vector3.new(
keyboard.D - keyboard.A + keyboard.K - keyboard.H,
keyboard.E - keyboard.Q + keyboard.I - keyboard.Y,
keyboard.S - keyboard.W + keyboard.J - keyboard.U
) * NAV_KEYBOARD_SPEED
local shift = UserInputService:IsKeyDown(Enum.KeyCode.LeftShift)
or UserInputService:IsKeyDown(Enum.KeyCode.RightShift)
return (kGamepad + kKeyboard) * (navSpeed * (shift and NAV_SHIFT_MUL or 1))
end
function Input.Pan(dt)
local kGamepad = Vector2.new(thumbstickCurve(gamepad.Thumbstick2.Y), thumbstickCurve(-gamepad.Thumbstick2.X))
* PAN_GAMEPAD_SPEED
local kMouse = mouse.Delta * PAN_MOUSE_SPEED
if FFlagUserFixFreecamDeltaTimeCalculation then
if dt > 0 then
kMouse = (mouse.Delta / dt) * PAN_MOUSE_SPEED_DT
end
end
mouse.Delta = Vector2.new()
return kGamepad + kMouse
end
function Input.Fov(dt)
if FFlagUserFreecamControlSpeed then
fovSpeed = clamp(
fovSpeed + dt * (keyboard.Right - keyboard.Left + gamepad.DPadRight - gamepad.DPadLeft) * FOV_ADJ_SPEED,
FOV_MIN_SPEED,
FOV_MAX_SPEED
)
end
local kGamepad = (gamepad.ButtonX - gamepad.ButtonY) * FOV_GAMEPAD_SPEED
local kMouse = mouse.MouseWheel * FOV_WHEEL_SPEED
if FFlagUserFixFreecamDeltaTimeCalculation then
if dt > 0 then
kMouse = (mouse.MouseWheel / dt) * FOV_WHEEL_SPEED_DT
end
end
mouse.MouseWheel = 0
if FFlagUserFreecamControlSpeed then
return (kGamepad + kMouse) * fovSpeed
else
return kGamepad + kMouse
end
end
function Input.Roll(dt)
rollSpeed =
clamp(rollSpeed + dt * (keyboard.Period - keyboard.Comma) * ROLL_ADJ_SPEED, ROLL_MIN_SPEED, ROLL_MAX_SPEED)
local kGamepad = (gamepad.ButtonR1 - gamepad.ButtonL1) * ROLL_GAMEPAD_SPEED
local kKeyboard = (keyboard.C - keyboard.Z) * ROLL_KEYBOARD_SPEED
return (kGamepad + kKeyboard) * rollSpeed
end
function Input.SpringControl(dt)
if FFlagUserFreecamDepthOfFieldEffect then
local shiftIsDown = UserInputService:IsKeyDown(Enum.KeyCode.LeftShift)
or UserInputService:IsKeyDown(Enum.KeyCode.RightShift)
local ctrlIsDown = UserInputService:IsKeyDown(Enum.KeyCode.LeftControl)
or UserInputService:IsKeyDown(Enum.KeyCode.RightControl)
if shiftIsDown or ctrlIsDown then
return -- reserve Shift+Keybinds for other actions, in this case Shift+Brackets for Depth of Field controls
end
end
VEL_STIFFNESS = clamp(
VEL_STIFFNESS + dt * (keyboard.RightBracket - keyboard.LeftBracket) * VEL_ADJ_STIFFNESS,
VEL_MIN_STIFFNESS,
VEL_MAX_STIFFNESS
)
velSpring:SetFreq(VEL_STIFFNESS)
PAN_STIFFNESS = clamp(
PAN_STIFFNESS + dt * (keyboard.Quote - keyboard.Semicolon) * PAN_ADJ_STIFFNESS,
PAN_MIN_STIFFNESS,
PAN_MAX_STIFFNESS
)
panSpring:SetFreq(PAN_STIFFNESS)
FOV_STIFFNESS = clamp(
FOV_STIFFNESS + dt * (keyboard.B - keyboard.V) * FOV_ADJ_STIFFNESS,
FOV_MIN_STIFFNESS,
FOV_MAX_STIFFNESS
)
fovSpring:SetFreq(FOV_STIFFNESS)
ROLL_STIFFNESS = clamp(
ROLL_STIFFNESS + dt * (keyboard.M - keyboard.N) * ROLL_ADJ_STIFFNESS,
ROLL_MIN_STIFFNESS,
ROLL_MAX_STIFFNESS
)
rollSpring:SetFreq(ROLL_STIFFNESS)
end
function Input.DoF(dt)
local shiftIsDown = UserInputService:IsKeyDown(Enum.KeyCode.LeftShift)
or UserInputService:IsKeyDown(Enum.KeyCode.RightShift)
local ctrlIsDown = UserInputService:IsKeyDown(Enum.KeyCode.LeftControl)
or UserInputService:IsKeyDown(Enum.KeyCode.RightControl)
if shiftIsDown then
FreecamDepthOfField.FarIntensity = clamp(
FreecamDepthOfField.FarIntensity
+ dt * (keyboard.RightBracket - keyboard.LeftBracket) * DoFConstants.FarIntensity.ADJ,
DoFConstants.FarIntensity.MIN,
DoFConstants.FarIntensity.MAX
)
FreecamDepthOfField.InFocusRadius = clamp(
FreecamDepthOfField.InFocusRadius
+ dt * (keyboard.Equals - keyboard.Minus) * DoFConstants.FocusRadius.ADJ,
DoFConstants.FocusRadius.MIN,
DoFConstants.FocusRadius.MAX
)
elseif ctrlIsDown then
FreecamDepthOfField.NearIntensity = clamp(
FreecamDepthOfField.NearIntensity
+ dt * (keyboard.RightBracket - keyboard.LeftBracket) * DoFConstants.NearIntensity.ADJ,
DoFConstants.NearIntensity.MIN,
DoFConstants.NearIntensity.MAX
)
else
FreecamDepthOfField.FocusDistance = clamp(
FreecamDepthOfField.FocusDistance
+ dt * (keyboard.Equals - keyboard.Minus) * DoFConstants.FocusDistance.ADJ,
DoFConstants.FocusDistance.MIN,
DoFConstants.FocusDistance.MAX
)
end
end
do
local function resetKeys(keys, table)
for keyEnum, _ in pairs(keys) do
if table[keyEnum.Name] then
table[keyEnum.Name] = 0
end
end
end
local function handleDoubleTapReset(keyCode)
local currentTime = os.clock()
local previousPressTime = lastPressTime[keyCode]
local timeSinceLastPress = previousPressTime and (currentTime - previousPressTime) or -1
if previousPressTime and (timeSinceLastPress <= DOUBLE_TAP_TIME_THRESHOLD) then
if (currentTime - lastResetTime) >= DOUBLE_TAP_DEBOUNCE_TIME then
cameraRot = Vector3.new(cameraRot.x, cameraRot.y, 0)
rollSpring:Reset(0)
if FFlagUserFreecamDepthOfFieldEffect then
resetKeys(FREECAM_TILT_RESET_GP, gamepad)
resetKeys(FREECAM_TILT_RESET_KB, keyboard)
else
gamepad.ButtonL1 = 0
gamepad.ButtonR1 = 0
keyboard.C = 0
keyboard.Z = 0
end
lastResetTime = currentTime
end
end
lastPressTime[keyCode] = currentTime
end
local function Keypress(action, state, input)
keyboard[input.KeyCode.Name] = state == Enum.UserInputState.Begin and 1 or 0
if FFlagUserFreecamTiltControl then
if FREECAM_TILT_RESET_KB[input.KeyCode] and input.UserInputState == Enum.UserInputState.Begin then
handleDoubleTapReset(input.KeyCode)
end
end
if FFlagUserFreecamDepthOfFieldEffect then
if FREECAM_DOF_TOGGLE[input.KeyCode] and input.UserInputState == Enum.UserInputState.Begin then
if not FreecamDepthOfField.Enabled then
postEffects = {}
-- Disable all existing DepthOfFieldEffects to be controlled by custom Freecam DoF.
for _, effect in ipairs(Camera:GetChildren()) do
if effect:IsA("DepthOfFieldEffect") and effect.Enabled then
postEffects[#postEffects + 1] = effect
effect.Enabled = false
end
end
for _, effect in ipairs(Lighting:GetChildren()) do
if effect:IsA("DepthOfFieldEffect") and effect.Enabled then
postEffects[#postEffects + 1] = effect
effect.Enabled = false
end
end
Camera.ChildAdded:Connect(function(child)
if child:IsA("DepthOfFieldEffect") and child.Enabled then
postEffects[#postEffects + 1] = child
child.Enabled = false
end
end)
Lighting.ChildAdded:Connect(function(child)
if child:IsA("DepthOfFieldEffect") and child.Enabled then
postEffects[#postEffects + 1] = child
child.Enabled = false
end
end)
else
-- Re-enable all existing DepthOfFieldEffects when custom Freecam DoF is off.
for _, effect in ipairs(postEffects) do
if effect.Parent then
effect.Enabled = true
end
end
postEffects = {}
end
FreecamDepthOfField.Enabled = not FreecamDepthOfField.Enabled
resetKeys(FREECAM_DOF_TOGGLE, keyboard)
end
end
return Enum.ContextActionResult.Sink
end
local function GpButton(action, state, input)
gamepad[input.KeyCode.Name] = state == Enum.UserInputState.Begin and 1 or 0
if FFlagUserFreecamTiltControl then
if FREECAM_TILT_RESET_GP[input.KeyCode] and input.UserInputState == Enum.UserInputState.Begin then
handleDoubleTapReset(input.KeyCode)
end
end
return Enum.ContextActionResult.Sink
end
local function MousePan(action, state, input)
local delta = input.Delta
mouse.Delta = Vector2.new(-delta.y, -delta.x)
return Enum.ContextActionResult.Sink
end
local function Thumb(action, state, input)
gamepad[input.KeyCode.Name] = input.Position
return Enum.ContextActionResult.Sink
end
local function Trigger(action, state, input)
gamepad[input.KeyCode.Name] = input.Position.z
return Enum.ContextActionResult.Sink
end
local function MouseWheel(action, state, input)
mouse[input.UserInputType.Name] = -input.Position.z
return Enum.ContextActionResult.Sink
end
local function Zero(t)
for k, v in pairs(t) do
t[k] = v * 0
end
end
function Input.StartCapture()
if FFlagUserFreecamControlSpeed then
ContextActionService:BindActionAtPriority(
"FreecamKeyboard",
Keypress,
false,
INPUT_PRIORITY,
Enum.KeyCode.W,
Enum.KeyCode.U,
Enum.KeyCode.A,
Enum.KeyCode.H,
Enum.KeyCode.S,
Enum.KeyCode.J,
Enum.KeyCode.D,
Enum.KeyCode.K,
Enum.KeyCode.E,
Enum.KeyCode.I,
Enum.KeyCode.Q,
Enum.KeyCode.Y
)
ContextActionService:BindActionAtPriority(
"FreecamKeyboardControlSpeed",
Keypress,
false,
INPUT_PRIORITY,
Enum.KeyCode.Up,
Enum.KeyCode.Down,
Enum.KeyCode.Left,
Enum.KeyCode.Right
)
ContextActionService:BindActionAtPriority(
"FreecamGamepadControlSpeed",
GpButton,
false,
INPUT_PRIORITY,
Enum.KeyCode.DPadUp,
Enum.KeyCode.DPadDown,
--Enum.KeyCode.DPadLeft, -- So this was bit of a problem because we use DPadLeft to toggle it but Roblox had some other ideas
Enum.KeyCode.DPadRight -- I myself would move the freecam toggle to another key but i dont know if that is a good idea. Well it will be someone else's problem now.
)
else
ContextActionService:BindActionAtPriority(
"FreecamKeyboard",
Keypress,
false,
INPUT_PRIORITY,
Enum.KeyCode.W,
Enum.KeyCode.U,
Enum.KeyCode.A,
Enum.KeyCode.H,
Enum.KeyCode.S,
Enum.KeyCode.J,
Enum.KeyCode.D,
Enum.KeyCode.K,
Enum.KeyCode.E,
Enum.KeyCode.I,
Enum.KeyCode.Q,
Enum.KeyCode.Y,
Enum.KeyCode.Up,
Enum.KeyCode.Down
)
end
if FFlagUserFreecamTiltControl then
ContextActionService:BindActionAtPriority(
"FreecamKeyboardTiltControl",
Keypress,
false,
INPUT_PRIORITY,
Enum.KeyCode.Z,
Enum.KeyCode.C
)
ContextActionService:BindActionAtPriority(
"FreecamGamepadTiltControl",
GpButton,
false,
INPUT_PRIORITY,
Enum.KeyCode.ButtonL1,
Enum.KeyCode.ButtonR1
)
ContextActionService:BindActionAtPriority(
"FreecamKeyboardTiltControlSpeed",
Keypress,
false,
INPUT_PRIORITY,
Enum.KeyCode.Comma,
Enum.KeyCode.Period
)
if FFlagUserFreecamSmoothnessControl then
ContextActionService:BindActionAtPriority(
"FreecamKeyboardSmoothnessControl",
Keypress,
false,
INPUT_PRIORITY,
Enum.KeyCode.LeftBracket,
Enum.KeyCode.RightBracket,
Enum.KeyCode.Semicolon,
Enum.KeyCode.Quote,
Enum.KeyCode.V,
Enum.KeyCode.B,
Enum.KeyCode.N,
Enum.KeyCode.M
)
end
end
if FFlagUserFreecamDepthOfFieldEffect then
ContextActionService:BindActionAtPriority(
"FreecamKeyboardDoFToggle",
Keypress,
false,
INPUT_PRIORITY,
Enum.KeyCode.BackSlash
)
ContextActionService:BindActionAtPriority(
"FreecamKeyboardDoFControls",
Keypress,
false,
INPUT_PRIORITY,
Enum.KeyCode.Minus,
Enum.KeyCode.Equals
)
end
ContextActionService:BindActionAtPriority(
"FreecamMousePan",
MousePan,
false,
INPUT_PRIORITY,
Enum.UserInputType.MouseMovement
)
ContextActionService:BindActionAtPriority(
"FreecamMouseWheel",
MouseWheel,
false,
INPUT_PRIORITY,
Enum.UserInputType.MouseWheel
)
ContextActionService:BindActionAtPriority(
"FreecamGamepadButton",
GpButton,
false,
INPUT_PRIORITY,
Enum.KeyCode.ButtonX,
Enum.KeyCode.ButtonY
)
ContextActionService:BindActionAtPriority(
"FreecamGamepadTrigger",
Trigger,
false,
INPUT_PRIORITY,
Enum.KeyCode.ButtonR2,
Enum.KeyCode.ButtonL2
)
ContextActionService:BindActionAtPriority(
"FreecamGamepadThumbstick",
Thumb,
false,
INPUT_PRIORITY,
Enum.KeyCode.Thumbstick1,
Enum.KeyCode.Thumbstick2
)
end
function Input.StopCapture()
navSpeed = 1
if FFlagUserFreecamControlSpeed then
fovSpeed = 1
end
if FFlagUserFreecamTiltControl then
rollSpeed = 1
end
Zero(gamepad)
Zero(keyboard)
Zero(mouse)
ContextActionService:UnbindAction("FreecamKeyboard")
if FFlagUserFreecamControlSpeed then
ContextActionService:UnbindAction("FreecamKeyboardControlSpeed")
ContextActionService:UnbindAction("FreecamGamepadControlSpeed")
end
if FFlagUserFreecamTiltControl then
ContextActionService:UnbindAction("FreecamKeyboardTiltControl")
ContextActionService:UnbindAction("FreecamGamepadTiltControl")
ContextActionService:UnbindAction("FreecamKeyboardTiltControlSpeed")
if FFlagUserFreecamSmoothnessControl then
ContextActionService:UnbindAction("FreecamKeyboardSmoothnessControl")
end
end
if FFlagUserFreecamDepthOfFieldEffect then
ContextActionService:UnbindAction("FreecamKeyboardDoFToggle")
ContextActionService:UnbindAction("FreecamKeyboardDoFControls")
end
ContextActionService:UnbindAction("FreecamMousePan")
ContextActionService:UnbindAction("FreecamMouseWheel")
ContextActionService:UnbindAction("FreecamGamepadButton")
ContextActionService:UnbindAction("FreecamGamepadTrigger")
ContextActionService:UnbindAction("FreecamGamepadThumbstick")
end
end
end
------------------------------------------------------------------------
local function StepFreecam(dt)
if FFlagUserFreecamSmoothnessControl then
Input.SpringControl(dt)
end
if FFlagUserFreecamDepthOfFieldEffect then
if FreecamDepthOfField and FreecamDepthOfField.Parent then
Input.DoF(dt)
end
end
local vel = velSpring:Update(dt, Input.Vel(dt))
local pan = panSpring:Update(dt, Input.Pan(dt))
local fov = fovSpring:Update(dt, Input.Fov(dt))
local roll
if FFlagUserFreecamTiltControl then
roll = rollSpring:Update(dt, Input.Roll(dt))
end
local zoomFactor = sqrt(tan(rad(70 / 2)) / tan(rad(cameraFov / 2)))
cameraFov = clamp(cameraFov + fov * FOV_GAIN * (dt / zoomFactor), 1, 120)
local cameraCFrame
if FFlagUserFreecamTiltControl then
local panVector: Vector2 = pan * PAN_GAIN * (dt / zoomFactor)
cameraRot = cameraRot + Vector3.new(panVector.X, panVector.Y, roll * ROLL_GAIN * (dt / zoomFactor))
if FFlagUserFreecamSmoothnessControl then
cameraRot = Vector3.new(cameraRot.x % (2 * pi), cameraRot.y % (2 * pi), cameraRot.z % (2 * pi))
else
cameraRot = Vector3.new(clamp(cameraRot.x, -PITCH_LIMIT, PITCH_LIMIT), cameraRot.y % (2 * pi), cameraRot.z)
end
cameraCFrame = CFrame.new(cameraPos)
* CFrame.fromOrientation(cameraRot.x, cameraRot.y, cameraRot.z)
* CFrame.new(vel * NAV_GAIN * dt)
else
cameraRot = cameraRot + pan * PAN_GAIN * (dt / zoomFactor)
cameraRot = Vector2.new(clamp(cameraRot.x, -PITCH_LIMIT, PITCH_LIMIT), cameraRot.y % (2 * pi))
cameraCFrame = CFrame.new(cameraPos)
* CFrame.fromOrientation(cameraRot.x, cameraRot.y, 0)
* CFrame.new(vel * NAV_GAIN * dt)
end
cameraPos = cameraCFrame.p
Camera.CFrame = cameraCFrame
Camera.Focus = cameraCFrame
Camera.FieldOfView = cameraFov
end
local function CheckMouseLockAvailability()
local devAllowsMouseLock = Players.LocalPlayer.DevEnableMouseLock
local devMovementModeIsScriptable = Players.LocalPlayer.DevComputerMovementMode
== Enum.DevComputerMovementMode.Scriptable
local userHasMouseLockModeEnabled = GameSettings.ControlMode == Enum.ControlMode.MouseLockSwitch
local userHasClickToMoveEnabled = GameSettings.ComputerMovementMode == Enum.ComputerMovementMode.ClickToMove
local MouseLockAvailable = devAllowsMouseLock
and userHasMouseLockModeEnabled
and not userHasClickToMoveEnabled
and not devMovementModeIsScriptable
return MouseLockAvailable
end
------------------------------------------------------------------------
local PlayerState = {}
do
local mouseBehavior
local mouseIconEnabled
local cameraType
local cameraFocus
local cameraCFrame
local cameraFieldOfView
local screenGuis = {}
local coreGuis = {
Backpack = true,
Chat = true,
Health = true,
PlayerList = true,
}
local setCores = {
BadgesNotificationsActive = true,
PointsNotificationsActive = true,
}
-- Save state and set up for freecam
function PlayerState.Push()
for name in pairs(coreGuis) do
coreGuis[name] = StarterGui:GetCoreGuiEnabled(Enum.CoreGuiType[name])
StarterGui:SetCoreGuiEnabled(Enum.CoreGuiType[name], false)
end
for name in pairs(setCores) do
setCores[name] = StarterGui:GetCore(name)
StarterGui:SetCore(name, false)
end
local playergui = LocalPlayer:FindFirstChildOfClass("PlayerGui")
if playergui then
for _, gui in pairs(playergui:GetChildren()) do
if gui:IsA("ScreenGui") and gui.Enabled then
screenGuis[#screenGuis + 1] = gui
gui.Enabled = false
end
end
if FFlagUserFixFreecamGuiChangeVisibility then
playergui.ChildAdded:Connect(function(child)
if child:IsA("ScreenGui") and child.Enabled then
screenGuis[#screenGuis + 1] = child
child.Enabled = false
end
end)
end
end
cameraFieldOfView = Camera.FieldOfView
Camera.FieldOfView = 70
cameraType = Camera.CameraType
Camera.CameraType = Enum.CameraType.Custom
cameraCFrame = Camera.CFrame
cameraFocus = Camera.Focus
mouseIconEnabled = UserInputService.MouseIconEnabled
UserInputService.MouseIconEnabled = false
if FFlagUserExitFreecamBreaksWithShiftlock and CheckMouseLockAvailability() then
mouseBehavior = Enum.MouseBehavior.Default
else
mouseBehavior = UserInputService.MouseBehavior
end
UserInputService.MouseBehavior = Enum.MouseBehavior.Default
end
-- Restore state
function PlayerState.Pop()
for name, isEnabled in pairs(coreGuis) do
StarterGui:SetCoreGuiEnabled(Enum.CoreGuiType[name], isEnabled)
end
for name, isEnabled in pairs(setCores) do
StarterGui:SetCore(name, isEnabled)
end
for _, gui in pairs(screenGuis) do
if gui.Parent then
gui.Enabled = true
end
end
if FFlagUserFixFreecamGuiChangeVisibility then
screenGuis = {}
end
Camera.FieldOfView = cameraFieldOfView
cameraFieldOfView = nil
Camera.CameraType = cameraType
cameraType = nil
Camera.CFrame = cameraCFrame
cameraCFrame = nil
Camera.Focus = cameraFocus
cameraFocus = nil
UserInputService.MouseIconEnabled = mouseIconEnabled
mouseIconEnabled = nil
UserInputService.MouseBehavior = mouseBehavior
mouseBehavior = nil
end
end
local function StartFreecam()
if not FFlagUserFreecamGuiDestabilization then
if FFlagUserShowGuiHideToggles then
script:SetAttribute(FREECAM_ENABLED_ATTRIBUTE_NAME, true)
end
end
local cameraCFrame = Camera.CFrame
if FFlagUserFreecamTiltControl then
cameraRot = Vector3.new(cameraCFrame:toEulerAnglesYXZ())
else
cameraRot = Vector2.new(cameraCFrame:toEulerAnglesYXZ())
end
cameraPos = cameraCFrame.p
cameraFov = Camera.FieldOfView
velSpring:Reset(Vector3.new())
panSpring:Reset(Vector2.new())
fovSpring:Reset(0)
if FFlagUserFreecamTiltControl then
rollSpring:Reset(0)
end
if FFlagUserFreecamSmoothnessControl then
VEL_STIFFNESS = 1.5
PAN_STIFFNESS = 1.0
FOV_STIFFNESS = 4.0
ROLL_STIFFNESS = 1.0
end
PlayerState.Push()
if FFlagUserFreecamDepthOfFieldEffect then
if not FreecamDepthOfField or not FreecamDepthOfField.Parent then
FreecamDepthOfField = Instance.new("DepthOfFieldEffect")
FreecamDepthOfField.Enabled = false
FreecamDepthOfField.Name = "FreecamDepthOfField"
FreecamDepthOfField.Parent = Camera
end
end
RunService:BindToRenderStep("Freecam", Enum.RenderPriority.Camera.Value, StepFreecam)
Input.StartCapture()
end
local function StopFreecam()
if not FFlagUserFreecamGuiDestabilization then
if FFlagUserShowGuiHideToggles then
script:SetAttribute(FREECAM_ENABLED_ATTRIBUTE_NAME, false)
end
end
if FFlagUserFreecamDepthOfFieldEffect then
if FreecamDepthOfField and FreecamDepthOfField.Parent then
if FreecamDepthOfField.Enabled then
for _, effect in ipairs(postEffects) do
if effect.Parent then
effect.Enabled = true
end
end
postEffects = {}
end
FreecamDepthOfField.Enabled = false
end
end
Input.StopCapture()
RunService:UnbindFromRenderStep("Freecam")
PlayerState.Pop()
end
------------------------------------------------------------------------
do
local enabled = false
local function ToggleFreecam()
if enabled then
StopFreecam()
else
StartFreecam()
end
enabled = not enabled
if FFlagUserFreecamGuiDestabilization then
script:SetAttribute(FREECAM_ENABLED_ATTRIBUTE_NAME, enabled)
end
end
local function CheckMacro(macro)
for i = 1, #macro - 1 do
if not UserInputService:IsKeyDown(macro[i]) then
return
end
end
ToggleFreecam()
end
local function HandleActivationInput(action, state, input)
if state == Enum.UserInputState.Begin then
if input.KeyCode == FREECAM_MACRO_KB[#FREECAM_MACRO_KB] then
CheckMacro(FREECAM_MACRO_KB)
end
if input.KeyCode == Enum.KeyCode.F or input.KeyCode == Enum.KeyCode.DPadLeft then
ToggleFreecam()
end
end
return Enum.ContextActionResult.Pass
end
ContextActionService:BindActionAtPriority(
"FreecamToggle",
HandleActivationInput,
false,
TOGGLE_INPUT_PRIORITY,
FREECAM_MACRO_KB[#FREECAM_MACRO_KB]
)
ContextActionService:BindActionAtPriority("FreecamToggleDPAD", HandleActivationInput, false, TOGGLE_INPUT_PRIORITY, Enum.KeyCode.DPadLeft)
if FFlagUserFreecamGuiDestabilization or FFlagUserShowGuiHideToggles then
script:SetAttribute(FREECAM_ENABLED_ATTRIBUTE_NAME, enabled)
script:GetAttributeChangedSignal(FREECAM_ENABLED_ATTRIBUTE_NAME):Connect(function()
local attributeValue = script:GetAttribute(FREECAM_ENABLED_ATTRIBUTE_NAME)
if typeof(attributeValue) ~= "boolean" then
script:SetAttribute(FREECAM_ENABLED_ATTRIBUTE_NAME, enabled)
return
end
-- If the attribute's value and `enabled` var don't match, pick attribute value as
-- source of truth
if attributeValue ~= enabled then
if attributeValue then
StartFreecam()
enabled = true
else
StopFreecam()
enabled = false
end
end
end)
end
RF.OnClientInvoke = function(a, b, c)
if a == "Disable" and enabled then
enabled = false
StopFreecam()
end
if a == "Enable" and not enabled then
enabled = true
StartFreecam()
end
if a == "Toggle" then
ToggleFreecam()
end
if a == "End" or a == "Stop" then
RF.OnClientInvoke = nil
Debris:AddItem(RF, 0.5)
ContextActionService:UnbindAction("FreecamToggle")
ContextActionService:UnbindAction("FreecamToggle2")
ContextActionService:UnbindAction("FreecamToggleDPAD")
if enabled then -- Had to add this check because it would break your camera if it wasnt here. Not sure why.
enabled = false
StopFreecam()
end
end
end
end
| 9,148 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Server/Dependencies/Assets/Glitcher/init.client.lua | task.wait()
local torso = script.Parent
local posed = false
local type = script:WaitForChild("Type").Value
local int = tonumber(script:WaitForChild("Num").Value) or 50
game:GetService("RunService").RenderStepped:Connect(function()
if type == "ghost" then
torso.CFrame += Vector3.new(tonumber(int) * (posed and 4 or -2), 0, 0)
elseif type == "trippy" then
torso.CFrame *= CFrame.new(tonumber(int) * (posed and 4 or -2), 0, 0)
elseif type == "vibrate" then
local num = math.random(1,4)
if num == 1 then
torso.CFrame *= CFrame.new(tonumber(int) * 2, 0, 0)
elseif num == 2 then
torso.CFrame *= CFrame.new(-tonumber(int) * 2, 0, 0)
elseif num == 3 then
torso.CFrame *= CFrame.new(0, 0, -tonumber(int) * 2)
elseif num == 4 then
torso.CFrame *= CFrame.new(0 ,0, tonumber(int) * 2)
end
end
posed = not posed
end)
| 300 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Server/Dependencies/Assets/HatPets.server.luau | local hats = script.Parent
local events = {}
if hats then
local mode = hats.Mode
local target = hats.Target
repeat
for _,hat in next,hats:GetChildren() do
if hat:IsA('Part') then
local bpos = hat.bpos
hat.CanCollide = false
if events[`{hat.Name}hatpet`] then
events[`{hat.Name}hatpet`]:Disconnect()
events[`{hat.Name}hatpet`] = nil
end
if mode.Value=='Follow' then
bpos.position = target.Value.Position+Vector3.new(math.random(-10,10),math.random(7,9),math.random(-10,10))
hat.CanCollide = false
elseif mode.Value=='Float' then
bpos.position = target.Value.Position+Vector3.new(math.random(-2.5,2.5),-3,math.random(-2.5,2.5))
hat.CanCollide = true
elseif mode.Value=='Attack' then
bpos.position = target.Value.Position+Vector3.new(math.random(-3,3),math.random(-3,3),math.random(-3,3))
events[`{hat.Name}hatpet`] = hat.Touched:Connect(function(p)
if not tonumber(p.Name) and game:GetService("Players"):GetPlayerFromCharacter(p.Parent) then
p.Parent.Humanoid:TakeDamage(1)
end
end)
hat.CanCollide = true
elseif mode.Value=='Swarm' then
bpos.position = target.Value.Position+Vector3.new(math.random(-8,8),math.random(-8,8),math.random(-8,8))
hat.CanCollide = true
end
end
end
wait(0.5)
until not script.Parent
end
| 408 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Server/Dependencies/Assets/Illegal.client.luau | local msgs={
{
Msg="We need more..... philosophy... ya know?",
Color=Enum.ChatColor.Green
},{
Msg="OH MY GOD STOP TRYING TO EAT MY SOUL",
Color=Enum.ChatColor.Red
},{
Msg="I.... CANT.... FEEL.... MY FACE",
Color=Enum.ChatColor.Red
},{
Msg="DO YOU SEE THE TURTLE?!?!",
Color=Enum.ChatColor.Red
},{
Msg="Omg puff the magic dragon!!!!",
Color=Enum.ChatColor.Green
},{
Msg="Omg double wat",
Color=Enum.ChatColor.Blue
},{
Msg="WHO STOLE MY LEGS",
Color=Enum.ChatColor.Red
},{
Msg="I... I think I might be dead....",
Color=Enum.ChatColor.Blue
},{
Msg="I'M GOING TO EAT YOUR FACE",
Color=Enum.ChatColor.Red
},{
Msg="Hey... Like... What if, like, listen, are you listening? What if.. like.. earth.. was a ball?",
Color=Enum.ChatColor.Green
},{
Msg="WHY IS EVERYBODY TALKING SO LOUD AHHHHHH",
Color=Enum.ChatColor.Red
},{
Msg="Woooo man do you see the elephent... theres an elephent man..its... PURPLE OHMY GOD ITS A SIGN FROM LIKE THE WARDROBE..",
Color=Enum.ChatColor.Blue
}}
local Chat = game:GetService("Chat")
local head = script.Parent.Parent.Head
local humanoid = script.Parent.Parent:FindFirstChildOfClass("Humanoid")
local torso = script.Parent
local old = math.huge
local stop = false
local val = Instance.new("StringValue")
val.Parent = head
humanoid.Died:Connect(function()
stop = true
task.wait(0.5)
workspace.CurrentCamera.FieldOfView = 70
end)
task.spawn(function()
while not stop and head and val and val.Parent == head do
local new = math.random(1, #msgs)
if old ~= new then
local m = msgs[new]
old = new
print(m.Msg)
Chat:Chat(head, m.Msg, m.Color)
end
task.wait(5)
end
end)
humanoid.WalkSpeed = -16
local startspaz = false
task.spawn(function()
repeat
task.wait(0.1)
workspace.CurrentCamera.FieldOfView = math.random(20, 80)
humanoid:TakeDamage(0.5)
if startspaz then
humanoid.PlatformStand = true
torso.AssemblyLinearVelocity = Vector3.new(math.random(-10, 10), -5, math.random(-10, 10))
torso.AssemblyAngularVelocity = Vector3.new(math.random(-5, 5), math.random(-5, 5), math.random(-5, 5))
end
until stop or not humanoid or not humanoid.Parent or humanoid.Health <= 0 or not torso
end)
task.wait(10)
local bg = Instance.new("BodyGyro")
bg.Name = "SPINNER"
bg.maxTorque = Vector3.new(0, math.huge, 0)
bg.P = 11111
bg.cframe = torso.CFrame
bg.Parent = torso
task.spawn(function()
repeat task.wait(1/44)
bg.cframe *= CFrame.Angles(0, math.rad(30), 0)
until stop or not bg or bg.Parent ~= torso
end)
task.wait(20)
startspaz = true
| 745 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Server/Dependencies/Assets/Quacker.server.luau | while true do
task.wait(math.random(5, 20))
if script.Parent ~= nil then
script.Parent:FindFirstChild(`Quack{math.random(1, 4)}`):Play()
else
script:Destroy()
break
end
end
| 57 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Server/Dependencies/Assets/Seize.client.luau | local root = script.Parent
local humanoid = root.Parent:FindFirstChildOfClass("Humanoid")
local origvel = root.AssemblyLinearVelocity
local origrot = root.AssemblyAngularVelocity
repeat
task.wait(0.1)
humanoid.PlatformStand = true
root.AssemblyLinearVelocity = Vector3.new(math.random(-10, 10), -5, math.random(-10, 10))
root.AssemblyAngularVelocity = Vector3.new(math.random(-5, 5), math.random(-5, 5), math.random(-5, 5))
until not root or not humanoid
humanoid.PlatformStand = false
root.AssemblyLinearVelocity = origvel
root.AssemblyAngularVelocity = origrot
| 143 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Server/Dependencies/Assets/Sfling/init.client.lua | task.wait()
local cam = workspace.CurrentCamera
local torso = script.Parent
local humanoid = torso.Parent:FindFirstChildOfClass("Humanoid")
local strength = script:WaitForChild("Strength").Value
for i = 1, 100 do
task.wait(0.1)
humanoid.Sit = true
local ex = Instance.new("Explosion")
ex.Position = torso.Position + Vector3.new(math.random(-5, 5), -10, math.random(-5, 5))
ex.BlastRadius = 35
ex.BlastPressure = strength
ex.ExplosionType = Enum.ExplosionType.NoCraters--Enum.ExplosionType.Craters
ex.DestroyJointRadiusPercent = 0
ex.Archivable = false
ex.Parent = cam
end
script:Destroy()
| 167 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Server/Dependencies/Assets/Slippery.client.luau | task.wait(0.5)
local vel = script.Parent:WaitForChild("ADONIS_IceVelocity")
while script.Parent ~= nil and vel and vel.Parent ~= nil do
vel.Velocity = Vector3.new(script.Parent.AssemblyLinearVelocity.X, 0, script.Parent.AssemblyLinearVelocity.Z)
task.wait(0.1)
end
if vel then vel:Destroy() end
| 82 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Server/Dependencies/Assets/Spinner.client.luau | local torso = script.Parent
local bg = torso:FindFirstChild("ADONIS_SPIN_GYRO")
repeat
task.wait(1/44)
bg.CFrame *= CFrame.Angles(0, math.rad(12), 0)
until not bg or bg.Parent ~= torso
| 60 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Server/Dependencies/CountryRegionCodes.luau | return {
US = "United States",
GB = "United Kingdom",
CA = "Canada",
AF = "Afghanistan",
AX = "Aland Islands",
AL = "Albania",
DZ = "Algeria",
AS = "American Samoa",
AD = "Andorra",
AO = "Angola",
AI = "Anguilla",
AQ = "Antarctica",
AG = "Antigua and Barbuda",
AR = "Argentina",
AM = "Armenia",
AW = "Aruba",
AU = "Australia",
AT = "Austria",
AZ = "Azerbaijan",
BS = "Bahamas",
BH = "Bahrain",
BD = "Bangladesh",
BB = "Barbados",
BY = "Belarus",
BE = "Belgium",
BZ = "Belize",
BJ = "Benin",
BM = "Bermuda",
BT = "Bhutan",
BO = "Bolivia",
BQ = "Bonaire, Saint Eustatius and Saba",
BA = "Bosnia and Herzegovina",
BW = "Botswana",
BV = "Bouvet Island",
BR = "Brazil",
IO = "British Indian Ocean Territory",
BN = "Brunei Darussalam",
BG = "Bulgaria",
BF = "Burkina Faso",
BI = "Burundi",
KH = "Cambodia",
CM = "Cameroon",
CV = "Cape Verde",
KY = "Cayman Islands",
CF = "Central African Republic",
TD = "Chad",
CL = "Chile",
CN = "China",
CX = "Christmas Island",
CC = "Cocos Islands",
CO = "Colombia",
KM = "Comoros",
CG = "Congo",
CD = "Congo (DRC)",
CK = "Cook Islands",
CR = "Costa Rica",
CI = "Ivory Coast",
HR = "Croatia",
CW = "Curaçao",
CY = "Cyprus",
CZ = "Czech Republic",
DK = "Denmark",
DJ = "Djibouti",
DM = "Dominica",
DO = "Dominican Republic",
EC = "Ecuador",
EG = "Egypt",
SV = "El Salvador",
GQ = "Equatorial Guinea",
ER = "Eritrea",
EE = "Estonia",
ET = "Ethiopia",
FK = "Falkland Islands (Malvinas)",
FO = "Faroe Islands",
FJ = "Fiji",
FI = "Finland",
FR = "France",
GF = "French Guiana",
PF = "French Polynesia",
TF = "French Southern Territories",
GA = "Gabon",
GM = "Gambia",
GE = "Georgia",
DE = "Germany",
GH = "Ghana",
GI = "Gibraltar",
GR = "Greece",
GL = "Greenland",
GD = "Grenada",
GP = "Guadeloupe",
GU = "Guam",
GT = "Guatemala",
GG = "Guernsey",
GN = "Guinea",
GW = "Guinea-Bissau",
GY = "Guyana",
HT = "Haiti",
HM = "Heard Island and the McDonald Islands",
VA = "Holy See",
HN = "Honduras",
HK = "Hong Kong",
HU = "Hungary",
IS = "Iceland",
IN = "India",
ID = "Indonesia",
IQ = "Iraq",
IE = "Ireland",
IM = "Isle of Man",
IL = "Israel",
IT = "Italy",
JM = "Jamaica",
JP = "Japan",
JE = "Jersey",
JO = "Jordan",
KZ = "Kazakhstan",
KE = "Kenya",
KI = "Kiribati",
KR = "Korea",
KW = "Kuwait",
KG = "Kyrgyzstan",
LA = "Laos",
LV = "Latvia",
LB = "Lebanon",
LS = "Lesotho",
LR = "Liberia",
LY = "Libya",
LI = "Liechtenstein",
LT = "Lithuania",
LU = "Luxembourg",
MO = "Macao",
MK = "Macedonia",
MG = "Madagascar",
MW = "Malawi",
MY = "Malaysia",
MV = "Maldives",
ML = "Mali",
MT = "Malta",
MH = "Marshall Islands",
MQ = "Martinique",
MR = "Mauritania",
MU = "Mauritius",
YT = "Mayotte",
MX = "Mexico",
FM = "Micronesia",
MD = "Moldova",
MC = "Monaco",
MN = "Mongolia",
ME = "Montenegro",
MS = "Montserrat",
MA = "Morocco",
MZ = "Mozambique",
MM = "Myanmar",
NA = "Namibia",
NR = "Nauru",
NP = "Nepal",
NL = "Netherlands",
AN = "Netherlands Antilles",
NC = "New Caledonia",
NZ = "New Zealand",
NI = "Nicaragua",
NE = "Niger",
NG = "Nigeria",
NU = "Niue",
NF = "Norfolk Island",
MP = "Northern Mariana Islands",
NO = "Norway",
OM = "Oman",
PK = "Pakistan",
PW = "Palau",
PS = "Palestine",
PA = "Panama",
PG = "Papua New Guinea",
PY = "Paraguay",
PE = "Peru",
PH = "Philippines",
PN = "Pitcairn Islands",
PL = "Poland",
PT = "Portugal",
PR = "Puerto Rico",
QA = "Qatar",
RE = "Reunion",
RO = "Romania",
RU = "Russian Federation",
RW = "Rwanda",
BL = "Saint Barthelemy",
SH = "Saint Helena, Ascension and Tristan da Cunha",
KN = "Saint Kitts and Nevis",
LC = "Saint Lucia",
MF = "Saint Martin",
PM = "Saint Pierre and Miquelon",
VC = "Saint Vincent and the Grenadines",
WS = "Samoa",
SM = "San Marino",
ST = "Sao Tome and Principe",
SA = "Saudi Arabia",
SN = "Senegal",
RS = "Serbia",
SC = "Seychelles",
SL = "Sierra Leone",
SG = "Singapore",
SX = "Sint Maarten",
SK = "Slovakia",
SI = "Slovenia",
SB = "Solomon Islands",
SO = "Somalia",
ZA = "South Africa",
GS = "South Georgia and the South Sandwich Islands",
SS = "South Sudan",
ES = "Spain",
LK = "Sri Lanka",
SR = "Suriname",
SJ = "Svalbard and Jan Mayen",
SZ = "Swaziland",
SE = "Sweden",
CH = "Switzerland",
TW = "Taiwan",
TJ = "Tajikistan",
TZ = "Tanzania",
TH = "Thailand",
TL = "Timor-leste",
TG = "Togo",
TK = "Tokelau",
TO = "Tonga",
TT = "Trinidad and Tobago",
TN = "Tunisia",
TR = "Turkey",
TM = "Turkmenistan",
TC = "Turks and Caicos Islands",
TV = "Tuvalu",
UG = "Uganda",
UA = "Ukraine",
AE = "United Arab Emirates",
UM = "United States Minor Outlying Islands",
UY = "Uruguay",
UZ = "Uzbekistan",
VU = "Vanuatu",
VE = "Venezuela",
VN = "Vietnam",
VG = "Virgin Islands (British)",
VI = "Virgin Islands (US)",
WF = "Wallis and Futuna",
EH = "Western Sahara",
YE = "Yemen",
ZM = "Zambia",
ZW = "Zimbabwe",
CU = "Cuba",
IR = "Iran",
SY = "Syria",
KP = "North Korea"
}
| 1,925 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Server/Dependencies/DataStoreService/init.lua | --[[
DataStoreService.lua
This module decides whether to use actual datastores or mock datastores depending on the environment.
This module is licensed under APLv2, refer to the LICENSE file or:
buildthomas/MockDataStoreService/blob/master/LICENSE
]]
local MockDataStoreServiceModule = script.MockDataStoreService
local shouldUseMock = false
if game.GameId == 0 then -- Local place file
shouldUseMock = true
elseif game:GetService("RunService"):IsStudio() then -- Published file in Studio
local status, message = pcall(function()
-- This will error if current instance has no Studio API access:
game:GetService("DataStoreService"):GetDataStore("__TEST"):SetAsync("__TEST", "__TEST_" .. os.time())
end)
if not status and message:find("403", 1, true) then -- HACK
-- Can connect to datastores, but no API access
shouldUseMock = true
end
end
return function(forceMockDatastore)
-- Return the mock or actual service depending on environment:
if shouldUseMock or forceMockDatastore then
warn(":: Adonis :: Using MockDataStoreService instead of DataStoreService")
return require(MockDataStoreServiceModule)
else
return game:GetService("DataStoreService")
end
end
| 284 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Server/Dependencies/FetchF3X.luau | --[[
A way to dynamically fetch the F3X module with require()'s ModuleScript sandboxing.
]]
script:Destroy()
-- selene: allow(incorrect_standard_library_use)
script = nil
return select(2, pcall(function()
return require(580330877)()
end)) or true
| 63 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Server/Dependencies/Loadstring/LuaU.luau | --# selene: allow(incorrect_standard_library_use, multiple_statements, shadowing, unused_variable, empty_if, divide_by_zero, unbalanced_assignments)
--[[--------------------------------------------------------------------
ldump.lua
Save precompiled Lua chunks
This file is part of Yueliang.
Copyright (c) 2006 Kein-Hong Man <khman@users.sf.net>
The COPYRIGHT file describes the conditions
under which this software may be distributed.
See the ChangeLog for more information.
----------------------------------------------------------------------]]
--[[--------------------------------------------------------------------
-- Notes:
-- * WARNING! byte order (little endian) and data type sizes for header
-- signature values hard-coded; see luaU:header
-- * chunk writer generators are included, see below
-- * one significant difference is that instructions are still in table
-- form (with OP/A/B/C/Bx fields) and luaP:Instruction() is needed to
-- convert them into 4-char strings
--
-- Not implemented:
-- * DumpVar, DumpMem has been removed
-- * DumpVector folded into folded into DumpDebug, DumpCode
--
-- Added:
-- * for convenience, the following two functions have been added:
-- luaU:make_setS: create a chunk writer that writes to a string
-- luaU:make_setF: create a chunk writer that writes to a file
-- (lua.h contains a typedef for lua_Writer/lua_Chunkwriter, and
-- a Lua-based implementation exists, writer() in lstrlib.c)
-- * luaU:ttype(o) (from lobject.h)
-- * for converting number types to its binary equivalent:
-- luaU:from_double(x): encode double value for writing
-- luaU:from_int(x): encode integer value for writing
-- (error checking is limited for these conversion functions)
-- (double conversion does not support denormals or NaNs)
--
-- Changed in 5.1.x:
-- * the dumper was mostly rewritten in Lua 5.1.x, so notes on the
-- differences between 5.0.x and 5.1.x is limited
-- * LUAC_VERSION bumped to 0x51, LUAC_FORMAT added
-- * developer is expected to adjust LUAC_FORMAT in order to identify
-- non-standard binary chunk formats
-- * header signature code is smaller, has been simplified, and is
-- tested as a single unit; its logic is shared with the undumper
-- * no more endian conversion, invalid endianness mean rejection
-- * opcode field sizes are no longer exposed in the header
-- * code moved to front of a prototype, followed by constants
-- * debug information moved to the end of the binary chunk, and the
-- relevant functions folded into a single function
-- * luaU:dump returns a writer status code
-- * chunk writer now implements status code because dumper uses it
-- * luaU:endianness removed
----------------------------------------------------------------------]]
--requires luaP
local luaU = {}
local luaP = require(script.Parent.LuaP)
-- mark for precompiled code ('<esc>Lua') (from lua.h)
luaU.LUA_SIGNATURE = "\27Lua"
-- constants used by dumper (from lua.h)
luaU.LUA_TNUMBER = 3
luaU.LUA_TSTRING = 4
luaU.LUA_TNIL = 0
luaU.LUA_TBOOLEAN = 1
luaU.LUA_TNONE = -1
-- constants for header of binary files (from lundump.h)
luaU.LUAC_VERSION = 0x51 -- this is Lua 5.1
luaU.LUAC_FORMAT = 0 -- this is the official format
luaU.LUAC_HEADERSIZE = 12 -- size of header of binary files
--[[--------------------------------------------------------------------
-- Additional functions to handle chunk writing
-- * to use make_setS and make_setF, see test_ldump.lua elsewhere
----------------------------------------------------------------------]]
------------------------------------------------------------------------
-- create a chunk writer that writes to a string
-- * returns the writer function and a table containing the string
-- * to get the final result, look in buff.data
------------------------------------------------------------------------
function luaU:make_setS()
local buff = {}
buff.data = ""
local writer =
function(s, buff) -- chunk writer
if not s then return 0 end
buff.data = buff.data..s
return 0
end
return writer, buff
end
------------------------------------------------------------------------
-- create a chunk writer that writes to a file
-- * returns the writer function and a table containing the file handle
-- * if a nil is passed, then writer should close the open file
------------------------------------------------------------------------
--[[
function luaU:make_setF(filename)
local buff = {}
buff.h = io.open(filename, "wb")
if not buff.h then return nil end
local writer =
function(s, buff) -- chunk writer
if not buff.h then return 0 end
if not s then
if buff.h:close() then return 0 end
else
if buff.h:write(s) then return 0 end
end
return 1
end
return writer, buff
end--]]
------------------------------------------------------------------------
-- works like the lobject.h version except that TObject used in these
-- scripts only has a 'value' field, no 'tt' field (native types used)
------------------------------------------------------------------------
function luaU:ttype(o)
local tt = type(o.value)
if tt == "number" then return self.LUA_TNUMBER
elseif tt == "string" then return self.LUA_TSTRING
elseif tt == "nil" then return self.LUA_TNIL
elseif tt == "boolean" then return self.LUA_TBOOLEAN
else
return self.LUA_TNONE -- the rest should not appear
end
end
-----------------------------------------------------------------------
-- converts a IEEE754 double number to an 8-byte little-endian string
-- * luaU:from_double() and luaU:from_int() are adapted from ChunkBake
-- * supports +/- Infinity, but not denormals or NaNs
-----------------------------------------------------------------------
function luaU:from_double(x)
local function grab_byte(v)
local c = v % 256
return (v - c) / 256, string.char(c)
end
local sign = 0
if x < 0 then sign = 1; x = -x end
local mantissa, exponent = math.frexp(x)
if x == 0 then -- zero
mantissa, exponent = 0, 0
elseif x == 1/0 then
mantissa, exponent = 0, 2047
else
mantissa = (mantissa * 2 - 1) * math.ldexp(0.5, 53)
exponent = exponent + 1022
end
local v, byte = "" -- convert to bytes
x = math.floor(mantissa)
for i = 1,6 do
x, byte = grab_byte(x); v = v..byte -- 47:0
end
x, byte = grab_byte(exponent * 16 + x); v = v..byte -- 55:48
x, byte = grab_byte(sign * 128 + x); v = v..byte -- 63:56
return v
end
-----------------------------------------------------------------------
-- converts a number to a little-endian 32-bit integer string
-- * input value assumed to not overflow, can be signed/unsigned
-----------------------------------------------------------------------
function luaU:from_int(x)
local v = ""
x = math.floor(x)
if x < 0 then x = 4294967296 + x end -- ULONG_MAX+1
for i = 1, 4 do
local c = x % 256
v = v..string.char(c); x = math.floor(x / 256)
end
return v
end
--[[--------------------------------------------------------------------
-- Functions to make a binary chunk
-- * many functions have the size parameter removed, since output is
-- in the form of a string and some sizes are implicit or hard-coded
----------------------------------------------------------------------]]
--[[--------------------------------------------------------------------
-- struct DumpState:
-- L -- lua_State (not used in this script)
-- writer -- lua_Writer (chunk writer function)
-- data -- void* (chunk writer context or data already written)
-- strip -- if true, don't write any debug information
-- status -- if non-zero, an error has occured
----------------------------------------------------------------------]]
------------------------------------------------------------------------
-- dumps a block of bytes
-- * lua_unlock(D.L), lua_lock(D.L) unused
------------------------------------------------------------------------
function luaU:DumpBlock(b, D)
if D.status == 0 then
-- lua_unlock(D->L);
D.status = D.write(b, D.data)
-- lua_lock(D->L);
end
end
------------------------------------------------------------------------
-- dumps a char
------------------------------------------------------------------------
function luaU:DumpChar(y, D)
self:DumpBlock(string.char(y), D)
end
------------------------------------------------------------------------
-- dumps a 32-bit signed or unsigned integer (for int) (hard-coded)
------------------------------------------------------------------------
function luaU:DumpInt(x, D)
self:DumpBlock(self:from_int(x), D)
end
------------------------------------------------------------------------
-- dumps a lua_Number (hard-coded as a double)
------------------------------------------------------------------------
function luaU:DumpNumber(x, D)
self:DumpBlock(self:from_double(x), D)
end
------------------------------------------------------------------------
-- dumps a Lua string (size type is hard-coded)
------------------------------------------------------------------------
function luaU:DumpString(s, D)
if s == nil then
self:DumpInt(0, D)
else
s = s.."\0" -- include trailing '\0'
self:DumpInt(#s, D)
self:DumpBlock(s, D)
end
end
------------------------------------------------------------------------
-- dumps instruction block from function prototype
------------------------------------------------------------------------
function luaU:DumpCode(f, D)
local n = f.sizecode
--was DumpVector
self:DumpInt(n, D)
for i = 0, n - 1 do
self:DumpBlock(luaP:Instruction(f.code[i]), D)
end
end
------------------------------------------------------------------------
-- dump constant pool from function prototype
-- * bvalue(o), nvalue(o) and rawtsvalue(o) macros removed
------------------------------------------------------------------------
function luaU:DumpConstants(f, D)
local n = f.sizek
self:DumpInt(n, D)
for i = 0, n - 1 do
local o = f.k[i] -- TValue
local tt = self:ttype(o)
self:DumpChar(tt, D)
if tt == self.LUA_TNIL then
elseif tt == self.LUA_TBOOLEAN then
self:DumpChar(o.value and 1 or 0, D)
elseif tt == self.LUA_TNUMBER then
self:DumpNumber(o.value, D)
elseif tt == self.LUA_TSTRING then
self:DumpString(o.value, D)
else
--lua_assert(0) -- cannot happen
end
end
n = f.sizep
self:DumpInt(n, D)
for i = 0, n - 1 do
self:DumpFunction(f.p[i], f.source, D)
end
end
------------------------------------------------------------------------
-- dump debug information
------------------------------------------------------------------------
function luaU:DumpDebug(f, D)
local n
n = D.strip and 0 or f.sizelineinfo -- dump line information
--was DumpVector
self:DumpInt(n, D)
for i = 0, n - 1 do
self:DumpInt(f.lineinfo[i], D)
end
n = D.strip and 0 or f.sizelocvars -- dump local information
self:DumpInt(n, D)
for i = 0, n - 1 do
self:DumpString(f.locvars[i].varname, D)
self:DumpInt(f.locvars[i].startpc, D)
self:DumpInt(f.locvars[i].endpc, D)
end
n = D.strip and 0 or f.sizeupvalues -- dump upvalue information
self:DumpInt(n, D)
for i = 0, n - 1 do
self:DumpString(f.upvalues[i], D)
end
end
------------------------------------------------------------------------
-- dump child function prototypes from function prototype
------------------------------------------------------------------------
function luaU:DumpFunction(f, p, D)
local source = f.source
if source == p or D.strip then source = nil end
self:DumpString(source, D)
self:DumpInt(f.lineDefined, D)
self:DumpInt(f.lastlinedefined, D)
self:DumpChar(f.nups, D)
self:DumpChar(f.numparams, D)
self:DumpChar(f.is_vararg, D)
self:DumpChar(f.maxstacksize, D)
self:DumpCode(f, D)
self:DumpConstants(f, D)
self:DumpDebug(f, D)
end
------------------------------------------------------------------------
-- dump Lua header section (some sizes hard-coded)
------------------------------------------------------------------------
function luaU:DumpHeader(D)
local h = self:header()
assert(#h == self.LUAC_HEADERSIZE) -- fixed buffer now an assert
self:DumpBlock(h, D)
end
------------------------------------------------------------------------
-- make header (from lundump.c)
-- returns the header string
------------------------------------------------------------------------
function luaU:header()
local x = 1
return self.LUA_SIGNATURE..
string.char(
self.LUAC_VERSION,
self.LUAC_FORMAT,
x, -- endianness (1=little)
4, -- sizeof(int)
4, -- sizeof(size_t)
4, -- sizeof(Instruction)
8, -- sizeof(lua_Number)
0) -- is lua_Number integral?
end
------------------------------------------------------------------------
-- dump Lua function as precompiled chunk
-- (lua_State* L, const Proto* f, lua_Writer w, void* data, int strip)
-- * w, data are created from make_setS, make_setF
------------------------------------------------------------------------
function luaU:dump(L, f, w, data, strip)
local D = {} -- DumpState
D.L = L
D.write = w
D.data = data
D.strip = strip
D.status = 0
self:DumpHeader(D)
self:DumpFunction(f, nil, D)
-- added: for a chunk writer writing to a file, this final call with
-- nil data is to indicate to the writer to close the file
D.write(nil, D.data)
return D.status
end
return luaU
| 3,201 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Server/Dependencies/Loadstring/LuaX.luau | --# selene: allow(incorrect_standard_library_use, multiple_statements, shadowing, unused_variable, empty_if, divide_by_zero, unbalanced_assignments)
--[[--------------------------------------------------------------------
llex.lua
Lua lexical analyzer in Lua
This file is part of Yueliang.
Copyright (c) 2005-2006 Kein-Hong Man <khman@users.sf.net>
The COPYRIGHT file describes the conditions
under which this software may be distributed.
See the ChangeLog for more information.
----------------------------------------------------------------------]]
--[[--------------------------------------------------------------------
-- Notes:
-- * intended to 'imitate' llex.c code; performance is not a concern
-- * tokens are strings; code structure largely retained
-- * deleted stuff (compared to llex.c) are noted, comments retained
-- * nextc() returns the currently read character to simplify coding
-- here; next() in llex.c does not return anything
-- * compatibility code is marked with "--#" comments
--
-- Added:
-- * luaX:chunkid (function luaO_chunkid from lobject.c)
-- * luaX:str2d (function luaO_str2d from lobject.c)
-- * luaX.LUA_QS used in luaX:lexerror (from luaconf.h)
-- * luaX.LUA_COMPAT_LSTR in luaX:read_long_string (from luaconf.h)
-- * luaX.MAX_INT used in luaX:inclinenumber (from llimits.h)
-- Luau specific additions by ccuser44:
-- * Added Luau number handling
-- * Added post 5.1 string handling
-- * Added env localisation aiding for parser
-- * Made lexer pre-lex lex tree instead of using on-the-fly lexing.
-- Necessary for env localisation and more efficient than building
-- a parse tree (which would require full pre-lexing as well)
--
-- To use the lexer:
-- (1) luaX:init() to initialize the lexer
-- (2) luaX:setinput() to set the input stream to lex
-- (3) call luaX:next() or luaX:luaX:lookahead() to get tokens,
-- until "TK_EOS": luaX:next()
-- * since EOZ is returned as a string, be careful when regexp testing
--
-- Not implemented:
-- * luaX_newstring: not required by this Lua implementation
-- * buffer MAX_SIZET size limit (from llimits.h) test not implemented
-- in the interest of performance
-- * locale-aware number handling is largely redundant as Lua's
-- tonumber() function is already capable of this
--
-- Changed in 5.1.x:
-- * TK_NAME token order moved down
-- * string representation for TK_NAME, TK_NUMBER, TK_STRING changed
-- * token struct renamed to lower case (LS -> ls)
-- * LexState struct: removed nestlevel, added decpoint
-- * error message functions have been greatly simplified
-- * token2string renamed to luaX_tokens, exposed in llex.h
-- * lexer now handles all kinds of newlines, including CRLF
-- * shbang first line handling removed from luaX:setinput;
-- it is now done in lauxlib.c (luaL_loadfile)
-- * next(ls) macro renamed to nextc(ls) due to new luaX_next function
-- * EXTRABUFF and MAXNOCHECK removed due to lexer changes
-- * checkbuffer(ls, len) macro deleted
-- * luaX:read_numeral now has 3 support functions: luaX:trydecpoint,
-- luaX:buffreplace and (luaO_str2d from lobject.c) luaX:str2d
-- * luaX:read_numeral is now more promiscuous in slurping characters;
-- hexadecimal numbers was added, locale-aware decimal points too
-- * luaX:skip_sep is new; used by luaX:read_long_string
-- * luaX:read_long_string handles new-style long blocks, with some
-- optional compatibility code
-- * luaX:llex: parts changed to support new-style long blocks
-- * luaX:llex: readname functionality has been folded in
-- * luaX:llex: removed test for control characters
--
--------------------------------------------------------------------]]
local luaZ = require(script.Parent.LuaZ)
local luaX = {}
-- FIRST_RESERVED is not required as tokens are manipulated as strings
-- TOKEN_LEN deleted; maximum length of a reserved word not needed
------------------------------------------------------------------------
-- "ORDER RESERVED" deleted; enumeration in one place: luaX.RESERVED
------------------------------------------------------------------------
-- terminal symbols denoted by reserved words: TK_AND to TK_WHILE
-- other terminal symbols: TK_NAME to TK_EOS
luaX.RESERVED = [[
TK_AND and
TK_BREAK break
TK_CONTINUE continue
TK_DO do
TK_ELSE else
TK_ELSEIF elseif
TK_END end
TK_FALSE false
TK_FOR for
TK_FUNCTION function
TK_IF if
TK_IN in
TK_LOCAL local
TK_NIL nil
TK_NOT not
TK_OR or
TK_REPEAT repeat
TK_RETURN return
TK_THEN then
TK_TRUE true
TK_UNTIL until
TK_WHILE while
TK_ASSIGN_ADD +=
TK_ASSIGN_SUB -=
TK_ASSIGN_MUL *=
TK_ASSIGN_DIV /=
TK_ASSIGN_MOD %=
TK_ASSIGN_POW ^=
TK_ASSIGN_CONCAT ..=
TK_CONCAT ..
TK_DOTS ...
TK_EQ ==
TK_GE >=
TK_LE <=
TK_NE ~=
TK_NAME <name>
TK_NUMBER <number>
TK_STRING <string>
TK_EOS <eof>]]
-- NUM_RESERVED is not required; number of reserved words
--[[--------------------------------------------------------------------
-- Instead of passing seminfo, the Token struct (e.g. ls.t) is passed
-- so that lexer functions can use its table element, ls.t.seminfo
--
-- SemInfo (struct no longer needed, a mixed-type value is used)
--
-- Token (struct of ls.t and ls.lookahead):
-- token -- token symbol
-- seminfo -- semantics information
--
-- LexState (struct of ls; ls is initialized by luaX:setinput):
-- current -- current character (charint)
-- linenumber -- input line counter
-- lastline -- line of last token 'consumed'
-- t -- current token (table: struct Token)
-- lookahead -- look ahead token (table: struct Token)
-- fs -- 'FuncState' is private to the parser
-- L -- LuaState
-- z -- input stream
-- buff -- buffer for tokens
-- source -- current source name
-- decpoint -- locale decimal point
-- nestlevel -- level of nested non-terminals
----------------------------------------------------------------------]]
-- luaX.tokens (was luaX_tokens) is now a hash; see luaX:init
luaX.MAXSRC = 80
luaX.MAX_INT = 2147483645 -- constants from elsewhere (see above)
luaX.LUA_QS = "'%s'"
luaX.LUA_COMPAT_LSTR = 1
--luaX.MAX_SIZET = 4294967293
------------------------------------------------------------------------
-- LuaU specific constants
-- * luaX.DEOP: Tokens that cause env deoptimisation
-- * luaX.GLOBALVARS: Tokens that are globals in the env
------------------------------------------------------------------------
luaX.DEOP = {
["getf".."env"] = true, ["setf".."env"] = true, ["_".."ENV"] = true
}
luaX.GLOBALVARS = [[
_G _VERSION
assert collectgarbage dofile error getmetatable ipairs
load loadfile module next pairs pcall
print rawequal rawget rawset require select
setmetatable tonumber tostring type unpack xpcall
newproxy gcinfo warn
game plugin script shared workspace
coroutine debug io math os package
string table bit32 utf8
DebuggerManager delay PluginManager settings spawn tick
time UserSettings wait
task
Axes BrickColor CatalogSearchParams CFrame Color3 ColorSequence
ColorSequenceKeypoint DateTime DockWidgetPluginGuiInfo Enum Faces FloatCurveKey
Font Instance NumberRange NumberSequence NumberSequenceKeypoint OverlapParams
PathWaypoint PhysicalProperties Random Ray RaycastParams Rect
Region3 Region3int16 RotationCurveKey SharedTable TweenInfo UDim
UDim2 Vector2 Vector2int16 Vector3 Vector3int16
]]
------------------------------------------------------------------------
-- initialize lexer
-- * original luaX_init has code to create and register token strings
-- * luaX.tokens: TK_* -> token
-- * luaX.enums: token -> TK_* (used in luaX:llex)
------------------------------------------------------------------------
function luaX:init()
local tokens, enums, globalvars = {}, {}, {}
for v in string.gmatch(self.RESERVED, "[^\n]+") do
local _, _, tok, str = string.find(v, "(%S+)%s+(%S+)")
tokens[tok] = str
enums[str] = tok
end
for v in string.gmatch(self.GLOBALVARS, "[^%s]+") do
globalvars[v] = true
end
self.tokens = tokens
self.enums = enums
self.globalvars = globalvars
end
------------------------------------------------------------------------
-- returns a suitably-formatted chunk name or id
-- * from lobject.c, used in llex.c and ldebug.c
-- * the result, out, is returned (was first argument)
------------------------------------------------------------------------
function luaX:chunkid(source, bufflen)
local out
local first = string.sub(source, 1, 1)
if first == "=" then
out = string.sub(source, 2, bufflen) -- remove first char
else -- out = "source", or "...source"
if first == "@" then
source = string.sub(source, 2) -- skip the '@'
bufflen = bufflen - #" '...' "
local l = #source
out = ""
if l > bufflen then
source = string.sub(source, 1 + l - bufflen) -- get last part of file name
out = out.."..."
end
out = out..source
else -- out = [string "string"]
local len = string.find(source, "[\n\r]") -- stop at first newline
len = len and (len - 1) or #source
bufflen = bufflen - #(" [string \"...\"] ")
if len > bufflen then len = bufflen end
out = "[string \""
if len < #source then -- must truncate?
out = out..string.sub(source, 1, len).."..."
else
out = out..source
end
out = out.."\"]"
end
end
return out
end
--[[--------------------------------------------------------------------
-- Support functions for lexer
-- * all lexer errors eventually reaches lexerror:
syntaxerror -> lexerror
----------------------------------------------------------------------]]
------------------------------------------------------------------------
-- look up token and return keyword if found (also called by parser)
------------------------------------------------------------------------
function luaX:token2str(ls, token)
if string.sub(token, 1, 3) ~= "TK_" then
if string.find(token, "%c") then
return string.format("char(%d)", string.byte(token))
end
return token
else
end
return self.tokens[token]
end
------------------------------------------------------------------------
-- throws a lexer error
-- * txtToken has been made local to luaX:lexerror
-- * can't communicate LUA_ERRSYNTAX, so it is unimplemented
------------------------------------------------------------------------
function luaX:lexerror(ls, msg, token)
local function txtToken(ls, token)
if token == "TK_NAME" or
token == "TK_STRING" or
token == "TK_NUMBER" then
return ls.buff
else
return self:token2str(ls, token)
end
end
local buff = self:chunkid(ls.source, self.MAXSRC)
local msg = string.format("%s:%d: %s", buff, ls.linenumber, msg)
if token then
msg = string.format("%s near "..self.LUA_QS, msg, txtToken(ls, token))
end
-- luaD_throw(ls->L, LUA_ERRSYNTAX)
error(msg)
end
------------------------------------------------------------------------
-- throws a syntax error (mainly called by parser)
-- * ls.t.token has to be set by the function calling luaX:llex
-- (see luaX:next and luaX:lookahead elsewhere in this file)
------------------------------------------------------------------------
function luaX:syntaxerror(ls, msg)
self:lexerror(ls, msg, ls.t.token)
end
------------------------------------------------------------------------
-- move on to next line
------------------------------------------------------------------------
function luaX:currIsNewline(ls)
return ls.current == "\n" or ls.current == "\r"
end
function luaX:inclinenumber(ls)
local old = ls.current
-- lua_assert(currIsNewline(ls))
self:nextc(ls) -- skip '\n' or '\r'
if self:currIsNewline(ls) and ls.current ~= old then
self:nextc(ls) -- skip '\n\r' or '\r\n'
end
ls.linenumber = ls.linenumber + 1
if ls.linenumber >= self.MAX_INT then
self:syntaxerror(ls, "chunk has too many lines")
end
end
------------------------------------------------------------------------
-- initializes an input stream for lexing
-- * if ls (the lexer state) is passed as a table, then it is filled in,
-- otherwise it has to be retrieved as a return value
-- * LUA_MINBUFFER not used; buffer handling not required any more
------------------------------------------------------------------------
function luaX:setinput(L, ls, z, source)
if not ls then ls = {} end -- create struct
if not ls.lookahead then ls.lookahead = {} end
if not ls.t then ls.t = {} end
ls.decpoint = "."
ls.L = L
ls.lookahead.token = "TK_EOS" -- no look-ahead token
ls.z = z
ls.fs = nil
ls.linenumber = 1
ls.lastline = 1
ls.source = source
ls.safeenv = true
ls.usedglobals = {}
self:nextc(ls) -- read first char
end
--[[--------------------------------------------------------------------
-- LEXICAL ANALYZER
----------------------------------------------------------------------]]
------------------------------------------------------------------------
-- checks if current character read is found in the set 'set'
------------------------------------------------------------------------
function luaX:check_next(ls, set)
if not string.find(set, ls.current, 1, 1) then
return false
end
self:save_and_next(ls)
return true
end
------------------------------------------------------------------------
-- retrieve next token, checking the lookahead buffer if necessary
-- * note that the macro next(ls) in llex.c is now luaX:nextc
-- * utilized used in lparser.c (various places)
------------------------------------------------------------------------
function luaX:next(ls)
ls.lastline = ls.linenumber
if ls.lookahead.token ~= "TK_EOS" then -- is there a look-ahead token?
-- this must be copy-by-value
ls.t.seminfo = ls.lookahead.seminfo -- use this one
ls.t.token = ls.lookahead.token
ls.lookahead.token = "TK_EOS" -- and discharge it
else
ls.t.token, ls.t.seminfo, ls.linenumber = self:poptk(ls) -- read next token
end
end
------------------------------------------------------------------------
-- fill in the lookahead buffer
-- * utilized used in lparser.c:constructor
-- * Does currently nothing because of lexer caching
------------------------------------------------------------------------
function luaX:lookahead(ls)
-- lua_assert(ls.lookahead.token == "TK_EOS")
ls.lookahead.token, ls.lookahead.seminfo, ls.lookahead.linenumber = self:poptk(ls)--self:llex(ls, ls.lookahead)
end
------------------------------------------------------------------------
-- gets the next character and returns it
-- * this is the next() macro in llex.c; see notes at the beginning
------------------------------------------------------------------------
function luaX:nextc(ls)
local c = luaZ:zgetc(ls.z)
ls.current = c
return c
end
------------------------------------------------------------------------
-- saves the given character into the token buffer
-- * buffer handling code removed, not used in this implementation
-- * test for maximum token buffer length not used, makes things faster
------------------------------------------------------------------------
function luaX:save(ls, c)
local buff = ls.buff
-- if you want to use this, please uncomment luaX.MAX_SIZET further up
--if #buff > self.MAX_SIZET then
-- self:lexerror(ls, "lexical element too long")
--end
ls.buff = buff..c
end
------------------------------------------------------------------------
-- save current character into token buffer, grabs next character
-- * like luaX:nextc, returns the character read for convenience
------------------------------------------------------------------------
function luaX:save_and_next(ls)
self:save(ls, ls.current)
return self:nextc(ls)
end
------------------------------------------------------------------------
-- LUA_NUMBER
-- * luaX:read_numeral is the main lexer function to read a number
-- * luaX:str2d, luaX:buffreplace, luaX:trydecpoint are support functions
------------------------------------------------------------------------
------------------------------------------------------------------------
-- string to number converter (was luaO_str2d from lobject.c)
-- * returns the number, nil if fails (originally returns a boolean)
-- * conversion function originally lua_str2number(s,p), a macro which
-- maps to the strtod() function by default (from luaconf.h)
-- * ccuser44 was here to add support for binary intiger constants and
-- intiger decimal seperators
------------------------------------------------------------------------
function luaX:str2d(s)
-- Support for Luau decimal seperators for integer literals
if string.match(string.lower(s), "[^b%da-f_]_") or string.match(string.lower(s), "_[^%da-f_]") then
return nil
end
s = string.gsub(s, "_", "")
local result = tonumber(s)
if result then return result end
-- conversion failed
if string.lower(string.sub(s, 1, 2)) == "0x" then -- maybe an hexadecimal constant?
result = tonumber(s, 16)
if result then return result end -- most common case
-- Was: invalid trailing characters?
-- In C, this function then skips over trailing spaces.
-- true is returned if nothing else is found except for spaces.
-- If there is still something else, then it returns a false.
-- All this is not necessary using Lua's tonumber.
elseif string.lower(string.sub(s, 1, 2)) == "0b" then -- binary intiger constants
if string.match(string.sub(s, 3), "[^01]") then
return nil
end
local bin = string.reverse(string.sub(s, 3))
local sum = 0
for i = 1, string.len(bin) do
sum = sum + bit32.lshift(string.sub(bin, i, i) == "1" and 1 or 0, i - 1)
end
return sum
end
return nil
end
------------------------------------------------------------------------
-- single-character replacement, for locale-aware decimal points
------------------------------------------------------------------------
function luaX:buffreplace(ls, from, to)
local result, buff = "", ls.buff
for p = 1, #buff do
local c = string.sub(buff, p, p)
if c == from then c = to end
result = result..c
end
ls.buff = result
end
------------------------------------------------------------------------
-- Attempt to convert a number by translating '.' decimal points to
-- the decimal point character used by the current locale. This is not
-- needed in Yueliang as Lua's tonumber() is already locale-aware.
-- Instead, the code is here in case the user implements localeconv().
------------------------------------------------------------------------
function luaX:trydecpoint(ls, Token)
-- format error: try to update decimal point separator
local old = ls.decpoint
-- translate the following to Lua if you implement localeconv():
-- struct lconv *cv = localeconv();
-- ls->decpoint = (cv ? cv->decimal_point[0] : '.');
self:buffreplace(ls, old, ls.decpoint) -- try updated decimal separator
local seminfo = self:str2d(ls.buff)
Token.seminfo = seminfo
if not seminfo then
-- format error with correct decimal point: no more options
self:buffreplace(ls, ls.decpoint, ".") -- undo change (for error message)
self:lexerror(ls, "malformed number", "TK_NUMBER")
end
end
------------------------------------------------------------------------
-- main number conversion function
-- * "^%w$" needed in the scan in order to detect "EOZ"
------------------------------------------------------------------------
function luaX:read_numeral(ls, Token)
-- lua_assert(string.find(ls.current, "%d"))
repeat
self:save_and_next(ls)
until string.find(ls.current, "%D") and ls.current ~= "."
if self:check_next(ls, "Ee") then -- 'E'?
self:check_next(ls, "+-") -- optional exponent sign
end
while string.find(ls.current, "^%w$") or ls.current == "_" do
self:save_and_next(ls)
end
self:buffreplace(ls, ".", ls.decpoint) -- follow locale for decimal point
local seminfo = self:str2d(ls.buff)
Token.seminfo = seminfo
if not seminfo then -- format error?
self:trydecpoint(ls, Token) -- try to update decimal point separator
end
end
------------------------------------------------------------------------
-- count separators ("=") in a long string delimiter
-- * used by luaX:read_long_string
------------------------------------------------------------------------
function luaX:skip_sep(ls)
local count = 0
local s = ls.current
-- lua_assert(s == "[" or s == "]")
self:save_and_next(ls)
while ls.current == "=" do
self:save_and_next(ls)
count = count + 1
end
return (ls.current == s) and count or (-count) - 1
end
------------------------------------------------------------------------
-- reads a long string or long comment
------------------------------------------------------------------------
function luaX:read_long_string(ls, Token, sep)
local cont = 0
self:save_and_next(ls) -- skip 2nd '['
if self:currIsNewline(ls) then -- string starts with a newline?
self:inclinenumber(ls) -- skip it
end
while true do
local c = ls.current
if c == "EOZ" then
self:lexerror(ls, Token and "unfinished long string" or
"unfinished long comment", "TK_EOS")
elseif c == "[" then
--# compatibility code start
if self.LUA_COMPAT_LSTR then
if self:skip_sep(ls) == sep then
self:save_and_next(ls) -- skip 2nd '['
cont = cont + 1
--# compatibility code start
if self.LUA_COMPAT_LSTR == 1 then
if sep == 0 then
self:lexerror(ls, "nesting of [[...]] is deprecated", "[")
end
end
--# compatibility code end
end
end
--# compatibility code end
elseif c == "]" then
if self:skip_sep(ls) == sep then
self:save_and_next(ls) -- skip 2nd ']'
--# compatibility code start
if self.LUA_COMPAT_LSTR and self.LUA_COMPAT_LSTR == 2 then
cont = cont - 1
if sep == 0 and cont >= 0 then break end
end
--# compatibility code end
break
end
elseif self:currIsNewline(ls) then
self:save(ls, "\n")
self:inclinenumber(ls)
if not Token then ls.buff = "" end -- avoid wasting space
else -- default
if Token then
self:save_and_next(ls)
else
self:nextc(ls)
end
end--if c
end--while
if Token then
local p = 3 + sep
Token.seminfo = string.sub(ls.buff, p, -p)
end
end
------------------------------------------------------------------------
-- reads a string
-- * has been restructured significantly compared to the original C code
-- * ccuser44 was here to add support for UTF8 string literals,
-- hex numerical string literals and the \z string literal
------------------------------------------------------------------------
function luaX:read_string(ls, del, Token)
self:save_and_next(ls)
while ls.current ~= del do
local c = ls.current
if c == "EOZ" then
self:lexerror(ls, "unfinished string", "TK_EOS")
elseif self:currIsNewline(ls) then
self:lexerror(ls, "unfinished string", "TK_STRING")
elseif c == "\\" then
c = self:nextc(ls) -- do not save the '\'
if self:currIsNewline(ls) then -- go through
self:save(ls, "\n")
self:inclinenumber(ls)
elseif c ~= "EOZ" then -- will raise an error next loop
-- escapes handling greatly simplified here:
local i = string.find("abfnrtv", c, 1, 1)
if i then
self:save(ls, string.sub("\a\b\f\n\r\t\v", i, i))
self:nextc(ls)
elseif c == "u" then -- UTF8 string literal
assert(utf8 and utf8.char, "No utf8 library found! Cannot decode UTF8 string literal!")
if self:nextc(ls) ~= "{" then
self:lexerror("Sounds like a skill issue", "TK_STRING")
end
local unicodeCharacter = ""
while true do
c = self:nextc(ls)
if c == "}" then
break
elseif string.match(c, "%x") then
unicodeCharacter = unicodeCharacter .. c
else
self:lexerror(string.format("Invalid unicode character sequence. Expected alphanumeric character, got %s. Did you forget to close the code sequence with a curly bracket?", c), "TK_STRING")
end
end
if not tonumber(unicodeCharacter, 16) or not utf8.char(tonumber(unicodeCharacter, 16)) then
self:lexerror(string.format("Invalid UTF8 char %s. Expected a valid UTF8 character code", unicodeCharacter), "TK_STRING")
else
self:save(ls, utf8.char(tonumber(unicodeCharacter)))
end
elseif string.lower(c) == "x" then -- Hex numeral literal
local hexNum = self:nextc(ls)..self:nextc(ls)
if not string.match(string.upper(hexNum), "%x") then
self:lexerror(string.format("Invalid hex string literal. Expected valid string literal, got %s", hexNum), "TK_STRING")
else
self:save(ls, string.char(tonumber(hexNum, 16)))
end
elseif string.lower(c) == "z" then -- Support \z string literal. I'm not sure why you would want to use this
local c = luaX:nextc(ls)
if c == del then
break
else
self:save(ls, c)
end
elseif not string.find(c, "%d") then
self:save_and_next(ls) -- handles \\, \", \', and \?
else -- \xxx
c, i = 0, 0
repeat
c = 10 * c + ls.current
self:nextc(ls)
i = i + 1
until i >= 3 or not string.find(ls.current, "%d")
if c > 255 then -- UCHAR_MAX
self:lexerror(ls, "escape sequence too large", "TK_STRING")
end
self:save(ls, string.char(c))
end
end
else
self:save_and_next(ls)
end--if c
end--while
self:save_and_next(ls) -- skip delimiter
Token.seminfo = string.sub(ls.buff, 2, -2)
end
------------------------------------------------------------------------
-- lexer cache
-- * Pre-lex the whole lex tree and then cache it
-- Allow global optimisation by scanning all lex tokens before parsing
------------------------------------------------------------------------
function luaX:poptk(ls)
if ls.lexercache then
local tkdata = ls.lexercache
local data = tkdata[tkdata.n]
tkdata.n, tkdata[tkdata.n] = tkdata.n - 1, nil
return data.type or "TK_EOS", data.seminfo or "", data.line
end
-- Generate lex tree stack
local tkdata = {}
ls.lexercache = tkdata
while true do
local type = luaX:llex(ls, ls.t)
table.insert(tkdata, {
type = type,
seminfo = ls.t.seminfo,
line = ls.linenumber,
})
if type == "TK_EOS" then
break
end
end
-- Reverse lex tree stack
local len = #tkdata
tkdata.n = len
ls.linenumber, ls.lastline, ls.lookahead.token = 1, 1, "TK_EOS"
for i = 1, math.floor(len/2) do
local j = len - i + 1
tkdata[i], tkdata[j] = tkdata[j], tkdata[i]
end
-- Ugly hack to support global localisation without parser logic
-- TODO: Switch to parser logic LOCALEXP(name) = GLOBALEXP(name), ...
local usedglobals = ls.usedglobals
if ls.safeenv and #usedglobals > 0 then
for i = #usedglobals, 1, -1 do
tkdata.n = tkdata.n + 2
tkdata[tkdata.n - 1], tkdata[tkdata.n] = {
type = "TK_NAME",
seminfo = usedglobals[i],
line = 1
}, {
type = ",",
seminfo = ",",
line = 1
}
end
tkdata[tkdata.n] = {
type = "=",
seminfo = "=",
line = 1
}
for i = #usedglobals, 1, -1 do
tkdata.n = tkdata.n + 2
tkdata[tkdata.n - 1], tkdata[tkdata.n] = {
type = "TK_NAME",
seminfo = usedglobals[i],
line = 1
}, {
type = ",",
seminfo = ",",
line = 1
}
end
tkdata[tkdata.n] = {
type = "TK_LOCAL",
seminfo = "local",
line = 1
}
end
return self:poptk(ls)
end
------------------------------------------------------------------------
-- main lexer function
------------------------------------------------------------------------
function luaX:llex(ls, Token)
ls.buff = ""
while true do
local c = ls.current
----------------------------------------------------------------
if self:currIsNewline(ls) then
self:inclinenumber(ls)
----------------------------------------------------------------
elseif c == "-" then
c = self:nextc(ls)
if c == "=" then self:nextc(ls); return "TK_ASSIGN_SUB" -- Luau Compound
elseif c ~= "-" then return "-" end
-- else is a comment
local sep = -1
if self:nextc(ls) == '[' then
sep = self:skip_sep(ls)
ls.buff = "" -- 'skip_sep' may dirty the buffer
end
if sep >= 0 then
self:read_long_string(ls, nil, sep) -- long comment
ls.buff = ""
else -- else short comment
while not self:currIsNewline(ls) and ls.current ~= "EOZ" do
self:nextc(ls)
end
end
----------------------------------------------------------------
elseif c == "[" then
local sep = self:skip_sep(ls)
if sep >= 0 then
self:read_long_string(ls, Token, sep)
return "TK_STRING"
elseif sep == -1 then
return "["
else
self:lexerror(ls, "invalid long string delimiter", "TK_STRING")
end
---------------------Luau Compound Start------------------------
elseif c == "+" then
c = self:nextc(ls)
if c ~= "=" then return "+"
else self:nextc(ls); return "TK_ASSIGN_ADD" end
----------------------------------------------------------------
elseif c == "*" then
c = self:nextc(ls)
if c ~= "=" then return "*"
else self:nextc(ls); return "TK_ASSIGN_MUL" end
----------------------------------------------------------------
elseif c == "/" then
c = self:nextc(ls)
if c ~= "=" then return "/"
else self:nextc(ls); return "TK_ASSIGN_DIV" end
----------------------------------------------------------------
elseif c == "%" then
c = self:nextc(ls)
if c ~= "=" then return "%"
else self:nextc(ls); return "TK_ASSIGN_MOD" end
----------------------------------------------------------------
elseif c == "^" then
c = self:nextc(ls)
if c ~= "=" then return "^"
else self:nextc(ls); return "TK_ASSIGN_POW" end
----------------------------------------------------------------
-- TODO: TK_ASSIGN_CONCAT support --
----------------------Luau Compound End-------------------------
elseif c == "=" then
c = self:nextc(ls)
if c ~= "=" then return "="
else self:nextc(ls); return "TK_EQ" end
----------------------------------------------------------------
elseif c == "<" then
c = self:nextc(ls)
if c ~= "=" then return "<"
else self:nextc(ls); return "TK_LE" end
----------------------------------------------------------------
elseif c == ">" then
c = self:nextc(ls)
if c ~= "=" then return ">"
else self:nextc(ls); return "TK_GE" end
----------------------------------------------------------------
elseif c == "~" then
c = self:nextc(ls)
if c ~= "=" then return "~"
else self:nextc(ls); return "TK_NE" end
----------------------------------------------------------------
elseif c == "\"" or c == "'" then
self:read_string(ls, c, Token)
return "TK_STRING"
----------------------------------------------------------------
elseif c == "." then
c = self:save_and_next(ls)
if self:check_next(ls, ".") then
if self:check_next(ls, ".") then
return "TK_DOTS" -- ...
else return "TK_CONCAT" -- ..
end
elseif not string.find(c, "%d") then
return "."
else
self:read_numeral(ls, Token)
return "TK_NUMBER"
end
----------------------------------------------------------------
elseif c == "EOZ" then
return "TK_EOS"
----------------------------------------------------------------
else -- default
if string.find(c, "%s") then
-- lua_assert(self:currIsNewline(ls))
self:nextc(ls)
elseif string.find(c, "%d") then
self:read_numeral(ls, Token)
return "TK_NUMBER"
elseif string.find(c, "[_%a]") then
-- identifier or reserved word
repeat
c = self:save_and_next(ls)
until c == "EOZ" or not string.find(c, "[_%w]")
local ts = ls.buff
local tok = self.enums[ts]
if tok then return tok end -- reserved word?
-- Global optimisation helper
if self.DEOP[ts] then
ls.safeenv = false
elseif self.globalvars[ts] and not table.find(ls.usedglobals, ts) then
table.insert(ls.usedglobals, ts)
end
Token.seminfo = ts
return "TK_NAME"
else
self:nextc(ls)
return c -- single-char tokens (+ - / ...)
end
----------------------------------------------------------------
end--if c
end--while
end
return luaX
| 8,009 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Server/Dependencies/Loadstring/LuaZ.luau | --# selene: allow(incorrect_standard_library_use, multiple_statements, shadowing, unused_variable, empty_if, divide_by_zero, unbalanced_assignments)
--[[--------------------------------------------------------------------
lzio.lua
Lua buffered streams in Lua
This file is part of Yueliang.
Copyright (c) 2005-2006 Kein-Hong Man <khman@users.sf.net>
The COPYRIGHT file describes the conditions
under which this software may be distributed.
See the ChangeLog for more information.
----------------------------------------------------------------------]]
--[[--------------------------------------------------------------------
-- Notes:
-- * EOZ is implemented as a string, "EOZ"
-- * Format of z structure (ZIO)
-- z.n -- bytes still unread
-- z.p -- last read position position in buffer
-- z.reader -- chunk reader function
-- z.data -- additional data
-- * Current position, p, is now last read index instead of a pointer
--
-- Not implemented:
-- * luaZ_lookahead: used only in lapi.c:lua_load to detect binary chunk
-- * luaZ_read: used only in lundump.c:ezread to read +1 bytes
-- * luaZ_openspace: dropped; let Lua handle buffers as strings (used in
-- lundump.c:LoadString & lvm.c:luaV_concat)
-- * luaZ buffer macros: dropped; buffers are handled as strings
-- * lauxlib.c:getF reader implementation has an extraline flag to
-- skip over a shbang (#!) line, this is not implemented here
--
-- Added:
-- (both of the following are vaguely adapted from lauxlib.c)
-- * luaZ:make_getS: create Reader from a string
-- * luaZ:make_getF: create Reader that reads from a file
--
-- Changed in 5.1.x:
-- * Chunkreader renamed to Reader (ditto with Chunkwriter)
-- * Zio struct: no more name string, added Lua state for reader
-- (however, Yueliang readers do not require a Lua state)
----------------------------------------------------------------------]]
local luaZ = {}
------------------------------------------------------------------------
-- * reader() should return a string, or nil if nothing else to parse.
-- Additional data can be set only during stream initialization
-- * Readers are handled in lauxlib.c, see luaL_load(file|buffer|string)
-- * LUAL_BUFFERSIZE=BUFSIZ=512 in make_getF() (located in luaconf.h)
-- * Original Reader typedef:
-- const char * (*lua_Reader) (lua_State *L, void *ud, size_t *sz);
-- * This Lua chunk reader implementation:
-- returns string or nil, no arguments to function
------------------------------------------------------------------------
------------------------------------------------------------------------
-- create a chunk reader from a source string
------------------------------------------------------------------------
function luaZ:make_getS(buff)
local b = buff
return function() -- chunk reader anonymous function here
if not b then return nil end
local data = b
b = nil
return data
end
end
------------------------------------------------------------------------
-- create a chunk reader from a source file
------------------------------------------------------------------------
--[[
function luaZ:make_getF(filename)
local LUAL_BUFFERSIZE = 512
local h = io.open(filename, "r")
if not h then return nil end
return function() -- chunk reader anonymous function here
if not h or io.type(h) == "closed file" then return nil end
local buff = h:read(LUAL_BUFFERSIZE)
if not buff then h:close(); h = nil end
return buff
end
end
--]]
------------------------------------------------------------------------
-- creates a zio input stream
-- returns the ZIO structure, z
------------------------------------------------------------------------
function luaZ:init(reader, data, name)
if not reader then return end
local z = {}
z.reader = reader
z.data = data or ""
z.name = name
-- set up additional data for reading
if not data or data == "" then z.n = 0 else z.n = #data end
z.p = 0
return z
end
------------------------------------------------------------------------
-- fill up input buffer
------------------------------------------------------------------------
function luaZ:fill(z)
local buff = z.reader()
z.data = buff
if not buff or buff == "" then return "EOZ" end
z.n, z.p = #buff - 1, 1
return string.sub(buff, 1, 1)
end
------------------------------------------------------------------------
-- get next character from the input stream
-- * local n, p are used to optimize code generation
------------------------------------------------------------------------
function luaZ:zgetc(z)
local n, p = z.n, z.p + 1
if n > 0 then
z.n, z.p = n - 1, p
return string.sub(z.data, p, p)
else
return self:fill(z)
end
end
return luaZ
| 1,057 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Server/Dependencies/Loadstring/init.luau | --# selene: allow(incorrect_standard_library_use)
--[[
Credit to einsteinK.
Credit to Stravant for LBI.
Credit to ccuser44 for proto conversion.
Credit to the creators of all the other modules used in this.
Sceleratis was here and decided modify some things.
einsteinK was here again to fix a bug in LBI for if-statements
--]]
local PROTO_CONVERT = true -- If proto conversion is used instead of serialise->deserialise
local DEPENDENCIES = {
"FiOne";
"LuaK";
"LuaP";
"LuaU";
"LuaX";
"LuaY";
"LuaZ";
"VirtualEnv";
}
for _, v in ipairs(DEPENDENCIES) do
script:WaitForChild(v)
end
local luaX = require(script.LuaX)
local luaY = require(script.LuaY)
local luaZ = require(script.LuaZ)
local luaU = require(script.LuaU)
local fiOne = require(script.FiOne)
local getvenv = require(script.VirtualEnv)
local function to1BasedIndex(tbl)
local tbl = table.move(tbl, 0, #tbl + (tbl[0] and 1 or 0), 1)
tbl[0] = nil
return tbl
end
local function protoConvert(proto, opRemap, opType, opMode)
local const = table.create(#proto.k + 1)
proto.code, proto.lines, proto.subs = to1BasedIndex(proto.code), to1BasedIndex(proto.lineinfo), to1BasedIndex(proto.p)
proto.lineinfo, proto.p = nil, nil
proto.max_stack, proto.maxstacksize = proto.maxstacksize, nil
proto.num_param, proto.numparams = proto.numparams, nil
proto.num_upval, proto.sizeupvalues = proto.sizeupvalues, nil
proto.sizecode, proto.sizek, proto.sizelineinfo, proto.sizelocvars, proto.sizep, proto.nups = nil, nil, nil, nil, nil, nil -- Clean up garbage values
for i, v in to1BasedIndex(proto.k) do
const[i] = v.value
end
proto.const, proto.k = const, nil
for i, v in proto.code do
local op = v.OP
v.op, v.OP = opRemap[op], nil
local regType = opType[op]
local mode = opMode[op]
if regType == "ABC" then
v.is_KB = mode.b == "OpArgK" and v.B > 0xFF -- post process optimization
v.is_KC = mode.c == "OpArgK" and v.C > 0xFF
if op == 10 then -- decode NEWTABLE array size, store it as constant value
local e = bit32.band(bit32.rshift(v.B, 3), 31)
if e == 0 then
v.const = v.B
else
v.const = bit32.lshift(bit32.band(v.B, 7) + 8, e - 1)
end
end
elseif regType == "ABx" then
v.is_K = mode.b == "OpArgK"
elseif regType == "AsBx" then
v.sBx, v.Bx = v.Bx - 131071, nil -- Fix for signed registers being treated as unsigned 18 bit registers
end
if v.is_K then
v.const = proto.const[v.Bx + 1] -- offset for 1 based index
else
if v.is_KB then v.const_B = proto.const[v.B - 0xFF] end
if v.is_KC then v.const_C = proto.const[v.C - 0xFF] end
end
end
for _, v in proto.subs do
protoConvert(v, opRemap, opType, opMode)
end
end
luaX:init()
script = nil
local LuaState = {}
return function(str, env)
local f, writer, buff
local name = (env and type(env.script) == "userdata") and env.script:GetFullName()
local ran, error = xpcall(function()
local zio = assert(luaZ:init(luaZ:make_getS(str), nil), "Failed to get buffered stream")
local func = luaY:parser(LuaState, zio, nil, name or "::Adonis::Loadstring::")
if PROTO_CONVERT and env ~= "LuaC" then
protoConvert(func, fiOne.OPCODE_RM, fiOne.OPCODE_T, fiOne.OPCODE_M)
f = fiOne.wrap_state(func, env or getvenv())
else
writer, buff = luaU:make_setS()
luaU:dump(LuaState, func, writer, buff)
f = fiOne.wrap_state(fiOne.bc_to_state(buff.data), env ~= "LuaC" and env or getvenv())
end
end, function(err)
return `{err}\n\n--- Loadstring Stacktrace Begin --- \n{debug.traceback("",2)}\n--- Loadstring Stacktrace End --- \n`
end)
if ran then
return f, buff and buff.data
else
return nil, error
end
end
| 1,157 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Server/Dependencies/RebootHandler/init.server.lua | --# selene: allow(incorrect_standard_library_use)
if script.Parent then
local dTargetVal = script:WaitForChild("Runner")
local parentVal = script:WaitForChild("mParent")
local modelVal = script:WaitForChild("Model")
local modeVal = script:WaitForChild("Mode")
warn("Reloading in 5 seconds...")
task.wait(5)
script.Parent = nil
local dTarget = dTargetVal.Value
local tParent = parentVal.Value
local model = modelVal.Value
local mode = modeVal.Value
local function CleanUp()
warn("TARGET DISABLED")
dTarget.Disabled = true
pcall(function() dTarget.Parent = game:GetService("ServerScriptService") end)
task.wait()
pcall(function() dTarget:Destroy() end)
warn("TARGET DESTROYED")
task.wait()
warn("CLEANING")
if not table.isfrozen(_G) then
rawset(_G, "Adonis", nil)
rawset(_G, "__Adonis_MODULE_MUTEX", nil)
rawset(_G, "__Adonis_MUTEX", nil)
end
warn("_G VARIABLES CLEARED")
warn("MOVING MODEL")
model.Parent = tParent
end
if mode == "REBOOT" then
warn("ATTEMPTING TO RELOAD ADONIS")
CleanUp()
task.wait()
warn("MOVING")
model.Parent = tParent
task.wait()
dTarget.Disabled = false
warn("RUNNING")
elseif mode == "STOP" then
warn("ATTEMPTING TO STOP ADONIS")
CleanUp()
end
warn("COMPLETE")
warn("Destroying reboot handler...")
script:Destroy()
end
| 389 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Server/Plugins/FindExistingObjects.luau | --[[
Description: Searches the place for existing Adonis items and registers them.
Author: Sceleratis
Date: 4/3/2022
--]]
return function(Vargs, GetEnv)
local server = Vargs.Server;
local service = Vargs.Service;
local Settings = server.Settings
local Functions, Commands, Admin, Anti, Core, HTTP, Logs, Remote, Process, Variables, Deps =
server.Functions, server.Commands, server.Admin, server.Anti, server.Core, server.HTTP, server.Logs, server.Remote, server.Process, server.Variables, server.Deps
local OBJ_NAME_PREFIX = "Adonis_"
for _, child in workspace:GetDescendants() do
local objType, name = string.match(child.Name, `{OBJ_NAME_PREFIX}(.*): (.*)`)
if child:IsA("BasePart") and objType and name then
if string.lower(objType) == "camera" then
table.insert(Variables.Cameras, { Brick = child, Name = name })
elseif string.lower(objType) == "waypoint" then
Variables.Waypoints[name] = child.Position
end
Logs.AddLog("Script", {
Text = `Found {child.Name}`;
Desc = `Found and registered system object of type '{objType}' with name '{name}'`;
})
end
end
Logs:AddLog("Script", "Current Adonis objects successfully loaded in to instance lists");
end
| 316 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Server/Plugins/Misc_Features.luau | --// NOTE: THIS IS NOT A *CONFIG/USER* PLUGIN! ANYTHING IN THE MAINMODULE PLUGIN FOLDERS IS ALREADY PART OF/LOADED BY THE SCRIPT! DO NOT ADD THEM TO YOUR CONFIG>PLUGINS FOLDER!
return function(Vargs, GetEnv)
local server = Vargs.Server;
local service = Vargs.Service;
local Settings = server.Settings
local Functions, Commands, Admin, Anti, Core, HTTP, Logs, Remote, Process, Variables, Deps =
server.Functions, server.Commands, server.Admin, server.Anti, server.Core, server.HTTP, server.Logs, server.Remote, server.Process, server.Variables, server.Deps
--// AutoClean
if Settings.AutoClean then
service.StartLoop("AUTO_CLEAN", Settings.AutoCleanDelay, Functions.CleanWorkspace, true)
Logs:AddLog("Script", `Started autoclean with {Settings.AutoCleanDelay}s delay`)
end
-- // Add legacy donors
Variables.OldDonorList = select(2, xpcall(require, warn, server.Deps.LegacyDonors)) or {}
for _, v in Variables.OldDonorList do
if v.Id then
Variables.CachedDonors[tostring(v.Id)] = os.time()
end
end
-- // Backwards compatibility
local Pcall = server.Pcall
local function cPcall(func, ...)
return Pcall(function(...)
return coroutine.resume(coroutine.create(func), ...)
end, ...)
end
server.cPcall, service.cPcall = cPcall, cPcall
service.AltUnpack = function(args, shift) -- TODO: Remove. This is not used in Adonis at all and is easily replicatable so you can safely remove it withour fear
return table.unpack(args, 1 + (shift and shift - 1 or 0), 10 + (shift and shift - 1 or 0))
end
service.CloneTable = function(tbl)
return (getmetatable(tbl) and not pcall(setmetatable(tbl, getmetatable(tbl)))) and setmetatable({}, {__index = function(_, k) return tbl[k] end}) or table.clone(tbl)
end
service.GoodSignal = service.Signal
service.Yield = function()
local event = service.Signal.new()
return {
Release = function(...) event:Fire(...) end;
Wait = function(...) return event:Wait(...) end;
Destroy = function() event:Destroy() end;
Event = event;
}
end
Remote.UnEncrypted = setmetatable({}, { -- TODO: Start adding a server.Messages message and remove later
__newindex = function(_, ind, val)
warn("Unencrypted remote commands are deprecated; moving", ind, "to Remote.Commands. Replace `Remote.Unencrypted` with `Remote.Commands`!")
Remote.Commands[ind] = val
Logs:AddLog("Script", `Attempted to add {ind} to legacy Remote.Unencrypted. Moving to Remote.Commands`)
end
})
if service.Wrapped(server.Folder) then
server.Folder:SetSpecial("Shared", server.Shared)
end
Functions.GetRandom = function(pLen)
local random = math.random
local format = string.format
local Len = (type(pLen) == "number" and pLen) or random(5,10) --// reru
local Res = {}
for Idx = 1, Len do
Res[Idx] = format("%02x", random(255))
end
return table.concat(Res)
end
if HTTP.Trello.API then
HTTP.Trello.API.GenerateRequestID = Functions.GetRandom
end
--// Old settings/plugins backwards compatibility. Do not remove this because many games use old loader ranks!
for _, rank in {"Owners", "HeadAdmins", "Admins", "Moderators", "Creators"} do
if Settings[rank] and not Settings.CustomRanks[rank] then
Settings.Ranks[if rank == "Owners" then "HeadAdmins" else rank].Users = Settings[rank]
end
end
if Settings.CustomRanks then
local Ranks = Settings.Ranks
for name, users in Settings.CustomRanks do
if not Ranks[name] then
Ranks[name] = {
Level = 1;
Users = users;
}
end
end
end
for k, v in {-- Legacy aliases
[`{Settings.Prefix}giveppoints <player> <amount>`] = `{Settings.Prefix}clientscript <player> game:GetService("StarterGui"):SetCore("SendNotification", \{Title = "Points Awarded", Text = "You received <amount> points!", Icon = "rbxassetid://155221172"\})`,
[`{Settings.Prefix}giveplayerpoints <player> <amount>`] = `{Settings.Prefix}clientscript <player> game:GetService("StarterGui"):SetCore("SendNotification", \{Title = "Points Awarded", Text = "You received <amount> points!", Icon = "rbxassetid://155221172"\})`,
[`{Settings.Prefix}sendplayerpoints <player> <amount>`] = `{Settings.Prefix}clientscript <player> game:GetService("StarterGui"):SetCore("SendNotification", \{Title = "Points Awarded", Text = "You received <amount> points!", Icon = "rbxassetid://155221172"\})`,
[`{Settings.Prefix}flyclip <player>`] = `{Settings.Prefix}fly <player> true`;
[`{Settings.Prefix}showlogs true <player>`] = `{Settings.Prefix}showlogs <player> true`; -- TODO: Remove legacy :showlogs aliases, only temporarily here.
[`{Settings.Prefix}showlogs false <player>`] = `{Settings.Prefix}showlogs <player> false`;
[`{Settings.Prefix}showlogs yes <player>`] = `{Settings.Prefix}showlogs <player> true`;
[`{Settings.Prefix}showlogs no <player>`] = `{Settings.Prefix}showlogs <player> false`;
[`{Settings.Prefix}showcommandlogs true <player>`] = `{Settings.Prefix}showlogs <player> true`;
[`{Settings.Prefix}showcommandlogs false <player>`] = `{Settings.Prefix}showlogs <player> false`;
[`{Settings.Prefix}showcommandlogs yes <player>`] = `{Settings.Prefix}showlogs <player> true`;
[`{Settings.Prefix}showcommandlogs no <player>`] = `{Settings.Prefix}showlogs <player> false`;
} do
if not Variables.Aliases[k] then
Variables.Aliases[k] = v
end
end
HTTP.CheckHttp = function()
return HTTP.HttpEnabled
end
-- TODO: Remove \\/
service.OwnsAsset = service.CheckAssetOwnership
Functions.CatchError = server.Pcall
Logs:AddLog("Script", "Misc Features Module Loaded")
end
| 1,544 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Server/Plugins/Trello.luau | -- Trello plugin
type Card = {id: string, name: string, desc: string, labels: {any}?}
type List = {id: string, name: string, cards: {Card}}
return function(Vargs, GetEnv)
local server = Vargs.Server;
local service = Vargs.Service;
local Settings = server.Settings
local Functions, Commands, Admin, Anti, Core, HTTP, Logs, Remote, Process, Variables, Deps =
server.Functions, server.Commands, server.Admin, server.Anti, server.Core, server.HTTP, server.Logs, server.Remote, server.Process, server.Variables, server.Deps
HTTP.Trello.Update = function()
if not HTTP.Trello.API or not Settings.Trello_Enabled then
Logs:AddLog("Script", "Not running Trello API update")
return
end
if not HTTP.HttpEnabled then
warn("Unable to connect to Trello. Make sure HTTP Requests are enabled in Game Settings.")
Logs:AddLog("Script", "Not running Trello API update due to HTTP request being disabled.")
return
else
local data = {
Bans = {};
Mutes = {};
Music = {};
Whitelist = {};
Blacklist = {};
InsertList = {};
Agents = {};
Ranks = {
["Moderators"] = {},
["Admins"] = {},
["HeadAdmins"] = {},
["Creators"] = {}
};
}
local function grabData(board)
local lists: {List} = HTTP.Trello.API.getListsAndCards(board, true)
if #lists == 0 then error("L + ratio") end --TODO: Improve TrelloAPI error handling so we don't need to assume no lists = failed request
for _, list in lists do
local foundOverride = false
for _, override in HTTP.Trello.Overrides do
if table.find(override.Lists, list.name) then
foundOverride = true
Logs:AddLog("Script", `Found override {list.name} for board {board} with {type(list.cards) == "table" and #list.cards or list.cards} cards.`)
for _, card in list.cards do
override.Process(card, data)
end
break
end
end
-- Allow lists for custom ranks
if not foundOverride and not data.Ranks[list.name] then
local rank = Settings.Ranks[list.name]
if rank and not rank.IsExternal then
local users = {}
for _, card in list.cards do
table.insert(users, card.name)
end
data.Ranks[list.name] = users
Logs:AddLog("Script", `Found custom rank override {list.name} for board {board} with {type(list.cards) == "table" and #list.cards or list.cards} cards.`)
end
end
end
end
local success = true
local boards = {
Settings.Trello_Primary,
unpack(Settings.Trello_Secondary)
}
for _, v in boards do
if not v or service.Trim(v) == "" then
continue
end
Logs:AddLog("Script", `Attempting to pool data from Trello board {v}.`)
local ran, err = pcall(grabData, v)
if not ran then
warn("Unable to reach Trello. Ensure your board IDs, Trello key, and token are all correct. If issue persists, try increasing HttpWait in your Adonis settings.")
Logs:AddLog("Script", `Failed to pool data from Trello board {v} due to {err}.`)
success = false
break
else
Logs:AddLog("Script", `Successfully pooled data from Trello board {v}.`)
end
end
-- Only replace existing values if all data was fetched successfully
if success then
HTTP.Trello.Bans = data.Bans
HTTP.Trello.Music = data.Music
HTTP.Trello.InsertList = data.InsertList
HTTP.Trello.Mutes = data.Mutes
HTTP.Trello.Agents = data.Agents
Variables.Blacklist.Lists.Trello = data.Blacklist
Variables.Whitelist.Lists.Trello = data.Whitelist
--// Clear any custom ranks that were not fetched from Trello
for rank, info in Settings.Ranks do
if rank.IsExternal and not data.Ranks[rank] then
Settings.Ranks[rank] = nil
end
end
for rank, users in data.Ranks do
local name = string.format("[Trello] %s", server.Functions.Trim(rank))
Settings.Ranks[name] = {
Level = Settings.Ranks[rank].Level or 1;
Users = users,
IsExternal = true,
Hidden = Settings.Trello_HideRanks;
}
end
for _, v in service.GetPlayers() do
local isBanned, Reason = Admin.CheckBan(v)
if isBanned then
v:Kick(string.format("%s | Reason: %s", Variables.BanMessage, (Reason or "No reason provided")))
continue
end
Admin.UpdateCachedLevel(v)
end
Logs.AddLog(Logs.Script,{
Text = "Updated Trello data";
Desc = "Data was retreived from Trello";
})
end
end
end
Remote.Commands.TrelloOperation = function(p: Player, args: {[number]: any})
local adminLevel = Admin.GetLevel(p)
local data = args[1]
if data.Action == "MakeCard" then
local command = Commands.MakeCard
if command and Admin.CheckComLevel(adminLevel, command.AdminLevel) then
local trello = HTTP.Trello.API
local listName = data.List
local name = data.Name
local desc = data.Desc
for _, overrideList in HTTP.Trello.GetOverrideLists() do
if service.Trim(string.lower(overrideList)) == service.Trim(string.lower(listName)) then
Functions.Hint("You cannot create a card in that list", {p}) -- Why??
return
end
end
local lists = trello.getLists(Settings.Trello_Primary)
local list = trello.getListObj(lists, listName)
if list then
local card = trello.makeCard(list.id, name, desc)
Functions.Hint(`Made card "{card.name}" in list "{list.name}"`, {p})
Logs.AddLog(Logs.Script,{
Text = `{p} performed Trello operation`;
Desc = "Player created a Trello card";
Player = p;
})
else
Functions.Hint(`"{listName}" does not exist"`, {p})
end
end
end
end
-- // Moderator commands
Commands.ShowTrelloBansList = {
Prefix = Settings.Prefix;
Commands = {"trellobans", "trellobanlist", "syncedtrellobans", "showtrellobans"};
Args = {};
Description = "Shows bans synced from Trello.";
TrelloRequired = true;
AdminLevel = "Moderators";
ListUpdater = function(plr: Player)
local tab = table.create(#HTTP.Trello.Bans + 2)
tab[1] = `# Banned Users: {#HTTP.Trello.Bans}`
tab[2] = "―――――――――――――――――――――――"
for _, banData in HTTP.Trello.Bans do
table.insert(tab, {
Text = banData.Name,
Desc = banData.Reason or "No reason specified",
})
end
return tab
end;
Function = function(plr: Player, args: {string})
local trello = HTTP.Trello.API
if not Settings.Trello_Enabled or trello == nil then
Functions.Notification("Trello Synced Ban List", "Trello has not been enabled.", {plr})
else
Remote.MakeGui(plr, "List", {
Title = "Trello Synced Bans List";
Icon = server.MatIcons.Gavel;
Tab = Logs.ListUpdaters.ShowTrelloBansList(plr);
Update = "ShowTrelloBansList";
})
end
end;
}
-- // Admin commands
Commands.TrelloBan = {
Prefix = Settings.Prefix;
Commands = {"trelloban"};
Args = {"player/user", "reason"};
Description = "Adds a user to the Trello ban list (Trello needs to be configured)";
Filter = true;
CrossServerDenied = true;
TrelloRequired = true;
AdminLevel = "Admins";
Function = function(plr: Player, args: {string}, data: {any})
local trello = HTTP.Trello.API
if not Settings.Trello_Enabled or trello == nil then
Functions.Notification("Trelloban", "Trello has not been configured.", {plr}, 10, "MatIcon://Description")
return
end
local lists = trello.getLists(Settings.Trello_Primary)
local list = trello.getListObj(lists, {"Banlist", "Ban List", "Bans"})
local level = data.PlayerData.Level
local reason = string.format("Administrator: %s\nReason: %s", service.FormatPlayer(plr), (args[2] or "N/A"))
for _, v in service.GetPlayers(plr, args[1], {
IsKicking = true;
UseFakePlayer = true;
})
do
if level > Admin.GetLevel(v) then
trello.makeCard(
list.id,
string.format("%s:%d", (v and tostring(v.Name) or tostring(v)), v.UserId),
reason
)
pcall(function() v:Kick(reason) end)
Functions.LogAdminAction(plr, "Trello Ban", v.Name, `Reason: {args[2] or "N/A"}`)
Functions.Notification("Notification", `Trello-banned {service.FormatPlayer(v, true)}`, {plr}, 5, "MatIcons://Gavel")
end
end
HTTP.Trello.Update()
end;
}
-- // HeadAdmin commands
Commands.MakeList = {
Prefix = Settings.Prefix;
Commands = {"makelist", "newlist", "newtrellolist", "maketrellolist"};
Args = {"name"};
Description = "Adds a list to the Trello board set in Settings. AppKey and Token MUST be set and have write perms for this to work.";
TrelloRequired = true;
AdminLevel = "HeadAdmins";
Function = function(plr: Player, args: {string})
local trello = HTTP.Trello.API
if not Settings.Trello_Enabled or trello == nil then return Functions.Hint('Trello has not been configured in settings', {plr}) end
local list = trello.Boards.MakeList(Settings.Trello_Primary, assert(args[1], "You need to supply a list name."))
Functions.Hint(`Made list {list.name}`, {plr})
end
}
Commands.ViewList = {
Prefix = Settings.Prefix;
Commands = {"viewtrellolist", "viewlist"};
Args = {"name"};
Description = "Views the specified Trello list from the primary board set in Settings.";
TrelloRequired = true;
AdminLevel = "HeadAdmins";
Function = function(plr: Player, args: {string})
local trello = HTTP.Trello.API
if not Settings.Trello_Enabled or trello == nil then return Functions.Hint('Trello has not been configured in settings', {plr}) end
local list = assert(trello.Boards.GetList(Settings.Trello_Primary, assert(args[1], "Enter a valid list name")), "List not found.")
local cards = trello.Lists.GetCards(list.id)
local temp = table.create(#cards)
for _, v in cards do
table.insert(temp, {Text = v.name, Desc = v.desc})
end
Remote.MakeGui(plr, "List", {Title = list.name; Tab = temp})
end
}
Commands.MakeCard = {
Prefix = Settings.Prefix;
Commands = {"makecard", "maketrellocard", "createcard"};
Args = {};
Description = "Opens a gui to make new Trello cards. AppKey and Token MUST be set and have write perms for this to work.";
TrelloRequired = true;
AdminLevel = "HeadAdmins";
Function = function(plr: Player, args: {string})
Remote.MakeGui(plr, "CreateCard")
end
}
-- // Initialization
if Settings.Trello_Enabled then
service.StartLoop("TRELLO_UPDATER", Settings.HttpWait, HTTP.Trello.Update, true)
Logs:AddLog("Script", `Trello update loop has been started to run every {Settings.HttpWait} seconds.`)
if not Settings.Trello_AppKey or Settings.Trello_AppKey == "" then
table.insert(server.Messages, {
Level = 301;
Title = "Potential Trello issue!";
Message = "You have enabled Trello without having an AppKey and thus Trello will likely not work! For better behavior it is adviced to also add a Trello Token. Click to see more";
Time = 15;
Icon = "MatIcon://Description";
onClick = (server.Data and server.Data.NightlyMode) and Core.Bytecode([[
local window = client.UI.Make("Window", {
Title = "How to change the Trello AppKey";
Size = {700,300};
Icon = "rbxassetid://7510994359";
})
window:Add("ImageLabel", {
Image = "rbxassetid://111103486118064";
})
window:Ready()
]]) or nil})
end
end
Logs:AddLog("Script", "Trello Module Loaded")
end
| 3,167 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Server/Plugins/Urgent_Messages.luau | return function(Vargs, GetEnv)
local server = Vargs.Server;
local service = Vargs.Service;
local Settings = server.Settings
local Functions, Commands, Admin, Anti, Core, HTTP, Logs, Remote, Process, Variables, Deps =
server.Functions, server.Commands, server.Admin, server.Anti, server.Core, server.HTTP, server.Logs, server.Remote, server.Process, server.Variables, server.Deps
local LastDateTime, Messages = "Loading...", {"The messages haven't loaded. Please comeback later..."}
Variables.UrgentModuleId = Variables.UrgentModuleId or 8096250407
task.spawn(xpcall, function()
local Alerts = require(Deps.__URGENT_MESSAGES)
local assetInfo = type(Variables.UrgentModuleId) == "number" and service.GetProductInfo(Variables.UrgentModuleId, Enum.InfoType.Asset)
local version = (assetInfo and assetInfo.Created) and assetInfo.Updated
local lastVersion = Core.GetData("LastAlertVersion")
if not version or not lastVersion or version ~= lastVersion then
Logs:AddLog("Script", "Loading alerts from cloud module")
xpcall(function()
if not server.Core.SilentStartup then
print("Requiring Alerts Module by ID; Expand for module URL > ", {URL = `https://www.roblox.com/library/{Variables.UrgentModuleId}/Adonis-Alerts-Module`})
end
local alertTab = require(Variables.UrgentModuleId)
if alertTab then
Alerts = alertTab
Logs:AddLog("Script", "Alerts cloud module returned proper data")
Core.SetData("LastAlertVersion", version)
Core.SetData("CachedAlerts", service.HttpService:JSONEncode(alertTab))
end
end, function(reason)
warn(`Error occured while requiring the urgent messages module. Reason {reason}`)
Logs:AddLog("Errors", `Error occured while requiring the urgent messages module. Reason {reason}`)
table.insert(server.Messages, `Error occured while requiring the urgent messages module. Reason {reason}`)
end)
elseif version and lastVersion then
Logs:AddLog("Script", "Loading alerts from datastore")
xpcall(function()
Alerts = service.HttpService:JSONDecode(Core.GetData("CachedAlerts"))
end, function(reason)
warn(`Error occured while loading alerts from datastore. Reason {reason}`)
Logs:AddLog("Errors", `Error occured while loading alerts from datastore. Reason {reason}`)
table.insert(server.Messages, `Error occured while loading alerts from datastore. Reason {reason}`)
Core.RemoveData("LastAlertVersion")
Core.RemoveData("CachedAlerts")
end)
end
local MessageVersion = Alerts.MessageVersion; --// Message version/number
local MessageAdminType = Alerts.MessageAdminType; --// Minimum admin level to be notified (Or Donors or Players or nil to not notify)
local MessageDate = Alerts.MessageDate; --// Time of message creation
local MessageDuration = Alerts.MessageDuration; --// How long should we notify people about this message
LastDateTime = Alerts.LastDateTime; --// Last message date and time
Messages = Alerts.Messages; --// List of alert messages/lines
local function checkDoNotify(p, data)
local lastMessage = data.LastUrgentMessage or 0;
if lastMessage < MessageVersion and os.time() - MessageDate <= MessageDuration then
if MessageAdminType == "Players" then
return true
elseif MessageAdminType == "Donors" then
if Admin.CheckDonor(p) then
return true
end
elseif type(MessageAdminType) == "number" and Admin.GetLevel(p) >= MessageAdminType then
return true
end
end
end
Variables.UrgentMessageCounter = MessageVersion
local function onPlayerAdded(p: Player)
if MessageAdminType then
local data = Core.GetPlayer(p);
if checkDoNotify(p, data) then
data.LastUrgentMessage = MessageVersion;
task.delay(0.5, Functions.Notification, "Urgent Message!", "Click to view messages", {p}, 20, "MatIcon://Announcement", Core.Bytecode("client.Remote.Send('ProcessCommand',':adonisalerts')"))
end
end
end
for _, p in service.Players:GetPlayers() do
task.spawn(pcall, onPlayerAdded, p)
end
service.Events.PlayerAdded:Connect(onPlayerAdded)
Logs:AddLog("Script", "Successfully loaded alerts module data")
end, warn)
Commands.UrgentMessages = {
Prefix = ":";
Commands = {"adonisalerts", "urgentmessages", "urgentalerts", "adonismessages", "urgentadonismessages", "ulog"};
Args = {};
Description = "URGENT ADONIS RELATED MESSAGES";
AdminLevel = "Players";
Function = function(plr,args)
Remote.MakeGui(plr,"List",{
Title = `URGENT MESSAGES [Recent: {LastDateTime}]`,
Icon = "rbxassetid://7467273592",
Table = Messages,
Font = "Code",
PageSize = 100;
Size = {700, 400},
})
end;
};
Logs:AddLog("Script", "Alerts Module Loaded")
end
| 1,207 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Shared/DoubleLinkedList.luau | --!native
--// File: LinkedList.lua
--// Desc: Provides a more performance-friendly alternative to large tables that get shifted in indexes constantly
--// Author: Coasterteam
local LinkedList = {}
LinkedList.__index = LinkedList
LinkedList.__meta = "DLL"
local LinkNode = {}
LinkNode.__index = LinkNode
function LinkNode.new(data, n, prev)
local self = setmetatable({}, LinkNode)
self.data = data
self.prev = prev
self.next = n
return self
end
function LinkNode:setnext(n)
self.next = n
end
function LinkNode:setprev(p)
self.prev = p
end
function LinkNode:Destroy()
for i, _ in self do
self[i] = nil
end
setmetatable(self, nil)
end
--[==[
LinkedNode end
]==]
function LinkedList.new()
local self = setmetatable({}, LinkedList)
self.snode = nil
self.enode = nil
self.count = 0
return self
end
function LinkedList:IsReal()
--// this is a ghost function
--// don't remove it
end
function LinkedList:AddStart(data)
local old = self.snode
local newNode = LinkNode.new(data)
newNode:setprev(nil)
if not old then
self.enode = newNode
else
old:setprev(newNode)
end
newNode:setnext(old)
self.snode = newNode
self.count += 1
end
function LinkedList:AddEnd(data)
local old = self.enode
local newNode = LinkNode.new(data)
newNode:setnext(nil)
if not old then
self.snode = newNode
else
old:setnext(newNode)
end
newNode:setprev(old)
self.enode = newNode
self.count += 1
end
function LinkedList:AddToStartAndRemoveEndIfEnd(data, limit)
self:AddStart(data)
if self.count > limit and self.enode then
self:RemoveNode(self.enode)
end
end
function LinkedList:AddBetweenNodes(data, left, right)
if not left or not right then
return false
end
local newNode = LinkNode.new(data)
newNode:setnext()
newNode:setprev()
left:setnext(newNode)
right:setprev(newNode)
self.count += 1
end
function LinkedList:RemoveNode(node)
local data = node.data
local prev = node.prev
local nextN = node.next
if self.snode == node then
self.snode = nextN
end
if self.enode == node then
self.enode = prev
end
if nextN then
nextN:setprev(prev)
end
if prev then
prev:setnext(nextN)
end
node:setnext(nil)
node:setprev(nil)
node:Destroy()
self.count -= 1
return data
end
function LinkedList:Get(val: any)
local nodes = table.create(self.count)
local curr = self.snode
while curr and type(curr) == "table" do
if val then
--// Pass a function and Adonis will pass through the current node into it
--// Return true to add it to the "list"
--// Final list will be returned after the call
--// Passed value:
--[==[
Node:
.data: The data inside of the node
.next: The next node in the list
.prev: The previous node in the list
]==]
if type(val) == "function" then
local success, found = pcall(val, curr)
if success and found then
table.insert(nodes, curr)
end
else
if curr.data == val then
table.insert(nodes, curr)
end
end
else
table.insert(nodes, curr)
end
curr = curr.next
end
return nodes
end
--// Returns a list of all passing notes with data
function LinkedList:GetAsTable(val: any)
local nodes = table.create(self.count)
local curr = self.snode
while curr and type(curr) == "table" do
--// Pass a function and Adonis will pass through the current node into it
--// Return true to add it to the "list"
--// Final list will be returned after the call
--// Passed value:
--[==[
Node:
.data: The data inside of the node
.next: The next node in the list
.prev: The previous node in the list
]==]
if val then
if type(val) == "function" then
local success, found = pcall(val, curr)
if success and found then
table.insert(nodes, curr.data)
end
else
if curr.data == val then
table.insert(nodes, curr.data)
end
end
else
table.insert(nodes, curr.data)
end
curr = curr.next
end
return nodes
end
function LinkedList:Destroy()
for k, _ in self do
self[k] = nil
end
setmetatable(self, nil)
end
return LinkedList
| 1,101 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Shared/FiOne/init.luau | --!native
--!optimize 2
--!nolint TableOperations
--# selene: allow(multiple_statements, mixed_table)
--[[
FiOne
Copyright (C) 2021 Rerumu
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
]] --
local lua_wrap_state
local stm_lua_func
-- SETLIST config
local FIELDS_PER_FLUSH = 50
-- remap for better lookup
local OPCODE_RM = {
-- level 1
[22] = 18, -- JMP
[31] = 8, -- FORLOOP
[33] = 28, -- TFORLOOP
-- level 2
[0] = 3, -- MOVE
[1] = 13, -- LOADK
[2] = 23, -- LOADBOOL
[26] = 33, -- TEST
-- level 3
[12] = 1, -- ADD
[13] = 6, -- SUB
[14] = 10, -- MUL
[15] = 16, -- DIV
[16] = 20, -- MOD
[17] = 26, -- POW
[18] = 30, -- UNM
[19] = 36, -- NOT
-- level 4
[3] = 0, -- LOADNIL
[4] = 2, -- GETUPVAL
[5] = 4, -- GETGLOBAL
[6] = 7, -- GETTABLE
[7] = 9, -- SETGLOBAL
[8] = 12, -- SETUPVAL
[9] = 14, -- SETTABLE
[10] = 17, -- NEWTABLE
[20] = 19, -- LEN
[21] = 22, -- CONCAT
[23] = 24, -- EQ
[24] = 27, -- LT
[25] = 29, -- LE
[27] = 32, -- TESTSET
[32] = 34, -- FORPREP
[34] = 37, -- SETLIST
-- level 5
[11] = 5, -- SELF
[28] = 11, -- CALL
[29] = 15, -- TAILCALL
[30] = 21, -- RETURN
[35] = 25, -- CLOSE
[36] = 31, -- CLOSURE
[37] = 35, -- VARARG
}
-- opcode types for getting values
local OPCODE_T = {
[0] = "ABC",
"ABx",
"ABC",
"ABC",
"ABC",
"ABx",
"ABC",
"ABx",
"ABC",
"ABC",
"ABC",
"ABC",
"ABC",
"ABC",
"ABC",
"ABC",
"ABC",
"ABC",
"ABC",
"ABC",
"ABC",
"ABC",
"AsBx",
"ABC",
"ABC",
"ABC",
"ABC",
"ABC",
"ABC",
"ABC",
"ABC",
"AsBx",
"AsBx",
"ABC",
"ABC",
"ABC",
"ABx",
"ABC",
}
local OPCODE_M = {
[0] = {b = "OpArgR", c = "OpArgN"},
{b = "OpArgK", c = "OpArgN"},
{b = "OpArgU", c = "OpArgU"},
{b = "OpArgR", c = "OpArgN"},
{b = "OpArgU", c = "OpArgN"},
{b = "OpArgK", c = "OpArgN"},
{b = "OpArgR", c = "OpArgK"},
{b = "OpArgK", c = "OpArgN"},
{b = "OpArgU", c = "OpArgN"},
{b = "OpArgK", c = "OpArgK"},
{b = "OpArgU", c = "OpArgU"},
{b = "OpArgR", c = "OpArgK"},
{b = "OpArgK", c = "OpArgK"},
{b = "OpArgK", c = "OpArgK"},
{b = "OpArgK", c = "OpArgK"},
{b = "OpArgK", c = "OpArgK"},
{b = "OpArgK", c = "OpArgK"},
{b = "OpArgK", c = "OpArgK"},
{b = "OpArgR", c = "OpArgN"},
{b = "OpArgR", c = "OpArgN"},
{b = "OpArgR", c = "OpArgN"},
{b = "OpArgR", c = "OpArgR"},
{b = "OpArgR", c = "OpArgN"},
{b = "OpArgK", c = "OpArgK"},
{b = "OpArgK", c = "OpArgK"},
{b = "OpArgK", c = "OpArgK"},
{b = "OpArgR", c = "OpArgU"},
{b = "OpArgR", c = "OpArgU"},
{b = "OpArgU", c = "OpArgU"},
{b = "OpArgU", c = "OpArgU"},
{b = "OpArgU", c = "OpArgN"},
{b = "OpArgR", c = "OpArgN"},
{b = "OpArgR", c = "OpArgN"},
{b = "OpArgN", c = "OpArgU"},
{b = "OpArgU", c = "OpArgU"},
{b = "OpArgN", c = "OpArgN"},
{b = "OpArgU", c = "OpArgN"},
{b = "OpArgU", c = "OpArgN"},
}
local intiger_types = {
[1] = buffer.readu8,
[2] = buffer.readu16,
[4] = buffer.readu32,
}
local intiger_write_type = {
[1] = buffer.writeu8,
[2] = buffer.writeu16,
[4] = buffer.writeu32,
}
-- int rd_int(string src, int s, int e)
-- @src - Source binary string
-- @s - Start index of a little endian integer
-- @e - End index of the integer
local function rd_int(src, s, e)
return intiger_types[e - s](src, s)
end
-- number big_endian(string src, int s)
-- @callback - Function to be called after bitswap
-- @byte_count - Lenght of the number
local function big_endian(callback, byte_count)
return function(src, s, e)
local e, write = (e or byte_count) * 8, intiger_write_type[e]
write(src, s, bit32.rshift(bit32.byteswap(rd_int(src, s, e)), 32 - e))
local n2 = callback(src, s)
write(src, s, bit32.rshift(bit32.byteswap(rd_int(src, s, e)), 32 - e))
return n2
end
end
-- to avoid nested ifs in deserializing
local float_types = {
[4] = {little = buffer.readf32, big = big_endian(buffer.readf32)},
[8] = {little = buffer.readf64, big = big_endian(buffer.readf64)},
}
-- byte stm_byte(Stream S)
-- @S - Stream object to read from
local function stm_byte(S)
local idx = S.index
local bt = buffer.readu8(S.source, idx)
S.index = idx + 1
return bt
end
-- string stm_string(Stream S, int len)
-- @S - Stream object to read from
-- @len - Length of string being read
local function stm_string(S, len)
local str = buffer.readstring(S.source, S.index, len)
S.index += len
return str
end
-- string stm_lstring(Stream S)
-- @S - Stream object to read from
local function stm_lstring(S)
local len = S:s_szt()
local str
if len ~= 0 then str = string.sub(stm_string(S, len), 1, -2) end
return str
end
-- fn cst_int_rdr(string src, int len, fn func)
-- @len - Length of type for reader
-- @func - Reader callback
local function cst_int_rdr(len, func)
return function(S)
local pos = S.index + len
local int = func(S.source, S.index, pos)
S.index = pos
return int
end
end
-- fn cst_flt_rdr(string src, int len, fn func)
-- @len - Length of type for reader
-- @func - Reader callback
local function cst_flt_rdr(len, func)
return function(S)
local flt = func(S.source, S.index)
S.index = S.index + len
return flt
end
end
local function stm_inst_list(S)
local len = S:s_int()
local list = table.create(len)
for i = 1, len do
local ins = S:s_ins()
local op = bit32.band(ins, 0x3F)
local args = OPCODE_T[op]
local mode = OPCODE_M[op]
local data = {value = ins, op = OPCODE_RM[op], A = bit32.band(bit32.rshift(ins, 6), 0xFF)}
if args == "ABC" then
data.B = bit32.band(bit32.rshift(ins, 23), 0x1FF)
data.C = bit32.band(bit32.rshift(ins, 14), 0x1FF)
data.is_KB = mode.b == "OpArgK" and data.B > 0xFF -- post process optimization
data.is_KC = mode.c == "OpArgK" and data.C > 0xFF
if op == 10 then -- decode NEWTABLE array size, store it as constant value
local e = bit32.band(bit32.rshift(data.B, 3), 31)
if e == 0 then
data.const = data.B
else
data.const = bit32.lshift(bit32.band(data.B, 7) + 8, e - 1)
end
end
elseif args == "ABx" then
data.Bx = bit32.band(bit32.rshift(ins, 14), 0x3FFFF)
data.is_K = mode.b == "OpArgK"
elseif args == "AsBx" then
data.sBx = bit32.band(bit32.rshift(ins, 14), 0x3FFFF) - 131071
end
list[i] = data
end
return list
end
local function stm_const_list(S)
local len = S:s_int()
local list = table.create(len)
for i = 1, len do
local tt = stm_byte(S)
local k
if tt == 1 then
k = stm_byte(S) ~= 0
elseif tt == 3 then
k = S:s_num()
elseif tt == 4 then
k = stm_lstring(S)
end
list[i] = k -- offset +1 during instruction decode
end
return list
end
local function stm_sub_list(S, src)
local len = S:s_int()
local list = table.create(len)
for i = 1, len do
list[i] = stm_lua_func(S, src) -- offset +1 in CLOSURE
end
return list
end
local function stm_line_list(S)
local len = S:s_int()
local list = table.create(len)
for i = 1, len do list[i] = S:s_int() end
return list
end
local function stm_loc_list(S)
local len = S:s_int()
local list = table.create(len)
for i = 1, len do list[i] = {varname = stm_lstring(S), startpc = S:s_int(), endpc = S:s_int()} end
return list
end
local function stm_upval_list(S)
local len = S:s_int()
local list = table.create(len)
for i = 1, len do list[i] = stm_lstring(S) end
return list
end
function stm_lua_func(S, psrc)
local proto = {}
local src = stm_lstring(S) or psrc -- source is propagated
proto.source = src -- source name
S:s_int() -- line defined
S:s_int() -- last line defined
proto.num_upval = stm_byte(S) -- num upvalues
proto.num_param = stm_byte(S) -- num params
stm_byte(S) -- vararg flag
proto.max_stack = stm_byte(S) -- max stack size
proto.code = stm_inst_list(S)
proto.const = stm_const_list(S)
proto.subs = stm_sub_list(S, src)
proto.lines = stm_line_list(S)
stm_loc_list(S)
stm_upval_list(S)
-- post process optimization
for _, v in ipairs(proto.code) do
if v.is_K then
v.const = proto.const[v.Bx + 1] -- offset for 1 based index
else
if v.is_KB then v.const_B = proto.const[v.B - 0xFF] end
if v.is_KC then v.const_C = proto.const[v.C - 0xFF] end
end
end
return proto
end
local function lua_bc_to_state(src)
-- func reader
local rdr_func
-- header flags
local little
local size_int
local size_szt
local size_ins
local size_num
local flag_int
-- stream object
local stream = {
-- data
index = 0,
source = typeof(src) == "buffer" and src or buffer.fromstring(src),
}
assert(stm_string(stream, 4) == "\27Lua", "invalid Lua signature")
assert(stm_byte(stream) == 0x51, "invalid Lua version")
assert(stm_byte(stream) == 0, "invalid Lua format")
little = stm_byte(stream) ~= 0
size_int = stm_byte(stream)
size_szt = stm_byte(stream)
size_ins = stm_byte(stream)
size_num = stm_byte(stream)
flag_int = stm_byte(stream) ~= 0
rdr_func = little and rd_int or big_endian(rd_int)
stream.s_int = cst_int_rdr(size_int, rdr_func)
stream.s_szt = cst_int_rdr(size_szt, rdr_func)
stream.s_ins = cst_int_rdr(size_ins, rdr_func)
if flag_int then
stream.s_num = cst_int_rdr(size_num, rdr_func)
elseif float_types[size_num] then
stream.s_num = cst_flt_rdr(size_num, float_types[size_num][little and "little" or "big"])
else
error("unsupported float size")
end
return stm_lua_func(stream, "@virtual")
end
local function close_lua_upvalues(list, index)
for i, uv in pairs(list) do
if uv.index >= index then
uv.value = uv.store[uv.index] -- store value
uv.store = uv
uv.index = "value" -- self reference
list[i] = nil
end
end
end
local function open_lua_upvalue(list, index, memory)
local prev = list[index]
if not prev then
prev = {index = index, store = memory}
list[index] = prev
end
return prev
end
local function on_lua_error(failed, err)
local src = failed.source
local line = failed.lines[failed.pc - 1]
error(string.format("%s:%i: %s", src, line, err), 0)
end
-- ccuser44 added multithreading support
-- TODO: Create multiple threads for closure and use a module and/or round robin load balancer to distribute usage
local isClient, actorContainer
local function new_threaded_closure(proto, env, upval)
isClient = isClient or game:GetService("RunService"):IsClient()
actorContainer = actorContainer or script
local actor = Instance.new("Actor")
local clone = script:Clone()
local runner = script[isClient and "LocalRunner" or "Runner"]:Clone()
local event = Instance.new("BindableEvent")
local tag = 0
for _, v in clone:GetChildren() do
if v:IsA("Actor") then
v:Destroy()
end
end
event.Name = "ReturnPass"
event.Parent = runner
clone.Parent = runner
runner.Disabled = false
runner.Parent = actor
actor.Name = "MultithreadRunner_"..tostring(math.random())
actor.Parent = actorContainer
task.defer(actor.SendMessage, actor, "wrap_state", proto, env, upval)
task.wait()
return function(...)
tag = tag + 1
local currentTag = tag
local routine = coroutine.running()
local connection = event.Event:Connect(function(eventTag, ...)
if eventTag == currentTag then
coroutine.resume(routine, ...)
end
end)
task.defer(actor.SendMessage, actor, "run_callback", currentTag, ...)
local args = table.pack(coroutine.yield())
connection:Disconnect()
if not args[1] then
error(args[2], 2)
end
return table.unpack(args, 2, args.n)
end
end
local function run_lua_func(state, env, upvals)
local code = state.code
local subs = state.subs
local vararg = state.vararg
local top_index = -1
local open_list = {}
local memory = state.memory
local pc = state.pc
while true do
local inst = code[pc]
local op = inst.op
pc = pc + 1
if op < 18 then
if op < 8 then
if op < 3 then
if op < 1 then
--[[LOADNIL]]
for i = inst.A, inst.B do memory[i] = nil end
elseif op > 1 then
--[[GETUPVAL]]
local uv = upvals[inst.B]
memory[inst.A] = uv.store[uv.index]
else
--[[ADD]]
local lhs, rhs
if inst.is_KB then
lhs = inst.const_B
else
lhs = memory[inst.B]
end
if inst.is_KC then
rhs = inst.const_C
else
rhs = memory[inst.C]
end
memory[inst.A] = lhs + rhs
end
elseif op > 3 then
if op < 6 then
if op > 4 then
--[[SELF]]
local A = inst.A
local B = inst.B
local index
if inst.is_KC then
index = inst.const_C
else
index = memory[inst.C]
end
memory[A + 1] = memory[B]
memory[A] = memory[B][index]
else
--[[GETGLOBAL]]
memory[inst.A] = env[inst.const]
end
elseif op > 6 then
--[[GETTABLE]]
local index
if inst.is_KC then
index = inst.const_C
else
index = memory[inst.C]
end
memory[inst.A] = memory[inst.B][index]
else
--[[SUB]]
local lhs, rhs
if inst.is_KB then
lhs = inst.const_B
else
lhs = memory[inst.B]
end
if inst.is_KC then
rhs = inst.const_C
else
rhs = memory[inst.C]
end
memory[inst.A] = lhs - rhs
end
else --[[MOVE]]
memory[inst.A] = memory[inst.B]
end
elseif op > 8 then
if op < 13 then
if op < 10 then
--[[SETGLOBAL]]
env[inst.const] = memory[inst.A]
elseif op > 10 then
if op < 12 then
--[[CALL]]
local A = inst.A
local B = inst.B
local C = inst.C
local params
if B == 0 then
params = top_index - A
else
params = B - 1
end
local ret_list = table.pack(memory[A](table.unpack(memory, A + 1, A + params)))
local ret_num = ret_list.n
if C == 0 then
top_index = A + ret_num - 1
else
ret_num = C - 1
end
table.move(ret_list, 1, ret_num, A, memory)
else
--[[SETUPVAL]]
local uv = upvals[inst.B]
uv.store[uv.index] = memory[inst.A]
end
else
--[[MUL]]
local lhs, rhs
if inst.is_KB then
lhs = inst.const_B
else
lhs = memory[inst.B]
end
if inst.is_KC then
rhs = inst.const_C
else
rhs = memory[inst.C]
end
memory[inst.A] = lhs * rhs
end
elseif op > 13 then
if op < 16 then
if op > 14 then
--[[TAILCALL]]
local A = inst.A
local B = inst.B
local params
if B == 0 then
params = top_index - A
else
params = B - 1
end
close_lua_upvalues(open_list, 0)
return memory[A](table.unpack(memory, A + 1, A + params))
else
--[[SETTABLE]]
local index, value
if inst.is_KB then
index = inst.const_B
else
index = memory[inst.B]
end
if inst.is_KC then
value = inst.const_C
else
value = memory[inst.C]
end
memory[inst.A][index] = value
end
elseif op > 16 then
--[[NEWTABLE]]
memory[inst.A] = table.create(inst.const) -- inst.const contains array size
else
--[[DIV]]
local lhs, rhs
if inst.is_KB then
lhs = inst.const_B
else
lhs = memory[inst.B]
end
if inst.is_KC then
rhs = inst.const_C
else
rhs = memory[inst.C]
end
memory[inst.A] = lhs / rhs
end
else
--[[LOADK]]
memory[inst.A] = inst.const
end
else
--[[FORLOOP]]
local A = inst.A
local step = memory[A + 2]
local index = memory[A] + step
local limit = memory[A + 1]
local loops
if step >= 0 then
loops = index <= limit
else
loops = index >= limit
end
if loops then
memory[A] = index
memory[A + 3] = index
pc = pc + inst.sBx
end
end
elseif op > 18 then
if op < 28 then
if op < 23 then
if op < 20 then
--[[LEN]]
memory[inst.A] = #memory[inst.B]
elseif op > 20 then
if op < 22 then
--[[RETURN]]
local A = inst.A
local B = inst.B
local len
if B == 0 then
len = top_index - A + 1
else
len = B - 1
end
close_lua_upvalues(open_list, 0)
return table.unpack(memory, A, A + len - 1)
else
--[[CONCAT]]
local B, C = inst.B, inst.C
local success, str = pcall(table.concat, memory, "", B, C)
if not success then
str = memory[B]
for i = B + 1, C do str = str .. memory[i] end
end
memory[inst.A] = str
end
else
--[[MOD]]
local lhs, rhs
if inst.is_KB then
lhs = inst.const_B
else
lhs = memory[inst.B]
end
if inst.is_KC then
rhs = inst.const_C
else
rhs = memory[inst.C]
end
memory[inst.A] = lhs % rhs
end
elseif op > 23 then
if op < 26 then
if op > 24 then
--[[CLOSE]]
close_lua_upvalues(open_list, inst.A)
else
--[[EQ]]
local lhs, rhs
if inst.is_KB then
lhs = inst.const_B
else
lhs = memory[inst.B]
end
if inst.is_KC then
rhs = inst.const_C
else
rhs = memory[inst.C]
end
if (lhs == rhs) == (inst.A ~= 0) then pc = pc + code[pc].sBx end
pc = pc + 1
end
elseif op > 26 then
--[[LT]]
local lhs, rhs
if inst.is_KB then
lhs = inst.const_B
else
lhs = memory[inst.B]
end
if inst.is_KC then
rhs = inst.const_C
else
rhs = memory[inst.C]
end
if (lhs < rhs) == (inst.A ~= 0) then pc = pc + code[pc].sBx end
pc = pc + 1
else
--[[POW]]
local lhs, rhs
if inst.is_KB then
lhs = inst.const_B
else
lhs = memory[inst.B]
end
if inst.is_KC then
rhs = inst.const_C
else
rhs = memory[inst.C]
end
memory[inst.A] = lhs ^ rhs
end
else
--[[LOADBOOL]]
memory[inst.A] = inst.B ~= 0
if inst.C ~= 0 then pc = pc + 1 end
end
elseif op > 28 then
if op < 33 then
if op < 30 then
--[[LE]]
local lhs, rhs
if inst.is_KB then
lhs = inst.const_B
else
lhs = memory[inst.B]
end
if inst.is_KC then
rhs = inst.const_C
else
rhs = memory[inst.C]
end
if (lhs <= rhs) == (inst.A ~= 0) then pc = pc + code[pc].sBx end
pc = pc + 1
elseif op > 30 then
if op < 32 then
--[[CLOSURE]]
local sub = subs[inst.Bx + 1] -- offset for 1 based index
local nups = sub.num_upval
local uvlist
if nups ~= 0 then
uvlist = table.create(nups - 1)
for i = 1, nups do
local pseudo = code[pc + i - 1]
if pseudo.op == OPCODE_RM[0] then -- @MOVE
uvlist[i - 1] = open_lua_upvalue(open_list, pseudo.B, memory)
elseif pseudo.op == OPCODE_RM[4] then -- @GETUPVAL
uvlist[i - 1] = upvals[pseudo.B]
end
end
pc = pc + nups
end
memory[inst.A] = (sub.source and string.sub(sub.source, 1, 39) == "SUPER_SECRET_ADONIS_MULTITHREAD_PREFIX_") and new_threaded_closure(sub, env, uvlist) or lua_wrap_state(sub, env, uvlist)
else
--[[TESTSET]]
local A = inst.A
local B = inst.B
if (not memory[B]) ~= (inst.C ~= 0) then
memory[A] = memory[B]
pc = pc + code[pc].sBx
end
pc = pc + 1
end
else
--[[UNM]]
memory[inst.A] = -memory[inst.B]
end
elseif op > 33 then
if op < 36 then
if op > 34 then
--[[VARARG]]
local A = inst.A
local len = inst.B
if len == 0 then
len = vararg.len
top_index = A + len - 1
end
table.move(vararg.list, 1, len, A, memory)
else
--[[FORPREP]]
local A = inst.A
local init, limit, step
init = assert(tonumber(memory[A]), "`for` initial value must be a number")
limit = assert(tonumber(memory[A + 1]), "`for` limit must be a number")
step = assert(tonumber(memory[A + 2]), "`for` step must be a number")
memory[A] = init - step
memory[A + 1] = limit
memory[A + 2] = step
pc = pc + inst.sBx
end
elseif op > 36 then
--[[SETLIST]]
local A = inst.A
local C = inst.C
local len = inst.B
local tab = memory[A]
local offset
if len == 0 then len = top_index - A end
if C == 0 then
C = inst[pc].value
pc = pc + 1
end
offset = (C - 1) * FIELDS_PER_FLUSH
table.move(memory, A + 1, A + len, offset + 1, tab)
else
--[[NOT]]
memory[inst.A] = not memory[inst.B]
end
else
--[[TEST]]
if (not memory[inst.A]) ~= (inst.C ~= 0) then pc = pc + code[pc].sBx end
pc = pc + 1
end
else
--[[TFORLOOP]]
local A = inst.A
local func = memory[A]
local state = memory[A + 1]
local index = memory[A + 2]
local base = A + 3
local vals
-- === Luau compatibility - General iteration begin ===
-- // ccuser44 added support for generic iteration
-- (Please don't use general iteration in vanilla Lua code)
if not index and not state and type(func) == "table" then
local metatable = pcall(getmetatable, func) and getmetatable(func)
if not (type(metatable) == "table" and rawget(metatable, "__call")) then
func, state, index = (type(metatable) == "table" and rawget(metatable, "__iter") or next), func, nil
memory[A], memory[A + 1], memory[A + 2] = func, state, index
end
end
-- === Luau compatibility - General iteration end ===
vals = {func(state, index)}
table.move(vals, 1, inst.C, base, memory)
if memory[base] ~= nil then
memory[A + 2] = memory[base]
pc = pc + code[pc].sBx
end
pc = pc + 1
end
else
--[[JMP]]
pc = pc + inst.sBx
end
state.pc = pc
end
end
function lua_wrap_state(proto, env, upval)
local function wrapped(...)
local passed = table.pack(...)
local memory = table.create(proto.max_stack)
local vararg = {len = 0, list = {}}
table.move(passed, 1, proto.num_param, 0, memory)
if proto.num_param < passed.n then
local start = proto.num_param + 1
local len = passed.n - proto.num_param
vararg.len = len
table.move(passed, start, start + len - 1, 1, vararg.list)
end
local state = {vararg = vararg, memory = memory, code = proto.code, subs = proto.subs, pc = 1}
local result = table.pack(pcall(run_lua_func, state, env, upval))
if result[1] then
return table.unpack(result, 2, result.n)
else
local failed = {pc = state.pc, source = proto.source, lines = proto.lines}
on_lua_error(failed, result[2])
return
end
end
return wrapped
end
return setmetatable({
bc_to_state = lua_bc_to_state,
wrap_state = lua_wrap_state,
OPCODE_RM = OPCODE_RM,
OPCODE_T = OPCODE_T,
OPCODE_M = OPCODE_M,
}, {__call = function(_, BCode, Env) -- Backwards compatibility for legacy rerubi usage
return lua_wrap_state(lua_bc_to_state(BCode), Env or {})
end})
| 7,695 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Shared/GoodSignal.luau | --!native
--------------------------------------------------------------------------------
-- Batched Yield-Safe Signal Implementation --
-- This is a Signal class which has effectively identical behavior to a --
-- normal RBXScriptSignal, with the only difference being a couple extra --
-- stack frames at the bottom of the stack trace when an error is thrown. --
-- This implementation caches runner coroutines, so the ability to yield in --
-- the signal handlers comes at minimal extra cost over a naive signal --
-- implementation that either always or never spawns a thread. --
-- --
-- API: --
-- local Signal = require(THIS MODULE) --
-- local sig = Signal.new() --
-- local connection = sig:Connect(function(arg1, arg2, ...) ... end) --
-- sig:Fire(arg1, arg2, ...) --
-- connection:Disconnect() --
-- sig:DisconnectAll() --
-- local arg1, arg2, ... = sig:Wait() --
-- --
-- Licence: --
-- Licenced under the MIT licence. --
-- --
-- Authors: --
-- stravant - July 31st, 2021 - Created the file. --
--------------------------------------------------------------------------------
--[[
MIT License
Copyright (c) 2021 Mark Langen
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
]]
-- The currently idle thread to run the next handler on
local freeRunnerThread = nil
-- Function which acquires the currently idle handler runner thread, runs the
-- function fn on it, and then releases the thread, returning it to being the
-- currently idle one.
-- If there was a currently idle runner thread already, that's okay, that old
-- one will just get thrown and eventually GCed.
local function acquireRunnerThreadAndCallEventHandler(fn, ...)
local acquiredRunnerThread = freeRunnerThread
freeRunnerThread = nil
fn(...)
-- The handler finished running, this runner thread is free again.
freeRunnerThread = acquiredRunnerThread
end
-- Coroutine runner that we create coroutines of. The coroutine can be
-- repeatedly resumed with functions to run followed by the argument to run
-- them with.
local function runEventHandlerInFreeThread()
-- Note: We cannot use the initial set of arguments passed to
-- runEventHandlerInFreeThread for a call to the handler, because those
-- arguments would stay on the stack for the duration of the thread's
-- existence, temporarily leaking references. Without access to raw bytecode
-- there's no way for us to clear the "..." references from the stack.
while true do
acquireRunnerThreadAndCallEventHandler(coroutine.yield())
end
end
-- Connection class
local Connection = {}
Connection.__index = Connection
function Connection.new(signal, fn)
return setmetatable({
_connected = true,
_signal = signal,
_fn = fn,
_next = false,
}, Connection)
end
function Connection:Disconnect()
self._connected = false
-- Unhook the node, but DON'T clear it. That way any fire calls that are
-- currently sitting on this node will be able to iterate forwards off of
-- it, but any subsequent fire calls will not hit it, and it will be GCed
-- when no more fire calls are sitting on it.
if self._signal._handlerListHead == self then
self._signal._handlerListHead = self._next
else
local prev = self._signal._handlerListHead
while prev and prev._next ~= self do
prev = prev._next
end
if prev then
prev._next = self._next
end
end
end
-- Make Connection strict
setmetatable(Connection, {
__index = function(tb, key)
error(("Attempt to get Connection::%s (not a valid member)"):format(tostring(key)), 2)
end,
__newindex = function(tb, key, value)
error(("Attempt to set Connection::%s (not a valid member)"):format(tostring(key)), 2)
end
})
-- Signal class
local Signal = {}
Signal.__index = Signal
function Signal.new()
return setmetatable({
_handlerListHead = false,
Event = {},
}, Signal)
end
function Signal:Connect(fn)
local connection = Connection.new(self, fn)
if self._handlerListHead then
connection._next = self._handlerListHead
self._handlerListHead = connection
else
self._handlerListHead = connection
end
local signalSelf = self
function connection:Fire(...)
signalSelf:Fire(fn)
end
function connection:fire(...)
signalSelf:Fire(fn)
end
function connection:disconnect()
self:Disconnect()
end
function connection:wait()
return signalSelf:Wait()
end
return connection
end
function Signal:connect(fn)
return self:Connect(fn)
end
-- Disconnect all handlers. Since we use a linked list it suffices to clear the
-- reference to the head handler.
function Signal:DisconnectAll()
self._handlerListHead = false
end
-- Signal:Fire(...) implemented by running the handler functions on the
-- coRunnerThread, and any time the resulting thread yielded without returning
-- to us, that means that it yielded to the Roblox scheduler and has been taken
-- over by Roblox scheduling, meaning we have to make a new coroutine runner.
function Signal:Fire(...)
local item = self._handlerListHead
while item do
if item._connected then
if not freeRunnerThread then
freeRunnerThread = coroutine.create(runEventHandlerInFreeThread)
-- Get the freeRunnerThread to the first yield
coroutine.resume(freeRunnerThread)
end
task.spawn(freeRunnerThread, item._fn, ...)
end
item = item._next
end
end
function Signal:fire(...)
self:Fire(...)
end
-- Implement Signal:Wait() in terms of a temporary connection using
-- a Signal:Connect() which disconnects itself.
function Signal:Wait()
local waitingCoroutine = coroutine.running()
local cn;
cn = self:Connect(function(...)
cn:Disconnect()
task.spawn(waitingCoroutine, ...)
end)
return coroutine.yield()
end
function Signal:wait()
return self:Wait()
end
-- Implement Signal:Once() in terms of a connection which disconnects
-- itself before running the handler.
function Signal:Once(fn)
local cn;
cn = self:Connect(function(...)
if cn._connected then
cn:Disconnect()
end
fn(...)
end)
return cn
end
function Signal:ConnectOnce(fn)
return self:Once(fn)
end
function Signal:connectOnce(fn)
return self:Once(fn)
end
function Signal:Destroy()
self:DisconnectAll()
setmetatable(self, nil)
end
-- Make signal strict
setmetatable(Signal, {
__index = function(tb, key)
error(("Attempt to get Signal::%s (not a valid member)"):format(tostring(key)), 2)
end,
__newindex = function(tb, key, value)
error(("Attempt to set Signal::%s (not a valid member)"):format(tostring(key)), 2)
end
})
return Signal
| 1,743 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Shared/HashLib.luau | --!native
--!optimize 2
--!strict
--[[
Description: SHA256 digest hash
Author: XoifailTheGod
Date: 2024
Link: https://devforum.roblox.com/t/fastest-sha256-module/3180016
]]
local MODULO = 2^32
local BYTE, DWORD = 1, 4
local CONSTANTS = buffer.create(64 * DWORD) do -- CONSTANTS = k
local RoundConstants = {
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
}
for Index, Constant in ipairs(RoundConstants) do
local BufferOffset = (Index - 1) * DWORD
buffer.writeu32(CONSTANTS, BufferOffset, Constant)
end
end
local HASH_VALUES = buffer.create(8 * DWORD) do -- HASH_VALUES = h0-h7
buffer.writeu32(HASH_VALUES, 0, 0x6a09e667)
buffer.writeu32(HASH_VALUES, 4, 0xbb67ae85)
buffer.writeu32(HASH_VALUES, 8, 0x3c6ef372)
buffer.writeu32(HASH_VALUES, 12, 0xa54ff53a)
buffer.writeu32(HASH_VALUES, 16, 0x510e527f)
buffer.writeu32(HASH_VALUES, 20, 0x9b05688c)
buffer.writeu32(HASH_VALUES, 24, 0x1f83d9ab)
buffer.writeu32(HASH_VALUES, 28, 0x5be0cd19)
end
local function ProcessNumber(Input: number, Length: number): buffer
local OutputBuffer = buffer.create(Length)
for Index = Length - 1, 0, -1 do
local Remainder = Input % 256
buffer.writeu8(OutputBuffer, Index, Remainder)
Input = bit32.rshift(Input, 8)
end
return OutputBuffer
end
local function PreProcess(Content: buffer): (buffer, number)
local ContentLength = buffer.len(Content)
local Padding = (64 - ((ContentLength + 9) % 64)) % 64
local NewContentLength = ContentLength + 1 + Padding + 8
local NewContent = buffer.create(NewContentLength)
buffer.copy(NewContent, 0, Content)
buffer.writeu8(NewContent, ContentLength, 128)
local Length8 = ContentLength * 8
for Index = 7, 0, -1 do
local Remainder = Length8 % 256
buffer.writeu8(NewContent, Index + ContentLength + 1 + Padding, Remainder)
Length8 = (Length8 - Remainder) / 256
end
return NewContent, NewContentLength
end
local Offsets = buffer.create(256)
local function DigestBlock(Blocks: buffer, Offset: number, A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number)
for BlockIndex = 0, 60, 4 do
local BlockBufferIndex = Offset + BlockIndex
local Word = bit32.byteswap(buffer.readu32(Blocks, BlockBufferIndex))
buffer.writeu32(Offsets, BlockIndex, Word)
end
for Index = 16 * 4, 63 * 4, 4 do
local Sub15 = buffer.readu32(Offsets, Index - (15 * 4))
local Sub2 = buffer.readu32(Offsets, Index - (2 * 4))
local Sub16 = buffer.readu32(Offsets, Index - (16 * 4))
local Sub7 = buffer.readu32(Offsets, Index - (7 * 4))
local S0 = bit32.bxor(bit32.rrotate(Sub15, 7), bit32.rrotate(Sub15, 18), bit32.rshift(Sub15, 3))
local S1 = bit32.bxor(bit32.rrotate(Sub2, 17), bit32.rrotate(Sub2, 19), bit32.rshift(Sub2, 10))
buffer.writeu32(Offsets, Index, (Sub16 + S0 + Sub7 + S1))
end
local OldA, OldB, OldC, OldD, OldE, OldF, OldG, OldH = A, B, C, D, E, F, G, H
for BufferIndex = 0, 63 * 4, 4 do
local S1 = bit32.bxor(bit32.rrotate(E, 6), bit32.rrotate(E, 11), bit32.rrotate(E, 25))
local Ch = bit32.bxor(bit32.band(E, F), bit32.band(bit32.bnot(E), G))
local Temp1 = H + S1 + Ch + buffer.readu32(CONSTANTS, BufferIndex) + buffer.readu32(Offsets, BufferIndex)
local S0 = bit32.bxor(bit32.rrotate(A, 2), bit32.rrotate(A, 13), bit32.rrotate(A, 22))
local Maj = bit32.bxor(bit32.band(A, B), bit32.band(A, C), bit32.band(B, C))
local Temp2 = S0 + Maj
H = G
G = F
F = E
E = D + Temp1
D = C
C = B
B = A
A = Temp1 + Temp2
end
return (A + OldA) % MODULO, (B + OldB) % MODULO, (C + OldC) % MODULO, (D + OldD) % MODULO, (E + OldE) % MODULO, (F + OldF) % MODULO, (G + OldG) % MODULO, (H + OldH) % MODULO
end
local HashValues = buffer.create(32)
local FormatString = string.rep("%08x", 8)
local function SHA256(Message: buffer | string, Salt: (buffer | string)?): string
Message = type(Message) == "string" and buffer.fromstring(Message) or Message
Salt = type(Salt) == "string" and buffer.fromstring(Salt) or Salt
if Salt and buffer.len(Salt) > 0 then
local MessageWithSalt = buffer.create(buffer.len(Message) + buffer.len(Salt))
buffer.copy(MessageWithSalt, 0, Message)
buffer.copy(MessageWithSalt, buffer.len(Message), Salt)
Message = MessageWithSalt
end
local A, B, C, D = 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a
local E, F, G, H = 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
local ProcessedMessage, Length = PreProcess(Message)
for Index = 0, Length - 1, 64 do
A, B, C, D, E, F, G, H = DigestBlock(ProcessedMessage, Index, A, B, C, D, E, F, G, H)
end
return string.format(FormatString, A, B, C, D, E, F, G, H)
end
return {
SHA256 = SHA256
}
| 2,152 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Shared/MatIcons.luau | --[[
════════════════════════════════════════════
Material Icons Collection for Roblox
Uploaded painstakingly by @Expertcoderz
Images are licensed under Apache 2.0 license
Sourced from Google LLC:
https://fonts.google.com/icons
('Sharp' style, white colored)
════════════════════════════════════════════
https://create.roblox.com/store/asset/7646623585
]]
return { -- Decal IDs
["Account circle"] = 7495451175,
["Add"] = 7541498082,
["Add box"] = 7541483541,
["Add circle"] = 7541498940,
["Add circle outline"] = 7541499713,
["Add moderator"] = 7495454078,
["Alert"] = 7467248902,
["Admin panel settings"] = 7495455898,
["Announcement"] = 7495456913,
["Arrow back"] = 7541501140,
["Arrow forward"] = 7541501877,
["Arrow left"] = 7541502824,
["Arrow right"] = 7541503474,
["Backspace"] = 7495457784,
["Ballot"] = 7510972090,
["Brush"] = 7707383293,
["Bug report"] = 7495460221,
["Build"] = 7495461226,
["Campaign"] = 7543116287,
["Category"] = 7707514735,
["Chat"] = 7495461949,
["Check circle"] = 7495462987,
["Checklist"] = 7541573776,
["Clear"] = 7495463952,
["Code"] = 7495464623,
["Create"] = 7495465397,
["Create new folder"] = 7495466343,
["Dangerous"] = 7495468117,
["Delete"] = 7495468832,
["Delete forever"] = 7495469947,
["Description"] = 7495471249,
["Done"] = 7495550742,
["Door sliding"] = 7495552050,
["Double arrow"] = 7541578585,
["Mail"] = 7501175708, -- originally 'Email'
["Epix"] = 7681261289,
["Error"] = 7501176860,
["Explore"] = 7646573201,
["Explore off"] = 7646577572,
["Feedback"] = 7501177838,
["Filter"] = 7510972987,
["Filter list"] = 7541506485,
["Flashlight off"] = 7510973971,
["Flashlight on"] = 7510975108,
["Folder"] = 7510976205,
["Folder open"] = 7510977628,
["Format list bulleted"] = 7541574838,
["Format list numbered"] = 7541902647,
["Forum"] = 7510978373,
["Gavel"] = 7510979485,
["Grade"] = 7510980474,
["Grid view"] = 7510992915,
["Help"] = 7510994359,
["Home"] = 7510996733,
["Hourglass empty"] = 7707374959,
["Hourglass full"] = 7707378666,
["How to reg"] = 7510998518,
["Info"] = 7510999669,
["Inventory"] = 7707384998,
["Inventory 2"] = 7707390573,
["Label"] = 7511000774,
["Label off"] = 7511001374,
["Language"] = 7514706994,
["Leaderboard"] = 7514708563,
["Light"] = 7514709535,
["Lock"] = 7514711240,
["Lock open"] = 7514712758,
["Logout"] = 7514714078,
["Manage accounts"] = 7541905350,
["Manage search"] = 7541904254,
["Menu"] = 7541580101,
["Menu open"] = 7541581631,
["No accounts"] = 7543066271,
["Notification important"] = 7543068343,
["Notifications"] = 7543117530,
["Notifications off"] = 7543118441,
["Palette"] = 7707391830,
["People alt"] = 7549500924,
["People"] = 7549501926,
["Person add"] = 7549503310,
["Person"] = 7549504320,
["Person off"] = 7549505192,
["Person remove"] = 7549506692,
["Person search"] = 7549514426,
["Policy"] = 17570230934,
["Poll"] = 7549517343,
["Priority high"] = 7541925009,
["Privacy tip"] = 7541923707,
["QR code scanner"] = 7543119186,
["Quick reference"] = 17557073691;
["Refresh"] = 7549521656,
["Remove moderator"] = 7536810074,
["Reply"] = 7541922000,
["Report"] = 7541920650,
["Schedule"] = 7541919785,
["Search"] = 7514716894,
["Security"] = 7541911332,
["Send"] = 7541921277,
["Settings"] = 7541906831,
["Broadcast"] = 7541576921, -- originally 'Settings input antenna'
["Shield"] = 7536784790,
["Shopping cart"] = 7541907631,
["Sort"] = 7541585212,
["Subject"] = 7541586088,
["Supervised user circle"] = 7541909700,
["Supervisor account"] = 7541908582,
["System upgrade"] = 16188125076,
["Tag"] = 7541583168,
["Text format"] = 7541917278,
["Text snippet"] = 7541918313,
["Topic"] = 7541919005,
["Verified"] = 7541916144,
["Verified user"] = 7536783953,
["Visibility"] = 7541894862,
["Visibility off"] = 7541895644,
["Volume off"] = 7541896724,
["Volume up"] = 7541896266,
["Key"] = 7541891753,
["Warning"] = 7514715386,
["Widgets"] = 7541897766,
}
| 1,549 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/Shared/Typechecker.luau | --!native
--[[
t: a runtime typechecker for Roblox
by osyrisrblx
MIT License
]]
local t = {}
function t.type(typeName)
return function(value)
local valueType = type(value)
if valueType == typeName then
return true
else
return false, string.format("%s expected, got %s", typeName, valueType)
end
end
end
function t.typeof(typeName)
return function(value)
local valueType = typeof(value)
if valueType == typeName then
return true
else
return false, string.format("%s expected, got %s", typeName, valueType)
end
end
end
--[[**
matches any type except nil
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
function t.any(value)
if value ~= nil then
return true
else
return false, "any expected, got nil"
end
end
--Lua primitives
--[[**
ensures Lua primitive boolean type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.boolean = t.typeof("boolean")
--[[**
ensures Lua primitive buffer type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.buffer = t.typeof("buffer")
--[[**
ensures Lua primitive thread type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.thread = t.typeof("thread")
--[[**
ensures Lua primitive callback type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.callback = t.typeof("function")
t["function"] = t.callback
--[[**
ensures Lua primitive none type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.none = t.typeof("nil")
t["nil"] = t.none
--[[**
ensures Lua primitive string type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.string = t.typeof("string")
--[[**
ensures Lua primitive table type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.table = t.typeof("table")
--[[**
ensures Lua primitive userdata type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.userdata = t.type("userdata")
--[[**
ensures Lua primitive vector type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.vector = t.type("vector")
--[[**
ensures value is a number and non-NaN
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
function t.number(value)
local valueType = typeof(value)
if valueType == "number" then
if value == value then
return true
else
return false, "unexpected NaN value"
end
else
return false, string.format("number expected, got %s", valueType)
end
end
--[[**
ensures value is NaN
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
function t.nan(value)
local valueType = typeof(value)
if valueType == "number" then
if value ~= value then
return true
else
return false, "unexpected non-NaN value"
end
else
return false, string.format("number expected, got %s", valueType)
end
end
-- roblox types
--[[**
ensures Roblox Axes type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.Axes = t.typeof("Axes")
--[[**
ensures Roblox BrickColor type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.BrickColor = t.typeof("BrickColor")
--[[**
ensures Roblox CatalogSearchParams type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.CatalogSearchParams = t.typeof("CatalogSearchParams")
--[[**
ensures Roblox CFrame type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.CFrame = t.typeof("CFrame")
--[[**
ensures Roblox Color3 type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.Color3 = t.typeof("Color3")
--[[**
ensures Roblox ColorSequence type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.ColorSequence = t.typeof("ColorSequence")
--[[**
ensures Roblox ColorSequenceKeypoint type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.ColorSequenceKeypoint = t.typeof("ColorSequenceKeypoint")
--[[**
ensures Roblox DateTime type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.DateTime = t.typeof("DateTime")
--[[**
ensures Roblox DockWidgetPluginGuiInfo type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.DockWidgetPluginGuiInfo = t.typeof("DockWidgetPluginGuiInfo")
--[[**
ensures Roblox Enum type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.Enum = t.typeof("Enum")
--[[**
ensures Roblox EnumItem type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.EnumItem = t.typeof("EnumItem")
--[[**
ensures Roblox Enums type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.Enums = t.typeof("Enums")
--[[**
ensures Roblox Faces type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.Faces = t.typeof("Faces")
--[[**
ensures Roblox FloatCurveKey type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.FloatCurveKey = t.typeof("FloatCurveKey")
--[[**
ensures Roblox Font type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.Font = t.typeof("Font")
--[[**
ensures Roblox Instance type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.Instance = t.typeof("Instance")
--[[**
ensures Roblox NumberRange type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.NumberRange = t.typeof("NumberRange")
--[[**
ensures Roblox NumberSequence type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.NumberSequence = t.typeof("NumberSequence")
--[[**
ensures Roblox NumberSequenceKeypoint type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.NumberSequenceKeypoint = t.typeof("NumberSequenceKeypoint")
--[[**
ensures Roblox OverlapParams type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.OverlapParams = t.typeof("OverlapParams")
--[[**
ensures Roblox PathWaypoint type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.PathWaypoint = t.typeof("PathWaypoint")
--[[**
ensures Roblox PhysicalProperties type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.PhysicalProperties = t.typeof("PhysicalProperties")
--[[**
ensures Roblox Random type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.Random = t.typeof("Random")
--[[**
ensures Roblox Ray type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.Ray = t.typeof("Ray")
--[[**
ensures Roblox RaycastParams type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.RaycastParams = t.typeof("RaycastParams")
--[[**
ensures Roblox RaycastResult type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.RaycastResult = t.typeof("RaycastResult")
--[[**
ensures Roblox RBXScriptConnection type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.RBXScriptConnection = t.typeof("RBXScriptConnection")
--[[**
ensures Roblox RBXScriptSignal type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.RBXScriptSignal = t.typeof("RBXScriptSignal")
--[[**
ensures Roblox Rect type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.Rect = t.typeof("Rect")
--[[**
ensures Roblox Region3 type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.Region3 = t.typeof("Region3")
--[[**
ensures Roblox Region3int16 type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.Region3int16 = t.typeof("Region3int16")
--[[**
ensures Roblox TweenInfo type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.TweenInfo = t.typeof("TweenInfo")
--[[**
ensures Roblox UDim type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.UDim = t.typeof("UDim")
--[[**
ensures Roblox UDim2 type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.UDim2 = t.typeof("UDim2")
--[[**
ensures Roblox Vector2 type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.Vector2 = t.typeof("Vector2")
--[[**
ensures Roblox Vector2int16 type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.Vector2int16 = t.typeof("Vector2int16")
--[[**
ensures Roblox Vector3 type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.Vector3 = t.typeof("Vector3")
--[[**
ensures Roblox Vector3int16 type
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
t.Vector3int16 = t.typeof("Vector3int16")
--[[**
ensures value is a given literal value
@param literal The literal to use
@returns A function that will return true iff the condition is passed
**--]]
function t.literal(...)
local size = select("#", ...)
if size == 1 then
local literal = ...
return function(value)
if value ~= literal then
return false, string.format("expected %s, got %s", tostring(literal), tostring(value))
end
return true
end
else
local literals = {}
for i = 1, size do
local value = select(i, ...)
literals[i] = t.literal(value)
end
return t.union(table.unpack(literals, 1, size))
end
end
--[[**
DEPRECATED
Please use t.literal
**--]]
t.exactly = t.literal
--[[**
Returns a t.union of each key in the table as a t.literal
@param keyTable The table to get keys from
@returns True iff the condition is satisfied, false otherwise
**--]]
function t.keyOf(keyTable)
local keys = {}
local length = 0
for key in keyTable do
length = length + 1
keys[length] = key
end
return t.literal(table.unpack(keys, 1, length))
end
--[[**
Returns a t.union of each value in the table as a t.literal
@param valueTable The table to get values from
@returns True iff the condition is satisfied, false otherwise
**--]]
function t.valueOf(valueTable)
local values = {}
local length = 0
for _, value in valueTable do
length = length + 1
values[length] = value
end
return t.literal(table.unpack(values, 1, length))
end
--[[**
ensures value is an integer
@param value The value to check against
@returns True iff the condition is satisfied, false otherwise
**--]]
function t.integer(value)
local success, errMsg = t.number(value)
if not success then
return false, errMsg or ""
end
if value % 1 == 0 then
return true
else
return false, string.format("integer expected, got %s", value)
end
end
--[[**
ensures value is a number where min <= value
@param min The minimum to use
@returns A function that will return true iff the condition is passed
**--]]
function t.numberMin(min)
return function(value)
local success, errMsg = t.number(value)
if not success then
return false, errMsg or ""
end
if value >= min then
return true
else
return false, string.format("number >= %s expected, got %s", min, value)
end
end
end
--[[**
ensures value is a number where value <= max
@param max The maximum to use
@returns A function that will return true iff the condition is passed
**--]]
function t.numberMax(max)
return function(value)
local success, errMsg = t.number(value)
if not success then
return false, errMsg
end
if value <= max then
return true
else
return false, string.format("number <= %s expected, got %s", max, value)
end
end
end
--[[**
ensures value is a number where min < value
@param min The minimum to use
@returns A function that will return true iff the condition is passed
**--]]
function t.numberMinExclusive(min)
return function(value)
local success, errMsg = t.number(value)
if not success then
return false, errMsg or ""
end
if min < value then
return true
else
return false, string.format("number > %s expected, got %s", min, value)
end
end
end
--[[**
ensures value is a number where value < max
@param max The maximum to use
@returns A function that will return true iff the condition is passed
**--]]
function t.numberMaxExclusive(max)
return function(value)
local success, errMsg = t.number(value)
if not success then
return false, errMsg or ""
end
if value < max then
return true
else
return false, string.format("number < %s expected, got %s", max, value)
end
end
end
--[[**
ensures value is a number where value > 0
@returns A function that will return true iff the condition is passed
**--]]
t.numberPositive = t.numberMinExclusive(0)
--[[**
ensures value is a number where value < 0
@returns A function that will return true iff the condition is passed
**--]]
t.numberNegative = t.numberMaxExclusive(0)
--[[**
ensures value is a number where min <= value <= max
@param min The minimum to use
@param max The maximum to use
@returns A function that will return true iff the condition is passed
**--]]
function t.numberConstrained(min, max)
assert(t.number(min))
assert(t.number(max))
local minCheck = t.numberMin(min)
local maxCheck = t.numberMax(max)
return function(value)
local minSuccess, minErrMsg = minCheck(value)
if not minSuccess then
return false, minErrMsg or ""
end
local maxSuccess, maxErrMsg = maxCheck(value)
if not maxSuccess then
return false, maxErrMsg or ""
end
return true
end
end
--[[**
ensures value is a number where min < value < max
@param min The minimum to use
@param max The maximum to use
@returns A function that will return true iff the condition is passed
**--]]
function t.numberConstrainedExclusive(min, max)
assert(t.number(min))
assert(t.number(max))
local minCheck = t.numberMinExclusive(min)
local maxCheck = t.numberMaxExclusive(max)
return function(value)
local minSuccess, minErrMsg = minCheck(value)
if not minSuccess then
return false, minErrMsg or ""
end
local maxSuccess, maxErrMsg = maxCheck(value)
if not maxSuccess then
return false, maxErrMsg or ""
end
return true
end
end
--[[**
ensures value matches string pattern
@param string pattern to check against
@returns A function that will return true iff the condition is passed
**--]]
function t.match(pattern)
assert(t.string(pattern))
return function(value)
local stringSuccess, stringErrMsg = t.string(value)
if not stringSuccess then
return false, stringErrMsg
end
if string.match(value, pattern) == nil then
return false, string.format("%q failed to match pattern %q", value, pattern)
end
return true
end
end
--[[**
ensures value is either nil or passes check
@param check The check to use
@returns A function that will return true iff the condition is passed
**--]]
function t.optional(check)
assert(t.callback(check))
return function(value)
if value == nil then
return true
end
local success, errMsg = check(value)
if success then
return true
else
return false, string.format("(optional) %s", errMsg or "")
end
end
end
--[[**
matches given tuple against tuple type definition
@param ... The type definition for the tuples
@returns A function that will return true iff the condition is passed
**--]]
function t.tuple(...)
local checks = { ... }
return function(...)
local args = { ... }
for i, check in ipairs(checks) do
local success, errMsg = check(args[i])
if success == false then
return false, string.format("Bad tuple index #%s:\n\t%s", i, errMsg or "")
end
end
return true
end
end
--[[**
ensures all keys in given table pass check
@param check The function to use to check the keys
@returns A function that will return true iff the condition is passed
**--]]
function t.keys(check)
assert(t.callback(check))
return function(value)
local tableSuccess, tableErrMsg = t.table(value)
if tableSuccess == false then
return false, tableErrMsg or ""
end
for key in value do
local success, errMsg = check(key)
if success == false then
return false, string.format("bad key %s:\n\t%s", tostring(key), errMsg or "")
end
end
return true
end
end
--[[**
ensures all values in given table pass check
@param check The function to use to check the values
@returns A function that will return true iff the condition is passed
**--]]
function t.values(check)
assert(t.callback(check))
return function(value)
local tableSuccess, tableErrMsg = t.table(value)
if tableSuccess == false then
return false, tableErrMsg or ""
end
for key, val in value do
local success, errMsg = check(val)
if success == false then
return false, string.format("bad value for key %s:\n\t%s", tostring(key), errMsg or "")
end
end
return true
end
end
--[[**
ensures value is a table and all keys pass keyCheck and all values pass valueCheck
@param keyCheck The function to use to check the keys
@param valueCheck The function to use to check the values
@returns A function that will return true iff the condition is passed
**--]]
function t.map(keyCheck, valueCheck)
assert(t.callback(keyCheck))
assert(t.callback(valueCheck))
local keyChecker = t.keys(keyCheck)
local valueChecker = t.values(valueCheck)
return function(value)
local keySuccess, keyErr = keyChecker(value)
if not keySuccess then
return false, keyErr or ""
end
local valueSuccess, valueErr = valueChecker(value)
if not valueSuccess then
return false, valueErr or ""
end
return true
end
end
--[[**
ensures value is a table and all keys pass valueCheck and all values are true
@param valueCheck The function to use to check the values
@returns A function that will return true iff the condition is passed
**--]]
function t.set(valueCheck)
return t.map(valueCheck, t.literal(true))
end
do
local arrayKeysCheck = t.keys(t.integer)
--[[**
ensures value is an array and all values of the array match check
@param check The check to compare all values with
@returns A function that will return true iff the condition is passed
**--]]
function t.array(check)
assert(t.callback(check))
local valuesCheck = t.values(check)
return function(value)
local keySuccess, keyErrMsg = arrayKeysCheck(value)
if keySuccess == false then
return false, string.format("[array] %s", keyErrMsg or "")
end
-- # is unreliable for sparse arrays
-- Count upwards using ipairs to avoid false positives from the behavior of #
local arraySize = 0
for _ in ipairs(value) do
arraySize = arraySize + 1
end
for key in value do
if key < 1 or key > arraySize then
return false, string.format("[array] key %s must be sequential", tostring(key))
end
end
local valueSuccess, valueErrMsg = valuesCheck(value)
if not valueSuccess then
return false, string.format("[array] %s", valueErrMsg or "")
end
return true
end
end
--[[**
ensures value is an array of a strict makeup and size
@param check The check to compare all values with
@returns A function that will return true iff the condition is passed
**--]]
function t.strictArray(...)
local valueTypes = { ... }
assert(t.array(t.callback)(valueTypes))
return function(value)
local keySuccess, keyErrMsg = arrayKeysCheck(value)
if keySuccess == false then
return false, string.format("[strictArray] %s", keyErrMsg or "")
end
-- If there's more than the set array size, disallow
if #valueTypes < #value then
return false, string.format("[strictArray] Array size exceeds limit of %d", #valueTypes)
end
for idx, typeFn in valueTypes do
local typeSuccess, typeErrMsg = typeFn(value[idx])
if not typeSuccess then
return false, string.format("[strictArray] Array index #%d - %s", idx, typeErrMsg)
end
end
return true
end
end
end
do
local callbackArray = t.array(t.callback)
--[[**
creates a union type
@param ... The checks to union
@returns A function that will return true iff the condition is passed
**--]]
function t.union(...)
local checks = { ... }
assert(callbackArray(checks))
return function(value)
for _, check in ipairs(checks) do
if check(value) then
return true
end
end
return false, "bad type for union"
end
end
--[[**
Alias for t.union
**--]]
t.some = t.union
--[[**
creates an intersection type
@param ... The checks to intersect
@returns A function that will return true iff the condition is passed
**--]]
function t.intersection(...)
local checks = { ... }
assert(callbackArray(checks))
return function(value)
for _, check in ipairs(checks) do
local success, errMsg = check(value)
if not success then
return false, errMsg or ""
end
end
return true
end
end
--[[**
Alias for t.intersection
**--]]
t.every = t.intersection
end
do
local checkInterface = t.map(t.any, t.callback)
--[[**
ensures value matches given interface definition
@param checkTable The interface definition
@returns A function that will return true iff the condition is passed
**--]]
function t.interface(checkTable)
assert(checkInterface(checkTable))
return function(value)
local tableSuccess, tableErrMsg = t.table(value)
if tableSuccess == false then
return false, tableErrMsg or ""
end
for key, check in pairs(checkTable) do
local success, errMsg = check(value[key])
if success == false then
return false, string.format("[interface] bad value for %s:\n\t%s", tostring(key), errMsg or "")
end
end
return true
end
end
--[[**
ensures value matches given interface definition strictly
@param checkTable The interface definition
@returns A function that will return true iff the condition is passed
**--]]
function t.strictInterface(checkTable)
assert(checkInterface(checkTable))
return function(value)
local tableSuccess, tableErrMsg = t.table(value)
if tableSuccess == false then
return false, tableErrMsg or ""
end
for key, check in checkTable do
local success, errMsg = check(value[key])
if success == false then
return false, string.format("[interface] bad value for %s:\n\t%s", tostring(key), errMsg or "")
end
end
for key in value do
if not checkTable[key] then
return false, string.format("[interface] unexpected field %q", tostring(key))
end
end
return true
end
end
end
--[[**
ensure value is an Instance and it's ClassName matches the given ClassName
@param className The class name to check for
@returns A function that will return true iff the condition is passed
**--]]
function t.instanceOf(className, childTable)
assert(t.string(className))
local childrenCheck
if childTable ~= nil then
childrenCheck = t.children(childTable)
end
return function(value)
local instanceSuccess, instanceErrMsg = t.Instance(value)
if not instanceSuccess then
return false, instanceErrMsg or ""
end
if value.ClassName ~= className then
return false, string.format("%s expected, got %s", className, value.ClassName)
end
if childrenCheck then
local childrenSuccess, childrenErrMsg = childrenCheck(value)
if not childrenSuccess then
return false, childrenErrMsg
end
end
return true
end
end
t.instance = t.instanceOf
--[[**
ensure value is an Instance and it's ClassName matches the given ClassName by an IsA comparison
@param className The class name to check for
@returns A function that will return true iff the condition is passed
**--]]
function t.instanceIsA(className, childTable)
assert(t.string(className))
local childrenCheck
if childTable ~= nil then
childrenCheck = t.children(childTable)
end
return function(value)
local instanceSuccess, instanceErrMsg = t.Instance(value)
if not instanceSuccess then
return false, instanceErrMsg or ""
end
if not value:IsA(className) then
return false, string.format("%s expected, got %s", className, value.ClassName)
end
if childrenCheck then
local childrenSuccess, childrenErrMsg = childrenCheck(value)
if not childrenSuccess then
return false, childrenErrMsg
end
end
return true
end
end
--[[**
ensures value is an enum of the correct type
@param enum The enum to check
@returns A function that will return true iff the condition is passed
**--]]
function t.enum(enum)
assert(t.Enum(enum))
return function(value)
local enumItemSuccess, enumItemErrMsg = t.EnumItem(value)
if not enumItemSuccess then
return false, enumItemErrMsg
end
if value.EnumType == enum then
return true
else
return false, string.format("enum of %s expected, got enum of %s", tostring(enum), tostring(value.EnumType))
end
end
end
do
local checkWrap = t.tuple(t.callback, t.callback)
--[[**
wraps a callback in an assert with checkArgs
@param callback The function to wrap
@param checkArgs The function to use to check arguments in the assert
@returns A function that first asserts using checkArgs and then calls callback
**--]]
function t.wrap(callback, checkArgs)
assert(checkWrap(callback, checkArgs))
return function(...)
assert(checkArgs(...))
return callback(...)
end
end
end
--[[**
asserts a given check
@param check The function to wrap with an assert
@returns A function that simply wraps the given check in an assert
**--]]
function t.strict(check)
return function(...)
assert(check(...))
end
end
do
local checkChildren = t.map(t.string, t.callback)
--[[**
Takes a table where keys are child names and values are functions to check the children against.
Pass an instance tree into the function.
If at least one child passes each check, the overall check passes.
Warning! If you pass in a tree with more than one child of the same name, this function will always return false
@param checkTable The table to check against
@returns A function that checks an instance tree
**--]]
function t.children(checkTable)
assert(checkChildren(checkTable))
return function(value)
local instanceSuccess, instanceErrMsg = t.Instance(value)
if not instanceSuccess then
return false, instanceErrMsg or ""
end
local childrenByName = {}
for _, child in ipairs(value:GetChildren()) do
local name = child.Name
if checkTable[name] then
if childrenByName[name] then
return false, string.format("Cannot process multiple children with the same name %q", name)
end
childrenByName[name] = child
end
end
for name, check in checkTable do
local success, errMsg = check(childrenByName[name])
if not success then
return false, string.format("[%s.%s] %s", value:GetFullName(), name, errMsg or "")
end
end
return true
end
end
end
return t
| 7,112 |
Epix-Incorporated/Adonis | Epix-Incorporated-Adonis-735143f/MainModule/init.luau | --[[
_ _ _ _ _ _
/ \ __| | ___ _ __ (_)___ / \ __| |_ __ ___ (_)_ __
/ _ \ / _` |/ _ \| '_ \| / __| / _ \ / _` | '_ ` _ \| | '_ \
/ ___ \ (_| | (_) | | | | \__ \ / ___ \ (_| | | | | | | | | | |
/_/ \_\__,_|\___/|_| |_|_|___/ /_/ \_\__,_|_| |_| |_|_|_| |_|
______ _ ____ __ __
/ ____/___ (_) __ / _/___ _________ _________ ____ _________ _/ /____ ____/ /
/ __/ / __ \/ / |/_/ / // __ \/ ___/ __ \/ ___/ __ \/ __ \/ ___/ __ `/ __/ _ \/ __ /
/ /___/ /_/ / /> < _/ // / / / /__/ /_/ / / / /_/ / /_/ / / / /_/ / /_/ __/ /_/ /
/_____/ .___/_/_/|_| /___/_/ /_/\___/\____/_/ / .___/\____/_/ \__,_/\__/\___/\__,_/
/_/ /_/
-----------------------
-- Adonis MainModule --
-----------------------
Distributed under the MIT license.
Please do not redistribute without proper credits.
--]]
return require(script.Server.Server)
| 356 |
notpoiu/cobalt | notpoiu-cobalt-bccb06a/.lune/fs.luau | local DateTime = require("./datetime")
type DateTime = DateTime.DateTime
export type MetadataKind = "file" | "dir" | "symlink"
--[=[
@interface MetadataPermissions
@within FS
Permissions for the given file or directory.
This is a dictionary that will contain the following values:
* `readOnly` - If the target path is read-only or not
]=]
export type MetadataPermissions = {
readOnly: boolean,
}
-- FIXME: We lose doc comments here below in Metadata because of the union type
--[=[
@interface Metadata
@within FS
Metadata for the given file or directory.
This is a dictionary that will contain the following values:
* `kind` - If the target path is a `file`, `dir` or `symlink`
* `exists` - If the target path exists
* `createdAt` - The timestamp represented as a `DateTime` object at which the file or directory was created
* `modifiedAt` - The timestamp represented as a `DateTime` object at which the file or directory was last modified
* `accessedAt` - The timestamp represented as a `DateTime` object at which the file or directory was last accessed
* `permissions` - Current permissions for the file or directory
Note that timestamps are relative to the unix epoch, and
may not be accurate if the system clock is not accurate.
]=]
export type Metadata = {
kind: MetadataKind,
exists: true,
createdAt: DateTime,
modifiedAt: DateTime,
accessedAt: DateTime,
permissions: MetadataPermissions,
} | {
kind: nil,
exists: false,
createdAt: nil,
modifiedAt: nil,
accessedAt: nil,
permissions: nil,
}
--[=[
@interface WriteOptions
@within FS
Options for filesystem APIs what write to files and/or directories.
This is a dictionary that may contain one or more of the following values:
* `overwrite` - If the target path should be overwritten or not, in the case that it already exists
]=]
export type WriteOptions = {
overwrite: boolean?,
}
--[=[
@class FS
Built-in library for filesystem access
### Example usage
```lua
local fs = require("@lune/fs")
-- Reading a file
local myTextFile: string = fs.readFile("myFileName.txt")
-- Reading entries (files & dirs) in a directory
for _, entryName in fs.readDir("myDirName") do
if fs.isFile("myDirName/" .. entryName) then
print("Found file " .. entryName)
elseif fs.isDir("myDirName/" .. entryName) then
print("Found subdirectory " .. entryName)
end
end
```
]=]
local fs = {}
--[=[
@within FS
@tag must_use
Reads a file at `path`.
An error will be thrown in the following situations:
* `path` does not point to an existing file.
* The current process lacks permissions to read the file.
* Some other I/O error occurred.
@param path The path to the file to read
@return The contents of the file
]=]
function fs.readFile(path: string): string
return nil :: any
end
--[=[
@within FS
@tag must_use
Reads entries in a directory at `path`.
An error will be thrown in the following situations:
* `path` does not point to an existing directory.
* The current process lacks permissions to read the contents of the directory.
* Some other I/O error occurred.
@param path The directory path to search in
@return A list of files & directories found
]=]
function fs.readDir(path: string): { string }
return {}
end
--[=[
@within FS
Writes to a file at `path`.
An error will be thrown in the following situations:
* The file's parent directory does not exist.
* The current process lacks permissions to write to the file.
* Some other I/O error occurred.
@param path The path of the file
@param contents The contents of the file
]=]
function fs.writeFile(path: string, contents: buffer | string) end
--[=[
@within FS
Creates a directory and its parent directories if they are missing.
An error will be thrown in the following situations:
* `path` already points to an existing file or directory.
* The current process lacks permissions to create the directory or its missing parents.
* Some other I/O error occurred.
@param path The directory to create
]=]
function fs.writeDir(path: string) end
--[=[
@within FS
Removes a file.
An error will be thrown in the following situations:
* `path` does not point to an existing file.
* The current process lacks permissions to remove the file.
* Some other I/O error occurred.
@param path The file to remove
]=]
function fs.removeFile(path: string) end
--[=[
@within FS
Removes a directory and all of its contents.
An error will be thrown in the following situations:
* `path` is not an existing and empty directory.
* The current process lacks permissions to remove the directory.
* Some other I/O error occurred.
@param path The directory to remove
]=]
function fs.removeDir(path: string) end
--[=[
@within FS
@tag must_use
Gets metadata for the given path.
An error will be thrown in the following situations:
* The current process lacks permissions to read at `path`.
* Some other I/O error occurred.
@param path The path to get metadata for
@return Metadata for the path
]=]
function fs.metadata(path: string): Metadata
return nil :: any
end
--[=[
@within FS
@tag must_use
Checks if a given path is a file.
An error will be thrown in the following situations:
* The current process lacks permissions to read at `path`.
* Some other I/O error occurred.
@param path The file path to check
@return If the path is a file or not
]=]
function fs.isFile(path: string): boolean
return nil :: any
end
--[=[
@within FS
@tag must_use
Checks if a given path is a directory.
An error will be thrown in the following situations:
* The current process lacks permissions to read at `path`.
* Some other I/O error occurred.
@param path The directory path to check
@return If the path is a directory or not
]=]
function fs.isDir(path: string): boolean
return nil :: any
end
--[=[
@within FS
Moves a file or directory to a new path.
Throws an error if a file or directory already exists at the target path.
This can be bypassed by passing `true` as the third argument, or a dictionary of options.
Refer to the documentation for `WriteOptions` for specific option keys and their values.
An error will be thrown in the following situations:
* The current process lacks permissions to read at `from` or write at `to`.
* The new path exists on a different mount point.
* Some other I/O error occurred.
@param from The path to move from
@param to The path to move to
@param overwriteOrOptions Options for the target path, such as if should be overwritten if it already exists
]=]
function fs.move(from: string, to: string, overwriteOrOptions: (boolean | WriteOptions)?) end
--[=[
@within FS
Copies a file or directory recursively to a new path.
Throws an error if a file or directory already exists at the target path.
This can be bypassed by passing `true` as the third argument, or a dictionary of options.
Refer to the documentation for `WriteOptions` for specific option keys and their values.
An error will be thrown in the following situations:
* The current process lacks permissions to read at `from` or write at `to`.
* Some other I/O error occurred.
@param from The path to copy from
@param to The path to copy to
@param overwriteOrOptions Options for the target path, such as if should be overwritten if it already exists
]=]
function fs.copy(from: string, to: string, overwriteOrOptions: (boolean | WriteOptions)?) end
return fs
| 1,803 |
notpoiu/cobalt | notpoiu-cobalt-bccb06a/.lune/regex.luau | --[=[
@class RegexMatch
A match from a regular expression.
Contains the following values:
- `start` -- The start index of the match in the original string.
- `finish` -- The end index of the match in the original string.
- `text` -- The text that was matched.
- `len` -- The length of the text that was matched.
]=]
local RegexMatch = {
start = 0,
finish = 0,
text = "",
len = 0,
}
type RegexMatch = typeof(RegexMatch)
--[=[
@class RegexCaptures
Captures from a regular expression.
]=]
local RegexCaptures = {}
--[=[
@within RegexCaptures
@tag Method
Returns the match at the given index, if one exists.
@param index -- The index of the match to get
@return RegexMatch -- The match, if one exists
]=]
function RegexCaptures.get(self: RegexCaptures, index: number): RegexMatch?
return nil :: any
end
--[=[
@within RegexCaptures
@tag Method
Returns the match for the given named match group, if one exists.
@param group -- The name of the group to get
@return RegexMatch -- The match, if one exists
]=]
function RegexCaptures.group(self: RegexCaptures, group: string): RegexMatch?
return nil :: any
end
--[=[
@within RegexCaptures
@tag Method
Formats the captures using the given format string.
### Example usage
```lua
local regex = require("@lune/regex")
local re = regex.new("(?<day>[0-9]{2})-(?<month>[0-9]{2})-(?<year>[0-9]{4})")
local caps = re:captures("On 14-03-2010, I became a Tenneessee lamb.");
assert(caps ~= nil, "Example pattern should match example text")
local formatted = caps:format("year=$year, month=$month, day=$day")
print(formatted) -- "year=2010, month=03, day=14"
```
@param format -- The format string to use
@return string -- The formatted string
]=]
function RegexCaptures.format(self: RegexCaptures, format: string): string
return nil :: any
end
export type RegexCaptures = typeof(RegexCaptures)
local Regex = {}
--[=[
@within Regex
@tag Method
Check if the given text matches the regular expression.
This method may be slightly more efficient than calling `find`
if you only need to know if the text matches the pattern.
@param text -- The text to search
@return boolean -- Whether the text matches the pattern
]=]
function Regex.isMatch(self: Regex, text: string): boolean
return nil :: any
end
--[=[
@within Regex
@tag Method
Finds the first match in the given text.
Returns `nil` if no match was found.
@param text -- The text to search
@return RegexMatch? -- The match object
]=]
function Regex.find(self: Regex, text: string): RegexMatch?
return nil :: any
end
--[=[
@within Regex
@tag Method
Finds all matches in the given text as a `RegexCaptures` object.
Returns `nil` if no matches are found.
@param text -- The text to search
@return RegexCaptures? -- The captures object
]=]
function Regex.captures(self: Regex, text: string): RegexCaptures?
return nil :: any
end
--[=[
@within Regex
@tag Method
Splits the given text using the regular expression.
@param text -- The text to split
@return { string } -- The split text
]=]
function Regex.split(self: Regex, text: string): { string }
return nil :: any
end
--[=[
@within Regex
@tag Method
Replaces the first match in the given text with the given replacer string.
@param haystack -- The text to search
@param replacer -- The string to replace matches with
@return string -- The text with the first match replaced
]=]
function Regex.replace(self: Regex, haystack: string, replacer: string): string
return nil :: any
end
--[=[
@within Regex
@tag Method
Replaces all matches in the given text with the given replacer string.
@param haystack -- The text to search
@param replacer -- The string to replace matches with
@return string -- The text with all matches replaced
]=]
function Regex.replaceAll(self: Regex, haystack: string, replacer: string): string
return nil :: any
end
export type Regex = typeof(Regex)
--[=[
@class Regex
Built-in library for regular expressions
### Example usage
```lua
local Regex = require("@lune/regex")
local re = Regex.new("hello")
if re:isMatch("hello, world!") then
print("Matched!")
end
local caps = re:captures("hello, world! hello, again!")
print(#caps) -- 2
print(caps:get(1)) -- "hello"
print(caps:get(2)) -- "hello"
print(caps:get(3)) -- nil
```
]=]
local regex = {}
--[=[
@within Regex
@tag Constructor
Creates a new `Regex` from a given string pattern.
### Errors
This constructor throws an error if the given pattern is invalid.
@param pattern -- The string pattern to use
@return Regex -- The new Regex object
]=]
function regex.new(pattern: string): Regex
return nil :: any
end
return regex
| 1,219 |
notpoiu/cobalt | notpoiu-cobalt-bccb06a/.lune/task.luau | --[=[
@class Task
Built-in task scheduler & thread spawning
### Example usage
```lua
local task = require("@lune/task")
-- Waiting for a certain amount of time
task.wait(1)
print("Waited for one second")
-- Running a task after a given amount of time
task.delay(2, function()
print("Ran after two seconds")
end)
-- Spawning a new task that runs concurrently
task.spawn(function()
print("Running instantly")
task.wait(1)
print("One second passed inside the task")
end)
print("Running after task.spawn yields")
```
]=]
local task = {}
--[=[
@within Task
Stops a currently scheduled thread from resuming.
@param thread The thread to cancel
]=]
function task.cancel(thread: thread) end
--[=[
@within Task
Defers a thread or function to run at the end of the current task queue.
@param functionOrThread The function or thread to defer
@return The thread that will be deferred
]=]
function task.defer<T...>(functionOrThread: thread | (T...) -> ...any, ...: T...): thread
return nil :: any
end
--[=[
@within Task
Delays a thread or function to run after `duration` seconds.
@param functionOrThread The function or thread to delay
@return The thread that will be delayed
]=]
function task.delay<T...>(
duration: number,
functionOrThread: thread | (T...) -> ...any,
...: T...
): thread
return nil :: any
end
--[=[
@within Task
Instantly runs a thread or function.
If the spawned task yields, the thread that spawned the task
will resume, letting the spawned task run in the background.
@param functionOrThread The function or thread to spawn
@return The thread that was spawned
]=]
function task.spawn<T...>(functionOrThread: thread | (T...) -> ...any, ...: T...): thread
return nil :: any
end
--[=[
@within Task
Waits for *at least* the given amount of time.
The minimum wait time possible when using `task.wait` is limited by the underlying OS sleep implementation.
For most systems this means `task.wait` is accurate down to about 5 milliseconds or less.
@param duration The amount of time to wait
@return The exact amount of time waited
]=]
function task.wait(duration: number?): number
return nil :: any
end
return task
| 541 |
notpoiu/cobalt | notpoiu-cobalt-bccb06a/Build/Lib/BundleModel.luau | -- MIT License | Copyright (c) 2023-2024 Latte Softworks <https://latte.to>
local luau = require("@lune/luau")
local roblox = require("@lune/roblox")
local LuneUtils = require("Libraries/LuneUtils")
local Log = LuneUtils.Log
local StringUtils = LuneUtils.StringUtils
local LuaEncode = require("Libraries/LuaEncode")
local Version = require("Data/Version")
-- Init script template for codegen (in this, we'll maintain 5.1 *syntax* compat
-- for optional compilation to vanilla Lua 5.1x bytecode format)
local InitScriptTemplate = require("Data/Template")
-- The line where the 1st closure's function will start in bundled codegen
local InitialLineOffset = 8
local ClassNameIdKeys = {
Folder = 1,
ModuleScript = 2,
Script = 3,
LocalScript = 4,
StringValue = 5,
}
-- Building codegen directly from model data (from .rbxm/.rbxmx) or a deserialized
-- object using Lune's `roblox` library
local function BundleModel(modelData: string | {roblox.Instance}, envName: string?, minifyCodegen: boolean?, extraLinesToOffset: number?, verbose: boolean?): (string, number)
local EnvName = envName or "WaxRuntime"
local MinifyCodegen = if minifyCodegen == nil then true else minifyCodegen
local ExtraLinesToOffset = extraLinesToOffset or 0
local Verbose = if verbose == nil then true else verbose
-- Same as in Wax CLI
local function RunIfVerbose(f, ...)
if Verbose then
f(...)
end
end
local LineDebugging = MinifyCodegen == false
local ModelRoot = if type(modelData) == "string" then
roblox.deserializeModel(modelData)
else modelData
-- We'll track how long it takes for us to read the entire object tree, with all
-- other various processes included
local ReadStartTime = os.clock()
local FailedCompilations = 0
-- We'll initialize the output object tree, then walk through what we need to
local ObjectTree = {}
local ClosureBindings = {} -- [RefId] = Closure
local ClosureSourceLineCounts = {} -- [RefId] = LineCount
local ScrapedInstanceTree = {} -- [RealRef] = {Child, ...}
local RefIds = {} -- [RefId] = RealRef
-- Recursive function to actually walk through the real instance tree, and assign refs
local function ScrapeInstanceChildren(instance)
-- Add a reference id for this instance
table.insert(RefIds, instance)
local ScrapedChildren = {}
for _, Child in instance:GetChildren() do
ScrapedChildren[Child] = ScrapeInstanceChildren(Child)
end
return ScrapedChildren
end
-- Initialize the scraped instance tree and assign all refs from root
local ModelRootChildren = ModelRoot -- Using later aswell
for _, RealInstance in ModelRootChildren do
ScrapedInstanceTree[RealInstance] = ScrapeInstanceChildren(RealInstance)
end
-- Now, we'll recursively create the fake object tree
local function CreateObjectTree(instance, children, currentPathString: string?)
currentPathString = currentPathString or instance.Name
local RefId = table.find(RefIds, instance)
local ClassName = instance.ClassName
local ClassNameId = ClassNameIdKeys[ClassName]
if not ClassNameId then
Log.Warn(`Skipping instance of ClassName "{ClassName}", as it isn't supported in bundling`)
return
end
local InstanceIsABaseScript = ClassName == "LocalScript" or ClassName == "Script"
local InstanceIsAScript = InstanceIsABaseScript or ClassName == "ModuleScript"
--[[
{
[1] = RefId,
[2] = ClassName,
[3] = Properties,
[4] = Children?
}
]]
local InstanceObject = {
[1] = RefId,
[2] = ClassNameId,
}
-- If it's statically disabled, we just won't include the closure to run
if InstanceIsAScript and not (InstanceIsABaseScript and instance.Disabled) then
local ScriptSource = instance.Source
RunIfVerbose(Log.Info, `Compile-checking {instance.ClassName} "{currentPathString}"..`)
local CompileSuccess, CompileError = pcall(luau.compile, ScriptSource)
if CompileSuccess then
-- The added line here is the "\nend" below every arbitrary closure
ClosureSourceLineCounts[RefId] = StringUtils.LineCount(ScriptSource) + 1
-- We're using `FunctionsReturnRaw` on LuaEncode later, this will set the return
-- to the rew value, which is the script closure
ClosureBindings[RefId] = function()
return "function()local wax,script,require=ImportGlobals(" .. RefId .. ")local ImportGlobals return (function(...)" .. ScriptSource .. "\nend)() end"
end
else
local FirstLineOfError = string.match(tostring(CompileError), "%w* ?:%d*: ?([^\n]*)\n")
Log.Warn(`WARNING: {instance.ClassName} "{currentPathString}" failed to compile: {FirstLineOfError or "[Failed to parse compiler error]"}`)
FailedCompilations += 1
ClosureSourceLineCounts[RefId] = 1 -- Guaranteed 1 line; see below lol
ClosureBindings[RefId] = function()
return `function()error("[AOT COMPILER ERROR] {StringUtils.SerializeStringData(FirstLineOfError)}")end`
end
end
end
-- Add any properties
local Properties = {[1] = instance.Name} -- For byte preservation (lol) the name is just set as the property index 1, and not "Name"
if ClassName == "StringValue" then
Properties.Value = instance.Value
end
-- The init script will assume the `Name` is the same as the `ClassName` if not included
if instance.Name ~= ClassName then
InstanceObject[3] = Properties
end
-- Recursively add children
if next(children) then
local ObjectChildren = {}
for Child, ChildrenOfChild in children do
local ChildObjectTree = CreateObjectTree(Child, ChildrenOfChild, `{currentPathString}.{Child.Name}`)
if ChildObjectTree then
table.insert(ObjectChildren, ChildObjectTree)
end
end
InstanceObject[4] = ObjectChildren
end
return InstanceObject
end
for RealInstance, Children in ScrapedInstanceTree do
local ChildObjectTree = CreateObjectTree(RealInstance, Children)
if ChildObjectTree then
table.insert(ObjectTree, ChildObjectTree)
end
end
local LineOffsets = {}
if LineDebugging then
-- Where the first closure func start should be
local CurrentLineOffset = ExtraLinesToOffset + InitialLineOffset
for RefId, LineCount in ClosureSourceLineCounts do
LineOffsets[RefId] = CurrentLineOffset
CurrentLineOffset += LineCount
end
end
-- Now we're done reading everything!
local ReadEndTime = os.clock()
RunIfVerbose(Log.Info, `Finished bundling model data in {string.format("%.4f", ReadEndTime - ReadStartTime)} (seconds)`)
local Prettify = if MinifyCodegen == false then true else false
local SerializedObjectTree = LuaEncode(ObjectTree, {
Prettify = Prettify,
StackLimit = math.huge,
})
local SerializedClosureBindings = LuaEncode(ClosureBindings, {
Prettify = Prettify,
FunctionsReturnRaw = true, -- For Script.Source function closures
})
local SerializedLineOffsets = if not LineDebugging then
"nil"
else
LuaEncode(LineOffsets, {
Prettify = Prettify,
})
local CodegenOutput = StringUtils.Replace(InitScriptTemplate, {
Version = StringUtils.SerializeStringData(Version),
EnvName = StringUtils.SerializeStringData(EnvName),
ObjectTree = SerializedObjectTree,
ClosureBindings = SerializedClosureBindings,
LineOffsets = SerializedLineOffsets,
})
-- If there's a top-level init modulescript, we'll return it from the output's closure directly
-- It's better to impl this all AoT!
if #ModelRootChildren == 1 and ModelRootChildren[1].ClassName == "ModuleScript" then
CodegenOutput ..= "\n-- AoT adjustment: Load init module (MainModule behavior)\nreturn LoadScript(RealObjectRoot:GetChildren()[1])"
else
for _, Ref in next, ModelRootChildren do
if Ref.ClassName == "ModuleScript" and Ref.Name == "MainModule" then
CodegenOutput ..= "\n-- AoT adjustment: Load init module (MainModule behavior)\nreturn LoadScript(RealObjectRoot.MainModule)"
break
end
end
end
return CodegenOutput, FailedCompilations
end
return BundleModel
| 2,041 |
notpoiu/cobalt | notpoiu-cobalt-bccb06a/Build/Lib/Data/DefaultDarkluaConfig.luau | local serde = require("@lune/serde")
local Config = {
generator = {
name = "dense",
column_span = 120,
},
rules = {
"convert_index_to_field",
"compute_expression",
"group_local_assignment",
"filter_after_early_return",
"remove_comments",
"remove_empty_do",
"remove_function_call_parens",
"remove_nil_declaration",
"remove_method_definition",
"remove_spaces",
"remove_unused_if_branch",
"remove_unused_while",
{
rule = "rename_variables",
include_functions = true,
},
},
}
return serde.encode("json", Config, false)
| 143 |
notpoiu/cobalt | notpoiu-cobalt-bccb06a/Build/Lib/Data/Template.luau | -- This codegen template *must* be 100% compatible with Lua 5.1x+, NOT just Luau
-- With that being said, this explains the weird cflow in some parts
return [[
-- ++++++++ WAX BUNDLED DATA BELOW ++++++++ --
-- Will be used later for getting flattened globals
local ImportGlobals
-- Holds direct closure data (defining this before the DOM tree for line debugging etc)
local ClosureBindings = ${ClosureBindings} -- [RefId] = Closure
-- Holds the actual DOM data
local ObjectTree = ${ObjectTree}
-- Line offsets for debugging (only included when minifyTables is false)
local LineOffsets = ${LineOffsets}
-- Misc AOT variable imports
local WaxVersion = "${Version}"
local EnvName = "${EnvName}"
-- ++++++++ RUNTIME IMPL BELOW ++++++++ --
-- Localizing certain libraries and built-ins for runtime efficiency
local string, task, setmetatable, error, next, table, unpack, coroutine, script, type, require, pcall, tostring, tonumber, _VERSION =
string, task, setmetatable, error, next, table, unpack, coroutine, script, type, require, pcall, tostring, tonumber, _VERSION
local table_insert = table.insert
local table_remove = table.remove
local table_freeze = table.freeze or function(t) return t end -- lol
local coroutine_wrap = coroutine.wrap
local string_sub = string.sub
local string_match = string.match
local string_gmatch = string.gmatch
-- The Lune runtime has its own `task` impl, but it must be imported by its builtin
-- module path, "@lune/task"
if _VERSION and string_sub(_VERSION, 1, 4) == "Lune" then
local RequireSuccess, LuneTaskLib = pcall(require, "@lune/task")
if RequireSuccess and LuneTaskLib then
task = LuneTaskLib
end
end
local task_defer = task and task.defer
-- If we're not running on the Roblox engine, we won't have a `task` global
local Defer = task_defer or function(f, ...)
coroutine_wrap(f)(...)
end
-- ClassName "IDs"
local ClassNameIdBindings = {
[1] = "Folder",
[2] = "ModuleScript",
[3] = "Script",
[4] = "LocalScript",
[5] = "StringValue",
}
local RefBindings = {} -- [RefId] = RealObject
local ScriptClosures = {}
local ScriptClosureRefIds = {} -- [ScriptClosure] = RefId
local StoredModuleValues = {}
local ScriptsToRun = {}
-- wax.shared __index/__newindex
local SharedEnvironment = {}
-- We're creating 'fake' instance refs soley for traversal of the DOM for require() compatibility
-- It's meant to be as lazy as possible
local RefChildren = {} -- [Ref] = {ChildrenRef, ...}
-- Implemented instance methods
local InstanceMethods = {
GetFullName = { {}, function(self)
local Path = self.Name
local ObjectPointer = self.Parent
while ObjectPointer do
Path = ObjectPointer.Name .. "." .. Path
-- Move up the DOM (parent will be nil at the end, and this while loop will stop)
ObjectPointer = ObjectPointer.Parent
end
return Path
end},
GetChildren = { {}, function(self)
local ReturnArray = {}
for Child in next, RefChildren[self] do
table_insert(ReturnArray, Child)
end
return ReturnArray
end},
GetDescendants = { {}, function(self)
local ReturnArray = {}
for Child in next, RefChildren[self] do
table_insert(ReturnArray, Child)
for _, Descendant in next, Child:GetDescendants() do
table_insert(ReturnArray, Descendant)
end
end
return ReturnArray
end},
FindFirstChild = { {"string", "boolean?"}, function(self, name, recursive)
local Children = RefChildren[self]
for Child in next, Children do
if Child.Name == name then
return Child
end
end
if recursive then
for Child in next, Children do
-- Yeah, Roblox follows this behavior- instead of searching the entire base of a
-- ref first, the engine uses a direct recursive call
return Child:FindFirstChild(name, true)
end
end
end},
FindFirstAncestor = { {"string"}, function(self, name)
local RefPointer = self.Parent
while RefPointer do
if RefPointer.Name == name then
return RefPointer
end
RefPointer = RefPointer.Parent
end
end},
-- Just to implement for traversal usage
WaitForChild = { {"string", "number?"}, function(self, name)
return self:FindFirstChild(name)
end},
}
-- "Proxies" to instance methods, with err checks etc
local InstanceMethodProxies = {}
for MethodName, MethodObject in next, InstanceMethods do
local Types = MethodObject[1]
local Method = MethodObject[2]
local EvaluatedTypeInfo = {}
for ArgIndex, TypeInfo in next, Types do
local ExpectedType, IsOptional = string_match(TypeInfo, "^([^%?]+)(%??)")
EvaluatedTypeInfo[ArgIndex] = {ExpectedType, IsOptional}
end
InstanceMethodProxies[MethodName] = function(self, ...)
if not RefChildren[self] then
error("Expected ':' not '.' calling member function " .. MethodName, 2)
end
local Args = {...}
for ArgIndex, TypeInfo in next, EvaluatedTypeInfo do
local RealArg = Args[ArgIndex]
local RealArgType = type(RealArg)
local ExpectedType, IsOptional = TypeInfo[1], TypeInfo[2]
if RealArg == nil and not IsOptional then
error("Argument " .. RealArg .. " missing or nil", 3)
end
if ExpectedType ~= "any" and RealArgType ~= ExpectedType and not (RealArgType == "nil" and IsOptional) then
error("Argument " .. ArgIndex .. " expects type \"" .. ExpectedType .. "\", got \"" .. RealArgType .. "\"", 2)
end
end
return Method(self, ...)
end
end
local function CreateRef(className, name, parent)
-- `name` and `parent` can also be set later by the init script if they're absent
-- Extras
local StringValue_Value
-- Will be set to RefChildren later aswell
local Children = setmetatable({}, {__mode = "k"})
-- Err funcs
local function InvalidMember(member)
error(member .. " is not a valid (virtual) member of " .. className .. " \"" .. name .. "\"", 3)
end
local function ReadOnlyProperty(property)
error("Unable to assign (virtual) property " .. property .. ". Property is read only", 3)
end
local Ref = {}
local RefMetatable = {}
RefMetatable.__metatable = false
RefMetatable.__index = function(_, index)
if index == "ClassName" then -- First check "properties"
return className
elseif index == "Name" then
return name
elseif index == "Parent" then
return parent
elseif className == "StringValue" and index == "Value" then
-- Supporting StringValue.Value for Rojo .txt file conv
return StringValue_Value
else -- Lastly, check "methods"
local InstanceMethod = InstanceMethodProxies[index]
if InstanceMethod then
return InstanceMethod
end
end
-- Next we'll look thru child refs
for Child in next, Children do
if Child.Name == index then
return Child
end
end
-- At this point, no member was found; this is the same err format as Roblox
InvalidMember(index)
end
RefMetatable.__newindex = function(_, index, value)
-- __newindex is only for props fyi
if index == "ClassName" then
ReadOnlyProperty(index)
elseif index == "Name" then
name = value
elseif index == "Parent" then
-- We'll just ignore the process if it's trying to set itself
if value == Ref then
return
end
if parent ~= nil then
-- Remove this ref from the CURRENT parent
RefChildren[parent][Ref] = nil
end
parent = value
if value ~= nil then
-- And NOW we're setting the new parent
RefChildren[value][Ref] = true
end
elseif className == "StringValue" and index == "Value" then
-- Supporting StringValue.Value for Rojo .txt file conv
StringValue_Value = value
else
-- Same err as __index when no member is found
InvalidMember(index)
end
end
RefMetatable.__tostring = function()
return name
end
setmetatable(Ref, RefMetatable)
RefChildren[Ref] = Children
if parent ~= nil then
RefChildren[parent][Ref] = true
end
return Ref
end
-- Create real ref DOM from object tree
local function CreateRefFromObject(object, parent)
local RefId = object[1]
local ClassNameId = object[2]
local Properties = object[3] -- Optional
local Children = object[4] -- Optional
local ClassName = ClassNameIdBindings[ClassNameId]
local Name = Properties and table_remove(Properties, 1) or ClassName
local Ref = CreateRef(ClassName, Name, parent) -- 3rd arg may be nil if this is from root
RefBindings[RefId] = Ref
if Properties then
for PropertyName, PropertyValue in next, Properties do
Ref[PropertyName] = PropertyValue
end
end
if Children then
for _, ChildObject in next, Children do
CreateRefFromObject(ChildObject, Ref)
end
end
return Ref
end
local RealObjectRoot = CreateRef("Folder", "[" .. EnvName .. "]")
for _, Object in next, ObjectTree do
CreateRefFromObject(Object, RealObjectRoot)
end
-- Now we'll set script closure refs and check if they should be ran as a BaseScript
for RefId, Closure in next, ClosureBindings do
local Ref = RefBindings[RefId]
ScriptClosures[Ref] = Closure
ScriptClosureRefIds[Ref] = RefId
local ClassName = Ref.ClassName
if ClassName == "LocalScript" or ClassName == "Script" then
table_insert(ScriptsToRun, Ref)
end
end
local function LoadScript(scriptRef)
local ScriptClassName = scriptRef.ClassName
-- First we'll check for a cached module value (packed into a tbl)
local StoredModuleValue = StoredModuleValues[scriptRef]
if StoredModuleValue and ScriptClassName == "ModuleScript" then
return unpack(StoredModuleValue)
end
local Closure = ScriptClosures[scriptRef]
local function FormatError(originalErrorMessage)
originalErrorMessage = tostring(originalErrorMessage)
local VirtualFullName = scriptRef:GetFullName()
-- Check for vanilla/Roblox format
local OriginalErrorLine, BaseErrorMessage = string_match(originalErrorMessage, "[^:]+:(%d+): (.+)")
if not OriginalErrorLine or not LineOffsets then
return VirtualFullName .. ":*: " .. (BaseErrorMessage or originalErrorMessage)
end
OriginalErrorLine = tonumber(OriginalErrorLine)
local RefId = ScriptClosureRefIds[scriptRef]
local LineOffset = LineOffsets[RefId]
local RealErrorLine = OriginalErrorLine - LineOffset + 1
if RealErrorLine < 0 then
RealErrorLine = "?"
end
return VirtualFullName .. ":" .. RealErrorLine .. ": " .. BaseErrorMessage
end
-- If it's a BaseScript, we'll just run it directly!
if ScriptClassName == "LocalScript" or ScriptClassName == "Script" then
local RunSuccess, ErrorMessage = xpcall(Closure, function(msg)
return msg
end)
if not RunSuccess then
error(FormatError(ErrorMessage), 0)
end
else
local PCallReturn = {xpcall(Closure, function(msg)
return msg
end)}
local RunSuccess = table_remove(PCallReturn, 1)
if not RunSuccess then
local ErrorMessage = table_remove(PCallReturn, 1)
error(FormatError(ErrorMessage), 0)
end
StoredModuleValues[scriptRef] = PCallReturn
return unpack(PCallReturn)
end
end
-- We'll assign the actual func from the top of this output for flattening user globals at runtime
-- Returns (in a tuple order): wax, script, require
function ImportGlobals(refId)
local ScriptRef = RefBindings[refId]
local function RealCall(f, ...)
local PCallReturn = {xpcall(f, function(msg)
return debug.traceback(msg, 2)
end, ...)}
local CallSuccess = table_remove(PCallReturn, 1)
if not CallSuccess then
error(PCallReturn[1], 3)
end
return unpack(PCallReturn)
end
-- `wax.shared` index
local WaxShared = table_freeze(setmetatable({}, {
__index = SharedEnvironment,
__newindex = function(_, index, value)
SharedEnvironment[index] = value
end,
__len = function()
return #SharedEnvironment
end,
__iter = function()
return next, SharedEnvironment
end,
}))
local Global_wax = table_freeze({
-- From AOT variable imports
version = WaxVersion,
envname = EnvName,
shared = WaxShared,
-- "Real" globals instead of the env set ones
script = script,
require = require,
})
local Global_script = ScriptRef
local function Global_require(module, ...)
local ModuleArgType = type(module)
local ErrorNonModuleScript = "Attempted to call require with a non-ModuleScript"
local ErrorSelfRequire = "Attempted to call require with self"
if ModuleArgType == "table" and RefChildren[module] then
if module.ClassName ~= "ModuleScript" then
error(ErrorNonModuleScript, 2)
elseif module == ScriptRef then
error(ErrorSelfRequire, 2)
end
return LoadScript(module)
elseif ModuleArgType == "string" and string_sub(module, 1, 1) ~= "@" then
-- The control flow on this SUCKS
if #module == 0 then
error("Attempted to call require with empty string", 2)
end
local CurrentRefPointer = ScriptRef
if string_sub(module, 1, 1) == "/" then
CurrentRefPointer = RealObjectRoot
elseif string_sub(module, 1, 2) == "./" then
module = string_sub(module, 3)
end
local PreviousPathMatch
for PathMatch in string_gmatch(module, "([^/]*)/?") do
local RealIndex = PathMatch
if PathMatch == ".." then
RealIndex = "Parent"
end
-- Don't advance dir if it's just another "/" either
if RealIndex ~= "" then
local ResultRef = CurrentRefPointer:FindFirstChild(RealIndex)
if not ResultRef then
local CurrentRefParent = CurrentRefPointer.Parent
if CurrentRefParent then
ResultRef = CurrentRefParent:FindFirstChild(RealIndex)
end
end
if ResultRef then
CurrentRefPointer = ResultRef
elseif PathMatch ~= PreviousPathMatch and PathMatch ~= "init" and PathMatch ~= "init.server" and PathMatch ~= "init.client" then
error("Virtual script path \"" .. module .. "\" not found", 2)
end
end
-- For possible checks next cycle
PreviousPathMatch = PathMatch
end
if CurrentRefPointer.ClassName ~= "ModuleScript" then
error(ErrorNonModuleScript, 2)
elseif CurrentRefPointer == ScriptRef then
error(ErrorSelfRequire, 2)
end
return LoadScript(CurrentRefPointer)
end
return RealCall(require, module, ...)
end
-- Now, return flattened globals ready for direct runtime exec
return Global_wax, Global_script, Global_require
end
for _, ScriptRef in next, ScriptsToRun do
Defer(LoadScript, ScriptRef)
end
]]
| 3,682 |
notpoiu/cobalt | notpoiu-cobalt-bccb06a/Build/Lib/Libraries/LuneUtils/CommandUtils.luau | -- MIT License | Copyright (c) 2023-2024 Latte Softworks <https://latte.to>
local process = require("@lune/process")
local CommandUtils = {}
function CommandUtils.CommandExists(binary: string): boolean
if process.os ~= "windows" then
-- Unix-compliance is simple!
return process.spawn("type", {binary}, {shell = true}).ok -- Return from status code directly
end
-- I hate Windows
return true
end
function CommandUtils.CheckCommands(requiredCommands: {string})
-- Check required commands to continue script exec
for _, Command in requiredCommands do
assert(CommandUtils.CommandExists(Command), `Required command "{Command}" no found in your PATH environment variable, is it not installed?`)
end
end
return CommandUtils
| 173 |
notpoiu/cobalt | notpoiu-cobalt-bccb06a/Build/Lib/Libraries/LuneUtils/EnsureFileTree.luau | -- MIT License | Copyright (c) 2023-2024 Latte Softworks <https://latte.to>
local fs = require("@lune/fs")
--[[
This kinda looks like a strange function, because of the format a "FileTree" accepts:
```lua
EnsureFileTree({
["test"] = {
["test.txt"] = "hi",
["test.json"] = "[\"hi again\"]",
["another-sub-dir"] = {
["bye.txt"] = "bye"
},
},
["another-test"] = {
["another-example.txt"] = "real",
},
})
```
]]
local function EnsureFileTree(fileTree: {[string]: any}, _currentPath: string?)
for FileName, Entry in fileTree do
local RealPath = if _currentPath then `{_currentPath}/{FileName}` else FileName
local EntryType = type(Entry)
if EntryType == "table" then -- This is to be a directory
if not fs.isDir(RealPath) then
fs.writeDir(RealPath)
end
-- Recursively continue creating the file tree..
EnsureFileTree(Entry, RealPath)
elseif EntryType == "string" and not fs.isFile(RealPath) then -- This is to be a file
fs.writeFile(RealPath, Entry)
end
end
end
return EnsureFileTree
| 302 |
notpoiu/cobalt | notpoiu-cobalt-bccb06a/Build/Lib/Libraries/LuneUtils/ParseArgs.luau | -- MIT License | Copyright (c) 2023-2024 Latte Softworks <https://latte.to>
type OptionsInput = {[string]: {string | number | boolean | nil}}
type OptionsOutput = {[string]: string | number | boolean | nil}
local process = require("@lune/process")
local Log = require("Log")
local function ParseArgs(args: {string}, optionsTable: OptionsInput, usageMessage: string?): OptionsOutput
local function ErrorExit()
if usageMessage then
print(`\n{usageMessage}`)
end
process.exit(1)
end
local OptionsOutput = {}
for _, Arg in args do
local Option, Value = string.match(Arg, "([%w%-_]+)=(.+)")
if not Option then
Log.Error(`Command argument given, "{Arg}" not in the proper \`option=value\` format, aborting..`)
ErrorExit()
end
local OptionDetails = optionsTable[Option]
if OptionDetails == nil then -- Then it isn't a defined arg
Log.Error(`"{Option}" isn't a valid option"`)
ErrorExit()
end
local OptionType = OptionDetails[1]
if OptionType == "boolean" then
Value = string.lower(Value)
Value = if Value == "true" then true elseif Value == "false" then false else nil
if Value == nil then
Log.Error(`"{Value}" isn't a valid boolean type; expected "true" or "false"`)
ErrorExit()
end
elseif OptionType == "number" then
Value = tonumber(Value)
if not Value then
Log.Error(`Failed to convert given input "{Value}" to a number value`)
ErrorExit()
end
end
OptionsOutput[Option] = Value
end
for Option, Details in optionsTable do
local DefaultValue = Details[2]
local IsRequired = Details[3] or false
if not OptionsOutput[Option] then
if IsRequired then
Log.Error(`Option "{Option}" required but not provided`)
ErrorExit()
end
OptionsOutput[Option] = DefaultValue
end
end
return OptionsOutput
end
return ParseArgs
| 488 |
notpoiu/cobalt | notpoiu-cobalt-bccb06a/Build/Lib/Libraries/LuneUtils/RecursiveReadDir.luau | -- MIT License | Copyright (c) 2023-2024 Latte Softworks <https://latte.to>
local fs = require("@lune/fs")
local function RecursiveReadDir(directory: string, _existingFileList: {string}?): {string}
if not string.match(directory, "[/\\]$") then
directory ..= "/"
end
local FileList = _existingFileList or {}
for _, EntryName in fs.readDir(directory) do
if fs.isFile(EntryName) then
table.insert(FileList, directory .. EntryName)
else -- Is dir
RecursiveReadDir(directory .. EntryName .. "/", FileList)
end
end
return FileList
end
return RecursiveReadDir
| 159 |
notpoiu/cobalt | notpoiu-cobalt-bccb06a/Build/Lib/Libraries/LuneUtils/Run.luau | -- MIT License | Copyright (c) 2023-2024 Latte Softworks <https://latte.to>
local process = require("@lune/process")
local Log = require("Log")
local function Run(command: string, args: {string}?, directRun: boolean?, errorHandler: (string?) -> ()?): process.SpawnResult
local Args = args or {}
local DirectRun = if directRun == nil then false else directRun
if not DirectRun then
if #Args == 0 then
Log.Info(`> {command}`)
else
Log.Info(`> {command} {table.concat(Args, " ")}`)
end
end
local Result = process.spawn(command, args, {
shell = if process.os ~= "windows" then true else nil,
stdio = if DirectRun then "default" else "inherit",
})
if not Result.ok and errorHandler then
errorHandler(`Command above failed with status code {Result.code}`)
end
return Result
end
return Run
| 222 |
notpoiu/cobalt | notpoiu-cobalt-bccb06a/Build/Lib/Libraries/LuneUtils/init.luau | -- MIT License | Copyright (c) 2023-2024 Latte Softworks <https://latte.to>
return {
Log = require("Log"),
StringUtils = require("StringUtils"),
CommandUtils = require("CommandUtils"),
WebhookQueue = require("WebhookQueue"),
Run = require("Run"),
ParseArgs = require("ParseArgs"),
EnsureFileTree = require("EnsureFileTree"),
RecursiveReadDir = require("RecursiveReadDir"),
}
| 100 |
notpoiu/cobalt | notpoiu-cobalt-bccb06a/Src/Utils/Connect.luau | wax.shared.Connections = {}
wax.shared.Connect = function(Connection)
table.insert(wax.shared.Connections, Connection)
return Connection
end
wax.shared.Disconnect = function(Connection)
Connection:Disconnect()
local Index = table.find(wax.shared.Connections, Connection)
if Index then
table.remove(wax.shared.Connections, Index)
end
return true
end
return {} | 80 |
notpoiu/cobalt | notpoiu-cobalt-bccb06a/Src/Utils/FileHelper.luau | local FileHelper = {}
FileHelper.__index = FileHelper
function FileHelper.new(basePath: string)
local self = setmetatable({
BasePath = FileHelper.NormalizePath(basePath),
}, FileHelper)
self:EnsureDirectory()
return self
end
function FileHelper:EnsureDirectory()
local paths = {}
local parts = self.BasePath:split("/")
for idx = 1, #parts do
paths[#paths + 1] = table.concat(parts, "/", 1, idx)
end
for i = 1, #paths do
local str = paths[i]
if isfolder(str) then continue end
makefolder(str)
end
end
function FileHelper:GetPath(relativePath: string)
local normalizedPath = self.NormalizePath(relativePath or "")
if self.BasePath:sub(-1) == "/" then
return self.BasePath .. normalizedPath
end
if normalizedPath == "" then
return self.BasePath
end
return self.BasePath .. "/" .. normalizedPath
end
function FileHelper.NormalizePath(path: string)
if type(path) ~= "string" then return "" end
return path:gsub("\\", "/")
end
function FileHelper:GetRelativePath(path: string)
path = self.NormalizePath(path)
local basePath = self.NormalizePath(self.BasePath)
if basePath:sub(-1) ~= "/" then
basePath = basePath .. "/"
end
local Start, End = string.find(path, basePath, 1, true)
if Start then
return string.sub(path, End + 1)
end
return path
end
function FileHelper:EnsureFile(relativePath: string, default: string)
relativePath = self.NormalizePath(relativePath or "")
if not isfile(self:GetPath(relativePath)) then
writefile(self:GetPath(relativePath), default)
end
end
function FileHelper:ReadFile(relativePath: string)
relativePath = self.NormalizePath(relativePath or "")
return readfile(self:GetPath(relativePath))
end
function FileHelper:ReadRawFile(path: string)
return readfile(path)
end
function FileHelper:WriteFile(relativePath: string, data: string)
relativePath = self.NormalizePath(relativePath or "")
writefile(self:GetPath(relativePath), data)
end
function FileHelper:DeleteFile(relativePath: string)
relativePath = self.NormalizePath(relativePath or "")
if isfile(self:GetPath(relativePath)) then
delfile(self:GetPath(relativePath))
end
end
function FileHelper:DeleteDirectory(relativePath: string)
relativePath = self.NormalizePath(relativePath or "")
if isfolder(self:GetPath(relativePath)) then
delfolder(self:GetPath(relativePath))
end
end
function FileHelper:ListFiles(relativePath: string?)
relativePath = self.NormalizePath(relativePath or "")
local files = {}
for _, file in listfiles(self:GetPath(relativePath)) do
table.insert(files, self:GetRelativePath(file))
end
return files
end
function FileHelper:GetFileName(relativePath: string)
relativePath = self.NormalizePath(relativePath or "")
return relativePath:match("[^/]+$")
end
function FileHelper:ListFileNames(relativePath: string?)
relativePath = self.NormalizePath(relativePath or "")
local names = {}
for _, file in self:ListFiles(relativePath) do
table.insert(names, self:GetFileName(file))
end
return names
end
return FileHelper | 768 |
notpoiu/cobalt | notpoiu-cobalt-bccb06a/Src/Utils/FileLog.luau | -- Logger
-- ActualMasterOogway
-- December 8, 2024
--[=[
A simple logging utility that writes messages to a file. Supports different log levels
and can be configured to overwrite or append to the log file.
Log Format: 2024-12-04T15:28:31.131Z,0.131060,MyThread,Warning [FLog::RobloxStarter] Roblox stage ReadyForFlagFetch completed
<timestamp>,<elapsed_time>,<thread_id>,<level> <message>
]=]
local Logger = {}
Logger.__index = Logger
Logger.LOG_LEVELS = {
ERROR = 1,
WARNING = 2,
INFO = 3,
DEBUG = 4,
}
local LOG_LEVEL_STRINGS = {
[Logger.LOG_LEVELS.ERROR] = "ERROR",
[Logger.LOG_LEVELS.WARNING] = "WARNING",
[Logger.LOG_LEVELS.INFO] = "INFO",
[Logger.LOG_LEVELS.DEBUG] = "DEBUG",
}
local startTime = tick()
local function createDirectoryRecursive(path)
local currentPath = ""
for part in path:gmatch("[^\\/]+") do
currentPath = currentPath .. part
if not isfolder(currentPath) then
makefolder(currentPath)
end
currentPath = currentPath .. "/"
end
end
--[=[
Generates a unique file name for the log file. The file name is based on the current
job ID, ensuring it is unique per server instance but consistent across multiple
executions within the same server.
@return string A unique file name for the log file.
]=]
function Logger:GenerateFileName()
local JobIdNumber = game.JobId:gsub("%D", "")
local timestamp = os.date("!%Y%m%d%H%M%S")
return `{self.logFileDirectory}/{JobIdNumber * 1.7 // 1.8}_{timestamp}.log`
end
--[=[
Creates a new Logger instance.
@param logFilePath string The path to the log file.
@param logLevel number The minimum log level to write to the file. Defaults to INFO.
@param overwrite boolean Whether to overwrite the log file or append to it. Defaults to false (append).
@return Logger A new Logger instance.
]=]
function Logger.new(logFilePath: string, logLevel: number?, overwrite: boolean?)
local self = setmetatable({}, Logger)
self.logFilePath = logFilePath
self.logFileDirectory = logFilePath:match("(.+)/")
self.logLevel = logLevel or Logger.LOG_LEVELS.INFO
self.overwrite = overwrite or false
local folderPath, fileName = logFilePath:match("(.*[\\/])(.*)")
if folderPath and not isfolder(folderPath) then
createDirectoryRecursive(folderPath)
end
if self.overwrite then
local success, err = pcall(writefile, self.logFilePath, "")
if not success then
warn(debug.traceback(`Failed to clear log file: {self.logFilePath} - {err}`, 2))
end
end
self:Info("Logger", "Logger initialized")
return self
end
--[=[
Logs a message to the file.
@param level number The log level of the message.
@param threadId string The ID of the thread or source of the log message.
@param message string The message to log.
]=]
function Logger:Log(level: number, threadId: string, message: string)
if level <= self.logLevel then
local levelStr = LOG_LEVEL_STRINGS[level]
local timestamp = `{os.date("!%Y-%m-%dT%H:%M:%S")}{("%.3f"):format(tick() % 1)}Z`
local elapsedTime = ("%.6f"):format(tick() - startTime)
local logMessage = `{timestamp},{elapsedTime},{threadId},{levelStr} {message}\n`
local success, err = pcall(appendfile, self.logFilePath, logMessage)
if not success then
warn(debug.traceback(`Failed to write to log file: {self.logFilePath} - {err}`, 2))
end
end
end
--[=[
Logs a debug message.
@param threadId string The ID of the thread or source of the log message.
@param message string The message to log.
]=]
function Logger:Debug(threadId: string, message: string)
self:Log(Logger.LOG_LEVELS.DEBUG, threadId, message)
end
--[=[
Logs an info message.
@param threadId string The ID of the thread or source of the log message.
@param message string The message to log.
]=]
function Logger:Info(threadId: string, message: string)
self:Log(Logger.LOG_LEVELS.INFO, threadId, message)
end
--[=[
Logs a warning message.
@param threadId string The ID of the thread or source of the log message.
@param message string The message to log.
]=]
function Logger:Warning(threadId: string, message: string)
self:Log(Logger.LOG_LEVELS.WARNING, threadId, message)
end
--[=[
Logs an error message.
@param threadId string The ID of the thread or source of the log message.
@param message string The message to log.
]=]
function Logger:Error(threadId: string, message: string)
self:Log(Logger.LOG_LEVELS.ERROR, threadId, message)
end
return Logger | 1,148 |
notpoiu/cobalt | notpoiu-cobalt-bccb06a/Src/Utils/Pagination.luau | --[[
Pagination Module
made by deivid and turned into module by upio
]]
local Pagination = {}
Pagination.__index = Pagination
function Pagination.new(Options: {
TotalItems: number,
ItemsPerPage: number,
CurrentPage: number?,
SiblingCount: number?,
})
return setmetatable({
TotalItems = Options.TotalItems,
ItemsPerPage = Options.ItemsPerPage,
CurrentPage = Options.CurrentPage or 1,
SiblingCount = Options.SiblingCount or 2,
}, Pagination)
end
function Pagination:GetInfo()
local TotalPages = math.ceil(self.TotalItems / self.ItemsPerPage)
return {
TotalItems = self.TotalItems,
ItemsPerPage = self.ItemsPerPage,
CurrentPage = self.CurrentPage,
TotalPages = TotalPages,
}
end
function Pagination:SetItemsPerPage(max: number)
self.ItemsPerPage = max
end
function Pagination:GetIndexRanges(Page: number?)
Page = Page or self.CurrentPage
local TotalPages = math.ceil(self.TotalItems / self.ItemsPerPage)
if TotalPages == 0 then
return 1, 0
end
assert(
Page <= TotalPages,
"Attempted to get invalid page out of range, got " .. Page .. " but max is " .. TotalPages
)
local Start = (((Page or self.CurrentPage) - 1) * self.ItemsPerPage) + 1
local End = Start + (self.ItemsPerPage - 1)
return Start, End
end
function Pagination:SetPage(Page: number)
local TotalPages = math.ceil(self.TotalItems / self.ItemsPerPage)
if TotalPages == 0 then
self.CurrentPage = 1
return
end
assert(Page <= TotalPages, "Attempted to set page out of range, got " .. Page .. " but max is " .. TotalPages)
self.CurrentPage = Page
end
function Pagination:Update(TotalItems: number?, ItemsPerPage: number?)
self.TotalItems = TotalItems or self.TotalItems
self.ItemsPerPage = ItemsPerPage or self.ItemsPerPage
end
function Pagination:GetVisualInfo(Page: number?)
Page = Page or self.CurrentPage
local TotalPages = math.ceil(self.TotalItems / self.ItemsPerPage)
if TotalPages == 0 then
return {}
end
assert(
Page <= TotalPages,
"Attempted to get invalid page out of range, got " .. Page .. " but max is " .. TotalPages
)
local MaxButtons = 5 + self.SiblingCount * 2
local Result = table.create(MaxButtons, "none")
if TotalPages <= MaxButtons then
for i = 1, TotalPages do
Result[i] = i
end
return Result
end
local LeftSibling = math.max(Page - self.SiblingCount, 1)
local RightSibling = math.min(Page + self.SiblingCount, TotalPages)
local FakeLeft = LeftSibling > 2
local FakeRight = RightSibling < TotalPages - 1
local TotalPageNumbers = math.min(2 * self.SiblingCount + 5, TotalPages)
local ItemCount = TotalPageNumbers - 2
if not FakeLeft and FakeRight then
for i = 1, ItemCount do
Result[i] = i
end
Result[ItemCount + 1] = "ellipsis"
Result[ItemCount + 2] = TotalPages
--return MergeTables(LeftRange, "ellipsis", TotalPages)
return Result
elseif FakeLeft and not FakeRight then
--local RightRange = CreateArray(TotalPages - ItemCount + 1, TotalPages)
Result[1] = 1
Result[2] = "ellipsis"
local Index = 3
for i = TotalPages - ItemCount + 1, TotalPages do
Result[Index] = i
Index += 1
end
return Result
elseif FakeLeft and FakeRight then
--local MiddleRange = CreateArray(LeftSibling, RightSibling)
Result[1] = 1
Result[2] = "ellipsis"
local Index = 3
for i = LeftSibling, RightSibling do
Result[Index] = i
Index += 1
end
Result[Index] = "ellipsis"
Result[Index + 1] = TotalPages
return Result
--return MergeTables(1, "ellipsis", MiddleRange, "ellipsis", TotalPages)
end
--return CreateArray(1, TotalPages)
for i = 1, TotalPages do
Result[i] = i
end
return Result
end
return Pagination
| 997 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.