content
stringlengths 5
1.05M
|
---|
--[[---------------------------------------------------------
Fonts: Font
-----------------------------------------------------------]]
fontsTable = {
{
file = 'Segoe UI Semibold',
name = 'segoe_semibold',
weight = 400,
from = 0,
to = 5
},
{
file = 'Segoe UI',
name = 'segoe_bold',
weight = 700,
from = 4,
to = 10
}
}
--[[---------------------------------------------------------
Fonts: Create
-----------------------------------------------------------]]
for k,v in pairs(fontsTable) do
for i = v.from, v.to do
--> Size
local fontSize = 14+i*2
--> Font
surface.CreateFont(v.name.."_"..fontSize, {
font = v.file,
size = fontSize,
weight = v.weight,
blursize = 0,
scanlines = 0,
antialias = true,
underline = false,
italic = false,
strikeout = false,
symbol = false,
rotary = false,
shadow = false,
additive = false,
outline = false
})
end
end |
kkorrwrot = Creature:new {
customName = "Kkorrwrot",
socialGroup = "kkorrwrot",
faction = "",
level = 187,
chanceHit = 0.9,
damageMin = 860,
damageMax = 1650,
baseXp = 12500,
baseHAM = 125000,
baseHAMmax = 185000,
armor = 2,
resists = {0,0,0,0,0,0,0,-1,-1},
meatType = "",
meatAmount = 0,
hideType = "",
hideAmount = 0,
boneType = "",
boneAmount = 0,
milkType = "",
milk = 0,
tamingChance = 0.25,
ferocity = 0,
pvpBitmask = ATTACKABLE,
creatureBitmask = HERD,
optionsBitmask = AIENABLED,
diet = HERBIVORE,
templates = {"object/mobile/kkorrwrot.iff"},
lootGroups = {},
weapons = {},
attacks = {
}
}
CreatureTemplates:addCreatureTemplate(kkorrwrot, "kkorrwrot")
|
harmonia = rawget(_G, "harmonia") or {}
harmonia.passive = harmonia.passive or {}
local DATA_DOMAIN = "harmonia_passive"
local passive_system = harmonia_passive.PassiveSystem:new(DATA_DOMAIN)
minetest.register_on_mods_loaded(passive_system:method("init"))
minetest.register_on_shutdown(passive_system:method("terminate"))
nokore.player_service:register_update(
"harmonia_passive:update_players",
passive_system:method("update_players")
)
nokore.player_data_service:register_domain(DATA_DOMAIN, {
save_method = "marshall"
})
harmonia.passive.system = passive_system
|
local jid_bare = require "util.jid".bare;
local um_get_roles = require "core.usermanager".get_roles;
local function load_main_host(module)
-- Check whether a user should be isolated from remote JIDs
-- If not, set a session flag that allows them to bypass mod_isolate_host
local function check_user_isolated(event)
local session = event.session;
if not session.no_host_isolation then
local bare_jid = jid_bare(session.full_jid);
local roles = um_get_roles(bare_jid, module.host);
if roles == false then return; end
if not roles or not roles["prosody:restricted"] then
-- Bypass isolation for all unrestricted users
session.no_host_isolation = true;
end
end
end
-- Add low-priority hook to run after the check_user_isolated default
-- behaviour in mod_isolate_host
module:hook("resource-bind", check_user_isolated, -0.5);
end
local function load_groups_host(module)
local primary_host = module.host:gsub("^%a+%.", "");
local function is_restricted(user_jid)
local roles = um_get_roles(user_jid, primary_host);
return not roles or roles["prosody:restricted"];
end
module:hook("muc-config-submitted/muc#roomconfig_publicroom", function (event)
if not is_restricted(event.actor) then return; end
-- Don't allow modification of this value by restricted users
return true;
end, 5);
module:hook("muc-config-form", function (event)
if not is_restricted(event.actor) then return; end -- Don't restrict admins
-- Hide the option from the config form for restricted users
local form = event.form;
for i = #form, 1, -1 do
if form[i].name == "muc#roomconfig_publicroom" then
table.remove(form, i);
end
end
end);
end
if module:get_host_type() == "component" and module:get_option_string("component_module") == "muc" then
load_groups_host(module);
else
load_main_host(module);
end
|
-- data.lua
require("item")
require("housing")
require("food")
require("consumer-product")
|
-- !!!!!!!!!!!!!!!!!!!!!!! WARNING !!!!!!!!!!!!!!!!!!!!!!!
-- This file is automaticly generated. Don't edit manualy!
-- !!!!!!!!!!!!!!!!!!!!!!! WARNING !!!!!!!!!!!!!!!!!!!!!!!
---[Wowpedia documentation](https://wow.gamepedia.com/API_CanUpgradeExpansion)
---@return boolean @canUpgradeExpansion
function CanUpgradeExpansion()
end
---[Wowpedia documentation](https://wow.gamepedia.com/API_DoesCurrentLocaleSellExpansionLevels)
---@return boolean @regionSellsExpansions
function DoesCurrentLocaleSellExpansionLevels()
end
---[Wowpedia documentation](https://wow.gamepedia.com/API_GetAccountExpansionLevel)
---@return number @expansionLevel
function GetAccountExpansionLevel()
end
---[Wowpedia documentation](https://wow.gamepedia.com/API_GetClientDisplayExpansionLevel)
---@return number @expansionLevel
function GetClientDisplayExpansionLevel()
end
---[Wowpedia documentation](https://wow.gamepedia.com/API_GetCurrentRegionName)
---@return string @regionName
function GetCurrentRegionName()
end
---[Wowpedia documentation](https://wow.gamepedia.com/API_GetExpansionDisplayInfo)
---@param expansionLevel number
---@return ExpansionDisplayInfo @info
function GetExpansionDisplayInfo(expansionLevel)
end
---[Wowpedia documentation](https://wow.gamepedia.com/API_GetExpansionForLevel)
---@param playerLevel number
---@return number @expansionLevel
function GetExpansionForLevel(playerLevel)
end
---[Wowpedia documentation](https://wow.gamepedia.com/API_GetExpansionLevel)
---@return number @expansionLevel
function GetExpansionLevel()
end
---[Wowpedia documentation](https://wow.gamepedia.com/API_GetExpansionTrialInfo)
---@return boolean, number @isExpansionTrialAccount, expansionTrialRemainingSeconds
function GetExpansionTrialInfo()
end
---[Wowpedia documentation](https://wow.gamepedia.com/API_GetMaxLevelForExpansionLevel)
---@param expansionLevel number
---@return number @maxLevel
function GetMaxLevelForExpansionLevel(expansionLevel)
end
---[Wowpedia documentation](https://wow.gamepedia.com/API_GetMaxLevelForLatestExpansion)
---@return number @maxLevel
function GetMaxLevelForLatestExpansion()
end
---[Wowpedia documentation](https://wow.gamepedia.com/API_GetMaxLevelForPlayerExpansion)
---@return number @maxLevel
function GetMaxLevelForPlayerExpansion()
end
---[Wowpedia documentation](https://wow.gamepedia.com/API_GetMaximumExpansionLevel)
---@return number @expansionLevel
function GetMaximumExpansionLevel()
end
---[Wowpedia documentation](https://wow.gamepedia.com/API_GetMinimumExpansionLevel)
---@return number @expansionLevel
function GetMinimumExpansionLevel()
end
---[Wowpedia documentation](https://wow.gamepedia.com/API_GetNumExpansions)
---@return number @numExpansions
function GetNumExpansions()
end
---[Wowpedia documentation](https://wow.gamepedia.com/API_GetServerExpansionLevel)
---@return number @serverExpansionLevel
function GetServerExpansionLevel()
end
---[Wowpedia documentation](https://wow.gamepedia.com/API_IsExpansionTrial)
---@return boolean @isExpansionTrialAccount
function IsExpansionTrial()
end
---[Wowpedia documentation](https://wow.gamepedia.com/API_IsTrialAccount)
---@return boolean @isTrialAccount
function IsTrialAccount()
end
---[Wowpedia documentation](https://wow.gamepedia.com/API_IsVeteranTrialAccount)
---@return boolean @isVeteranTrialAccount
function IsVeteranTrialAccount()
end
---[Wowpedia documentation](https://wow.gamepedia.com/API_SendSubscriptionInterstitialResponse)
---@param response SubscriptionInterstitialResponseType
function SendSubscriptionInterstitialResponse(response)
end
---@alias SubscriptionInterstitialResponseType number|"Enum.SubscriptionInterstitialResponseType.Clicked"|"Enum.SubscriptionInterstitialResponseType.Closed"|"Enum.SubscriptionInterstitialResponseType.WebRedirect"
---@alias SubscriptionInterstitialType number|"Enum.SubscriptionInterstitialType.Standard"|"Enum.SubscriptionInterstitialType.LeftNpeArea"|"Enum.SubscriptionInterstitialType.MaxLevel"
---@class ExpansionDisplayInfo
---@field public logo number
---@field public banner string
---@field public features table
ExpansionDisplayInfo = {}
---@class ExpansionDisplayInfoFeature
---@field public icon number
---@field public text string
ExpansionDisplayInfoFeature = {}
|
-------------------------------------------------------------------
-- This script is created by zdroid9770; please do not edit this --
-- script and claim it as your own, as of All rights are claimed --
-- by me. --
-- Copyright (c) zdroid9770 --
-------------------------------------------------------------------
--[[
----Quotes
----Spells-ID
Enrage-15061
Flurry-17687
Sunder Armor-15572
]]--
function GAF_OnCombat(pUnit, Event)
pUnit:RegisterEvent("GAF_Enrage", 25000, 0)
pUnit:RegisterEvent("GAF_Flurry", 5000, 0)
pUnit:RegisterEvent("GAF_SunderArmor", 20000, 0)
end
function GAF_Enrage(pUnit, Event)
if (pUnit:GetHealthPct() >= 30) then
pUnit:SpawnCreature(8894, pUnit:GetX(), pUnit:GetY(),pUnit:GetZ(), pUnit:GetO(), 14, 300000)
pUnit:SpawnCreature(8894, pUnit:GetX(), pUnit:GetY(),pUnit:GetZ(), pUnit:GetO(), 14, 300000)
pUnit:FullCastSpell(15061)
end
end
function GAF_Flurry(pUnit, Event)
pUnit:FullCastSpell(17687)
end
function GAF_SunderArmor(pUnit, Event)
pUnit:FullCastSpellOnTarget(15572)
end
function GAF_OnLeaveCombat(pUnit, Event)
pUnit:RemoveEvents()
end
function GAF_OnDeath(pUnit, Event)
pUnit:RemoveEvents()
end
RegisterUnitEvent(9033, 1, "GAF_OnCombat")
RegisterUnitEvent(9033, 2, "GAF_OnLeaveCombat")
RegisterUnitEvent(9033, 4, "GAF_OnDeath") |
local Virovirokun, super = Class("virovirokun", true)
function Virovirokun:init()
super:init(self)
if Game:getPartyMember("susie"):getFlag("auto_attack") then
self:registerAct("Warning")
end
self.susie_warned = false
self.asleep = false
self.become_red = false
self:registerAct("Tell Story", "", {"ralsei"})
self:registerAct("Red", "", {"susie"})
end
function Virovirokun:getSpareText(battler, success)
local result = super:getSpareText(self, battler, success)
if not success then
if type(result) ~= "table" then
result = {result}
end
result[1] = "* " .. battler.chara:getName() .. " spared " .. self.name .. "!\n* But its name wasn't [color:green]GREEN[color:reset]..."
end
return result
end
function Virovirokun:mercyFlash(color)
super:mercyFlash(self, color or {0, 1, 0})
end
function Virovirokun:getNameColors()
local result = {}
if self.become_red then
table.insert(result, {1, 0, 0})
end
if self:canSpare() then
table.insert(result, {0, 1, 0})
end
if self.tired then
table.insert(result, {0, 0.7, 1})
end
return result
end
function Virovirokun:onAct(battler, name)
self.acted_once = true
if name == "Warning" then
self.susie_warned = true
self.comment = "(Warned)"
return "* You told Virovirokun to watch out for Susie's attacks.[wait:5]\n* It went on guard."
elseif name == "Tell Story" then
for _,v in ipairs(Game.battle.enemies) do
v.asleep = true
v:setTired(true)
v.comment = "(Sleepy)"
v:setScale(4, 2)
v.text_override = "Zzz..."
end
self:addMercy(100)
local susie = Game.battle:getPartyBattler("susie")
if susie then
susie:setSleeping(true)
end
return "* Ralsei tells Virovirokun a story.[wait:5]\n* The enemies fell asleep![wait:5]\n* Susie fell asleep too!"
elseif name == "Red" then
self.become_red = true
self:setColor(1, 0, 0)
return "* You and Susie turned Virovirokun red."
else
return super:onAct(self, battler, name)
end
end
function Virovirokun:getAttackDamage(damage, battler)
if self.susie_warned and battler.chara.id == "susie" then
return 0
else
return super:getAttackDamage(self, damage, battler)
end
end
function Virovirokun:getNextWaves()
if self.asleep then
return nil
end
return super:getNextWaves(self)
end
return Virovirokun |
--[[
SF LPeg library by Mijyuoon.
]]
--- LPeg library, allows for advanced pattern matching.
-- @shared
local lpeg_lib, _ = SF.Libraries.Register("lpeg")
local patt_mt = debug.getmetatable(lpeg.P(true))
local lp_methods, lp_meta = SF.Typedef("Pattern")
local wrap, unwrap = SF.CreateWrapper(lp_meta, true, false, patt_mt)
local op_types = {
["number"] = true, ["string"] = true,
["boolean"] = true, ["Pattern"] = true
}
local function getpatt(patt)
local vtype = SF.GetType(patt)
if not op_types[vtype] then
return nil
end
return unwrap(patt) or patt
end
local p_types = {
["number"] = true, ["string"] = true,
["boolean"] = true, ["table"] = true,
["function"] = true, ["Pattern"] = true
}
function lpeg_lib.P(patt)
local vtype = SF.GetType(patt)
if not p_types[vtype] then
SF.throw("Bad argument to pattern constructor",2)
end
if vtype == "table" then
patt = adv.TblMapN(patt, unwrap)
else
patt = unwrap(patt) or patt
end
return wrap(lpeg.P(patt))
end
function lpeg_lib.B(patt)
SF.CheckType(patt, lp_meta)
local patt = unwrap(patt)
return wrap(lpeg.B(patt))
end
function lpeg_lib.R(...)
local range = {...}
for _, rng in ipairs(range) do
SF.CheckType(rng, "string")
if #rng ~= 2 then
SF.throw("Range string length must be 2", 2)
end
end
return wrap(lpeg.R(...))
end
function lpeg_lib.S(str)
SF.CheckType(str, "string")
return wrap(lpeg.S(str))
end
function lpeg_lib.V(str)
SF.CheckType(str, "string")
return wrap(lpeg.V(str))
end
function lpeg_lib.L(patt)
SF.CheckType(patt, lp_meta)
local patt = unwrap(patt)
return wrap(lpeg.L(patt))
end
function lpeg_lib.locale()
local loc = lpeg.locale()
for key, patt in pairs(loc) do
loc[key] = wrap(patt)
end
return loc
end
function lpeg_lib.setmaxstack(num)
SF.CheckType(num, "number")
lpeg.setmaxstack(math.Clamp(num, 1, 10000))
end
function lpeg_lib.match(patt, str, pos, ...)
SF.CheckType(patt, lp_meta)
SF.CheckType(str, "string")
if pos ~= nil then
SF.CheckType(pos, "number")
end
local patt = unwrap(patt)
return lpeg.match(patt, str, pos, ...)
end
function lp_methods:match(str, pos, ...)
SF.CheckType(str, "string")
if pos ~= nil then
SF.CheckType(pos, "number")
end
local patt = unwrap(self) or patt
return lpeg.match(patt, str, pos, ...)
end
function lp_meta.__unm(patt)
local patt = unwrap(patt)
return wrap(-patt)
end
function lp_meta.__add(pt1, pt2)
local pt1 = getpatt(pt1)
local pt2 = getpatt(pt2)
if pt1 == nil or pt2 == nil then
SF.throw("Bad argument to LPeg operator", 2)
end
return wrap(pt1 + pt2)
end
function lp_meta.__sub(pt1, pt2)
local pt1 = getpatt(pt1)
local pt2 = getpatt(pt2)
if pt1 == nil or pt2 == nil then
SF.throw("Bad argument to LPeg operator", 2)
end
return wrap(pt1 - pt2)
end
function lp_meta.__mul(pt1, pt2)
local pt1 = getpatt(pt1)
local pt2 = getpatt(pt2)
if pt1 == nil or pt2 == nil then
SF.throw("Bad argument to LPeg operator", 2)
end
return wrap(pt1 * pt2)
end
function lp_meta.__pow(patt, num)
SF.CheckType(num, "number")
local patt = unwrap(patt)
return wrap(patt ^ num)
end
local c_types = {
["number"] = true, ["string"] = true,
["table"] = true, ["function"] = true,
}
function lp_meta.__div(patt, val)
if not c_types[SF.GetType(val)] then
SF.throw("Bad argument to LPeg operator",2)
end
local patt = unwrap(patt)
return wrap(patt / val)
end
function lp_meta.__tostring()
return "[LPeg Pattern]"
end
function lpeg_lib.C(patt)
SF.CheckType(patt, lp_meta)
local patt = unwrap(patt)
return wrap(lpeg.C(patt))
end
function lpeg_lib.Carg(num)
SF.CheckType(num, "number")
return wrap(lpeg.Carg(num))
end
function lpeg_lib.Cb(name)
SF.CheckType(name, "string")
return wrap(lpeg.Cb(name))
end
function lpeg_lib.Cc(...)
return wrap(lpeg.Cc(...))
end
function lpeg_lib.Cf(patt, func)
SF.CheckType(patt, lp_meta)
SF.CheckType(func, "function")
local patt = unwrap(patt)
return wrap(lpeg.Cf(patt, func))
end
function lpeg_lib.Cg(patt, name)
SF.CheckType(patt, lp_meta)
if name ~= nil then
SF.CheckType(name, "string")
end
local patt = unwrap(patt)
return wrap(lpeg.Cg(patt, name))
end
function lpeg_lib.Cp()
return wrap(lpeg.Cp())
end
function lpeg_lib.Cs(patt)
SF.CheckType(patt, lp_meta)
local patt = unwrap(patt)
return wrap(lpeg.Cs(patt))
end
function lpeg_lib.Ct(patt)
SF.CheckType(patt, lp_meta)
local patt = unwrap(patt)
return wrap(lpeg.Ct(patt))
end
function lpeg_lib.Cmt(patt, func)
SF.CheckType(patt, lp_meta)
SF.CheckType(func, "function")
local patt = unwrap(patt)
return wrap(lpeg.Cmt(patt, func))
end
local lpeg_re = {}
lpeg_lib.re = lpeg_re
local re_lib = lpeg.re
function lpeg_re.compile(patt, defs)
SF.CheckType(patt, "string")
if defs ~= nil then
SF.CheckType(defs, "table")
end
return wrap(re_lib.compile(patt, defs))
end
local pt_types = {
["string"] = true, ["Pattern"] = true,
}
function lpeg_re.find(str, patt, pos)
SF.CheckType(str, "string")
if not pt_types[SF.GetType(patt)] then
SF.throw("Bad LPeg pattern type", 2)
end
if pos ~= nil then
SF.CheckType(pos, "number")
end
local patt = unwrap(patt) or patt
return re_lib.find(str, patt, pos)
end
function lpeg_re.match(str, patt)
SF.CheckType(str, "string")
if not pt_types[SF.GetType(patt)] then
SF.throw("Bad LPeg pattern type", 2)
end
local patt = unwrap(patt) or patt
return re_lib.match(str, patt)
end
local gs_types = {
["string"] = true, ["table"] = true,
["function"] = true,
}
function lpeg_re.gsub(str, patt, repl)
SF.CheckType(str, "string")
if not pt_types[SF.GetType(patt)] then
SF.throw("Bad LPeg pattern type", 2)
end
if not gs_types[SF.GetType(repl)] then
SF.throw("Bad replacement value type", 2)
end
local patt = unwrap(patt) or patt
return re_lib.gsub(str, patt, repl)
end |
local self = {}
local ctor = GLib.MakeConstructor (self, GLib.Vector)
function GLib.ColumnVector (h, ...)
return ctor (1, h, ...)
end
function self:SetElementCount (elementCount)
self.Height = elementCount
end |
local addon = LibStub("AceAddon-3.0"):GetAddon("WSAttendance")
addon.util = {}
local GetNumGroupMembers, GetNumGuildMembers, GetGuildRosterInfo = GetNumGroupMembers, GetNumGuildMembers, GetGuildRosterInfo
local IsInRaid = IsInRaid
function addon.util.IterateGuildMembers()
local i = 0
local max = GetNumGuildMembers()
return function()
i = i + 1
if i > max then return end
return GetGuildRosterInfo(i)
end
end
do
local raid = {
"raid1", "raid2", "raid3", "raid4", "raid5", "raid6", "raid7", "raid8", "raid9", "raid10",
"raid11", "raid12", "raid13", "raid14", "raid15", "raid16", "raid17", "raid18", "raid19", "raid20",
"raid21", "raid22", "raid23", "raid24", "raid25", "raid26", "raid27", "raid28", "raid29", "raid30",
"raid31", "raid32", "raid33", "raid34", "raid35", "raid36", "raid37", "raid38", "raid39", "raid40"
}
local party = {
"player", "party1", "party2", "party3", "party4"
}
function addon.util.IterateGroupMembers()
local groupMembers = GetNumGroupMembers()
if groupMembers == 0 then
groupMembers = 1 -- Party, first element is player
end
local group = IsInRaid() and raid or party
local i = 0
return function()
i = i + 1
if i <= groupMembers then
return group[i]
end
end
end
end
-- Returns a table containing all keys that are in one table but not the other
function addon.util.TableDiff(t1, t2)
local diff = {}
local count = 0
-- Add all keys if a table is nil
if t1 ~= nil then
for k, v in pairs(t1) do
if t2 == nil or v ~= t2[k] then
count = count + 1
diff[count] = k
end
end
end
if t2 ~= nil then
for k, v in pairs(t2) do
if t1 == nil or t1[k] == nil then -- If it's not nil, it was caught in the pass through t1
count = count + 1
diff[count] = k
end
end
end
return diff
end
|
return {
{
effect_list = {
{
type = "BattleBuffAddAttrRatio",
trigger = {
"onAttach"
},
arg_list = {
attr = "loadSpeed",
number = 800
}
},
{
type = "BattleBuffFixVelocity",
trigger = {
"onAttach",
"onRemove"
},
arg_list = {
add = 3,
mul = 0
}
}
}
},
{
effect_list = {
{
type = "BattleBuffAddAttrRatio",
trigger = {
"onAttach"
},
arg_list = {
attr = "loadSpeed",
number = 910
}
},
{
type = "BattleBuffFixVelocity",
trigger = {
"onAttach",
"onRemove"
},
arg_list = {
add = 3,
mul = 0
}
}
}
},
{
effect_list = {
{
type = "BattleBuffAddAttrRatio",
trigger = {
"onAttach"
},
arg_list = {
attr = "loadSpeed",
number = 1020
}
},
{
type = "BattleBuffFixVelocity",
trigger = {
"onAttach",
"onRemove"
},
arg_list = {
add = 3,
mul = 0
}
}
}
},
{
effect_list = {
{
type = "BattleBuffAddAttrRatio",
trigger = {
"onAttach"
},
arg_list = {
attr = "loadSpeed",
number = 1130
}
},
{
type = "BattleBuffFixVelocity",
trigger = {
"onAttach",
"onRemove"
},
arg_list = {
add = 3,
mul = 0
}
}
}
},
{
effect_list = {
{
type = "BattleBuffAddAttrRatio",
trigger = {
"onAttach"
},
arg_list = {
attr = "loadSpeed",
number = 1240
}
},
{
type = "BattleBuffFixVelocity",
trigger = {
"onAttach",
"onRemove"
},
arg_list = {
add = 3,
mul = 0
}
}
}
},
{
effect_list = {
{
type = "BattleBuffAddAttrRatio",
trigger = {
"onAttach"
},
arg_list = {
attr = "loadSpeed",
number = 1350
}
},
{
type = "BattleBuffFixVelocity",
trigger = {
"onAttach",
"onRemove"
},
arg_list = {
add = 3,
mul = 0
}
}
}
},
{
effect_list = {
{
type = "BattleBuffAddAttrRatio",
trigger = {
"onAttach"
},
arg_list = {
attr = "loadSpeed",
number = 1460
}
},
{
type = "BattleBuffFixVelocity",
trigger = {
"onAttach",
"onRemove"
},
arg_list = {
add = 3,
mul = 0
}
}
}
},
{
effect_list = {
{
type = "BattleBuffAddAttrRatio",
trigger = {
"onAttach"
},
arg_list = {
attr = "loadSpeed",
number = 1570
}
},
{
type = "BattleBuffFixVelocity",
trigger = {
"onAttach",
"onRemove"
},
arg_list = {
add = 3,
mul = 0
}
}
}
},
{
effect_list = {
{
type = "BattleBuffAddAttrRatio",
trigger = {
"onAttach"
},
arg_list = {
attr = "loadSpeed",
number = 1680
}
},
{
type = "BattleBuffFixVelocity",
trigger = {
"onAttach",
"onRemove"
},
arg_list = {
add = 3,
mul = 0
}
}
}
},
{
effect_list = {
{
type = "BattleBuffAddAttrRatio",
trigger = {
"onAttach"
},
arg_list = {
attr = "loadSpeed",
number = 1800
}
},
{
type = "BattleBuffFixVelocity",
trigger = {
"onAttach",
"onRemove"
},
arg_list = {
add = 3,
mul = 0
}
}
}
},
init_effect = "",
name = "狼群战术-U37",
time = 0,
picture = "",
desc = "属性提升",
stack = 5,
id = 13942,
icon = 13940,
last_effect = "",
effect_list = {}
}
|
local Players = game:GetService("Players")
local Modules = Players.LocalPlayer.PlayerGui.AvatarEditorInGame.Modules
local Action = require(Modules.Common.Action)
return Action(script.Name, function(itemDetailsExpanded)
return {
itemDetailsExpanded = itemDetailsExpanded,
}
end) |
help(
[[
This module loads Git 1.9.0 into the environment. Git is a
source control module tool.
]])
whatis("Loads the Git SCM tools")
local version = "1.9.0"
local base = "/cvmfs/oasis.opensciencegrid.org/osg/modules/git/"..version
prepend_path("PATH", pathJoin(base, "bin"))
prepend_path("CPATH", pathJoin(base, "include"))
prepend_path("LIBRARY_PATH", pathJoin(base, "lib"))
family('git')
|
dependency "vrp"
dependency "cops"
server_script {
"@vrp/lib/utils.lua",
"server.lua"
}
client_script {
"@vrp/lib/utils.lua",
"init.lua",
--"gui/gui.lua"
}
--ui_page("public/index.html")
files {
-- "public/index.html",
-- "public/main.js",
-- "public/style.css",
-- "public/monitor.png",
-- "public/logo.png",
-- "public/cursor.png",
"configs/business.lua",
"client.lua",
"client-jobs.lua",
"gang/c-gang.lua",
"stores/c-stores.lua",
"gang/s-gang.lua",
"stores/s-stores.lua",
"businesses/c-business.lua"
}
|
io.stdout:setvbuf'no'
io.stderr:setvbuf'no'
local glue = require'glue'
local thread = require'thread'
local sock = require'sock'
local ffi = require'ffi'
local coro = require'coro'
local function test_addr()
local function dump(...)
for ai in assert(sock.addr(...)):addrs() do
print(ai:tostring(), ai:type(), ai:family(), ai:protocol(), ai:name())
end
end
dump('1234:2345:3456:4567:5678:6789:7890:8901', 0, 'tcp', 'inet6')
dump('123.124.125.126', 1234, 'tcp', 'inet', nil, {cannonname = true})
dump()
end
local function test_sockopt()
local s = assert(sock.tcp())
for _,k in ipairs{
'acceptconn ',
'broadcast ',
--'bsp_state ',
'conditional_accept',
'connect_time ',
'dontlinger ',
'dontroute ',
'error ',
'exclusiveaddruse ',
'keepalive ',
--'linger ',
'max_msg_size ',
'maxdg ',
'maxpathdg ',
'oobinline ',
'pause_accept ',
'port_scalability ',
--'protocol_info ',
'randomize_port ',
'rcvbuf ',
'rcvlowat ',
'rcvtimeo ',
'reuseaddr ',
'sndbuf ',
'sndlowat ',
'sndtimeo ',
'type ',
'tcp_bsdurgent ',
'tcp_expedited_1122',
'tcp_maxrt ',
'tcp_nodelay ',
'tcp_timestamps ',
} do
local sk, k = k, glue.trim(k)
local v = s:getopt(k)
print(sk, v)
end
print''
for _,k in ipairs{
'broadcast ',
'conditional_accept ',
'dontlinger ',
'dontroute ',
'exclusiveaddruse ',
'keepalive ',
'linger ',
'max_msg_size ',
'oobinline ',
'pause_accept ',
'port_scalability ',
'randomize_port ',
'rcvbuf ',
'rcvlowat ',
'rcvtimeo ',
'reuseaddr ',
'sndbuf ',
'sndlowat ',
'sndtimeo ',
'update_accept_context ',
'update_connect_context ',
'tcp_bsdurgent ',
'tcp_expedited_1122 ',
'tcp_maxrt ',
'tcp_nodelay ',
'tcp_timestamps ',
} do
local sk, k = k, glue.trim(k)
local canget, v = pcall(s.getopt, s, k)
if canget then
print(k, pcall(s.setopt, s, k, v))
end
end
end
local function start_server()
local server_thread = thread.new(function()
local sock = require'sock'
local coro = require'coro'
local s = assert(sock.tcp())
assert(s:listen('*', 8090))
sock.newthread(function()
while true do
print'...'
local cs, ra, la = assert(s:accept())
print('accepted', cs, ra:tostring(), ra:port(), la and la:tostring(), la and la:port())
print('accepted_thread', coro.running())
sock.newthread(function()
print'closing cs'
--cs:recv(buf, len)
assert(cs:close())
print('closed', coro.running())
end)
print('backto accepted_thread', coro.running())
end
s:close()
end)
print(sock.start())
end)
-- local s = assert(sock.tcp())
-- --assert(s:bind('127.0.0.1', 8090))
-- print(s:connect('127.0.0.1', '8080'))
-- --assert(s:send'hello')
-- s:close()
server_thread:join()
end
local function start_client()
local s = assert(sock.tcp())
sock.newthread(function()
print'...'
print(assert(s:connect(ffi.abi'win' and '10.8.1.130' or '10.8.2.153', 8090)))
print(assert(s:send'hello'))
print(assert(s:close()))
sock.stop()
end)
print(sock.start())
end
local function test_http()
sock.newthread(function()
local s = assert(sock.tcp())
print('connect', s:connect(ffi.abi'win' and '127.0.0.1' or '10.8.2.153', 80))
print('send', s:send'GET / HTTP/1.0\r\n\r\n')
local buf = ffi.new'char[4096]'
local n, err, ec = s:recv(buf, 4096)
if n then
print('recv', n, ffi.string(buf, n))
else
print(n, err, ec)
end
s:close()
end)
print('start', sock.start(1))
end
local function test_timers()
sock.run(function()
local i = 1
local job = sock.runevery(.1, function()
print(i); i = i + 1
end)
sock.runafter(1, function()
print'canceling'
job:cancel()
print'done'
end)
end)
os.exit()
end
test_timers()
--test_addr()
--test_sockopt()
--test_http()
if ffi.os == 'Windows' then
start_server()
else
start_client()
end
|
local pl = require'pl.import_into'()
return {
cmd = function(cmd)
end,
list_extend = function(dst, src)
pl.tablex.insertvalues(dst, src)
return dst
end,
tbl_contains = function(t, value)
local l = pl.List(t)
return l:contains(value)
end,
tbl_keys = function(t)
return pl.tablex.keys(t)
end,
tbl_extend = function(behavior, a, b)
if behavior == "force" then
return pl.tablex.union(a, b)
end
return nil
end,
tbl_filter = function(func, t)
return pl.tablex.filter(t, func)
end,
inspect = function(object)
return pl.pretty.write(object)
end,
startswith = function(s, prefix)
return pl.stringx.startswith(s, prefix)
end,
fn = {
split = pl.stringx.split,
join = function(list, sep)
if sep == nil or sep == "" then
sep = " "
end
return pl.stringx.join(sep, list)
end,
has = function(h)
local d = {
win32 = (pl.path.is_windows) and 1 or 0,
win64 = (pl.path.is_windows) and 1 or 0,
}
return d[h]
end,
mkdir = function(name)
pl.dir.makepath(name)
end,
expand = function(expr)
return pl.path.expanduser(expr)
end,
},
g = {},
b = {},
w = {},
t = {},
v = {},
env = {},
o = {},
bo = {},
wo = {},
}
|
-- Generated By protoc-gen-lua Do not Edit
local protobuf = require "protobuf"
module('Gift_pb', package.seeall)
local GIFT = protobuf.Descriptor();
local GIFT_REWARDTYPEINDEX_FIELD = protobuf.FieldDescriptor();
local GIFT_ITEMID_FIELD = protobuf.FieldDescriptor();
local GIFT_TYPEID_FIELD = protobuf.FieldDescriptor();
local GIFT_LEVEL_FIELD = protobuf.FieldDescriptor();
local GIFT_COUNT_FIELD = protobuf.FieldDescriptor();
local GIFT_INDATE_FIELD = protobuf.FieldDescriptor();
local GIFT_COLORINDEX_FIELD = protobuf.FieldDescriptor();
local GIFT_ATTACK_FIELD = protobuf.FieldDescriptor();
local GIFT_DEFEND_FIELD = protobuf.FieldDescriptor();
local GIFT_AGILITY_FIELD = protobuf.FieldDescriptor();
local GIFT_LUCKY_FIELD = protobuf.FieldDescriptor();
local GIFT_MAXLV_FIELD = protobuf.FieldDescriptor();
local GIFT_SLOT_FIELD = protobuf.FieldDescriptor();
GIFT_REWARDTYPEINDEX_FIELD.name = "rewardTypeIndex"
GIFT_REWARDTYPEINDEX_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.Gift.rewardTypeIndex"
GIFT_REWARDTYPEINDEX_FIELD.number = 1
GIFT_REWARDTYPEINDEX_FIELD.index = 0
GIFT_REWARDTYPEINDEX_FIELD.label = 2
GIFT_REWARDTYPEINDEX_FIELD.has_default_value = false
GIFT_REWARDTYPEINDEX_FIELD.default_value = 0
GIFT_REWARDTYPEINDEX_FIELD.type = 5
GIFT_REWARDTYPEINDEX_FIELD.cpp_type = 1
GIFT_ITEMID_FIELD.name = "itemId"
GIFT_ITEMID_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.Gift.itemId"
GIFT_ITEMID_FIELD.number = 2
GIFT_ITEMID_FIELD.index = 1
GIFT_ITEMID_FIELD.label = 1
GIFT_ITEMID_FIELD.has_default_value = false
GIFT_ITEMID_FIELD.default_value = ""
GIFT_ITEMID_FIELD.type = 9
GIFT_ITEMID_FIELD.cpp_type = 9
GIFT_TYPEID_FIELD.name = "typeId"
GIFT_TYPEID_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.Gift.typeId"
GIFT_TYPEID_FIELD.number = 3
GIFT_TYPEID_FIELD.index = 2
GIFT_TYPEID_FIELD.label = 1
GIFT_TYPEID_FIELD.has_default_value = false
GIFT_TYPEID_FIELD.default_value = ""
GIFT_TYPEID_FIELD.type = 9
GIFT_TYPEID_FIELD.cpp_type = 9
GIFT_LEVEL_FIELD.name = "level"
GIFT_LEVEL_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.Gift.level"
GIFT_LEVEL_FIELD.number = 4
GIFT_LEVEL_FIELD.index = 3
GIFT_LEVEL_FIELD.label = 1
GIFT_LEVEL_FIELD.has_default_value = false
GIFT_LEVEL_FIELD.default_value = 0
GIFT_LEVEL_FIELD.type = 5
GIFT_LEVEL_FIELD.cpp_type = 1
GIFT_COUNT_FIELD.name = "count"
GIFT_COUNT_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.Gift.count"
GIFT_COUNT_FIELD.number = 5
GIFT_COUNT_FIELD.index = 4
GIFT_COUNT_FIELD.label = 1
GIFT_COUNT_FIELD.has_default_value = false
GIFT_COUNT_FIELD.default_value = 0
GIFT_COUNT_FIELD.type = 5
GIFT_COUNT_FIELD.cpp_type = 1
GIFT_INDATE_FIELD.name = "indate"
GIFT_INDATE_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.Gift.indate"
GIFT_INDATE_FIELD.number = 6
GIFT_INDATE_FIELD.index = 5
GIFT_INDATE_FIELD.label = 1
GIFT_INDATE_FIELD.has_default_value = false
GIFT_INDATE_FIELD.default_value = 0
GIFT_INDATE_FIELD.type = 5
GIFT_INDATE_FIELD.cpp_type = 1
GIFT_COLORINDEX_FIELD.name = "colorIndex"
GIFT_COLORINDEX_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.Gift.colorIndex"
GIFT_COLORINDEX_FIELD.number = 7
GIFT_COLORINDEX_FIELD.index = 6
GIFT_COLORINDEX_FIELD.label = 1
GIFT_COLORINDEX_FIELD.has_default_value = false
GIFT_COLORINDEX_FIELD.default_value = 0
GIFT_COLORINDEX_FIELD.type = 5
GIFT_COLORINDEX_FIELD.cpp_type = 1
GIFT_ATTACK_FIELD.name = "attack"
GIFT_ATTACK_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.Gift.attack"
GIFT_ATTACK_FIELD.number = 8
GIFT_ATTACK_FIELD.index = 7
GIFT_ATTACK_FIELD.label = 1
GIFT_ATTACK_FIELD.has_default_value = false
GIFT_ATTACK_FIELD.default_value = 0
GIFT_ATTACK_FIELD.type = 5
GIFT_ATTACK_FIELD.cpp_type = 1
GIFT_DEFEND_FIELD.name = "defend"
GIFT_DEFEND_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.Gift.defend"
GIFT_DEFEND_FIELD.number = 9
GIFT_DEFEND_FIELD.index = 8
GIFT_DEFEND_FIELD.label = 1
GIFT_DEFEND_FIELD.has_default_value = false
GIFT_DEFEND_FIELD.default_value = 0
GIFT_DEFEND_FIELD.type = 5
GIFT_DEFEND_FIELD.cpp_type = 1
GIFT_AGILITY_FIELD.name = "agility"
GIFT_AGILITY_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.Gift.agility"
GIFT_AGILITY_FIELD.number = 10
GIFT_AGILITY_FIELD.index = 9
GIFT_AGILITY_FIELD.label = 1
GIFT_AGILITY_FIELD.has_default_value = false
GIFT_AGILITY_FIELD.default_value = 0
GIFT_AGILITY_FIELD.type = 5
GIFT_AGILITY_FIELD.cpp_type = 1
GIFT_LUCKY_FIELD.name = "lucky"
GIFT_LUCKY_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.Gift.lucky"
GIFT_LUCKY_FIELD.number = 11
GIFT_LUCKY_FIELD.index = 10
GIFT_LUCKY_FIELD.label = 1
GIFT_LUCKY_FIELD.has_default_value = false
GIFT_LUCKY_FIELD.default_value = 0
GIFT_LUCKY_FIELD.type = 5
GIFT_LUCKY_FIELD.cpp_type = 1
GIFT_MAXLV_FIELD.name = "maxlv"
GIFT_MAXLV_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.Gift.maxlv"
GIFT_MAXLV_FIELD.number = 12
GIFT_MAXLV_FIELD.index = 11
GIFT_MAXLV_FIELD.label = 1
GIFT_MAXLV_FIELD.has_default_value = false
GIFT_MAXLV_FIELD.default_value = 0
GIFT_MAXLV_FIELD.type = 5
GIFT_MAXLV_FIELD.cpp_type = 1
GIFT_SLOT_FIELD.name = "slot"
GIFT_SLOT_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.Gift.slot"
GIFT_SLOT_FIELD.number = 13
GIFT_SLOT_FIELD.index = 12
GIFT_SLOT_FIELD.label = 1
GIFT_SLOT_FIELD.has_default_value = false
GIFT_SLOT_FIELD.default_value = 0
GIFT_SLOT_FIELD.type = 5
GIFT_SLOT_FIELD.cpp_type = 1
GIFT.name = "Gift"
GIFT.full_name = ".com.xinqihd.sns.gameserver.proto.Gift"
GIFT.nested_types = {}
GIFT.enum_types = {}
GIFT.fields = {GIFT_REWARDTYPEINDEX_FIELD, GIFT_ITEMID_FIELD, GIFT_TYPEID_FIELD, GIFT_LEVEL_FIELD, GIFT_COUNT_FIELD, GIFT_INDATE_FIELD, GIFT_COLORINDEX_FIELD, GIFT_ATTACK_FIELD, GIFT_DEFEND_FIELD, GIFT_AGILITY_FIELD, GIFT_LUCKY_FIELD, GIFT_MAXLV_FIELD, GIFT_SLOT_FIELD}
GIFT.is_extendable = false
GIFT.extensions = {}
Gift = protobuf.Message(GIFT)
_G.GIFT_PB_GIFT = GIFT
|
dofile("myassert.lua")
-- type convertion tests
assert(tolua.type(A.last) == 'Tst_A') -- first time the object is mapped
assert(tolua.type(B.last) == 'Tst_B') -- type convertion to specialized type
assert(tolua.type(A.last) == 'Tst_B') -- no convertion: obj already mapped as B
local a = A:new()
assert(tolua.type(A.last) == 'Tst_A') -- no type convertion: same type
local b = B:new()
assert(tolua.type(A.last) == 'Tst_B') -- no convertion: obj already mapped as B
local c = luaC:new(0)
assert(tolua.type(A.last) == 'Tst_C') -- no convertion: obj already mapped as C
assert(tolua.type(luaC.last) == 'Tst_C')
local aa = A.AA:new()
local bb = A.BB:new()
local xx = create_aa()
-- casting test
local base = bb:Base();
local derived = tolua.cast(base,"Tst_A::Tst_BB");
assert(derived:classname()=="Tst_BB")
-- method calling tests
assert(a:a() == 'A')
assert(b:a() == 'A')
assert(b:b() == 'B')
assert(c:a() == 'A')
assert(c:b() == 'B')
assert(c:c() == 'C')
assert(aa:aa() == 'AA')
assert(bb:aa() == bb:Base():aa())
assert(xx:aa() == 'AA')
assert(is_aa(bb) == true)
-- test ownershipping handling
-- should delete objects: 6 7 8 9 10 (it may vary!)
remark = [[
local set = {}
for i=1,10 do
local c = luaC:new(i)
tolua.takeownership(c)
set[i] = c
end
for i=1,5 do
tolua.releaseownership(set[i])
end
--]]
print("Class test OK")
|
return {
"icons/life_flowerpot/life_flowerpot_038",
"icons/life_flowerpot/life_flowerpot_039",
"icons/life_flowerpot/life_flowerpot_040",
"icons/life_flowerpot/life_flowerpot_041",
"icons/life_flowerpot/life_flowerpot_042",
"icons/life_flowerpot/life_flowerpot_043",
"icons/life_flowerpot/life_flowerpot_044",
"icons/life_flowerpot/life_flowerpot_045",
"icons/life_flowerpot/life_flowerpot_046",
"icons/life_flowerpot/life_flowerpot_047",
"icons/life_flowerpot/life_flowerpot_048",
"icons/life_flowerpot/life_flowerpot_049",
"icons/life_flowerpot/life_flowerpot_050",
"icons/life_flowerpot/life_flowerpot_051",
"icons/life_flowerpot/life_flowerpot_052",
"icons/life_flowerpot/life_flowerpot_053",
"icons/life_flowerpot/life_flowerpot_054",
"icons/life_flowerpot/life_flowerpot_055",
"icons/life_flowerpot/life_flowerpot_056",
"icons/life_flowerpot/life_flowerpot_057",
"icons/life_flowerpot/life_flowerpot_058",
"icons/life_flowerpot/life_flowerpot_059",
"icons/life_flowerpot/life_flowerpot_060",
"icons/life_flowerpot/life_flowerpot_061",
"icons/life_flowerpot/life_flowerpot_062",
"icons/life_flowerpot/life_flowerpot_063",
"icons/life_flowerpot/life_flowerpot_064",
"icons/life_flowerpot/life_flowerpot_065",
"icons/life_flowerpot/life_flowerpot_066",
"icons/life_flowerpot/life_flowerpot_067",
"icons/life_flowerpot/life_flowerpot_068",
"icons/life_flowerpot/life_flowerpot_069",
"icons/life_flowerpot/life_flowerpot_070",
"icons/life_flowerpot/life_flowerpot_071",
"icons/life_flowerpot/life_flowerpot_072",
"icons/life_flowerpot/life_flowerpot_073",
"icons/life_flowerpot/life_flowerpot_074",
"icons/life_flowerpot/life_flowerpot_075",
"icons/life_flowerpot/life_flowerpot_076",
"icons/life_flowerpot/life_flowerpot_077",
"icons/life_flowerpot/life_flowerpot_078",
"icons/life_flowerpot/life_flowerpot_079",
"icons/life_flowerpot_001",
"icons/life_flowerpot_002",
"icons/life_flowerpot_003",
"icons/life_flowerpot_004",
"icons/life_flowerpot_005",
"icons/life_flowerpot_006",
"icons/life_flowerpot_007",
"icons/life_flowerpot_008",
"icons/life_flowerpot_009",
"icons/life_flowerpot_010",
"icons/life_flowerpot_011",
"icons/life_flowerpot_012",
"icons/life_flowerpot_013",
"icons/life_flowerpot_014",
"icons/life_flowerpot_015",
"icons/life_flowerpot_016",
"icons/life_flowerpot_017",
"icons/life_flowerpot_018",
"icons/life_flowerpot_019",
"icons/life_flowerpot_020",
"icons/life_flowerpot_021",
"icons/life_flowerpot_022",
"icons/life_flowerpot_023",
"icons/life_flowerpot_024",
"icons/life_flowerpot_025",
"icons/life_flowerpot_026",
"icons/life_flowerpot_027",
"icons/life_flowerpot_028",
"icons/life_flowerpot_029",
"icons/life_flowerpot_030",
"icons/life_flowerpot_031",
"icons/life_flowerpot_032",
"icons/life_flowerpot_033",
"icons/life_flowerpot_034",
"icons/life_flowerpot_035",
"icons/life_flowerpot_036",
"icons/life_flowerpot_037",
}
|
fx_version 'cerulean'
game 'gta5'
shared_scripts {
"config.lua"
}
client_scripts {
"vehcontrol-c.lua",
"menu-c.lua"
}
server_scripts {
"vehcontrol-s.lua"
}
ui_page 'html/index.html'
files {
'html/index.html',
'html/css/main.css',
'html/css/RadialMenu.css',
'html/js/main.js',
'html/js/RadialMenu.js'
}
dependency 'baseevents'
author 'Jake Hopkins'
description 'Vehicle Control'
version '1.3'
|
wrk.method = "POST"
wrk.body = [[{ "query": "{ human(id: \"1000\") { name } }", "variables": null, "operationName": null }]]
wrk.headers["Content-Type"] = "application/graphql"
|
--[[
{Madwork}
-[RateLimiter]---------------------------------------
Prevents RemoteEvent spamming; Player references are automatically removed as they leave
Members:
RateLimiter.Default [RateLimiter]
Functions:
RateLimiter.NewRateLimiter(rate) --> [RateLimiter]
rate [number] -- Events per second allowed; Excessive events are dropped
Methods [RateLimiter]:
RateLimiter:CheckRate(source) --> is_to_be_processed [bool] -- Whether event should be processed
source [any]
RateLimiter:CleanSource(source) -- Forgets about the source - must be called for any object that
has been passed to RateLimiter:CheckRate() after that object is no longer going to be used;
Does not have to be called for Player instances!
RateLimiter:Cleanup() -- Forgets all sources
RateLimiter:Destroy() -- Make the RateLimiter module forget about this RateLimiter object
--]]
local Players = game:GetService("Players")
local SETTINGS = {
DefaultRateLimiterRate = 120;
}
----- Service Table -----
local RateLimiter = {}
RateLimiter.Default = nil
local PlayerReference = {} -- {player = true}
local RateLimiters = {} -- {rate_limiter = true, ...}
----- Public functions -----
-- RateLimiter object:
local RateLimiterObject = {}
RateLimiterObject.ClassName = "RateLimiterObject"
RateLimiterObject.__index = RateLimiterObject
function RateLimiterObject:CheckRate(source) --> is_to_be_processed [bool] -- Whether event should be processed
local sources = self._sources
local os_clock = os.clock()
local rate_time = sources[source]
if rate_time ~= nil then
rate_time = math.max(os_clock, rate_time + self._rate_period)
if rate_time - os_clock < 1 then
sources[source] = rate_time
return true
else
return false
end
else
-- Preventing from remembering players that already left:
if typeof(source) == "Instance" and source:IsA("Player") and PlayerReference[source] == nil then
return false
end
sources[source] = os_clock + self._rate_period
return true
end
end
function RateLimiterObject:CleanSource(source) -- Forgets about the source - must be called for any object that
self._sources[source] = nil
end
function RateLimiterObject:Cleanup() -- Forgets all sources
self._sources = {}
end
function RateLimiterObject:Destroy() -- Make the RateLimiter module forget about this RateLimiter object
RateLimiters[self] = nil
end
-- Module functions:
function RateLimiter.NewRateLimiter(rate) --> [RateLimiter]
if rate <= 0 then
error("[RateLimiter]: Invalid rate")
end
local self = {
_sources = {};
_rate_period = 1 / rate;
}
setmetatable(self, RateLimiterObject)
RateLimiters[self] = true
return self
end
----- Initialize -----
for _, player in ipairs(Players:GetPlayers()) do
PlayerReference[player] = true
end
RateLimiter.Default = RateLimiter.NewRateLimiter(SETTINGS.DefaultRateLimiterRate)
----- Connections -----
Players.PlayerAdded:Connect(function(player)
PlayerReference[player] = true
end)
Players.PlayerRemoving:Connect(function(player)
PlayerReference[player] = nil
-- Automatic player reference cleanup:
for rate_limiter in next, RateLimiters do
rate_limiter._sources[player] = nil
end
end)
return RateLimiter
|
local ObjectManager = require("managers.object.object_manager")
corvetteRepairDroidConvoHandler = conv_handler:new {}
function corvetteRepairDroidConvoHandler:getInitialScreen(pPlayer, pNpc, pConvTemplate)
local convoTemplate = LuaConversationTemplate(pConvTemplate)
local pCorvette = SceneObject(SceneObject(pPlayer):getParent()):getParent()
local droidFixed = readData(BuildingObject(pCorvette):getObjectID() .. ":repairDroidComplete")
if (droidFixed == 1) then
return convoTemplate:getScreen("pdroid_excellent")
else
return convoTemplate:getScreen("pdroid_instructions")
end
end
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local nw = require "luci.model.network"
local fw = require "luci.model.firewall"
local ds = require "luci.dispatcher"
local has_v2 = nixio.fs.access("/lib/firewall/fw.sh")
require("luci.tools.webadmin")
m = Map("firewall", translate("Firewall"), translate("The firewall creates zones over your network interfaces to control network traffic flow."))
fw.init(m.uci)
nw.init(m.uci)
s = m:section(TypedSection, "defaults")
s.anonymous = true
s.addremove = false
s:tab("general", translate("General Settings"))
s:tab("custom", translate("Custom Rules"))
s:taboption("general", Flag, "syn_flood", translate("Enable SYN-flood protection"))
local di = s:taboption("general", Flag, "drop_invalid", translate("Drop invalid packets"))
di.rmempty = false
function di.cfgvalue(...)
return AbstractValue.cfgvalue(...) or "1"
end
p = {}
p[1] = s:taboption("general", ListValue, "input", translate("Input"))
p[2] = s:taboption("general", ListValue, "output", translate("Output"))
p[3] = s:taboption("general", ListValue, "forward", translate("Forward"))
for i, v in ipairs(p) do
v:value("REJECT", translate("reject"))
v:value("DROP", translate("drop"))
v:value("ACCEPT", translate("accept"))
end
custom = s:taboption("custom", Value, "_custom",
translate("Custom Rules (/etc/firewall.user)"))
custom.template = "cbi/tvalue"
custom.rows = 20
function custom.cfgvalue(self, section)
return nixio.fs.readfile("/etc/firewall.user")
end
function custom.write(self, section, value)
value = value:gsub("\r\n?", "\n")
nixio.fs.writefile("/etc/firewall.user", value)
end
s = m:section(TypedSection, "zone", translate("Zones"))
s.template = "cbi/tblsection"
s.anonymous = true
s.addremove = true
s.extedit = ds.build_url("admin", "network", "firewall", "zones", "%s")
function s.create(self)
local z = fw:new_zone()
if z then
luci.http.redirect(
ds.build_url("admin", "network", "firewall", "zones", z.sid)
)
end
end
function s.remove(self, section)
return fw:del_zone(section)
end
info = s:option(DummyValue, "_info", translate("Zone ⇒ Forwardings"))
info.template = "cbi/firewall_zoneforwards"
function info.cfgvalue(self, section)
return self.map:get(section, "name")
end
p = {}
p[1] = s:option(ListValue, "input", translate("Input"))
p[2] = s:option(ListValue, "output", translate("Output"))
p[3] = s:option(ListValue, "forward", translate("Forward"))
for i, v in ipairs(p) do
v:value("REJECT", translate("reject"))
v:value("DROP", translate("drop"))
v:value("ACCEPT", translate("accept"))
end
s:option(Flag, "masq", translate("Masquerading"))
s:option(Flag, "mtu_fix", translate("MSS clamping"))
local created = nil
--
-- Redirects
--
s = m:section(TypedSection, "redirect", translate("Redirections"))
s.template = "cbi/tblsection"
s.addremove = true
s.anonymous = true
s.sortable = true
s.extedit = ds.build_url("admin", "network", "firewall", "redirect", "%s")
function s.create(self, section)
created = TypedSection.create(self, section)
end
function s.parse(self, ...)
TypedSection.parse(self, ...)
if created then
m.uci:save("firewall")
luci.http.redirect(ds.build_url(
"admin", "network", "firewall", "redirect", created
))
end
end
name = s:option(DummyValue, "_name", translate("Name"))
function name.cfgvalue(self, s)
return self.map:get(s, "_name") or "-"
end
proto = s:option(DummyValue, "proto", translate("Protocol"))
function proto.cfgvalue(self, s)
local p = self.map:get(s, "proto")
if not p or p == "tcpudp" then
return "TCP+UDP"
else
return p:upper()
end
end
src = s:option(DummyValue, "src", translate("Source"))
function src.cfgvalue(self, s)
local rv = "%s:%s:%s" % {
self.map:get(s, "src") or "*",
self.map:get(s, "src_ip") or "0.0.0.0/0",
self.map:get(s, "src_port") or "*"
}
local mac = self.map:get(s, "src_mac")
if mac then
rv = rv .. ", MAC " .. mac
end
return rv
end
via = s:option(DummyValue, "via", translate("Via"))
function via.cfgvalue(self, s)
return "%s:%s:%s" % {
translate("Device"),
self.map:get(s, "src_dip") or "0.0.0.0/0",
self.map:get(s, "src_dport") or "*"
}
end
dest = s:option(DummyValue, "dest", translate("Destination"))
function dest.cfgvalue(self, s)
return "%s:%s:%s" % {
self.map:get(s, "dest") or "*",
self.map:get(s, "dest_ip") or "0.0.0.0/0",
self.map:get(s, "dest_port") or "*"
}
end
target = s:option(DummyValue, "target", translate("Action"))
function target.cfgvalue(self, s)
return self.map:get(s, "target") or "DNAT"
end
--
-- Rules
--
s = m:section(TypedSection, "rule", translate("Rules"))
s.addremove = true
s.anonymous = true
s.sortable = true
s.template = "cbi/tblsection"
s.extedit = ds.build_url("admin", "network", "firewall", "rule", "%s")
s.defaults.target = "ACCEPT"
function s.create(self, section)
local created = TypedSection.create(self, section)
m.uci:save("firewall")
luci.http.redirect(ds.build_url(
"admin", "network", "firewall", "rule", created
))
return
end
name = s:option(DummyValue, "_name", translate("Name"))
function name.cfgvalue(self, s)
return self.map:get(s, "_name") or "-"
end
if has_v2 then
family = s:option(DummyValue, "family", translate("Family"))
function family.cfgvalue(self, s)
local f = self.map:get(s, "family")
if f and f:match("4") then
return translate("IPv4 only")
elseif f and f:match("6") then
return translate("IPv6 only")
else
return translate("IPv4 and IPv6")
end
end
end
proto = s:option(DummyValue, "proto", translate("Protocol"))
function proto.cfgvalue(self, s)
local p = self.map:get(s, "proto")
local t = self.map:get(s, "icmp_type")
if p == "icmp" and t then
return "ICMP (%s)" % t
elseif p == "tcpudp" or not p then
return "TCP+UDP"
else
return p:upper()
end
end
src = s:option(DummyValue, "src", translate("Source"))
function src.cfgvalue(self, s)
local rv = "%s:%s:%s" % {
self.map:get(s, "src") or "*",
self.map:get(s, "src_ip") or "0.0.0.0/0",
self.map:get(s, "src_port") or "*"
}
local mac = self.map:get(s, "src_mac")
if mac then
rv = rv .. ", MAC " .. mac
end
return rv
end
dest = s:option(DummyValue, "dest", translate("Destination"))
function dest.cfgvalue(self, s)
return "%s:%s:%s" % {
self.map:get(s, "dest") or translate("Device"),
self.map:get(s, "dest_ip") or "0.0.0.0/0",
self.map:get(s, "dest_port") or "*"
}
end
s:option(DummyValue, "target", translate("Action"))
return m
|
print("character loaded")
function Character.OnInsert()
print("Character", tostring(this), "has been created")
this:GetPlayer():GetSelf():enableDennis()
if this:GetPlayer():GetSelf().prev_tuning ~= nil then
print("applying previous tuning!!")
this.Tuning = this:GetPlayer():GetSelf().prev_tuning:Copy()
end
end
--[[
function Character.Destroy()
print("Character", tostring(this), "has been destroyed")
this:GetPlayer():GetSelf():disableDennis()
end
]]
function Character.OnDeath(Killer, Weapon)
print("Character", tostring(this), "was kileld by " .. Killer .. " with " .. Weapon)
this:GetPlayer():GetSelf():disableDennis()
this:GetPlayer():GetSelf().prev_tuning = this.Tuning:Copy()
print(tostring(this:GetPlayer():GetSelf().prev_tuning))
end
function Character.OnWeaponFire(Weapon)
this:GetPlayer():GetSelf():triggerDennis(Weapon)
end
|
local luasnip
if
not pcall(
function()
luasnip = require("luasnip")
end
)
then
return
end
luasnip.config.set_config(
{
history = true,
updateevents = "TextChanged,TextChangedI"
}
)
require("luasnip/loaders/from_vscode").load()
|
local lm = require 'luamake'
lm.EXE = "lua"
lm.EXE_RESOURCE = "../../make/lua-language-server.rc"
lm:import "3rd/bee.lua/make.lua"
lm:lua_dll 'lpeglabel' {
rootdir = '3rd',
sources = 'lpeglabel/*.c',
visibility = 'default',
defines = {
'MAXRECLEVEL=1000',
},
}
lm:build 'install' {
'$luamake', 'lua', 'make/install.lua', lm.builddir,
deps = {
'lua',
'lpeglabel',
'bee',
}
}
local fs = require 'bee.filesystem'
local pf = require 'bee.platform'
local exe = pf.OS == 'Windows' and ".exe" or ""
lm:build 'unittest' {
fs.path 'bin' / pf.OS / ('lua-language-server' .. exe), 'test.lua', '-E',
pool = "console",
deps = {
'install',
}
}
lm:default 'unittest'
|
-- {{ Log something with the check name as a prefix
function check_log(str)
print(check_name .. ': ' .. str)
end
-- }}
-- {{ Fetch the amount of seconds since a device was updated
function last_update(device_name)
local t1 = os.time()
local s = otherdevices_lastupdate[device_name]
local year = string.sub(s, 1, 4)
local month = string.sub(s, 6, 7)
local day = string.sub(s, 9, 10)
local hour = string.sub(s, 12, 13)
local minutes = string.sub(s, 15, 16)
local seconds = string.sub(s, 18, 19)
local t2 = os.time{year=year, month=month, day=day, hour=hour, min=minutes, sec=seconds}
local difference = (os.difftime (t1, t2))
return difference
end
-- }}
check_name = 'AggregatePresenceDetection'
device_name = 'Presence (Any)'
check_interval = 30
commandArray = {}
check_log('Attempting to execute')
local difference = last_update(device_name)
if (difference > check_interval) then
check_log('Last ran ' .. difference .. ' seconds ago, running again..')
-- {{ Check-specific logic here
-- Loop through presence devices list and detect presences
local presence = nil
-- local presence_last_update_threshold = tonumber(uservariables['PRESENCE_AGGREGATION_DEVICE_LAST_UPDATE_THRESHOLD'])
for i in string.gmatch(uservariables['PRESENCE_AGGREGATION_DEVICES'], "[^;]+") do
-- Only continue if the value of this device hasn't changed within THRESHOLD seconds
-- if last_update(i) > presence_last_update_threshold then
local presence_check = otherdevices[i] == 'On'
check_log('Device "' .. i .. '" active: ' .. tostring(presence_check))
-- If our presence value is still unset, set it to false
-- This lets us know when a device has been checked after a threshold match
if presence == nil then
presence = false
end
if presence_check then
presence = true
end
-- else
-- check_log('Device "' .. i .. '" was updated less than "' .. tostring(presence_last_update_threshold) .. '" seconds ago, skipping value')
-- end
end
if presence == nil then
check_log('No devices were checked')
else
check_log('Presence detected: ' .. tostring(presence))
local device_state = presence and 'On' or 'Off'
if otherdevices[device_name] ~= device_state then
commandArray[device_name] = device_state
check_log('Setting value of device "' .. device_name .. '" to "' .. device_state .. '"')
else
check_log('Value of device "' .. device_name .. '" is already set to "' .. device_state .. '"')
end
end
-- }}
else
print('Last ran ' .. difference .. ' seconds ago, not running..')
end
return commandArray
|
-- Sound ids for all of the whispers, divided into seperate tables for each old god. --
local CthunSounds = {
546633, 546620, 546621, 546623, 546626, 546627, 546628, 546636
}
local NzothSounds = {
2529827, 2529828, 2529829, 2529830, 2529831, 2529832, 2529833, 2529834, 2529835, 2529836, 2529837, 2529838, 2529839, 2529840
, 2529841, 2529842, 2529843, 2529844, 2529846, 2564962, 2564963, 2564964, 2564965, 2564966, 2564967, 2564968, 2564969, 2564970, 2618480, 2618483, 2618486,
2923228, 2923229, 2923230, 2923231, 2923232, 2923233, 2923236, 2923237, 2959164, 2959166, 2959167, 2959168, 2959169, 2959170, 2959189, 2959190, 2959191, 2959192, 2959193, 2959194, 2960030
}
local IlgynothSounds = {
1360537, 1360538, 1360539, 1360540, 1360541, 1360542, 1360543, 1360544,1360545,
1360546, 1360547, 1360553, 1360554, 1360555, 1360556, 1360557, 1360558, 1360559,
1360560, 1360561, 1360562, 3178932, 3178933, 3178934, 3178935, 3178936,3178937
, 3180746, 3180788, 3180789, 3180790, 3180791, 3180792, 3180900, 3180901,
3180902, 3180903, 3180904, 3180905, 3180906, 3180907, 3180910, 3180911, 3180938,
3180939, 3180940, 3180944
}
local YoggSaronSounds = {
564844, 564858, 564838, 564877, 564865, 564834, 564862, 564868, 564857, 564870, 564856, 564845, 564823
}
local GhuunSounds = {
2000113, 2000114, 2000115, 2000119, 2000120, 2000121, 2000149
}
-- Plays a random sound depending on what configuration settings are enabled. --
local function PlaySounds(click)
-- availableSounds always starts of with a number of shared whispers. --
local availableSounds = {2494907, 2494908, 2494909, 2494910, 2494911, 2494912, 2494913, 2494914, 2494915, 2494916}
if OldGodWhispersDatabase['cthunEnabled'] == true then
for k, v in pairs(CthunSounds) do
table.insert(availableSounds, v)
end
end
if OldGodWhispersDatabase['nzothEnabled'] == true then
for k, v in pairs(NzothSounds) do
table.insert(availableSounds, v)
end
end
if OldGodWhispersDatabase['ghuunEnabled'] == true then
for k, v in pairs(GhuunSounds) do
table.insert(availableSounds, v)
end
end
if OldGodWhispersDatabase['yoggSaronEnabled'] == true then
for k, v in pairs(YoggSaronSounds) do
table.insert(availableSounds, v)
end
end
if OldGodWhispersDatabase['ilgynothEnabled'] == true then
for k, v in pairs(IlgynothSounds) do
table.insert(availableSounds, v)
end
end
-- Prevents random mode from lingering by checking if its true before playing a souns. --
if OldGodWhispersDatabase['random'] == true or click == true then
PlaySoundFile(availableSounds[math.random(#availableSounds)], "Dialog")
end
-- This should only fire if it's a callback from an interval. --
-- The click arg gets passed as true on all button presses to prevent double firing. --
if OldGodWhispersDatabase['random'] == true and click == nil then
PerformRandom()
end
end
-- Fires a random function on an interval. --
local function PerformRandom()
C_Timer.After(math.random(300, 1800), PlaySounds)
end
-- Registers the frame that renders the button in-game. --
local frame = CreateFrame("Button", "DragFrame", UIParent)
frame:RegisterEvent("ADDON_LOADED")
frame:RegisterEvent("PLAYER_LOGOUT")
frame:SetPoint("Center", 0, 0)
frame:SetSize(45, 45)
-- Makes the frame draggable. --
frame:SetMovable(true)
frame:EnableMouse(true)
frame:RegisterForDrag("LeftButton")
frame:SetScript("OnDragStart", frame.StartMoving)
frame:SetScript("OnDragStop", frame.StopMovingOrSizing)
local icon = frame:CreateTexture("Texture", "Background")
-- N'Zoth eyeball texture. --
icon:SetTexture("3004126")
-- Makes the area behind the background invisible. --
icon:SetMask("Interface\\CharacterFrame\\TempPortraitAlphaMask")
icon:SetAllPoints(frame)
local ring = frame:CreateTexture("Texture", "Overlay")
ring:SetAtlas("adventureguide-ring")
ring:SetPoint("Center", frame)
ring:SetSize(60, 60)
local ringHighlight = frame:CreateTexture("Texture", "Overlay")
ringHighlight:SetAtlas("adventureguide-rewardring")
ringHighlight:SetPoint("Center", frame)
ringHighlight:SetSize(60, 60)
ringHighlight:SetBlendMode("Add")
ringHighlight:SetVertexColor(1, 1, 1, 0.25)
frame:SetScript("OnEnter", function(self)
ringHighlight:Show()
end)
frame:SetScript("OnLeave", function(self)
ringHighlight:Hide()
end)
frame:SetScript('OnClick', function(self)
PlaySounds(true)
end)
frame:SetScript("OnEvent", function(self, event, arg1)
if event == "ADDON_LOADED" and arg1 == "OldGodWhispers" then
-- Checks to see if the session already has data for the addon. --
if OldGodWhispersDatabase == nil then
-- If no data is found some initial values get set. --
OldGodWhispersDatabase = {
random = false,
addonShow = true,
cthunEnabled = true,
nzothEnabled = true,
ghuunEnabled = true,
yoggSaronEnabled = true,
ilgynothEnabled = true
}
end
else
-- If there is addon data some initial calls get made to ensure the saved preferences are correctly respected. --
if OldGodWhispersDatabase['addonShow'] == false then
frame:Hide()
end
if OldGodWhispersDatabase['random'] == true then
PerformRandom()
end
end
end)
-- Handles slash commands / toggling. --
local function AvailableCommands(msg)
if msg == 'toggle' then
if OldGodWhispersDatabase['addonShow'] == true then
frame:Hide()
else
frame:Show()
end
OldGodWhispersDatabase['addonShow'] = not OldGodWhispersDatabase['addonShow']
elseif msg == 'random' then
OldGodWhispersDatabase['random'] = not OldGodWhispersDatabase['random']
print("Random Whispers - ", OldGodWhispersDatabase['random'] and "Enabled" or "Disabled")
if OldGodWhispersDatabase['random'] == true then
PerformRandom()
end
elseif msg == 'cthun' then
OldGodWhispersDatabase['cthunEnabled'] = not OldGodWhispersDatabase['cthunEnabled']
print("C'thun Whispers - ", OldGodWhispersDatabase['cthunEnabled'] and "Enabled" or "Disabled")
elseif msg == 'nzoth' then
OldGodWhispersDatabase['nzothEnabled'] = not OldGodWhispersDatabase['nzothEnabled']
print("N'Zoth Whispers - ", OldGodWhispersDatabase['nzothEnabled'] and "Enabled" or "Disabled")
elseif msg == 'ghuun' then
OldGodWhispersDatabase['ghuunEnabled'] = not OldGodWhispersDatabase['ghuunEnabled']
print("G'huun Whispers - ", OldGodWhispersDatabase['ghuunEnabled'] and "Enabled" or "Disabled")
elseif msg == 'yoggsaron' then
OldGodWhispersDatabase['yoggSaronEnabled'] = not OldGodWhispersDatabase['yoggSaronEnabled']
print("Yogg-Saron Whispers - ", OldGodWhispersDatabase['yoggSaronEnabled'] and "Enabled" or "Disabled")
elseif msg == 'ilgynoth' then
OldGodWhispersDatabase['ilgynothEnabled'] = not OldGodWhispersDatabase['ilgynothEnabled']
print("Il'gynoth Whispers - ", OldGodWhispersDatabase['ilgynothEnabled'] and "Enabled" or "Disabled")
elseif msg == 'status' then
print("Old God Whispers <James Ives - https://jamesiv.es>")
print("Status:")
print("Random Whispers - ", OldGodWhispersDatabase['random'] and "Enabled" or "Disabled")
print("C'thun Whispers - ", OldGodWhispersDatabase['cthunEnabled'] and "Enabled" or "Disabled")
print("N'Zoth Whispers - ", OldGodWhispersDatabase['nzothEnabled'] and "Enabled" or "Disabled")
print("G'huun Whispers - ", OldGodWhispersDatabase['ghuunEnabled'] and "Enabled" or "Disabled")
print("Yogg-Saron Whispers - ", OldGodWhispersDatabase['yoggSaronEnabled'] and "Enabled" or "Disabled")
print("Il'gynoth Whispers - ", OldGodWhispersDatabase['ilgynothEnabled'] and "Enabled" or "Disabled")
else
print("Old God Whispers <James Ives - https://jamesiv.es>")
print("Available Commands:")
print("/ogw toggle <Toggles the addon>")
print("/ogw random <Enables random whispers from the Old Gods without pressing the button>")
print("/ogw status <Shows which whispers are currently enabled/disabled>")
print("/ogw cthun <Toggles whispers from C'thun>")
print("/ogw nzoth <Toggles whispers from N'Zoth>")
print("/ogw ghuun <Toggles whispers from G'huun>")
print("/ogw yoggsaron <Toggles whispers from Yogg-Saron>")
print("/ogw ilgynoth <Toggles whispers from Il'gynoth>")
end
end
-- Registers /ogw and /oldgodwhispers as available commands. --
SLASH_OLD_GOD_WHISPERS1, SLASH_OLD_GOD_WHISPERS2 = '/ogw', '/oldgodwhispers'
SlashCmdList["OLD_GOD_WHISPERS"] = AvailableCommands
|
kboard.Specs = kboard.Specs or {}
kboard.Specs.Personal = kboard.Specs.Personal or {}
include("kleaderboards/kboard_config.lua")
include("kleaderboards/shared/sh_kboard.lua")
include("kleaderboards/client/cl_kboard_draw.lua")
include("kleaderboards/client/cl_kboard_leaderboards.lua")
include("kleaderboards/client/cl_kboard_personalstats.lua")
include("kleaderboards/client/cl_kboard_serverpanel.lua")
include("kleaderboards/client/cl_kboard_connectedplayers.lua")
KLEADERBOARDS = 1 -- Enums for deciding which panel the user is on.
KPERSONAL_STATS = 2
KCONNECTED_PLAYERS = 3
KSERVER_STATS = 4
local col_orange = Color(255,150,0)
local col_black = Color(0,0,0)
local col_white = Color(255,255,255)
for i = 1,45 do -- Create fonts of different sizes for resolution scaling
surface.CreateFont( "kboard_Default"..i, {font = "Tahoma", size = i,weight = 1000,antialias = true})
end
local baseFrame = {}
local clply = LocalPlayer()
kboard.leaderboardTable = kboard.leaderboardTable or {}
kboard.personalTable = kboard.personalTable or {}
kboard.serverTable = kboard.serverTable or {}
kboard.weaponsTable = kboard.weaponsTable or {}
kboard.Specs.whiteSpace = 5
vgui.Register("mainFrame", baseFrame, "DFrame")
net.Receive("kboard_openMenu", function(len)
kboard.Specs.totalPages = net.ReadUInt(16)
local leaderboardLen = net.ReadUInt(16)
local serverLen = net.ReadUInt(16)
local weaponsLen = net.ReadUInt(16)
kboard.leaderboardTable = net.ReadData(leaderboardLen)
if (not isstring(kboard.leaderboardTable)) then clply:kboard_CMSG(kboard.errors.InvalidQuery.." (Client leaderboardTable1)") return end --error handling
kboard.leaderboardTable = util.Decompress(kboard.leaderboardTable)
if (not isstring(kboard.leaderboardTable)) then clply:kboard_CMSG(kboard.errors.InvalidQuery.." (Client leaderboardTable2)") return end --error handling
kboard.leaderboardTable = util.JSONToTable(kboard.leaderboardTable)
if (not istable(kboard.leaderboardTable)) then clply:kboard_CMSG(kboard.errors.InvalidQuery.." (Client leaderboardTable3)") return end --error handling
kboard.serverTable = net.ReadData(serverLen)
if (not isstring(kboard.serverTable)) then clply:kboard_CMSG(kboard.errors.InvalidQuery.." (Client serverTable1)") return end --error handling
kboard.serverTable = util.Decompress(kboard.serverTable)
if (not isstring(kboard.serverTable)) then clply:kboard_CMSG(kboard.errors.InvalidQuery.." (Client serverTable2)") return end --error handling
kboard.serverTable = util.JSONToTable(kboard.serverTable)
if (not istable(kboard.serverTable)) then clply:kboard_CMSG(kboard.errors.InvalidQuery.." (Client serverTable3)") return end --error handling
kboard.weaponsTable = net.ReadData(weaponsLen)
if (not isstring(kboard.weaponsTable)) then clply:kboard_CMSG(kboard.errors.InvalidQuery.." (Client weaponsTable1)") return end --error handling
kboard.weaponsTable = util.Decompress(kboard.weaponsTable)
if (not isstring(kboard.weaponsTable)) then clply:kboard_CMSG(kboard.errors.InvalidQuery.." (Client weaponsTable2)") return end --error handling
kboard.weaponsTable = util.JSONToTable(kboard.weaponsTable)
if (not istable(kboard.weaponsTable)) then clply:kboard_CMSG(kboard.errors.InvalidQuery.." (Client weaponsTable3)") return end --error handling
kboard.mainMenu()
end)
function baseFrame:Init()
kboard.Specs.leaderboardPage = 1
local scrW = ScrW()
local scrH = ScrH()
local defaultWidth = 1920 -- the default width this panel is created for. to decide how much to scale
kboard.Specs.count = 0
for i=1,10 do -- resolution scaling for fonts.
if defaultWidth > scrW then
kboard.Specs.count = kboard.Specs.count + 1
defaultWidth = defaultWidth - 100
end
end
kboard.Specs.hasFocus = KLEADERBOARDS -- Important variable to decide which panel has focus atm
kboard.Specs.frameSizeX = scrW - ((scrW / 16) *8)
kboard.Specs.frameSizeY = scrH - ((scrH / 9) *4)
kboard.Specs.closeSizeX = 35
kboard.Specs.closeSizeY = 20
kboard.Specs.Personal.fontSize = 25
kboard.Specs.buttonsSizeX = kboard.Specs.frameSizeX * 0.3
kboard.Specs.buttonsSizeY = kboard.Specs.frameSizeY - (kboard.Specs.whiteSpace * 2)
kboard.Specs.buttonsPosX = kboard.Specs.whiteSpace
kboard.Specs.buttonsPosY = kboard.Specs.whiteSpace
kboard.Specs.titlePanelSizeX = kboard.Specs.frameSizeX - kboard.Specs.buttonsSizeX - (kboard.Specs.whiteSpace * 4)
kboard.Specs.titlePanelSizeY = (kboard.Specs.frameSizeY - (kboard.Specs.whiteSpace * 2)) * 0.10 + 1
kboard.Specs.titlePanelPosX = (kboard.Specs.whiteSpace * 3) + kboard.Specs.buttonsSizeX
kboard.Specs.titlePanelPosY = kboard.Specs.whiteSpace
kboard.Specs.lineOffset = 0
kboard.Specs.whiteLine1Y = kboard.Specs.titlePanelSizeY -1
kboard.Specs.whiteLine1X = (kboard.Specs.whiteSpace * (kboard.Specs.lineOffset/2))
kboard.Specs.whiteLine1SizeX = kboard.Specs.titlePanelSizeX - (kboard.Specs.whiteSpace * kboard.Specs.lineOffset)
kboard.Specs.contentPanelSizeX = kboard.Specs.frameSizeX - kboard.Specs.buttonsSizeX - (kboard.Specs.whiteSpace * 4)
kboard.Specs.contentPanelSizeY = kboard.Specs.frameSizeY - (kboard.Specs.whiteSpace * 2) - kboard.Specs.titlePanelSizeY
kboard.Specs.contentPanelPosX = (kboard.Specs.whiteSpace * 3) + kboard.Specs.buttonsSizeX
kboard.Specs.contentPanelPosY = kboard.Specs.whiteSpace + kboard.Specs.titlePanelSizeY
kboard.Specs.whiteLine2Offset = 10
kboard.Specs.whiteLine2Y = kboard.Specs.frameSizeY * 0.05
kboard.Specs.whiteLine2X = (kboard.Specs.whiteSpace * (kboard.Specs.whiteLine2Offset/2))
kboard.Specs.whiteLine2SizeX = kboard.Specs.contentPanelSizeX - (kboard.Specs.whiteSpace * kboard.Specs.whiteLine2Offset)
kboard.Specs.whiteLine3Offset = 10
kboard.Specs.whiteLine3Y = kboard.Specs.contentPanelSizeY - (kboard.Specs.frameSizeY * 0.10)
kboard.Specs.whiteLine3X = (kboard.Specs.whiteSpace * (kboard.Specs.whiteLine3Offset/2))
kboard.Specs.whiteLine3SizeX = kboard.Specs.contentPanelSizeX - (kboard.Specs.whiteSpace * kboard.Specs.whiteLine3Offset)
kboard.Specs.closePosX = kboard.Specs.contentPanelSizeX - kboard.Specs.closeSizeX
kboard.Specs.closePosY = 0
kboard.Specs.selectionButtonsSizeX = kboard.Specs.contentPanelSizeX
kboard.Specs.selectionButtonsSizeY = kboard.Specs.buttonsSizeY * 0.17
kboard.Specs.selectionFontSize = 30
kboard.Specs.selectionFont = "kboard_Default"..(kboard.Specs.selectionFontSize - kboard.Specs.count)
kboard.Specs.titleText = "Leaderboards"
kboard.Specs.titleFontSize = 40
kboard.Specs.titleFont = "kboard_Default"..(kboard.Specs.titleFontSize - kboard.Specs.count)
kboard.Specs.titlePosX = kboard.Specs.whiteSpace
kboard.Specs.titlePosY = kboard.Specs.whiteLine1Y - kboard.Specs.whiteSpace
end
function kboard.mainMenu() -- the code for the main menu (Does not include code for the content of all panels)
kboard.frame = vgui.Create("mainFrame")
kboard.frame:SetSize(kboard.Specs.frameSizeX,kboard.Specs.frameSizeY)
kboard.frame:Center()
kboard.frame:MakePopup(true)
kboard.frame:SetTitle("")
kboard.frame:ShowCloseButton(false)
kboard.frame.Paint = function(s,w,h)
kboard.paintFrame(w, h, kboard.colors.frame)
end
local buttonsPanel = vgui.Create("DPanel", kboard.frame)
buttonsPanel:SetSize(kboard.Specs.buttonsSizeX, kboard.Specs.buttonsSizeY)
buttonsPanel:SetPos(kboard.Specs.buttonsPosX,kboard.Specs.buttonsPosY)
buttonsPanel.Paint = function(s,w,h)
kboard.paintFrame(w, h, kboard.colors.buttonsPanel)
end
kboard.titlePanel = vgui.Create("DPanel", kboard.frame)
kboard.titlePanel:SetSize(kboard.Specs.titlePanelSizeX, kboard.Specs.titlePanelSizeY)
kboard.titlePanel:SetPos(kboard.Specs.titlePanelPosX,kboard.Specs.titlePanelPosY)
kboard.titlePanel.Paint = function(s,w,h)
kboard.paintFrame(w, h, kboard.colors.titlePanel, false)
surface.SetDrawColor(kboard.colors.whiteLines)
surface.DrawRect(kboard.Specs.whiteLine1X, kboard.Specs.whiteLine1Y, kboard.Specs.whiteLine1SizeX, 1) -- Draw White Line 1
end
kboard.contentPanel = vgui.Create("DPanel", kboard.frame)
kboard.contentPanel:SetSize(kboard.Specs.contentPanelSizeX, kboard.Specs.contentPanelSizeY)
kboard.contentPanel:SetPos(kboard.Specs.contentPanelPosX, kboard.Specs.contentPanelPosY)
kboard.contentPanel.Paint = function(s,w,h)
kboard.paintFrame(w, h, kboard.colors.contentPanel, false)
if (kboard.Specs.hasFocus == KLEADERBOARDS || kboard.Specs.hasFocus == KCONNECTED_PLAYERS) then
surface.SetDrawColor(kboard.colors.whiteLines)
surface.DrawRect(kboard.Specs.whiteLine2X, kboard.Specs.whiteLine2Y, kboard.Specs.whiteLine2SizeX, 1)
surface.DrawRect(kboard.Specs.whiteLine3X, kboard.Specs.whiteLine3Y, kboard.Specs.whiteLine3SizeX, 1)
end
end
kboard.titleLabel = vgui.Create("DLabel", kboard.titlePanel)
kboard.setText(kboard.Specs.titleText, kboard.Specs.titleFont, kboard.titleLabel)
kboard.clickOption(KLEADERBOARDS, "Leaderboards", kboard.titleLabel)
kboard.drawLeaderboards(kboard.contentPanel, kboard.Specs.count)
local buttonHovered = kboard.colors.closeText
local closeButton = vgui.Create("DButton", kboard.titlePanel)
closeButton:SetSize(kboard.Specs.closeSizeX,kboard.Specs.closeSizeY)
closeButton:SetPos(kboard.Specs.closePosX,kboard.Specs.closePosY)
closeButton:SetFont("kboard_Default16")
closeButton:SetText("X")
closeButton.DoClick = function(self)
kboard.frame:Close()
end
closeButton.Paint = function(s,w,h)
if closeButton:IsHovered() then buttonHovered = kboard.colors.closeHovered else buttonHovered = kboard.colors.closeText end
closeButton:SetTextColor(buttonHovered)
kboard.paintFrame(w, h, kboard.colors.closeButton, false)
end
local leaderboardsColor = kboard.colors.selectionButtons
local leaderboardsTextColor = kboard.colors.selectionTextHovered
local buttonLeaderboards = vgui.Create("DButton", buttonsPanel)
buttonLeaderboards:SetSize(kboard.Specs.selectionButtonsSizeX,kboard.Specs.selectionButtonsSizeY)
buttonLeaderboards:Dock(TOP)
buttonLeaderboards:SetFont(kboard.Specs.selectionFont)
buttonLeaderboards:SetText("Leaderboards")
buttonLeaderboards.Paint = function(s,w,h)
if (kboard.Specs.hasFocus == KLEADERBOARDS || s:IsHovered()) then
leaderboardsColor = kboard.colors.selectionHovered
else
leaderboardsColor = kboard.colors.selectionButtons
end
if (kboard.Specs.hasFocus == KLEADERBOARDS) then leaderboardsTextColor = kboard.colors.selectionTextHovered else leaderboardsTextColor = kboard.colors.selectionText end
buttonLeaderboards:SetTextColor(leaderboardsTextColor)
kboard.paintFrame(w, h, leaderboardsColor, false)
end
buttonLeaderboards.DoClick = function(self)
kboard.clickOption(KLEADERBOARDS, "Leaderboards", kboard.titleLabel)
kboard.drawLeaderboards(kboard.contentPanel, kboard.Specs.count)
end
local connectedPlayersColor = kboard.colors.selectionButtons
local connectedPlayersTextColor = kboard.colors.selectionTextHovered
local connectedPlayers = vgui.Create("DButton", buttonsPanel)
connectedPlayers:SetSize(kboard.Specs.selectionButtonsSizeX,kboard.Specs.selectionButtonsSizeY)
connectedPlayers:Dock(TOP)
connectedPlayers:SetFont(kboard.Specs.selectionFont)
connectedPlayers:SetText("Connected Players")
connectedPlayers.Paint = function(s,w,h)
if (kboard.Specs.hasFocus == KCONNECTED_PLAYERS || s:IsHovered()) then
connectedPlayersColor = kboard.colors.selectionHovered
else
connectedPlayersColor = kboard.colors.selectionButtons
end
if (kboard.Specs.hasFocus == KCONNECTED_PLAYERS) then connectedPlayersTextColor = kboard.colors.selectionTextHovered else connectedPlayersTextColor = kboard.colors.selectionText end
connectedPlayers:SetTextColor(connectedPlayersTextColor)
kboard.paintFrame(w, h, connectedPlayersColor, false)
end
connectedPlayers.DoClick = function(self)
kboard.clickOption(KCONNECTED_PLAYERS, "Connected Players", kboard.titleLabel)
kboard.callConnectedPlayers(kboard.contentPanel,kboard.Specs.count)
end
local personalColor = kboard.colors.selectionButtons
local personalTextColor = kboard.colors.selectionText
local buttonPersonal = vgui.Create("DButton", buttonsPanel)
buttonPersonal:SetSize(kboard.Specs.selectionButtonsSizeX,kboard.Specs.selectionButtonsSizeY)
buttonPersonal:Dock(TOP)
buttonPersonal:SetFont(kboard.Specs.selectionFont)
buttonPersonal:SetText("Player Stats")
buttonPersonal.Paint = function(s,w,h)
if (kboard.Specs.hasFocus == KPERSONAL_STATS || s:IsHovered()) then
personalColor = kboard.colors.selectionHovered
else
personalColor = kboard.colors.selectionButtons
end
if (kboard.Specs.hasFocus == KPERSONAL_STATS) then personalTextColor = kboard.colors.selectionTextHovered else personalTextColor = kboard.colors.selectionText end
buttonPersonal:SetTextColor(personalTextColor)
kboard.paintFrame(w, h, personalColor, false)
end
buttonPersonal.DoClick = function(self)
net.Start("kboard_RequestPlayerData")
net.WriteString(LocalPlayer():SteamID())
net.SendToServer()
end
local serverStatsColor = kboard.colors.selectionButtons
local serverTextColor = kboard.colors.selectionText
local buttonServer = vgui.Create("DButton", buttonsPanel)
buttonServer:SetSize(kboard.Specs.selectionButtonsSizeX,kboard.Specs.selectionButtonsSizeY)
buttonServer:Dock(TOP)
buttonServer:SetFont(kboard.Specs.selectionFont)
buttonServer:SetText("Server Stats")
buttonServer.Paint = function(s,w,h)
if (kboard.Specs.hasFocus == KSERVER_STATS || s:IsHovered()) then
serverStatsColor = kboard.colors.selectionHovered
else
serverStatsColor = kboard.colors.selectionButtons
end
if (kboard.Specs.hasFocus == KSERVER_STATS) then serverTextColor = kboard.colors.selectionTextHovered else serverTextColor = kboard.colors.selectionText end
buttonServer:SetTextColor(serverTextColor)
kboard.paintFrame(w, h, serverStatsColor, false)
end
buttonServer.DoClick = function(self)
kboard.clickOption(KSERVER_STATS, "Server Stats", kboard.titleLabel)
kboard.drawServerStats(kboard.contentPanel, kboard.Specs.count)
end
end
net.Receive("kboard_SendPlayerData", function(len)
kboard.personalTable = net.ReadData(len)
kboard.personalTable = util.Decompress(kboard.personalTable)
kboard.personalTable = util.JSONToTable(kboard.personalTable)
if (not istable(kboard.personalTable)) then return end
local reqPly = player.GetBySteamID(kboard.personalTable.SteamID)
kboard.drawPlayerStats(kboard.contentPanel, reqPly, kboard.Specs.count)
kboard.clickOption(KPERSONAL_STATS, "Player Stats", kboard.titleLabel)
end)
function kboard.clickOption(focus, titleText, label) -- function to change title when one of the option buttons is clicked.
kboard.Specs.titleText = titleText
kboard.setText(kboard.Specs.titleText, kboard.Specs.titleFont, label)
end
net.Receive("kboard_SendMessage", function()
local msg = net.ReadString()
chat.AddText(col_black, "[", col_orange,"KLeaderboards", col_black, "] ",col_white, msg)
end) |
display.setStatusBar( display.HiddenStatusBar )
local StickLib = require("libs.lib_analog_stick")
local physics = require ("physics")
physics.start()
local screenW = display.contentWidth
local screenH = display.contentHeight
local posX = display.contentWidth/2
local posY = display.contentHeight/2
-- local hero
-- local localGroup = display.newGroup() -- remember this for farther down in the code
-- motionx = 0; -- Variable used to move character along x axis
-- motiony = 0; -- Variable used to move character along y axis
-- speed = 2; -- Set Walking Speed
-- CREATE ANALOG STICK
MyStick = StickLib.NewStick(
{
x = screenW*.15,
y = screenH*.85,
thumbSize = 16,
borderSize = 32,
snapBackSpeed = .2,
R = 25,
G = 255,
B = 255
} )
-- MAIN LOOP
----------------------------------------------------------------
local function main( event )
-- MOVE THE SHIP
MyStick:move(hero, 2.5, false) -- se a opção for true o objeto se move com o joystick
-- -- SHOW STICK INFO
-- Text.text = "ANGLE = "..MyStick:getAngle().." DIST = "..math.ceil(MyStick:getDistance()).." PERCENT = "..math.ceil(MyStick:getPercent()*100).."%"
-- print("MyStick:getAngle = "..MyStick:getAngle())
-- print("MyStick:getDistance = "..MyStick:getDistance())
-- print("MyStick:getPercent = "..MyStick:getPercent()*100)
-- print("POSICAO X / Y " ..hero.x,hero.y)
angle = MyStick:getAngle()
moving = MyStick:getMoving()
-- Determine which animation to play based on the direction of the analog stick
if(angle <= 45 or angle > 315) then
seq = "forward"
elseif(angle <= 135 and angle > 45) then
seq = "right"
elseif(angle <= 225 and angle > 135) then
seq = "back"
elseif(angle <= 315 and angle > 225) then
seq = "left"
end
-- Change the sequence only if another sequence isn't still playing
if(not (seq == hero.sequence) and moving) then -- and not attacking
hero:setSequence(seq)
end
-- If the analog stick is moving, animate the sprite
if(moving) then
hero:play()
end
end
timer.performWithDelay(2000, function()
--MyStick:delete()
end, 1)
Runtime:addEventListener( "enterFrame", main )
--Declare and set up Sprite Image Sheet and sequence data
spriteOptions = {
height = 64,
width = 64,
numFrames = 273,
sheetContentWidth = 832,
sheetContentHeight = 1344
}
mySheet = graphics.newImageSheet("player/rectSmall.png", spriteOptions)
sequenceData = {
{name = "forward", frames={105,106,107,108,109,110,111,112}, time = 500, loopCount = 1},
{name = "right", frames={144,145,146,147,148,149,150,151,152}, time = 500, loopCount = 1},
{name = "back", frames= {131,132,133,134,135,136,137,138,139}, time = 500, loopCount = 1},
{name = "left", frames={118,119,120,121,122,123,124,125,126}, time = 500, loopCount = 1},
{name = "attackForward", frames={157,158,159,160,161,162,157}, time = 400, loopCount = 1},
{name = "attackRight", frames={196,197,198,199,200,201,196}, time = 400, loopCount = 1},
{name = "attackBack", frames={183,184,185,186,187,188,183}, time = 400, loopCount = 1},
{name = "attackLeft", frames={170,171,172,173,174,175,170}, time = 400, loopCount = 1},
{name = "death", frames={261,262,263,264,265,266}, time = 500, loopCount = 1}
}
playerCollisionFilter = { categoryBits = 1, maskBits = 6 }
-- Display the new sprite at the coordinates passed
hero = display.newSprite(mySheet, sequenceData) --ImageRect("player/hero.png", 32, 32)
-- hero.bodyType = "static"
physics.addBody( hero, "static", {filter = playerCollisionFilter})
hero:setSequence( "forward" )
hero.type = "player"
hero:scale(1.5, 1.5)
hero.x = posX*2.55 --- 110
hero.y = posY*3.8 --+ 15
hero.collision = onCollision
hero:addEventListener("collision", hero)
-- localGroup:insert(hero) |
require ("lib.lclass.init")
class "FocusLostEvent"
function FocusLostEvent:FocusLostEvent ()
end
|
local tLibError = Apollo.GetPackage("Gemini:LibError-1.0")
local fnErrorHandler = tLibError and tLibError.tPackage and tLibError.tPackage.Error or Print
-- first load the submodule
local function loadModule(dir, file)
local func = assert(loadfile(dir..file..".lua"))
if func then
-- Does not handle multiple return values, but these are not using that.
local bSuccess, retVal = xpcall(func, fnErrorHandler)
return retVal
end
end
-- This gets the current directory of this file, so it also works when embedded
local strsub, strgsub, debug = string.sub, string.gsub, debug
local dir = string.sub(string.gsub(debug.getinfo(1).source, "^(.+[\\/])[^\\/]+$", "%1"), 2, -1)
local BustedDone = loadModule(dir, "done")
-------------------------------------------------------------------------------
--- Olivine-Labs Busted-Init
-------------------------------------------------------------------------------
--math.randomseed(os.time())
local function shuffle(t)
local n = #t
while n >= 2 do
local k = math.random(n)
t[n], t[k] = t[k], t[n]
n = n - 1
end
return t
end
return function(busted)
local function execAll(descriptor, current, propagate)
local parent = busted.context.parent(current)
if propagate and parent then execAll(descriptor, parent, propagate) end
local list = current[descriptor]
if list then
for _, v in pairs(list) do
busted.safe(descriptor, v.run, v)
end
end
end
local function dexecAll(descriptor, current, propagate)
local parent = busted.context.parent(current)
local list = current[descriptor]
if list then
for _, v in pairs(list) do
busted.safe(descriptor, v.run, v)
end
end
if propagate and parent then execAll(descriptor, parent, propagate) end
end
local file = function(file)
busted.publish({ 'file', 'start' }, file.name)
if busted.safe('file', file.run, file, true) then
busted.execute(file)
end
busted.publish({ 'file', 'end' }, file.name)
end
local describe = function(describe)
local parent = busted.context.parent(describe)
busted.publish({ 'describe', 'start' }, describe, parent)
if not describe.env then describe.env = {} end
local randomize = false
describe.env.randomize = function()
randomize = true
end
if busted.safe('describe', describe.run, describe) then
if randomize then
shuffle(busted.context.children(describe))
end
execAll('setup', describe)
busted.execute(describe)
dexecAll('teardown', describe)
end
busted.publish({ 'describe', 'end' }, describe, parent)
end
local it = function(it)
local finally
if not it.env then it.env = {} end
it.env.finally = function(fn)
finally = fn
end
local parent = busted.context.parent(it)
execAll('before_each', parent, true)
busted.publish({ 'test', 'start' }, it, parent)
local res = busted.safe('it', it.run, it)
if not it.env.done then
busted.publish({ 'test', 'end' }, it, parent, res and 'success' or 'failure')
if finally then busted.safe('finally', finally, it) end
dexecAll('after_each', parent, true)
end
end
local pending = function(pending)
local trace = busted.getTrace(pending, 3)
busted.publish({ 'test', 'end' }, pending, busted.context.parent(pending), 'pending', trace)
end
local async = function()
local parent = busted.context.get()
if not parent.env then parent.env = {} end
parent.env.done = BustedDone.new(function()
busted.publish({ 'test', 'end' }, it, parent, 'success')
if finally then busted.safe('finally', finally, it) end
dexecAll('after_each', parent, true)
end)
end
busted.register('file', file)
busted.register('describe', describe)
busted.register('context', describe)
busted.register('it', it)
busted.register('pending', pending)
busted.context.get().env.async = async
busted.register('setup')
busted.register('teardown')
busted.register('before_each')
busted.register('after_each')
return busted
end
|
#!/usr/bin/env lua
-------------------------------------------------------------------------------
-- Description: unit test file for iptable
-------------------------------------------------------------------------------
package.cpath = "./build/?.so;"
describe("iptable.mask(af, num)", function()
expose("module: ", function()
iptable = require("iptable");
assert.is_truthy(iptable);
it("handles ipv4 max (inv)mask", function()
assert.equal("255.255.255.255", iptable.mask(iptable.AF_INET, 32));
assert.equal("0.0.0.0", iptable.mask(iptable.AF_INET, 32, true));
end)
it("handles ipv4 min (inv)mask", function()
assert.equal("0.0.0.0", iptable.mask(iptable.AF_INET, 0));
assert.equal("0.0.0.0", iptable.mask(iptable.AF_INET, -0));
end)
it("handles ipv4 regular (inv)masks", function()
assert.equal("255.255.255.254", iptable.mask(iptable.AF_INET, 31));
assert.equal("0.0.0.1", iptable.mask(iptable.AF_INET, 31, true));
assert.equal("255.255.255.252", iptable.mask(iptable.AF_INET, 30));
assert.equal("0.0.0.3", iptable.mask(iptable.AF_INET, 30, true));
assert.equal("255.255.255.128", iptable.mask(iptable.AF_INET, 25));
assert.equal("0.0.0.127", iptable.mask(iptable.AF_INET, 25, true));
assert.equal("255.255.255.0", iptable.mask(iptable.AF_INET, 24));
assert.equal("0.0.0.255", iptable.mask(iptable.AF_INET, 24,true));
assert.equal("255.255.0.0", iptable.mask(iptable.AF_INET, 16));
assert.equal("0.0.255.255", iptable.mask(iptable.AF_INET, 16, true));
assert.equal("255.0.0.0", iptable.mask(iptable.AF_INET, 8));
assert.equal("0.255.255.255", iptable.mask(iptable.AF_INET, 8, true));
assert.equal("128.0.0.0", iptable.mask(iptable.AF_INET, 1));
assert.equal("127.255.255.255", iptable.mask(iptable.AF_INET, 1, true));
end)
end)
end)
|
local WhiteNoise_local, Parent = torch.class('nn.WhiteNoise_local', 'nn.Module')
function WhiteNoise_local:__init(mean, std)
Parent.__init(self)
-- std corresponds to 50% for MNIST training data std.
self.mean = mean or 0
self.std = std or 0.1
self.noise = torch.Tensor()
end
function WhiteNoise_local:updateOutput(input)
self.output:resizeAs(input):copy(input)
if self.train ~= false then
self.noise:resizeAs(input)
self.noise:normal(self.mean, self.std)
self.output:add(self.noise)
else
if self.mean ~= 0 then
self.output:add(self.mean)
end
end
return self.output
end
function WhiteNoise_local:updateGradInput(input, gradOutput)
if self.train ~= false then
-- Simply return the gradients.
self.gradInput:resizeAs(gradOutput):copy(gradOutput)
else
-- error('backprop only defined while training')
self.gradInput:resizeAs(gradOutput):copy(gradOutput)
end
return self.gradInput
end
function WhiteNoise_local:__tostring__()
return string.format('%s mean: %f, std: %f',
torch.type(self), self.mean, self.std)
end
|
local M = { _NAME = "uri", VERSION = "1.0" }
M.__index = M
package.path = package.path..";./lib/uri/uri/?.lua"
local Util = require ("_util")
local _UNRESERVED = "A-Za-z0-9%-._~"
local _GEN_DELIMS = ":/?#%[%]@"
local _SUB_DELIMS = "!$&'()*+,;="
local _RESERVED = _GEN_DELIMS .. _SUB_DELIMS
local _USERINFO = "^[" .. _UNRESERVED .. "%%" .. _SUB_DELIMS .. ":]*$"
local _REG_NAME = "^[" .. _UNRESERVED .. "%%" .. _SUB_DELIMS .. "]*$"
local _IP_FUTURE_LITERAL = "^v[0-9A-Fa-f]+%." ..
"[" .. _UNRESERVED .. _SUB_DELIMS .. "]+$"
local _QUERY_OR_FRAG = "^[" .. _UNRESERVED .. "%%" .. _SUB_DELIMS .. ":@/?]*$"
local _PATH_CHARS = "^[" .. _UNRESERVED .. "%%" .. _SUB_DELIMS .. ":@/]*$"
local function _normalize_percent_encoding (s)
if s:find("%%$") or s:find("%%.$") then
error("unfinished percent encoding at end of URI '" .. s .. "'")
end
return s:gsub("%%(..)", function (hex)
if not hex:find("^[0-9A-Fa-f][0-9A-Fa-f]$") then
error("invalid percent encoding '%" .. hex ..
"' in URI '" .. s .. "'")
end
-- Never percent-encode unreserved characters, and always use uppercase
-- hexadecimal for percent encoding. RFC 3986 section 6.2.2.2.
local char = string.char(tonumber("0x" .. hex))
return char:find("^[" .. _UNRESERVED .. "]") and char or "%" .. hex:upper()
end)
end
local function _is_ip4_literal (s)
if not s:find("^[0-9]+%.[0-9]+%.[0-9]+%.[0-9]+$") then return false end
for dec_octet in s:gmatch("[0-9]+") do
if dec_octet:len() > 3 or dec_octet:find("^0.") or
tonumber(dec_octet) > 255 then
return false
end
end
return true
end
local function _is_ip6_literal (s)
local had_elipsis = false -- true when '::' found
local num_chunks = 0
while s ~= "" do
num_chunks = num_chunks + 1
local p1, p2 = s:find("::?")
local chunk
if p1 then
chunk = s:sub(1, p1 - 1)
s = s:sub(p2 + 1)
if p2 ~= p1 then -- found '::'
if had_elipsis then return false end -- two of '::'
had_elipsis = true
if chunk == "" then num_chunks = num_chunks - 1 end
else
if chunk == "" then return false end -- ':' at start
if s == "" then return false end -- ':' at end
end
else
chunk = s
s = ""
end
-- Chunk is neither 4-digit hex num, nor IPv4address in last chunk.
if (not chunk:find("^[0-9a-f]+$") or chunk:len() > 4) and
(s ~= "" or not _is_ip4_literal(chunk)) and
chunk ~= "" then
return false
end
-- IPv4address in last position counts for two chunks of hex digits.
if chunk:len() > 4 then num_chunks = num_chunks + 1 end
end
if had_elipsis then
if num_chunks > 7 then return false end
else
if num_chunks ~= 8 then return false end
end
return true
end
local function _is_valid_host (host)
if host:find("^%[.*%]$") then
local ip_literal = host:sub(2, -2)
if ip_literal:find("^v") then
if not ip_literal:find(_IP_FUTURE_LITERAL) then
return "invalid IPvFuture literal '" .. ip_literal .. "'"
end
else
if not _is_ip6_literal(ip_literal) then
return "invalid IPv6 address '" .. ip_literal .. "'"
end
end
elseif not _is_ip4_literal(host) and not host:find(_REG_NAME) then
return "invalid host value '" .. host .. "'"
end
return nil
end
local function _normalize_and_check_path (s, normalize)
if not s:find(_PATH_CHARS) then return false end
if not normalize then return s end
-- Remove unnecessary percent encoding for path values.
-- TODO - I think this should be HTTP-specific (probably file also).
--s = Util.uri_decode(s, _SUB_DELIMS .. ":@")
return Util.remove_dot_segments(s)
end
function M.new (class, uri, base)
if not uri then error("usage: URI:new(uristring, [baseuri])") end
if type(uri) ~= "string" then uri = tostring(uri) end
if base then
local uri, err = M.new(class, uri)
if not uri then return nil, err end
if type(base) ~= "table" then
base, err = M.new(class, base)
if not base then return nil, "error parsing base URI: " .. err end
end
if base:is_relative() then return nil, "base URI must be absolute" end
local ok, err = pcall(uri.resolve, uri, base)
if not ok then return nil, err end
return uri
end
local s = _normalize_percent_encoding(uri)
local _, p
local scheme, authority, userinfo, host, port, path, query, fragment
_, p, scheme = s:find("^([a-zA-Z][-+.a-zA-Z0-9]*):")
if scheme then
scheme = scheme:lower()
s = s:sub(p + 1)
end
_, p, authority = s:find("^//([^/?#]*)")
if authority then
s = s:sub(p + 1)
_, p, userinfo = authority:find("^([^@]*)@")
if userinfo then
if not userinfo:find(_USERINFO) then
return nil, "invalid userinfo value '" .. userinfo .. "'"
end
authority = authority:sub(p + 1)
end
p, _, port = authority:find(":([0-9]*)$")
if port then
port = (port ~= "") and tonumber(port) or nil
authority = authority:sub(1, p - 1)
end
host = authority:lower()
local err = _is_valid_host(host)
if err then return nil, err end
end
_, p, path = s:find("^([^?#]*)")
if path ~= "" then
local normpath = _normalize_and_check_path(path, scheme)
if not normpath then return nil, "invalid path '" .. path .. "'" end
path = normpath
s = s:sub(p + 1)
end
_, p, query = s:find("^%?([^#]*)")
if query then
s = s:sub(p + 1)
if not query:find(_QUERY_OR_FRAG) then
return nil, "invalid query value '?" .. query .. "'"
end
end
_, p, fragment = s:find("^#(.*)")
if fragment then
if not fragment:find(_QUERY_OR_FRAG) then
return nil, "invalid fragment value '#" .. fragment .. "'"
end
end
local o = {
_scheme = scheme,
_userinfo = userinfo,
_host = host,
_port = port,
_path = path,
_query = query,
_fragment = fragment,
}
setmetatable(o, scheme and class or (require "uri._relative"))
return o:init()
end
function M.uri (self, ...)
local uri = self._uri
if not uri then
local scheme = self:scheme()
if scheme then
uri = scheme .. ":"
else
uri = ""
end
local host, port, userinfo = self:host(), self._port, self:userinfo()
if host or port or userinfo then
uri = uri .. "//"
if userinfo then uri = uri .. userinfo .. "@" end
if host then uri = uri .. host end
if port then uri = uri .. ":" .. port end
end
local path = self:path()
if uri == "" and path:find("^[^/]*:") then
path = "./" .. path
end
uri = uri .. path
if self:query() then uri = uri .. "?" .. self:query() end
if self:fragment() then uri = uri .. "#" .. self:fragment() end
self._uri = uri -- cache
end
if select("#", ...) > 0 then
local new = ...
if not new then error("URI can't be set to nil") end
local newuri, err = M:new(new)
if not newuri then
error("new URI string is invalid (" .. err .. ")")
end
setmetatable(self, getmetatable(newuri))
for k in pairs(self) do self[k] = nil end
for k, v in pairs(newuri) do self[k] = v end
end
return uri
end
function M.__tostring (self) return self:uri() end
function M.eq (a, b)
if type(a) == "string" then a = assert(M:new(a)) end
if type(b) == "string" then b = assert(M:new(b)) end
return a:uri() == b:uri()
end
function M.scheme (self, ...)
local old = self._scheme
if select("#", ...) > 0 then
local new = ...
if not new then error("can't remove scheme from absolute URI") end
if type(new) ~= "string" then new = tostring(new) end
if not new:find("^[a-zA-Z][-+.a-zA-Z0-9]*$") then
error("invalid scheme '" .. new .. "'")
end
Util.do_class_changing_change(self, M, "scheme", new,
function (uri, new) uri._scheme = new end)
end
return old
end
function M.userinfo (self, ...)
local old = self._userinfo
if select("#", ...) > 0 then
local new = ...
if new then
if not new:find(_USERINFO) then
error("invalid userinfo value '" .. new .. "'")
end
new = _normalize_percent_encoding(new)
end
self._userinfo = new
if new and not self._host then self._host = "" end
self._uri = nil
end
return old
end
function M.host (self, ...)
local old = self._host
if select("#", ...) > 0 then
local new = ...
if new then
new = tostring(new):lower()
local err = _is_valid_host(new)
if err then error(err) end
else
if self._userinfo or self._port then
error("there must be a host if there is a userinfo or port," ..
" although it can be the empty string")
end
end
self._host = new
self._uri = nil
end
return old
end
function M.port (self, ...)
local old = self._port or self:default_port()
if select("#", ...) > 0 then
local new = ...
if new then
if type(new) == "string" then new = tonumber(new) end
if new < 0 then error("port number must not be negative") end
local newint = new - new % 1
if newint ~= new then error("port number not integer") end
if new == self:default_port() then new = nil end
end
self._port = new
if new and not self._host then self._host = "" end
self._uri = nil
end
return old
end
function M.path (self, ...)
local old = self._path
if select("#", ...) > 0 then
local new = ... or ""
new = _normalize_percent_encoding(new)
new = Util.uri_encode(new, "^A-Za-z0-9%-._~%%!$&'()*+,;=:@/")
if self._host then
if new ~= "" and not new:find("^/") then
error("path must begin with '/' when there is an authority")
end
else
if new:find("^//") then new = "/%2F" .. new:sub(3) end
end
self._path = new
self._uri = nil
end
return old
end
function M.query (self, ...)
local old = self._query
if select("#", ...) > 0 then
local new = ...
if new then
new = Util.uri_encode(new, "^" .. _UNRESERVED .. "%%" .. _SUB_DELIMS .. ":@/?")
end
self._query = new
self._uri = nil
end
return old
end
function M.fragment (self, ...)
local old = self._fragment
if select("#", ...) > 0 then
local new = ...
if new then
new = Util.uri_encode(new, "^" .. _UNRESERVED .. "%%" .. _SUB_DELIMS .. ":@/?")
end
self._fragment = new
self._uri = nil
end
return old
end
function M.init (self)
local scheme_class
= Util.attempt_require("uri." .. self._scheme:gsub("[-+.]", "_"))
if scheme_class then
setmetatable(self, scheme_class)
if self._port and self._port == self:default_port() then
self._port = nil
end
-- Call the subclass 'init' method, if it has its own.
if scheme_class ~= M and self.init ~= M.init then
return self:init()
end
end
return self
end
function M.default_port () return nil end
function M.is_relative () return false end
function M.resolve () end -- only does anything in uri._relative
-- TODO - there should probably be an option or something allowing you to
-- choose between making a link relative whenever possible (always using a
-- relative path if the scheme and authority are the same as the base URI) or
-- just using a relative reference to make the link as small as possible, which
-- might meaning using a path of '/' instead if '../../../' or whatever.
-- This method's algorithm is loosely based on the one described here:
-- http://lists.w3.org/Archives/Public/uri/2007Sep/0003.html
function M.relativize (self, base)
if type(base) == "string" then base = assert(M:new(base)) end
-- Leave it alone if we can't a relative URI, or if it would be a network
-- path reference.
if self._scheme ~= base._scheme or self._host ~= base._host or
self._port ~= base._port or self._userinfo ~= base._userinfo then
return
end
local basepath = base._path
local oldpath = self._path
-- This is to avoid trying to make a URN or something relative, which
-- is likely to lead to grief.
if not basepath:find("^/") or not oldpath:find("^/") then return end
-- Turn it into a relative reference.
self._uri = nil
self._scheme = nil
self._host = nil
self._port = nil
self._userinfo = nil
setmetatable(self, require "uri._relative")
-- Use empty path if the path in the base URI is already correct.
if oldpath == basepath then
if self._query or not base._query then
self._path = ""
else
-- An empty URI reference leaves the query string in the base URI
-- unchanged, so to get a result with no query part we have to
-- have something in the relative path.
local _, _, lastseg = oldpath:find("/([^/]+)$")
if lastseg and lastseg:find(":") then lastseg = "./" .. lastseg end
self._path = lastseg or "."
end
return
end
if oldpath == "/" or basepath == "/" then return end
local basesegs = Util.split("/", basepath:sub(2))
local oldsegs = Util.split("/", oldpath:sub(2))
if oldsegs[1] ~= basesegs[1] then return end
table.remove(basesegs)
while #oldsegs > 1 and #basesegs > 0 and oldsegs[1] == basesegs[1] do
table.remove(oldsegs, 1)
table.remove(basesegs, 1)
end
local path_naked = true
local newpath = ""
while #basesegs > 0 do
table.remove(basesegs, 1)
newpath = newpath .. "../"
path_naked = false
end
if path_naked and #oldsegs == 1 and oldsegs[1] == "" then
newpath = "./"
table.remove(oldsegs)
end
while #oldsegs > 0 do
if path_naked then
if oldsegs[1]:find(":") then
newpath = newpath .. "./"
elseif #oldsegs > 1 and oldsegs[1] == "" and oldsegs[2] == "" then
newpath = newpath .. "/."
end
end
newpath = newpath .. oldsegs[1]
path_naked = false
table.remove(oldsegs, 1)
if #oldsegs > 0 then newpath = newpath .. "/" end
end
self._path = newpath
end
return M
-- vi:ts=4 sw=4 expandtab
|
--
--
--
local GameCreate = {}
local General = require ("src.logic.general")
local Explore = require ("src.control.gamestate.explore")
local Save = require ("src.control.save")
local MapGenerate = require ("src.logic.generation.map.mapgenerate")
-- Creates a new save game
-- Argument: save slot
function GameCreate.createSave (save)
General.Random:setSeed (os.time ())
for i=1, 5 do
General.randomInt ()
end
local seed = General.randomInt ()
return Explore (GameCreate.createNewSaveGame (seed))
end
-- Loads a save game
-- TODO
function GameCreate.loadSave (save)
end
-- Builds the "save" table
function GameCreate.createNewSaveGame (seed)
--General.setSeed (seed)
local save = Save (seed)
MapGenerate._generate (save)
return save
end
return GameCreate
|
-- {"regionName", xCenter, yCenter, shape and size, tier, {"spawnGroup1", ...}, maxSpawnLimit}
-- Shape and size is a table with the following format depending on the shape of the area:
-- - Circle: {CIRCLE, radius}
-- - Rectangle: {RECTANGLE, x2, y2}
-- - Ring: {RING, inner radius, outer radius}
-- Tier is a bit mask with the following possible values where each hexadecimal position is one possible configuration.
-- That means that it is not possible to have both a spawn area and a no spawn area in the same region, but
-- a spawn area that is also a no build zone is possible.
require("scripts.managers.spawn_manager.regions")
taanab_regions = {
{"pandath",2000,5400,{CIRCLE,300},NOSPAWNAREA + NOBUILDZONEAREA},
{"starhunterstation",3763,-5425,{CIRCLE,300},NOSPAWNAREA + NOBUILDZONEAREA},
{"world_spawner",0,0,{CIRCLE,-1},SPAWNAREA + WORLDSPAWNAREA,{"taanab_world"},2048},
{"taanabhexfarms",-3000,-105,{CIRCLE,300},NOSPAWNAREA + NOBUILDZONEAREA},
{"taanabgreatherd",5537,-4958,{CIRCLE,300},NOWORLDSPAWNAREA + NOBUILDZONEAREA + SPAWNAREA,{"taanab_nerfherd"},1024},
{"downedship",3293,-1324,{CIRCLE,150},NOBUILDZONEAREA},
{"taanabcanyonlands",-2590,3705,{CIRCLE,50},NOBUILDZONEAREA},
{"taanabmine",-2609,-1305,{CIRCLE,200},NOSPAWNAREA + NOBUILDZONEAREA},
{"taanabcave",-850,7200,{CIRCLE,150},NOSPAWNAREA + NOBUILDZONEAREA},
}
|
local ffi = require("ffi")
local inspect = require("inspect")
require("allegro52")
local retval = false
local allegro = ffi.load("allegro_monolith-debug-5.2.dll")
local ALLEGRO_VERSION_INT = ffi.cast("int", 84018176)
retval = allegro.al_install_system(ALLEGRO_VERSION_INT, nil)
assert(retval == true)
retval = allegro.al_install_keyboard()
print(retval)
local display = allegro.al_create_display(800, 600)
assert(display ~= nil)
while true do
allegro.al_clear_to_color(allegro.al_map_rgb(255, 255, 255))
allegro.al_flip_display()
end
|
-- by Qige
-- 2016.04.05
-- 2017.01.03/2017.03.04
-- 2017.03.13: add local, change "require 'six.cmd'" to "local cmd = require 'six.cmd'"
local cmd = {}
function cmd.exec(_pstring)
local _result
if (_pstring and string.len(_pstring) > 0) then
local _sys = io.popen(_pstring)
_result = _sys:read("*all")
io.close(_sys)
end
return _result
end
function cmd.sleep(sec)
cmd.exec(string.format("sleep %d", sec))
end
return cmd
|
urlp = require('rest_url_parser');
cjson = require('cjson.safe');
mongo = require('mongo');
roc_params = require('roc_db_param');
mcm = require('mongo_connection_manager');
local handlers = {};
--{
local function get_criteria_json_str(fields, query_params)
local criteria = {};
for _, f in ipairs(fields) do -- {
if (query_params[f] ~= nil) then -- {
criteria[f] = query_params[f];
end -- }
end -- }
local i = 0;
local crit_str = '';
for field, value in pairs(criteria) do -- {
i = i + 1;
if (i>1) then -- {
crit_str = crit_str..', ';
end -- }
crit_str = crit_str..'{ '..'"data.'..field..'" : { "$regex" : "'..value..'", "$options" : "i" } }'
end -- }
if (i > 1) then -- {
crit_str = '{ "$and" : [ '..crit_str..' ] }';
elseif (i == 0) then -- } {
crit_str = '{}'
end -- }
return mongo.BSON(crit_str);
end
--}
-- {
local function get_criteria(fields, query_params)
local criteria = {};
for _, f in ipairs(fields) do -- {
if (query_params[f] ~= nil) then -- {
criteria[f] = query_params[f];
end -- }
end -- }
local i = 0;
local crit_array = {__array=true}
for field, value in pairs(criteria) do -- {
local _crit_str = mongo.BSON{};
local _field = 'data.'..field;
local _value = mongo.Regex(value, "i");
_crit_str:append(_field , _value)
i = i + 1;
crit_array[i] = _crit_str;
end -- }
local crit;
if (i>1) then -- {
local ab = {};
ab["$and"] = crit_array;
crit = mongo.BSON(ab);
elseif (i==1) then -- } {
crit = crit_array[1];
end --}
return crit;
end
-- }
-- {
handlers.list= function (self, db_handle, url_parts, query_params)
local fields = {"org_id", "org_name"};
local collection = db_handle:getCollection('companies');
local criteria = get_criteria(fields, query_params);
if (criteria == nil) then -- {
criteria = {};
end -- }
local cursor = collection:find(criteria);
local result = {};
local i = 0;
local err = nil;
for doc in cursor:iterator() do -- {
i = i + 1;
local record = {};
for name,value in pairs(doc.data) do -- {
if (type(value) == 'userdata') then -- {
record[name] = tostring(value);
else --} {
record[name] = value;
end -- }
end -- }
result[i] = record;
end -- }
local out = { companies = result };
return out, err;
end
-- }
--{
handlers.validateForAdd = function(self, db_handle, company)
if (company.org_id == nil or company.org_id == '') then -- {
return -1, "org_id is a manadatory field";
end -- }
if (company.org_name == nil or company.org_name == '') then -- {
return -1, "org_name is a manadatory field";
end -- }
local collection = db_handle:getCollection('companies');
local query = {};
query = { ["data.org_id"] = { ["$eq"] = company.org_id } };
doc, err = collection:findOne(query);
if (err ~= nil) then -- {
error(err);
return -1, err;
end -- }
--print(doc);
if (doc ~= nil) then -- {
return -1, "Record with id "..company.org_id.." already exists";
end -- }
return 0, nil;
end
--}
-- {
handlers.add= function (self, db_handle, url_parts, query_params, company)
local ret, errmsg = self:validateForAdd(db_handle, company);
--print(ret, errmsg);
if (ret ~= 0) then -- {
return { errcode=-1, message = errmsg }, 400;
end -- }
company.ts_cnt = 1;
local collection = db_handle:getCollection('companies');
local envelope = { data = company };
local flg, err = collection:insert(envelope)
--print(flg, err);
local error_code = nil;
local table_out = {};
if (flg ~= nil and flg == true ) then -- {
table_out = { message = "Record inserted"};
else -- } {
error_code = 400;
table_out = { errcode = -1, errmsg = err };
end --}
return table_out, error_code;
end
-- }
-- {
handlers.fetch= function (self, db_handle, url_parts, query_params)
local org_id = url_parts[2];
local err = 200;
local result = {};
if (org_id == nil or org_id == '') then -- {
err = 400;
result.msg = "org_id is mandatory"
result.errcode = -1;
return result, err;
end --}
local collection = db_handle:getCollection('companies');
local query = {};
query = { ["data.org_id"] = { ["$eq"] = org_id } };
local projection = { projection = { data = 1, _id = 0 } };
doc = collection:findOne(mongo.BSON(query), mongo.BSON(projection));
if (doc == nil) then -- {
return { errcode = 1403, errmsg = "Record not found" }, 400
else -- } {
return doc:value().data, nil;
end -- }
end
-- }
--{
handlers.validateForModify = function(self, db_handle, company)
if (company.org_id == nil or company.org_id == '') then -- {
return -1, "org_id is a manadatory field";
end -- }
if (company.org_name == nil or company.org_name == '') then -- {
return -1, "org_name is a manadatory field";
end -- }
if (company.ts_cnt == nil or company.ts_cnt == '') then -- {
return -1, "original ts_cnt should be submitted as part of the document during modify";
end -- }
local collection = db_handle:getCollection('companies');
local query = {};
query = { ["data.org_id"] = { ["$eq"] = company.org_id } };
doc, err = collection:findOne(query);
if (err ~= nil) then -- {
error(err);
return -1, err;
end -- }
--print(doc);
if (doc == nil) then -- {
return -1, "Record with id "..company.org_id.." does not exist";
end -- }
return 0, nil;
end
--}
-- {
handlers.modify = function (self, db_handle, url_parts, query_params, company)
local ret, errmsg = self:validateForModify(db_handle, company);
if (ret ~= 0) then -- {
return { message = errmsg }, 400;
end -- }
local collection = db_handle:getCollection('companies');
local old_ts_cnt = company.ts_cnt
local query_part1 = { ["data.org_id"] = { ["$eq"] = company.org_id } };
local query_part2 = { ["data.ts_cnt"] = { ["$eq"] = math.tointeger(old_ts_cnt) } };
local query = { ["$and"] = { __array=true, query_part1, query_part2 }};
company.ts_cnt = company.ts_cnt + 1;
old_doc, err = collection:findAndModify(mongo.BSON(query), {update = {data = company}});
local error_code = nil;
local table_out = {};
if (old_doc ~= nil and err == nil) then -- {
table_out = { message = "Record updated"};
else -- } {
error_code = 400;
if (err ~= nil) then -- {
table_out = { message = err };
else -- } {
table_out = { errcode = 1403,
message = "Record not found, org_id: "..company.org_id..", ts_cnt: "..math.tointeger(old_ts_cnt)} ;
end -- }
end --}
return table_out, error_code;
end
-- }
--{
handlers.validateForDelete = function(self, db_handle, company)
if (company.org_id == nil or company.org_id == '') then -- {
return nil, -1, "org_id is a manadatory field";
end -- }
if (company.ts_cnt == nil or company.ts_cnt == '') then -- {
return nil, -1, "original ts_cnt should be submitted as part of the document during modify";
end -- }
local collection = db_handle:getCollection('companies');
local query = {};
query = { ["data.org_id"] = { ["$eq"] = company.org_id } };
doc, err = collection:findOne(query);
if (err ~= nil) then -- {
error(err);
return nil, -1, err;
end -- }
print(doc);
if (doc == nil) then -- {
return nil, -1, "Record with id "..company.org_id.." does not exist";
elseif (doc:value().data.deleted ~= nil and doc:value().data.deleted == 1) then -- } {
return nil, -1, "Record with id "..company.org_id.." is already marked deleted";
elseif (doc:value().data.ts_cnt ~= company.ts_cnt) then -- } {
return nil, -1, "Sapshot of input record with id "..company.org_id.." is not current";
end -- }
return doc, 0, nil;
end
--}
-- {
handlers.delete = function (self, db_handle, url_parts, query_params, company)
if (company == nil) then -- {
return { errcode = -1, errmsg = "Company data not submitted for deletion" }
end -- }
local doc, ret, errmsg = self:validateForDelete(db_handle, company);
if (ret ~= 0) then -- {
print("HERERERER");
return { errcode = -1, message = errmsg }, 400;
end -- }
company = nil;
company = doc:value().data;
local collection = db_handle:getCollection('companies');
local old_ts_cnt = company.ts_cnt
local query_part1 = { ["data.org_id"] = { ["$eq"] = company.org_id } };
local query_part2 = { ["data.ts_cnt"] = { ["$eq"] = math.tointeger(old_ts_cnt) } };
local query = { ["$and"] = { __array=true, query_part1, query_part2 }};
company.ts_cnt = company.ts_cnt + 1;
if (company.deleted ~= nil) then -- {
company.deleted = nil;
end -- }
company.deleted = 1;
old_doc, err = collection:findAndModify(mongo.BSON(query), {update = {data = company}});
local error_code = nil;
local table_out = {};
if (old_doc ~= nil and err == nil) then -- {
table_out = { message = "Record logically deleted"};
else -- } {
error_code = 400;
if (err ~= nil) then -- {
table_out = { message = err };
else -- } {
table_out = { errcode = 1403,
message = "Record not found, org_id: "..company.org_id..", ts_cnt: "..math.tointeger(old_ts_cnt)} ;
end -- }
end --}
return table_out, error_code;
end
-- }
--{
handlers.validateForUndelete = function(self, db_handle, company)
if (company.org_id == nil or company.org_id == '') then -- {
return nil, -1, "org_id is a manadatory field";
end -- }
if (company.ts_cnt == nil or company.ts_cnt == '') then -- {
return nil, -1, "original ts_cnt should be submitted as part of the document during modify";
end -- }
local collection = db_handle:getCollection('companies');
local query = {};
query = { ["data.org_id"] = { ["$eq"] = company.org_id } };
doc, err = collection:findOne(query);
if (err ~= nil) then -- {
error(err);
return nil, -1, err;
end -- }
if (doc == nil) then -- {
return nil, -1, "Record with id "..company.org_id.." does not exist";
elseif (doc:value().data.deleted == nil or doc:value().data.deleted ~= 1) then -- } {
return nil, -1, "Record with id "..company.org_id.." is not marked as deleted";
elseif (doc:value().data.ts_cnt ~= company.ts_cnt) then -- } {
return nil, -1, "Sapshot of input record with id "..company.org_id.." is not current";
end -- }
return doc, 0, nil;
end
--}
-- {
handlers.undelete= function (self, db_handle, url_parts, query_params, company)
if (company == nil) then -- {
return { errcode = -1, errmsg = "Company data not submitted for deletion" }
end -- }
local doc, ret, errmsg = self:validateForUndelete(db_handle, company);
if (ret ~= 0) then -- {
return { message = errmsg }, 400;
end -- }
company = nil;
company = doc:value().data;
local collection = db_handle:getCollection('companies');
local old_ts_cnt = company.ts_cnt
local query_part1 = { ["data.org_id"] = { ["$eq"] = company.org_id } };
local query_part2 = { ["data.ts_cnt"] = { ["$eq"] = math.tointeger(old_ts_cnt) } };
local query = { ["$and"] = { __array=true, query_part1, query_part2 }};
company.ts_cnt = company.ts_cnt + 1;
if (company.deleted ~= nil) then -- {
company.deleted = nil;
end -- }
old_doc, err = collection:findAndModify(mongo.BSON(query), {update = {data = company}});
local error_code = nil;
local table_out = {};
if (old_doc ~= nil and err == nil) then -- {
table_out = { message = "Record undeleted"};
else -- } {
error_code = 400;
if (err ~= nil) then -- {
table_out = { message = err };
else -- } {
table_out = { errcode = 1403,
message = "Record not found, org_id: "..company.org_id..", ts_cnt: "..math.tointeger(old_ts_cnt)} ;
end -- }
end --}
return table_out, error_code;
end
-- }
--[[
--URL Standard followed in all BIOP API
--/Resource_name/<id>/<<verb>>
--Resource_name: Name of the set on which action is being performed
--<id>: Optional, if the action is being performed on a single entry in the set
-- id has to be supplied
--<<verb>>: Optional, can be supplied only if <id> is present
-- => 2nd parameter if present is always id
-- => 3rd parameter if present is always a verb, acting on the entry in the set
-- identified by <id>
--]]
-- {
local function deduce_method(request, num, url_parts, qp)
local method = request:get_method();
if (num == 1) then -- {
if (method ~= 'GET') then -- {
if (method == 'POST') then -- {
return 'add', nil;
elseif (method == 'PUT') then -- } {
return 'modify', nil;
elseif (method == 'DELETE') then -- } {
return 'delete', nil;
else -- } {
return nil, 'HTTP method '..method..' not supported';
end -- }
else --} {
return 'list', nil;
end -- }
elseif (num == 2) then --} {
if (method == 'GET') then --{
return 'fetch', nil;
elseif (method == 'PUT') then --} {
return 'modify', nil;
elseif (method == 'POST') then --} {
return 'add', nil;
elseif (method == 'DELETE') then --} {
return 'delete', nil;
else --} {
return nil, 'HTTP method '..method..' not supported';
end --}
elseif (num == 3) then --} {
if ((method ~= 'GET') and (method ~= 'PUT') and (method ~= 'POST') and (method ~= 'DELETE')) then -- {
return nil, 'HTTP method '..method..' not supported';
end -- }
return url_parts[3], nil;
else --} {
return nil, 'Invalid URL'..request:get_uri();
end --}
end
-- }
--{
local handle_request = function (request, response)
local flg, json_input = pcall(request.get_message_body_str, request);
local n, url_parts = urlp.parse_url_path(request);
local qp = urlp.get_qry_params(request);
local json_parser = cjson.new();
if (json_input == nil) then json_input = '{}'; end
local flg, table_input, err = pcall(json_parser.decode, json_input);
local func, err = deduce_method(request, n, url_parts, qp);
if (func == nil) then -- {
--print("in func == nil");
response:set_status(400);
response:set_chunked_trfencoding(true);
response:set_content_type("application/json");
response:send();
response:write('{ "error": '..'"'..err..'"'..' }');
return ;
end -- }
local db_handle = mcm.connect(roc_params.db_url, roc_params.db_schema_name, roc_params.db_user_id, roc_params.db_user_password);
h = handlers[func];
local table_output, err = h(handlers, db_handle, url_parts, qp, table_input);
if (err ~= nil) then -- {
if (err ~= 400 and err ~= 500) then -- {
error('Invalid error code returned '..err);
else -- } {
response:set_status(err);
end -- }
else -- } {
response:set_status(200);
end -- }
local flg, json_output, err = pcall(json_parser.encode, table_output);
if (json_output == nil or json_output == '') then --{
json_output = '{}';
end -- }
response:set_chunked_trfencoding(true);
response:set_content_type("application/json");
response:send();
response:write(json_output);
return ;
end
--}
local request = platform.get_http_request();
local response = platform.get_http_response();
return pcall(handle_request, request, response);
|
-- test Lua cqr library
------------------------------------------------------------------------------
package.path = ''
ok, complex = pcall(require,"complex")
package.cpath = "./?.so"
H=require"cqr" -- class of quaternions is named 'H' for Hamilton
print(H._VERSION,'\n')
-- generic constructor
local construct = function(class,...) return class.new(...) end
setmetatable(H,{__call = construct})
-- math functions globally visible
setmetatable(_ENV,{__index=math})
-- extend H by adding an 'eval' function if the complex library is standard
if complex and complex.new and complex.real and complex.imag then
H.eval = function(q,f)
local fz = complex[f]
if type(fz) ~= "function" then
error("Attempt to evaluate quaternion function '"..f..
"'\n but no function 'complex."..f.."' is available")
end
local fq = fz(complex.new(q:scalar(),#q:vector()))
return fq:real() + fq:imag()*q:axis()
end
end
failed, passed = {},{new=0, _VERSION=H._VERSION and 0}
tnum = 0
if H.__name == "quaternion" then passed.__name=tnum else failed.__name=tnum end
if H.__index == H then passed.__index=tnum else failed.__index=tnum end
local is = function(object,class)
return getmetatable(object)==class
end
-- Display multiplication table
local centerformat = function(s,n)
s = tostring(s)
local m = (n-#s)//2
local k = n-#s-m
return (' '):rep(k) ..s.. (' '):rep(m)
end
local multab = {}
for m=1,4 do
local mult = {}
for n=1,4 do
local a, b = {0,0,0,0}, {0,0,0,0}
a[m], b[n] = 1, 1
a,b = H(table.unpack(a)), H(table.unpack(b))
mult[n] = centerformat(a*b,6)
end
multab[m] = table.concat(mult)
end
multab = table.concat(multab,"\n")
print" Multiplication table\n"
print(multab); print()
correct_multab = [[
1.0 i j k
i -1.0 k -j
j -k -1.0 i
k j -i -1.0 ]]
if multab == correct_multab then
passed.__mul, passed.unpack, passed.__tostring = 0,0
else
print"Multiplication table prints wrong, should be:\n"
print(correct_multab)
end
local TOL = 1e-12
local function eq(x,y,tol)
return abs(x-y)<=(tol or TOL)
end
local function test(q,msg,...)
local w,x,y,z = q:unpack()
local W,X,Y,Z = ...
if is(W,H) then W,X,Y,Z = q:unpack() end
local result
if not (eq(w,W) and eq(x,X) and eq(y,Y) and eq(z,Z)) then
print(msg..(": wrong result; expected %s, got %s"):format(H(...),q))
result = failed
else
result = passed
end
tnum = tnum+1
for name in msg:gmatch"[_%a]+" do result[name] = tnum end
end
local function testreal(x,msg,y)
local result
if not eq(x,y) then
print(msg..(": wrong result; expected %s, got %s"):format(y,x))
result = failed
else
result = passed
end
for name in msg:gmatch"[_%a]+" do result[name] = tnum end
end
p = H(3,5,7,11)
if tostring(p)=="3.0+5.0i+7.0j+11.0k" then
passed.__tostring=0 else
failed.__tostring=0
end
v = p:vector(); vv = H(0,5,7,11)
if v==vv then t=passed else t=failed end
tnum = tnum+1; t.__eq, t.vector = tnum,tnum
testreal(#p,"__len",sqrt(204))
test(p*~p,"__mul,__bnot,normsq",H(204));
testreal(p..p,"__concat",204)
-- test specific functions using random arguments
p = H(random(),random(),random(),random())
q = H(random(),random(),random(),random())
print" Specific tests"
a = (q+5):log()
testreal(cos(p:arg())*#p,"arg,scalar,__add",p:scalar())
if a.eval then
test(a:exp(),"exp,eval",a:eval"exp")
test(a:log(),"log",a:eval"log")
test(a:sqrt(),"sqrt",a:eval"sqrt")
else
test(a:exp():log(),"exp,log",a)
test(a:log():exp(),"log,exp",a)
test(a:sqrt()^2,"sqrt",a)
end
test(q-p,"__sub,__unm",-(p-q))
w = v >> pi/6
test(w,"__shr,matrix",H(w:matrix()))
a,b = p:axis(), a:axis()
testreal(#a,'axis',1)
test(a,"angles",H(a:angles()))
testreal(H.slerpdist(a,b),"slerpdist,arg,__div",(a/b):arg())
test(p:root(5,3)^5,"root,__pow",p)
testreal(H.hlerpdist(a,-b),"hlerpdist",H.slerpdist(a,b))
test(H.hlerp(-p,q,8,5), "hlerp",H.slerp(p,q,8,5))
-- rotation, slerp tests are not random, though
w = H(0,0,0,1) >> pi/6
test(w*H(0,1,0,0)*~w,"__idiv",H(0,cos(pi/6),sin(pi/6),0))
test(H.slerp(H(0,1,0,0),H(0,0,1,0),0.7,0.3), "slerp",
H(0,cos(pi*0.3),sin(pi*0,3),0))
u,v = p:vector(), q:vector()
test(u//(v|u), "__bor", (#u/#v)*v)
print""
any = false
for k,v in pairs(H) do if failed[k] then
print(k.." FAILED in test #"..failed[k])
any=true
end end
if any then print"" else print"No test failed.\n"
end
any = false
for k,v in pairs(H) do if passed[k] and not failed[k] then
print(k.." passed in test #"..passed[k])
any=true
end end
if any then print"" end
any = false
for k,v in pairs(H) do if not (passed[k] or failed[k]) then
print(k.." was not tested")
any=true
end end
if any then print"" end
------------------------------------------------------------------------------
|
--
-- codeblocks_workspace.lua
-- Generate a Code::Blocks workspace.
-- Copyright (c) 2009 Jason Perkins and the Premake project
--
function premake.codeblocks.workspace(sln)
_p('<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>')
_p('<CodeBlocks_workspace_file>')
_p(1,'<Workspace title="%s">', sln.name)
for prj in premake.solution.eachproject(sln) do
local fname = path.join(path.getrelative(sln.location, prj.location), prj.name)
local active = iif(prj.project == sln.projects[1], ' active="1"', '')
_p(2,'<Project filename="%s.cbp"%s>', fname, active)
for _,dep in ipairs(premake.getdependencies(prj)) do
_p(3,'<Depends filename="%s.cbp" />', path.join(path.getrelative(sln.location, dep.location), dep.name))
end
_p(2,'</Project>')
end
_p(1,'</Workspace>')
_p('</CodeBlocks_workspace_file>')
end
|
do
local _ = {
['pipe-to-ground'] = {
icon = '__base__/graphics/icons/pipe-to-ground.png',
close_sound = 0,
fast_replaceable_group = 'pipe',
collision_box = {{-0.29, -0.29}, {0.29, 0.2}},
corpse = 'pipe-to-ground-remnants',
fluid_box = {
pipe_covers = {
north = {
layers = {
{
filename = '__base__/graphics/entity/pipe-covers/pipe-cover-north.png',
priority = 'extra-high',
height = 64,
width = 64,
hr_version = {
filename = '__base__/graphics/entity/pipe-covers/hr-pipe-cover-north.png',
priority = 'extra-high',
scale = 0.5,
height = 128,
width = 128
}
}, {
filename = '__base__/graphics/entity/pipe-covers/pipe-cover-north-shadow.png',
draw_as_shadow = true,
priority = 'extra-high',
height = 64,
width = 64,
hr_version = {
filename = '__base__/graphics/entity/pipe-covers/hr-pipe-cover-north-shadow.png',
draw_as_shadow = true,
priority = 'extra-high',
scale = 0.5,
height = 128,
width = 128
}
}
}
},
east = {
layers = {
{
filename = '__base__/graphics/entity/pipe-covers/pipe-cover-east.png',
priority = 'extra-high',
height = 64,
width = 64,
hr_version = {
filename = '__base__/graphics/entity/pipe-covers/hr-pipe-cover-east.png',
priority = 'extra-high',
scale = 0.5,
height = 128,
width = 128
}
}, {
filename = '__base__/graphics/entity/pipe-covers/pipe-cover-east-shadow.png',
draw_as_shadow = true,
priority = 'extra-high',
height = 64,
width = 64,
hr_version = {
filename = '__base__/graphics/entity/pipe-covers/hr-pipe-cover-east-shadow.png',
draw_as_shadow = true,
priority = 'extra-high',
scale = 0.5,
height = 128,
width = 128
}
}
}
},
west = {
layers = {
{
filename = '__base__/graphics/entity/pipe-covers/pipe-cover-west.png',
priority = 'extra-high',
height = 64,
width = 64,
hr_version = {
filename = '__base__/graphics/entity/pipe-covers/hr-pipe-cover-west.png',
priority = 'extra-high',
scale = 0.5,
height = 128,
width = 128
}
}, {
filename = '__base__/graphics/entity/pipe-covers/pipe-cover-west-shadow.png',
draw_as_shadow = true,
priority = 'extra-high',
height = 64,
width = 64,
hr_version = {
filename = '__base__/graphics/entity/pipe-covers/hr-pipe-cover-west-shadow.png',
draw_as_shadow = true,
priority = 'extra-high',
scale = 0.5,
height = 128,
width = 128
}
}
}
},
south = {
layers = {
{
filename = '__base__/graphics/entity/pipe-covers/pipe-cover-south.png',
priority = 'extra-high',
height = 64,
width = 64,
hr_version = {
filename = '__base__/graphics/entity/pipe-covers/hr-pipe-cover-south.png',
priority = 'extra-high',
scale = 0.5,
height = 128,
width = 128
}
}, {
filename = '__base__/graphics/entity/pipe-covers/pipe-cover-south-shadow.png',
draw_as_shadow = true,
priority = 'extra-high',
height = 64,
width = 64,
hr_version = {
filename = '__base__/graphics/entity/pipe-covers/hr-pipe-cover-south-shadow.png',
draw_as_shadow = true,
priority = 'extra-high',
scale = 0.5,
height = 128,
width = 128
}
}
}
}
},
base_area = 1,
pipe_connections = {{position = {0, -1}}, {max_underground_distance = 10, position = {0, 1}}}
},
dying_explosion = 'pipe-to-ground-explosion',
icon_mipmaps = 4,
resistances = {{percent = 80, type = 'fire'}, {percent = 40, type = 'impact'}},
vehicle_impact_sound = 0,
type = 'pipe-to-ground',
damaged_trigger_effect = {
damage_type_filters = 'fire',
entity_name = 'spark-explosion',
type = 'create-entity',
offsets = {{0, 1}},
offset_deviation = {{-0.5, -0.5}, {0.5, 0.5}}
},
pictures = {
right = {
filename = '__base__/graphics/entity/pipe-to-ground/pipe-to-ground-right.png',
priority = 'high',
height = 64,
width = 64,
hr_version = {
filename = '__base__/graphics/entity/pipe-to-ground/hr-pipe-to-ground-right.png',
priority = 'extra-high',
scale = 0.5,
height = 128,
width = 128
}
},
down = {
filename = '__base__/graphics/entity/pipe-to-ground/pipe-to-ground-down.png',
priority = 'high',
height = 64,
width = 64,
hr_version = {
filename = '__base__/graphics/entity/pipe-to-ground/hr-pipe-to-ground-down.png',
priority = 'extra-high',
scale = 0.5,
height = 128,
width = 128
}
},
up = {
filename = '__base__/graphics/entity/pipe-to-ground/pipe-to-ground-up.png',
priority = 'high',
height = 64,
width = 64,
hr_version = {
filename = '__base__/graphics/entity/pipe-to-ground/hr-pipe-to-ground-up.png',
priority = 'extra-high',
scale = 0.5,
height = 128,
width = 128
}
},
left = {
filename = '__base__/graphics/entity/pipe-to-ground/pipe-to-ground-left.png',
priority = 'high',
height = 64,
width = 64,
hr_version = {
filename = '__base__/graphics/entity/pipe-to-ground/hr-pipe-to-ground-left.png',
priority = 'extra-high',
scale = 0.5,
height = 128,
width = 128
}
}
},
flags = {'placeable-neutral', 'player-creation'},
working_sound = {
audible_distance_modifier = 0.3,
fade_out_ticks = 60,
fade_in_ticks = 4,
match_volume_to_activity = true,
sound = 0
},
max_health = 150,
name = 'pipe-to-ground',
selection_box = {{-0.5, -0.5}, {0.5, 0.5}},
open_sound = 0,
icon_size = 64,
minable = {mining_time = 0.1, result = 'pipe-to-ground'}
}
};
return _;
end
|
Test = require('connecttest')
require('cardinalities')
local events = require('events')
local mobile_session = require('mobile_session')
---------------------------------------------------------------------------------------------
-----------------------------Required Shared Libraries---------------------------------------
---------------------------------------------------------------------------------------------
local commonSteps = require('user_modules/shared_testcases/commonSteps')
local commonFunctions = require('user_modules/shared_testcases/commonFunctions')
local commonTestCases = require('user_modules/shared_testcases/commonTestCases')
require('user_modules/AppTypes')
local DEVICE_ID = config.deviceMAC
local DEVICE_NAME = "127.0.0.1"
---------------------------------------------------------------------------------------------
-------------------------------------------Common function-----------------------------------
---------------------------------------------------------------------------------------------
function BC_OnDeviceChosen_Notification(self, Description, Method, DeviceInfo)
self.hmiConnection:SendNotification("BasicCommunication.OnStartDeviceDiscovery")
EXPECT_HMICALL("BasicCommunication.UpdateDeviceList")
:Do(function(exp,data)
self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {})
if (Description == "Invalid Json") then
self.hmiConnection:Send('{"method";"BasicCommunication.OnDeviceChosen","params":{"deviceInfo":{"name":"127.0.0.1","id":"12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0"}},"jsonrpc":"2.0"}')
else
self.hmiConnection:SendNotification( Method, { deviceInfo = DeviceInfo })
end
end)
commonTestCases:DelayedExp(5000)
end
---------------------------------------------------------------------------------------------
-----------------------------------------I TEST BLOCK----------------------------------------
---------------Check notification BasicCommunication.OnDeviceChosen from HMI-----------------
---------------------------------------------------------------------------------------------
--Description: TC's checks processing
--HMI sends BasicCommunication.OnDeviceChosen notification with positive case and (full deviceInfo)
--HMI sends BasicCommunication.OnDeviceChosen notification with Missing deviceInfo
--HMI sends BasicCommunication.OnDeviceChosen notification with Missing deviceID
--HMI sends BasicCommunication.OnDeviceChosen notification with Missing DeviceName
--HMI sends BasicCommunication.OnDeviceChosen notification with Missing ID and Name
--HMI sends BasicCommunication.OnDeviceChosen notification with Missing All Parameters
--HMI sends BasicCommunication.OnDeviceChosen notification with Missing Method
--HMI sends BasicCommunication.OnDeviceChosen notification with Empty deviceInfo
--HMI sends BasicCommunication.OnDeviceChosen notification with Empty deviceID
--HMI sends BasicCommunication.OnDeviceChosen notification with WrongType deviceInfo
--HMI sends BasicCommunication.OnDeviceChosen notification with WrongType deviceID
--HMI sends BasicCommunication.OnDeviceChosen notification with WrongType deviceName
--HMI sends BasicCommunication.OnDeviceChosen notification with WrongType ID and Name
--HMI sends BasicCommunication.OnDeviceChosen notification with Invalid Json
--Requirement id in JAMA:
--APPLINK-24441: https://adc.luxoft.com/svn/APPLINK/doc/technical/HOW-TOs_and_Guidelines/FORD.SmartDeviceLink.SDL_Integration_Guidelines.docx (6.10)
----------------------------------------------------------------------------------------------
local TestData = {
{description = "Positive Case", method = "BasicCommunication.OnDeviceChosen", deviceInfo = {id = DEVICE_ID, name = DEVICE_NAME} },
{description = "Missing deviceInfo", method = "BasicCommunication.OnDeviceChosen", deviceInfo = nil },
{description = "Missing deviceID", method = "BasicCommunication.OnDeviceChosen", deviceInfo = {id = nil, name = DEVICE_NAME} },
{description = "Missing DeviceName", method = "BasicCommunication.OnDeviceChosen", deviceInfo = {id = DEVICE_ID, name = nil} },
{description = "Missing ID and Name", method = "BasicCommunication.OnDeviceChosen", deviceInfo = {id = nil, name = nil} },
{description = "Missing All Parameters", method = nil, deviceInfo = nil },
{description = "Missing Method", method = nil, deviceInfo = {id = DEVICE_ID, name = DEVICE_NAME} },
{description = "Empty deviceInfo", method = "BasicCommunication.OnDeviceChosen", deviceInfo = {} },
{description = "Empty deviceID", method = "BasicCommunication.OnDeviceChosen", deviceInfo = {name = DEVICE_NAME} },
{description = "Empty deviceName", method = "BasicCommunication.OnDeviceChosen", deviceInfo = {id = DEVICE_ID} },
{description = "WrongType deviceInfo", method = "BasicCommunication.OnDeviceChosen", deviceInfo = 1234 },
{description = "WrongType deviceID", method = "BasicCommunication.OnDeviceChosen", deviceInfo = {id = true, name = DEVICE_NAME} },
{description = "WrongType deviceName", method = "BasicCommunication.OnDeviceChosen", deviceInfo = {id = DEVICE_ID, name = {1234}} },
{description = "WrongType ID and Name", method = "BasicCommunication.OnDeviceChosen", deviceInfo = {id = 1234, name = true} },
{description = "Invalid Json", _, _, }
}
----------------------------------------------------------------------------------------------
-- commonSteps:ActivationApp()
--Main executing
for i=1, #TestData do
--Print new line to separate new test cases group
commonFunctions:newTestCasesGroup("-----------------------I." ..tostring(i).." [" ..TestData[i].description .. "]------------------------------")
Test["BC_" .. TestData[i].description] = function(self)
BC_OnDeviceChosen_Notification(self, TestData[i].description, TestData[i].method, TestData[i].deviceInfo)
end
end |
return {'kedive','kedde'} |
Livre = "Livre"
Ocupado = "Ocupado"
Reservado = "Reser."
Estado_nao_reconhecido = "O estado que voce escreveu nao e nenhum dos seguintes: LIVRE, OCUPADO, RESERVADO"
Mesa_nao_existe = "A mesa que voce tentou acessar nao existe"
Pedir_a_hora_da_reserva = "Diga o horario da reserva"
|
object_tangible_quest_luilris_mushrooms = object_tangible_quest_shared_luilris_mushrooms:new {
}
ObjectTemplates:addTemplate(object_tangible_quest_luilris_mushrooms, "object/tangible/quest/luilris_mushrooms.iff")
|
-- this is a simple demo module for reading
-- /writing files with strings.
local fs = {}
function fs.readstr(filename)
local f = io.open(filename, "rb")
local content = f:read("*all")
f:close()
return content
end
-- r = read
-- w = write or create
-- a = append
-- r+ = read/write
-- w+ = overwrite with r/w permissions
-- a+ = r/w append or create
function fs.writestr(filename, string)
local f = io.open(filename, "w+")
io.output(f)
io.write(string)
io.close(f)
end
return fs
|
--[[
desc:扑克枚举
auth:Caorl Luo
]]
local class = require("class")
local gameEnum = require("game.enum")
---@class pokerEnum:gameEnum
local enum = class(gameEnum)
local this = enum
---构造
function enum:ctor()
end
return enum |
-- vim: ts=4:sw=4:expandtab
local cosock = require "cosock"
local classify = require "classify"
local Timer = require "timer"
local Parent = classify.single({
_init = function(_, self, name, latitude, longitude, height)
self.name = name
self.latitude = latitude
self.longitude = longitude
self.height = height
self.timer = Timer(name, latitude, longitude, height)
self.child = {}
self.angle_methods = {}
end,
add = function(self, child)
self.child[child] = true
self.angle_methods[child.angle] = child.method
self.timer:stop()
self.timer = Timer(self.name, self.latitude, self.longitude, self.height, self.angle_methods)
end,
remove = function(self, child)
self.child[child] = nil
self.angle_methods[child.angle] = nil
self.timer:stop()
self.timer = Timer(self.name, self.latitude, self.longitude, self.height, self.angle_methods)
end,
})
local Child = classify.single({
_init = function(_, self, parent, angle)
self.parent = parent
self.angle = angle
self.method = function(bool)
print(angle, bool)
end
parent:add(self)
parent.timer:refresh(self.method)
end
})
local parent = Parent("LA", 34.052235, -118.243683, 0)
for angle, _ in pairs(Timer.angles) do
Child(parent, angle)
end
for _, angle in ipairs{-90, -60, -45, -30, 30, 45, 60, 90} do
Child(parent, angle)
end
cosock.run()
|
local t = Def.ActorFrame {};
local txc = THEME:GetMetric ('EditableColors','FontColor');
local gc = Var('GameCommand');
-- menu selections
t[#t+1] = Def.ActorFrame {
LoadFont("Common Normal") .. {
Text=THEME:GetString('ScreenTitleMenu',gc:GetText());
InitCommand=cmd(diffuse,color(txc);y,60;horizalign,right);
GainFocusCommand=cmd(decelerate,0.1;x,-10);
LoseFocusCommand=cmd(decelerate,0.1;x,10);
};
};
return t |
namespace "standard"
local DebugHand = require "app.debug.hand"
local split = {}
local split2
local ui3
function split.makeSplitScreen(spec, force2d)
if force2d then
if not split2 then split2 = require "ent.ui2.split" end
return split2.SplitScreenEnt(spec)
else
if not ui3 then ui3 = require "ent.ui3" end
local pages = spec.pages or {}
local pagesn = #spec.pages
local e = Ent{}
local hand = ui3.Hand{doHover=true}:insert(e)
for i,v in ipairs(spec.pages) do
v.hand = hand
v.surface3 = ui3.SurfaceEnt{}
v:insert(e)
local oneRotate = math.pi/3 -- Hand tune. TODO try with more screen sizes
local rotateIndexOffset = math.floor(pagesn/2) - 2.5
local offset = Loc(vec3((i*2-2-pagesn/2)*1,0,0), quat.from_angle_axis(-(i + rotateIndexOffset)*oneRotate, 0,1,0))
v.surface3.transform = v.surface3.transform:compose(offset)
v.surface3:insert(v)
end
return e
end
end
return split |
-------------------------------------------------------------------------------
-- Module Declaration
local mod, CL = BigWigs:NewBoss("Exarch Maladaar", 558, 524)
if not mod then return end
mod:RegisterEnableMob(18373)
-- mod.engageId = 1889 -- no boss frames
-- mod.respawnTime = 0 -- resets, doesn't respawn
-------------------------------------------------------------------------------
-- Localization
local L = mod:GetLocale()
if L then
L.avatar = -5046 -- Avatar of the Martyred
L.avatar_desc = -5045 -- EJ entry of the summoning spell, has better description than that of the actual spell
L.avatar_icon = -5045
end
-------------------------------------------------------------------------------
-- Initialization
function mod:GetOptions()
return {
32346, -- Stolen Soul
"avatar",
}
end
function mod:OnBossEnable()
self:RegisterUnitEvent("UNIT_HEALTH_FREQUENT", nil, "target", "focus")
self:Log("SPELL_AURA_APPLIED", "StolenSoul", 32346)
self:Log("SPELL_CAST_SUCCESS", "AvatarOfTheMartyred", 32424)
self:Death("Win", 18373)
end
-------------------------------------------------------------------------------
-- Event Handlers
function mod:StolenSoul(args)
self:TargetMessage(args.spellId, args.destName, "orange")
end
function mod:AvatarOfTheMartyred(args)
self:Message("avatar", "red", "Info", CL.spawned:format(self:SpellName(L.avatar)), args.spellId)
end
function mod:UNIT_HEALTH_FREQUENT(event, unit)
if self:MobId(UnitGUID(unit)) ~= 18373 then return end
local hp = UnitHealth(unit) / UnitHealthMax(unit) * 100
if hp < 30 then
self:UnregisterUnitEvent(event, "target", "focus")
self:Message("avatar", "yellow", nil, CL.soon:format(CL.spawning:format(self:SpellName(L.avatar))), 32424)
end
end
|
ITEM.name = "Desert Eagle"
ITEM.desc = "A slow yet powerful firearm that fires .50 AE Rounds"
ITEM.model = "models/weapons/w_stalker_deagle.mdl"
ITEM.class = "stalker_deagle"
ITEM.weaponCategory = "sidearm"
ITEM.width = 2
ITEM.height = 1
ITEM.price = 300 |
-- **************************************************************************
-- * TitanXP.lua
-- *
-- * By: TitanMod, Dark Imakuni, Adsertor and the Titan Panel Development Team
-- **************************************************************************
-- ******************************** Constants *******************************
local TITAN_XP_ID = "XP";
local _G = getfenv(0);
local TITAN_XP_FREQUENCY = 1;
local updateTable = {TITAN_XP_ID, TITAN_PANEL_UPDATE_ALL};
-- ******************************** Variables *******************************
local TitanPanelXPButton_ButtonAdded = nil;
local found = nil;
local lastMobXP, lastXP, XPGain = 0, 0, 0
local L = LibStub("AceLocale-3.0"):GetLocale("Titan", true)
-- ******************************** Functions *******************************
--[[
Add commas or period in the value given as needed
--]]
local function comma_value(amount)
local formatted = amount
local k
local sep = (TitanGetVar(TITAN_XP_ID, "UseSeperatorComma") and "UseComma" or "UsePeriod")
while true do
if sep == "UseComma" then formatted, k = string.gsub(formatted, "^(-?%d+)(%d%d%d)", '%1,%2') end
if sep == "UsePeriod" then formatted, k = string.gsub(formatted, "^(-?%d+)(%d%d%d)", '%1.%2') end
if (k==0) then
break
end
end
return formatted
end
-- **************************************************************************
-- NAME : TitanPanelXP_OnLoad()
-- DESC : Registers the plugin upon it loading
-- **************************************************************************
function TitanPanelXPButton_OnLoad(self)
self.registry = {
id = TITAN_XP_ID,
category = "Built-ins",
version = TITAN_VERSION,
menuText = L["TITAN_XP_MENU_TEXT"],
buttonTextFunction = "TitanPanelXPButton_GetButtonText",
tooltipTitle = L["TITAN_XP_TOOLTIP"],
tooltipTextFunction = "TitanPanelXPButton_GetTooltipText",
iconWidth = 16,
controlVariables = {
ShowIcon = true,
ShowLabelText = true,
ShowRegularText = false,
ShowColoredText = false,
DisplayOnRightSide = false
},
savedVariables = {
DisplayType = "ShowXPPerHourSession",
ShowIcon = 1,
ShowLabelText = 1,
ShowSimpleRested = false,
ShowSimpleToLevel = false,
ShowSimpleNumOfKills = false,
ShowSimpleNumOfGains = false,
UseSeperatorComma = true,
UseSeperatorPeriod = false,
}
};
self:RegisterEvent("PLAYER_ENTERING_WORLD");
self:RegisterEvent("TIME_PLAYED_MSG");
self:RegisterEvent("PLAYER_XP_UPDATE");
self:RegisterEvent("PLAYER_LEVEL_UP");
self:RegisterEvent("CHAT_MSG_COMBAT_XP_GAIN");
end
-- **************************************************************************
-- NAME : TitanPanelXPButton_OnShow()
-- DESC : Display the icon in the bar
-- NOTE : For a lack of better check at the moment TitanPanel_ButtonAdded
-- is a global variable set to true only when a button has just been
-- added to the panel
-- **************************************************************************
function TitanPanelXPButton_OnShow()
TitanPanelXPButton_SetIcon();
found = nil;
if not TitanPanelXPButton_ButtonAdded then
if not TitanAllGetVar("Silenced") then
RequestTimePlayed();
end
TitanPanelXPButton_ButtonAdded = true;
end
end
function TitanPanelXPButton_OnHide()
if (TitanPanelSettings) then
for i = 1, table.getn(TitanPanelSettings.Buttons) do
if(TitanPanelSettings.Buttons[i] == TITAN_XP_ID) then
found = true;
end
end
if not found then
TitanPanelXPButton_ButtonAdded = nil
end
end
end
-- **************************************************************************
-- NAME : TitanPanelXPButton_OnEvent(arg1, arg2)
-- DESC : Parse events registered to addon and act on them
-- VARS : arg1 = <research> , arg2 = <research>
-- **************************************************************************
function TitanPanelXPButton_OnEvent(self, event, a1, a2, ...)
if (event == "PLAYER_ENTERING_WORLD") then
if (not self.sessionTime) then
self.sessionTime = time();
end
if (not self.initXP) then
self.initXP = UnitXP("player");
self.accumXP = 0;
self.sessionXP = 0;
self.startSessionTime = time();
lastXP = self.initXP;
end
elseif (event == "TIME_PLAYED_MSG") then
-- Remember play time
self.totalTime = a1;
self.levelTime = a2;
elseif (event == "PLAYER_XP_UPDATE") then
if (not self.initXP) then
self.initXP = UnitXP("player");
self.accumXP = 0;
self.sessionXP = 0;
self.startSessionTime = time();
end
XPGain = UnitXP("player") - lastXP;
lastXP = UnitXP("player");
if XPGain < 0 then XPGain = 0 end
self.sessionXP = UnitXP("player") - self.initXP + self.accumXP;
elseif (event == "PLAYER_LEVEL_UP") then
self.levelTime = 0;
self.accumXP = self.accumXP + UnitXPMax("player") - self.initXP;
self.initXP = 0;
elseif (event == "CHAT_MSG_COMBAT_XP_GAIN") then
local _,_,_,killXP = string.find(a1, "^"..L["TITAN_XP_GAIN_PATTERN"])
if killXP then lastMobXP = tonumber(killXP) end
if lastMobXP < 0 then lastMobXP = 0 end
end
end
-- **************************************************************************
-- NAME : TitanPanelXPButton_OnUpdate(elapsed)
-- DESC : Update button data
-- VARS : elapsed = <research>
-- **************************************************************************
function TitanPanelXPButton_OnUpdate(self, elapsed)
TITAN_XP_FREQUENCY = TITAN_XP_FREQUENCY - elapsed;
if (TITAN_XP_FREQUENCY <=0) then
TITAN_XP_FREQUENCY = 1;
TitanPanelPluginHandle_OnUpdate(updateTable)
end
if (self.totalTime) then
self.totalTime = self.totalTime + elapsed;
self.levelTime = self.levelTime + elapsed;
end
end
-- **************************************************************************
-- NAME : TitanPanelXPButton_GetButtonText(id)
-- DESC : Calculate time based logic for button text
-- VARS : id = button ID
-- NOTE : Because the panel gets loaded before XP we need to check whether
-- the variables have been initialized and take action if they haven't
-- **************************************************************************
function TitanPanelXPButton_GetButtonText(id)
if (TitanPanelXPButton.startSessionTime == nil) then
return;
end
local button, id = TitanUtils_GetButton(id, true);
local totalXP = UnitXPMax("player");
local currentXP = UnitXP("player");
local toLevelXP = totalXP - currentXP;
local sessionXP = button.sessionXP;
local xpPerHour, xpPerHourText, timeToLevel, timeToLevelText;
local sessionTime = time() - TitanPanelXPButton.startSessionTime;
local levelTime = TitanPanelXPButton.levelTime;
local numofkills, numofgains;
if lastMobXP ~= 0 then numofkills = math.ceil(toLevelXP / lastMobXP) else numofkills = _G["UNKNOWN"] end
if XPGain ~= 0 then numofgains = math.ceil(toLevelXP / XPGain) else numofgains = _G["UNKNOWN"] end
if (levelTime) then
if (TitanGetVar(TITAN_XP_ID, "DisplayType") == "ShowXPPerHourSession") then
xpPerHour = sessionXP / sessionTime * 3600;
-- timeToLevel = TitanUtils_Ternary((sessionXP == 0), -1, toLevelXP / sessionXP * sessionTime);
timeToLevel = (sessionXP == 0) and -1 or toLevelXP / sessionXP * sessionTime;
xpPerHourText = comma_value(math.floor(xpPerHour+0.5));
timeToLevelText = TitanUtils_GetEstTimeText(timeToLevel);
return L["TITAN_XP_BUTTON_LABEL_XPHR_SESSION"], TitanUtils_GetHighlightText(xpPerHourText),
L["TITAN_XP_BUTTON_LABEL_TOLEVEL_TIME_LEVEL"], TitanUtils_GetHighlightText(timeToLevelText);
elseif (TitanGetVar(TITAN_XP_ID,"DisplayType") == "ShowXPPerHourLevel") then
xpPerHour = currentXP / levelTime * 3600;
-- timeToLevel = TitanUtils_Ternary((currentXP == 0), -1, toLevelXP / currentXP * levelTime);
timeToLevel = (currentXP == 0) and -1 or toLevelXP / currentXP * levelTime;
xpPerHourText = comma_value(math.floor(xpPerHour+0.5));
timeToLevelText = TitanUtils_GetEstTimeText(timeToLevel);
return L["TITAN_XP_BUTTON_LABEL_XPHR_LEVEL"], TitanUtils_GetHighlightText(xpPerHourText),
L["TITAN_XP_BUTTON_LABEL_TOLEVEL_TIME_LEVEL"], TitanUtils_GetHighlightText(timeToLevelText);
elseif (TitanGetVar(TITAN_XP_ID,"DisplayType") == "ShowSessionTime") then
return L["TITAN_XP_BUTTON_LABEL_SESSION_TIME"], TitanUtils_GetHighlightText(TitanUtils_GetAbbrTimeText(sessionTime));
elseif (TitanGetVar(TITAN_XP_ID,"DisplayType") == "ShowXPSimple") then
local toLevelXPText = "";
local rest = "";
local labelrested = "";
local labeltolevel = "";
local labelnumofkills = "";
local labelnumofgains = "";
local percent = floor(10000*(currentXP/totalXP)+0.5)/100;
if TitanGetVar(TITAN_XP_ID,"ShowSimpleToLevel") then
toLevelXPText = TitanUtils_GetColoredText(format(L["TITAN_XP_FORMAT"], comma_value(math.floor(toLevelXP+0.5))), _G["GREEN_FONT_COLOR"]);
labeltolevel = L["TITAN_XP_XPTOLEVELUP"];
end
if TitanGetVar(TITAN_XP_ID,"ShowSimpleRested") then
rest = TitanUtils_GetColoredText(comma_value(GetXPExhaustion()==nil and "0" or GetXPExhaustion()),{r=0.44, g=0.69, b=0.94});
labelrested = L["TITAN_XP_TOTAL_RESTED"];
end
if TitanGetVar(TITAN_XP_ID,"ShowSimpleNumOfKills") then
numofkills = TitanUtils_GetColoredText(comma_value(numofkills), {r=0.24, g=0.7, b=0.44})
labelnumofkills = L["TITAN_XP_KILLS_LABEL_SHORT"];
else
numofkills = ""
end
if TitanGetVar(TITAN_XP_ID,"ShowSimpleNumOfGains") then
numofgains = TitanUtils_GetColoredText(comma_value(numofgains), {r=1, g=0.49, b=0.04})
labelnumofgains = L["TITAN_XP_XPGAINS_LABEL_SHORT"];
else
numofgains = ""
end
if TitanGetVar(TITAN_XP_ID,"ShowSimpleNumOfGains") then
return L["TITAN_XP_LEVEL_COMPLETE"], TitanUtils_GetHighlightText(percent .. "%"), labelrested, rest , labeltolevel, toLevelXPText, labelnumofgains, numofgains
else
return L["TITAN_XP_LEVEL_COMPLETE"], TitanUtils_GetHighlightText(percent .. "%"), labelrested, rest , labeltolevel, toLevelXPText, labelnumofkills, numofkills
end
end
else
return "("..L["TITAN_XP_UPDATE_PENDING"]..")";
end
end
-- **************************************************************************
-- NAME : TitanPanelXPButton_GetTooltipText()
-- DESC : Display tooltip text
-- **************************************************************************
function TitanPanelXPButton_GetTooltipText()
local totalTime = TitanPanelXPButton.totalTime;
local sessionTime = time() - TitanPanelXPButton.startSessionTime;
local levelTime = TitanPanelXPButton.levelTime;
-- failsafe to ensure that an error wont be returned
if not levelTime then return end
local totalXP = UnitXPMax("player");
local currentXP = UnitXP("player");
local toLevelXP = totalXP - currentXP;
local currentXPPercent = currentXP / totalXP * 100;
local toLevelXPPercent = toLevelXP / totalXP * 100;
local xpPerHourThisLevel = currentXP / levelTime * 3600;
local xpPerHourThisSession = TitanPanelXPButton.sessionXP / sessionTime * 3600;
local estTimeToLevelThisLevel = TitanUtils_Ternary((currentXP == 0), -1, toLevelXP / (max(currentXP,1)) * levelTime);
local estTimeToLevelThisSession = 0;
if TitanPanelXPButton.sessionXP > 0 then
estTimeToLevelThisSession = TitanUtils_Ternary((TitanPanelXPButton.sessionXP == 0), -1, toLevelXP / TitanPanelXPButton.sessionXP * sessionTime);
end
local numofkills, numofgains;
if lastMobXP ~= 0 then numofkills = math.ceil(toLevelXP / lastMobXP) else numofkills = _G["UNKNOWN"] end
if XPGain ~= 0 then numofgains = math.ceil(toLevelXP / XPGain) else numofgains = _G["UNKNOWN"] end
return ""..
L["TITAN_XP_TOOLTIP_TOTAL_TIME"].."\t"..TitanUtils_GetHighlightText(TitanUtils_GetAbbrTimeText(totalTime)).."\n"..
L["TITAN_XP_TOOLTIP_LEVEL_TIME"].."\t"..TitanUtils_GetHighlightText(TitanUtils_GetAbbrTimeText(levelTime)).."\n"..
L["TITAN_XP_TOOLTIP_SESSION_TIME"].."\t"..TitanUtils_GetHighlightText(TitanUtils_GetAbbrTimeText(sessionTime)).."\n"..
"\n"..
L["TITAN_XP_TOOLTIP_TOTAL_XP"].."\t"..TitanUtils_GetHighlightText(comma_value(totalXP)).."\n"..
L["TITAN_XP_TOTAL_RESTED"].."\t"..TitanUtils_GetHighlightText(comma_value(GetXPExhaustion()==nil and "0" or GetXPExhaustion())).."\n"..
L["TITAN_XP_TOOLTIP_LEVEL_XP"].."\t"..TitanUtils_GetHighlightText(comma_value(currentXP).." "..format(L["TITAN_XP_PERCENT_FORMAT"], currentXPPercent)).."\n"..
L["TITAN_XP_TOOLTIP_TOLEVEL_XP"].."\t"..TitanUtils_GetHighlightText(comma_value(toLevelXP).." "..format(L["TITAN_XP_PERCENT_FORMAT"], toLevelXPPercent)).."\n"..
L["TITAN_XP_TOOLTIP_SESSION_XP"].."\t"..TitanUtils_GetHighlightText(comma_value(TitanPanelXPButton.sessionXP)).."\n"..
format(L["TITAN_XP_KILLS_LABEL"], comma_value(lastMobXP)).."\t"..TitanUtils_GetHighlightText(comma_value(numofkills)).."\n"..
format(L["TITAN_XP_XPGAINS_LABEL"], comma_value(XPGain)).."\t"..TitanUtils_GetHighlightText(comma_value(numofgains)).."\n"..
"\n"..
L["TITAN_XP_TOOLTIP_XPHR_LEVEL"].."\t"..TitanUtils_GetHighlightText(format(L["TITAN_XP_FORMAT"], comma_value(math.floor(xpPerHourThisLevel+0.5)))).."\n"..
L["TITAN_XP_TOOLTIP_XPHR_SESSION"].."\t"..TitanUtils_GetHighlightText(format(L["TITAN_XP_FORMAT"], comma_value(math.floor(xpPerHourThisSession+0.5)))).."\n"..
L["TITAN_XP_TOOLTIP_TOLEVEL_LEVEL"].."\t"..TitanUtils_GetHighlightText(TitanUtils_GetAbbrTimeText(estTimeToLevelThisLevel)).."\n"..
L["TITAN_XP_TOOLTIP_TOLEVEL_SESSION"].."\t"..TitanUtils_GetHighlightText(TitanUtils_GetAbbrTimeText(estTimeToLevelThisSession));
end
-- **************************************************************************
-- NAME : TitanPanelXPButton_SetIcon()
-- DESC : Define icon based on faction
-- **************************************************************************
function TitanPanelXPButton_SetIcon()
local icon = TitanPanelXPButtonIcon;
local factionGroup, factionName = UnitFactionGroup("player");
if (factionGroup == "Alliance") then
icon:SetTexture("Interface\\TargetingFrame\\UI-PVP-Alliance");
icon:SetTexCoord(0.046875, 0.609375, 0.03125, 0.59375);
elseif (factionGroup == "Horde") then
icon:SetTexture("Interface\\TargetingFrame\\UI-PVP-Horde");
icon:SetTexCoord(0.046875, 0.609375, 0.015625, 0.578125);
else
icon:SetTexture("Interface\\TargetingFrame\\UI-PVP-FFA");
icon:SetTexCoord(0.046875, 0.609375, 0.03125, 0.59375);
end
end
local function Seperator(chosen)
--[[
TitanDebug("Sep: "
..(chosen or "?").." "
)
--]]
if chosen == "UseSeperatorComma" then
TitanSetVar(TITAN_XP_ID, "UseSeperatorComma", true);
TitanSetVar(TITAN_XP_ID, "UseSeperatorPeriod", false);
end
if chosen == "UseSeperatorPeriod" then
TitanSetVar(TITAN_XP_ID, "UseSeperatorComma", false);
TitanSetVar(TITAN_XP_ID, "UseSeperatorPeriod", true);
end
TitanPanelButton_UpdateButton(TITAN_XP_ID);
end
-- **************************************************************************
-- NAME : TitanPanelRightClickMenu_PrepareXPMenu()
-- DESC : Display rightclick menu options
-- **************************************************************************
function TitanPanelRightClickMenu_PrepareXPMenu()
local info = {};
if L_UIDROPDOWNMENU_MENU_LEVEL == 2 then
TitanPanelRightClickMenu_AddTitle(L["TITAN_XP_MENU_SIMPLE_BUTTON_TITLE"], 2);
info = {};
info.text = L["TITAN_XP_MENU_SIMPLE_BUTTON_RESTED"];
info.func = function() TitanPanelRightClickMenu_ToggleVar({TITAN_XP_ID, "ShowSimpleRested"}) end
info.checked = TitanUtils_Ternary(TitanGetVar(TITAN_XP_ID, "ShowSimpleRested"), 1, nil);
info.keepShownOnClick = 1;
L_UIDropDownMenu_AddButton(info, 2);
info = {};
info.text = L["TITAN_XP_MENU_SIMPLE_BUTTON_TOLEVELUP"];
info.func = function() TitanPanelRightClickMenu_ToggleVar({TITAN_XP_ID, "ShowSimpleToLevel"}) end
info.checked = TitanUtils_Ternary(TitanGetVar(TITAN_XP_ID, "ShowSimpleToLevel"), 1, nil);
info.keepShownOnClick = 1;
L_UIDropDownMenu_AddButton(info, 2);
info = {};
info.text = L["TITAN_XP_MENU_SIMPLE_BUTTON_KILLS"];
info.func = function() TitanSetVar(TITAN_XP_ID, "ShowSimpleNumOfKills", true) TitanSetVar(TITAN_XP_ID, "ShowSimpleNumOfGains", false) end
info.checked = TitanUtils_Ternary(TitanGetVar(TITAN_XP_ID, "ShowSimpleNumOfKills"), 1, nil);
L_UIDropDownMenu_AddButton(info, 2);
info = {};
info.text = L["TITAN_XP_MENU_SIMPLE_BUTTON_XPGAIN"];
info.func = function() TitanSetVar(TITAN_XP_ID, "ShowSimpleNumOfGains", true) TitanSetVar(TITAN_XP_ID, "ShowSimpleNumOfKills", false) end
info.checked = TitanUtils_Ternary(TitanGetVar(TITAN_XP_ID, "ShowSimpleNumOfGains"), 1, nil);
L_UIDropDownMenu_AddButton(info, 2);
else
TitanPanelRightClickMenu_AddTitle(TitanPlugins[TITAN_XP_ID].menuText);
info = {};
info.text = L["TITAN_XP_MENU_SHOW_XPHR_THIS_SESSION"];
info.func = TitanPanelXPButton_ShowXPPerHourSession;
info.checked = TitanUtils_Ternary("ShowXPPerHourSession" == TitanGetVar(TITAN_XP_ID, "DisplayType"), 1, nil);
L_UIDropDownMenu_AddButton(info);
info = {};
info.text = L["TITAN_XP_MENU_SHOW_XPHR_THIS_LEVEL"];
info.func = TitanPanelXPButton_ShowXPPerHourLevel;
info.checked = TitanUtils_Ternary("ShowXPPerHourLevel" == TitanGetVar(TITAN_XP_ID, "DisplayType"), 1, nil);
L_UIDropDownMenu_AddButton(info);
info = {};
info.text = L["TITAN_XP_MENU_SHOW_SESSION_TIME"];
info.func = TitanPanelXPButton_ShowSessionTime;
info.checked = TitanUtils_Ternary("ShowSessionTime" == TitanGetVar(TITAN_XP_ID, "DisplayType"), 1, nil);
L_UIDropDownMenu_AddButton(info);
info = {};
info.text = L["TITAN_XP_MENU_SHOW_RESTED_TOLEVELUP"];
info.func = TitanPanelXPButton_ShowXPSimple;
info.hasArrow = 1;
info.checked = TitanUtils_Ternary("ShowXPSimple" == TitanGetVar(TITAN_XP_ID, "DisplayType"), 1, nil);
L_UIDropDownMenu_AddButton(info);
TitanPanelRightClickMenu_AddSpacer();
TitanPanelRightClickMenu_AddCommand(L["TITAN_XP_MENU_RESET_SESSION"], TITAN_XP_ID, "TitanPanelXPButton_ResetSession");
TitanPanelRightClickMenu_AddCommand(L["TITAN_XP_MENU_REFRESH_PLAYED"], TITAN_XP_ID, "TitanPanelXPButton_RefreshPlayed");
TitanPanelRightClickMenu_AddSpacer();
TitanPanelRightClickMenu_AddToggleIcon(TITAN_XP_ID);
TitanPanelRightClickMenu_AddToggleLabelText(TITAN_XP_ID);
TitanPanelRightClickMenu_AddSpacer();
local info = {};
info.text = L["TITAN_USE_COMMA"];
info.checked = TitanGetVar(TITAN_XP_ID, "UseSeperatorComma");
info.func = function()
Seperator("UseSeperatorComma")
end
L_UIDropDownMenu_AddButton(info, _G["L_UIDROPDOWNMENU_MENU_LEVEL"]);
local info = {};
info.text = L["TITAN_USE_PERIOD"];
info.checked = TitanGetVar(TITAN_XP_ID, "UseSeperatorPeriod");
info.func = function()
Seperator("UseSeperatorPeriod")
end
L_UIDropDownMenu_AddButton(info, _G["L_UIDROPDOWNMENU_MENU_LEVEL"]);
TitanPanelRightClickMenu_AddSpacer();
TitanPanelRightClickMenu_AddCommand(L["TITAN_PANEL_MENU_HIDE"], TITAN_XP_ID, TITAN_PANEL_MENU_FUNC_HIDE);
end
end
-- **************************************************************************
-- NAME : TitanPanelXPButton_ShowSessionTime()
-- DESC : Display session time in bar if set
-- **************************************************************************
function TitanPanelXPButton_ShowSessionTime()
TitanSetVar(TITAN_XP_ID, "DisplayType", "ShowSessionTime");
TitanPanelButton_UpdateButton(TITAN_XP_ID);
TitanSetVar(TITAN_XP_ID, "ShowSimpleRested", false);
TitanSetVar(TITAN_XP_ID, "ShowSimpleToLevel", false);
TitanSetVar(TITAN_XP_ID, "ShowSimpleNumOfKills", false);
TitanSetVar(TITAN_XP_ID, "ShowSimpleNumOfGains", false);
end
-- **************************************************************************
-- NAME : TitanPanelXPButton_ShowXPPerHourSession()
-- DESC : Display per hour in session data in bar if set
-- **************************************************************************
function TitanPanelXPButton_ShowXPPerHourSession()
TitanSetVar(TITAN_XP_ID, "DisplayType", "ShowXPPerHourSession");
TitanPanelButton_UpdateButton(TITAN_XP_ID);
TitanSetVar(TITAN_XP_ID, "ShowSimpleRested", false);
TitanSetVar(TITAN_XP_ID, "ShowSimpleToLevel", false);
TitanSetVar(TITAN_XP_ID, "ShowSimpleNumOfKills", false);
TitanSetVar(TITAN_XP_ID, "ShowSimpleNumOfGains", false);
end
-- **************************************************************************
-- NAME : TitanPanelXPButton_ShowXPPerHourLevel()
-- DESC : Display per hour to level data in bar if set
-- **************************************************************************
function TitanPanelXPButton_ShowXPPerHourLevel()
TitanSetVar(TITAN_XP_ID, "DisplayType", "ShowXPPerHourLevel");
TitanPanelButton_UpdateButton(TITAN_XP_ID);
TitanSetVar(TITAN_XP_ID, "ShowSimpleRested", false);
TitanSetVar(TITAN_XP_ID, "ShowSimpleToLevel", false);
TitanSetVar(TITAN_XP_ID, "ShowSimpleNumOfKills", false);
TitanSetVar(TITAN_XP_ID, "ShowSimpleNumOfGains", false);
end
-- **************************************************************************
-- NAME : TitanPanelXPButton_ShowXPSimple()
-- DESC : Display simple XP data (% level, rest, xp to level) in bar if set
-- **************************************************************************
function TitanPanelXPButton_ShowXPSimple()
TitanSetVar(TITAN_XP_ID, "DisplayType", "ShowXPSimple");
TitanPanelButton_UpdateButton(TITAN_XP_ID);
end
-- **************************************************************************
-- NAME : TitanPanelXPButton_ResetSession()
-- DESC : Reset session and accumulated variables
-- **************************************************************************
function TitanPanelXPButton_ResetSession()
TitanPanelXPButton.initXP = UnitXP("player");
TitanPanelXPButton.accumXP = 0;
TitanPanelXPButton.sessionXP = 0;
TitanPanelXPButton.startSessionTime = time();
lastXP = TitanPanelXPButton.initXP;
end
-- **************************************************************************
-- NAME : TitanPanelXPButton_RefreshPlayed()
-- DESC : Get total time played
-- **************************************************************************
function TitanPanelXPButton_RefreshPlayed()
RequestTimePlayed();
end
|
function request()
print('do it')
local conn = tls.createConnection(net.TCP, 0)
conn:on("connection", function(sck)
print('connected')
msg = 'GET /RemoteDevices/time HTTP/1.1\r\nHost: 192.168.1.7\r\n\r\n'
sck:send(msg)
end)
conn:on("reconnection", function(sck, c)
-- reconn is fired on disconn instead of the disconn event for some reason
print('reconn', c)
end)
conn:on("disconnection", function(sck, c)
print('disconn', c)
startConnection()
end)
conn:on("receive",
function(sck, c)
print('recv ')
sck:close()
end
)
conn:on("sent", function()
print('sent')
end)
conn:connect(5001, '192.168.1.7')
print('heap ', node.heap())
end
reqTmr = tmr.create()
reqTmr:register(10000, tmr.ALARM_AUTO, request)
reqTmr:start() |
------------------------
-- General Settings --
------------------------
UNDO_DIR = os.getenv "HOME" .. "/.vim/undo/"
local M = {}
M.load_options = function()
local opt = vim.opt
local default_options = { -- create table of options
clipboard = "unnamedplus", -- allows neovim to access the system clipboard
cmdheight = 2, -- more space in the neovim command line for displaying messages
fileencoding = "utf-8", -- use utf-8 file encoding
foldmethod = "manual", -- code folding, set to "expr" for treesitter based folding
foldexpr = "", -- set to "nvim_treesitter#foldexpr()" for treesitter based folding
hlsearch = true, -- highlight all matches on previous search pattern
ignorecase = true, -- ignore case when searching, see also: smartcase
smartcase = true, -- case sensitive search if at least one letter is uppercase
mouse = "a", -- enable mouse for nvim
showmode = false, -- don't show which mode we are in
-- pumheight = 10, -- popup menu height
splitbelow = true, -- force all horizontal splits to go below current window
splitright = true, -- force all vertical splits to go to the right of current window
termguicolors = true, -- set term gui colors
title = true, -- set the title of window to the value of the titlestring
expandtab = true, -- convert tabs to spaces
shiftwidth = 2, -- the number of spaces inserted for each indentation
tabstop = 2, -- insert 2 spaces for a tab
cursorline = true, -- highlight the current line
number = true, -- set numbered lines
relativenumber = true, -- set relative numbered lines
numberwidth = 4, -- set number column width
signcolumn = "yes", -- always show the sign column, otherwise it would shift text each time
spell = false, --
spelllang = "en", --
scrolloff = 8, -- Minimal number of lines to keep above and below the cursor
sidescrolloff = 8, -- same as above, except for left and right, if nowrap is set
-- timeoutlen = 100, -- time to wait for a mapped sequence to complete (in milliseconds)
undodir = UNDO_DIR, -- set an undo directory
undofile = true, -- enable persistent undo
updatetime = 300, -- faster completion
wrap = false, -- display lines as one long line
autoread = true, -- Detect changes in files if they are edited outside of nvim
wildmenu = true, -- Shows possible matches when using tab completion
showtabline = 2, -- always show tabs
guifont = "Hack\\ Nerd\\ Font:h11",
hidden = true, -- any buffer can be hidden (keeping its changes)
}
-- assign all options in default_options
for k, v in pairs(default_options) do
vim.opt[k] = v
end
-- completion global settings
vim.o.completeopt = "menuone,noselect"
-- good defaults for sessions
vim.o.sessionoptions="blank,buffers,curdir,folds,help,options,tabpages,winsize,resize,winpos,terminal"
-- colorscheme
vim.g.tokyonight_style = "storm"
vim.g.tokyonight_terminal_colors = true
vim.g.tokyonight_italic_keywords = true
vim.g.tokyonight_transparent = false
vim.g.tokyonight_sidebars = { "terminal", "packer", "dapui_scopes", "dapui_breakpoints", "dapui_stacks", "dapui_watches", "dap-repl" }
vim.cmd[[colorscheme tokyonight]]
end
----------------------------
-- General Autocommands --
----------------------------
M.load_commands = function()
-- autocommands
--- This function is taken from https://github.com/norcalli/nvim_utils
local function nvim_create_augroups(definitions)
for group_name, definition in pairs(definitions) do
vim.api.nvim_command('augroup '..group_name)
vim.api.nvim_command('autocmd!')
for _, def in ipairs(definition) do
local command = table.concat(vim.tbl_flatten{'autocmd', def}, ' ')
vim.api.nvim_command(command)
end
vim.api.nvim_command('augroup END')
end
end
local autocmds = {
-- reload_vimrc = {
-- -- Reload vim config automatically
-- {"BufWritePost",[[$VIM_PATH/{init.vim,*.vim,*.yaml} nested source $MYVIMRC | redraw]]};
-- };
packer = {
{ "BufWritePost", "plugins.lua", "PackerCompile" };
};
terminal_job = {
{ "TermOpen", "*", [[tnoremap <buffer> <Esc> <c-\><c-n>]] };
{ "TermOpen", "*", "startinsert" };
{ "TermOpen", "*", "setlocal listchars= nonumber norelativenumber" };
};
}
nvim_create_augroups(autocmds)
end
return M
|
TOOL.Name = "UnitTestsServer"
TOOL.Category = "Test"
TOOL.Directory = "../tests"
TOOL.EnableConsole = true
TOOL.Kind = "Application"
TOOL.TargetDirectory = TOOL.Directory
TOOL.Defines = {
"NDK_SERVER"
}
TOOL.Includes = {
"../include"
}
TOOL.Files = {
"../tests/main.cpp",
"../tests/Engine/**.hpp",
"../tests/Engine/**.cpp",
"../tests/SDK/**.hpp",
"../tests/SDK/**.cpp"
}
-- Excludes client-only files
TOOL.FilesExcluded = {
"../tests/Engine/Audio/**",
"../tests/Engine/Graphics/**",
"../tests/Engine/Platform/**",
"../tests/SDK/NDK/Application.cpp",
"../tests/SDK/NDK/Systems/ListenerSystem.cpp",
"../tests/SDK/NDK/Systems/RenderSystem.cpp"
}
TOOL.Libraries = {
"NazaraNetwork",
"NazaraSDKServer"
}
|
local S = technic.worldgen.gettext
minetest.register_node( ":technic:mineral_uranium", {
description = S("Uranium Ore"),
tiles = { "default_stone.png^technic_mineral_uranium.png" },
is_ground_content = true,
groups = {cracky=3, radioactive=1},
sounds = default.node_sound_stone_defaults(),
drop = "technic:uranium_lump",
})
minetest.register_node( ":technic:mineral_chromium", {
description = S("Chromium Ore"),
tiles = { "default_stone.png^technic_mineral_chromium.png" },
is_ground_content = true,
groups = {cracky=3},
sounds = default.node_sound_stone_defaults(),
drop = "technic:chromium_lump",
})
minetest.register_node( ":technic:mineral_zinc", {
description = S("Zinc Ore"),
tiles = { "default_stone.png^technic_mineral_zinc.png" },
is_ground_content = true,
groups = {cracky=3},
sounds = default.node_sound_stone_defaults(),
drop = "technic:zinc_lump",
})
minetest.register_node( ":technic:mineral_lead", {
description = S("Lead Ore"),
tiles = { "default_stone.png^technic_mineral_lead.png" },
is_ground_content = true,
groups = {cracky=3},
sounds = default.node_sound_stone_defaults(),
drop = "technic:lead_lump",
})
minetest.register_node( ":technic:mineral_sulfur", {
description = S("Sulfur Ore"),
tiles = { "default_stone.png^technic_mineral_sulfur.png" },
is_ground_content = true,
groups = {cracky=3},
sounds = default.node_sound_stone_defaults(),
drop = "technic:sulfur_lump",
})
minetest.register_node( ":technic:granite", {
description = S("Granite"),
tiles = { "technic_granite.png" },
is_ground_content = true,
groups = {cracky=1},
sounds = default.node_sound_stone_defaults(),
})
minetest.register_node( ":technic:marble", {
description = S("Marble"),
tiles = { "technic_marble.png" },
is_ground_content = true,
groups = {cracky=3, marble=1},
sounds = default.node_sound_stone_defaults(),
})
minetest.register_node( ":technic:marble_bricks", {
description = S("Marble Bricks"),
tiles = { "technic_marble_bricks.png" },
is_ground_content = true,
groups = {cracky=3},
sounds = default.node_sound_stone_defaults(),
})
minetest.register_node(":technic:uranium_block", {
description = S("Uranium Block"),
tiles = { "technic_uranium_block.png" },
is_ground_content = true,
groups = {uranium_block=1, cracky=1, level=2, radioactive=2},
sounds = default.node_sound_stone_defaults()
})
minetest.register_node(":technic:chromium_block", {
description = S("Chromium Block"),
tiles = { "technic_chromium_block.png" },
is_ground_content = true,
groups = {cracky=1, level=2},
sounds = default.node_sound_stone_defaults()
})
minetest.register_node(":technic:zinc_block", {
description = S("Zinc Block"),
tiles = { "technic_zinc_block.png" },
is_ground_content = true,
groups = {cracky=1, level=2},
sounds = default.node_sound_stone_defaults()
})
minetest.register_node(":technic:lead_block", {
description = S("Lead Block"),
tiles = { "technic_lead_block.png" },
is_ground_content = true,
groups = {cracky=1, level=2},
sounds = default.node_sound_stone_defaults()
})
minetest.register_alias("technic:wrought_iron_block", "default:steelblock")
minetest.override_item("default:steelblock", {
description = S("Wrought Iron Block"),
tiles = { "technic_wrought_iron_block.png" },
})
minetest.register_node(":technic:cast_iron_block", {
description = S("Cast Iron Block"),
tiles = { "technic_cast_iron_block.png" },
is_ground_content = true,
groups = {cracky=1, level=2},
sounds = default.node_sound_stone_defaults()
})
minetest.register_node(":technic:carbon_steel_block", {
description = S("Carbon Steel Block"),
tiles = { "technic_carbon_steel_block.png" },
is_ground_content = true,
groups = {cracky=1, level=2},
sounds = default.node_sound_stone_defaults()
})
minetest.register_node(":technic:stainless_steel_block", {
description = S("Stainless Steel Block"),
tiles = { "technic_stainless_steel_block.png" },
is_ground_content = true,
groups = {cracky=1, level=2},
sounds = default.node_sound_stone_defaults()
})
minetest.register_node(":technic:brass_block", {
description = S("Brass Block"),
tiles = { "technic_brass_block.png" },
is_ground_content = true,
groups = {cracky=1, level=2},
sounds = default.node_sound_stone_defaults()
})
minetest.register_craft({
output = 'technic:marble_bricks 4',
recipe = {
{'technic:marble','technic:marble'},
{'technic:marble','technic:marble'}
}
})
minetest.register_alias("technic:diamond_block", "default:diamondblock")
minetest.register_alias("technic:diamond", "default:diamond")
minetest.register_alias("technic:mineral_diamond", "default:stone_with_diamond")
local function for_each_registered_node(action)
local really_register_node = minetest.register_node
minetest.register_node = function(name, def)
really_register_node(name, def)
action(name:gsub("^:", ""), def)
end
for name, def in pairs(minetest.registered_nodes) do
action(name, def)
end
end
for_each_registered_node(function(node_name, node_def)
if node_name ~= "default:steelblock" and
node_name:find("steelblock", 1, true) and
node_def.description:find("Steel", 1, true) then
minetest.override_item(node_name, {
description = node_def.description:gsub("Steel", S("Wrought Iron")),
})
end
local tiles = node_def.tiles or node_def.tile_images
if tiles then
local new_tiles = {}
local do_override = false
if type(tiles) == "string" then
tiles = {tiles}
end
for i, t in ipairs(tiles) do
if type(t) == "string" and t == "default_steel_block.png" then
do_override = true
t = "technic_wrought_iron_block.png"
end
table.insert(new_tiles, t)
end
if do_override then
minetest.override_item(node_name, {
tiles = new_tiles
})
end
end
end)
|
-----------------------------------------------------------
-- Indent line configuration file
-----------------------------------------------------------
-- Plugin: indent-blankline
-- https://github.com/lukas-reineke/indent-blankline.nvim
require('indent_blankline').setup {
char = "▏",
show_first_indent_level = false,
filetype_exclude = {
'help',
'git',
'markdown',
'text',
'terminal',
'lspinfo',
'packer'
},
buftype_exclude = {
'terminal',
'nofile'
},
}
|
local Hups = {}
function Hups.new(t)
local hup = {
vel = t.vel or 300,
game = t.game or false,
gameover = false,
segs = {{
x = t.x or 0,
y = t.y or 0,
a = t.a or 0,
r = t.r or 20,
col = t.hcol or {1.0,1.0,1.0}
}},
}
setmetatable(hup, {__index = Hups})
hup:init(t)
return hup
end
function Hups.copy(hup)
setmetatable(hup, {__index = Hups})
return hup
end
function Hups:init(t)
t = t or {}
local h = self.segs[1]
for i = 1, (t.len or 3) do
local seg = {
x = h.x,
y = h.y,
a = h.a,
r = h.r,
col = {0.4,0.8,0.2}
}
table.insert(self.segs, #self.segs, seg)
end
end
function Hups:getHead()
return self.segs[#self.segs]
end
function Hups:setHead(h)
self.segs[#self.segs] = h
end
function Hups:append(food)
local h = self:getHead()
local seg = {
x = h.x,
y = h.y,
a = h.a,
r = food.r,
col = food.col
}
table.insert(self.segs, #self.segs, seg)
end
function Hups:update(dt)
local mx, my = love.mouse.getPosition()
-- Keep track of consumed energy
local energy = 0
-- Update head position
local h = self:getHead()
local md2 = (my - h.y)^2 + (mx - h.x)^2
local md = math.sqrt(md2)
local d = dt*math.min(self.vel, 4*md)
local a = math.atan2(my - h.y, mx - h.x)
h.a = a
h.x = h.x + d*math.cos(a)
h.y = h.y + d*math.sin(a)
self:setHead(h)
energy = energy + d*h.r
-- Update other segment positions
for i = #self.segs-1, 1, -1 do
local sc = self.segs[i]
local sp = self.segs[i+1]
local d2 = (sp.y - sc.y)^2 + (sp.x - sc.x)^2
local d = math.sqrt(d2)
local maxd = 0.75*(sp.r + sc.r)
if d > maxd then
d = d - maxd
local a = math.atan2(sp.y - sc.y, sp.x - sc.x)
sc.a = a
sc.x = sc.x + d*math.cos(a)
sc.y = sc.y + d*math.sin(a)
energy = energy + d*sc.r
end
end
if self.game then
-- Use food
local seg = self.segs[1]
-- New energy in last seg
local ne = seg.r^2 - energy*0.01 - dt*100
if ne < 0 then -- Remove segment if used up
if #self.segs > 1 then
table.remove(self.segs, 1)
else
self.gameover = true
end
else
seg.r = math.sqrt(ne)
end
end
end
local function drawSeg(seg, head)
-- Translate to segment frame
love.graphics.push()
love.graphics.translate(seg.x, seg.y)
love.graphics.rotate(seg.a-0.5*math.pi)
-- Draw circle
love.graphics.setColor(seg.col)
love.graphics.circle("fill", 0, 0, seg.r)
love.graphics.setColor(0,0,0)
love.graphics.circle("line", 0, 0, seg.r)
-- Draw details
if head then
local er = 3
love.graphics.circle("fill", -0.5*seg.r, 0.5*seg.r, er)
love.graphics.circle("fill", 0.5*seg.r, 0.5*seg.r, er)
else
local ll = 4
love.graphics.circle("fill", -seg.r-0.5*ll, 0, ll)
love.graphics.circle("fill", seg.r+0.5*ll, 0, ll)
end
love.graphics.pop()
end
function Hups:draw()
love.graphics.setLineWidth(3)
for i = 1, #self.segs-1 do
drawSeg(self.segs[i])
end
local h = self:getHead()
drawSeg(h, true)
end
return Hups
|
local _2afile_2a = "fnl/snap/view/view.fnl"
local _0_
do
local name_0_ = "snap.view.view"
local module_0_
do
local x_0_ = package.loaded[name_0_]
if ("table" == type(x_0_)) then
module_0_ = x_0_
else
module_0_ = {}
end
end
module_0_["aniseed/module"] = name_0_
module_0_["aniseed/locals"] = ((module_0_)["aniseed/locals"] or {})
do end (module_0_)["aniseed/local-fns"] = ((module_0_)["aniseed/local-fns"] or {})
do end (package.loaded)[name_0_] = module_0_
_0_ = module_0_
end
local autoload
local function _1_(...)
return (require("aniseed.autoload")).autoload(...)
end
autoload = _1_
local function _2_(...)
local ok_3f_0_, val_0_ = nil, nil
local function _2_()
return {require("snap.common.buffer"), require("snap.common.register"), require("snap.view.size"), require("snap.common.tbl"), require("snap.common.window")}
end
ok_3f_0_, val_0_ = pcall(_2_)
if ok_3f_0_ then
_0_["aniseed/local-fns"] = {require = {buffer = "snap.common.buffer", register = "snap.common.register", size = "snap.view.size", tbl = "snap.common.tbl", window = "snap.common.window"}}
return val_0_
else
return print(val_0_)
end
end
local _local_0_ = _2_(...)
local buffer = _local_0_[1]
local register = _local_0_[2]
local size = _local_0_[3]
local tbl = _local_0_[4]
local window = _local_0_[5]
local _2amodule_2a = _0_
local _2amodule_name_2a = "snap.view.view"
do local _ = ({nil, _0_, nil, {{}, nil, nil, nil}})[2] end
local function layout(config)
local _let_0_ = config.layout()
local col = _let_0_["col"]
local height = _let_0_["height"]
local row = _let_0_["row"]
local width = _let_0_["width"]
local index = (config.index - 1)
local border = (index * size.border)
local padding = (index * size.padding)
local total_borders = ((config["total-views"] - 1) * size.border)
local total_paddings = ((config["total-views"] - 1) * size.padding)
local sizes = tbl.allocate((height - total_borders - total_paddings), config["total-views"])
local height0 = sizes[config.index]
local col_offset = math.floor((width * size["view-width"]))
return {col = (col + col_offset + (size.border * 2) + size.padding), focusable = false, height = height0, row = (row + tbl.sum(tbl.take(sizes, index)) + border + padding), width = (width - col_offset - size.padding - size.padding - size.border)}
end
local create
do
local v_0_
do
local v_0_0
local function create0(config)
local bufnr = buffer.create()
local layout_config = layout(config)
local winnr = window.create(bufnr, layout_config)
vim.api.nvim_win_set_option(winnr, "cursorline", false)
vim.api.nvim_win_set_option(winnr, "cursorcolumn", false)
vim.api.nvim_win_set_option(winnr, "wrap", false)
vim.api.nvim_win_set_option(winnr, "winhl", "Normal:SnapNormal,FloatBorder:SnapBorder")
local function delete()
if vim.api.nvim_win_is_valid(winnr) then
window.close(winnr)
end
if vim.api.nvim_buf_is_valid(bufnr) then
return buffer.delete(bufnr, {force = true})
end
end
local function update(view)
if vim.api.nvim_win_is_valid(winnr) then
local layout_config0 = layout(config)
window.update(winnr, layout_config0)
vim.api.nvim_win_set_option(winnr, "cursorline", true)
do end (view)["height"] = layout_config0.height
view["width"] = layout_config0.width
return nil
end
end
local view = {bufnr = bufnr, delete = delete, height = layout_config.height, update = update, width = layout_config.width, winnr = winnr}
vim.api.nvim_command("augroup SnapViewResize")
vim.api.nvim_command("autocmd!")
local function _3_()
return view:update()
end
vim.api.nvim_command(string.format("autocmd VimResized * %s", register["get-autocmd-call"]("VimResized", _3_)))
vim.api.nvim_command("augroup END")
return view
end
v_0_0 = create0
_0_["create"] = v_0_0
v_0_ = v_0_0
end
local t_0_ = (_0_)["aniseed/locals"]
t_0_["create"] = v_0_
create = v_0_
end
return nil |
--
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
--
package.path = package.path .. ';../?.lua'
local utils = require 'utils.utils'
utils.require_torch()
utils.require_cutorch()
local playoutv2 = require('mctsv2.playout_multithread')
local common = require("common.common")
local goutils = require 'utils.goutils'
local CNNPlayerV2 = require 'cnnPlayerV2.cnnPlayerV2Framework'
local board = require 'board.board'
local pl = require 'pl.import_into'()
local opt = pl.lapp[[
--rollout (default 1000) The number of rollout we use.
--dcnn_rollout (default -1) The number of dcnn rollout we use (If we set to -1, then it is the same as rollout), if cpu_only is set, then dcnn_rollout is not used.
--dp_max_depth (default 10000) The max_depth of default policy.
-v,--verbose (default 1) The verbose level (1 = critical, 2 = info, 3 = debug)
--print_tree Whether print the search tree.
--max_send_attempts (default 3) #attempts to send to the server.
--pipe_path (default "/data/local/go/") Pipe path
--tier_name (default "ai.go-evaluator") Tier name
--server_type (default "local") We can choose "local" or "cluster". For open source version, for now "cluster" is not usable.
--tree_to_json Whether we save the tree to json file for visualization. Note that pipe_path will be used.
--num_tree_thread (default 16) The number of threads used to expand MCTS tree.
--num_gpu (default 1) The number of gpus to use for local play.
--sigma (default 0) Sigma used to perturb the win rate in MCTS search.
--use_sigma_over_n use sigma / n (or sqrt(nparent/n)). This makes sigma small for nodes with confident win rate estimation.
--num_virtual_games (default 0) Number of virtual games we use.
--acc_prob_thres (default 0.8) Accumulated probability threshold. We remove the remove if by the time we see it, the accumulated prob is greater than this thres.
--max_num_move (default 20) Maximum number of moves to consider in each tree node.
--min_num_move (default 1) Minimum number of moves to consider in each tree node.
--decision_mixture_ratio (default 5.0) Mixture MCTS count ratio with cnn_confidence.
--time_limit (default 0) Limit time for each move in second. If set to 0, then there is no time limit.
--win_rate_thres (default 0.0) If the win rate is lower than that, resign.
--use_pondering Whether we use pondering
--exec (default "") Whether we run an initial script
--setup_board (default "") Setup board. The argument is "sgfname moveto"
--dynkomi_factor (default 0.0) Use dynkomi_factor
--num_playout_per_rollout (default 1) Number of playouts per rollouts.
--single_move_return Use single move return (When we only have one choice, return the move immediately)
--expand_search_endgame Whether we expand the search in end game.
--default_policy (default "v2") The default policy used. Could be "simple", "v2".
--default_policy_pattern_file (default "../models/playout-model.bin") The patter file
--default_policy_temperature (default 0.125) The temperature we use for sampling.
--online_model_alpha (default 0.0) Whether we use online model and its alpha
--online_prior_mixture_ratio (default 0.0) Online prior mixture ratio.
--use_rave Whether we use RAVE.
--use_cnn_final_score Whether we use CNN final score.
--min_ply_to_use_cnn_final_score (default 100) When to use cnn final score.
--final_mixture_ratio (default 0.5) The mixture ratio we used.
--percent_playout_in_expansion (default 0) The percent of threads that will run playout when we expand the node. Other threads will block wait.
--use_old_uct Use old uct
--use_async Open async model.
--cpu_only Whether we only use fast rollout.
--expand_n_thres (default 0) Statistics collected before expand.
--sample_topn (default -1) If use v2, topn we should sample..
--rule (default cn) Use JP rule : jp, use CN rule: cn
--heuristic_tm_total_time (default 0) Time for heuristic tm (0 mean you don't use it).
--min_rollout_peekable (default 20000) The command peek will return if the minimal number of rollouts exceed this threshold
--save_sgf_per_move If so, then we save sgf file for each move
--use_formal_params If so, then use formal parameters
]]
local function load_params_for_formal_game()
opt.rollout = 10000000 -- (default 1000) The number of rollout we use.
opt.dcnn_rollout = -1 -- The number of dcnn rollout we use (If we set to -1, then it is the same as rollout), if cpu_only is set, then dcnn_rollout is not used.
opt.dp_max_depth = 10000 -- (default 10000) The max_depth of default policy.
opt.verbose = 1 -- (default 1) The verbose level (1 = critical, 2 = info, 3 = debug)
opt.print_tree = false -- Whether print the search tree.
opt.max_send_attempts = 3 -- (default 3) #attempts to send to the server.
--opt.pipe_path = "/home/huanghe/lxt/data" -- (default "/data/local/go/") Pipe path
opt.tier_name = "ai.go-evaluator" -- (default "ai.go-evaluator") Tier name
opt.server_type = "local" -- (default "local") We can choose "local" or "cluster"
opt.tree_to_json = false -- Whether we save the tree to json file for visualization. Note that pipe_path will be used.
opt.num_tree_thread = 64 -- (default 16) The number of threads used to expand MCTS tree.
opt.num_virtual_games = 5
opt.acc_prob_thres = 1 -- (default 0.8) Accumulated probability threshold. We remove the remove if by the time we see it, the accumulated prob is greater than this thres.
opt.max_num_move = 7 -- (default 20) Maximum number of moves to consider in each tree node.
opt.min_num_move = 1 -- (default 1) Minimum number of moves to consider in each tree node.
opt.decision_mixture_ratio = 5.0 -- (default 5.0) Mixture MCTS count ratio with cnn_confidence.
opt.win_rate_thres = -1 -- (default 0.0) If the win rate is lower than that, resign.
opt.use_pondering = true -- Whether we use pondering
opt.dynkomi_factor = 0.035 -- (default 0.0) Use dynkomi_factor
opt.single_move_return = false -- Use single move return (When we only have one choice, return the move immediately)
opt.expand_search_endgame = false -- Whether we expand the search in end game.
opt.default_policy= "v2" -- (default "v2") The default policy used. Could be "simple", "pachi", "v2".
opt.default_policy_pattern_file = "../models/playout-model.bin" -- The default policy pattern file
opt.default_policy_temperature = 0.5
opt.online_model_alpha = 0.0 -- (default 0.0) Whether we use online model and its alpha
opt.online_prior_mixture_ratio = 0.0 -- (default 0.0) Online prior mixture ratio.
opt.use_rave = false -- Whether we use RAVE.
opt.use_cnn_final_score = false -- Whether we use CNN final score.
opt.min_ply_to_use_cnn_final_score = 100 -- (default 100) When to use cnn final score.
opt.final_mixture_ratio = 0.35 -- (default 0.5) The mixture ratio we used.
opt.use_old_uct = false
opt.percent_playout_in_expansion = 5
opt.use_async = false -- Open async model.
opt.cpu_only = false -- Whether we only use fast rollout.
opt.expand_n_thres = 0 -- (default 0) Statistics collected before expand.
opt.sample_topn = -1 -- (default -1) If use v2, topn we should sample..
opt.rule = "cn" -- (default cn) Use JP rule : jp, use CN rule: cn
opt.num_playout_per_rollout = 1
--opt.save_sgf_per_move = true
end
if opt.use_formal_params then
load_params_for_formal_game()
end
-- io.stderr:write("Loading model = " .. opt.input)
local function set_playout_params_from_opt()
playoutv2.params.print_search_tree = opt.print_tree and common.TRUE or common.FALSE
playoutv2.params.pipe_path = opt.pipe_path
playoutv2.params.tier_name = opt.tier_name
playoutv2.params.server_type = opt.server_type == "local" and playoutv2.server_local or playoutv2.server_cluster
playoutv2.params.verbose = opt.verbose
playoutv2.params.num_gpu = opt.num_gpu
playoutv2.params.dynkomi_factor = opt.dynkomi_factor
playoutv2.params.cpu_only = opt.cpu_only and common.TRUE or common.FALSE
playoutv2.params.rule = opt.rule == "jp" and board.japanese_rule or board.chinese_rule
-- Whether to use heuristic time manager. If so, then (total time is info->common_params->heuristic_tm_total_time)
if opt.heuristic_tm_total_time > 0 then
-- 1. Gradually add more time per move for the first 30 moves (ply < 60). (1 sec -> 15 sec, 15s * 30 / 2 = 225 s)
-- 2. Keep 15 sec move, 31-100 move ( 70 * 15sec = 1050 s)
-- 3. Decrease the time linearly, 101-130 (30 * 15/2 = 225s)
-- 4. Once we enter the region that time_left < 120s, try 1sec per move.
-- If the total time is x, then the max_time_spent y could be computed as:
-- y * ply1 / 4 + (ply2 - ply1) / 2 * y + y * (ply3 - ply2) / 4 < alpha * x
-- y * [ -ply1/4 + ply2/4 + ply3 / 4] < alpha * x
-- y < 4 * alpha * x / (ply2 + ply3 - ply1)
-- For x = 1800sec, we have y = 4 * alpha * 1800 / (200 + 260 - 60) = 12.5 sec.
local alpha = 0.75;
playoutv2.params.heuristic_tm_total_time = opt.heuristic_tm_total_time
playoutv2.params.max_time_spent = 4 * alpha * opt.heuristic_tm_total_time / (playoutv2.thres_ply2 + playoutv2.thres_ply3 - playoutv2.thres_ply1);
playoutv2.params.min_time_spent = playoutv2.min_time_spent;
end
playoutv2.tree_params.max_depth_default_policy = opt.dp_max_depth
playoutv2.tree_params.max_send_attempts = opt.max_send_attempts
playoutv2.tree_params.verbose = opt.verbose
playoutv2.tree_params.time_limit = opt.time_limit
playoutv2.tree_params.num_receiver = opt.num_gpu
playoutv2.tree_params.sigma = opt.sigma
playoutv2.tree_params.use_pondering = opt.use_pondering
playoutv2.tree_params.use_cnn_final_score = opt.use_cnn_final_score and common.TRUE or common.FALSE
playoutv2.tree_params.final_mixture_ratio = opt.final_mixture_ratio
playoutv2.tree_params.min_ply_to_use_cnn_final_score = opt.min_ply_to_use_cnn_final_score
playoutv2.tree_params.num_tree_thread = opt.num_tree_thread
playoutv2.tree_params.rcv_acc_percent_thres = opt.acc_prob_thres * 100.0
playoutv2.tree_params.rcv_max_num_move = opt.max_num_move
playoutv2.tree_params.rcv_min_num_move = opt.min_num_move
playoutv2.tree_params.decision_mixture_ratio = opt.decision_mixture_ratio
playoutv2.tree_params.single_move_return = opt.single_move_return and common.TRUE or common.FALSE
playoutv2.tree_params.default_policy_choice = playoutv2.dp_table[opt.default_policy]
playoutv2.tree_params.pattern_filename = opt.default_policy_pattern_file
playoutv2.tree_params.use_online_model = math.abs(opt.online_model_alpha) < 1e-6 and common.FALSE or common.TRUE
playoutv2.tree_params.online_model_alpha = opt.online_model_alpha
playoutv2.tree_params.online_prior_mixture_ratio = opt.online_prior_mixture_ratio
playoutv2.tree_params.use_rave = opt.use_rave and common.TRUE or common.FALSE
playoutv2.tree_params.use_async = opt.use_async and common.TRUE or common.FALSE
playoutv2.tree_params.expand_n_thres = opt.expand_n_thres
playoutv2.tree_params.num_virtual_games = opt.num_virtual_games
playoutv2.tree_params.percent_playout_in_expansion = opt.percent_playout_in_expansion
playoutv2.tree_params.default_policy_sample_topn = opt.sample_topn
playoutv2.tree_params.default_policy_temperature = opt.default_policy_temperature
playoutv2.tree_params.use_old_uct = opt.use_old_uct and common.TRUE or common.FALSE
playoutv2.tree_params.use_sigma_over_n = opt.use_sigma_over_n and common.TRUE or common.FALSE
playoutv2.tree_params.num_playout_per_rollout = opt.num_playout_per_rollout
end
local tr
local count = 0
local signature
local function prepare_prefix()
if opt.tree_to_json then
local prefix = paths.concat(opt.pipe_path, signature, string.format("mcts_%04d", count))
count = count + 1
return prefix
end
end
local callbacks = { }
function callbacks.set_komi(komi, handi)
if komi ~= nil then
playoutv2.set_params(tr, { komi = komi })
end
-- for large handi game, cnn need to give more candidate, so mcts could possibly be more aggressive
local changed_params
if handi and handi <= -5 then
changed_params = { dynkomi_factor=1.0 }
end
if changed_params then
if playoutv2.set_params(tr, changed_params) then
playoutv2.print_params(tr)
end
end
end
function callbacks.adjust_params_in_game(b, isCanada)
-- When we are at the end of game, pay attention to local tactics.
if not opt.expand_search_endgame then return end
local changed_params
if isCanada then -- enter canada time setting, so lower the rollout number
local min_rollout = 7500
changed_params = {num_rollout = min_rollout, num_rollout_per_move = min_rollout}
else
if b._ply >= 230 then
-- Try avoid blunder if there is any.
-- changed_params = { rcv_max_num_move = 7, rcv_min_num_move = 3 }
elseif b._ply >= 150 then
changed_params = { rcv_max_num_move = 5 }
end
end
if changed_params then
if playoutv2.set_params(tr, changed_params) then
playoutv2.print_params(tr)
end
end
end
function callbacks.on_time_left(sec_left, num_moves)
playoutv2.set_time_left(tr, sec_left, num_moves)
end
function callbacks.new_game()
set_playout_params_from_opt()
if tr then
playoutv2.restart(tr)
else
local rs = {
rollout = opt.rollout,
dcnn_rollout_per_move = (opt.dcnn_rollout == -1 and opt.rollout or opt.dcnn_rollout),
rollout_per_move = opt.rollout
}
tr = playoutv2.new(rs)
end
count = 0
signature = utils.get_signature()
io.stderr:write("New MCTS game, signature: " .. signature)
os.execute("mkdir -p " .. paths.concat(opt.pipe_path, signature))
playoutv2.print_params(tr)
end
function callbacks.quit_func()
if tr then
playoutv2.free(tr)
end
end
function callbacks.move_predictor(b, player)
local prefix = prepare_prefix()
local m = playoutv2.play_rollout(tr, prefix, b)
if prefix then io.stderr:write("Save tree to " .. prefix) end
return m.x + 1, m.y + 1, m.win_rate
end
function callbacks.move_receiver(x, y, player)
local prefix = prepare_prefix()
playoutv2.prune_xy(tr, x, y, player, prefix)
end
function callbacks.peek_simulation(num_simulation)
return playoutv2.set_params(tr, { min_rollout_peekable = num_simulation })
end
function callbacks.move_peeker(b, player, topk)
return playoutv2.peek_rollout(tr, topk, b)
end
function callbacks.undo_func(b, undone_move)
if goutils.coord_is_pass(undone_move) then
playoutv2.undo_pass(tr, b)
else
playoutv2.set_board(tr, b)
end
end
function callbacks.set_board(b)
playoutv2.set_board(tr, b)
end
function callbacks.thread_switch(arg)
if arg == "on" then
playoutv2.thread_on(tr)
elseif arg == 'off' then
playoutv2.thread_off(tr)
else
io.stderr:write("Command " .. arg .. " is not recognized!")
end
end
function callbacks.set_move_history(history)
for _, h in pairs(history) do
playoutv2.add_move_history(tr, unpack(h))
end
end
function callbacks.set_verbose_level(verbose_level)
if playoutv2.set_params(tr, { verbose = verbose_level }) then
playoutv2.print_params(tr)
end
end
local opt2 = {
rule = opt.rule,
win_rate_thres = opt.win_rate_thres,
exec = opt.exec,
setup_board = opt.setup_board,
default_policy = opt.default_policy,
default_policy_pattern_file = opt.default_policy_pattern_file,
default_policy_temperature = opt.default_policy_temperature,
default_policy_sample_topn = opt.sample_topn,
save_sgf_per_move = opt.save_sgf_per_move
}
local cnnplayer = CNNPlayerV2("CNNPlayerV2MCTS", "go_player_v2_mcts", "1.0", callbacks, opt2)
cnnplayer:mainloop()
|
resource_manifest_version '77731fab-63ca-442c-a67b-abc70f28dfa5'
dependency "vrp"
server_script {
"@vrp/lib/utils.lua",
"init-server.lua"
}
client_script {
"@vrp/lib/utils.lua",
"init-client.lua"
}
files {
"client.lua"
}
|
function factions.start_diplomacy(name, faction)
for l, i in factions.factions.iterate() do
local fac = factions.factions.get(l)
if l ~= name and not (faction.neutral[l] or faction.allies[l] or faction.enemies[l]) then
if factions_config.faction_diplomacy == true then
factions.new_neutral(name, l)
factions.new_neutral(l, name)
else
factions.new_enemy(name, l)
factions.new_enemy(l, name)
end
end
end
end
function factions.new_alliance(name, faction)
local bfaction = factions.factions.get(name)
bfaction.allies[faction] = true
factions.on_new_alliance(name, faction)
if bfaction.enemies[faction] then
factions.end_enemy(name, faction)
end
if bfaction.neutral[faction] then
factions.end_neutral(name, faction)
end
factions.factions.set(name, bfaction)
end
function factions.end_alliance(name, faction)
local bfaction = factions.factions.get(name)
bfaction.allies[faction] = nil
factions.on_end_alliance(name, faction)
factions.factions.set(name, bfaction)
end
function factions.new_neutral(name, faction)
local bfaction = factions.factions.get(name)
bfaction.neutral[faction] = true
factions.on_new_neutral(name, faction)
if bfaction.allies[faction] then
factions.end_alliance(name, faction)
end
if bfaction.enemies[faction] then
factions.end_enemy(name, faction)
end
factions.factions.set(name, bfaction)
end
function factions.end_neutral(name, faction)
local bfaction = factions.factions.get(name)
bfaction.neutral[faction] = nil
factions.on_end_neutral(name, faction)
factions.factions.set(name, bfaction)
end
function factions.new_enemy(name, faction)
local bfaction = factions.factions.get(name)
bfaction.enemies[faction] = true
factions.on_new_enemy(name, faction)
if bfaction.allies[faction] then
factions.end_alliance(name, faction)
end
if bfaction.neutral[faction] then
factions.end_neutral(name, faction)
end
factions.factions.set(name, bfaction)
end
function factions.end_enemy(name, faction)
local bfaction = factions.factions.get(name)
bfaction.enemies[faction] = nil
factions.on_end_enemy(name, faction)
factions.factions.set(name, bfaction)
end
|
local luarpc = require("luarpc")
local r = {}
-- Globals
local default_arq_interface = "interface.lua"
local states = {
FOLLOWER = "follower",
CANDIDATE = "candidate",
LEADER = "leader"
}
local msgs = {
OK = "ok",
NO = "no",
VOTE = "vote",
VOTEREQUEST = "voterequest",
HEARTBEAT = "beat"
}
local default_IP = "127.0.0.1"
--- Auxiliary
local function printt(t)
for k, v in pairs(t) do
print(k, v)
end
end
local function getRandomTimeout(a,b)
a = a or 2
b = b or 6
return math.random(a, b)
end
local function getWaitTime(n) -- retorna a divisao inteira de (n / 3), caso o resultado seja 0 retorna 1
local wait = n // 3
if wait < 0 then
wait = 1
end
return wait
end
r.buildRaftObj = function (IP, arq_interface)
IP = IP or default_IP
arq_interface = arq_interface or default_arq_interface
local me = {}
me.timeout = { [states.CANDIDATE] = nil, [states.FOLLOWER] = nil , [states.LEADER] = nil}
me.state = states.FOLLOWER
me.currTime = 0 -- contabiliza a passagem de tempo desde o ultimo heartbeat ou troca de estado
me.leader = nil
me.id = nil -- id vai ser a porta
me.peers = {}
me.numberOfPeers = 0
me.majority = 0
me.shutdown = false;
me.failureTime = 0
me.myTerm = 0
me.term = 0
me.votedFor = nil
me.shouldVote = false
me.votes = 0
-- changing glogal print so it prints the peer's id
local realPrint = print
local print = function(s)
if me ~= nil and me.id ~= nil and (s ~= nil and type(s) ~= "table")then
local timestamp = luarpc.gettime()
realPrint(timestamp .. " --- id[" .. me.id .. "]: " .. s)
else
realPrint(s)
end
end
local function printMe()
local myString = "\n Timeout: " .. me.timeout[me.state] .. " State: " .. me.state .. " My term: " .. me.myTerm
if me.numberOfPeers > 0 then
myString = myString .. "\n Peers:"
for k, _ in pairs(me.peers) do
myString = myString .. "\n\t" .. k
end
end
myString = myString .. "\n Leader: "
if me.leader then
myString = myString .. me.leader
else
myString = myString .. "nil"
end
print(myString)
end
local function heartbeat()
for port, peer in pairs(me.peers) do
if port ~= me.id then
print("heartbeating: " .. port)
peer.appendEntry(me.term) -- FIXME: What to send here?
end
end
end
local function elected()
-- me.timeout[states.CANDIDATE] = 0 -- FIXME: Do i need to reset the timer????
me.state = states.LEADER
me.votes = 0
me.currTime = me.timeout[states.LEADER] + 1 -- making sure it will timeout and send the heatbeat in the control loop
print("Got Elected")
end
local function processVote(msg)
if msg.value == msgs.OK and me.state == states.CANDIDATE then
me.votes = me.votes + 1
if me.votes >= me.majority then
elected()
end
end
end
local function callElection()
me.term = me.term + 1
me.state = states.CANDIDATE
me.votes = 1 -- my vote
me.votedFor = me.id
me.shouldVote = false
local votes = {}
for peer, _ in pairs(me.peers) do -- FIXME: extract method "broadcast(msg)"
if(peer ~= me.id) then
me.peers[peer].receiveMessage({term = me.term, from = me.id, to = peer, type = msgs.VOTEREQUEST, value = ""})
end
end
end
local function wait()
local timeToWait = getWaitTime(me.timeout[me.state])
if me.failureTime > 0 then
timeToWait = me.failureTime
me.failureTime = 0
end
print("Will wait " .. timeToWait)
luarpc.wait(timeToWait) -- BUG AQUI, As vezes o wait não aguarda
end
local function castVote(peer, response)
local to = tonumber(peer)
me.peers[to].receiveMessage({term = me.term, from = me.id, to = to, type = msgs.VOTE, value = response})
end
local function checkVoteRequest(msg)
if msg.term < me.term then
return false
end
if me.votedFor ~= nil and me.votedFor ~= msg.from then
return false
end
return true
end
local function initializeProxies()
for port, _ in pairs(me.peers) do
print('Hello')
me.peers[port] = luarpc.createProxy(IP, port, arq_interface)
end
end
-- CORE FUNCTION
me.initializeNode = function()
me.state = states.FOLLOWER
me.leader = nil
me.shutdown = false
me.majority = (me.numberOfPeers // 2 + 1)
me.timeout[states.FOLLOWER] = getRandomTimeout(9, 12) -- timeout to call election
me.timeout[states.CANDIDATE] = getRandomTimeout(6, 9) -- timeout to abort current election and retry
me.timeout[states.LEADER] = getRandomTimeout(3, 6) -- timeout for heartbeat
initializeProxies()
print("Initializing node")
printMe()
while me.shutdown == false do
local timeBefore = luarpc.gettime()
wait()
me.currTime = me.currTime + (luarpc.gettime() - timeBefore)
if me.failureTime > 0 then -- Failure execution
if me.currTime >= me.failureTime then
me.failureTime = 0
me.currTime = 0
end
else -- Normal Execution
if me.state == states.FOLLOWER and me.votedFor ~= nil and me.shouldVote then --should cast my vote
castVote(me.votedFor, msgs.OK)
me.shouldVote = false
me.currTime = 0 -- reset time when voting
end
-- controle de timeouts
if me.currTime > me.timeout[me.state] then
me.currTime = 0 -- reset timeout
if me.state == states.FOLLOWER then -- FIXME extract a method
me.state = states.CANDIDATE
print("TIMEOUT --- BEGIN ELECTION")
callElection()
elseif me.state == states.LEADER then
print("LEADER WILL HEARTBEAT")
heartbeat()
else -- CANDIDATE election timeout
print("ELECTION TIMEOUT --- NEW ELECTION")
callElection()
end
end
end
end
end
-- CORE FUNCTION
-- msg { term, from, to, type, value}
me.receiveMessage = function(msg)
local returnMsg = msgs.OK
if msg == nil or me.failureTime > 0 or me.shutdown then
if msg == nil then
print("ERRO MENSAGEM RECEBIDA NIL")
else
print("Mensagem recebida>> " .. msg.type .. " from: " .. msg.from .. " msgTerm: " .. msg.term)
print("Will not respond! On falure")
end
return
end
print("Mensagem recebida>> " .. msg.type .. " from: " .. msg.from .. " msgTerm: " .. msg.term)
if msg.term > me.term then
me.votedFor = nil -- making sure that i can cast a vote in each term
end
if msg.type == msgs.VOTEREQUEST then
returnMsg = msgs.OK
if checkVoteRequest(msg) then
print("Will vote for ".. msg.from)
me.votedFor = msg.from
me.shouldVote = true
else
print("Will not vote for " .. msg.from .. " My term: " .. me.term .. " his term: " .. msg.term)
end
elseif msg.type == msgs.VOTE then
print("Got a vote")
processVote(msg)
else
print("No action for msg received " .. msg.type)
end
if msg.term > me.term then
me.term = msg.term
if me.state == states.LEADER then
me.state = states.FOLLOWER -- How to know who is the new leader? Just wait for a hearbeat??
me.currTime = 0
end
end
return returnMsg
end
-- CORE FUNCTION
me.stopNode = function(time)
if time == 0 then
print("Should shutdown")
me.shutdown = true
else
me.failureTime = time
end
end
-- CORE FUNCTION
me.appendEntry = function(msg)
print("Received heartBeat")
me.currTime = 0 -- FIXME: How to check if the appendEntry is from the correct leader?
return "OK"
end
-- CORE FUNCTION
me.snapshot = function()
printMe()
return
end
return me
end
return r |
local M = {}
M.intersects = function(row, col, sRow, sCol, eRow, eCol)
if sRow > row or eRow < row then
return false
end
if sRow == row and sCol > col then
return false
end
if eRow == row and eCol < col then
return false
end
return true
end
return M
|
--[[
Copyright (C) 2018 HarpyWar ([email protected])
This file is a part of the plugin https://github.com/HarpyWar/ts3plugin_mybadges
]]--
require("ts3defs")
-- Run with "/lua run mybadges.clear"
local function clear(serverConnectionHandlerID)
mybadges_events.onMenuItemEvent(serverConnectionHandlerID, nil, 2, nil)
end
-- Run with "/lua run mybadges.show"
local function show(serverConnectionHandlerID)
mybadges_events.onMenuItemEvent(serverConnectionHandlerID, nil, 1, nil)
end
local function set_badge(sid, badge_id, idx)
if badge_id < 0 or badge_id > #badgelist then
ts3.printMessageToCurrentTab("Invalid badge ID: " .. badge_id)
do return end
end
if (badge_id == 0) then
enableoverwolf[sid] = 1
else
if (#enabledbadges[sid] < 3) then
table.insert(enabledbadges[sid], badgelist[badge_id + mybadges_offset][1])
end
end
end
-- Run with "/lua run mybadges.set 1 1 16 0"
local function set(serverConnectionHandlerID, badge1, badge2, badge3, badge4)
local sid = ts3.getServerVariableAsString(serverConnectionHandlerID, ts3defs.VirtualServerProperties.VIRTUALSERVER_UNIQUE_IDENTIFIER)
-- clear
enabledbadges[sid] = {}
enableoverwolf[sid] = 0
-- add
if (badge1 ~= nil) then
set_badge(sid, badge1, 1)
end
if (badge2 ~= nil) then
set_badge(sid, badge2, 2)
end
if (badge3 ~= nil) then
set_badge(sid, badge3, 3)
end
if (badge4 ~= nil) then
set_badge(sid, badge4, 4)
end
show(serverConnectionHandlerID)
end
mybadges = {
show = show,
clear = clear,
set = set
}
|
-------------------------------------------------------------------
-- This script is created by zdroid9770; please do not edit this --
-- script and claim it as your own, as of All rights are claimed --
-- by me. --
-- Copyright (c) zdroid9770 --
--------------------------------------------------------------------
--[[
----Quotes
----Spells-ID
Heal-15586
Mind Blast-15587
Renew-8362
Shadow Bolt-15537
Shadow Word: Pain-15654
]]--
function PMBB_OnCombat(pUnit, event)
pUnit:RegisterEvent("PMBB_Heal", 5000, 0)
pUnit:RegisterEvent("PMBB_MindBlast", 25000, 0)
pUnit:RegisterEvent("PMBB_SWPain", 30000, 0)
pUnit:RegisterEvent("PMBB_Renew", 35000, 0)
pUnit:RegisterEvent("PMBB_ShadowBolt", 40000, 0)
end
function PMBB_Heal(pUnit, Event)
pUnit:FullCastSpell(15586)
end
function PMBB_MindBlast(pUnit, Event)
pUnit:FullCastSpellOnTarget(15587)
end
function PMBB_SWPain(pUnit, Event)
pUnit:CastSpellOnTarget(15654)
end
function PMBB_ShadowBolt(Unit, Event)
pUnit:FullCastSpellOnTarget(15537)
end
function PMBB_Renew(Unit, Event)
pUnit:FullCastSpell(8362)
end
function PMBB_OnLeaveCombat(pUnit, event)
pUnit:RemoveEvents()
end
function PMBB_OnDeath(pUnit, event)
pUnit:RemoveEvents()
end
RegisterUnitEvent(8929, 1, "PMBB_OnCombat")
RegisterUnitEvent(8929, 2, "PMBB_OnLeaveCombat")
RegisterUnitEvent(8929, 4, "PMBB_OnDeath") |
local migrations = {
["yatm_machines:battery_bank_off"] = "yatm_energy_storage:battery_bank_off",
["yatm_machines:battery_bank_on"] = "yatm_energy_storage:battery_bank_on0",
["yatm_energy_storage:battery_bank_on"] = "yatm_energy_storage:battery_bank_on0",
["yatm_machines:battery_bank_error"] = "yatm_energy_storage:battery_bank_error0",
["yatm_energy_storage:battery_bank_error"] = "yatm_energy_storage:battery_bank_error0",
["yatm_machines:energy_cell_basic_creative"] = "yatm_energy_storage:energy_cell_basic_creative",
["yatm_machines:energy_cell_normal_creative"] = "yatm_energy_storage:energy_cell_normal_creative",
["yatm_machines:energy_cell_dense_creative"] = "yatm_energy_storage:energy_cell_dense_creative",
}
for i = 0,7 do
migrations["yatm_machines:energy_cell_basic_" .. i] = "yatm_energy_storage:energy_cell_basic_" .. i
migrations["yatm_machines:energy_cell_normal_" .. i] = "yatm_energy_storage:energy_cell_normal_" .. i
migrations["yatm_machines:energy_cell_dense_" .. i] = "yatm_energy_storage:energy_cell_dense_" .. i
end
for from, to in pairs(migrations) do
minetest.register_lbm({
name = "yatm_energy_storage:migrate_" .. string.gsub(from, ":", "_"),
nodenames = {
from,
},
run_at_every_load = false,
action = function (pos, node)
node.name = to
minetest.swap_node(pos, node)
end
})
end
|
--- Map object. Inherited from @{l2df.class.entity.scene|l2df.class.entity.Scene} class.
-- @classmod l2df.class.entity.map
-- @author Abelidze
-- @copyright Atom-TM 2020
local core = l2df or require(((...):match('(.-)class.+$') or '') .. 'core')
assert(type(core) == 'table' and core.version >= 1.0, 'Entities works only with l2df v1.0 and higher')
local Scene = core.import 'class.entity.scene'
local Render = core.import 'class.component.render'
local Frames = core.import 'class.component.frames'
local States = core.import 'class.component.states'
local World = core.import 'class.component.physix.world'
local Transform = core.import 'class.component.transform'
local Renderer = core.import 'manager.render'
local Map = Scene:extend({ name = 'map' })
--- Map initialization. Components:
-- @{l2df.class.component.transform|Transform},
-- @{l2df.class.component.frames|Frames},
-- @{l2df.class.component.states|States},
-- @{l2df.class.component.render|Render},
-- @{l2df.class.component.physix.world|World} (instance).
-- @param[opt] table kwargs Keyword arguments.
-- @param[opt=false] boolean kwargs.hidden Initial map hidden state.
function Map:init(kwargs)
kwargs.width = kwargs.width or Renderer.minwidth
kwargs.height = kwargs.height or Renderer.minheight
self:super(kwargs)
self.data.hidden = kwargs.hidden or false
self:addComponent(Transform, kwargs)
self:addComponent(Frames, kwargs)
self:addComponent(States, kwargs)
self:addComponent(Render, kwargs)
self:addComponent(World(), kwargs)
end
return Map
|
---------------------------------------------------------- dependencies -- ;
local capi = {root=root}
local naughty = require('naughty')
local gears = require("gears")
local awful = require("awful")
local beautiful = require('beautiful')
local modkey = "Mod4"
local altkey = "Mod1"
local machina = require("machina.methods")
local backham = require("machina.backham")
local focus_by_direction = machina.focus_by_direction
local shift_by_direction = machina.shift_by_direction
local expand_horizontal = machina.expand_horizontal
local shuffle = machina.shuffle
local my_shifter = machina.my_shifter
local expand_vertical = machina.expand_vertical
local move_to = machina.move_to
local toggle_always_on = machina.toggle_always_on
local teleport_client = machina.teleport_client
local get_client_info = machina.get_client_info
local focus_by_index = machina.focus_by_index
local focus_by_number = machina.focus_by_number
local set_region = machina.set_region
local align_floats = machina.align_floats
---------------------------------------------------------- key bindings -- ;
local bindings = {
awful.key({altkey},"Tab", shuffle("backward")),
awful.key({altkey, "Shift"}, "Tab", shuffle("forward")),
-- awful.key({modkey}, "#10", focus_by_number(1)),
-- awful.key({modkey}, "#11", focus_by_number(2)),
-- awful.key({modkey}, "#12", focus_by_number(3)),
-- awful.key({modkey}, "#13", focus_by_number(4)),
-- awful.key({modkey}, "#14", focus_by_number(5)),
awful.key({modkey}, "[", shuffle("backward")),
awful.key({modkey}, "]", shuffle("forward")),
--▨ move
-- awful.key({modkey}, "Tab", focus_by_index("backward")),
-- awful.key({modkey, "Shift"}, "Tab", focus_by_index("forward")),
awful.key({modkey}, ";", align_floats("right")),
awful.key({modkey, "Shift"}, ";", align_floats("left")),
--▨ alignment
awful.key({modkey}, "x", function ()
c = client.focus or nil
if not c then return end
if c.floating then c.minimized = true return end
shuffle("backward")(c)
end),
awful.key({modkey, "Shift"}, "x", function ()
c = client.focus or nil
if not c then return end
if c.floating then c.minimized = true return end
shuffle("forward")(c)
end),
--▨ shuffle
awful.key({modkey, "Shift"}, "[", my_shifter("backward")),
awful.key({modkey, "Shift"}, "]", my_shifter("forward")),
--▨ move
awful.key({modkey, "Control"}, "[", my_shifter("backward", "swap")),
awful.key({modkey, "Control"}, "]", my_shifter("forward", "swap")),
--▨ swap
awful.key({modkey}, "'", function ()
naughty.notify({text=inspect(client.focus.transient_for)})
end),
--▨ shuffle
awful.key({modkey}, "j", focus_by_direction("left")),
awful.key({modkey}, "k", focus_by_direction("down")),
awful.key({modkey}, "l", focus_by_direction("right")),
awful.key({modkey}, "i", focus_by_direction("up")),
--▨ focus
awful.key({modkey, "Shift"}, "j", shift_by_direction("left")),
awful.key({modkey, "Shift"}, "l", shift_by_direction("right")),
awful.key({modkey, "Shift"}, "k", shift_by_direction("down")),
awful.key({modkey, "Shift"}, "i", shift_by_direction("up")),
--▨ move
awful.key({modkey, "Control"}, "j", shift_by_direction("left", "swap")),
awful.key({modkey, "Control"}, "l", shift_by_direction("right", "swap")),
awful.key({modkey, "Control"}, "k", shift_by_direction("down", "swap")),
awful.key({modkey, "Control"}, "i", shift_by_direction("up","swap")),
--▨ swap
awful.key({modkey}, "Insert", move_to("top-left")),
awful.key({modkey}, "Delete", move_to("bottom-left")),
awful.key({modkey}, "u", expand_horizontal("center")),
awful.key({modkey}, "Home", expand_horizontal("center")),
awful.key({modkey}, "Page_Up", move_to("top-right")),
awful.key({modkey}, "Page_Down", move_to("bottom-right")),
--▨ move (positional)
awful.key({modkey, "Shift"}, "Insert", expand_horizontal("left")),
awful.key({modkey, "Shift"}, "End", toggle_always_on),
awful.key({modkey, "Shift"}, "Home", move_to("center")),
awful.key({modkey, "Shift"}, "Page_Up", expand_horizontal("right")),
awful.key({modkey, "Shift"}, "Page_Down", expand_vertical),
--▨ expand (neighbor)
awful.key({modkey}, "End", function(c)
client.focus.maximized_vertical = false
client.focus.maximized_horizontal = false
awful.client.floating.toggle()
end), --|toggle floating status
awful.key({modkey}, "Left", focus_by_direction("left")),
awful.key({modkey}, "Down", focus_by_direction("down")),
awful.key({modkey}, "Right", focus_by_direction("right")),
awful.key({modkey}, "Up", focus_by_direction("up")),
--▨ focus
awful.key({modkey,}, "o", teleport_client), --|client teleport to other screen
}
--------------------------------------------------------------- signals -- ;
tag.connect_signal("property::selected", function(t)
if client.focus == nil then
local s = awful.screen.focused()
client.focus = awful.client.focus.history.get(s, 0)
end
end) --|ensure there is always a selected client during tag
--|switching or logins
client.connect_signal("manage", function(c)
c.maximized = false
c.maximized_horizontal = false
c.maximized_vertical = false
end) --|during reload maximized clients get messed up, as machi
--|also tries to best fit the windows. this resets the
--|maximized state during a reload problem is with our hack
--|to use maximized, we should look into using machi
--|resize_handler instead
client.connect_signal("request::activate", function(c)
c.hidden = false
-- c.minimized = false
c:raise()
client.focus = c
end) --|this is needed to ensure floating stuff becomes
--|visible when invoked through run_or_raise.
client.connect_signal("focus", function(c)
if not (c.bypass or c.always_on) then
if not c.floating then
for _, tc in ipairs(screen[awful.screen.focused()].all_clients) do
if tc.floating and not tc.always_on then
tc.hidden = true
end
end
return
end
if c.floating then
for _, tc in ipairs(screen[awful.screen.focused()].all_clients) do
if tc.floating and not tc.role then
tc.hidden = false
end
end
return
end
end
end)
--[[+]
hide all floating windows when the user switches to a tiled
client. This is handy when you have a floating browser
open. Unless, client is set to always_on or bypass through
rules. ]]
--------------------------------------------------------------- exports -- ;
module = {
bindings = bindings
}
local function new(arg)
capi.root.keys(awful.util.table.join(capi.root.keys(), table.unpack(bindings)))
return module
end
return setmetatable(module, { __call = function(_,...) return new({...}) end }) |
module("EnemyEntity", package.seeall)
setmetatable(EnemyEntity, {__index=PlayerEntity})
function new(cid, propID)
local entity = {
}
setmetatable(entity, {__index=EnemyEntity})
entity:Init(cid, propID)
return entity
end
function Init(self, cid, propID)
PlayerEntity.Init(self, cid, propID)
self.type = self.type + resmng.XActorType.Enemy
end |
-- 24RightAngles
-- Modified by CloneTrooper1019
local module = {}
local importer = script.Parent
local core = importer.Parent
local modules = core.Modules
local GuiUtilities = require(modules.GuiUtilities)
local ProgressFrame = require(modules.ProgressFrame)
local CustomTextButton = require(modules.CustomTextButton)
local LabeledTextInput = require(modules.LabeledTextInput)
local ImageButtonWithText = require(modules.ImageButtonWithText)
local TabbableVector3Input = require(modules.TabbableVector3Input)
local CollapsibleTitledSection = require(modules.CollapsibleTitledSection)
local VerticallyScalingListFrame = require(modules.VerticallyScalingListFrame)
local HeightMapper = require(importer.HeightMapper)
local ImageSelector = require(importer.ImageSelector)
local CoreGui = game:GetService('CoreGui')
local StudioService = game:GetService("StudioService")
local UserInputService = game:GetService("UserInputService")
local ChangeHistoryService = game:GetService('ChangeHistoryService')
local ON_LIGHT = "rbxasset://textures/TerrainTools/import_toggleOn.png"
local OFF_LIGHT = "rbxasset://textures/TerrainTools/import_toggleOff.png"
local ON_DARK = "rbxasset://textures/TerrainTools/import_toggleOn_dark.png"
local OFF_DARK = "rbxasset://textures/TerrainTools/import_toggleOff_dark.png"
local toggleOnImage = ON_LIGHT
local toggleOffImage = OFF_LIGHT
local supportedFileType = {"png"}
local useColorMap = false
local terrain
local mouse = nil
local pluginGui = nil
local screenGui = nil
local progressFrameObj = nil
local progressFrame = nil
local progressUpdate = nil
local heightMapper = nil
local MIN_STUDS = 5
local MAX_STUDS = 16384
local MIN_STUDS_ERROR_STR = string.format("Input must be greater than %d studs.", MIN_STUDS - 1)
local MAX_STUDS_ERROR_STR = string.format("Input can not exceed %d studs.", MAX_STUDS)
local INVALID_INPUT_ERROR = "Input is not a valid number."
local WARN_HEIGHTMAP_MISSING = "HeightMap required to begin importing Terrain"
local WARN_INVALID_POS_INPUT = "Position has invalid input"
local WARN_INVALID_SIZE_INPUT = "Size has invalid input."
local WARN_SIZE_REQUIRED = "Size of region must be defined."
-- these two targets are ImageSelectors that
-- hold the target files
local targetHeightMap = nil
local targetColorMap = nil
local regionPosition = nil
local regionSize = nil
-- for each of x, y, z
local posHasError = {false, false, false}
local sizeHasError = {false, false, false}
local terrainImporterFrame = nil
local generating = false
local SECOND_COLUMN_OFFSET = 90 + GuiUtilities.StandardLineLabelLeftMargin
local TEXTBOX_HEIGHT = 22
local LABEL_HEIGHT = 16
local SECTION_PADDING = 12
local PADDING = 4
local IMAGE_SELECT_FRAME_SIZE = UDim2.new(1, 0, 0, 60)
local function MakeTerrainImporterFrame()
local verticallyScalingListFrameObj = VerticallyScalingListFrame.new("GenerationFrame")
local verticallyScalingListFrame = verticallyScalingListFrameObj:GetFrame()
local mapSettingsFrame = MakeMapSettingsFrame()
mapSettingsFrame.Parent = verticallyScalingListFrame
mapSettingsFrame.LayoutOrder = 1
local materialSettingsFrame = MakeMaterialSettingsFrame()
materialSettingsFrame.Parent = verticallyScalingListFrame
materialSettingsFrame.LayoutOrder = 2
local importButtonFrame = MakeButtonsFrame()
importButtonFrame.Parent = verticallyScalingListFrame
importButtonFrame.LayoutOrder = 3
return verticallyScalingListFrame
end
function module:Setup(thePluginGui, contentFrame)
terrain = workspace.Terrain
pluginGui = thePluginGui
screenGui = Instance.new("ScreenGui")
screenGui.Name = "_TerrainImportGui"
progressFrameObj = ProgressFrame.new()
progressFrame = progressFrameObj:GetFrame()
progressFrameObj:GetPauseButton().Visible = false
progressFrameObj:GetCancelButton().Visible = false
progressFrame.Parent = screenGui
progressUpdate = Instance.new("BindableEvent")
heightMapper = HeightMapper.new(progressUpdate)
progressUpdate.Event:Connect(function (completionPercent)
if completionPercent < 1 then
progressFrame.Visible = true
progressFrameObj:GetFill().Size = UDim2.new(completionPercent, 0, 1, 0)
else
progressFrame.Visible = false
end
end)
terrainImporterFrame = MakeTerrainImporterFrame()
terrainImporterFrame.Parent = contentFrame
terrainImporterFrame.ImportButton.ImportTerrainButton.MouseButton1Down:connect(importTerrain)
return terrainImporterFrame
end
function MakeMapSettingsFrame()
local mapSettingsObj = CollapsibleTitledSection.new('MapSettingsFrame',
"Map Settings", -- need to localize
true, -- show title
true, -- minimizable
false)-- init minimized
local contentFrame = mapSettingsObj:GetContentsFrame()
local hackPadding = Instance.new("Frame")
hackPadding.BorderSizePixel = 0
hackPadding.LayoutOrder = 1
hackPadding.Parent = contentFrame
local heightMapFrame = Instance.new("Frame")
heightMapFrame.Size = IMAGE_SELECT_FRAME_SIZE
heightMapFrame.BackgroundTransparency = 1
heightMapFrame.LayoutOrder = 2
heightMapFrame.Parent = contentFrame
local heightMapLabel = GuiUtilities.MakeStandardPropertyLabel("Heightmap")
heightMapLabel.TextYAlignment = Enum.TextYAlignment.Top
heightMapLabel.Parent = heightMapFrame
targetHeightMap = ImageSelector.new(supportedFileType)
targetHeightMap:getFrame().Position = UDim2.new(0, SECOND_COLUMN_OFFSET, 0, 0)
targetHeightMap:getFrame().Parent = heightMapFrame
local initialFrameHeight = TEXTBOX_HEIGHT * 3 + PADDING * 2
regionPosition = TabbableVector3Input.new("Position", {0, 0, 0})
regionPosition:GetFrame().LayoutOrder = 3
regionPosition:GetFrame().Parent = contentFrame
regionPosition:SetWarningFunc(function (text, index)
local num = tonumber(text)
if num then
posHasError[index] = false
return true
end
posHasError[index] = true
return false, INVALID_INPUT_ERROR
end)
regionSize = TabbableVector3Input.new("Size", {1024, 512, 1024})
regionSize:GetFrame().LayoutOrder = 4
regionSize:GetFrame().Parent = contentFrame
-- these error messages should be localized when we submit changes for the final
regionSize:SetWarningFunc(function (text, index)
local num = tonumber(text)
sizeHasError[index] = true
if not num then
return false, INVALID_INPUT_ERROR
end
if num < MIN_STUDS then
return false, MIN_STUDS_ERROR_STR
end
if num > MAX_STUDS then
return false, MAX_STUDS_ERROR_STR
end
sizeHasError[index] = false
return true
end)
--link the position and region so we can tab across them
regionPosition:LinkToNextTabbableVector3Input(regionSize)
regionSize:LinkToNextTabbableVector3Input(regionPosition)
local hackPadding2 = Instance.new("Frame")
hackPadding2.BorderSizePixel = 0
hackPadding2.LayoutOrder = 5
hackPadding2.Parent = contentFrame
local sectionUIListLayout = Instance.new("UIListLayout")
sectionUIListLayout.Padding = UDim.new(0, SECTION_PADDING)
sectionUIListLayout.SortOrder = Enum.SortOrder.LayoutOrder
sectionUIListLayout.FillDirection = Enum.FillDirection.Vertical
sectionUIListLayout.Parent = contentFrame
GuiUtilities.AdjustHeightDynamicallyToLayout(contentFrame, sectionUIListLayout)
return mapSettingsObj:GetSectionFrame()
end
function MakeMaterialSettingsFrame()
local materialFrameObj = CollapsibleTitledSection.new('MaterialSettings',
"Material Settings", -- need localize
true, -- show title
true, -- minimizable
false-- init minimized
)
local materialFrame = materialFrameObj:GetContentsFrame()
local hackPadding = Instance.new("Frame")
hackPadding.BorderSizePixel = 0
hackPadding.LayoutOrder = 1
hackPadding.Parent = materialFrame
local colorMatSliderFrame = Instance.new("Frame")
colorMatSliderFrame.Size = UDim2.new(1, 0, 0, TEXTBOX_HEIGHT)
colorMatSliderFrame.BackgroundTransparency = 1
colorMatSliderFrame.LayoutOrder = 2
colorMatSliderFrame.Parent = materialFrame
local colorMapLabel = GuiUtilities.MakeStandardPropertyLabel("Use Colormap")
colorMapLabel.TextYAlignment = Enum.TextYAlignment.Top
colorMapLabel.AnchorPoint = Vector2.new(0, 0)
colorMapLabel.Parent = colorMatSliderFrame
local initTheme = settings().Studio["UI Theme"]
toggleOffImage = initTheme == Enum.UITheme.Dark and OFF_DARK or OFF_LIGHT
toggleOnImage = initTheme == Enum.UITheme.Dark and ON_DARK or ON_LIGHT
local toggleButton = Instance.new("ImageButton")
toggleButton.Size = UDim2.new(0, 27, 0, LABEL_HEIGHT)
toggleButton.Position = UDim2.new(0, SECOND_COLUMN_OFFSET, 1, -LABEL_HEIGHT)
toggleButton.Image = toggleOffImage
toggleButton.BackgroundTransparency = 1
toggleButton.Parent = colorMatSliderFrame
-- button Toggle
toggleButton.Activated:connect(function ()
useColorMap = not useColorMap
if useColorMap then
toggleButton.Image = toggleOnImage
else
toggleButton.Image = toggleOffImage
end
end)
settings().Studio.ThemeChanged:connect(function ()
if settings().Studio["UI Theme"] == Enum.UITheme.Dark then
toggleOffImage = OFF_DARK
toggleOnImage = ON_DARK
else -- we could check for light but since it's the fall back no need
toggleOffImage = OFF_LIGHT
toggleOnImage = ON_LIGHT
end
toggleButton.Image = useColorMap and toggleOnImage or toggleOffImage
end)
local colorMatFrame = Instance.new("Frame")
colorMatFrame.Size = IMAGE_SELECT_FRAME_SIZE
colorMatFrame.BackgroundTransparency = 1
colorMatFrame.LayoutOrder = 3
colorMatFrame.Parent = materialFrame
targetColorMap = ImageSelector.new(supportedFileType)
targetColorMap:getFrame().Position = UDim2.new(0, SECOND_COLUMN_OFFSET, 0, 0)
targetColorMap:getFrame().Parent = colorMatFrame
targetColorMap:setImageSelectedCallback(function ()
useColorMap = true
toggleButton.Image = toggleOnImage
end)
local hackPadding2 = Instance.new("Frame")
hackPadding2.BorderSizePixel = 0
hackPadding2.LayoutOrder = 4
hackPadding2.Parent = materialFrame
local sectionUIListLayout = Instance.new("UIListLayout")
sectionUIListLayout.Padding = UDim.new(0, 8)
sectionUIListLayout.SortOrder = Enum.SortOrder.LayoutOrder
sectionUIListLayout.FillDirection = Enum.FillDirection.Vertical
sectionUIListLayout.Parent = materialFrame
GuiUtilities.AdjustHeightDynamicallyToLayout(materialFrame, sectionUIListLayout)
return materialFrameObj:GetSectionFrame()
end
function MakeButtonsFrame()
local frame = GuiUtilities.MakeFixedHeightFrame("ImportButton", GuiUtilities.kBottomButtonsFrameHeight)
frame.BackgroundTransparency = 1
local importButtonObj = CustomTextButton.new("ImportTerrainButton", "Import")
local importButton = importButtonObj:getButton()
importButton.Size = UDim2.new(.7, 0, 0, GuiUtilities.kBottomButtonsHeight)
importButton.Position = UDim2.new(.15, 0, 1, -GuiUtilities.kBottomButtonsHeight)
importButton.Parent = frame
return frame
end
function importTerrain()
if targetHeightMap and not targetHeightMap:imageSelected() then
warn(WARN_HEIGHTMAP_MISSING)
return
end
if posHasError[1] or posHasError[2] or posHasError[3] then
warn(WARN_INVALID_POS_INPUT)
return
end
if sizeHasError[1] or sizeHasError[2] or sizeHasError[3] then
warn(WARN_INVALID_SIZE_INPUT)
return
end
terrain = workspace.Terrain
if not generating then
generating = true
local size = regionSize:GetVector3()
local center = regionPosition:GetVector3() or Vector3.new(0, 0, 0)
local region
if size then
-- expect Studs
local offset = size / 2
local regionStart = (center - offset)
local regionEnd = (center + offset)
region = Region3.new(regionStart, regionEnd)
region = region:ExpandToGrid(4)
local heightMap = targetHeightMap:getPngFile()
local colorMap = nil
if useColorMap and targetColorMap and targetColorMap:imageSelected() then
colorMap = targetColorMap:getPngFile()
end
heightMapper:Import(region, heightMap, colorMap)
else
warn(WARN_SIZE_REQUIRED)
end
generating = false
end
end
function module:SetEnabled(enabled)
terrainImporterFrame.Visible = enabled
screenGui.Parent = enabled and CoreGui or nil
end
return module |
------------------------------------------------------------------------
-- Copyright (C) 1994-2008 Lua.org, PUC-Rio. All rights reserved.
--
-- 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.
------------------------------------------------------------------------
-- Operating System Facilities http://www.lua.org/manual/5.3/manual.html#pdf-os.clock
-- This library is implemented through table os.
os = {}
-- os.clock Returns an approximation of the amount in seconds of CPU time used by the program.
function os.clock() end
-- os.date Returns a string or a table containing date and time, formatted according to the given string format.
-- If the time argument is present, this is the time to be formatted (see the os.time function for a description of this value). Otherwise, date formats the current time.
-- If format starts with '!', then the date is formatted in Coordinated Universal Time. After this optional character, if format is the string "*t", then date returns a table with the following fields: year, month (1–12), day (1–31), hour (0–23), min (0–59), sec (0–61), wday (weekday, 1–7, Sunday is 1), yday (day of the year, 1–366), and isdst (daylight saving flag, a boolean). This last field may be absent if the information is not available.
-- If format is not "*t", then date returns the date as a string, formatted according to the same rules as the ISO C function strftime.
-- When called without arguments, date returns a reasonable date and time representation that depends on the host system and on the current locale. (More specifically, os.date() is equivalent to os.date("%c").)
-- In non-POSIX systems, this function may be not thread safe because of its reliance on C function gmtime and C function localtime.
function os.date(format, time) end
-- os.difftime Returns the difference, in seconds, from time t1 to time t2 (where the times are values returned by os.time). In POSIX, Windows, and some other systems, this value is exactly t2-t1.
function os.difftime(t2, t1) end
-- This function is equivalent to the ISO C function system. It passes command to be executed by an operating system shell. Its first result is true if the command terminated successfully, or nil otherwise. After this first result the function returns a string plus a number, as follows:
-- "exit": the command terminated normally; the following number is the exit status of the command.
-- "signal": the command was terminated by a signal; the following number is the signal that terminated the command.
-- When called without a command, os.execute returns a boolean that is true if a shell is available.
function os.execute(command) end
-- Calls the ISO C function exit to terminate the host program. If code is true, the returned status is EXIT_SUCCESS; if code is false, the returned status is EXIT_FAILURE; if code is a number, the returned status is this number. The default value for code is true.
-- If the optional second argument close is true, closes the Lua state before exiting.
function os.exit(code, close) end
-- Returns the value of the process environment variable varname, or nil if the variable is not defined.
function os.getenv(varname) end
-- Deletes the file (or empty directory, on POSIX systems) with the given name. If this function fails, it returns nil, plus a string describing the error and the error code. Otherwise, it returns true.
function os.remove(filename) end
-- Renames the file or directory named oldname to newname. If this function fails, it returns nil, plus a string describing the error and the error code. Otherwise, it returns true.
function os.rename(oldname, newname) end
-- Sets the current locale of the program. locale is a system-dependent string specifying a locale; category is an optional string describing which category to change: "all", "collate", "ctype", "monetary", "numeric", or "time"; the default category is "all". The function returns the name of the new locale, or nil if the request cannot be honored.
-- If locale is the empty string, the current locale is set to an implementation-defined native locale. If locale is the string "C", the current locale is set to the standard C locale.
-- When called with nil as the first argument, this function only returns the name of the current locale for the given category.
-- This function may be not thread safe because of its reliance on C function setlocale.
function os.setlocale(locale, category) end
-- Returns the current time when called without arguments, or a time representing the local date and time specified by the given table. This table must have fields year, month, and day, and may have fields hour (default is 12), min (default is 0), sec (default is 0), and isdst (default is nil). Other fields are ignored. For a description of these fields, see the os.date function.
-- The values in these fields do not need to be inside their valid ranges. For instance, if sec is -10, it means -10 seconds from the time specified by the other fields; if hour is 1000, it means +1000 hours from the time specified by the other fields.
-- The returned value is a number, whose meaning depends on your system. In POSIX, Windows, and some other systems, this number counts the number of seconds since some given start time (the "epoch"). In other systems, the meaning is not specified, and the number returned by time can be used only as an argument to os.date and os.difftime.
function os.time(table) end
-- Returns a string with a file name that can be used for a temporary file. The file must be explicitly opened before its use and explicitly removed when no longer needed.
-- In POSIX systems, this function also creates a file with that name, to avoid security risks. (Someone else might create the file with wrong permissions in the time between getting the name and creating the file.) You still have to open the file to use it and to remove it (even if you do not use it).
-- When possible, you may prefer to use io.tmpfile, which automatically removes the file when the program ends.
function os.tmpname() end |
return {
include = function()
includedirs { "../vendor/nghttp2/lib/includes/" }
defines { '_SSIZE_T_DEFINED=1', '_U_=', 'NGHTTP2_STATICLIB' }
if os.istarget('windows') then
defines 'ssize_t=__int64'
else
-- check if this is a glibc distro
local succ, status, code = os.execute('ldd --version | grep -c "Free Software Foundation"')
if code ~= 0 then
defines 'ssize_t=long'
end
end
end,
run = function()
targetname "nghttp2"
language "C"
kind "StaticLib"
flags "NoRuntimeChecks"
files_project '../vendor/nghttp2/lib/'
{
'*.c'
}
end
}
|
local t = {}
local function ScopedConnect(parentInstance, instance, event, signalFunc, syncFunc, removeFunc)
local eventConnection = nil
--Connection on parentInstance is scoped by parentInstance (when destroyed, it goes away)
local tryConnect = function()
if game:IsAncestorOf(parentInstance) then
--Entering the world, make sure we are connected/synced
if not eventConnection then
eventConnection = instance[event]:connect(signalFunc)
if syncFunc then syncFunc() end
end
else
--Probably leaving the world, so disconnect for now
if eventConnection then
eventConnection:disconnect()
if removeFunc then removeFunc() end
end
end
end
--Hook it up to ancestryChanged signal
local connection = parentInstance.AncestryChanged:connect(tryConnect)
--Now connect us if we're already in the world
tryConnect()
return connection
end
local function getLayerCollectorAncestor(instance)
local localInstance = instance
while localInstance and not localInstance:IsA("LayerCollector") do
localInstance = localInstance.Parent
end
return localInstance
end
local function CreateButtons(frame, buttons, yPos, ySize)
local buttonNum = 1
local buttonObjs = {}
for i, obj in ipairs(buttons) do
local button = Instance.new("TextButton")
button.Name = "Button" .. buttonNum
button.Font = Enum.Font.Arial
button.FontSize = Enum.FontSize.Size18
button.AutoButtonColor = true
button.Modal = true
if obj["Style"] then
button.Style = obj.Style
else
button.Style = Enum.ButtonStyle.RobloxButton
end
if obj["ZIndex"] then
button.ZIndex = obj.ZIndex
end
button.Text = obj.Text
button.TextColor3 = Color3.new(1,1,1)
button.MouseButton1Click:connect(obj.Function)
button.Parent = frame
buttonObjs[buttonNum] = button
buttonNum = buttonNum + 1
end
local numButtons = buttonNum-1
if numButtons == 1 then
frame.Button1.Position = UDim2.new(0.35, 0, yPos.Scale, yPos.Offset)
frame.Button1.Size = UDim2.new(.4,0,ySize.Scale, ySize.Offset)
elseif numButtons == 2 then
frame.Button1.Position = UDim2.new(0.1, 0, yPos.Scale, yPos.Offset)
frame.Button1.Size = UDim2.new(.8/3,0, ySize.Scale, ySize.Offset)
frame.Button2.Position = UDim2.new(0.55, 0, yPos.Scale, yPos.Offset)
frame.Button2.Size = UDim2.new(.35,0, ySize.Scale, ySize.Offset)
elseif numButtons >= 3 then
local spacing = .1 / numButtons
local buttonSize = .9 / numButtons
buttonNum = 1
while buttonNum <= numButtons do
buttonObjs[buttonNum].Position = UDim2.new(spacing*buttonNum + (buttonNum-1) * buttonSize, 0, yPos.Scale, yPos.Offset)
buttonObjs[buttonNum].Size = UDim2.new(buttonSize, 0, ySize.Scale, ySize.Offset)
buttonNum = buttonNum + 1
end
end
end
local function setSliderPos(newAbsPosX,slider,sliderPosition,bar,steps)
local newStep = steps - 1 --otherwise we really get one more step than we want
local relativePosX = math.min(1, math.max(0, (newAbsPosX - bar.AbsolutePosition.X) / bar.AbsoluteSize.X ))
local wholeNum, remainder = math.modf(relativePosX * newStep)
if remainder > 0.5 then
wholeNum = wholeNum + 1
end
relativePosX = wholeNum/newStep
local result = math.ceil(relativePosX * newStep)
if sliderPosition.Value ~= (result + 1) then --only update if we moved a step
sliderPosition.Value = result + 1
slider.Position = UDim2.new(relativePosX,-slider.AbsoluteSize.X/2,slider.Position.Y.Scale,slider.Position.Y.Offset)
end
end
local function cancelSlide(areaSoak)
areaSoak.Visible = false
end
t.CreateStyledMessageDialog = function(title, message, style, buttons)
local frame = Instance.new("Frame")
frame.Size = UDim2.new(0.5, 0, 0, 165)
frame.Position = UDim2.new(0.25, 0, 0.5, -72.5)
frame.Name = "MessageDialog"
frame.Active = true
frame.Style = Enum.FrameStyle.RobloxRound
local styleImage = Instance.new("ImageLabel")
styleImage.Name = "StyleImage"
styleImage.BackgroundTransparency = 1
styleImage.Position = UDim2.new(0,5,0,15)
if style == "error" or style == "Error" then
styleImage.Size = UDim2.new(0, 71, 0, 71)
styleImage.Image = "https://www.roblox.com/asset/?id=42565285"
elseif style == "notify" or style == "Notify" then
styleImage.Size = UDim2.new(0, 71, 0, 71)
styleImage.Image = "https://www.roblox.com/asset/?id=42604978"
elseif style == "confirm" or style == "Confirm" then
styleImage.Size = UDim2.new(0, 74, 0, 76)
styleImage.Image = "https://www.roblox.com/asset/?id=42557901"
else
return t.CreateMessageDialog(title,message,buttons)
end
styleImage.Parent = frame
local titleLabel = Instance.new("TextLabel")
titleLabel.Name = "Title"
titleLabel.Text = title
titleLabel.TextStrokeTransparency = 0
titleLabel.BackgroundTransparency = 1
titleLabel.TextColor3 = Color3.new(221/255,221/255,221/255)
titleLabel.Position = UDim2.new(0, 80, 0, 0)
titleLabel.Size = UDim2.new(1, -80, 0, 40)
titleLabel.Font = Enum.Font.ArialBold
titleLabel.FontSize = Enum.FontSize.Size36
titleLabel.TextXAlignment = Enum.TextXAlignment.Center
titleLabel.TextYAlignment = Enum.TextYAlignment.Center
titleLabel.Parent = frame
local messageLabel = Instance.new("TextLabel")
messageLabel.Name = "Message"
messageLabel.Text = message
messageLabel.TextStrokeTransparency = 0
messageLabel.TextColor3 = Color3.new(221/255,221/255,221/255)
messageLabel.Position = UDim2.new(0.025, 80, 0, 45)
messageLabel.Size = UDim2.new(0.95, -80, 0, 55)
messageLabel.BackgroundTransparency = 1
messageLabel.Font = Enum.Font.Arial
messageLabel.FontSize = Enum.FontSize.Size18
messageLabel.TextWrap = true
messageLabel.TextXAlignment = Enum.TextXAlignment.Left
messageLabel.TextYAlignment = Enum.TextYAlignment.Top
messageLabel.Parent = frame
CreateButtons(frame, buttons, UDim.new(0, 105), UDim.new(0, 40) )
return frame
end
t.CreateMessageDialog = function(title, message, buttons)
local frame = Instance.new("Frame")
frame.Size = UDim2.new(0.5, 0, 0.5, 0)
frame.Position = UDim2.new(0.25, 0, 0.25, 0)
frame.Name = "MessageDialog"
frame.Active = true
frame.Style = Enum.FrameStyle.RobloxRound
local titleLabel = Instance.new("TextLabel")
titleLabel.Name = "Title"
titleLabel.Text = title
titleLabel.BackgroundTransparency = 1
titleLabel.TextColor3 = Color3.new(221/255,221/255,221/255)
titleLabel.Position = UDim2.new(0, 0, 0, 0)
titleLabel.Size = UDim2.new(1, 0, 0.15, 0)
titleLabel.Font = Enum.Font.ArialBold
titleLabel.FontSize = Enum.FontSize.Size36
titleLabel.TextXAlignment = Enum.TextXAlignment.Center
titleLabel.TextYAlignment = Enum.TextYAlignment.Center
titleLabel.Parent = frame
local messageLabel = Instance.new("TextLabel")
messageLabel.Name = "Message"
messageLabel.Text = message
messageLabel.TextColor3 = Color3.new(221/255,221/255,221/255)
messageLabel.Position = UDim2.new(0.025, 0, 0.175, 0)
messageLabel.Size = UDim2.new(0.95, 0, .55, 0)
messageLabel.BackgroundTransparency = 1
messageLabel.Font = Enum.Font.Arial
messageLabel.FontSize = Enum.FontSize.Size18
messageLabel.TextWrap = true
messageLabel.TextXAlignment = Enum.TextXAlignment.Left
messageLabel.TextYAlignment = Enum.TextYAlignment.Top
messageLabel.Parent = frame
CreateButtons(frame, buttons, UDim.new(0.8,0), UDim.new(0.15, 0))
return frame
end
-- written by jmargh
-- to be used for the new settings menu
t.CreateScrollingDropDownMenu = function(onSelectedCallback, size, position, baseZ)
local maxVisibleList = 6
local baseZIndex = 0
if type(baseZ) == 'number' then
baseZIndex = baseZ
end
local dropDownMenu = {}
local currentList = nil
local updateFunc = nil
local frame = Instance.new('Frame')
frame.Name = "DropDownMenuFrame"
frame.Size = size
frame.Position = position
frame.BackgroundTransparency = 1
dropDownMenu.Frame = frame
local currentSelectionName = Instance.new('TextButton')
currentSelectionName.Name = "CurrentSelectionName"
currentSelectionName.Size = UDim2.new(1, 0, 1, 0)
currentSelectionName.BackgroundTransparency = 1
currentSelectionName.Font = Enum.Font.SourceSansBold
currentSelectionName.FontSize = Enum.FontSize.Size18
currentSelectionName.TextXAlignment = Enum.TextXAlignment.Left
currentSelectionName.TextYAlignment = Enum.TextYAlignment.Center
currentSelectionName.TextColor3 = Color3.new(0.5, 0.5, 0.5)
currentSelectionName.TextWrap = true
currentSelectionName.ZIndex = baseZIndex
currentSelectionName.Style = Enum.ButtonStyle.RobloxRoundDropdownButton
currentSelectionName.Text = "Choose One"
currentSelectionName.Parent = frame
dropDownMenu.CurrentSelectionButton = currentSelectionName
local icon = Instance.new('ImageLabel')
icon.Name = "DropDownIcon"
icon.Size = UDim2.new(0, 16, 0, 12)
icon.Position = UDim2.new(1, -17, 0.5, -6)
icon.Image = 'rbxasset://textures/ui/dropdown_arrow.png'
icon.BackgroundTransparency = 1
icon.ZIndex = baseZIndex
icon.Parent = currentSelectionName
local listMenu = nil
local scrollingBackground = nil
local visibleCount = 0
local isOpen = false
local function onEntrySelected()
icon.Rotation = 0
scrollingBackground:TweenSize(UDim2.new(1, 0, 0, currentSelectionName.AbsoluteSize.y), Enum.EasingDirection.InOut, Enum.EasingStyle.Sine, 0.15, true)
--
listMenu.ScrollBarThickness = 0
listMenu:TweenSize(UDim2.new(1, -16, 0, 24), Enum.EasingDirection.InOut, Enum.EasingStyle.Sine, 0.15, true, function()
if not isOpen then
listMenu.Visible = false
scrollingBackground.Visible = false
end
end)
isOpen = false
end
currentSelectionName.MouseButton1Click:connect(function()
if not currentSelectionName.Active or #currentList == 0 then return end
if isOpen then
onEntrySelected()
return
end
--
isOpen = true
icon.Rotation = 180
if listMenu then listMenu.Visible = true end
if scrollingBackground then scrollingBackground.Visible = true end
--
if scrollingBackground then
scrollingBackground:TweenSize(UDim2.new(1, 0, 0, visibleCount * 24 + 8), Enum.EasingDirection.InOut, Enum.EasingStyle.Sine, 0.15, true)
end
if listMenu then
listMenu:TweenSize(UDim2.new(1, -16, 0, visibleCount * 24), Enum.EasingDirection.InOut, Enum.EasingStyle.Sine, 0.15, true, function()
listMenu.ScrollBarThickness = 6
end)
end
end)
--[[ Public API ]]--
dropDownMenu.IsOpen = function()
return isOpen
end
dropDownMenu.Close = function()
onEntrySelected()
end
dropDownMenu.Reset = function()
isOpen = false
icon.Rotation = 0
listMenu.ScrollBarThickness = 0
listMenu.Size = UDim2.new(1, -16, 0, 24)
listMenu.Visible = false
scrollingBackground.Visible = false
end
dropDownMenu.SetVisible = function(isVisible)
if frame then
frame.Visible = isVisible
end
end
dropDownMenu.UpdateZIndex = function(newZIndexBase)
currentSelectionName.ZIndex = newZIndexBase
icon.ZIndex = newZIndexBase
if scrollingBackground then scrollingBackground.ZIndex = newZIndexBase + 1 end
if listMenu then
listMenu.ZIndex = newZIndexBase + 2
for _,child in pairs(listMenu:GetChildren()) do
child.ZIndex = newZIndexBase + 4
end
end
end
dropDownMenu.SetActive = function(isActive)
currentSelectionName.Active = isActive
end
dropDownMenu.SetSelectionText = function(text)
currentSelectionName.Text = text
end
dropDownMenu.CreateList = function(list)
currentSelectionName.Text = "Choose One"
if listMenu then listMenu:Destroy() end
if scrollingBackground then scrollingBackground:Destroy() end
--
currentList = list
local length = #list
visibleCount = math.min(maxVisibleList, length)
local listMenuOffset = visibleCount * 24
listMenu = Instance.new('ScrollingFrame')
listMenu.Name = "ListMenu"
listMenu.Size = UDim2.new(1, -16, 0, 24)
listMenu.Position = UDim2.new(0, 12, 0, 32)
listMenu.CanvasSize = UDim2.new(0, 0, 0, length * 24)
listMenu.BackgroundTransparency = 1
listMenu.BorderSizePixel = 0
listMenu.ZIndex = baseZIndex + 2
listMenu.Visible = false
listMenu.Active = true
listMenu.BottomImage = 'rbxasset://textures/ui/scroll-bottom.png'
listMenu.MidImage = 'rbxasset://textures/ui/scroll-middle.png'
listMenu.TopImage = 'rbxasset://textures/ui/scroll-top.png'
listMenu.ScrollBarThickness = 0
listMenu.Parent = frame
scrollingBackground = Instance.new('TextButton')
scrollingBackground.Name = "ScrollingBackground"
scrollingBackground.Size = UDim2.new(1, 0, 0, currentSelectionName.AbsoluteSize.y)
scrollingBackground.Position = UDim2.new(0, 0, 0, 28)
scrollingBackground.BackgroundColor3 = Color3.new(1, 1, 1)
scrollingBackground.Style = Enum.ButtonStyle.RobloxRoundDropdownButton
scrollingBackground.ZIndex = baseZIndex + 1
scrollingBackground.Text = ""
scrollingBackground.Visible = false
scrollingBackground.AutoButtonColor = false
scrollingBackground.Parent = frame
for i = 1, length do
local entry = list[i]
local btn = Instance.new('TextButton')
btn.Name = entry
btn.Size = UDim2.new(1, 0, 0, 24)
btn.Position = UDim2.new(0, 0, 0, (i - 1) * 24)
btn.BackgroundTransparency = 0
btn.BackgroundColor3 = Color3.new(1, 1, 1)
btn.BorderSizePixel = 0
btn.Font = Enum.Font.SourceSans
btn.FontSize = Enum.FontSize.Size18
btn.TextColor3 = Color3.new(0.5, 0.5, 0.5)
btn.TextXAlignment = Enum.TextXAlignment.Left
btn.TextYAlignment = Enum.TextYAlignment.Center
btn.Text = entry
btn.ZIndex = baseZIndex + 4
btn.AutoButtonColor = false
btn.Parent = listMenu
btn.MouseButton1Click:connect(function()
currentSelectionName.Text = btn.Text
onEntrySelected()
btn.Font = Enum.Font.SourceSans
btn.TextColor3 = Color3.new(0.5, 0.5, 0.5)
btn.BackgroundColor3 = Color3.new(1, 1, 1)
onSelectedCallback(btn.Text)
end)
btn.MouseEnter:connect(function()
btn.TextColor3 = Color3.new(1, 1, 1)
btn.BackgroundColor3 = Color3.new(0.75, 0.75, 0.75)
end)
btn.MouseLeave:connect(function()
btn.TextColor3 = Color3.new(0.5, 0.5, 0.5)
btn.BackgroundColor3 = Color3.new(1, 1, 1)
end)
end
end
return dropDownMenu
end
t.CreateDropDownMenu = function(items, onSelect, forRoblox, whiteSkin, baseZ)
local baseZIndex = 0
if (type(baseZ) == "number") then
baseZIndex = baseZ
end
local width = UDim.new(0, 100)
local height = UDim.new(0, 32)
local xPos = 0.055
local frame = Instance.new("Frame")
local textColor = Color3.new(1,1,1)
if (whiteSkin) then
textColor = Color3.new(0.5, 0.5, 0.5)
end
frame.Name = "DropDownMenu"
frame.BackgroundTransparency = 1
frame.Size = UDim2.new(width, height)
local dropDownMenu = Instance.new("TextButton")
dropDownMenu.Name = "DropDownMenuButton"
dropDownMenu.TextWrap = true
dropDownMenu.TextColor3 = textColor
dropDownMenu.Text = "Choose One"
dropDownMenu.Font = Enum.Font.ArialBold
dropDownMenu.FontSize = Enum.FontSize.Size18
dropDownMenu.TextXAlignment = Enum.TextXAlignment.Left
dropDownMenu.TextYAlignment = Enum.TextYAlignment.Center
dropDownMenu.BackgroundTransparency = 1
dropDownMenu.AutoButtonColor = true
if (whiteSkin) then
dropDownMenu.Style = Enum.ButtonStyle.RobloxRoundDropdownButton
else
dropDownMenu.Style = Enum.ButtonStyle.RobloxButton
end
dropDownMenu.Size = UDim2.new(1,0,1,0)
dropDownMenu.Parent = frame
dropDownMenu.ZIndex = 2 + baseZIndex
local dropDownIcon = Instance.new("ImageLabel")
dropDownIcon.Name = "Icon"
dropDownIcon.Active = false
if (whiteSkin) then
dropDownIcon.Image = "rbxasset://textures/ui/dropdown_arrow.png"
dropDownIcon.Size = UDim2.new(0,16,0,12)
dropDownIcon.Position = UDim2.new(1,-17,0.5, -6)
else
dropDownIcon.Image = "https://www.roblox.com/asset/?id=45732894"
dropDownIcon.Size = UDim2.new(0,11,0,6)
dropDownIcon.Position = UDim2.new(1,-11,0.5, -2)
end
dropDownIcon.BackgroundTransparency = 1
dropDownIcon.Parent = dropDownMenu
dropDownIcon.ZIndex = 2 + baseZIndex
local itemCount = #items
local dropDownItemCount = #items
local useScrollButtons = false
if dropDownItemCount > 6 then
useScrollButtons = true
dropDownItemCount = 6
end
local droppedDownMenu = Instance.new("TextButton")
droppedDownMenu.Name = "List"
droppedDownMenu.Text = ""
droppedDownMenu.BackgroundTransparency = 1
--droppedDownMenu.AutoButtonColor = true
if (whiteSkin) then
droppedDownMenu.Style = Enum.ButtonStyle.RobloxRoundDropdownButton
else
droppedDownMenu.Style = Enum.ButtonStyle.RobloxButton
end
droppedDownMenu.Visible = false
droppedDownMenu.Active = true --Blocks clicks
droppedDownMenu.Position = UDim2.new(0,0,0,0)
droppedDownMenu.Size = UDim2.new(1,0, (1 + dropDownItemCount)*.8, 0)
droppedDownMenu.Parent = frame
droppedDownMenu.ZIndex = 2 + baseZIndex
local choiceButton = Instance.new("TextButton")
choiceButton.Name = "ChoiceButton"
choiceButton.BackgroundTransparency = 1
choiceButton.BorderSizePixel = 0
choiceButton.Text = "ReplaceMe"
choiceButton.TextColor3 = textColor
choiceButton.TextXAlignment = Enum.TextXAlignment.Left
choiceButton.TextYAlignment = Enum.TextYAlignment.Center
choiceButton.BackgroundColor3 = Color3.new(1, 1, 1)
choiceButton.Font = Enum.Font.Arial
choiceButton.FontSize = Enum.FontSize.Size18
if useScrollButtons then
choiceButton.Size = UDim2.new(1,-13, .8/((dropDownItemCount + 1)*.8),0)
else
choiceButton.Size = UDim2.new(1, 0, .8/((dropDownItemCount + 1)*.8),0)
end
choiceButton.TextWrap = true
choiceButton.ZIndex = 2 + baseZIndex
local areaSoak = Instance.new("TextButton")
areaSoak.Name = "AreaSoak"
areaSoak.Text = ""
areaSoak.BackgroundTransparency = 1
areaSoak.Active = true
areaSoak.Size = UDim2.new(1,0,1,0)
areaSoak.Visible = false
areaSoak.ZIndex = 3 + baseZIndex
local dropDownSelected = false
local scrollUpButton
local scrollDownButton
local scrollMouseCount = 0
local setZIndex = function(baseZIndex)
droppedDownMenu.ZIndex = baseZIndex +1
if scrollUpButton then
scrollUpButton.ZIndex = baseZIndex + 3
end
if scrollDownButton then
scrollDownButton.ZIndex = baseZIndex + 3
end
local children = droppedDownMenu:GetChildren()
if children then
for i, child in ipairs(children) do
if child.Name == "ChoiceButton" then
child.ZIndex = baseZIndex + 2
elseif child.Name == "ClickCaptureButton" then
child.ZIndex = baseZIndex
end
end
end
end
local scrollBarPosition = 1
local updateScroll = function()
if scrollUpButton then
scrollUpButton.Active = scrollBarPosition > 1
end
if scrollDownButton then
scrollDownButton.Active = scrollBarPosition + dropDownItemCount <= itemCount
end
local children = droppedDownMenu:GetChildren()
if not children then return end
local childNum = 1
for i, obj in ipairs(children) do
if obj.Name == "ChoiceButton" then
if childNum < scrollBarPosition or childNum >= scrollBarPosition + dropDownItemCount then
obj.Visible = false
else
obj.Position = UDim2.new(0,0,((childNum-scrollBarPosition+1)*.8)/((dropDownItemCount+1)*.8),0)
obj.Visible = true
end
obj.TextColor3 = textColor
obj.BackgroundTransparency = 1
childNum = childNum + 1
end
end
end
local toggleVisibility = function()
dropDownSelected = not dropDownSelected
areaSoak.Visible = not areaSoak.Visible
dropDownMenu.Visible = not dropDownSelected
droppedDownMenu.Visible = dropDownSelected
if dropDownSelected then
setZIndex(4 + baseZIndex)
else
setZIndex(2 + baseZIndex)
end
if useScrollButtons then
updateScroll()
end
end
droppedDownMenu.MouseButton1Click:connect(toggleVisibility)
local updateSelection = function(text)
local foundItem = false
local children = droppedDownMenu:GetChildren()
local childNum = 1
if children then
for i, obj in ipairs(children) do
if obj.Name == "ChoiceButton" then
if obj.Text == text then
obj.Font = Enum.Font.ArialBold
foundItem = true
scrollBarPosition = childNum
if (whiteSkin) then
obj.TextColor3 = Color3.new(90/255,142/255,233/255)
end
else
obj.Font = Enum.Font.Arial
if (whiteSkin) then
obj.TextColor3 = textColor
end
end
childNum = childNum + 1
end
end
end
if not text then
dropDownMenu.Text = "Choose One"
scrollBarPosition = 1
else
if not foundItem then
error("Invalid Selection Update -- " .. text)
end
if scrollBarPosition + dropDownItemCount > itemCount + 1 then
scrollBarPosition = itemCount - dropDownItemCount + 1
end
dropDownMenu.Text = text
end
end
local function scrollDown()
if scrollBarPosition + dropDownItemCount <= itemCount then
scrollBarPosition = scrollBarPosition + 1
updateScroll()
return true
end
return false
end
local function scrollUp()
if scrollBarPosition > 1 then
scrollBarPosition = scrollBarPosition - 1
updateScroll()
return true
end
return false
end
if useScrollButtons then
--Make some scroll buttons
scrollUpButton = Instance.new("ImageButton")
scrollUpButton.Name = "ScrollUpButton"
scrollUpButton.BackgroundTransparency = 1
scrollUpButton.Image = "rbxasset://textures/ui/scrollbuttonUp.png"
scrollUpButton.Size = UDim2.new(0,17,0,17)
scrollUpButton.Position = UDim2.new(1,-11,(1*.8)/((dropDownItemCount+1)*.8),0)
scrollUpButton.MouseButton1Click:connect(
function()
scrollMouseCount = scrollMouseCount + 1
end)
scrollUpButton.MouseLeave:connect(
function()
scrollMouseCount = scrollMouseCount + 1
end)
scrollUpButton.MouseButton1Down:connect(
function()
scrollMouseCount = scrollMouseCount + 1
scrollUp()
local val = scrollMouseCount
wait(0.5)
while val == scrollMouseCount do
if scrollUp() == false then
break
end
wait(0.1)
end
end)
scrollUpButton.Parent = droppedDownMenu
scrollDownButton = Instance.new("ImageButton")
scrollDownButton.Name = "ScrollDownButton"
scrollDownButton.BackgroundTransparency = 1
scrollDownButton.Image = "rbxasset://textures/ui/scrollbuttonDown.png"
scrollDownButton.Size = UDim2.new(0,17,0,17)
scrollDownButton.Position = UDim2.new(1,-11,1,-11)
scrollDownButton.Parent = droppedDownMenu
scrollDownButton.MouseButton1Click:connect(
function()
scrollMouseCount = scrollMouseCount + 1
end)
scrollDownButton.MouseLeave:connect(
function()
scrollMouseCount = scrollMouseCount + 1
end)
scrollDownButton.MouseButton1Down:connect(
function()
scrollMouseCount = scrollMouseCount + 1
scrollDown()
local val = scrollMouseCount
wait(0.5)
while val == scrollMouseCount do
if scrollDown() == false then
break
end
wait(0.1)
end
end)
local scrollbar = Instance.new("ImageLabel")
scrollbar.Name = "ScrollBar"
scrollbar.Image = "rbxasset://textures/ui/scrollbar.png"
scrollbar.BackgroundTransparency = 1
scrollbar.Size = UDim2.new(0, 18, (dropDownItemCount*.8)/((dropDownItemCount+1)*.8), -(17) - 11 - 4)
scrollbar.Position = UDim2.new(1,-11,(1*.8)/((dropDownItemCount+1)*.8),17+2)
scrollbar.Parent = droppedDownMenu
end
for i,item in ipairs(items) do
-- needed to maintain local scope for items in event listeners below
local button = choiceButton:clone()
if forRoblox then
button.RobloxLocked = true
end
button.Text = item
button.Parent = droppedDownMenu
if (whiteSkin) then
button.TextColor3 = textColor
end
button.MouseButton1Click:connect(function()
--Remove Highlight
if (not whiteSkin) then
button.TextColor3 = Color3.new(1,1,1)
end
button.BackgroundTransparency = 1
updateSelection(item)
onSelect(item)
toggleVisibility()
end)
button.MouseEnter:connect(function()
--Add Highlight
if (not whiteSkin) then
button.TextColor3 = Color3.new(0,0,0)
end
button.BackgroundTransparency = 0
end)
button.MouseLeave:connect(function()
--Remove Highlight
if (not whiteSkin) then
button.TextColor3 = Color3.new(1,1,1)
end
button.BackgroundTransparency = 1
end)
end
--This does the initial layout of the buttons
updateScroll()
frame.AncestryChanged:connect(function(child,parent)
if parent == nil then
areaSoak.Parent = nil
else
areaSoak.Parent = getLayerCollectorAncestor(frame)
end
end)
dropDownMenu.MouseButton1Click:connect(toggleVisibility)
areaSoak.MouseButton1Click:connect(toggleVisibility)
return frame, updateSelection
end
t.CreatePropertyDropDownMenu = function(instance, property, enum)
local items = enum:GetEnumItems()
local names = {}
local nameToItem = {}
for i,obj in ipairs(items) do
names[i] = obj.Name
nameToItem[obj.Name] = obj
end
local frame
local updateSelection
frame, updateSelection = t.CreateDropDownMenu(names, function(text) instance[property] = nameToItem[text] end)
ScopedConnect(frame, instance, "Changed",
function(prop)
if prop == property then
updateSelection(instance[property].Name)
end
end,
function()
updateSelection(instance[property].Name)
end)
return frame
end
t.GetFontHeight = function(font, fontSize)
if font == nil or fontSize == nil then
error("Font and FontSize must be non-nil")
end
local fontSizeInt = tonumber(fontSize.Name:match("%d+")) -- Clever hack to extract the size from the enum itself.
if font == Enum.Font.Legacy then -- Legacy has a 50% bigger size.
return math.ceil(fontSizeInt*1.5)
else -- Size is literally just the fontSizeInt
return fontSizeInt
end
end
local function layoutGuiObjectsHelper(frame, guiObjects, settingsTable)
local totalPixels = frame.AbsoluteSize.Y
local pixelsRemaining = frame.AbsoluteSize.Y
for i, child in ipairs(guiObjects) do
if child:IsA("TextLabel") or child:IsA("TextButton") then
local isLabel = child:IsA("TextLabel")
if isLabel then
pixelsRemaining = pixelsRemaining - settingsTable["TextLabelPositionPadY"]
else
pixelsRemaining = pixelsRemaining - settingsTable["TextButtonPositionPadY"]
end
child.Position = UDim2.new(child.Position.X.Scale, child.Position.X.Offset, 0, totalPixels - pixelsRemaining)
child.Size = UDim2.new(child.Size.X.Scale, child.Size.X.Offset, 0, pixelsRemaining)
if child.TextFits and child.TextBounds.Y < pixelsRemaining then
child.Visible = true
if isLabel then
child.Size = UDim2.new(child.Size.X.Scale, child.Size.X.Offset, 0, child.TextBounds.Y + settingsTable["TextLabelSizePadY"])
else
child.Size = UDim2.new(child.Size.X.Scale, child.Size.X.Offset, 0, child.TextBounds.Y + settingsTable["TextButtonSizePadY"])
end
while not child.TextFits do
child.Size = UDim2.new(child.Size.X.Scale, child.Size.X.Offset, 0, child.AbsoluteSize.Y + 1)
end
pixelsRemaining = pixelsRemaining - child.AbsoluteSize.Y
if isLabel then
pixelsRemaining = pixelsRemaining - settingsTable["TextLabelPositionPadY"]
else
pixelsRemaining = pixelsRemaining - settingsTable["TextButtonPositionPadY"]
end
else
child.Visible = false
pixelsRemaining = -1
end
else
--GuiObject
child.Position = UDim2.new(child.Position.X.Scale, child.Position.X.Offset, 0, totalPixels - pixelsRemaining)
pixelsRemaining = pixelsRemaining - child.AbsoluteSize.Y
child.Visible = (pixelsRemaining >= 0)
end
end
end
t.LayoutGuiObjects = function(frame, guiObjects, settingsTable)
if not frame:IsA("GuiObject") then
error("Frame must be a GuiObject")
end
for i, child in ipairs(guiObjects) do
if not child:IsA("GuiObject") then
error("All elements that are layed out must be of type GuiObject")
end
end
if not settingsTable then
settingsTable = {}
end
if not settingsTable["TextLabelSizePadY"] then
settingsTable["TextLabelSizePadY"] = 0
end
if not settingsTable["TextLabelPositionPadY"] then
settingsTable["TextLabelPositionPadY"] = 0
end
if not settingsTable["TextButtonSizePadY"] then
settingsTable["TextButtonSizePadY"] = 12
end
if not settingsTable["TextButtonPositionPadY"] then
settingsTable["TextButtonPositionPadY"] = 2
end
--Wrapper frame takes care of styled objects
local wrapperFrame = Instance.new("Frame")
wrapperFrame.Name = "WrapperFrame"
wrapperFrame.BackgroundTransparency = 1
wrapperFrame.Size = UDim2.new(1,0,1,0)
wrapperFrame.Parent = frame
for i, child in ipairs(guiObjects) do
child.Parent = wrapperFrame
end
local recalculate = function()
wait()
layoutGuiObjectsHelper(wrapperFrame, guiObjects, settingsTable)
end
frame.Changed:connect(
function(prop)
if prop == "AbsoluteSize" then
--Wait a heartbeat for it to sync in
recalculate(nil)
end
end)
frame.AncestryChanged:connect(recalculate)
layoutGuiObjectsHelper(wrapperFrame, guiObjects, settingsTable)
end
t.CreateSlider = function(steps,width,position)
local sliderGui = Instance.new("Frame")
sliderGui.Size = UDim2.new(1,0,1,0)
sliderGui.BackgroundTransparency = 1
sliderGui.Name = "SliderGui"
local sliderSteps = Instance.new("IntValue")
sliderSteps.Name = "SliderSteps"
sliderSteps.Value = steps
sliderSteps.Parent = sliderGui
local areaSoak = Instance.new("TextButton")
areaSoak.Name = "AreaSoak"
areaSoak.Text = ""
areaSoak.BackgroundTransparency = 1
areaSoak.Active = false
areaSoak.Size = UDim2.new(1,0,1,0)
areaSoak.Visible = false
areaSoak.ZIndex = 4
sliderGui.AncestryChanged:connect(function(child,parent)
if parent == nil then
areaSoak.Parent = nil
else
areaSoak.Parent = getLayerCollectorAncestor(sliderGui)
end
end)
local sliderPosition = Instance.new("IntValue")
sliderPosition.Name = "SliderPosition"
sliderPosition.Value = 0
sliderPosition.Parent = sliderGui
local id = math.random(1,100)
local bar = Instance.new("TextButton")
bar.Text = ""
bar.AutoButtonColor = false
bar.Name = "Bar"
bar.BackgroundColor3 = Color3.new(0,0,0)
if type(width) == "number" then
bar.Size = UDim2.new(0,width,0,5)
else
bar.Size = UDim2.new(0,200,0,5)
end
bar.BorderColor3 = Color3.new(95/255,95/255,95/255)
bar.ZIndex = 2
bar.Parent = sliderGui
if position["X"] and position["X"]["Scale"] and position["X"]["Offset"] and position["Y"] and position["Y"]["Scale"] and position["Y"]["Offset"] then
bar.Position = position
end
local slider = Instance.new("ImageButton")
slider.Name = "Slider"
slider.BackgroundTransparency = 1
slider.Image = "rbxasset://textures/ui/Slider.png"
slider.Position = UDim2.new(0,0,0.5,-10)
slider.Size = UDim2.new(0,20,0,20)
slider.ZIndex = 3
slider.Parent = bar
local areaSoakMouseMoveCon = nil
areaSoak.MouseLeave:connect(function()
if areaSoak.Visible then
cancelSlide(areaSoak)
end
end)
areaSoak.MouseButton1Up:connect(function()
if areaSoak.Visible then
cancelSlide(areaSoak)
end
end)
slider.MouseButton1Down:connect(function()
areaSoak.Visible = true
if areaSoakMouseMoveCon then areaSoakMouseMoveCon:disconnect() end
areaSoakMouseMoveCon = areaSoak.MouseMoved:connect(function(x,y)
setSliderPos(x,slider,sliderPosition,bar,steps)
end)
end)
slider.MouseButton1Up:connect(function() cancelSlide(areaSoak) end)
sliderPosition.Changed:connect(function(prop)
sliderPosition.Value = math.min(steps, math.max(1,sliderPosition.Value))
local relativePosX = (sliderPosition.Value - 1) / (steps - 1)
slider.Position = UDim2.new(relativePosX,-slider.AbsoluteSize.X/2,slider.Position.Y.Scale,slider.Position.Y.Offset)
end)
bar.MouseButton1Down:connect(function(x,y)
setSliderPos(x,slider,sliderPosition,bar,steps)
end)
return sliderGui, sliderPosition, sliderSteps
end
t.CreateSliderNew = function(steps,width,position)
local sliderGui = Instance.new("Frame")
sliderGui.Size = UDim2.new(1,0,1,0)
sliderGui.BackgroundTransparency = 1
sliderGui.Name = "SliderGui"
local sliderSteps = Instance.new("IntValue")
sliderSteps.Name = "SliderSteps"
sliderSteps.Value = steps
sliderSteps.Parent = sliderGui
local areaSoak = Instance.new("TextButton")
areaSoak.Name = "AreaSoak"
areaSoak.Text = ""
areaSoak.BackgroundTransparency = 1
areaSoak.Active = false
areaSoak.Size = UDim2.new(1,0,1,0)
areaSoak.Visible = false
areaSoak.ZIndex = 6
sliderGui.AncestryChanged:connect(function(child,parent)
if parent == nil then
areaSoak.Parent = nil
else
areaSoak.Parent = getLayerCollectorAncestor(sliderGui)
end
end)
local sliderPosition = Instance.new("IntValue")
sliderPosition.Name = "SliderPosition"
sliderPosition.Value = 0
sliderPosition.Parent = sliderGui
local id = math.random(1,100)
local sliderBarImgHeight = 7
local sliderBarCapImgWidth = 4
local bar = Instance.new("ImageButton")
bar.BackgroundTransparency = 1
bar.Image = "rbxasset://textures/ui/Slider-BKG-Center.png"
bar.Name = "Bar"
local displayWidth = 200
if type(width) == "number" then
bar.Size = UDim2.new(0,width - (sliderBarCapImgWidth * 2),0,sliderBarImgHeight)
displayWidth = width - (sliderBarCapImgWidth * 2)
else
bar.Size = UDim2.new(0,200,0,sliderBarImgHeight)
end
bar.ZIndex = 3
bar.Parent = sliderGui
if position["X"] and position["X"]["Scale"] and position["X"]["Offset"] and position["Y"] and position["Y"]["Scale"] and position["Y"]["Offset"] then
bar.Position = position
end
local barLeft = bar:clone()
barLeft.Name = "BarLeft"
barLeft.Image = "rbxasset://textures/ui/Slider-BKG-Left-Cap.png"
barLeft.Size = UDim2.new(0, sliderBarCapImgWidth, 0, sliderBarImgHeight)
barLeft.Position = UDim2.new(position.X.Scale, position.X.Offset - sliderBarCapImgWidth, position.Y.Scale, position.Y.Offset)
barLeft.Parent = sliderGui
barLeft.ZIndex = 3
local barRight = barLeft:clone()
barRight.Name = "BarRight"
barRight.Image = "rbxasset://textures/ui/Slider-BKG-Right-Cap.png"
barRight.Position = UDim2.new(position.X.Scale, position.X.Offset + displayWidth, position.Y.Scale, position.Y.Offset)
barRight.Parent = sliderGui
local fillLeft = barLeft:clone()
fillLeft.Name = "FillLeft"
fillLeft.Image = "rbxasset://textures/ui/Slider-Fill-Left-Cap.png"
fillLeft.Parent = sliderGui
fillLeft.ZIndex = 4
local fill = fillLeft:clone()
fill.Name = "Fill"
fill.Image = "rbxasset://textures/ui/Slider-Fill-Center.png"
fill.Parent = bar
fill.ZIndex = 4
fill.Position = UDim2.new(0, 0, 0, 0)
fill.Size = UDim2.new(0.5, 0, 1, 0)
-- bar.Visible = false
local slider = Instance.new("ImageButton")
slider.Name = "Slider"
slider.BackgroundTransparency = 1
slider.Image = "rbxasset://textures/ui/slider_new_tab.png"
slider.Position = UDim2.new(0,0,0.5,-14)
slider.Size = UDim2.new(0,28,0,28)
slider.ZIndex = 5
slider.Parent = bar
local areaSoakMouseMoveCon = nil
areaSoak.MouseLeave:connect(function()
if areaSoak.Visible then
cancelSlide(areaSoak)
end
end)
areaSoak.MouseButton1Up:connect(function()
if areaSoak.Visible then
cancelSlide(areaSoak)
end
end)
slider.MouseButton1Down:connect(function()
areaSoak.Visible = true
if areaSoakMouseMoveCon then areaSoakMouseMoveCon:disconnect() end
areaSoakMouseMoveCon = areaSoak.MouseMoved:connect(function(x,y)
setSliderPos(x,slider,sliderPosition,bar,steps)
end)
end)
slider.MouseButton1Up:connect(function() cancelSlide(areaSoak) end)
sliderPosition.Changed:connect(function(prop)
sliderPosition.Value = math.min(steps, math.max(1,sliderPosition.Value))
local relativePosX = (sliderPosition.Value - 1) / (steps - 1)
slider.Position = UDim2.new(relativePosX,-slider.AbsoluteSize.X/2,slider.Position.Y.Scale,slider.Position.Y.Offset)
fill.Size = UDim2.new(relativePosX, 0, 1, 0)
end)
bar.MouseButton1Down:connect(function(x,y)
setSliderPos(x,slider,sliderPosition,bar,steps)
end)
fill.MouseButton1Down:connect(function(x,y)
setSliderPos(x,slider,sliderPosition,bar,steps)
end)
fillLeft.MouseButton1Down:connect(function(x,y)
setSliderPos(x,slider,sliderPosition,bar,steps)
end)
return sliderGui, sliderPosition, sliderSteps
end
t.CreateTrueScrollingFrame = function()
local lowY = nil
local highY = nil
local dragCon = nil
local upCon = nil
local internalChange = false
local descendantsChangeConMap = {}
local scrollingFrame = Instance.new("Frame")
scrollingFrame.Name = "ScrollingFrame"
scrollingFrame.Active = true
scrollingFrame.Size = UDim2.new(1,0,1,0)
scrollingFrame.ClipsDescendants = true
local controlFrame = Instance.new("Frame")
controlFrame.Name = "ControlFrame"
controlFrame.BackgroundTransparency = 1
controlFrame.Size = UDim2.new(0,18,1,0)
controlFrame.Position = UDim2.new(1,-20,0,0)
controlFrame.Parent = scrollingFrame
local scrollBottom = Instance.new("BoolValue")
scrollBottom.Value = false
scrollBottom.Name = "ScrollBottom"
scrollBottom.Parent = controlFrame
local scrollUp = Instance.new("BoolValue")
scrollUp.Value = false
scrollUp.Name = "scrollUp"
scrollUp.Parent = controlFrame
local scrollUpButton = Instance.new("TextButton")
scrollUpButton.Name = "ScrollUpButton"
scrollUpButton.Text = ""
scrollUpButton.AutoButtonColor = false
scrollUpButton.BackgroundColor3 = Color3.new(0,0,0)
scrollUpButton.BorderColor3 = Color3.new(1,1,1)
scrollUpButton.BackgroundTransparency = 0.5
scrollUpButton.Size = UDim2.new(0,18,0,18)
scrollUpButton.ZIndex = 2
scrollUpButton.Parent = controlFrame
for i = 1, 6 do
local triFrame = Instance.new("Frame")
triFrame.BorderColor3 = Color3.new(1,1,1)
triFrame.Name = "tri" .. tostring(i)
triFrame.ZIndex = 3
triFrame.BackgroundTransparency = 0.5
triFrame.Size = UDim2.new(0,12 - ((i -1) * 2),0,0)
triFrame.Position = UDim2.new(0,3 + (i -1),0.5,2 - (i -1))
triFrame.Parent = scrollUpButton
end
scrollUpButton.MouseEnter:connect(function()
scrollUpButton.BackgroundTransparency = 0.1
local upChildren = scrollUpButton:GetChildren()
for i = 1, #upChildren do
upChildren[i].BackgroundTransparency = 0.1
end
end)
scrollUpButton.MouseLeave:connect(function()
scrollUpButton.BackgroundTransparency = 0.5
local upChildren = scrollUpButton:GetChildren()
for i = 1, #upChildren do
upChildren[i].BackgroundTransparency = 0.5
end
end)
local scrollDownButton = scrollUpButton:clone()
scrollDownButton.Name = "ScrollDownButton"
scrollDownButton.Position = UDim2.new(0,0,1,-18)
local downChildren = scrollDownButton:GetChildren()
for i = 1, #downChildren do
downChildren[i].Position = UDim2.new(0,3 + (i -1),0.5,-2 + (i - 1))
end
scrollDownButton.MouseEnter:connect(function()
scrollDownButton.BackgroundTransparency = 0.1
local downChildren = scrollDownButton:GetChildren()
for i = 1, #downChildren do
downChildren[i].BackgroundTransparency = 0.1
end
end)
scrollDownButton.MouseLeave:connect(function()
scrollDownButton.BackgroundTransparency = 0.5
local downChildren = scrollDownButton:GetChildren()
for i = 1, #downChildren do
downChildren[i].BackgroundTransparency = 0.5
end
end)
scrollDownButton.Parent = controlFrame
local scrollTrack = Instance.new("Frame")
scrollTrack.Name = "ScrollTrack"
scrollTrack.BackgroundTransparency = 1
scrollTrack.Size = UDim2.new(0,18,1,-38)
scrollTrack.Position = UDim2.new(0,0,0,19)
scrollTrack.Parent = controlFrame
local scrollbar = Instance.new("TextButton")
scrollbar.BackgroundColor3 = Color3.new(0,0,0)
scrollbar.BorderColor3 = Color3.new(1,1,1)
scrollbar.BackgroundTransparency = 0.5
scrollbar.AutoButtonColor = false
scrollbar.Text = ""
scrollbar.Active = true
scrollbar.Name = "ScrollBar"
scrollbar.ZIndex = 2
scrollbar.BackgroundTransparency = 0.5
scrollbar.Size = UDim2.new(0, 18, 0.1, 0)
scrollbar.Position = UDim2.new(0,0,0,0)
scrollbar.Parent = scrollTrack
local scrollNub = Instance.new("Frame")
scrollNub.Name = "ScrollNub"
scrollNub.BorderColor3 = Color3.new(1,1,1)
scrollNub.Size = UDim2.new(0,10,0,0)
scrollNub.Position = UDim2.new(0.5,-5,0.5,0)
scrollNub.ZIndex = 2
scrollNub.BackgroundTransparency = 0.5
scrollNub.Parent = scrollbar
local newNub = scrollNub:clone()
newNub.Position = UDim2.new(0.5,-5,0.5,-2)
newNub.Parent = scrollbar
local lastNub = scrollNub:clone()
lastNub.Position = UDim2.new(0.5,-5,0.5,2)
lastNub.Parent = scrollbar
scrollbar.MouseEnter:connect(function()
scrollbar.BackgroundTransparency = 0.1
scrollNub.BackgroundTransparency = 0.1
newNub.BackgroundTransparency = 0.1
lastNub.BackgroundTransparency = 0.1
end)
scrollbar.MouseLeave:connect(function()
scrollbar.BackgroundTransparency = 0.5
scrollNub.BackgroundTransparency = 0.5
newNub.BackgroundTransparency = 0.5
lastNub.BackgroundTransparency = 0.5
end)
local mouseDrag = Instance.new("ImageButton")
mouseDrag.Active = false
mouseDrag.Size = UDim2.new(1.5, 0, 1.5, 0)
mouseDrag.AutoButtonColor = false
mouseDrag.BackgroundTransparency = 1
mouseDrag.Name = "mouseDrag"
mouseDrag.Position = UDim2.new(-0.25, 0, -0.25, 0)
mouseDrag.ZIndex = 10
local function positionScrollBar(x,y,offset)
local oldPos = scrollbar.Position
if y < scrollTrack.AbsolutePosition.y then
scrollbar.Position = UDim2.new(scrollbar.Position.X.Scale,scrollbar.Position.X.Offset,0,0)
return (oldPos ~= scrollbar.Position)
end
local relativeSize = scrollbar.AbsoluteSize.Y/scrollTrack.AbsoluteSize.Y
if y > (scrollTrack.AbsolutePosition.y + scrollTrack.AbsoluteSize.y) then
scrollbar.Position = UDim2.new(scrollbar.Position.X.Scale,scrollbar.Position.X.Offset,1 - relativeSize,0)
return (oldPos ~= scrollbar.Position)
end
local newScaleYPos = (y - scrollTrack.AbsolutePosition.y - offset)/scrollTrack.AbsoluteSize.y
if newScaleYPos + relativeSize > 1 then
newScaleYPos = 1 - relativeSize
scrollBottom.Value = true
scrollUp.Value = false
elseif newScaleYPos <= 0 then
newScaleYPos = 0
scrollUp.Value = true
scrollBottom.Value = false
else
scrollUp.Value = false
scrollBottom.Value = false
end
scrollbar.Position = UDim2.new(scrollbar.Position.X.Scale,scrollbar.Position.X.Offset,newScaleYPos,0)
return (oldPos ~= scrollbar.Position)
end
local function drillDownSetHighLow(instance)
if not instance or not instance:IsA("GuiObject") then return end
if instance == controlFrame then return end
if instance:IsDescendantOf(controlFrame) then return end
if not instance.Visible then return end
if lowY and lowY > instance.AbsolutePosition.Y then
lowY = instance.AbsolutePosition.Y
elseif not lowY then
lowY = instance.AbsolutePosition.Y
end
if highY and highY < (instance.AbsolutePosition.Y + instance.AbsoluteSize.Y) then
highY = instance.AbsolutePosition.Y + instance.AbsoluteSize.Y
elseif not highY then
highY = instance.AbsolutePosition.Y + instance.AbsoluteSize.Y
end
local children = instance:GetChildren()
for i = 1, #children do
drillDownSetHighLow(children[i])
end
end
local function resetHighLow()
local firstChildren = scrollingFrame:GetChildren()
for i = 1, #firstChildren do
drillDownSetHighLow(firstChildren[i])
end
end
local function recalculate()
internalChange = true
local percentFrame = 0
if scrollbar.Position.Y.Scale > 0 then
if scrollbar.Visible then
percentFrame = scrollbar.Position.Y.Scale/((scrollTrack.AbsoluteSize.Y - scrollbar.AbsoluteSize.Y)/scrollTrack.AbsoluteSize.Y)
else
percentFrame = 0
end
end
if percentFrame > 0.99 then percentFrame = 1 end
local hiddenYAmount = (scrollingFrame.AbsoluteSize.Y - (highY - lowY)) * percentFrame
local guiChildren = scrollingFrame:GetChildren()
for i = 1, #guiChildren do
if guiChildren[i] ~= controlFrame then
guiChildren[i].Position = UDim2.new(guiChildren[i].Position.X.Scale,guiChildren[i].Position.X.Offset,
0, math.ceil(guiChildren[i].AbsolutePosition.Y) - math.ceil(lowY) + hiddenYAmount)
end
end
lowY = nil
highY = nil
resetHighLow()
internalChange = false
end
local function setSliderSizeAndPosition()
if not highY or not lowY then return end
local totalYSpan = math.abs(highY - lowY)
if totalYSpan == 0 then
scrollbar.Visible = false
scrollDownButton.Visible = false
scrollUpButton.Visible = false
if dragCon then dragCon:disconnect() dragCon = nil end
if upCon then upCon:disconnect() upCon = nil end
return
end
local percentShown = scrollingFrame.AbsoluteSize.Y/totalYSpan
if percentShown >= 1 then
scrollbar.Visible = false
scrollDownButton.Visible = false
scrollUpButton.Visible = false
recalculate()
else
scrollbar.Visible = true
scrollDownButton.Visible = true
scrollUpButton.Visible = true
scrollbar.Size = UDim2.new(scrollbar.Size.X.Scale,scrollbar.Size.X.Offset,percentShown,0)
end
local percentPosition = (scrollingFrame.AbsolutePosition.Y - lowY)/totalYSpan
scrollbar.Position = UDim2.new(scrollbar.Position.X.Scale,scrollbar.Position.X.Offset,percentPosition,-scrollbar.AbsoluteSize.X/2)
if scrollbar.AbsolutePosition.y < scrollTrack.AbsolutePosition.y then
scrollbar.Position = UDim2.new(scrollbar.Position.X.Scale,scrollbar.Position.X.Offset,0,0)
end
if (scrollbar.AbsolutePosition.y + scrollbar.AbsoluteSize.Y) > (scrollTrack.AbsolutePosition.y + scrollTrack.AbsoluteSize.y) then
local relativeSize = scrollbar.AbsoluteSize.Y/scrollTrack.AbsoluteSize.Y
scrollbar.Position = UDim2.new(scrollbar.Position.X.Scale,scrollbar.Position.X.Offset,1 - relativeSize,0)
end
end
local buttonScrollAmountPixels = 7
local reentrancyGuardScrollUp = false
local function doScrollUp()
if reentrancyGuardScrollUp then return end
reentrancyGuardScrollUp = true
if positionScrollBar(0,scrollbar.AbsolutePosition.Y - buttonScrollAmountPixels,0) then
recalculate()
end
reentrancyGuardScrollUp = false
end
local reentrancyGuardScrollDown = false
local function doScrollDown()
if reentrancyGuardScrollDown then return end
reentrancyGuardScrollDown = true
if positionScrollBar(0,scrollbar.AbsolutePosition.Y + buttonScrollAmountPixels,0) then
recalculate()
end
reentrancyGuardScrollDown = false
end
local function scrollUp(mouseYPos)
if scrollUpButton.Active then
scrollStamp = tick()
local current = scrollStamp
local upCon
upCon = mouseDrag.MouseButton1Up:connect(function()
scrollStamp = tick()
mouseDrag.Parent = nil
upCon:disconnect()
end)
mouseDrag.Parent = getLayerCollectorAncestor(scrollbar)
doScrollUp()
wait(0.2)
local t = tick()
local w = 0.1
while scrollStamp == current do
doScrollUp()
if mouseYPos and mouseYPos > scrollbar.AbsolutePosition.y then
break
end
if not scrollUpButton.Active then break end
if tick()-t > 5 then
w = 0
elseif tick()-t > 2 then
w = 0.06
end
wait(w)
end
end
end
local function scrollDown(mouseYPos)
if scrollDownButton.Active then
scrollStamp = tick()
local current = scrollStamp
local downCon
downCon = mouseDrag.MouseButton1Up:connect(function()
scrollStamp = tick()
mouseDrag.Parent = nil
downCon:disconnect()
end)
mouseDrag.Parent = getLayerCollectorAncestor(scrollbar)
doScrollDown()
wait(0.2)
local t = tick()
local w = 0.1
while scrollStamp == current do
doScrollDown()
if mouseYPos and mouseYPos < (scrollbar.AbsolutePosition.y + scrollbar.AbsoluteSize.x) then
break
end
if not scrollDownButton.Active then break end
if tick()-t > 5 then
w = 0
elseif tick()-t > 2 then
w = 0.06
end
wait(w)
end
end
end
scrollbar.MouseButton1Down:connect(function(x,y)
if scrollbar.Active then
scrollStamp = tick()
local mouseOffset = y - scrollbar.AbsolutePosition.y
if dragCon then dragCon:disconnect() dragCon = nil end
if upCon then upCon:disconnect() upCon = nil end
local prevY = y
local reentrancyGuardMouseScroll = false
dragCon = mouseDrag.MouseMoved:connect(function(x,y)
if reentrancyGuardMouseScroll then return end
reentrancyGuardMouseScroll = true
if positionScrollBar(x,y,mouseOffset) then
recalculate()
end
reentrancyGuardMouseScroll = false
end)
upCon = mouseDrag.MouseButton1Up:connect(function()
scrollStamp = tick()
mouseDrag.Parent = nil
dragCon:disconnect(); dragCon = nil
upCon:disconnect(); drag = nil
end)
mouseDrag.Parent = getLayerCollectorAncestor(scrollbar)
end
end)
local scrollMouseCount = 0
scrollUpButton.MouseButton1Down:connect(function()
scrollUp()
end)
scrollUpButton.MouseButton1Up:connect(function()
scrollStamp = tick()
end)
scrollDownButton.MouseButton1Up:connect(function()
scrollStamp = tick()
end)
scrollDownButton.MouseButton1Down:connect(function()
scrollDown()
end)
scrollbar.MouseButton1Up:connect(function()
scrollStamp = tick()
end)
local function heightCheck(instance)
if highY and (instance.AbsolutePosition.Y + instance.AbsoluteSize.Y) > highY then
highY = instance.AbsolutePosition.Y + instance.AbsoluteSize.Y
elseif not highY then
highY = instance.AbsolutePosition.Y + instance.AbsoluteSize.Y
end
setSliderSizeAndPosition()
end
local function highLowRecheck()
local oldLowY = lowY
local oldHighY = highY
lowY = nil
highY = nil
resetHighLow()
if (lowY ~= oldLowY) or (highY ~= oldHighY) then
setSliderSizeAndPosition()
end
end
local function descendantChanged(this, prop)
if internalChange then return end
if not this.Visible then return end
if prop == "Size" or prop == "Position" then
wait()
highLowRecheck()
end
end
scrollingFrame.DescendantAdded:connect(function(instance)
if not instance:IsA("GuiObject") then return end
if instance.Visible then
wait() -- wait a heartbeat for sizes to reconfig
highLowRecheck()
end
descendantsChangeConMap[instance] = instance.Changed:connect(function(prop) descendantChanged(instance, prop) end)
end)
scrollingFrame.DescendantRemoving:connect(function(instance)
if not instance:IsA("GuiObject") then return end
if descendantsChangeConMap[instance] then
descendantsChangeConMap[instance]:disconnect()
descendantsChangeConMap[instance] = nil
end
wait() -- wait a heartbeat for sizes to reconfig
highLowRecheck()
end)
scrollingFrame.Changed:connect(function(prop)
if prop == "AbsoluteSize" then
if not highY or not lowY then return end
highLowRecheck()
setSliderSizeAndPosition()
end
end)
return scrollingFrame, controlFrame
end
t.CreateScrollingFrame = function(orderList,scrollStyle)
local frame = Instance.new("Frame")
frame.Name = "ScrollingFrame"
frame.BackgroundTransparency = 1
frame.Size = UDim2.new(1,0,1,0)
local scrollUpButton = Instance.new("ImageButton")
scrollUpButton.Name = "ScrollUpButton"
scrollUpButton.BackgroundTransparency = 1
scrollUpButton.Image = "rbxasset://textures/ui/scrollbuttonUp.png"
scrollUpButton.Size = UDim2.new(0,17,0,17)
local scrollDownButton = Instance.new("ImageButton")
scrollDownButton.Name = "ScrollDownButton"
scrollDownButton.BackgroundTransparency = 1
scrollDownButton.Image = "rbxasset://textures/ui/scrollbuttonDown.png"
scrollDownButton.Size = UDim2.new(0,17,0,17)
local scrollbar = Instance.new("ImageButton")
scrollbar.Name = "ScrollBar"
scrollbar.Image = "rbxasset://textures/ui/scrollbar.png"
scrollbar.BackgroundTransparency = 1
scrollbar.Size = UDim2.new(0, 18, 0, 150)
local scrollStamp = 0
local scrollDrag = Instance.new("ImageButton")
scrollDrag.Image = "https://www.roblox.com/asset/?id=61367186"
scrollDrag.Size = UDim2.new(1, 0, 0, 16)
scrollDrag.BackgroundTransparency = 1
scrollDrag.Name = "ScrollDrag"
scrollDrag.Active = true
scrollDrag.Parent = scrollbar
local mouseDrag = Instance.new("ImageButton")
mouseDrag.Active = false
mouseDrag.Size = UDim2.new(1.5, 0, 1.5, 0)
mouseDrag.AutoButtonColor = false
mouseDrag.BackgroundTransparency = 1
mouseDrag.Name = "mouseDrag"
mouseDrag.Position = UDim2.new(-0.25, 0, -0.25, 0)
mouseDrag.ZIndex = 10
local style = "simple"
if scrollStyle and tostring(scrollStyle) then
style = scrollStyle
end
local scrollPosition = 1
local rowSize = 0
local howManyDisplayed = 0
local layoutGridScrollBar = function()
howManyDisplayed = 0
local guiObjects = {}
if orderList then
for i, child in ipairs(orderList) do
if child.Parent == frame then
table.insert(guiObjects, child)
end
end
else
local children = frame:GetChildren()
if children then
for i, child in ipairs(children) do
if child:IsA("GuiObject") then
table.insert(guiObjects, child)
end
end
end
end
if #guiObjects == 0 then
scrollUpButton.Active = false
scrollDownButton.Active = false
scrollDrag.Active = false
scrollPosition = 1
return
end
if scrollPosition > #guiObjects then
scrollPosition = #guiObjects
end
if scrollPosition < 1 then scrollPosition = 1 end
local totalPixelsY = frame.AbsoluteSize.Y
local pixelsRemainingY = frame.AbsoluteSize.Y
local totalPixelsX = frame.AbsoluteSize.X
local xCounter = 0
local rowSizeCounter = 0
local setRowSize = true
local pixelsBelowScrollbar = 0
local pos = #guiObjects
local currentRowY = 0
pos = scrollPosition
--count up from current scroll position to fill out grid
while pos <= #guiObjects and pixelsBelowScrollbar < totalPixelsY do
xCounter = xCounter + guiObjects[pos].AbsoluteSize.X
--previous pos was the end of a row
if xCounter >= totalPixelsX then
pixelsBelowScrollbar = pixelsBelowScrollbar + currentRowY
currentRowY = 0
xCounter = guiObjects[pos].AbsoluteSize.X
end
if guiObjects[pos].AbsoluteSize.Y > currentRowY then
currentRowY = guiObjects[pos].AbsoluteSize.Y
end
pos = pos + 1
end
--Count wherever current row left off
pixelsBelowScrollbar = pixelsBelowScrollbar + currentRowY
currentRowY = 0
pos = scrollPosition - 1
xCounter = 0
--objects with varying X,Y dimensions can rarely cause minor errors
--rechecking every new scrollPosition is necessary to avoid 100% of errors
--count backwards from current scrollPosition to see if we can add more rows
while pixelsBelowScrollbar + currentRowY < totalPixelsY and pos >= 1 do
xCounter = xCounter + guiObjects[pos].AbsoluteSize.X
rowSizeCounter = rowSizeCounter + 1
if xCounter >= totalPixelsX then
rowSize = rowSizeCounter - 1
rowSizeCounter = 0
xCounter = guiObjects[pos].AbsoluteSize.X
if pixelsBelowScrollbar + currentRowY <= totalPixelsY then
--It fits, so back up our scroll position
pixelsBelowScrollbar = pixelsBelowScrollbar + currentRowY
if scrollPosition <= rowSize then
scrollPosition = 1
break
else
scrollPosition = scrollPosition - rowSize
end
currentRowY = 0
else
break
end
end
if guiObjects[pos].AbsoluteSize.Y > currentRowY then
currentRowY = guiObjects[pos].AbsoluteSize.Y
end
pos = pos - 1
end
--Do check last time if pos = 0
if (pos == 0) and (pixelsBelowScrollbar + currentRowY <= totalPixelsY) then
scrollPosition = 1
end
xCounter = 0
--pos = scrollPosition
rowSizeCounter = 0
setRowSize = true
local lastChildSize = 0
local xOffset,yOffset = 0
if guiObjects[1] then
yOffset = math.ceil(math.floor(math.fmod(totalPixelsY,guiObjects[1].AbsoluteSize.X))/2)
xOffset = math.ceil(math.floor(math.fmod(totalPixelsX,guiObjects[1].AbsoluteSize.Y))/2)
end
for i, child in ipairs(guiObjects) do
if i < scrollPosition then
--print("Hiding " .. child.Name)
child.Visible = false
else
if pixelsRemainingY < 0 then
--print("Out of Space " .. child.Name)
child.Visible = false
else
--print("Laying out " .. child.Name)
--GuiObject
if setRowSize then rowSizeCounter = rowSizeCounter + 1 end
if xCounter + child.AbsoluteSize.X >= totalPixelsX then
if setRowSize then
rowSize = rowSizeCounter - 1
setRowSize = false
end
xCounter = 0
pixelsRemainingY = pixelsRemainingY - child.AbsoluteSize.Y
end
child.Position = UDim2.new(child.Position.X.Scale,xCounter + xOffset, 0, totalPixelsY - pixelsRemainingY + yOffset)
xCounter = xCounter + child.AbsoluteSize.X
child.Visible = ((pixelsRemainingY - child.AbsoluteSize.Y) >= 0)
if child.Visible then
howManyDisplayed = howManyDisplayed + 1
end
lastChildSize = child.AbsoluteSize
end
end
end
scrollUpButton.Active = (scrollPosition > 1)
if lastChildSize == 0 then
scrollDownButton.Active = false
else
scrollDownButton.Active = ((pixelsRemainingY - lastChildSize.Y) < 0)
end
scrollDrag.Active = #guiObjects > howManyDisplayed
scrollDrag.Visible = scrollDrag.Active
end
local layoutSimpleScrollBar = function()
local guiObjects = {}
howManyDisplayed = 0
if orderList then
for i, child in ipairs(orderList) do
if child.Parent == frame then
table.insert(guiObjects, child)
end
end
else
local children = frame:GetChildren()
if children then
for i, child in ipairs(children) do
if child:IsA("GuiObject") then
table.insert(guiObjects, child)
end
end
end
end
if #guiObjects == 0 then
scrollUpButton.Active = false
scrollDownButton.Active = false
scrollDrag.Active = false
scrollPosition = 1
return
end
if scrollPosition > #guiObjects then
scrollPosition = #guiObjects
end
local totalPixels = frame.AbsoluteSize.Y
local pixelsRemaining = frame.AbsoluteSize.Y
local pixelsBelowScrollbar = 0
local pos = #guiObjects
while pixelsBelowScrollbar < totalPixels and pos >= 1 do
if pos >= scrollPosition then
pixelsBelowScrollbar = pixelsBelowScrollbar + guiObjects[pos].AbsoluteSize.Y
else
if pixelsBelowScrollbar + guiObjects[pos].AbsoluteSize.Y <= totalPixels then
--It fits, so back up our scroll position
pixelsBelowScrollbar = pixelsBelowScrollbar + guiObjects[pos].AbsoluteSize.Y
if scrollPosition <= 1 then
scrollPosition = 1
break
else
--local ("Backing up ScrollPosition from -- " ..scrollPosition)
scrollPosition = scrollPosition - 1
end
else
break
end
end
pos = pos - 1
end
pos = scrollPosition
for i, child in ipairs(guiObjects) do
if i < scrollPosition then
--print("Hiding " .. child.Name)
child.Visible = false
else
if pixelsRemaining < 0 then
--print("Out of Space " .. child.Name)
child.Visible = false
else
--print("Laying out " .. child.Name)
--GuiObject
child.Position = UDim2.new(child.Position.X.Scale, child.Position.X.Offset, 0, totalPixels - pixelsRemaining)
pixelsRemaining = pixelsRemaining - child.AbsoluteSize.Y
if (pixelsRemaining >= 0) then
child.Visible = true
howManyDisplayed = howManyDisplayed + 1
else
child.Visible = false
end
end
end
end
scrollUpButton.Active = (scrollPosition > 1)
scrollDownButton.Active = (pixelsRemaining < 0)
scrollDrag.Active = #guiObjects > howManyDisplayed
scrollDrag.Visible = scrollDrag.Active
end
local moveDragger = function()
local guiObjects = 0
local children = frame:GetChildren()
if children then
for i, child in ipairs(children) do
if child:IsA("GuiObject") then
guiObjects = guiObjects + 1
end
end
end
if not scrollDrag.Parent then return end
local dragSizeY = scrollDrag.Parent.AbsoluteSize.y * (1/(guiObjects - howManyDisplayed + 1))
if dragSizeY < 16 then dragSizeY = 16 end
scrollDrag.Size = UDim2.new(scrollDrag.Size.X.Scale,scrollDrag.Size.X.Offset,scrollDrag.Size.Y.Scale,dragSizeY)
local relativeYPos = (scrollPosition - 1)/(guiObjects - (howManyDisplayed))
if relativeYPos > 1 then relativeYPos = 1
elseif relativeYPos < 0 then relativeYPos = 0 end
local absYPos = 0
if relativeYPos ~= 0 then
absYPos = (relativeYPos * scrollbar.AbsoluteSize.y) - (relativeYPos * scrollDrag.AbsoluteSize.y)
end
scrollDrag.Position = UDim2.new(scrollDrag.Position.X.Scale,scrollDrag.Position.X.Offset,scrollDrag.Position.Y.Scale,absYPos)
end
local reentrancyGuard = false
local recalculate = function()
if reentrancyGuard then
return
end
reentrancyGuard = true
wait()
local success, err = nil
if style == "grid" then
success, err = pcall(function() layoutGridScrollBar() end)
elseif style == "simple" then
success, err = pcall(function() layoutSimpleScrollBar() end)
end
if not success then print(err) end
moveDragger()
reentrancyGuard = false
end
local doScrollUp = function()
scrollPosition = (scrollPosition) - rowSize
if scrollPosition < 1 then scrollPosition = 1 end
recalculate(nil)
end
local doScrollDown = function()
scrollPosition = (scrollPosition) + rowSize
recalculate(nil)
end
local scrollUp = function(mouseYPos)
if scrollUpButton.Active then
scrollStamp = tick()
local current = scrollStamp
local upCon
upCon = mouseDrag.MouseButton1Up:connect(function()
scrollStamp = tick()
mouseDrag.Parent = nil
upCon:disconnect()
end)
mouseDrag.Parent = getLayerCollectorAncestor(scrollbar)
doScrollUp()
wait(0.2)
local t = tick()
local w = 0.1
while scrollStamp == current do
doScrollUp()
if mouseYPos and mouseYPos > scrollDrag.AbsolutePosition.y then
break
end
if not scrollUpButton.Active then break end
if tick()-t > 5 then
w = 0
elseif tick()-t > 2 then
w = 0.06
end
wait(w)
end
end
end
local scrollDown = function(mouseYPos)
if scrollDownButton.Active then
scrollStamp = tick()
local current = scrollStamp
local downCon
downCon = mouseDrag.MouseButton1Up:connect(function()
scrollStamp = tick()
mouseDrag.Parent = nil
downCon:disconnect()
end)
mouseDrag.Parent = getLayerCollectorAncestor(scrollbar)
doScrollDown()
wait(0.2)
local t = tick()
local w = 0.1
while scrollStamp == current do
doScrollDown()
if mouseYPos and mouseYPos < (scrollDrag.AbsolutePosition.y + scrollDrag.AbsoluteSize.x) then
break
end
if not scrollDownButton.Active then break end
if tick()-t > 5 then
w = 0
elseif tick()-t > 2 then
w = 0.06
end
wait(w)
end
end
end
local y = 0
scrollDrag.MouseButton1Down:connect(function(x,y)
if scrollDrag.Active then
scrollStamp = tick()
local mouseOffset = y - scrollDrag.AbsolutePosition.y
local dragCon
local upCon
dragCon = mouseDrag.MouseMoved:connect(function(x,y)
local barAbsPos = scrollbar.AbsolutePosition.y
local barAbsSize = scrollbar.AbsoluteSize.y
local dragAbsSize = scrollDrag.AbsoluteSize.y
local barAbsOne = barAbsPos + barAbsSize - dragAbsSize
y = y - mouseOffset
y = y < barAbsPos and barAbsPos or y > barAbsOne and barAbsOne or y
y = y - barAbsPos
local guiObjects = 0
local children = frame:GetChildren()
if children then
for i, child in ipairs(children) do
if child:IsA("GuiObject") then
guiObjects = guiObjects + 1
end
end
end
local doublePercent = y/(barAbsSize-dragAbsSize)
local rowDiff = rowSize
local totalScrollCount = guiObjects - (howManyDisplayed - 1)
local newScrollPosition = math.floor((doublePercent * totalScrollCount) + 0.5) + rowDiff
if newScrollPosition < scrollPosition then
rowDiff = -rowDiff
end
if newScrollPosition < 1 then
newScrollPosition = 1
end
scrollPosition = newScrollPosition
recalculate(nil)
end)
upCon = mouseDrag.MouseButton1Up:connect(function()
scrollStamp = tick()
mouseDrag.Parent = nil
dragCon:disconnect(); dragCon = nil
upCon:disconnect(); drag = nil
end)
mouseDrag.Parent = getLayerCollectorAncestor(scrollbar)
end
end)
local scrollMouseCount = 0
scrollUpButton.MouseButton1Down:connect(
function()
scrollUp()
end)
scrollUpButton.MouseButton1Up:connect(function()
scrollStamp = tick()
end)
scrollDownButton.MouseButton1Up:connect(function()
scrollStamp = tick()
end)
scrollDownButton.MouseButton1Down:connect(
function()
scrollDown()
end)
scrollbar.MouseButton1Up:connect(function()
scrollStamp = tick()
end)
scrollbar.MouseButton1Down:connect(
function(x,y)
if y > (scrollDrag.AbsoluteSize.y + scrollDrag.AbsolutePosition.y) then
scrollDown(y)
elseif y < (scrollDrag.AbsolutePosition.y) then
scrollUp(y)
end
end)
frame.ChildAdded:connect(function()
recalculate(nil)
end)
frame.ChildRemoved:connect(function()
recalculate(nil)
end)
frame.Changed:connect(
function(prop)
if prop == "AbsoluteSize" then
--Wait a heartbeat for it to sync in
recalculate(nil)
end
end)
frame.AncestryChanged:connect(function() recalculate(nil) end)
return frame, scrollUpButton, scrollDownButton, recalculate, scrollbar
end
local function binaryGrow(min, max, fits)
if min > max then
return min
end
local biggestLegal = min
while min <= max do
local mid = min + math.floor((max - min) / 2)
if fits(mid) and (biggestLegal == nil or biggestLegal < mid) then
biggestLegal = mid
--Try growing
min = mid + 1
else
--Doesn't fit, shrink
max = mid - 1
end
end
return biggestLegal
end
local function binaryShrink(min, max, fits)
if min > max then
return min
end
local smallestLegal = max
while min <= max do
local mid = min + math.floor((max - min) / 2)
if fits(mid) and (smallestLegal == nil or smallestLegal > mid) then
smallestLegal = mid
--It fits, shrink
max = mid - 1
else
--Doesn't fit, grow
min = mid + 1
end
end
return smallestLegal
end
local function getGuiOwner(instance)
while instance ~= nil do
if instance:IsA("ScreenGui") or instance:IsA("BillboardGui") then
return instance
end
instance = instance.Parent
end
return nil
end
t.AutoTruncateTextObject = function(textLabel)
local text = textLabel.Text
local fullLabel = textLabel:Clone()
fullLabel.Name = "Full" .. textLabel.Name
fullLabel.BorderSizePixel = 0
fullLabel.BackgroundTransparency = 0
fullLabel.Text = text
fullLabel.TextXAlignment = Enum.TextXAlignment.Center
fullLabel.Position = UDim2.new(0,-3,0,0)
fullLabel.Size = UDim2.new(0,100,1,0)
fullLabel.Visible = false
fullLabel.Parent = textLabel
local shortText = nil
local mouseEnterConnection = nil
local mouseLeaveConnection= nil
local checkForResize = function()
if getGuiOwner(textLabel) == nil then
return
end
textLabel.Text = text
if textLabel.TextFits then
--Tear down the rollover if it is active
if mouseEnterConnection then
mouseEnterConnection:disconnect()
mouseEnterConnection = nil
end
if mouseLeaveConnection then
mouseLeaveConnection:disconnect()
mouseLeaveConnection = nil
end
else
local len = string.len(text)
textLabel.Text = text .. "~"
--Shrink the text
local textSize = binaryGrow(0, len,
function(pos)
if pos == 0 then
textLabel.Text = "~"
else
textLabel.Text = string.sub(text, 1, pos) .. "~"
end
return textLabel.TextFits
end)
shortText = string.sub(text, 1, textSize) .. "~"
textLabel.Text = shortText
--Make sure the fullLabel fits
if not fullLabel.TextFits then
--Already too small, grow it really bit to start
fullLabel.Size = UDim2.new(0, 10000, 1, 0)
end
--Okay, now try to binary shrink it back down
local fullLabelSize = binaryShrink(textLabel.AbsoluteSize.X,fullLabel.AbsoluteSize.X,
function(size)
fullLabel.Size = UDim2.new(0, size, 1, 0)
return fullLabel.TextFits
end)
fullLabel.Size = UDim2.new(0,fullLabelSize+6,1,0)
--Now setup the rollover effects, if they are currently off
if mouseEnterConnection == nil then
mouseEnterConnection = textLabel.MouseEnter:connect(
function()
fullLabel.ZIndex = textLabel.ZIndex + 1
fullLabel.Visible = true
--textLabel.Text = ""
end)
end
if mouseLeaveConnection == nil then
mouseLeaveConnection = textLabel.MouseLeave:connect(
function()
fullLabel.Visible = false
--textLabel.Text = shortText
end)
end
end
end
textLabel.AncestryChanged:connect(checkForResize)
textLabel.Changed:connect(
function(prop)
if prop == "AbsoluteSize" then
checkForResize()
end
end)
checkForResize()
local function changeText(newText)
text = newText
fullLabel.Text = text
checkForResize()
end
return textLabel, changeText
end
local function TransitionTutorialPages(fromPage, toPage, transitionFrame, currentPageValue)
if fromPage then
fromPage.Visible = false
if transitionFrame.Visible == false then
transitionFrame.Size = fromPage.Size
transitionFrame.Position = fromPage.Position
end
else
if transitionFrame.Visible == false then
transitionFrame.Size = UDim2.new(0.0,50,0.0,50)
transitionFrame.Position = UDim2.new(0.5,-25,0.5,-25)
end
end
transitionFrame.Visible = true
currentPageValue.Value = nil
local newSize, newPosition
if toPage then
--Make it visible so it resizes
toPage.Visible = true
newSize = toPage.Size
newPosition = toPage.Position
toPage.Visible = false
else
newSize = UDim2.new(0.0,50,0.0,50)
newPosition = UDim2.new(0.5,-25,0.5,-25)
end
transitionFrame:TweenSizeAndPosition(newSize, newPosition, Enum.EasingDirection.InOut, Enum.EasingStyle.Quad, 0.3, true,
function(state)
if state == Enum.TweenStatus.Completed then
transitionFrame.Visible = false
if toPage then
toPage.Visible = true
currentPageValue.Value = toPage
end
end
end)
end
t.CreateTutorial = function(name, tutorialKey, createButtons)
local frame = Instance.new("Frame")
frame.Name = "Tutorial-" .. name
frame.BackgroundTransparency = 1
frame.Size = UDim2.new(0.6, 0, 0.6, 0)
frame.Position = UDim2.new(0.2, 0, 0.2, 0)
local transitionFrame = Instance.new("Frame")
transitionFrame.Name = "TransitionFrame"
transitionFrame.Style = Enum.FrameStyle.RobloxRound
transitionFrame.Size = UDim2.new(0.6, 0, 0.6, 0)
transitionFrame.Position = UDim2.new(0.2, 0, 0.2, 0)
transitionFrame.Visible = false
transitionFrame.Parent = frame
local currentPageValue = Instance.new("ObjectValue")
currentPageValue.Name = "CurrentTutorialPage"
currentPageValue.Value = nil
currentPageValue.Parent = frame
local boolValue = Instance.new("BoolValue")
boolValue.Name = "Buttons"
boolValue.Value = createButtons
boolValue.Parent = frame
local pages = Instance.new("Frame")
pages.Name = "Pages"
pages.BackgroundTransparency = 1
pages.Size = UDim2.new(1,0,1,0)
pages.Parent = frame
local function getVisiblePageAndHideOthers()
local visiblePage = nil
local children = pages:GetChildren()
if children then
for i,child in ipairs(children) do
if child.Visible then
if visiblePage then
child.Visible = false
else
visiblePage = child
end
end
end
end
return visiblePage
end
local showTutorial = function(alwaysShow)
if alwaysShow or UserSettings().GameSettings:GetTutorialState(tutorialKey) == false then
print("Showing tutorial-",tutorialKey)
local currentTutorialPage = getVisiblePageAndHideOthers()
local firstPage = pages:FindFirstChild("TutorialPage1")
if firstPage then
TransitionTutorialPages(currentTutorialPage, firstPage, transitionFrame, currentPageValue)
else
error("Could not find TutorialPage1")
end
end
end
local dismissTutorial = function()
local currentTutorialPage = getVisiblePageAndHideOthers()
if currentTutorialPage then
TransitionTutorialPages(currentTutorialPage, nil, transitionFrame, currentPageValue)
end
UserSettings().GameSettings:SetTutorialState(tutorialKey, true)
end
local gotoPage = function(pageNum)
local page = pages:FindFirstChild("TutorialPage" .. pageNum)
local currentTutorialPage = getVisiblePageAndHideOthers()
TransitionTutorialPages(currentTutorialPage, page, transitionFrame, currentPageValue)
end
return frame, showTutorial, dismissTutorial, gotoPage
end
local function CreateBasicTutorialPage(name, handleResize, skipTutorial, giveDoneButton)
local frame = Instance.new("Frame")
frame.Name = "TutorialPage"
frame.Style = Enum.FrameStyle.RobloxRound
frame.Size = UDim2.new(0.6, 0, 0.6, 0)
frame.Position = UDim2.new(0.2, 0, 0.2, 0)
frame.Visible = false
local frameHeader = Instance.new("TextLabel")
frameHeader.Name = "Header"
frameHeader.Text = name
frameHeader.BackgroundTransparency = 1
frameHeader.FontSize = Enum.FontSize.Size24
frameHeader.Font = Enum.Font.ArialBold
frameHeader.TextColor3 = Color3.new(1,1,1)
frameHeader.TextXAlignment = Enum.TextXAlignment.Center
frameHeader.TextWrap = true
frameHeader.Size = UDim2.new(1,-55, 0, 22)
frameHeader.Position = UDim2.new(0,0,0,0)
frameHeader.Parent = frame
local skipButton = Instance.new("ImageButton")
skipButton.Name = "SkipButton"
skipButton.AutoButtonColor = false
skipButton.BackgroundTransparency = 1
skipButton.Image = "rbxasset://textures/ui/closeButton.png"
skipButton.MouseButton1Click:connect(function()
skipTutorial()
end)
skipButton.MouseEnter:connect(function()
skipButton.Image = "rbxasset://textures/ui/closeButton_dn.png"
end)
skipButton.MouseLeave:connect(function()
skipButton.Image = "rbxasset://textures/ui/closeButton.png"
end)
skipButton.Size = UDim2.new(0, 25, 0, 25)
skipButton.Position = UDim2.new(1, -25, 0, 0)
skipButton.Parent = frame
if giveDoneButton then
local doneButton = Instance.new("TextButton")
doneButton.Name = "DoneButton"
doneButton.Style = Enum.ButtonStyle.RobloxButtonDefault
doneButton.Text = "Done"
doneButton.TextColor3 = Color3.new(1,1,1)
doneButton.Font = Enum.Font.ArialBold
doneButton.FontSize = Enum.FontSize.Size18
doneButton.Size = UDim2.new(0,100,0,50)
doneButton.Position = UDim2.new(0.5,-50,1,-50)
if skipTutorial then
doneButton.MouseButton1Click:connect(function() skipTutorial() end)
end
doneButton.Parent = frame
end
local innerFrame = Instance.new("Frame")
innerFrame.Name = "ContentFrame"
innerFrame.BackgroundTransparency = 1
innerFrame.Position = UDim2.new(0,0,0,25)
innerFrame.Parent = frame
local nextButton = Instance.new("TextButton")
nextButton.Name = "NextButton"
nextButton.Text = "Next"
nextButton.TextColor3 = Color3.new(1,1,1)
nextButton.Font = Enum.Font.Arial
nextButton.FontSize = Enum.FontSize.Size18
nextButton.Style = Enum.ButtonStyle.RobloxButtonDefault
nextButton.Size = UDim2.new(0,80, 0, 32)
nextButton.Position = UDim2.new(0.5, 5, 1, -32)
nextButton.Active = false
nextButton.Visible = false
nextButton.Parent = frame
local prevButton = Instance.new("TextButton")
prevButton.Name = "PrevButton"
prevButton.Text = "Previous"
prevButton.TextColor3 = Color3.new(1,1,1)
prevButton.Font = Enum.Font.Arial
prevButton.FontSize = Enum.FontSize.Size18
prevButton.Style = Enum.ButtonStyle.RobloxButton
prevButton.Size = UDim2.new(0,80, 0, 32)
prevButton.Position = UDim2.new(0.5, -85, 1, -32)
prevButton.Active = false
prevButton.Visible = false
prevButton.Parent = frame
if giveDoneButton then
innerFrame.Size = UDim2.new(1,0,1,-75)
else
innerFrame.Size = UDim2.new(1,0,1,-22)
end
local parentConnection = nil
local function basicHandleResize()
if frame.Visible and frame.Parent then
local maxSize = math.min(frame.Parent.AbsoluteSize.X, frame.Parent.AbsoluteSize.Y)
handleResize(200,maxSize)
end
end
frame.Changed:connect(
function(prop)
if prop == "Parent" then
if parentConnection ~= nil then
parentConnection:disconnect()
parentConnection = nil
end
if frame.Parent and frame.Parent:IsA("GuiObject") then
parentConnection = frame.Parent.Changed:connect(
function(parentProp)
if parentProp == "AbsoluteSize" then
wait()
basicHandleResize()
end
end)
basicHandleResize()
end
end
if prop == "Visible" then
basicHandleResize()
end
end)
return frame, innerFrame
end
t.CreateTextTutorialPage = function(name, text, skipTutorialFunc)
local frame = nil
local contentFrame = nil
local textLabel = Instance.new("TextLabel")
textLabel.BackgroundTransparency = 1
textLabel.TextColor3 = Color3.new(1,1,1)
textLabel.Text = text
textLabel.TextWrap = true
textLabel.TextXAlignment = Enum.TextXAlignment.Left
textLabel.TextYAlignment = Enum.TextYAlignment.Center
textLabel.Font = Enum.Font.Arial
textLabel.FontSize = Enum.FontSize.Size14
textLabel.Size = UDim2.new(1,0,1,0)
local function handleResize(minSize, maxSize)
size = binaryShrink(minSize, maxSize,
function(size)
frame.Size = UDim2.new(0, size, 0, size)
return textLabel.TextFits
end)
frame.Size = UDim2.new(0, size, 0, size)
frame.Position = UDim2.new(0.5, -size/2, 0.5, -size/2)
end
frame, contentFrame = CreateBasicTutorialPage(name, handleResize, skipTutorialFunc)
textLabel.Parent = contentFrame
return frame
end
t.CreateImageTutorialPage = function(name, imageAsset, x, y, skipTutorialFunc, giveDoneButton)
local frame = nil
local contentFrame = nil
local imageLabel = Instance.new("ImageLabel")
imageLabel.BackgroundTransparency = 1
imageLabel.Image = imageAsset
imageLabel.Size = UDim2.new(0,x,0,y)
imageLabel.Position = UDim2.new(0.5,-x/2,0.5,-y/2)
local function handleResize(minSize, maxSize)
size = binaryShrink(minSize, maxSize,
function(size)
return size >= x and size >= y
end)
if size >= x and size >= y then
imageLabel.Size = UDim2.new(0,x, 0,y)
imageLabel.Position = UDim2.new(0.5,-x/2, 0.5, -y/2)
else
if x > y then
--X is limiter, so
imageLabel.Size = UDim2.new(1,0,y/x,0)
imageLabel.Position = UDim2.new(0,0, 0.5 - (y/x)/2, 0)
else
--Y is limiter
imageLabel.Size = UDim2.new(x/y,0,1, 0)
imageLabel.Position = UDim2.new(0.5-(x/y)/2, 0, 0, 0)
end
end
size = size + 50
frame.Size = UDim2.new(0, size, 0, size)
frame.Position = UDim2.new(0.5, -size/2, 0.5, -size/2)
end
frame, contentFrame = CreateBasicTutorialPage(name, handleResize, skipTutorialFunc, giveDoneButton)
imageLabel.Parent = contentFrame
return frame
end
t.AddTutorialPage = function(tutorial, tutorialPage)
local transitionFrame = tutorial.TransitionFrame
local currentPageValue = tutorial.CurrentTutorialPage
if not tutorial.Buttons.Value then
tutorialPage.NextButton.Parent = nil
tutorialPage.PrevButton.Parent = nil
end
local children = tutorial.Pages:GetChildren()
if children and #children > 0 then
tutorialPage.Name = "TutorialPage" .. (#children+1)
local previousPage = children[#children]
if not previousPage:IsA("GuiObject") then
error("All elements under Pages must be GuiObjects")
end
if tutorial.Buttons.Value then
if previousPage.NextButton.Active then
error("NextButton already Active on previousPage, please only add pages with RbxGui.AddTutorialPage function")
end
previousPage.NextButton.MouseButton1Click:connect(
function()
TransitionTutorialPages(previousPage, tutorialPage, transitionFrame, currentPageValue)
end)
previousPage.NextButton.Active = true
previousPage.NextButton.Visible = true
if tutorialPage.PrevButton.Active then
error("PrevButton already Active on tutorialPage, please only add pages with RbxGui.AddTutorialPage function")
end
tutorialPage.PrevButton.MouseButton1Click:connect(
function()
TransitionTutorialPages(tutorialPage, previousPage, transitionFrame, currentPageValue)
end)
tutorialPage.PrevButton.Active = true
tutorialPage.PrevButton.Visible = true
end
tutorialPage.Parent = tutorial.Pages
else
--First child
tutorialPage.Name = "TutorialPage1"
tutorialPage.Parent = tutorial.Pages
end
end
t.CreateSetPanel = function(userIdsForSets, objectSelected, dialogClosed, size, position, showAdminCategories, useAssetVersionId)
if not userIdsForSets then
error("CreateSetPanel: userIdsForSets (first arg) is nil, should be a table of number ids")
end
if type(userIdsForSets) ~= "table" and type(userIdsForSets) ~= "userdata" then
error("CreateSetPanel: userIdsForSets (first arg) is of type " ..type(userIdsForSets) .. ", should be of type table or userdata")
end
if not objectSelected then
error("CreateSetPanel: objectSelected (second arg) is nil, should be a callback function!")
end
if type(objectSelected) ~= "function" then
error("CreateSetPanel: objectSelected (second arg) is of type " .. type(objectSelected) .. ", should be of type function!")
end
if dialogClosed and type(dialogClosed) ~= "function" then
error("CreateSetPanel: dialogClosed (third arg) is of type " .. type(dialogClosed) .. ", should be of type function!")
end
if showAdminCategories == nil then -- by default, don't show beta sets
showAdminCategories = false
end
local arrayPosition = 1
local insertButtons = {}
local insertButtonCons = {}
local contents = nil
local setGui = nil
-- used for water selections
local waterForceDirection = "NegX"
local waterForce = "None"
local waterGui, waterTypeChangedEvent = nil
local Data = {}
Data.CurrentCategory = nil
Data.Category = {}
local SetCache = {}
local userCategoryButtons = nil
local buttonWidth = 64
local buttonHeight = buttonWidth
local SmallThumbnailUrl = nil
local LargeThumbnailUrl = nil
local BaseUrl = game:GetService("ContentProvider").BaseUrl:lower()
local AssetGameUrl = string.gsub(BaseUrl, "www", "assetgame")
if useAssetVersionId then
LargeThumbnailUrl = AssetGameUrl .. "Game/Tools/ThumbnailAsset.ashx?fmt=png&wd=420&ht=420&assetversionid="
SmallThumbnailUrl = AssetGameUrl .. "Game/Tools/ThumbnailAsset.ashx?fmt=png&wd=75&ht=75&assetversionid="
else
LargeThumbnailUrl = AssetGameUrl .. "Game/Tools/ThumbnailAsset.ashx?fmt=png&wd=420&ht=420&aid="
SmallThumbnailUrl = AssetGameUrl .. "Game/Tools/ThumbnailAsset.ashx?fmt=png&wd=75&ht=75&aid="
end
local function drillDownSetZIndex(parent, index)
local children = parent:GetChildren()
for i = 1, #children do
if children[i]:IsA("GuiObject") then
children[i].ZIndex = index
end
drillDownSetZIndex(children[i], index)
end
end
-- for terrain stamping
local currTerrainDropDownFrame = nil
local terrainShapes = {"Block","Vertical Ramp","Corner Wedge","Inverse Corner Wedge","Horizontal Ramp","Auto-Wedge"}
local terrainShapeMap = {}
for i = 1, #terrainShapes do
terrainShapeMap[terrainShapes[i]] = i - 1
end
terrainShapeMap[terrainShapes[#terrainShapes]] = 6
local function createWaterGui()
local waterForceDirections = {"NegX","X","NegY","Y","NegZ","Z"}
local waterForces = {"None", "Small", "Medium", "Strong", "Max"}
local waterFrame = Instance.new("Frame")
waterFrame.Name = "WaterFrame"
waterFrame.Style = Enum.FrameStyle.RobloxSquare
waterFrame.Size = UDim2.new(0,150,0,110)
waterFrame.Visible = false
local waterForceLabel = Instance.new("TextLabel")
waterForceLabel.Name = "WaterForceLabel"
waterForceLabel.BackgroundTransparency = 1
waterForceLabel.Size = UDim2.new(1,0,0,12)
waterForceLabel.Font = Enum.Font.ArialBold
waterForceLabel.FontSize = Enum.FontSize.Size12
waterForceLabel.TextColor3 = Color3.new(1,1,1)
waterForceLabel.TextXAlignment = Enum.TextXAlignment.Left
waterForceLabel.Text = "Water Force"
waterForceLabel.Parent = waterFrame
local waterForceDirLabel = waterForceLabel:Clone()
waterForceDirLabel.Name = "WaterForceDirectionLabel"
waterForceDirLabel.Text = "Water Force Direction"
waterForceDirLabel.Position = UDim2.new(0,0,0,50)
waterForceDirLabel.Parent = waterFrame
local waterTypeChangedEvent = Instance.new("BindableEvent",waterFrame)
waterTypeChangedEvent.Name = "WaterTypeChangedEvent"
local waterForceDirectionSelectedFunc = function(newForceDirection)
waterForceDirection = newForceDirection
waterTypeChangedEvent:Fire({waterForce, waterForceDirection})
end
local waterForceSelectedFunc = function(newForce)
waterForce = newForce
waterTypeChangedEvent:Fire({waterForce, waterForceDirection})
end
local waterForceDirectionDropDown, forceWaterDirectionSelection = t.CreateDropDownMenu(waterForceDirections, waterForceDirectionSelectedFunc)
waterForceDirectionDropDown.Size = UDim2.new(1,0,0,25)
waterForceDirectionDropDown.Position = UDim2.new(0,0,1,3)
forceWaterDirectionSelection("NegX")
waterForceDirectionDropDown.Parent = waterForceDirLabel
local waterForceDropDown, forceWaterForceSelection = t.CreateDropDownMenu(waterForces, waterForceSelectedFunc)
forceWaterForceSelection("None")
waterForceDropDown.Size = UDim2.new(1,0,0,25)
waterForceDropDown.Position = UDim2.new(0,0,1,3)
waterForceDropDown.Parent = waterForceLabel
return waterFrame, waterTypeChangedEvent
end
-- Helper Function that contructs gui elements
local function createSetGui()
local setGui = Instance.new("ScreenGui")
setGui.Name = "SetGui"
local setPanel = Instance.new("Frame")
setPanel.Name = "SetPanel"
setPanel.Active = true
setPanel.BackgroundTransparency = 1
if position then
setPanel.Position = position
else
setPanel.Position = UDim2.new(0.2, 29, 0.1, 24)
end
if size then
setPanel.Size = size
else
setPanel.Size = UDim2.new(0.6, -58, 0.64, 0)
end
setPanel.Style = Enum.FrameStyle.RobloxRound
setPanel.ZIndex = 6
setPanel.Parent = setGui
-- Children of SetPanel
local itemPreview = Instance.new("Frame")
itemPreview.Name = "ItemPreview"
itemPreview.BackgroundTransparency = 1
itemPreview.Position = UDim2.new(0.8,5,0.085,0)
itemPreview.Size = UDim2.new(0.21,0,0.9,0)
itemPreview.ZIndex = 6
itemPreview.Parent = setPanel
-- Children of ItemPreview
local textPanel = Instance.new("Frame")
textPanel.Name = "TextPanel"
textPanel.BackgroundTransparency = 1
textPanel.Position = UDim2.new(0,0,0.45,0)
textPanel.Size = UDim2.new(1,0,0.55,0)
textPanel.ZIndex = 6
textPanel.Parent = itemPreview
-- Children of TextPanel
local rolloverText = Instance.new("TextLabel")
rolloverText.Name = "RolloverText"
rolloverText.BackgroundTransparency = 1
rolloverText.Size = UDim2.new(1,0,0,48)
rolloverText.ZIndex = 6
rolloverText.Font = Enum.Font.ArialBold
rolloverText.FontSize = Enum.FontSize.Size24
rolloverText.Text = ""
rolloverText.TextColor3 = Color3.new(1,1,1)
rolloverText.TextWrap = true
rolloverText.TextXAlignment = Enum.TextXAlignment.Left
rolloverText.TextYAlignment = Enum.TextYAlignment.Top
rolloverText.Parent = textPanel
local largePreview = Instance.new("ImageLabel")
largePreview.Name = "LargePreview"
largePreview.BackgroundTransparency = 1
largePreview.Image = ""
largePreview.Size = UDim2.new(1,0,0,170)
largePreview.ZIndex = 6
largePreview.Parent = itemPreview
local sets = Instance.new("Frame")
sets.Name = "Sets"
sets.BackgroundTransparency = 1
sets.Position = UDim2.new(0,0,0,5)
sets.Size = UDim2.new(0.23,0,1,-5)
sets.ZIndex = 6
sets.Parent = setPanel
-- Children of Sets
local line = Instance.new("Frame")
line.Name = "Line"
line.BackgroundColor3 = Color3.new(1,1,1)
line.BackgroundTransparency = 0.7
line.BorderSizePixel = 0
line.Position = UDim2.new(1,-3,0.06,0)
line.Size = UDim2.new(0,3,0.9,0)
line.ZIndex = 6
line.Parent = sets
local setsLists, controlFrame = t.CreateTrueScrollingFrame()
setsLists.Size = UDim2.new(1,-6,0.94,0)
setsLists.Position = UDim2.new(0,0,0.06,0)
setsLists.BackgroundTransparency = 1
setsLists.Name = "SetsLists"
setsLists.ZIndex = 6
setsLists.Parent = sets
drillDownSetZIndex(controlFrame, 7)
local setsHeader = Instance.new("TextLabel")
setsHeader.Name = "SetsHeader"
setsHeader.BackgroundTransparency = 1
setsHeader.Size = UDim2.new(0,47,0,24)
setsHeader.ZIndex = 6
setsHeader.Font = Enum.Font.ArialBold
setsHeader.FontSize = Enum.FontSize.Size24
setsHeader.Text = "Sets"
setsHeader.TextColor3 = Color3.new(1,1,1)
setsHeader.TextXAlignment = Enum.TextXAlignment.Left
setsHeader.TextYAlignment = Enum.TextYAlignment.Top
setsHeader.Parent = sets
local cancelButton = Instance.new("TextButton")
cancelButton.Name = "CancelButton"
cancelButton.Position = UDim2.new(1,-32,0,-2)
cancelButton.Size = UDim2.new(0,34,0,34)
cancelButton.Style = Enum.ButtonStyle.RobloxButtonDefault
cancelButton.ZIndex = 6
cancelButton.Text = ""
cancelButton.Modal = true
cancelButton.Parent = setPanel
-- Children of Cancel Button
local cancelImage = Instance.new("ImageLabel")
cancelImage.Name = "CancelImage"
cancelImage.BackgroundTransparency = 1
cancelImage.Image = "https://www.roblox.com/asset/?id=54135717"
cancelImage.Position = UDim2.new(0,-2,0,-2)
cancelImage.Size = UDim2.new(0,16,0,16)
cancelImage.ZIndex = 6
cancelImage.Parent = cancelButton
return setGui
end
local function createSetButton(text)
local setButton = Instance.new("TextButton")
if text then setButton.Text = text
else setButton.Text = "" end
setButton.AutoButtonColor = false
setButton.BackgroundTransparency = 1
setButton.BackgroundColor3 = Color3.new(1,1,1)
setButton.BorderSizePixel = 0
setButton.Size = UDim2.new(1,-5,0,18)
setButton.ZIndex = 6
setButton.Visible = false
setButton.Font = Enum.Font.Arial
setButton.FontSize = Enum.FontSize.Size18
setButton.TextColor3 = Color3.new(1,1,1)
setButton.TextXAlignment = Enum.TextXAlignment.Left
return setButton
end
local function buildSetButton(name, setId, setImageId, i, count)
local button = createSetButton(name)
button.Text = name
button.Name = "SetButton"
button.Visible = true
local setValue = Instance.new("IntValue")
setValue.Name = "SetId"
setValue.Value = setId
setValue.Parent = button
local setName = Instance.new("StringValue")
setName.Name = "SetName"
setName.Value = name
setName.Parent = button
return button
end
local function processCategory(sets)
local setButtons = {}
local numSkipped = 0
for i = 1, #sets do
if not showAdminCategories and sets[i].Name == "Beta" then
numSkipped = numSkipped + 1
else
setButtons[i - numSkipped] = buildSetButton(sets[i].Name, sets[i].CategoryId, sets[i].ImageAssetId, i - numSkipped, #sets)
end
end
return setButtons
end
local function handleResize()
wait() -- neccessary to insure heartbeat happened
local itemPreview = setGui.SetPanel.ItemPreview
itemPreview.LargePreview.Size = UDim2.new(1,0,0,itemPreview.AbsoluteSize.X)
itemPreview.LargePreview.Position = UDim2.new(0.5,-itemPreview.LargePreview.AbsoluteSize.X/2,0,0)
itemPreview.TextPanel.Position = UDim2.new(0,0,0,itemPreview.LargePreview.AbsoluteSize.Y)
itemPreview.TextPanel.Size = UDim2.new(1,0,0,itemPreview.AbsoluteSize.Y - itemPreview.LargePreview.AbsoluteSize.Y)
end
local function makeInsertAssetButton()
local insertAssetButtonExample = Instance.new("Frame")
insertAssetButtonExample.Name = "InsertAssetButtonExample"
insertAssetButtonExample.Position = UDim2.new(0,128,0,64)
insertAssetButtonExample.Size = UDim2.new(0,64,0,64)
insertAssetButtonExample.BackgroundTransparency = 1
insertAssetButtonExample.ZIndex = 6
insertAssetButtonExample.Visible = false
local assetId = Instance.new("IntValue")
assetId.Name = "AssetId"
assetId.Value = 0
assetId.Parent = insertAssetButtonExample
local assetName = Instance.new("StringValue")
assetName.Name = "AssetName"
assetName.Value = ""
assetName.Parent = insertAssetButtonExample
local button = Instance.new("TextButton")
button.Name = "Button"
button.Text = ""
button.Style = Enum.ButtonStyle.RobloxButton
button.Position = UDim2.new(0.025,0,0.025,0)
button.Size = UDim2.new(0.95,0,0.95,0)
button.ZIndex = 6
button.Parent = insertAssetButtonExample
local buttonImage = Instance.new("ImageLabel")
buttonImage.Name = "ButtonImage"
buttonImage.Image = ""
buttonImage.Position = UDim2.new(0,-7,0,-7)
buttonImage.Size = UDim2.new(1,14,1,14)
buttonImage.BackgroundTransparency = 1
buttonImage.ZIndex = 7
buttonImage.Parent = button
local configIcon = buttonImage:clone()
configIcon.Name = "ConfigIcon"
configIcon.Visible = false
configIcon.Position = UDim2.new(1,-23,1,-24)
configIcon.Size = UDim2.new(0,16,0,16)
configIcon.Image = ""
configIcon.ZIndex = 6
configIcon.Parent = insertAssetButtonExample
return insertAssetButtonExample
end
local function showLargePreview(insertButton)
if insertButton:FindFirstChild("AssetId") then
delay(0,function()
game:GetService("ContentProvider"):Preload(LargeThumbnailUrl .. tostring(insertButton.AssetId.Value))
setGui.SetPanel.ItemPreview.LargePreview.Image = LargeThumbnailUrl .. tostring(insertButton.AssetId.Value)
end)
end
if insertButton:FindFirstChild("AssetName") then
setGui.SetPanel.ItemPreview.TextPanel.RolloverText.Text = insertButton.AssetName.Value
end
end
local function selectTerrainShape(shape)
if currTerrainDropDownFrame then
objectSelected(tostring(currTerrainDropDownFrame.AssetName.Value), tonumber(currTerrainDropDownFrame.AssetId.Value), shape)
end
end
local function createTerrainTypeButton(name, parent)
local dropDownTextButton = Instance.new("TextButton")
dropDownTextButton.Name = name .. "Button"
dropDownTextButton.Font = Enum.Font.ArialBold
dropDownTextButton.FontSize = Enum.FontSize.Size14
dropDownTextButton.BorderSizePixel = 0
dropDownTextButton.TextColor3 = Color3.new(1,1,1)
dropDownTextButton.Text = name
dropDownTextButton.TextXAlignment = Enum.TextXAlignment.Left
dropDownTextButton.BackgroundTransparency = 1
dropDownTextButton.ZIndex = parent.ZIndex + 1
dropDownTextButton.Size = UDim2.new(0,parent.Size.X.Offset - 2,0,16)
dropDownTextButton.Position = UDim2.new(0,1,0,0)
dropDownTextButton.MouseEnter:connect(function()
dropDownTextButton.BackgroundTransparency = 0
dropDownTextButton.TextColor3 = Color3.new(0,0,0)
end)
dropDownTextButton.MouseLeave:connect(function()
dropDownTextButton.BackgroundTransparency = 1
dropDownTextButton.TextColor3 = Color3.new(1,1,1)
end)
dropDownTextButton.MouseButton1Click:connect(function()
dropDownTextButton.BackgroundTransparency = 1
dropDownTextButton.TextColor3 = Color3.new(1,1,1)
if dropDownTextButton.Parent and dropDownTextButton.Parent:IsA("GuiObject") then
dropDownTextButton.Parent.Visible = false
end
selectTerrainShape(terrainShapeMap[dropDownTextButton.Text])
end)
return dropDownTextButton
end
local function createTerrainDropDownMenu(zIndex)
local dropDown = Instance.new("Frame")
dropDown.Name = "TerrainDropDown"
dropDown.BackgroundColor3 = Color3.new(0,0,0)
dropDown.BorderColor3 = Color3.new(1,0,0)
dropDown.Size = UDim2.new(0,200,0,0)
dropDown.Visible = false
dropDown.ZIndex = zIndex
dropDown.Parent = setGui
for i = 1, #terrainShapes do
local shapeButton = createTerrainTypeButton(terrainShapes[i],dropDown)
shapeButton.Position = UDim2.new(0,1,0,(i - 1) * (shapeButton.Size.Y.Offset))
shapeButton.Parent = dropDown
dropDown.Size = UDim2.new(0,200,0,dropDown.Size.Y.Offset + (shapeButton.Size.Y.Offset))
end
dropDown.MouseLeave:connect(function()
dropDown.Visible = false
end)
end
local function createDropDownMenuButton(parent)
local dropDownButton = Instance.new("ImageButton")
dropDownButton.Name = "DropDownButton"
dropDownButton.Image = "https://www.roblox.com/asset/?id=67581509"
dropDownButton.BackgroundTransparency = 1
dropDownButton.Size = UDim2.new(0,16,0,16)
dropDownButton.Position = UDim2.new(1,-24,0,6)
dropDownButton.ZIndex = parent.ZIndex + 2
dropDownButton.Parent = parent
if not setGui:FindFirstChild("TerrainDropDown") then
createTerrainDropDownMenu(8)
end
dropDownButton.MouseButton1Click:connect(function()
setGui.TerrainDropDown.Visible = true
setGui.TerrainDropDown.Position = UDim2.new(0,parent.AbsolutePosition.X,0,parent.AbsolutePosition.Y)
currTerrainDropDownFrame = parent
end)
end
local function buildInsertButton()
local insertButton = makeInsertAssetButton()
insertButton.Name = "InsertAssetButton"
insertButton.Visible = true
if Data.Category[Data.CurrentCategory].SetName == "High Scalability" then
createDropDownMenuButton(insertButton)
end
local lastEnter = nil
local mouseEnterCon = insertButton.MouseEnter:connect(function()
lastEnter = insertButton
delay(0.1,function()
if lastEnter == insertButton then
showLargePreview(insertButton)
end
end)
end)
return insertButton, mouseEnterCon
end
local function realignButtonGrid(columns)
local x = 0
local y = 0
for i = 1, #insertButtons do
insertButtons[i].Position = UDim2.new(0, buttonWidth * x, 0, buttonHeight * y)
x = x + 1
if x >= columns then
x = 0
y = y + 1
end
end
end
local function setInsertButtonImageBehavior(insertFrame, visible, name, assetId)
if visible then
insertFrame.AssetName.Value = name
insertFrame.AssetId.Value = assetId
local newImageUrl = SmallThumbnailUrl .. assetId
if newImageUrl ~= insertFrame.Button.ButtonImage.Image then
delay(0,function()
game:GetService("ContentProvider"):Preload(SmallThumbnailUrl .. assetId)
if insertFrame:findFirstChild("Button") then
insertFrame.Button.ButtonImage.Image = SmallThumbnailUrl .. assetId
end
end)
end
table.insert(insertButtonCons,
insertFrame.Button.MouseButton1Click:connect(function()
-- special case for water, show water selection gui
local isWaterSelected = (name == "Water") and (Data.Category[Data.CurrentCategory].SetName == "High Scalability")
waterGui.Visible = isWaterSelected
if isWaterSelected then
objectSelected(name, tonumber(assetId), nil)
else
objectSelected(name, tonumber(assetId))
end
end)
)
insertFrame.Visible = true
else
insertFrame.Visible = false
end
end
local function loadSectionOfItems(setGui, rows, columns)
local pageSize = rows * columns
if arrayPosition > #contents then return end
local origArrayPos = arrayPosition
local yCopy = 0
for i = 1, pageSize + 1 do
if arrayPosition >= #contents + 1 then
break
end
local buttonCon
insertButtons[arrayPosition], buttonCon = buildInsertButton()
table.insert(insertButtonCons,buttonCon)
insertButtons[arrayPosition].Parent = setGui.SetPanel.ItemsFrame
arrayPosition = arrayPosition + 1
end
realignButtonGrid(columns)
local indexCopy = origArrayPos
for index = origArrayPos, arrayPosition do
if insertButtons[index] then
if contents[index] then
-- we don't want water to have a drop down button
if contents[index].Name == "Water" then
if Data.Category[Data.CurrentCategory].SetName == "High Scalability" then
insertButtons[index]:FindFirstChild("DropDownButton",true):Destroy()
end
end
local assetId
if useAssetVersionId then
assetId = contents[index].AssetVersionId
else
assetId = contents[index].AssetId
end
setInsertButtonImageBehavior(insertButtons[index], true, contents[index].Name, assetId)
else
break
end
else
break
end
indexCopy = index
end
end
local function setSetIndex()
Data.Category[Data.CurrentCategory].Index = 0
rows = 7
columns = math.floor(setGui.SetPanel.ItemsFrame.AbsoluteSize.X/buttonWidth)
contents = Data.Category[Data.CurrentCategory].Contents
if contents then
-- remove our buttons and their connections
for i = 1, #insertButtons do
insertButtons[i]:remove()
end
for i = 1, #insertButtonCons do
if insertButtonCons[i] then insertButtonCons[i]:disconnect() end
end
insertButtonCons = {}
insertButtons = {}
arrayPosition = 1
loadSectionOfItems(setGui, rows, columns)
end
end
local function selectSet(button, setName, setId, setIndex)
if button and Data.Category[Data.CurrentCategory] ~= nil then
if button ~= Data.Category[Data.CurrentCategory].Button then
Data.Category[Data.CurrentCategory].Button = button
if SetCache[setId] == nil then
SetCache[setId] = game:GetService("InsertService"):GetCollection(setId)
end
Data.Category[Data.CurrentCategory].Contents = SetCache[setId]
Data.Category[Data.CurrentCategory].SetName = setName
Data.Category[Data.CurrentCategory].SetId = setId
end
setSetIndex()
end
end
local function selectCategoryPage(buttons, page)
if buttons ~= Data.CurrentCategory then
if Data.CurrentCategory then
for key, button in pairs(Data.CurrentCategory) do
button.Visible = false
end
end
Data.CurrentCategory = buttons
if Data.Category[Data.CurrentCategory] == nil then
Data.Category[Data.CurrentCategory] = {}
if #buttons > 0 then
selectSet(buttons[1], buttons[1].SetName.Value, buttons[1].SetId.Value, 0)
end
else
Data.Category[Data.CurrentCategory].Button = nil
selectSet(Data.Category[Data.CurrentCategory].ButtonFrame, Data.Category[Data.CurrentCategory].SetName, Data.Category[Data.CurrentCategory].SetId, Data.Category[Data.CurrentCategory].Index)
end
end
end
local function selectCategory(category)
selectCategoryPage(category, 0)
end
local function resetAllSetButtonSelection()
local setButtons = setGui.SetPanel.Sets.SetsLists:GetChildren()
for i = 1, #setButtons do
if setButtons[i]:IsA("TextButton") then
setButtons[i].Selected = false
setButtons[i].BackgroundTransparency = 1
setButtons[i].TextColor3 = Color3.new(1,1,1)
setButtons[i].BackgroundColor3 = Color3.new(1,1,1)
end
end
end
local function populateSetsFrame()
local currRow = 0
for i = 1, #userCategoryButtons do
local button = userCategoryButtons[i]
button.Visible = true
button.Position = UDim2.new(0,5,0,currRow * button.Size.Y.Offset)
button.Parent = setGui.SetPanel.Sets.SetsLists
if i == 1 then -- we will have this selected by default, so show it
button.Selected = true
button.BackgroundColor3 = Color3.new(0,204/255,0)
button.TextColor3 = Color3.new(0,0,0)
button.BackgroundTransparency = 0
end
button.MouseEnter:connect(function()
if not button.Selected then
button.BackgroundTransparency = 0
button.TextColor3 = Color3.new(0,0,0)
end
end)
button.MouseLeave:connect(function()
if not button.Selected then
button.BackgroundTransparency = 1
button.TextColor3 = Color3.new(1,1,1)
end
end)
button.MouseButton1Click:connect(function()
resetAllSetButtonSelection()
button.Selected = not button.Selected
button.BackgroundColor3 = Color3.new(0,204/255,0)
button.TextColor3 = Color3.new(0,0,0)
button.BackgroundTransparency = 0
selectSet(button, button.Text, userCategoryButtons[i].SetId.Value, 0)
end)
currRow = currRow + 1
end
local buttons = setGui.SetPanel.Sets.SetsLists:GetChildren()
-- set first category as loaded for default
if buttons then
for i = 1, #buttons do
if buttons[i]:IsA("TextButton") then
selectSet(buttons[i], buttons[i].Text, userCategoryButtons[i].SetId.Value, 0)
selectCategory(userCategoryButtons)
break
end
end
end
end
setGui = createSetGui()
waterGui, waterTypeChangedEvent = createWaterGui()
waterGui.Position = UDim2.new(0,55,0,0)
waterGui.Parent = setGui
setGui.Changed:connect(function(prop) -- this resizes the preview image to always be the right size
if prop == "AbsoluteSize" then
handleResize()
setSetIndex()
end
end)
local scrollFrame, controlFrame = t.CreateTrueScrollingFrame()
scrollFrame.Size = UDim2.new(0.54,0,0.85,0)
scrollFrame.Position = UDim2.new(0.24,0,0.085,0)
scrollFrame.Name = "ItemsFrame"
scrollFrame.ZIndex = 6
scrollFrame.Parent = setGui.SetPanel
scrollFrame.BackgroundTransparency = 1
drillDownSetZIndex(controlFrame,7)
controlFrame.Parent = setGui.SetPanel
controlFrame.Position = UDim2.new(0.76, 5, 0, 0)
local debounce = false
controlFrame.ScrollBottom.Changed:connect(function(prop)
if controlFrame.ScrollBottom.Value == true then
if debounce then return end
debounce = true
loadSectionOfItems(setGui, rows, columns)
debounce = false
end
end)
local userData = {}
for id = 1, #userIdsForSets do
local newUserData = game:GetService("InsertService"):GetUserSets(userIdsForSets[id])
if newUserData and #newUserData > 2 then
-- start at #3 to skip over My Decals and My Models for each account
for category = 3, #newUserData do
if newUserData[category].Name == "High Scalability" then -- we want high scalability parts to show first
table.insert(userData,1,newUserData[category])
else
table.insert(userData, newUserData[category])
end
end
end
end
if userData then
userCategoryButtons = processCategory(userData)
end
rows = math.floor(setGui.SetPanel.ItemsFrame.AbsoluteSize.Y/buttonHeight)
columns = math.floor(setGui.SetPanel.ItemsFrame.AbsoluteSize.X/buttonWidth)
populateSetsFrame()
setGui.SetPanel.CancelButton.MouseButton1Click:connect(function()
setGui.SetPanel.Visible = false
if dialogClosed then dialogClosed() end
end)
local setVisibilityFunction = function(visible)
if visible then
setGui.SetPanel.Visible = true
else
setGui.SetPanel.Visible = false
end
end
local getVisibilityFunction = function()
if setGui then
if setGui:FindFirstChild("SetPanel") then
return setGui.SetPanel.Visible
end
end
return false
end
return setGui, setVisibilityFunction, getVisibilityFunction, waterTypeChangedEvent
end
t.CreateTerrainMaterialSelector = function(size,position)
local terrainMaterialSelectionChanged = Instance.new("BindableEvent")
terrainMaterialSelectionChanged.Name = "TerrainMaterialSelectionChanged"
local selectedButton = nil
local frame = Instance.new("Frame")
frame.Name = "TerrainMaterialSelector"
if size then
frame.Size = size
else
frame.Size = UDim2.new(0, 245, 0, 230)
end
if position then
frame.Position = position
end
frame.BorderSizePixel = 0
frame.BackgroundColor3 = Color3.new(0,0,0)
frame.Active = true
terrainMaterialSelectionChanged.Parent = frame
local waterEnabled = true -- todo: turn this on when water is ready
local materialToImageMap = {}
local materialNames = {"Grass", "Sand", "Brick", "Granite", "Asphalt", "Iron", "Aluminum", "Gold", "Plank", "Log", "Gravel", "Cinder Block", "Stone Wall", "Concrete", "Plastic (red)", "Plastic (blue)"}
if waterEnabled then
table.insert(materialNames,"Water")
end
local currentMaterial = 1
function getEnumFromName(choice)
if choice == "Grass" then return 1 end
if choice == "Sand" then return 2 end
if choice == "Erase" then return 0 end
if choice == "Brick" then return 3 end
if choice == "Granite" then return 4 end
if choice == "Asphalt" then return 5 end
if choice == "Iron" then return 6 end
if choice == "Aluminum" then return 7 end
if choice == "Gold" then return 8 end
if choice == "Plank" then return 9 end
if choice == "Log" then return 10 end
if choice == "Gravel" then return 11 end
if choice == "Cinder Block" then return 12 end
if choice == "Stone Wall" then return 13 end
if choice == "Concrete" then return 14 end
if choice == "Plastic (red)" then return 15 end
if choice == "Plastic (blue)" then return 16 end
if choice == "Water" then return 17 end
end
function getNameFromEnum(choice)
if choice == Enum.CellMaterial.Grass or choice == 1 then return "Grass"end
if choice == Enum.CellMaterial.Sand or choice == 2 then return "Sand" end
if choice == Enum.CellMaterial.Empty or choice == 0 then return "Erase" end
if choice == Enum.CellMaterial.Brick or choice == 3 then return "Brick" end
if choice == Enum.CellMaterial.Granite or choice == 4 then return "Granite" end
if choice == Enum.CellMaterial.Asphalt or choice == 5 then return "Asphalt" end
if choice == Enum.CellMaterial.Iron or choice == 6 then return "Iron" end
if choice == Enum.CellMaterial.Aluminum or choice == 7 then return "Aluminum" end
if choice == Enum.CellMaterial.Gold or choice == 8 then return "Gold" end
if choice == Enum.CellMaterial.WoodPlank or choice == 9 then return "Plank" end
if choice == Enum.CellMaterial.WoodLog or choice == 10 then return "Log" end
if choice == Enum.CellMaterial.Gravel or choice == 11 then return "Gravel" end
if choice == Enum.CellMaterial.CinderBlock or choice == 12 then return "Cinder Block" end
if choice == Enum.CellMaterial.MossyStone or choice == 13 then return "Stone Wall" end
if choice == Enum.CellMaterial.Cement or choice == 14 then return "Concrete" end
if choice == Enum.CellMaterial.RedPlastic or choice == 15 then return "Plastic (red)" end
if choice == Enum.CellMaterial.BluePlastic or choice == 16 then return "Plastic (blue)" end
if waterEnabled then
if choice == Enum.CellMaterial.Water or choice == 17 then return "Water" end
end
end
local function updateMaterialChoice(choice)
currentMaterial = getEnumFromName(choice)
terrainMaterialSelectionChanged:Fire(currentMaterial)
end
-- we so need a better way to do this
for i,v in pairs(materialNames) do
materialToImageMap[v] = {}
if v == "Grass" then materialToImageMap[v].Regular = "https://www.roblox.com/asset/?id=56563112"
elseif v == "Sand" then materialToImageMap[v].Regular = "https://www.roblox.com/asset/?id=62356652"
elseif v == "Brick" then materialToImageMap[v].Regular = "https://www.roblox.com/asset/?id=65961537"
elseif v == "Granite" then materialToImageMap[v].Regular = "https://www.roblox.com/asset/?id=67532153"
elseif v == "Asphalt" then materialToImageMap[v].Regular = "https://www.roblox.com/asset/?id=67532038"
elseif v == "Iron" then materialToImageMap[v].Regular = "https://www.roblox.com/asset/?id=67532093"
elseif v == "Aluminum" then materialToImageMap[v].Regular = "https://www.roblox.com/asset/?id=67531995"
elseif v == "Gold" then materialToImageMap[v].Regular = "https://www.roblox.com/asset/?id=67532118"
elseif v == "Plastic (red)" then materialToImageMap[v].Regular = "https://www.roblox.com/asset/?id=67531848"
elseif v == "Plastic (blue)" then materialToImageMap[v].Regular = "https://www.roblox.com/asset/?id=67531924"
elseif v == "Plank" then materialToImageMap[v].Regular = "https://www.roblox.com/asset/?id=67532015"
elseif v == "Log" then materialToImageMap[v].Regular = "https://www.roblox.com/asset/?id=67532051"
elseif v == "Gravel" then materialToImageMap[v].Regular = "https://www.roblox.com/asset/?id=67532206"
elseif v == "Cinder Block" then materialToImageMap[v].Regular = "https://www.roblox.com/asset/?id=67532103"
elseif v == "Stone Wall" then materialToImageMap[v].Regular = "https://www.roblox.com/asset/?id=67531804"
elseif v == "Concrete" then materialToImageMap[v].Regular = "https://www.roblox.com/asset/?id=67532059"
elseif v == "Water" then materialToImageMap[v].Regular = "https://www.roblox.com/asset/?id=81407474"
else materialToImageMap[v].Regular = "https://www.roblox.com/asset/?id=66887593" -- fill in the rest here!!
end
end
local scrollFrame, scrollUp, scrollDown, recalculateScroll = t.CreateScrollingFrame(nil,"grid")
scrollFrame.Size = UDim2.new(0.85,0,1,0)
scrollFrame.Position = UDim2.new(0,0,0,0)
scrollFrame.Parent = frame
scrollUp.Parent = frame
scrollUp.Visible = true
scrollUp.Position = UDim2.new(1,-19,0,0)
scrollDown.Parent = frame
scrollDown.Visible = true
scrollDown.Position = UDim2.new(1,-19,1,-17)
local function goToNewMaterial(buttonWrap, materialName)
updateMaterialChoice(materialName)
buttonWrap.BackgroundTransparency = 0
selectedButton.BackgroundTransparency = 1
selectedButton = buttonWrap
end
local function createMaterialButton(name)
local buttonWrap = Instance.new("TextButton")
buttonWrap.Text = ""
buttonWrap.Size = UDim2.new(0,32,0,32)
buttonWrap.BackgroundColor3 = Color3.new(1,1,1)
buttonWrap.BorderSizePixel = 0
buttonWrap.BackgroundTransparency = 1
buttonWrap.AutoButtonColor = false
buttonWrap.Name = tostring(name)
local imageButton = Instance.new("ImageButton")
imageButton.AutoButtonColor = false
imageButton.BackgroundTransparency = 1
imageButton.Size = UDim2.new(0,30,0,30)
imageButton.Position = UDim2.new(0,1,0,1)
imageButton.Name = tostring(name)
imageButton.Parent = buttonWrap
imageButton.Image = materialToImageMap[name].Regular
local enumType = Instance.new("NumberValue")
enumType.Name = "EnumType"
enumType.Parent = buttonWrap
enumType.Value = 0
imageButton.MouseEnter:connect(function()
buttonWrap.BackgroundTransparency = 0
end)
imageButton.MouseLeave:connect(function()
if selectedButton ~= buttonWrap then
buttonWrap.BackgroundTransparency = 1
end
end)
imageButton.MouseButton1Click:connect(function()
if selectedButton ~= buttonWrap then
goToNewMaterial(buttonWrap, tostring(name))
end
end)
return buttonWrap
end
for i = 1, #materialNames do
local imageButton = createMaterialButton(materialNames[i])
if materialNames[i] == "Grass" then -- always start with grass as the default
selectedButton = imageButton
imageButton.BackgroundTransparency = 0
end
imageButton.Parent = scrollFrame
end
local forceTerrainMaterialSelection = function(newMaterialType)
if not newMaterialType then return end
if currentMaterial == newMaterialType then return end
local matName = getNameFromEnum(newMaterialType)
local buttons = scrollFrame:GetChildren()
for i = 1, #buttons do
if buttons[i].Name == "Plastic (blue)" and matName == "Plastic (blue)" then goToNewMaterial(buttons[i],matName) return end
if buttons[i].Name == "Plastic (red)" and matName == "Plastic (red)" then goToNewMaterial(buttons[i],matName) return end
if string.find(buttons[i].Name, matName) then
goToNewMaterial(buttons[i],matName)
return
end
end
end
frame.Changed:connect(function ( prop )
if prop == "AbsoluteSize" then
recalculateScroll()
end
end)
recalculateScroll()
return frame, terrainMaterialSelectionChanged, forceTerrainMaterialSelection
end
t.CreateLoadingFrame = function(name,size,position)
game:GetService("ContentProvider"):Preload("https://www.roblox.com/asset/?id=35238053")
local loadingFrame = Instance.new("Frame")
loadingFrame.Name = "LoadingFrame"
loadingFrame.Style = Enum.FrameStyle.RobloxRound
if size then loadingFrame.Size = size
else loadingFrame.Size = UDim2.new(0,300,0,160) end
if position then loadingFrame.Position = position
else loadingFrame.Position = UDim2.new(0.5, -150, 0.5,-80) end
local loadingBar = Instance.new("Frame")
loadingBar.Name = "LoadingBar"
loadingBar.BackgroundColor3 = Color3.new(0,0,0)
loadingBar.BorderColor3 = Color3.new(79/255,79/255,79/255)
loadingBar.Position = UDim2.new(0,0,0,41)
loadingBar.Size = UDim2.new(1,0,0,30)
loadingBar.Parent = loadingFrame
local loadingGreenBar = Instance.new("ImageLabel")
loadingGreenBar.Name = "LoadingGreenBar"
loadingGreenBar.Image = "https://www.roblox.com/asset/?id=35238053"
loadingGreenBar.Position = UDim2.new(0,0,0,0)
loadingGreenBar.Size = UDim2.new(0,0,1,0)
loadingGreenBar.Visible = false
loadingGreenBar.Parent = loadingBar
local loadingPercent = Instance.new("TextLabel")
loadingPercent.Name = "LoadingPercent"
loadingPercent.BackgroundTransparency = 1
loadingPercent.Position = UDim2.new(0,0,1,0)
loadingPercent.Size = UDim2.new(1,0,0,14)
loadingPercent.Font = Enum.Font.Arial
loadingPercent.Text = "0%"
loadingPercent.FontSize = Enum.FontSize.Size14
loadingPercent.TextColor3 = Color3.new(1,1,1)
loadingPercent.Parent = loadingBar
local cancelButton = Instance.new("TextButton")
cancelButton.Name = "CancelButton"
cancelButton.Position = UDim2.new(0.5,-60,1,-40)
cancelButton.Size = UDim2.new(0,120,0,40)
cancelButton.Font = Enum.Font.Arial
cancelButton.FontSize = Enum.FontSize.Size18
cancelButton.TextColor3 = Color3.new(1,1,1)
cancelButton.Text = "Cancel"
cancelButton.Style = Enum.ButtonStyle.RobloxButton
cancelButton.Parent = loadingFrame
local loadingName = Instance.new("TextLabel")
loadingName.Name = "loadingName"
loadingName.BackgroundTransparency = 1
loadingName.Size = UDim2.new(1,0,0,18)
loadingName.Position = UDim2.new(0,0,0,2)
loadingName.Font = Enum.Font.Arial
loadingName.Text = name
loadingName.TextColor3 = Color3.new(1,1,1)
loadingName.TextStrokeTransparency = 1
loadingName.FontSize = Enum.FontSize.Size18
loadingName.Parent = loadingFrame
local cancelButtonClicked = Instance.new("BindableEvent")
cancelButtonClicked.Name = "CancelButtonClicked"
cancelButtonClicked.Parent = cancelButton
cancelButton.MouseButton1Click:connect(function()
cancelButtonClicked:Fire()
end)
local updateLoadingGuiPercent = function(percent, tweenAction, tweenLength)
if percent and type(percent) ~= "number" then
error("updateLoadingGuiPercent expects number as argument, got",type(percent),"instead")
end
local newSize = nil
if percent < 0 then
newSize = UDim2.new(0,0,1,0)
elseif percent > 1 then
newSize = UDim2.new(1,0,1,0)
else
newSize = UDim2.new(percent,0,1,0)
end
if tweenAction then
if not tweenLength then
error("updateLoadingGuiPercent is set to tween new percentage, but got no tween time length! Please pass this in as third argument")
end
if (newSize.X.Scale > 0) then
loadingGreenBar.Visible = true
loadingGreenBar:TweenSize( newSize,
Enum.EasingDirection.Out,
Enum.EasingStyle.Quad,
tweenLength,
true)
else
loadingGreenBar:TweenSize( newSize,
Enum.EasingDirection.Out,
Enum.EasingStyle.Quad,
tweenLength,
true,
function()
if (newSize.X.Scale < 0) then
loadingGreenBar.Visible = false
end
end)
end
else
loadingGreenBar.Size = newSize
loadingGreenBar.Visible = (newSize.X.Scale > 0)
end
end
loadingGreenBar.Changed:connect(function(prop)
if prop == "Size" then
loadingPercent.Text = tostring( math.ceil(loadingGreenBar.Size.X.Scale * 100) ) .. "%"
end
end)
return loadingFrame, updateLoadingGuiPercent, cancelButtonClicked
end
t.CreatePluginFrame = function (name,size,position,scrollable,parent)
local function createMenuButton(size,position,text,fontsize,name,parent)
local button = Instance.new("TextButton",parent)
button.AutoButtonColor = false
button.Name = name
button.BackgroundTransparency = 1
button.Position = position
button.Size = size
button.Font = Enum.Font.ArialBold
button.FontSize = fontsize
button.Text = text
button.TextColor3 = Color3.new(1,1,1)
button.BorderSizePixel = 0
button.BackgroundColor3 = Color3.new(20/255,20/255,20/255)
button.MouseEnter:connect(function ( )
if button.Selected then return end
button.BackgroundTransparency = 0
end)
button.MouseLeave:connect(function ( )
if button.Selected then return end
button.BackgroundTransparency = 1
end)
return button
end
local dragBar = Instance.new("Frame",parent)
dragBar.Name = tostring(name) .. "DragBar"
dragBar.BackgroundColor3 = Color3.new(39/255,39/255,39/255)
dragBar.BorderColor3 = Color3.new(0,0,0)
if size then
dragBar.Size = UDim2.new(size.X.Scale,size.X.Offset,0,20) + UDim2.new(0,20,0,0)
else
dragBar.Size = UDim2.new(0,183,0,20)
end
if position then
dragBar.Position = position
end
dragBar.Active = true
dragBar.Draggable = true
--dragBar.Visible = false
dragBar.MouseEnter:connect(function ( )
dragBar.BackgroundColor3 = Color3.new(49/255,49/255,49/255)
end)
dragBar.MouseLeave:connect(function ( )
dragBar.BackgroundColor3 = Color3.new(39/255,39/255,39/255)
end)
-- plugin name label
local pluginNameLabel = Instance.new("TextLabel",dragBar)
pluginNameLabel.Name = "BarNameLabel"
pluginNameLabel.Text = " " .. tostring(name)
pluginNameLabel.TextColor3 = Color3.new(1,1,1)
pluginNameLabel.TextStrokeTransparency = 0
pluginNameLabel.Size = UDim2.new(1,0,1,0)
pluginNameLabel.Font = Enum.Font.ArialBold
pluginNameLabel.FontSize = Enum.FontSize.Size18
pluginNameLabel.TextXAlignment = Enum.TextXAlignment.Left
pluginNameLabel.BackgroundTransparency = 1
-- close button
local closeButton = createMenuButton(UDim2.new(0,15,0,17),UDim2.new(1,-16,0.5,-8),"X",Enum.FontSize.Size14,"CloseButton",dragBar)
local closeEvent = Instance.new("BindableEvent")
closeEvent.Name = "CloseEvent"
closeEvent.Parent = closeButton
closeButton.MouseButton1Click:connect(function ()
closeEvent:Fire()
closeButton.BackgroundTransparency = 1
end)
-- help button
local helpButton = createMenuButton(UDim2.new(0,15,0,17),UDim2.new(1,-51,0.5,-8),"?",Enum.FontSize.Size14,"HelpButton",dragBar)
local helpFrame = Instance.new("Frame",dragBar)
helpFrame.Name = "HelpFrame"
helpFrame.BackgroundColor3 = Color3.new(0,0,0)
helpFrame.Size = UDim2.new(0,300,0,552)
helpFrame.Position = UDim2.new(1,5,0,0)
helpFrame.Active = true
helpFrame.BorderSizePixel = 0
helpFrame.Visible = false
helpButton.MouseButton1Click:connect(function( )
helpFrame.Visible = not helpFrame.Visible
if helpFrame.Visible then
helpButton.Selected = true
helpButton.BackgroundTransparency = 0
local screenGui = getLayerCollectorAncestor(helpFrame)
if screenGui then
if helpFrame.AbsolutePosition.X + helpFrame.AbsoluteSize.X > screenGui.AbsoluteSize.X then --position on left hand side
helpFrame.Position = UDim2.new(0,-5 - helpFrame.AbsoluteSize.X,0,0)
else -- position on right hand side
helpFrame.Position = UDim2.new(1,5,0,0)
end
else
helpFrame.Position = UDim2.new(1,5,0,0)
end
else
helpButton.Selected = false
helpButton.BackgroundTransparency = 1
end
end)
local minimizeButton = createMenuButton(UDim2.new(0,16,0,17),UDim2.new(1,-34,0.5,-8),"-",Enum.FontSize.Size14,"MinimizeButton",dragBar)
minimizeButton.TextYAlignment = Enum.TextYAlignment.Top
local minimizeFrame = Instance.new("Frame",dragBar)
minimizeFrame.Name = "MinimizeFrame"
minimizeFrame.BackgroundColor3 = Color3.new(73/255,73/255,73/255)
minimizeFrame.BorderColor3 = Color3.new(0,0,0)
minimizeFrame.Position = UDim2.new(0,0,1,0)
if size then
minimizeFrame.Size = UDim2.new(size.X.Scale,size.X.Offset,0,50) + UDim2.new(0,20,0,0)
else
minimizeFrame.Size = UDim2.new(0,183,0,50)
end
minimizeFrame.Visible = false
local minimizeBigButton = Instance.new("TextButton",minimizeFrame)
minimizeBigButton.Position = UDim2.new(0.5,-50,0.5,-20)
minimizeBigButton.Name = "MinimizeButton"
minimizeBigButton.Size = UDim2.new(0,100,0,40)
minimizeBigButton.Style = Enum.ButtonStyle.RobloxButton
minimizeBigButton.Font = Enum.Font.ArialBold
minimizeBigButton.FontSize = Enum.FontSize.Size18
minimizeBigButton.TextColor3 = Color3.new(1,1,1)
minimizeBigButton.Text = "Show"
local separatingLine = Instance.new("Frame",dragBar)
separatingLine.Name = "SeparatingLine"
separatingLine.BackgroundColor3 = Color3.new(115/255,115/255,115/255)
separatingLine.BorderSizePixel = 0
separatingLine.Position = UDim2.new(1,-18,0.5,-7)
separatingLine.Size = UDim2.new(0,1,0,14)
local otherSeparatingLine = separatingLine:clone()
otherSeparatingLine.Position = UDim2.new(1,-35,0.5,-7)
otherSeparatingLine.Parent = dragBar
local widgetContainer = Instance.new("Frame",dragBar)
widgetContainer.Name = "WidgetContainer"
widgetContainer.BackgroundTransparency = 1
widgetContainer.Position = UDim2.new(0,0,1,0)
widgetContainer.BorderColor3 = Color3.new(0,0,0)
if not scrollable then
widgetContainer.BackgroundTransparency = 0
widgetContainer.BackgroundColor3 = Color3.new(72/255,72/255,72/255)
end
if size then
if scrollable then
widgetContainer.Size = size
else
widgetContainer.Size = UDim2.new(0,dragBar.AbsoluteSize.X,size.Y.Scale,size.Y.Offset)
end
else
if scrollable then
widgetContainer.Size = UDim2.new(0,163,0,400)
else
widgetContainer.Size = UDim2.new(0,dragBar.AbsoluteSize.X,0,400)
end
end
if position then
widgetContainer.Position = position + UDim2.new(0,0,0,20)
end
local frame,control,verticalDragger = nil
if scrollable then
--frame for widgets
frame,control = t.CreateTrueScrollingFrame()
frame.Size = UDim2.new(1, 0, 1, 0)
frame.BackgroundColor3 = Color3.new(72/255,72/255,72/255)
frame.BorderColor3 = Color3.new(0,0,0)
frame.Active = true
frame.Parent = widgetContainer
control.Parent = dragBar
control.BackgroundColor3 = Color3.new(72/255,72/255,72/255)
control.BorderSizePixel = 0
control.BackgroundTransparency = 0
control.Position = UDim2.new(1,-21,1,1)
if size then
control.Size = UDim2.new(0,21,size.Y.Scale,size.Y.Offset)
else
control.Size = UDim2.new(0,21,0,400)
end
control:FindFirstChild("ScrollDownButton").Position = UDim2.new(0,0,1,-20)
local fakeLine = Instance.new("Frame",control)
fakeLine.Name = "FakeLine"
fakeLine.BorderSizePixel = 0
fakeLine.BackgroundColor3 = Color3.new(0,0,0)
fakeLine.Size = UDim2.new(0,1,1,1)
fakeLine.Position = UDim2.new(1,0,0,0)
verticalDragger = Instance.new("TextButton",widgetContainer)
verticalDragger.ZIndex = 2
verticalDragger.AutoButtonColor = false
verticalDragger.Name = "VerticalDragger"
verticalDragger.BackgroundColor3 = Color3.new(50/255,50/255,50/255)
verticalDragger.BorderColor3 = Color3.new(0,0,0)
verticalDragger.Size = UDim2.new(1,20,0,20)
verticalDragger.Position = UDim2.new(0,0,1,0)
verticalDragger.Active = true
verticalDragger.Text = ""
local scrubFrame = Instance.new("Frame",verticalDragger)
scrubFrame.Name = "ScrubFrame"
scrubFrame.BackgroundColor3 = Color3.new(1,1,1)
scrubFrame.BorderSizePixel = 0
scrubFrame.Position = UDim2.new(0.5,-5,0.5,0)
scrubFrame.Size = UDim2.new(0,10,0,1)
scrubFrame.ZIndex = 5
local scrubTwo = scrubFrame:clone()
scrubTwo.Position = UDim2.new(0.5,-5,0.5,-2)
scrubTwo.Parent = verticalDragger
local scrubThree = scrubFrame:clone()
scrubThree.Position = UDim2.new(0.5,-5,0.5,2)
scrubThree.Parent = verticalDragger
local areaSoak = Instance.new("TextButton",getLayerCollectorAncestor(parent))
areaSoak.Name = "AreaSoak"
areaSoak.Size = UDim2.new(1,0,1,0)
areaSoak.BackgroundTransparency = 1
areaSoak.BorderSizePixel = 0
areaSoak.Text = ""
areaSoak.ZIndex = 10
areaSoak.Visible = false
areaSoak.Active = true
local draggingVertical = false
local startYPos = nil
verticalDragger.MouseEnter:connect(function ()
verticalDragger.BackgroundColor3 = Color3.new(60/255,60/255,60/255)
end)
verticalDragger.MouseLeave:connect(function ()
verticalDragger.BackgroundColor3 = Color3.new(50/255,50/255,50/255)
end)
verticalDragger.MouseButton1Down:connect(function(x,y)
draggingVertical = true
areaSoak.Visible = true
startYPos = y
end)
areaSoak.MouseButton1Up:connect(function ( )
draggingVertical = false
areaSoak.Visible = false
end)
areaSoak.MouseMoved:connect(function(x,y)
if not draggingVertical then return end
local yDelta = y - startYPos
if not control.ScrollDownButton.Visible and yDelta > 0 then
return
end
if (widgetContainer.Size.Y.Offset + yDelta) < 150 then
widgetContainer.Size = UDim2.new(widgetContainer.Size.X.Scale, widgetContainer.Size.X.Offset,widgetContainer.Size.Y.Scale,150)
control.Size = UDim2.new (0,21,0,150)
return
end
startYPos = y
if widgetContainer.Size.Y.Offset + yDelta >= 0 then
widgetContainer.Size = UDim2.new(widgetContainer.Size.X.Scale, widgetContainer.Size.X.Offset,widgetContainer.Size.Y.Scale,widgetContainer.Size.Y.Offset + yDelta)
control.Size = UDim2.new(0,21,0,control.Size.Y.Offset + yDelta )
end
end)
end
local function switchMinimize()
minimizeFrame.Visible = not minimizeFrame.Visible
if scrollable then
frame.Visible = not frame.Visible
verticalDragger.Visible = not verticalDragger.Visible
control.Visible = not control.Visible
else
widgetContainer.Visible = not widgetContainer.Visible
end
if minimizeFrame.Visible then
minimizeButton.Text = "+"
else
minimizeButton.Text = "-"
end
end
minimizeBigButton.MouseButton1Click:connect(function ( )
switchMinimize()
end)
minimizeButton.MouseButton1Click:connect(function( )
switchMinimize()
end)
if scrollable then
return dragBar, frame, helpFrame, closeEvent
else
return dragBar, widgetContainer, helpFrame, closeEvent
end
end
t.Help =
function(funcNameOrFunc)
--input argument can be a string or a function. Should return a description (of arguments and expected side effects)
if funcNameOrFunc == "CreatePropertyDropDownMenu" or funcNameOrFunc == t.CreatePropertyDropDownMenu then
return "Function CreatePropertyDropDownMenu. " ..
"Arguments: (instance, propertyName, enumType). " ..
"Side effect: returns a container with a drop-down-box that is linked to the 'property' field of 'instance' which is of type 'enumType'"
end
if funcNameOrFunc == "CreateDropDownMenu" or funcNameOrFunc == t.CreateDropDownMenu then
return "Function CreateDropDownMenu. " ..
"Arguments: (items, onItemSelected). " ..
"Side effect: Returns 2 results, a container to the gui object and a 'updateSelection' function for external updating. The container is a drop-down-box created around a list of items"
end
if funcNameOrFunc == "CreateMessageDialog" or funcNameOrFunc == t.CreateMessageDialog then
return "Function CreateMessageDialog. " ..
"Arguments: (title, message, buttons). " ..
"Side effect: Returns a gui object of a message box with 'title' and 'message' as passed in. 'buttons' input is an array of Tables contains a 'Text' and 'Function' field for the text/callback of each button"
end
if funcNameOrFunc == "CreateStyledMessageDialog" or funcNameOrFunc == t.CreateStyledMessageDialog then
return "Function CreateStyledMessageDialog. " ..
"Arguments: (title, message, style, buttons). " ..
"Side effect: Returns a gui object of a message box with 'title' and 'message' as passed in. 'buttons' input is an array of Tables contains a 'Text' and 'Function' field for the text/callback of each button, 'style' is a string, either Error, Notify or Confirm"
end
if funcNameOrFunc == "GetFontHeight" or funcNameOrFunc == t.GetFontHeight then
return "Function GetFontHeight. " ..
"Arguments: (font, fontSize). " ..
"Side effect: returns the size in pixels of the given font + fontSize"
end
if funcNameOrFunc == "LayoutGuiObjects" or funcNameOrFunc == t.LayoutGuiObjects then
end
if funcNameOrFunc == "CreateScrollingFrame" or funcNameOrFunc == t.CreateScrollingFrame then
return "Function CreateScrollingFrame. " ..
"Arguments: (orderList, style) " ..
"Side effect: returns 4 objects, (scrollFrame, scrollUpButton, scrollDownButton, recalculateFunction). 'scrollFrame' can be filled with GuiObjects. It will lay them out and allow scrollUpButton/scrollDownButton to interact with them. Orderlist is optional (and specifies the order to layout the children. Without orderlist, it uses the children order. style is also optional, and allows for a 'grid' styling if style is passed 'grid' as a string. recalculateFunction can be called when a relayout is needed (when orderList changes)"
end
if funcNameOrFunc == "CreateTrueScrollingFrame" or funcNameOrFunc == t.CreateTrueScrollingFrame then
return "Function CreateTrueScrollingFrame. " ..
"Arguments: (nil) " ..
"Side effect: returns 2 objects, (scrollFrame, controlFrame). 'scrollFrame' can be filled with GuiObjects, and they will be clipped if not inside the frame's bounds. controlFrame has children scrollup and scrolldown, as well as a slider. controlFrame can be parented to any guiobject and it will readjust itself to fit."
end
if funcNameOrFunc == "AutoTruncateTextObject" or funcNameOrFunc == t.AutoTruncateTextObject then
return "Function AutoTruncateTextObject. " ..
"Arguments: (textLabel) " ..
"Side effect: returns 2 objects, (textLabel, changeText). The 'textLabel' input is modified to automatically truncate text (with ellipsis), if it gets too small to fit. 'changeText' is a function that can be used to change the text, it takes 1 string as an argument"
end
if funcNameOrFunc == "CreateSlider" or funcNameOrFunc == t.CreateSlider then
return "Function CreateSlider. " ..
"Arguments: (steps, width, position) " ..
"Side effect: returns 2 objects, (sliderGui, sliderPosition). The 'steps' argument specifies how many different positions the slider can hold along the bar. 'width' specifies in pixels how wide the bar should be (modifiable afterwards if desired). 'position' argument should be a UDim2 for slider positioning. 'sliderPosition' is an IntValue whose current .Value specifies the specific step the slider is currently on."
end
if funcNameOrFunc == "CreateSliderNew" or funcNameOrFunc == t.CreateSliderNew then
return "Function CreateSliderNew. " ..
"Arguments: (steps, width, position) " ..
"Side effect: returns 2 objects, (sliderGui, sliderPosition). The 'steps' argument specifies how many different positions the slider can hold along the bar. 'width' specifies in pixels how wide the bar should be (modifiable afterwards if desired). 'position' argument should be a UDim2 for slider positioning. 'sliderPosition' is an IntValue whose current .Value specifies the specific step the slider is currently on."
end
if funcNameOrFunc == "CreateLoadingFrame" or funcNameOrFunc == t.CreateLoadingFrame then
return "Function CreateLoadingFrame. " ..
"Arguments: (name, size, position) " ..
"Side effect: Creates a gui that can be manipulated to show progress for a particular action. Name appears above the loading bar, and size and position are udim2 values (both size and position are optional arguments). Returns 3 arguments, the first being the gui created. The second being updateLoadingGuiPercent, which is a bindable function. This function takes one argument (two optionally), which should be a number between 0 and 1, representing the percentage the loading gui should be at. The second argument to this function is a boolean value that if set to true will tween the current percentage value to the new percentage value, therefore our third argument is how long this tween should take. Our third returned argument is a BindableEvent, that when fired means that someone clicked the cancel button on the dialog."
end
if funcNameOrFunc == "CreateTerrainMaterialSelector" or funcNameOrFunc == t.CreateTerrainMaterialSelector then
return "Function CreateTerrainMaterialSelector. " ..
"Arguments: (size, position) " ..
"Side effect: Size and position are UDim2 values that specifies the selector's size and position. Both size and position are optional arguments. This method returns 3 objects (terrainSelectorGui, terrainSelected, forceTerrainSelection). terrainSelectorGui is just the gui object that we generate with this function, parent it as you like. TerrainSelected is a BindableEvent that is fired whenever a new terrain type is selected in the gui. ForceTerrainSelection is a function that takes an argument of Enum.CellMaterial and will force the gui to show that material as currently selected."
end
end
return t
|
--[[
Infinite Chest for Minetest
Copyright (c) 2012 cornernote, Brett O'Donnell <[email protected]>
Source Code: https://github.com/cornernote/minetest-infinite_chest
License: BSD-3-Clause https://raw.github.com/cornernote/minetest-infinite_chest/master/LICENSE
API
]]--
infinite_chest = {}
infinite_chest.log = function(message)
minetest.log("action", message)
end
infinite_chest.formspec = function(pos,page)
local formspec = "size[15,11]"
.."button[12,10;1,0.5;go;Go]"
if page=="main" then
local meta = minetest.env:get_meta(pos)
local pages = infinite_chest.get_pages(meta)
local x,y = 0,0
local p
for i = #pages,1,-1 do
p = pages[i]
x = x+2
if x == 16 then
y = y+1
x = 2
end
formspec = formspec .."button["..(x-1.5)..","..(y+1)..";1.5,0.5;jump;"..p.."]"
end
if #pages == 0 then
formspec = formspec
.."label[4,3; --== Infinite Chest ==--]"
.."label[4,4.5; Create as many inventory slots as you like!]"
.."label[4,5.0; Simply enter a name for your inventory slot]"
.."label[4,5.5; then click Go.]"
end
return formspec
.."field[10.5,10.1;2,1;page;;]"
.."label[0,0;Infinite Chest]"
end
return formspec
.."field[10.5,10.1;2,1;page;;"..page.."]"
.."label[0,0;Infinite Chest - page: " .. page .. "]"
.."button[13,10;2,0.5;back;Back]"
.."button[13,6.5;2,0.5;delete;Delete]"
.."list[current_name;"..page..";0,1;15,5;]"
.."list[current_player;main;0,7;8,4;]"
end
infinite_chest.get_pages = function(meta)
local invs = meta:get_string("infinite_chest_list")
local pages = {}
for p in string.gmatch(invs, "[^%s]+") do
table.insert(pages,p)
end
return pages
end
infinite_chest.add_page = function(pos,page)
local meta = minetest.env:get_meta(pos)
local invs = meta:get_string("infinite_chest_list")
local pages = {}
for p in string.gmatch(invs, "[^%s]+") do
if page ~= p then
table.insert(pages,p)
end
end
table.insert(pages,page)
invs = ""
for i,p in pairs(pages) do
invs = invs .." ".. p
end
meta:set_string("infinite_chest_list",invs)
meta:get_inventory():set_size(page, 15*5)
end
infinite_chest.remove_page = function(pos,page)
local meta = minetest.env:get_meta(pos)
local invs = meta:get_string("infinite_chest_list")
local inv = meta:get_inventory()
if not inv:is_empty(page) then
return
end
local pages = {}
for p in string.gmatch(invs, "[^%s]+") do
if page ~= p then
table.insert(pages,p)
end
end
invs = ""
for i,p in pairs(pages) do
invs = invs .." ".. p
end
meta:set_string("infinite_chest_list",invs)
return true
end
infinite_chest.on_receive_fields = function(pos, formname, fields, sender)
local meta = minetest.env:get_meta(pos)
local page
if fields.go ~= nil and fields.page ~= "" then
page = string.lower(string.gsub(fields.page, "%W", "_"))
end
if fields.jump ~= nil then
page = fields.jump
end
if page ~= nil then
infinite_chest.add_page(pos,page)
meta:set_string("formspec", infinite_chest.formspec(pos,page))
return
end
if fields.delete ~= nil then
if not infinite_chest.remove_page(pos,fields.page) then
minetest.chat_send_player(sender:get_player_name(), "cannot delete \""..fields.page.."\" - page is not empty")
return
end
end
meta:set_string("formspec", infinite_chest.formspec(pos,"main"))
end
infinite_chest.on_construct = function(pos)
local meta = minetest.env:get_meta(pos)
meta:set_string("formspec", infinite_chest.formspec(pos,"main"))
meta:set_string("infotext", "Infinite Chest")
end
infinite_chest.can_dig = function(pos,player)
local meta = minetest.env:get_meta(pos);
local pages = infinite_chest.get_pages(meta)
local inv = meta:get_inventory()
for i,page in pairs(pages) do
if not inv:is_empty(page) then
minetest.chat_send_player(player:get_player_name(), "cannot dig - page \""..page.."\" is not empty")
return false
end
end
return true
end
infinite_chest.after_place_node = function(pos, placer)
local meta = minetest.env:get_meta(pos)
meta:set_string("owner", placer:get_player_name() or "")
meta:set_string("infotext", "Locked Infinite Chest (owned by "..meta:get_string("owner")..")")
end
infinite_chest.allow_metadata_inventory_move = function(pos, from_list, from_index, to_list, to_index, count, player)
local meta = minetest.env:get_meta(pos)
if not infinite_chest.has_locked_chest_privilege(meta, player) then
infinite_chest.log(player:get_player_name().." tried to access a locked chest belonging to "..meta:get_string("owner").." at "..minetest.pos_to_string(pos))
return 0
end
return count
end
infinite_chest.allow_metadata_inventory_put = function(pos, listname, index, stack, player)
local meta = minetest.env:get_meta(pos)
if not infinite_chest.has_locked_chest_privilege(meta, player) then
infinite_chest.log(player:get_player_name().." tried to access a locked chest belonging to "..meta:get_string("owner").." at "..minetest.pos_to_string(pos))
return 0
end
return stack:get_count()
end
infinite_chest.allow_metadata_inventory_take = function(pos, listname, index, stack, player)
local meta = minetest.env:get_meta(pos)
if not infinite_chest.has_locked_chest_privilege(meta, player) then
infinite_chest.log(player:get_player_name()..
" tried to access a locked chest belonging to "..
meta:get_string("owner").." at "..
minetest.pos_to_string(pos))
return 0
end
return stack:get_count()
end
infinite_chest.has_locked_chest_privilege = function(meta, player)
if meta:get_string("owner") ~= "" and player:get_player_name() ~= meta:get_string("owner") then
return false
end
return true
end
infinite_chest.on_metadata_inventory_move = function(pos, from_list, from_index, to_list, to_index, count, player)
infinite_chest.log(player:get_player_name().." moves stuff in infinite chest at "..minetest.pos_to_string(pos))
end
infinite_chest.on_metadata_inventory_put = function(pos, listname, index, stack, player)
infinite_chest.log(player:get_player_name().." moves stuff to infinite chest at "..minetest.pos_to_string(pos))
end
infinite_chest.on_metadata_inventory_take = function(pos, listname, index, stack, player)
infinite_chest.log(player:get_player_name().." takes stuff from infinite chest at "..minetest.pos_to_string(pos))
end
|
addEvent('onRaceStateChanging', true)
addEventHandler('onRaceStateChanging', getRootElement(),
function(state)
local mode = getResourceRootElement(getResourceFromName'race') and getElementData(getResourceRootElement(getResourceFromName'race'), 'info') and getElementData(getResourceRootElement(getResourceFromName'race'), 'info').mapInfo.modename
if mode == "Destruction derby" then
triggerClientEvent('informClientAntiMinimize', resourceRoot, state == "Running")
end
end
) |
local npairs = require("nvim-autopairs")
local set_keymap = vim.api.nvim_set_keymap
npairs.setup()
_G.MUtils= {}
vim.g.completion_confirm_key = ""
MUtils.completion_confirm = function()
if vim.fn.pumvisible() ~= 0 then
if vim.fn.complete_info()["selected"] ~= -1 then
return vim.fn["compe#confirm"](npairs.esc("<cr>"))
else
return npairs.esc("<cr>")
end
else
return npairs.autopairs_cr()
end
end
-- Key mappings
local opts = { expr = true, noremap = true }
set_keymap("i", "<cr>", "v:lua.MUtils.completion_confirm()", opts)
|
object_tangible_item_beast_converted_kliknik_decoration = object_tangible_item_beast_shared_converted_kliknik_decoration:new {
}
ObjectTemplates:addTemplate(object_tangible_item_beast_converted_kliknik_decoration, "object/tangible/item/beast/converted_kliknik_decoration.iff")
|
--local cjson = require('cjson')
local f = io.open("mblog.dat")
box.cfg{}
s = box.schema.space.create("bench", {engine="ws"})
s:create_index('a1')
local line_nu = 0;
data = {"a"}
--box.space.bench:insert({1}, {233, 2342})
offset = 0
lines = {}
for line in f:lines() do
line_nu = line_nu + 1
-- json = cjson.decode(line)
-- lines[line_nu] = json
lines[line_nu] = line
offset = offset + #line
--box.space.bench:insert{line_nu, json}
if line_nu % 10000 == 0 then
print("read line: "..line_nu)
end
if line_nu == 100000 then
break
end
end
print("total line: "..line_nu)
count = 0
local start_time = os.time()
for k, v in pairs(lines) do
count = count + 1
if count % 10000 == 0 then
print("insert line: "..count)
end
box.space.bench:insert{k, v}
end
print("insert line: "..line_nu)
local end_time = os.time()
print("bench over")
print("used time: "..start_time-end_time.."s")
os.exit(0)
|
local AddonName, AddonTable = ...
AddonTable.mechagon = {
-- King Gobbamak
169050, -- Logg
169035, -- Reclaimed Shock Coil
169052, -- Cranial Recalibrator
169054, -- Galvanized Leather Grips
169051, -- Anodized Plate Legguards
169053, -- Roughshod Chain Boots
169049, -- Supplicant's Soiled Slippers
-- Gunker
169058, -- Salvaged Incendiary Tool
169062, -- Sharpened Trogg Femur
169061, -- Insulating Threaded Gloves
169059, -- Slick Tactical Grips
169060, -- Mekgineer's Utility Belt
169057, -- Well-Oiled Plate Girdle
169055, -- Greaves of Acid Resistance
169056, -- Ooey-Gooey Galoshes
-- Trixie & Naeno
169066, -- Trixie's Backup Backbiter
169068, -- Salvaged Mekacycle Shielding
169064, -- Mountebank's Colorful Cloak
169069, -- Wraps of Electrostatic Potential
169063, -- High Speed Gauntlets
169067, -- Silken Safety Harness
169065, -- Reinforced Riding Chausses
169070, -- Unseen Predator's Breeches
169769, -- Remote Guidance Device
-- HK-8 Aerial Oppression Unit
168657, -- Friend-or-Foe Identifier
167677, -- Harmonic Dematerializer
168826, -- Mechagon Peacekeeper [Mount]
168909, -- Subroutine: Emergency Repairs
168963, -- Fusion Hacker
169077, -- Light Auto-Stabilizing Energy Rifle
169074, -- Epaulettes of Arcing Power
169075, -- Tank Buster Pauldrons
169073, -- Type II Bomber Jacket
169072, -- Volatile Arming Doublet
169071, -- Overcharged Pantaloons
169157, -- Logic Loop of Division
169076, -- Logic Loop of Maintenance
169158, -- Logic Loop of Recursion
169156, -- Logic Loop of Synergy
-- Tussle Tonks
168962, -- Apex Perforator
168955, -- Electrifying Cognitive Amplifier
168967, -- Gold-Coated Superconductors
168957, -- Mekgineer's Championship Belt
168958, -- Ringmaster's Cummerbund
168966, -- Heavy Alloy Legplates
168964, -- Hyperthreaded Boots
168965, -- Modular Platinum Plating
-- K.U.-J.O.
168970, -- Trashmaster's Mantle
168969, -- Operator's Mitts
168971, -- Swift Pneumatic Grips
168968, -- Flame-Seared Leggings
168972, -- Pyroclastic Greatboots
-- Machinist's Garden
167556, -- Subroutine: Overclock
168973, -- Neural Synapse Enhancer
169608, -- Tearing Sawtooth Blade
168976, -- Automatic Waist Tightener
168974, -- Self-Repairing Cuisses
168975, -- Machinist's Treasured Treads
169159, -- Overclocking Bit Band
169161, -- Protecting Bit Band
168977, -- Rebooting Bit Band
169160, -- Shorting Bit Band
169344, -- Ingenious Mana Battery
-- King Mechagon
169172, -- Blueprint: Perfectly Timed Differential
168671, -- Electromagnetic Resistors
168842, -- Engine of Mecha-Perfection
169378, -- Golden Snorf
169774, -- Progression Sprocket
168984, -- Extravagant Epaulettes
168987, -- Shoulderguards of Fraying Sanity
168981, -- Circuit-Linked Chainmail
168979, -- Mechanized Plate Chasse
168978, -- Anodized Deflectors
168989, -- Hyperthread Wristwraps
168980, -- Gauntlets of Absolute Authority
168985, -- Self-Sanitizing Handwraps
168986, -- Mad King's Sporran
168983, -- Maniacal Monarch's Girdle
168988, -- Royal Attendant's Trousers
168982, -- Regal Mekanospurs
-- Multiple
170510, -- Forceful Logic Board
170509, -- Performant Logic Board
170508, -- Optimized Logic Board
170507, -- Omnipurpose Logic Board
}
|
include("shared.lua")
local frame = nil
function CreateFrame()
if !frame or !frame:IsValid() then
local self = net.ReadEntity()
local Map = game.GetMap() or ""
if Map:find("gm_metrostroi") and Map:find("lite") then
Map = "gm_metrostroi_lite"
elseif Map:find("gm_metrostroi") then
Map = "gm_metrostroi"
elseif Map:find("gm_mus_orange_line") and Map:find("long") then
Map = "gm_orange"
elseif Map:find("gm_mus_orange_line") then
Map = "gm_orange_lite"
end
frame = vgui.Create("DFrame")
frame:SetDeleteOnClose(true)
frame:SetTitle("Dispatch control")
--frame:SetSize(275, 34+24*17)
frame:SetDraggable(false)
frame:SetSizable(false)
frame:MakePopup()
frame:SetSize(ScrW()-40,ScrH()-40)
frame:Center()
local StationChoose = vgui.Create( "DComboBox",frame )
StationChoose:SetPos( 5, 30 )
StationChoose:SetSize( 250, 20 )
StationChoose:SetValue( "Choose station" )
for k,v in pairs(Metrostroi.WorkingStations[Map][1]) do
if Metrostroi.AnnouncerData[v] then StationChoose:AddChoice(Metrostroi.AnnouncerData[v][1]) end
end
local PlayerChoose = vgui.Create( "DComboBox",frame )
PlayerChoose:SetPos( ScrW()-300,30 )
PlayerChoose:SetSize( 250, 20 )
PlayerChoose:SetValue( "Choose player" )
for i = 1,20 do
PlayerChoose:AddChoice(i)
end
local Main = vgui.Create( "DPanel",frame )
Main:SetPos(0,60)
Main:SetSize(frame:GetWide(),frame:GetTall()-60)
Main.Paint = function(self,w,h)
surface.DrawRect(5, 0, w-10, h-5)
end
end
end
function ENT:Initialize()
end
net.Receive("TrackController",CreateFrame) |
-------------------------------------
-- 查看装备等级 Author: M
-------------------------------------
local LibEvent = LibStub:GetLibrary("LibEvent.7000")
local LibItemInfo = LibStub:GetLibrary("LibItemInfo.7000")
local E = unpack(ElvUI)
--裝備清單
local slots = {
{ index = 1, name = HEADSLOT, },
{ index = 2, name = NECKSLOT, },
{ index = 3, name = SHOULDERSLOT, },
{ index = 5, name = CHESTSLOT, },
{ index = 6, name = WAISTSLOT, },
{ index = 7, name = LEGSSLOT, },
{ index = 8, name = FEETSLOT, },
{ index = 9, name = WRISTSLOT, },
{ index = 10, name = HANDSSLOT, },
{ index = 11, name = FINGER0SLOT, },
{ index = 12, name = FINGER1SLOT, },
{ index = 13, name = TRINKET0SLOT, },
{ index = 14, name = TRINKET1SLOT, },
{ index = 15, name = BACKSLOT, },
{ index = 16, name = MAINHANDSLOT, },
{ index = 17, name = SECONDARYHANDSLOT, },
}
--創建面板
local function GetInspectItemListFrame(parent)
if (not parent.inspectFrame) then
local itemfont = "ChatFontNormal"
local frame = CreateFrame("Frame", nil, parent)
local height = parent:GetHeight()
if (height < 424) then
height = 424
end
frame.backdrop = {
bgFile = "Interface\\Tooltips\\UI-Tooltip-Background",
edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
tile = true,
tileSize = 8,
edgeSize = 16,
insets = {left = 4, right = 4, top = 4, bottom = 4}
}
frame:SetSize(160, height)
frame:SetFrameLevel(0)
frame:SetPoint("TOPLEFT", parent, "TOPRIGHT", 0, 0)
frame:SetBackdrop(frame.backdrop)
frame:SetBackdropColor(0, 0, 0, 0.8)
frame:SetBackdropBorderColor(0.6, 0.6, 0.6)
frame.portrait = CreateFrame("Button", nil, frame, "GarrisonFollowerPortraitTemplate")
frame.portrait:SetPoint("TOPLEFT", frame, "TOPLEFT", 18, -16)
frame.portrait:SetScale(0.8)
frame.portrait:RegisterForClicks('AnyDown')
frame.portrait:SetScript("OnClick", function(self)
InspectDB.green = not InspectDB.green
if InspectDB.green then
frame.green:SetText('绿')
E:Print("开启绿字显示,重载/rl 后生效!");
else
frame.green:SetText('')
E:Print("关闭绿字显示,重载/rl 后生效!");
end
end)
frame.title = frame:CreateFontString(nil, "ARTWORK", "GameFontNormalLargeOutline")
frame.title:SetPoint("TOPLEFT", frame, "TOPLEFT", 66, -18)
frame.level = frame:CreateFontString(nil, "ARTWORK", itemfont)
frame.level:SetPoint("TOPLEFT", frame, "TOPLEFT", 66, -42)
frame.level:SetFont(frame.level:GetFont(), 14, "THINOUTLINE")
frame.green = frame:CreateFontString(nil, "ARTWORK", itemfont)
frame.green:SetPoint("LEFT", frame.level, "RIGHT", 4, 0)
frame.green:SetFont(UNIT_NAME_FONT, 12, "NORMAL")
frame.green:SetTextColor(0, 0.9, 0.1)
local itemframe
local fontsize = GetLocale():sub(1,2) == "zh" and 12 or 9
local backdrop = {
bgFile = "Interface\\Tooltips\\UI-Tooltip-Background",
edgeFile = "Interface\\Buttons\\WHITE8X8",
tile = true,
tileSize = 8,
edgeSize = 1,
insets = {left = 1, right = 1, top = 1, bottom = 1}
}
for i, v in ipairs(slots) do
itemframe = CreateFrame("Button", nil, frame)
itemframe:SetSize(120, (height-82)/#slots)
itemframe.index = v.index
itemframe.backdrop = backdrop
if (i == 1) then
itemframe:SetPoint("TOPLEFT", frame, "TOPLEFT", 15, -70)
else
itemframe:SetPoint("TOPLEFT", frame["item"..(i-1)], "BOTTOMLEFT")
end
itemframe.label = CreateFrame("Frame", nil, itemframe)
itemframe.label:SetSize(38, 16)
itemframe.label:SetPoint("LEFT")
itemframe.label:SetBackdrop(backdrop)
itemframe.label:SetBackdropBorderColor(0, 0.9, 0.9, 0.2)
itemframe.label:SetBackdropColor(0, 0.9, 0.9, 0.2)
itemframe.label.text = itemframe.label:CreateFontString(nil, "ARTWORK")
itemframe.label.text:SetFont(UNIT_NAME_FONT, fontsize, "THINOUTLINE")
itemframe.label.text:SetSize(34, 14)
itemframe.label.text:SetPoint("CENTER", 1, 0)
itemframe.label.text:SetText(v.name)
itemframe.label.text:SetTextColor(0, 0.9, 0.9)
itemframe.levelString = itemframe:CreateFontString(nil, "ARTWORK", itemfont)
itemframe.levelString:SetPoint("LEFT", itemframe.label, "RIGHT", 4, 0)
itemframe.levelString:SetJustifyH("RIGHT")
itemframe.itemString = itemframe:CreateFontString(nil, "ARTWORK", itemfont)
itemframe.itemString:SetHeight(16)
itemframe.itemString:SetPoint("LEFT", itemframe.levelString, "RIGHT", 2, 0)
itemframe:SetScript("OnEnter", function(self)
local r, g, b, a = self.label:GetBackdropColor()
self.label:SetBackdropColor(r, g, b, a+0.5)
if (self.link or (self.level and self.level > 0)) then
GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
GameTooltip:SetInventoryItem(self:GetParent().unit, self.index)
GameTooltip:Show()
end
end)
itemframe:SetScript("OnLeave", function(self)
local r, g, b, a = self.label:GetBackdropColor()
self.label:SetBackdropColor(r, g, b, abs(a-0.5))
GameTooltip:Hide()
end)
itemframe:SetScript("OnDoubleClick", function(self)
if (self.link) then
ChatEdit_ActivateChat(ChatEdit_ChooseBoxForSend())
ChatEdit_InsertLink(self.link)
end
end)
frame["item"..i] = itemframe
LibEvent:trigger("INSPECT_ITEMFRAME_CREATED", itemframe)
end
frame.closeButton = CreateFrame("Button", nil, frame)
frame.closeButton:SetSize(12, 12)
frame.closeButton:SetScale(0.85)
frame.closeButton:SetPoint("BOTTOMLEFT", 5, 6)
frame.closeButton:SetNormalTexture("Interface\\Cursor\\Item")
frame.closeButton:GetNormalTexture():SetTexCoord(0, 12/32, 12/32, 0)
frame.closeButton:SetScript("OnClick", function(self)
self:GetParent():Hide()
end)
parent:HookScript("OnHide", function(self) frame:Hide() end)
parent.inspectFrame = frame
LibEvent:trigger("INSPECT_FRAME_CREATED", frame, parent)
end
return parent.inspectFrame
end
--等級字符
local ItemLevelPattern = gsub(ITEM_LEVEL, "%%d", "%%d")
--顯示面板
function ShowInspectItemListFrame(unit, parent, ilevel, maxLevel)
if (not parent:IsShown()) then return end
local frame = GetInspectItemListFrame(parent)
local class = select(2, UnitClass(unit))
local color = RAID_CLASS_COLORS[class] or NORMAL_FONT_COLOR
frame.unit = unit
frame.portrait:SetLevel(UnitLevel(unit))
frame.portrait.PortraitRingQuality:SetVertexColor(color.r, color.g, color.b)
frame.portrait.LevelBorder:SetVertexColor(color.r, color.g, color.b)
SetPortraitTexture(frame.portrait.Portrait, unit)
frame.title:SetText(UnitName(unit))
frame.title:SetTextColor(color.r, color.g, color.b)
if InspectDB.green then
frame.green:SetText('绿')
else
frame.green:SetText('')
end
frame.level:SetText(format(ItemLevelPattern, ilevel))
frame.level:SetTextColor(1, 0.82, 0)
local _, name, level, link, quality
local itemframe, mframe, oframe, itemwidth
local width = 160
local formats = "%3s"
if (maxLevel) then
formats = "%" .. string.len(floor(maxLevel)) .. "s"
end
for i, v in ipairs(slots) do
_, level, name, link, quality = LibItemInfo:GetUnitItemInfo(unit, v.index)
itemframe = frame["item"..i]
itemframe.name = name
itemframe.link = link
itemframe.level = level
itemframe.quality = quality
itemframe.itemString:SetWidth(0)
if (level > 0) then
itemframe.levelString:SetText(format(formats,level))
itemframe.itemString:SetText(link or name)
else
itemframe.levelString:SetText(format(formats,""))
itemframe.itemString:SetText("")
end
itemwidth = itemframe.itemString:GetWidth()
if (itemwidth > 208) then
itemwidth = 208
itemframe.itemString:SetWidth(itemwidth)
end
itemframe.width = itemwidth + max(64, floor(itemframe.label:GetWidth() + itemframe.levelString:GetWidth()) + 4)
itemframe:SetWidth(itemframe.width)
if (width < itemframe.width) then
width = itemframe.width
end
if (v.index == 16) then
mframe = itemframe
mframe:SetAlpha(1)
elseif (v.index == 17) then
oframe = itemframe
oframe:SetAlpha(1)
end
LibEvent:trigger("INSPECT_ITEMFRAME_UPDATED", itemframe)
end
if (mframe and oframe and (mframe.quality == 6 or oframe.quality == 6)) then
level = max(mframe.level, oframe.level)
if mframe.link then
mframe.levelString:SetText(format(formats,level))
end
if oframe.link then
oframe.levelString:SetText(format(formats,level))
end
end
if (mframe and mframe.level <= 0) then
mframe:SetAlpha(0.4)
end
if (oframe and oframe.level <= 0) then
oframe:SetAlpha(0.4)
end
frame:SetWidth(width + 36)
frame:Show()
LibEvent:trigger("INSPECT_FRAME_SHOWN", frame, parent, ilevel)
frame:SetBackdrop(frame.backdrop)
frame:SetBackdropColor(0, 0, 0, 0.9)
-- frame:SetBackdropBorderColor(color.r, color.g, color.b)
frame:SetTemplate('Default')
return frame
end
--裝備變更時
LibEvent:attachEvent("UNIT_INVENTORY_CHANGED", function(self, unit)
if (InspectFrame and InspectFrame.unit and InspectFrame.unit == unit) then
ReInspect(unit)
end
end)
--@see InspectCore.lua
LibEvent:attachTrigger("UNIT_INSPECT_READY, UNIT_REINSPECT_READY", function(self, data)
if (InspectFrame and InspectFrame.unit and UnitGUID(InspectFrame.unit) == data.guid) then
local frame = ShowInspectItemListFrame(InspectFrame.unit, InspectFrame, data.ilevel, data.maxLevel)
LibEvent:trigger("INSPECT_FRAME_COMPARE", frame)
end
end)
--設置邊框
LibEvent:attachTrigger("INSPECT_FRAME_SHOWN", function(self, frame, parent, ilevel)
frame.backdrop.edgeSize = 2
frame.backdrop.edgeFile = "Interface\\Buttons\\WHITE8X8"
frame.backdrop.insets.top = 2
frame.backdrop.insets.left = 2
frame.backdrop.insets.right = 2
frame.backdrop.insets.bottom = 2
frame:SetPoint("TOPLEFT", parent, "TOPRIGHT", 4, 0)
end)
--高亮橙裝和武器
LibEvent:attachTrigger("INSPECT_ITEMFRAME_UPDATED", function(self, itemframe)
local r, g, b = 0, 0.9, 0.9
if (itemframe.quality and itemframe.quality > 4) then
r, g, b = GetItemQualityColor(itemframe.quality)
elseif (itemframe.name and not itemframe.link) then
r, g, b = 0.9, 0.8, 0.4
elseif (not itemframe.link) then
r, g, b = 0.5, 0.5, 0.5
end
itemframe.label:SetBackdropBorderColor(r, g, b, 0.2)
itemframe.label:SetBackdropColor(r, g, b, 0.2)
itemframe.label.text:SetTextColor(r, g, b)
end)
--自己裝備列表
LibEvent:attachTrigger("INSPECT_FRAME_COMPARE", function(self, frame)
if (not frame) then return end
local _, ilevel, _, _, _, maxLevel = LibItemInfo:GetUnitItemLevel("player")
local playerFrame = ShowInspectItemListFrame("player", frame, ilevel, maxLevel)
if (frame.statsFrame) then
frame.statsFrame:SetParent(playerFrame)
frame.statsFrame:SetPoint("TOPLEFT", playerFrame, "TOPRIGHT", 0, -1)
end
end)
----------------
-- Player --
----------------
PaperDollFrame:HookScript("OnShow", function(self)
if (E and not E.db.euiscript.ShowCharacterItemSheet) then return end
local _, ilevel, _, _, _, maxLevel = LibItemInfo:GetUnitItemLevel("player")
ShowInspectItemListFrame("player", self, ilevel, maxLevel)
end)
LibEvent:attachEvent("PLAYER_EQUIPMENT_CHANGED", function(self)
if (CharacterFrame:IsShown() and E and E.db.euiscript.ShowCharacterItemSheet) then
local _, ilevel, _, _, _, maxLevel = LibItemInfo:GetUnitItemLevel("player")
ShowInspectItemListFrame("player", PaperDollFrame, ilevel, maxLevel)
end
end)
|
local _, private = ...
-- RealUI --
local RealUI = private.RealUI
local MODNAME = "Chat"
local Chat = RealUI:NewModule(MODNAME, "AceEvent-3.0")
-- TODO: consolidate this module
function Chat:PLAYER_LOGIN()
-- Hide IM selector if BCM is enabled
if _G.IsAddOnLoaded("BasicChatMods") then
_G["InterfaceOptionsSocialPanelChatStyle"]:Hide()
end
end
function Chat:OnInitialize()
self.db = RealUI.db:RegisterNamespace(MODNAME)
self.db:RegisterDefaults({
profile = {
modules = {
["**"] = {
enabled = true,
},
tabs = {
colors = {
classcolorhighlight = true,
["normal"] = {1, 1, 1},
["highlight"] = {1, 1, 1},
["flash"] = {1, 1, 0},
},
},
opacity = {},
strings = {},
history = {
[RealUI.charInfo.realm] = {history = {}},
},
},
},
})
self:SetEnabledState(RealUI:GetModuleEnabled(MODNAME))
end
function Chat:OnEnable()
self:debug("OnEnable")
self:RegisterEvent("PLAYER_LOGIN")
local start, stop = 3, 8
for i = 1, _G.NUM_CHAT_WINDOWS do
local editbox = _G["ChatFrame"..i.."EditBox"]
for k = start, stop do
local tex = _G.select(k, editbox:GetRegions())
if tex:GetObjectType() == "Texture" then
tex:SetTexture("")
end
end
end
end
|
-----------------------------------------
-- Stratus Cell
-- ID 5369
-- Unlocks leg and feet equipment
-----------------------------------------
require("scripts/globals/status")
-----------------------------------------
function onItemCheck(target)
local encumbrance = target:getStatusEffect(tpz.effect.ENCUMBRANCE_I)
if (encumbrance) then
local power = encumbrance:getPower()
if bit.band(power, 0x0180) > 0 then
return 0
end
end
return -1
end
function onItemUse(target)
local encumbrance = target:getStatusEffect(tpz.effect.ENCUMBRANCE_I)
local power = encumbrance:getPower()
local newpower = bit.band(power, bit.bnot(0x0180))
target:delStatusEffectSilent(tpz.effect.ENCUMBRANCE_I)
if (newpower > 0) then
target:addStatusEffectEx(tpz.effect.ENCUMBRANCE_I, tpz.effect.ENCUMBRANCE_I, newpower, 0, 0)
end
target:messageText(target, zones[target:getZoneID()].text.CELL_OFFSET + 4)
end |
-- 这个脚本是在初始化snlua服务的时候,在接口init_cb (service-src/service_snlua)中调用的
-- 这个脚本的全局变量也都是在 init_cb (service-src/service_snlua) 中设置的
local args = {}
for word in string.gmatch(..., "%S+") do
table.insert(args, word)
end
-- 按config/examples 中配置, SERVICE_NAME值就是 bootstrap
-- 在脚本中使用skynet.launch("snlua","launcher")调用的时候,这个地方SERVICE_NAME就是launcher
SERVICE_NAME = args[1]
local main, pattern
-- LUA_SERVICE 在examples/config.path配置,默认值就是
-- ./service/?.lua;./test/?.lua;./examples/?.lua;./test/?/init.lua
-- 也就是说从目录 service/ test/ examples/ /tes/name/init.lua 找相应的lua服务对应的lua文件
-- 直到找到为止
local err = {}
for pat in string.gmatch(LUA_SERVICE, "([^;]+);*") do
local filename = string.gsub(pat, "?", SERVICE_NAME)
-- 按 config/examples 配置 对于bootstrap服务,这里的filename就是 比如serivce/bootstrap.lua
local f, msg = loadfile(filename)
if not f then
table.insert(err, msg)
else
pattern = pat
main = f
break
end
end
-- 按 config/examples 配置,到这里 pattern 就是 service/?.lua,
-- main就是 比如serivce/bootstrap.lua loadfile返回的结果
if not main then
error(table.concat(err, "\n"))
end
-- 下面都是准备环境,为执行比如serivce/bootstrap.lua做准备
LUA_SERVICE = nil
-- 把 LUA_PATH 的值赋值给package.path,同时赋值 LUA_PATH 为nil
-- 上面执行后,按examples/config.pat配置
-- package.path就是./lualib/?.lua;./lualib/?/init.lua
-- path.cpath 就是 /luaclib/?.so
package.path , LUA_PATH = LUA_PATH
package.cpath , LUA_CPATH = LUA_CPATH
local service_path = string.match(pattern, "(.*/)[^/?]+$")
if service_path then
service_path = string.gsub(service_path, "?", args[1])
package.path = service_path .. "?.lua;" .. package.path
SERVICE_PATH = service_path
else
-- 默认执行到这个分支,执行完成后,SERVICE_PATH的值为 serivce/
local p = string.match(pattern, "(.*/).+$")
SERVICE_PATH = p
end
-- 执行 examples/config 中的的 preload 配置
if LUA_PRELOAD then
local f = assert(loadfile(LUA_PRELOAD))
f(table.unpack(args))
LUA_PRELOAD = nil
end
-- 比如执行service/bootstrap.lua
main(select(2, table.unpack(args)))
|
--[[
-- Copyright(c) 2019, 武汉舜立软件 All Rights Reserved
-- Created: 2019/04/16
--
-- @file check_arping.lua
-- @brief 对网卡做 arping
-- @version 0.1
-- @author 李绍良
-- @history 修改历史
-- \n 2019/04/16 0.1 创建文件
-- @warning 没有警告
--]]
local string = require("string")
local io = require("io")
local unix = require("base.unix")
local l_sys = require("l_sys")
local sh = l_sys.sh
local arping = function (name, ip)
-- arping 格式: arping -I eth0 -c 3 192.168.1.247
local cmd = string.format('arping -I %s -c 3 %s', name, ip)
local ret, str = sh(cmd)
print('arping cmd:'..cmd, ret, str)
end
local check_arping = function ()
local ifs = unix.get_ifconfig()
for k, v in pairs(ifs) do
local name = v['name']
local ipv4 = v['ipv4']
arping(name, ipv4)
end
end
return check_arping
|
---@param skillLineID number
---[Documentation](https://wow.gamepedia.com/API_AbandonSkill)
function AbandonSkill(skillLineID) end
---[Documentation](https://wow.gamepedia.com/API_AcceptAreaSpiritHeal)
function AcceptAreaSpiritHeal() end
---@param index number
---@param accept boolean
---[Documentation](https://wow.gamepedia.com/API_AcceptBattlefieldPort)
function AcceptBattlefieldPort(index, accept) end
---[Documentation](https://wow.gamepedia.com/API_AcceptDuel)
function AcceptDuel() end
---[Documentation](https://wow.gamepedia.com/API_AcceptGroup)
function AcceptGroup() end
---[Documentation](https://wow.gamepedia.com/API_AcceptGuild)
function AcceptGuild() end
---[Documentation](https://wow.gamepedia.com/API_AcceptProposal)
function AcceptProposal() end
---[Documentation](https://wow.gamepedia.com/API_AcceptQuest)
function AcceptQuest() end
---[Documentation](https://wow.gamepedia.com/API_AcceptResurrect)
function AcceptResurrect() end
---[Documentation](https://wow.gamepedia.com/API_AcceptSockets)
function AcceptSockets() end
---@param spellID number
---[Documentation](https://wow.gamepedia.com/API_AcceptSpellConfirmationPrompt)
function AcceptSpellConfirmationPrompt(spellID) end
---[Documentation](https://wow.gamepedia.com/API_AcceptTrade)
function AcceptTrade() end
---[Documentation](https://wow.gamepedia.com/API_AcceptXPLoss)
function AcceptXPLoss() end
---[Documentation](https://wow.gamepedia.com/API_AcknowledgeAutoAcceptQuest)
function AcknowledgeAutoAcceptQuest() end
---[Documentation](https://wow.gamepedia.com/API_AcknowledgeSurvey)
function AcknowledgeSurvey(caseIndex) end
---[Documentation](https://wow.gamepedia.com/API_ActionBindsItem)
function ActionBindsItem() end
---@param slotID number
---@return boolean hasRange
---[Documentation](https://wow.gamepedia.com/API_ActionHasRange)
function ActionHasRange(slotID) end
---@param questID number
---@param type string
---[Documentation](https://wow.gamepedia.com/API_AddAutoQuestPopUp)
function AddAutoQuestPopUp(questID, type) end
---@param windowId number
---@param channelName string
---[Documentation](https://wow.gamepedia.com/API_AddChatWindowChannel)
function AddChatWindowChannel(windowId, channelName) end
---@param index number
---@param messageGroup string
---[Documentation](https://wow.gamepedia.com/API_AddChatWindowMessages)
function AddChatWindowMessages(index, messageGroup) end
---@param achievementID number
---[Documentation](https://wow.gamepedia.com/API_AddTrackedAchievement)
function AddTrackedAchievement(achievementID) end
---[Documentation](https://wow.gamepedia.com/API_AddTradeMoney)
function AddTradeMoney() end
---@param fullName string
---@param context string
---@return string name
---[Documentation](https://wow.gamepedia.com/API_Ambiguate)
function Ambiguate(fullName, context) end
---[Documentation](https://wow.gamepedia.com/API_AntiAliasingSupported)
function AntiAliasingSupported() end
---[Documentation](https://wow.gamepedia.com/API_ApplyBarberShopStyle)
function ApplyBarberShopStyle() end
---[Documentation](https://wow.gamepedia.com/API_ArchaeologyGetIconInfo)
function ArchaeologyGetIconInfo(index) end
---@return number numSites
---[Documentation](https://wow.gamepedia.com/API_ArchaeologyMapUpdateAll)
function ArchaeologyMapUpdateAll() end
---[Documentation](https://wow.gamepedia.com/API_ArcheologyGetVisibleBlobID)
function ArcheologyGetVisibleBlobID(index) end
---@return boolean hidden
---[Documentation](https://wow.gamepedia.com/API_AreAccountAchievementsHidden)
function AreAccountAchievementsHidden() end
---[Documentation](https://wow.gamepedia.com/API_AreDangerousScriptsAllowed)
function AreDangerousScriptsAllowed() end
---[Documentation](https://wow.gamepedia.com/API_AreTalentsLocked)
function AreTalentsLocked() end
---[Documentation](https://wow.gamepedia.com/API_AscendStop)
function AscendStop() end
---@param unit string
---[Documentation](https://wow.gamepedia.com/API_AssistUnit)
function AssistUnit(unit) end
---[Documentation](https://wow.gamepedia.com/API_AttachGlyphToSpell)
function AttachGlyphToSpell(spellID) end
---[Documentation](https://wow.gamepedia.com/API_AttackTarget)
function AttackTarget() end
---[Documentation](https://wow.gamepedia.com/API_AutoChooseCurrentGraphicsSetting)
function AutoChooseCurrentGraphicsSetting() end
---[Documentation](https://wow.gamepedia.com/API_AutoEquipCursorItem)
function AutoEquipCursorItem() end
---[Documentation](https://wow.gamepedia.com/API_AutoLootMailItem)
function AutoLootMailItem(index) end
---@param tab number
---@param slot number
---[Documentation](https://wow.gamepedia.com/API_AutoStoreGuildBankItem)
function AutoStoreGuildBankItem(tab, slot) end
---[Documentation](https://wow.gamepedia.com/API_BNAcceptFriendInvite)
function BNAcceptFriendInvite(ID) end
---[Documentation](https://wow.gamepedia.com/API_BNCheckBattleTagInviteToGuildMember)
function BNCheckBattleTagInviteToGuildMember(fullname) end
---[Documentation](https://wow.gamepedia.com/API_BNCheckBattleTagInviteToUnit)
function BNCheckBattleTagInviteToUnit(unit) end
---@return boolean connected
---[Documentation](https://wow.gamepedia.com/API_BNConnected)
function BNConnected() end
---[Documentation](https://wow.gamepedia.com/API_BNDeclineFriendInvite)
function BNDeclineFriendInvite(ID) end
---[Documentation](https://wow.gamepedia.com/API_BNFeaturesEnabled)
function BNFeaturesEnabled() end
---[Documentation](https://wow.gamepedia.com/API_BNFeaturesEnabledAndConnected)
function BNFeaturesEnabledAndConnected() end
---[Documentation](https://wow.gamepedia.com/API_BNGetBlockedInfo)
function BNGetBlockedInfo(index) end
---[Documentation](https://wow.gamepedia.com/API_BNGetDisplayName)
function BNGetDisplayName(bnetIdAccount) end
---@param mutual boolean
---@param nonMutual boolean
---@param index number
---@return number friendID
---@return string accountName
---@return boolean isMutual
---[Documentation](https://wow.gamepedia.com/API_BNGetFOFInfo)
function BNGetFOFInfo(mutual, nonMutual, index) end
---@param presenceID number
---@return number index
---[Documentation](https://wow.gamepedia.com/API_BNGetFriendIndex)
function BNGetFriendIndex(presenceID) end
---@param inviteIndex number
---@return number inviteID
---@return number accountName
---@return boolean isBattleTag
---@return unknown unknown
---@return number sentTime
---[Documentation](https://wow.gamepedia.com/API_BNGetFriendInviteInfo)
function BNGetFriendInviteInfo(inviteIndex) end
---@return number presenceID
---@return string battleTag
---@return number toonID
---@return string currentBroadcast
---@return boolean bnetAFK
---@return boolean bnetDND
---@return boolean isRIDEnabled
---[Documentation](https://wow.gamepedia.com/API_BNGetInfo)
function BNGetInfo() end
---[Documentation](https://wow.gamepedia.com/API_BNGetNumBlocked)
function BNGetNumBlocked() end
---[Documentation](https://wow.gamepedia.com/API_BNGetNumFOF)
function BNGetNumFOF(ID, mutual, non) end
---[Documentation](https://wow.gamepedia.com/API_BNGetNumFriendInvites)
function BNGetNumFriendInvites() end
---@return number numBNetTotal
---@return number numBNetOnline
---@return number numBNetFavorite
---@return number numBNetFavoriteOnline
---[Documentation](https://wow.gamepedia.com/API_BNGetNumFriends)
function BNGetNumFriends() end
---[Documentation](https://wow.gamepedia.com/API_BNGetSelectedBlock)
function BNGetSelectedBlock() end
---[Documentation](https://wow.gamepedia.com/API_BNGetSelectedFriend)
function BNGetSelectedFriend() end
---[Documentation](https://wow.gamepedia.com/API_BNInviteFriend)
function BNInviteFriend(bnetIDGameAccount) end
---[Documentation](https://wow.gamepedia.com/API_BNIsBlocked)
function BNIsBlocked(ID) end
---[Documentation](https://wow.gamepedia.com/API_BNIsFriend)
function BNIsFriend(presenceID) end
---[Documentation](https://wow.gamepedia.com/API_BNIsSelf)
function BNIsSelf(presenceID) end
---[Documentation](https://wow.gamepedia.com/API_BNRemoveFriend)
function BNRemoveFriend(ID) end
---[Documentation](https://wow.gamepedia.com/API_BNRequestFOFInfo)
function BNRequestFOFInfo(bnetIDAccount) end
---[Documentation](https://wow.gamepedia.com/API_BNRequestInviteFriend)
function BNRequestInviteFriend(presenceID, tank, heal, dps) end
---[Documentation](https://wow.gamepedia.com/API_BNSendFriendInvite)
function BNSendFriendInvite(text, noteText) end
---[Documentation](https://wow.gamepedia.com/API_BNSendFriendInviteByID)
function BNSendFriendInviteByID(ID, noteText) end
---@param presenceID number
---@param addonPrefix string
---@param message string
---[Documentation](https://wow.gamepedia.com/API_BNSendGameData)
function BNSendGameData(presenceID, addonPrefix, message) end
---[Documentation](https://wow.gamepedia.com/API_BNSendSoR)
function BNSendSoR(target, comment) end
---[Documentation](https://wow.gamepedia.com/API_BNSendVerifiedBattleTagInvite)
function BNSendVerifiedBattleTagInvite() end
---@param bnetAccountID number
---@param message string
---[Documentation](https://wow.gamepedia.com/API_BNSendWhisper)
function BNSendWhisper(bnetAccountID, message) end
---@param bool boolean
---[Documentation](https://wow.gamepedia.com/API_BNSetAFK)
function BNSetAFK(bool) end
---[Documentation](https://wow.gamepedia.com/API_BNSetBlocked)
function BNSetBlocked(ID, bool) end
---@param text string
---[Documentation](https://wow.gamepedia.com/API_BNSetCustomMessage)
function BNSetCustomMessage(text) end
---@param bool boolean
---[Documentation](https://wow.gamepedia.com/API_BNSetDND)
function BNSetDND(bool) end
---@param id number
---@param isFavorite boolean
---[Documentation](https://wow.gamepedia.com/API_BNSetFriendFavoriteFlag)
function BNSetFriendFavoriteFlag(id, isFavorite) end
---@param bnetIDAccount number
---@param noteText string
---[Documentation](https://wow.gamepedia.com/API_BNSetFriendNote)
function BNSetFriendNote(bnetIDAccount, noteText) end
---[Documentation](https://wow.gamepedia.com/API_BNSetSelectedBlock)
function BNSetSelectedBlock(index) end
---[Documentation](https://wow.gamepedia.com/API_BNSetSelectedFriend)
function BNSetSelectedFriend(index) end
---[Documentation](https://wow.gamepedia.com/API_BNSummonFriendByIndex)
function BNSummonFriendByIndex(id) end
---[Documentation](https://wow.gamepedia.com/API_BNTokenFindName)
function BNTokenFindName(target) end
---[Documentation](https://wow.gamepedia.com/API_BankButtonIDToInvSlotID)
function BankButtonIDToInvSlotID(buttonID, isBag) end
---[Documentation](https://wow.gamepedia.com/API_BarberShopReset)
function BarberShopReset() end
---[Documentation](https://wow.gamepedia.com/API_BattlefieldMgrEntryInviteResponse)
function BattlefieldMgrEntryInviteResponse(queueId, accept) end
---[Documentation](https://wow.gamepedia.com/API_BattlefieldMgrExitRequest)
function BattlefieldMgrExitRequest(queueId) end
---[Documentation](https://wow.gamepedia.com/API_BattlefieldMgrQueueInviteResponse)
function BattlefieldMgrQueueInviteResponse(queueId, accept) end
---[Documentation](https://wow.gamepedia.com/API_BattlefieldMgrQueueRequest)
function BattlefieldMgrQueueRequest() end
---[Documentation](https://wow.gamepedia.com/API_BattlefieldSetPendingReportTarget)
function BattlefieldSetPendingReportTarget(index) end
---[Documentation](https://wow.gamepedia.com/API_BeginTrade)
function BeginTrade() end
---[Documentation](https://wow.gamepedia.com/API_BindEnchant)
function BindEnchant() end
---@param value number
---@return string valueString
---[Documentation](https://wow.gamepedia.com/API_BreakUpLargeNumbers)
function BreakUpLargeNumbers(value) end
---[Documentation](https://wow.gamepedia.com/API_BuyGuildBankTab)
function BuyGuildBankTab() end
---@param guildName string
---[Documentation](https://wow.gamepedia.com/API_BuyGuildCharter)
function BuyGuildCharter(guildName) end
---@param index number
---@param quantity number
---[Documentation](https://wow.gamepedia.com/API_BuyMerchantItem)
function BuyMerchantItem(index, quantity) end
---[Documentation](https://wow.gamepedia.com/API_BuyReagentBank)
function BuyReagentBank() end
---@param index number
---[Documentation](https://wow.gamepedia.com/API_BuyTrainerService)
function BuyTrainerService(index) end
---@param slot number
---[Documentation](https://wow.gamepedia.com/API_BuybackItem)
function BuybackItem(slot) end
---[Documentation](https://wow.gamepedia.com/API_C_AdventureJournal.ActivateEntry)
function C_AdventureJournal.ActivateEntry(index) end
---[Documentation](https://wow.gamepedia.com/API_C_AdventureJournal.CanBeShown)
function C_AdventureJournal.CanBeShown() end
---[Documentation](https://wow.gamepedia.com/API_C_AdventureJournal.GetNumAvailableSuggestions)
function C_AdventureJournal.GetNumAvailableSuggestions() end
---[Documentation](https://wow.gamepedia.com/API_C_AdventureJournal.GetPrimaryOffset)
function C_AdventureJournal.GetPrimaryOffset() end
---[Documentation](https://wow.gamepedia.com/API_C_AdventureJournal.GetReward)
function C_AdventureJournal.GetReward() end
---[Documentation](https://wow.gamepedia.com/API_C_AdventureJournal.GetSuggestions)
function C_AdventureJournal.GetSuggestions(suggestions) end
---[Documentation](https://wow.gamepedia.com/API_C_AdventureJournal.SetPrimaryOffset)
function C_AdventureJournal.SetPrimaryOffset(offset) end
---[Documentation](https://wow.gamepedia.com/API_C_AdventureJournal.UpdateSuggestions)
function C_AdventureJournal.UpdateSuggestions(levelUp) end
---[Documentation](https://wow.gamepedia.com/API_C_AdventureMap.Close)
function C_AdventureMap.Close() end
---[Documentation](https://wow.gamepedia.com/API_C_AdventureMap.GetMapID)
function C_AdventureMap.GetMapID() end
---[Documentation](https://wow.gamepedia.com/API_C_AdventureMap.GetMapInsetDetailTileInfo)
function C_AdventureMap.GetMapInsetDetailTileInfo(insetIndex, tileIndex) end
---[Documentation](https://wow.gamepedia.com/API_C_AdventureMap.GetMapInsetInfo)
function C_AdventureMap.GetMapInsetInfo(insetIndex) end
---[Documentation](https://wow.gamepedia.com/API_C_AdventureMap.GetNumMapInsets)
function C_AdventureMap.GetNumMapInsets() end
---[Documentation](https://wow.gamepedia.com/API_C_AdventureMap.GetNumQuestOffers)
function C_AdventureMap.GetNumQuestOffers() end
---[Documentation](https://wow.gamepedia.com/API_C_AdventureMap.GetNumZoneChoices)
function C_AdventureMap.GetNumZoneChoices() end
---[Documentation](https://wow.gamepedia.com/API_C_AdventureMap.GetQuestInfo)
function C_AdventureMap.GetQuestInfo(questID) end
---[Documentation](https://wow.gamepedia.com/API_C_AdventureMap.GetQuestOfferInfo)
function C_AdventureMap.GetQuestOfferInfo(offerIndex) end
---[Documentation](https://wow.gamepedia.com/API_C_AdventureMap.GetZoneChoiceInfo)
function C_AdventureMap.GetZoneChoiceInfo(choiceIndex) end
---[Documentation](https://wow.gamepedia.com/API_C_AdventureMap.StartQuest)
function C_AdventureMap.StartQuest(questID) end
---[Documentation](https://wow.gamepedia.com/API_C_BlackMarket.Close)
function C_BlackMarket.Close() end
---[Documentation](https://wow.gamepedia.com/API_C_BlackMarket.GetHotItem)
function C_BlackMarket.GetHotItem() end
---[Documentation](https://wow.gamepedia.com/API_C_BlackMarket.GetItemInfoByID)
function C_BlackMarket.GetItemInfoByID(marketID) end
---[Documentation](https://wow.gamepedia.com/API_C_BlackMarket.GetItemInfoByIndex)
function C_BlackMarket.GetItemInfoByIndex(index) end
---@return number numItems
---[Documentation](https://wow.gamepedia.com/API_C_BlackMarket.GetNumItems)
function C_BlackMarket.GetNumItems() end
---@return boolean viewOnly
---[Documentation](https://wow.gamepedia.com/API_C_BlackMarket.IsViewOnly)
function C_BlackMarket.IsViewOnly() end
---@param marketID number
---@param bid number
---[Documentation](https://wow.gamepedia.com/API_C_BlackMarket.ItemPlaceBid)
function C_BlackMarket.ItemPlaceBid(marketID, bid) end
---[Documentation](https://wow.gamepedia.com/API_C_BlackMarket.RequestItems)
function C_BlackMarket.RequestItems() end
---[Documentation](https://wow.gamepedia.com/API_C_CharacterServices.AssignUpgradeDistribution)
function C_CharacterServices.AssignUpgradeDistribution() end
---[Documentation](https://wow.gamepedia.com/API_C_CharacterServices.GetActiveCharacterUpgradeBoostType)
function C_CharacterServices.GetActiveCharacterUpgradeBoostType() end
---[Documentation](https://wow.gamepedia.com/API_C_CharacterServices.GetActiveClassTrialBoostType)
function C_CharacterServices.GetActiveClassTrialBoostType() end
---[Documentation](https://wow.gamepedia.com/API_C_CharacterServices.GetAutomaticBoost)
function C_CharacterServices.GetAutomaticBoost() end
---[Documentation](https://wow.gamepedia.com/API_C_CharacterServices.GetAutomaticBoostCharacter)
function C_CharacterServices.GetAutomaticBoostCharacter() end
---[Documentation](https://wow.gamepedia.com/API_C_CharacterServices.GetCharacterServiceDisplayData)
function C_CharacterServices.GetCharacterServiceDisplayData() end
---[Documentation](https://wow.gamepedia.com/API_C_CharacterServices.GetCharacterServiceDisplayOrder)
function C_CharacterServices.GetCharacterServiceDisplayOrder() end
---[Documentation](https://wow.gamepedia.com/API_C_CharacterServices.HasRequiredBoostForClassTrial)
function C_CharacterServices.HasRequiredBoostForClassTrial() end
---[Documentation](https://wow.gamepedia.com/API_C_CharacterServices.HasRequiredBoostForUnrevoke)
function C_CharacterServices.HasRequiredBoostForUnrevoke() end
---[Documentation](https://wow.gamepedia.com/API_C_CharacterServices.SetAutomaticBoost)
function C_CharacterServices.SetAutomaticBoost() end
---[Documentation](https://wow.gamepedia.com/API_C_CharacterServices.SetAutomaticBoostCharacter)
function C_CharacterServices.SetAutomaticBoostCharacter() end
---[Documentation](https://wow.gamepedia.com/API_C_CharacterServicesPublic.ShouldSeeControlPopup)
function C_CharacterServicesPublic.ShouldSeeControlPopup() end
---[Documentation](https://wow.gamepedia.com/API_C_ClassTrial.GetClassTrialLogoutTimeSeconds)
function C_ClassTrial.GetClassTrialLogoutTimeSeconds() end
---[Documentation](https://wow.gamepedia.com/API_C_ClassTrial.IsClassTrialCharacter)
function C_ClassTrial.IsClassTrialCharacter() end
---[Documentation](https://wow.gamepedia.com/API_C_Debug.DashboardIsEnabled)
function C_Debug.DashboardIsEnabled() end
---[Documentation](https://wow.gamepedia.com/API_C_Debug.GetAllPortLocsForMap)
function C_Debug.GetAllPortLocsForMap(uiMapID) end
---[Documentation](https://wow.gamepedia.com/API_C_Debug.GetMapDebugObjects)
function C_Debug.GetMapDebugObjects(uiMapID) end
---[Documentation](https://wow.gamepedia.com/API_C_Debug.TeleportToMapDebugObject)
function C_Debug.TeleportToMapDebugObject(pinIndex) end
---[Documentation](https://wow.gamepedia.com/API_C_Debug.TeleportToMapLocation)
function C_Debug.TeleportToMapLocation(uiMapID, mapX, mapY) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.AllowMissionStartAboveSoftCap)
function C_Garrison.AllowMissionStartAboveSoftCap(garrFollowerTypeID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.AreMissionFollowerRequirementsMet)
function C_Garrison.AreMissionFollowerRequirementsMet(missionRecID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.AssignFollowerToBuilding)
function C_Garrison.AssignFollowerToBuilding(plotInstanceID, followerID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.CanGenerateRecruits)
function C_Garrison.CanGenerateRecruits() end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.CanOpenMissionChest)
function C_Garrison.CanOpenMissionChest(missionID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.CanSetRecruitmentPreference)
function C_Garrison.CanSetRecruitmentPreference() end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.CanSpellTargetFollowerIDWithAddAbility)
function C_Garrison.CanSpellTargetFollowerIDWithAddAbility(followerID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.CanUpgradeGarrison)
function C_Garrison.CanUpgradeGarrison() end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.CancelConstruction)
function C_Garrison.CancelConstruction(plotInstanceID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.CastItemSpellOnFollowerAbility)
function C_Garrison.CastItemSpellOnFollowerAbility(followerID, abilityID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.CastSpellOnFollower)
function C_Garrison.CastSpellOnFollower(followerID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.CastSpellOnFollowerAbility)
function C_Garrison.CastSpellOnFollowerAbility(followerID, abilityID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.CastSpellOnMission)
function C_Garrison.CastSpellOnMission(missionID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.ClearCompleteTalent)
function C_Garrison.ClearCompleteTalent(garrisonType) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.CloseArchitect)
function C_Garrison.CloseArchitect() end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.CloseGarrisonTradeskillNPC)
function C_Garrison.CloseGarrisonTradeskillNPC() end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.CloseMissionNPC)
function C_Garrison.CloseMissionNPC() end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.CloseRecruitmentNPC)
function C_Garrison.CloseRecruitmentNPC() end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.CloseTalentNPC)
function C_Garrison.CloseTalentNPC() end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.CloseTradeskillCrafter)
function C_Garrison.CloseTradeskillCrafter() end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GenerateRecruits)
function C_Garrison.GenerateRecruits(mechanicTypeID, traitID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetAllBonusAbilityEffects)
function C_Garrison.GetAllBonusAbilityEffects() end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetAllEncounterThreats)
function C_Garrison.GetAllEncounterThreats(garrFollowerTypeID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetAvailableMissions)
function C_Garrison.GetAvailableMissions(missionList, garrFollowerTypeID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetAvailableRecruits)
function C_Garrison.GetAvailableRecruits() end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetBasicMissionInfo)
function C_Garrison.GetBasicMissionInfo(missionID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetBuffedFollowersForMission)
function C_Garrison.GetBuffedFollowersForMission(missionID, displayingAbilities) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetBuildingInfo)
function C_Garrison.GetBuildingInfo(buildingID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetBuildingLockInfo)
function C_Garrison.GetBuildingLockInfo() end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetBuildingSizes)
function C_Garrison.GetBuildingSizes() end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetBuildingSpecInfo)
function C_Garrison.GetBuildingSpecInfo() end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetBuildingTimeRemaining)
function C_Garrison.GetBuildingTimeRemaining(plotInstanceID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetBuildingTooltip)
function C_Garrison.GetBuildingTooltip(buildingID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetBuildingUpgradeInfo)
function C_Garrison.GetBuildingUpgradeInfo(buildingID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetBuildings)
function C_Garrison.GetBuildings(garrisonType) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetBuildingsForPlot)
function C_Garrison.GetBuildingsForPlot(plotInstanceID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetBuildingsForSize)
function C_Garrison.GetBuildingsForSize(garrisonType, uiCategoryID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetClassSpecCategoryInfo)
function C_Garrison.GetClassSpecCategoryInfo(garrFollowerType) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetCombatAllyMission)
function C_Garrison.GetCombatAllyMission(garrFollowerTypeID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetCompleteMissions)
function C_Garrison.GetCompleteMissions(missionList, garrFollowerTypeID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetCompleteTalent)
function C_Garrison.GetCompleteTalent(garrisonType) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetCurrencyTypes)
function C_Garrison.GetCurrencyTypes(garrType) end
---@param followerID number
---@return table abilities
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetFollowerAbilities)
function C_Garrison.GetFollowerAbilities(followerID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetFollowerAbilityAtIndex)
function C_Garrison.GetFollowerAbilityAtIndex(followerID, index) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetFollowerAbilityAtIndexByID)
function C_Garrison.GetFollowerAbilityAtIndexByID(garrFollowerID, index) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetFollowerAbilityCounterMechanicInfo)
function C_Garrison.GetFollowerAbilityCounterMechanicInfo(garrAbilityID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetFollowerAbilityCountersForMechanicTypes)
function C_Garrison.GetFollowerAbilityCountersForMechanicTypes(garrFollowerTypeID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetFollowerAbilityDescription)
function C_Garrison.GetFollowerAbilityDescription(garrAbilityID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetFollowerAbilityIcon)
function C_Garrison.GetFollowerAbilityIcon(garrAbilityID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetFollowerAbilityInfo)
function C_Garrison.GetFollowerAbilityInfo(garrAbilityID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetFollowerAbilityIsTrait)
function C_Garrison.GetFollowerAbilityIsTrait(garrAbilityID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetFollowerAbilityLink)
function C_Garrison.GetFollowerAbilityLink(abilityID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetFollowerAbilityName)
function C_Garrison.GetFollowerAbilityName(garrAbilityID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetFollowerActivationCost)
function C_Garrison.GetFollowerActivationCost() end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetFollowerBiasForMission)
function C_Garrison.GetFollowerBiasForMission(missionID, followerID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetFollowerClassSpec)
function C_Garrison.GetFollowerClassSpec(followerID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetFollowerClassSpecAtlas)
function C_Garrison.GetFollowerClassSpecAtlas(garrSpecID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetFollowerClassSpecByID)
function C_Garrison.GetFollowerClassSpecByID(garrFollowerID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetFollowerClassSpecName)
function C_Garrison.GetFollowerClassSpecName(garrFollowerID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetFollowerDisplayID)
function C_Garrison.GetFollowerDisplayID(followerID) end
---@param followerID number
---@return table info
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetFollowerInfo)
function C_Garrison.GetFollowerInfo(followerID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetFollowerInfoForBuilding)
function C_Garrison.GetFollowerInfoForBuilding() end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetFollowerIsTroop)
function C_Garrison.GetFollowerIsTroop() end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetFollowerItemLevelAverage)
function C_Garrison.GetFollowerItemLevelAverage(followerID) end
---@param followerID string
---@return number weaponItemID
---@return number weaponItemLevel
---@return number armorItemID
---@return number armorItemLevel
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetFollowerItems)
function C_Garrison.GetFollowerItems(followerID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetFollowerLevel)
function C_Garrison.GetFollowerLevel(followerID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetFollowerLevelXP)
function C_Garrison.GetFollowerLevelXP(followerID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetFollowerLink)
function C_Garrison.GetFollowerLink(followerID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetFollowerLinkByID)
function C_Garrison.GetFollowerLinkByID(garrFollowerID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetFollowerMissionTimeLeft)
function C_Garrison.GetFollowerMissionTimeLeft(followerID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetFollowerMissionTimeLeftSeconds)
function C_Garrison.GetFollowerMissionTimeLeftSeconds(followerID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetFollowerModelItems)
function C_Garrison.GetFollowerModelItems(followerID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetFollowerName)
function C_Garrison.GetFollowerName(followerID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetFollowerNameByID)
function C_Garrison.GetFollowerNameByID(garrFollowerID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetFollowerPortraitIconID)
function C_Garrison.GetFollowerPortraitIconID(followerID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetFollowerPortraitIconIDByID)
function C_Garrison.GetFollowerPortraitIconIDByID(garrFollowerID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetFollowerQuality)
function C_Garrison.GetFollowerQuality(followerID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetFollowerQualityTable)
function C_Garrison.GetFollowerQualityTable(garrFollowerTypeID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetFollowerRecentlyGainedAbilityIDs)
function C_Garrison.GetFollowerRecentlyGainedAbilityIDs(followerID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetFollowerRecentlyGainedTraitIDs)
function C_Garrison.GetFollowerRecentlyGainedTraitIDs(followerID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetFollowerShipments)
function C_Garrison.GetFollowerShipments(garrTypeID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetFollowerSoftCap)
function C_Garrison.GetFollowerSoftCap(garrFollowerTypeID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetFollowerSourceTextByID)
function C_Garrison.GetFollowerSourceTextByID(garrFollowerID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetFollowerSpecializationAtIndex)
function C_Garrison.GetFollowerSpecializationAtIndex(followerID, index) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetFollowerStatus)
function C_Garrison.GetFollowerStatus(followerID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetFollowerTraitAtIndex)
function C_Garrison.GetFollowerTraitAtIndex(followerID, index) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetFollowerTraitAtIndexByID)
function C_Garrison.GetFollowerTraitAtIndexByID(garrFollowerID, index) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetFollowerTypeByID)
function C_Garrison.GetFollowerTypeByID(garrFollowerID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetFollowerTypeByMissionID)
function C_Garrison.GetFollowerTypeByMissionID(missionID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetFollowerUnderBiasReason)
function C_Garrison.GetFollowerUnderBiasReason(missionID, followerID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetFollowerXP)
function C_Garrison.GetFollowerXP(followerID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetFollowerXPTable)
function C_Garrison.GetFollowerXPTable(garrFollowerTypeID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetFollowerZoneSupportAbilities)
function C_Garrison.GetFollowerZoneSupportAbilities() end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetFollowers)
function C_Garrison.GetFollowers() end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetFollowersSpellsForMission)
function C_Garrison.GetFollowersSpellsForMission(missionID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetFollowersTraitsForMission)
function C_Garrison.GetFollowersTraitsForMission(missionID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetGarrisonInfo)
function C_Garrison.GetGarrisonInfo(garrisonType) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetGarrisonUpgradeCost)
function C_Garrison.GetGarrisonUpgradeCost(followerType) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetInProgressMissions)
function C_Garrison.GetInProgressMissions(missionList, garrFollowerTypeID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetLandingPageGarrisonType)
function C_Garrison.GetLandingPageGarrisonType() end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetLandingPageItems)
function C_Garrison.GetLandingPageItems(garrTypeID, noSort) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetLandingPageShipmentCount)
function C_Garrison.GetLandingPageShipmentCount() end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetLandingPageShipmentInfo)
function C_Garrison.GetLandingPageShipmentInfo(buildingID) end
---@param containerID number
---@return string name
---@return number texture
---@return number shipmentCapacity
---@return number shipmentsReady
---@return number shipmentsTotal
---@return number creationTime
---@return number duration
---@return string timeleftString
---@return string itemName
---@return number itemTexture
---@return number unk1
---@return number itemID
---@return number followerID
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetLandingPageShipmentInfoByContainerID)
function C_Garrison.GetLandingPageShipmentInfoByContainerID(containerID) end
---@param garrisonType number
---@return table looseShipments
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetLooseShipments)
function C_Garrison.GetLooseShipments(garrisonType) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetMissionBonusAbilityEffects)
function C_Garrison.GetMissionBonusAbilityEffects(missionID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetMissionCost)
function C_Garrison.GetMissionCost(missionID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetMissionDisplayIDs)
function C_Garrison.GetMissionDisplayIDs(missionID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetMissionLink)
function C_Garrison.GetMissionLink(missionID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetMissionMaxFollowers)
function C_Garrison.GetMissionMaxFollowers(garrMissionID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetMissionName)
function C_Garrison.GetMissionName(garrMissionID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetMissionRewardInfo)
function C_Garrison.GetMissionRewardInfo(garrMissionID, missionDBID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetMissionSuccessChance)
function C_Garrison.GetMissionSuccessChance(missionID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetMissionTexture)
function C_Garrison.GetMissionTexture(offeredGarrMissionTextureID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetMissionTimes)
function C_Garrison.GetMissionTimes(missionID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetMissionUncounteredMechanics)
function C_Garrison.GetMissionUncounteredMechanics(missionID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetNumActiveFollowers)
function C_Garrison.GetNumActiveFollowers() end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetNumFollowerActivationsRemaining)
function C_Garrison.GetNumFollowerActivationsRemaining(garrTypeID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetNumFollowerDailyActivations)
function C_Garrison.GetNumFollowerDailyActivations() end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetNumFollowers)
function C_Garrison.GetNumFollowers() end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetNumFollowersForMechanic)
function C_Garrison.GetNumFollowersForMechanic(followerType, mechanicID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetNumFollowersOnMission)
function C_Garrison.GetNumFollowersOnMission(missionID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetNumPendingShipments)
function C_Garrison.GetNumPendingShipments() end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetNumShipmentCurrencies)
function C_Garrison.GetNumShipmentCurrencies() end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetNumShipmentReagents)
function C_Garrison.GetNumShipmentReagents() end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetOwnedBuildingInfo)
function C_Garrison.GetOwnedBuildingInfo(plotInstanceID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetOwnedBuildingInfoAbbrev)
function C_Garrison.GetOwnedBuildingInfoAbbrev(plotInstanceID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetPartyBuffs)
function C_Garrison.GetPartyBuffs(missionID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetPartyMentorLevels)
function C_Garrison.GetPartyMentorLevels(missionID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetPartyMissionInfo)
function C_Garrison.GetPartyMissionInfo(missionID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetPendingShipmentInfo)
function C_Garrison.GetPendingShipmentInfo(index) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetPlots)
function C_Garrison.GetPlots(followerType) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetPlotsForBuilding)
function C_Garrison.GetPlotsForBuilding(buildingID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetPossibleFollowersForBuilding)
function C_Garrison.GetPossibleFollowersForBuilding(followerType, plotInstanceID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetRecruitAbilities)
function C_Garrison.GetRecruitAbilities(index) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetRecruiterAbilityCategories)
function C_Garrison.GetRecruiterAbilityCategories() end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetRecruiterAbilityList)
function C_Garrison.GetRecruiterAbilityList(traits) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetRecruitmentPreferences)
function C_Garrison.GetRecruitmentPreferences() end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetShipDeathAnimInfo)
function C_Garrison.GetShipDeathAnimInfo() end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetShipmentContainerInfo)
function C_Garrison.GetShipmentContainerInfo() end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetShipmentItemInfo)
function C_Garrison.GetShipmentItemInfo() end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetShipmentReagentCurrencyInfo)
function C_Garrison.GetShipmentReagentCurrencyInfo(currencyIndex) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetShipmentReagentInfo)
function C_Garrison.GetShipmentReagentInfo(reagentIndex) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetShipmentReagentItemLink)
function C_Garrison.GetShipmentReagentItemLink(reagentIndex) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetSpecChangeCost)
function C_Garrison.GetSpecChangeCost() end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.GetTabForPlot)
function C_Garrison.GetTabForPlot(plotInstanceID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.HasGarrison)
function C_Garrison.HasGarrison(garrisonType) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.HasShipyard)
function C_Garrison.HasShipyard() end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.IsAboveFollowerSoftCap)
function C_Garrison.IsAboveFollowerSoftCap(garrFollowerTypeID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.IsFollowerCollected)
function C_Garrison.IsFollowerCollected(garrFollowerID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.IsInvasionAvailable)
function C_Garrison.IsInvasionAvailable() end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.IsMechanicFullyCountered)
function C_Garrison.IsMechanicFullyCountered(missionID, followerID, mechanicID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.IsOnGarrisonMap)
function C_Garrison.IsOnGarrisonMap() end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.IsOnShipmentQuestForNPC)
function C_Garrison.IsOnShipmentQuestForNPC() end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.IsOnShipyardMap)
function C_Garrison.IsOnShipyardMap() end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.IsPlayerInGarrison)
function C_Garrison.IsPlayerInGarrison(garrType) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.IsUsingPartyGarrison)
function C_Garrison.IsUsingPartyGarrison() end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.IsVisitGarrisonAvailable)
function C_Garrison.IsVisitGarrisonAvailable() end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.MarkMissionComplete)
function C_Garrison.MarkMissionComplete(missionID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.MissionBonusRoll)
function C_Garrison.MissionBonusRoll(missionID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.PlaceBuilding)
function C_Garrison.PlaceBuilding(plotInstanceID, buildingID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.RecruitFollower)
function C_Garrison.RecruitFollower(followerIndex) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.RemoveFollower)
function C_Garrison.RemoveFollower(dbID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.RemoveFollowerFromBuilding)
function C_Garrison.RemoveFollowerFromBuilding() end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.RenameFollower)
function C_Garrison.RenameFollower(followerID, name) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.RequestClassSpecCategoryInfo)
function C_Garrison.RequestClassSpecCategoryInfo(garrFollowerTypeID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.RequestGarrisonUpgradeable)
function C_Garrison.RequestGarrisonUpgradeable(followerType) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.RequestLandingPageShipmentInfo)
function C_Garrison.RequestLandingPageShipmentInfo() end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.RequestShipmentCreation)
function C_Garrison.RequestShipmentCreation() end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.RequestShipmentInfo)
function C_Garrison.RequestShipmentInfo() end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.ResearchTalent)
function C_Garrison.ResearchTalent(garrTalentID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.SearchForFollower)
function C_Garrison.SearchForFollower() end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.SetBuildingActive)
function C_Garrison.SetBuildingActive(plotInstanceID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.SetBuildingSpecialization)
function C_Garrison.SetBuildingSpecialization() end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.SetFollowerFavorite)
function C_Garrison.SetFollowerFavorite() end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.SetFollowerInactive)
function C_Garrison.SetFollowerInactive(followerID, inactive) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.SetRecruitmentPreferences)
function C_Garrison.SetRecruitmentPreferences(mechanicTypeID, traitID) end
---@param enabled boolean
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.SetUsingPartyGarrison)
function C_Garrison.SetUsingPartyGarrison(enabled) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.ShouldShowMapTab)
function C_Garrison.ShouldShowMapTab(garrType) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.ShowFollowerNameInErrorMessage)
function C_Garrison.ShowFollowerNameInErrorMessage(missionRecID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.StartMission)
function C_Garrison.StartMission(missionID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.SwapBuildings)
function C_Garrison.SwapBuildings(plotInstanceID1, plotInstanceID2) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.TargetSpellHasFollowerItemLevelUpgrade)
function C_Garrison.TargetSpellHasFollowerItemLevelUpgrade() end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.TargetSpellHasFollowerReroll)
function C_Garrison.TargetSpellHasFollowerReroll() end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.TargetSpellHasFollowerTemporaryAbility)
function C_Garrison.TargetSpellHasFollowerTemporaryAbility() end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.UpgradeBuilding)
function C_Garrison.UpgradeBuilding(plotInstanceID) end
---[Documentation](https://wow.gamepedia.com/API_C_Garrison.UpgradeGarrison)
function C_Garrison.UpgradeGarrison(followerType) end
---[Documentation](https://wow.gamepedia.com/API_C_Heirloom.CanHeirloomUpgradeFromPending)
function C_Heirloom.CanHeirloomUpgradeFromPending(itemID) end
---[Documentation](https://wow.gamepedia.com/API_C_Heirloom.CreateHeirloom)
function C_Heirloom.CreateHeirloom(itemID) end
---[Documentation](https://wow.gamepedia.com/API_C_Heirloom.GetClassAndSpecFilters)
function C_Heirloom.GetClassAndSpecFilters() end
---[Documentation](https://wow.gamepedia.com/API_C_Heirloom.GetCollectedHeirloomFilter)
function C_Heirloom.GetCollectedHeirloomFilter() end
---@param itemID number
---@return string name
---@return string itemEquipLoc
---@return boolean isPvP
---@return string itemTexture
---@return number upgradeLevel
---@return number source
---@return boolean searchFiltered
---@return number effectiveLevel
---@return number minLevel
---@return number maxLevel
---[Documentation](https://wow.gamepedia.com/API_C_Heirloom.GetHeirloomInfo)
function C_Heirloom.GetHeirloomInfo(itemID) end
---[Documentation](https://wow.gamepedia.com/API_C_Heirloom.GetHeirloomItemIDFromDisplayedIndex)
function C_Heirloom.GetHeirloomItemIDFromDisplayedIndex(heirloomIndex) end
---[Documentation](https://wow.gamepedia.com/API_C_Heirloom.GetHeirloomItemIDs)
function C_Heirloom.GetHeirloomItemIDs() end
---[Documentation](https://wow.gamepedia.com/API_C_Heirloom.GetHeirloomLink)
function C_Heirloom.GetHeirloomLink(itemID) end
---[Documentation](https://wow.gamepedia.com/API_C_Heirloom.GetHeirloomMaxUpgradeLevel)
function C_Heirloom.GetHeirloomMaxUpgradeLevel(itemID) end
---[Documentation](https://wow.gamepedia.com/API_C_Heirloom.GetHeirloomSourceFilter)
function C_Heirloom.GetHeirloomSourceFilter(source) end
---[Documentation](https://wow.gamepedia.com/API_C_Heirloom.GetNumDisplayedHeirlooms)
function C_Heirloom.GetNumDisplayedHeirlooms() end
---[Documentation](https://wow.gamepedia.com/API_C_Heirloom.GetNumHeirlooms)
function C_Heirloom.GetNumHeirlooms() end
---[Documentation](https://wow.gamepedia.com/API_C_Heirloom.GetNumKnownHeirlooms)
function C_Heirloom.GetNumKnownHeirlooms() end
---[Documentation](https://wow.gamepedia.com/API_C_Heirloom.GetUncollectedHeirloomFilter)
function C_Heirloom.GetUncollectedHeirloomFilter() end
---[Documentation](https://wow.gamepedia.com/API_C_Heirloom.IsHeirloomSourceValid)
function C_Heirloom.IsHeirloomSourceValid(source) end
---[Documentation](https://wow.gamepedia.com/API_C_Heirloom.IsItemHeirloom)
function C_Heirloom.IsItemHeirloom(itemID) end
---[Documentation](https://wow.gamepedia.com/API_C_Heirloom.IsPendingHeirloomUpgrade)
function C_Heirloom.IsPendingHeirloomUpgrade() end
---[Documentation](https://wow.gamepedia.com/API_C_Heirloom.PlayerHasHeirloom)
function C_Heirloom.PlayerHasHeirloom(itemID) end
---[Documentation](https://wow.gamepedia.com/API_C_Heirloom.SetClassAndSpecFilters)
function C_Heirloom.SetClassAndSpecFilters(classID, specID) end
---[Documentation](https://wow.gamepedia.com/API_C_Heirloom.SetCollectedHeirloomFilter)
function C_Heirloom.SetCollectedHeirloomFilter(boolean) end
---[Documentation](https://wow.gamepedia.com/API_C_Heirloom.SetHeirloomSourceFilter)
function C_Heirloom.SetHeirloomSourceFilter(source, filtered) end
---[Documentation](https://wow.gamepedia.com/API_C_Heirloom.SetSearch)
function C_Heirloom.SetSearch(searchValue) end
---[Documentation](https://wow.gamepedia.com/API_C_Heirloom.SetUncollectedHeirloomFilter)
function C_Heirloom.SetUncollectedHeirloomFilter(boolean) end
---[Documentation](https://wow.gamepedia.com/API_C_Heirloom.ShouldShowHeirloomHelp)
function C_Heirloom.ShouldShowHeirloomHelp() end
---[Documentation](https://wow.gamepedia.com/API_C_Heirloom.UpgradeHeirloom)
function C_Heirloom.UpgradeHeirloom(itemID) end
---[Documentation](https://wow.gamepedia.com/API_C_LFGList.AcceptInvite)
function C_LFGList.AcceptInvite(resultID) end
---[Documentation](https://wow.gamepedia.com/API_C_LFGList.ApplyToGroup)
function C_LFGList.ApplyToGroup(resultID, comment, tank, healer, dps) end
---[Documentation](https://wow.gamepedia.com/API_C_LFGList.CancelApplication)
function C_LFGList.CancelApplication(resultID) end
---[Documentation](https://wow.gamepedia.com/API_C_LFGList.ClearSearchResults)
function C_LFGList.ClearSearchResults() end
---[Documentation](https://wow.gamepedia.com/API_C_LFGList.CreateListing)
function C_LFGList.CreateListing(activityID, itemLevel, honorLevel, autoAccept, privateGroup, questID) end
---[Documentation](https://wow.gamepedia.com/API_C_LFGList.DeclineApplicant)
function C_LFGList.DeclineApplicant(applicantID) end
---[Documentation](https://wow.gamepedia.com/API_C_LFGList.DeclineInvite)
function C_LFGList.DeclineInvite(searchResultID) end
---@param groupID number
---@return string name
---@return number groupOrder
---[Documentation](https://wow.gamepedia.com/API_C_LFGList.GetActivityGroupInfo)
function C_LFGList.GetActivityGroupInfo(groupID) end
---[Documentation](https://wow.gamepedia.com/API_C_LFGList.GetActivityIDForQuestID)
function C_LFGList.GetActivityIDForQuestID(questID) end
---[Documentation](https://wow.gamepedia.com/API_C_LFGList.GetActivityInfo)
function C_LFGList.GetActivityInfo(activityID) end
---@param activityID number
---@return boolean currentArea
---[Documentation](https://wow.gamepedia.com/API_C_LFGList.GetActivityInfoExpensive)
function C_LFGList.GetActivityInfoExpensive(activityID) end
---[Documentation](https://wow.gamepedia.com/API_C_LFGList.GetApplicantMemberInfo)
function C_LFGList.GetApplicantMemberInfo(applicantID) end
---@param applicantID number
---@param memberIndex number
---@return table stats
---[Documentation](https://wow.gamepedia.com/API_C_LFGList.GetApplicantMemberStats)
function C_LFGList.GetApplicantMemberStats(applicantID, memberIndex) end
---@return table applicants
---[Documentation](https://wow.gamepedia.com/API_C_LFGList.GetApplicants)
function C_LFGList.GetApplicants() end
---[Documentation](https://wow.gamepedia.com/API_C_LFGList.GetApplicationInfo)
function C_LFGList.GetApplicationInfo(searchResultID) end
---[Documentation](https://wow.gamepedia.com/API_C_LFGList.GetApplications)
function C_LFGList.GetApplications() end
---@param categoryID number
---@param groupID number
---@param filter number
---@return table activities
---[Documentation](https://wow.gamepedia.com/API_C_LFGList.GetAvailableActivities)
function C_LFGList.GetAvailableActivities(categoryID, groupID, filter) end
---@param categoryID number
---@param filter number
---@return table groups
---[Documentation](https://wow.gamepedia.com/API_C_LFGList.GetAvailableActivityGroups)
function C_LFGList.GetAvailableActivityGroups(categoryID, filter) end
---@param filter number
---@return table categories
---[Documentation](https://wow.gamepedia.com/API_C_LFGList.GetAvailableCategories)
function C_LFGList.GetAvailableCategories(filter) end
---[Documentation](https://wow.gamepedia.com/API_C_LFGList.GetAvailableLanguageSearchFilter)
function C_LFGList.GetAvailableLanguageSearchFilter() end
---[Documentation](https://wow.gamepedia.com/API_C_LFGList.GetAvailableRoles)
function C_LFGList.GetAvailableRoles() end
---[Documentation](https://wow.gamepedia.com/API_C_LFGList.GetCategoryInfo)
function C_LFGList.GetCategoryInfo(categoryID) end
---[Documentation](https://wow.gamepedia.com/API_C_LFGList.GetDefaultLanguageSearchFilter)
function C_LFGList.GetDefaultLanguageSearchFilter() end
---[Documentation](https://wow.gamepedia.com/API_C_LFGList.GetLanguageSearchFilter)
function C_LFGList.GetLanguageSearchFilter() end
---[Documentation](https://wow.gamepedia.com/API_C_LFGList.GetNumApplicants)
function C_LFGList.GetNumApplicants() end
---[Documentation](https://wow.gamepedia.com/API_C_LFGList.GetNumApplications)
function C_LFGList.GetNumApplications() end
---[Documentation](https://wow.gamepedia.com/API_C_LFGList.GetNumInvitedApplicantMembers)
function C_LFGList.GetNumInvitedApplicantMembers() end
---[Documentation](https://wow.gamepedia.com/API_C_LFGList.GetNumPendingApplicantMembers)
function C_LFGList.GetNumPendingApplicantMembers() end
---[Documentation](https://wow.gamepedia.com/API_C_LFGList.GetRoleCheckInfo)
function C_LFGList.GetRoleCheckInfo() end
---[Documentation](https://wow.gamepedia.com/API_C_LFGList.GetSearchResultEncounterInfo)
function C_LFGList.GetSearchResultEncounterInfo(searchResultID) end
---[Documentation](https://wow.gamepedia.com/API_C_LFGList.GetSearchResultFriends)
function C_LFGList.GetSearchResultFriends(searchResultID) end
---[Documentation](https://wow.gamepedia.com/API_C_LFGList.GetSearchResultMemberCounts)
function C_LFGList.GetSearchResultMemberCounts(searchResultID) end
---[Documentation](https://wow.gamepedia.com/API_C_LFGList.GetSearchResultMemberInfo)
function C_LFGList.GetSearchResultMemberInfo(searchResultID, memberIndex) end
---@return number numResults
---@return table resultIDTable
---[Documentation](https://wow.gamepedia.com/API_C_LFGList.GetSearchResults)
function C_LFGList.GetSearchResults() end
---[Documentation](https://wow.gamepedia.com/API_C_LFGList.HasActivityList)
function C_LFGList.HasActivityList() end
---@param applicantID number
---[Documentation](https://wow.gamepedia.com/API_C_LFGList.InviteApplicant)
function C_LFGList.InviteApplicant(applicantID) end
---[Documentation](https://wow.gamepedia.com/API_C_LFGList.IsCurrentlyApplying)
function C_LFGList.IsCurrentlyApplying() end
---[Documentation](https://wow.gamepedia.com/API_C_LFGList.RefreshApplicants)
function C_LFGList.RefreshApplicants() end
---[Documentation](https://wow.gamepedia.com/API_C_LFGList.RemoveApplicant)
function C_LFGList.RemoveApplicant(applicantID) end
---[Documentation](https://wow.gamepedia.com/API_C_LFGList.RemoveListing)
function C_LFGList.RemoveListing() end
---[Documentation](https://wow.gamepedia.com/API_C_LFGList.ReportApplicant)
function C_LFGList.ReportApplicant(applicantID) end
---[Documentation](https://wow.gamepedia.com/API_C_LFGList.ReportSearchResult)
function C_LFGList.ReportSearchResult(resultID, complaintType) end
---[Documentation](https://wow.gamepedia.com/API_C_LFGList.RequestAvailableActivities)
function C_LFGList.RequestAvailableActivities() end
---[Documentation](https://wow.gamepedia.com/API_C_LFGList.SaveLanguageSearchFilter)
function C_LFGList.SaveLanguageSearchFilter(enabled) end
---[Documentation](https://wow.gamepedia.com/API_C_LFGList.SetApplicantMemberRole)
function C_LFGList.SetApplicantMemberRole(applicantID, memberIndex, role) end
---[Documentation](https://wow.gamepedia.com/API_C_LFGList.UpdateListing)
function C_LFGList.UpdateListing(lfgID, itemLevel, honorLevel, autoAccept, private, questID) end
---[Documentation](https://wow.gamepedia.com/API_C_LootHistory.CanMasterLoot)
function C_LootHistory.CanMasterLoot(itemIndex, playerIndex) end
---[Documentation](https://wow.gamepedia.com/API_C_LootHistory.GetExpiration)
function C_LootHistory.GetExpiration() end
---[Documentation](https://wow.gamepedia.com/API_C_LootHistory.GetItem)
function C_LootHistory.GetItem(itemIndex) end
---[Documentation](https://wow.gamepedia.com/API_C_LootHistory.GetNumItems)
function C_LootHistory.GetNumItems() end
---[Documentation](https://wow.gamepedia.com/API_C_LootHistory.GetPlayerInfo)
function C_LootHistory.GetPlayerInfo(itemIndex, playerIndex) end
---[Documentation](https://wow.gamepedia.com/API_C_LootHistory.GiveMasterLoot)
function C_LootHistory.GiveMasterLoot(itemIndex, playerIndex) end
---[Documentation](https://wow.gamepedia.com/API_C_LootHistory.SetExpiration)
function C_LootHistory.SetExpiration(numItemsToSave, secondsToSave) end
---[Documentation](https://wow.gamepedia.com/API_C_NamePlate.GetNamePlateEnemyClickThrough)
function C_NamePlate.GetNamePlateEnemyClickThrough() end
---[Documentation](https://wow.gamepedia.com/API_C_NamePlate.GetNamePlateEnemyPreferredClickInsets)
function C_NamePlate.GetNamePlateEnemyPreferredClickInsets() end
---[Documentation](https://wow.gamepedia.com/API_C_NamePlate.GetNamePlateEnemySize)
function C_NamePlate.GetNamePlateEnemySize() end
---[Documentation](https://wow.gamepedia.com/API_C_NamePlate.GetNamePlateForUnit)
function C_NamePlate.GetNamePlateForUnit(unitToken, includeForbidden) end
---[Documentation](https://wow.gamepedia.com/API_C_NamePlate.GetNamePlateFriendlyClickThrough)
function C_NamePlate.GetNamePlateFriendlyClickThrough() end
---[Documentation](https://wow.gamepedia.com/API_C_NamePlate.GetNamePlateFriendlyPreferredClickInsets)
function C_NamePlate.GetNamePlateFriendlyPreferredClickInsets() end
---[Documentation](https://wow.gamepedia.com/API_C_NamePlate.GetNamePlateFriendlySize)
function C_NamePlate.GetNamePlateFriendlySize() end
---[Documentation](https://wow.gamepedia.com/API_C_NamePlate.GetNamePlateSelfClickThrough)
function C_NamePlate.GetNamePlateSelfClickThrough() end
---[Documentation](https://wow.gamepedia.com/API_C_NamePlate.GetNamePlateSelfPreferredClickInsets)
function C_NamePlate.GetNamePlateSelfPreferredClickInsets() end
---[Documentation](https://wow.gamepedia.com/API_C_NamePlate.GetNamePlateSelfSize)
function C_NamePlate.GetNamePlateSelfSize() end
---[Documentation](https://wow.gamepedia.com/API_C_NamePlate.GetNamePlates)
function C_NamePlate.GetNamePlates(includeForbidden) end
---[Documentation](https://wow.gamepedia.com/API_C_NamePlate.GetNumNamePlateMotionTypes)
function C_NamePlate.GetNumNamePlateMotionTypes() end
---[Documentation](https://wow.gamepedia.com/API_C_NamePlate.GetTargetClampingInsets)
function C_NamePlate.GetTargetClampingInsets() end
---[Documentation](https://wow.gamepedia.com/API_C_NamePlate.SetNamePlateEnemyClickThrough)
function C_NamePlate.SetNamePlateEnemyClickThrough(clickthrough) end
---[Documentation](https://wow.gamepedia.com/API_C_NamePlate.SetNamePlateEnemyPreferredClickInsets)
function C_NamePlate.SetNamePlateEnemyPreferredClickInsets() end
---[Documentation](https://wow.gamepedia.com/API_C_NamePlate.SetNamePlateEnemySize)
function C_NamePlate.SetNamePlateEnemySize(width, height) end
---[Documentation](https://wow.gamepedia.com/API_C_NamePlate.SetNamePlateFriendlyClickThrough)
function C_NamePlate.SetNamePlateFriendlyClickThrough() end
---[Documentation](https://wow.gamepedia.com/API_C_NamePlate.SetNamePlateFriendlyPreferredClickInsets)
function C_NamePlate.SetNamePlateFriendlyPreferredClickInsets(left, right, top, bottom) end
---[Documentation](https://wow.gamepedia.com/API_C_NamePlate.SetNamePlateFriendlySize)
function C_NamePlate.SetNamePlateFriendlySize(width, height) end
---[Documentation](https://wow.gamepedia.com/API_C_NamePlate.SetNamePlateSelfClickThrough)
function C_NamePlate.SetNamePlateSelfClickThrough(clickthrough) end
---[Documentation](https://wow.gamepedia.com/API_C_NamePlate.SetNamePlateSelfPreferredClickInsets)
function C_NamePlate.SetNamePlateSelfPreferredClickInsets(left, right, top, bottom) end
---[Documentation](https://wow.gamepedia.com/API_C_NamePlate.SetNamePlateSelfSize)
function C_NamePlate.SetNamePlateSelfSize(width, height) end
---[Documentation](https://wow.gamepedia.com/API_C_NamePlate.SetTargetClampingInsets)
function C_NamePlate.SetTargetClampingInsets(clickthrough) end
---[Documentation](https://wow.gamepedia.com/API_C_NewItems.ClearAll)
function C_NewItems.ClearAll() end
---@param bag number
---@param slot number
---@return boolean isNewItem
---[Documentation](https://wow.gamepedia.com/API_C_NewItems.IsNewItem)
function C_NewItems.IsNewItem(bag, slot) end
---@param bag number
---@param slot number
---[Documentation](https://wow.gamepedia.com/API_C_NewItems.RemoveNewItem)
function C_NewItems.RemoveNewItem(bag, slot) end
---[Documentation](https://wow.gamepedia.com/API_C_PetBattles.AcceptPVPDuel)
function C_PetBattles.AcceptPVPDuel() end
---[Documentation](https://wow.gamepedia.com/API_C_PetBattles.AcceptQueuedPVPMatch)
function C_PetBattles.AcceptQueuedPVPMatch() end
---@return boolean canAccept
---[Documentation](https://wow.gamepedia.com/API_C_PetBattles.CanAcceptQueuedPVPMatch)
function C_PetBattles.CanAcceptQueuedPVPMatch() end
---@return boolean usable
---[Documentation](https://wow.gamepedia.com/API_C_PetBattles.CanActivePetSwapOut)
function C_PetBattles.CanActivePetSwapOut() end
---@param petIndex number
---@return boolean usable
---[Documentation](https://wow.gamepedia.com/API_C_PetBattles.CanPetSwapIn)
function C_PetBattles.CanPetSwapIn(petIndex) end
---[Documentation](https://wow.gamepedia.com/API_C_PetBattles.CancelPVPDuel)
function C_PetBattles.CancelPVPDuel() end
---@param petIndex number
---[Documentation](https://wow.gamepedia.com/API_C_PetBattles.ChangePet)
function C_PetBattles.ChangePet(petIndex) end
---[Documentation](https://wow.gamepedia.com/API_C_PetBattles.DeclineQueuedPVPMatch)
function C_PetBattles.DeclineQueuedPVPMatch() end
---[Documentation](https://wow.gamepedia.com/API_C_PetBattles.ForfeitGame)
function C_PetBattles.ForfeitGame() end
---@param abilityID number
---@param turnIndex number
---@param effectIndex number
---@param effectName string
---@return number value
---[Documentation](https://wow.gamepedia.com/API_C_PetBattles.GetAbilityEffectInfo)
function C_PetBattles.GetAbilityEffectInfo(abilityID, turnIndex, effectIndex, effectName) end
---@param petOwner number
---@param petIndex number
---@param abilityIndex number
---@return number id
---@return string name
---@return string icon
---@return number maxCooldown
---@return string unparsedDescription
---@return number numTurns
---@return number petType
---@return boolean noStrongWeakHints
---[Documentation](https://wow.gamepedia.com/API_C_PetBattles.GetAbilityInfo)
function C_PetBattles.GetAbilityInfo(petOwner, petIndex, abilityIndex) end
---[Documentation](https://wow.gamepedia.com/API_C_PetBattles.GetAbilityInfoByID)
function C_PetBattles.GetAbilityInfoByID(abilityID) end
---@param abilityID number
---@param procType number
---@return number turnIndex
---[Documentation](https://wow.gamepedia.com/API_C_PetBattles.GetAbilityProcTurnIndex)
function C_PetBattles.GetAbilityProcTurnIndex(abilityID, procType) end
---@param petOwner number
---@param petIndex number
---@param actionIndex number
---@return boolean isUsable
---@return number currentCooldown
---@return number currentLockdown
---[Documentation](https://wow.gamepedia.com/API_C_PetBattles.GetAbilityState)
function C_PetBattles.GetAbilityState(petOwner, petIndex, actionIndex) end
---@param abilityID number
---@param stateID number
---@return number abilityStateMod
---[Documentation](https://wow.gamepedia.com/API_C_PetBattles.GetAbilityStateModification)
function C_PetBattles.GetAbilityStateModification(abilityID, stateID) end
---@param petOwner number
---@return number petIndex
---[Documentation](https://wow.gamepedia.com/API_C_PetBattles.GetActivePet)
function C_PetBattles.GetActivePet(petOwner) end
---[Documentation](https://wow.gamepedia.com/API_C_PetBattles.GetAllEffectNames)
function C_PetBattles.GetAllEffectNames() end
---[Documentation](https://wow.gamepedia.com/API_C_PetBattles.GetAllStates)
function C_PetBattles.GetAllStates() end
---@param petType number
---@param enemyPetType number
---@return number modifier
---[Documentation](https://wow.gamepedia.com/API_C_PetBattles.GetAttackModifier)
function C_PetBattles.GetAttackModifier(petType, enemyPetType) end
---@param petOwner number
---@param petIndex number
---@param auraIndex number
---@return number auraID
---@return number instanceID
---@return number turnsRemaining
---@return boolean isBuff
---[Documentation](https://wow.gamepedia.com/API_C_PetBattles.GetAuraInfo)
function C_PetBattles.GetAuraInfo(petOwner, petIndex, auraIndex) end
---@return number battleState
---[Documentation](https://wow.gamepedia.com/API_C_PetBattles.GetBattleState)
function C_PetBattles.GetBattleState() end
---@param petOwner number
---@param petIndex number
---@return number rarity
---[Documentation](https://wow.gamepedia.com/API_C_PetBattles.GetBreedQuality)
function C_PetBattles.GetBreedQuality(petOwner, petIndex) end
---@param petOwner number
---@param petIndex number
---@return number displayID
---[Documentation](https://wow.gamepedia.com/API_C_PetBattles.GetDisplayID)
function C_PetBattles.GetDisplayID(petOwner, petIndex) end
---@return number forfeitPenalty
---[Documentation](https://wow.gamepedia.com/API_C_PetBattles.GetForfeitPenalty)
function C_PetBattles.GetForfeitPenalty() end
---@param petOwner number
---@param petIndex number
---@return number health
---[Documentation](https://wow.gamepedia.com/API_C_PetBattles.GetHealth)
function C_PetBattles.GetHealth(petOwner, petIndex) end
---@param petOwner number
---@param petIndex number
---@return string icon
---[Documentation](https://wow.gamepedia.com/API_C_PetBattles.GetIcon)
function C_PetBattles.GetIcon(petOwner, petIndex) end
---@param petOwner number
---@param petIndex number
---@return number level
---[Documentation](https://wow.gamepedia.com/API_C_PetBattles.GetLevel)
function C_PetBattles.GetLevel(petOwner, petIndex) end
---@param petOwner number
---@param petIndex number
---@return number maxHealth
---[Documentation](https://wow.gamepedia.com/API_C_PetBattles.GetMaxHealth)
function C_PetBattles.GetMaxHealth(petOwner, petIndex) end
---@param petOwner number
---@param petIndex number
---@return string name
---@return string speciesName
---[Documentation](https://wow.gamepedia.com/API_C_PetBattles.GetName)
function C_PetBattles.GetName(petOwner, petIndex) end
---@param petOwner number
---@param petIndex number
---@return number numAuras
---[Documentation](https://wow.gamepedia.com/API_C_PetBattles.GetNumAuras)
function C_PetBattles.GetNumAuras(petOwner, petIndex) end
---[Documentation](https://wow.gamepedia.com/API_C_PetBattles.GetNumPets)
function C_PetBattles.GetNumPets(petOwner) end
---@return string queueState
---@return number estimatedTime
---@return number queuedTime
---[Documentation](https://wow.gamepedia.com/API_C_PetBattles.GetPVPMatchmakingInfo)
function C_PetBattles.GetPVPMatchmakingInfo() end
---@param petOwner number
---@param petIndex number
---@return number speciesID
---[Documentation](https://wow.gamepedia.com/API_C_PetBattles.GetPetSpeciesID)
function C_PetBattles.GetPetSpeciesID(petOwner, petIndex) end
---@param petOwner number
---@param petIndex number
---@return number petType
---[Documentation](https://wow.gamepedia.com/API_C_PetBattles.GetPetType)
function C_PetBattles.GetPetType(petOwner, petIndex) end
---@return number trapAbilityID
---[Documentation](https://wow.gamepedia.com/API_C_PetBattles.GetPlayerTrapAbility)
function C_PetBattles.GetPlayerTrapAbility() end
---@param petOwner number
---@param petIndex number
---@return number power
---[Documentation](https://wow.gamepedia.com/API_C_PetBattles.GetPower)
function C_PetBattles.GetPower(petOwner, petIndex) end
---@return number selectedActionType
---@return number selectedActionIndex
---[Documentation](https://wow.gamepedia.com/API_C_PetBattles.GetSelectedAction)
function C_PetBattles.GetSelectedAction() end
---@param petOwner number
---@param petIndex number
---@return number speed
---[Documentation](https://wow.gamepedia.com/API_C_PetBattles.GetSpeed)
function C_PetBattles.GetSpeed(petOwner, petIndex) end
---@param petOwner number
---@param petIndex number
---@param stateID number
---@return number stateValue
---[Documentation](https://wow.gamepedia.com/API_C_PetBattles.GetStateValue)
function C_PetBattles.GetStateValue(petOwner, petIndex, stateID) end
---@return number timeRemaining
---@return number turnTime
---[Documentation](https://wow.gamepedia.com/API_C_PetBattles.GetTurnTimeInfo)
function C_PetBattles.GetTurnTimeInfo() end
---@param petOwner number
---@param petIndex number
---@return number xp
---@return number maxXp
---[Documentation](https://wow.gamepedia.com/API_C_PetBattles.GetXP)
function C_PetBattles.GetXP(petOwner, petIndex) end
---@return boolean inBattle
---[Documentation](https://wow.gamepedia.com/API_C_PetBattles.IsInBattle)
function C_PetBattles.IsInBattle() end
---@param petOwner number
---@return boolean isNPC
---[Documentation](https://wow.gamepedia.com/API_C_PetBattles.IsPlayerNPC)
function C_PetBattles.IsPlayerNPC(petOwner) end
---@return boolean usable
---[Documentation](https://wow.gamepedia.com/API_C_PetBattles.IsSkipAvailable)
function C_PetBattles.IsSkipAvailable() end
---@return boolean usable
---[Documentation](https://wow.gamepedia.com/API_C_PetBattles.IsTrapAvailable)
function C_PetBattles.IsTrapAvailable() end
---@return boolean isWaiting
---[Documentation](https://wow.gamepedia.com/API_C_PetBattles.IsWaitingOnOpponent)
function C_PetBattles.IsWaitingOnOpponent() end
---@return boolean inWildBattle
---[Documentation](https://wow.gamepedia.com/API_C_PetBattles.IsWildBattle)
function C_PetBattles.IsWildBattle() end
---@param petIndex number
---[Documentation](https://wow.gamepedia.com/API_C_PetBattles.SetPendingReportBattlePetTarget)
function C_PetBattles.SetPendingReportBattlePetTarget(petIndex) end
---@param unit string
---[Documentation](https://wow.gamepedia.com/API_C_PetBattles.SetPendingReportTargetFromUnit)
function C_PetBattles.SetPendingReportTargetFromUnit(unit) end
---@return boolean shouldShow
---[Documentation](https://wow.gamepedia.com/API_C_PetBattles.ShouldShowPetSelect)
function C_PetBattles.ShouldShowPetSelect() end
---[Documentation](https://wow.gamepedia.com/API_C_PetBattles.SkipTurn)
function C_PetBattles.SkipTurn() end
---[Documentation](https://wow.gamepedia.com/API_C_PetBattles.StartPVPDuel)
function C_PetBattles.StartPVPDuel() end
---[Documentation](https://wow.gamepedia.com/API_C_PetBattles.StartPVPMatchmaking)
function C_PetBattles.StartPVPMatchmaking() end
---[Documentation](https://wow.gamepedia.com/API_C_PetBattles.StopPVPMatchmaking)
function C_PetBattles.StopPVPMatchmaking() end
---@param actionIndex number
---[Documentation](https://wow.gamepedia.com/API_C_PetBattles.UseAbility)
function C_PetBattles.UseAbility(actionIndex) end
---[Documentation](https://wow.gamepedia.com/API_C_PetBattles.UseTrap)
function C_PetBattles.UseTrap() end
---@param petID string
---[Documentation](https://wow.gamepedia.com/API_C_PetJournal.CagePetByID)
function C_PetJournal.CagePetByID(petID) end
---[Documentation](https://wow.gamepedia.com/API_C_PetJournal.ClearFanfare)
function C_PetJournal.ClearFanfare() end
---[Documentation](https://wow.gamepedia.com/API_C_PetJournal.ClearRecentFanfares)
function C_PetJournal.ClearRecentFanfares() end
---[Documentation](https://wow.gamepedia.com/API_C_PetJournal.ClearSearchFilter)
function C_PetJournal.ClearSearchFilter() end
---@param petName string
---@return number speciesId
---@return string petGUID
---[Documentation](https://wow.gamepedia.com/API_C_PetJournal.FindPetIDByName)
function C_PetJournal.FindPetIDByName(petName) end
---@param petID string
---@return string link
---[Documentation](https://wow.gamepedia.com/API_C_PetJournal.GetBattlePetLink)
function C_PetJournal.GetBattlePetLink(petID) end
---@param speciesId number
---@return number numCollected
---@return number limit
---[Documentation](https://wow.gamepedia.com/API_C_PetJournal.GetNumCollectedInfo)
function C_PetJournal.GetNumCollectedInfo(speciesId) end
---[Documentation](https://wow.gamepedia.com/API_C_PetJournal.GetNumMaxPets)
function C_PetJournal.GetNumMaxPets() end
---@return number numSources
---[Documentation](https://wow.gamepedia.com/API_C_PetJournal.GetNumPetSources)
function C_PetJournal.GetNumPetSources() end
---@return number numTypes
---[Documentation](https://wow.gamepedia.com/API_C_PetJournal.GetNumPetTypes)
function C_PetJournal.GetNumPetTypes() end
|
local C = {}
local credits = {
{
department = "CODING",
people = {"NICUSOR NEDELCU", "JOHN DOE", "SUPERMAN"}
},
{
department = "OBJECT ART",
people = {"NICUSOR NEDELCU", "JOHN DOE", "SUPERMAN"}
},
{
department = "SOUNDS",
people = {"NICUSOR NEDELCU", "JOHN DOE", "SUPERMAN"}
}
}
function C:init(gs)
self.gameScreen = gs
self:loadFonts()
self.offset = gfx.videoHeight
end
function C:loadFonts()
self.fntTitle = game:loadFont("fonts/credits_title")
self.fntNormal = game:loadFont("fonts/default")
end
function C:onUpdate(dt)
self.offset = self.offset - dt * 20
end
function C:onRender()
gfx.colorMode = ColorMode_Add
gfx.color = 0
local y = self.offset
for _, v in ipairs(credits) do
local tsize = gfx:getTextSize(self.fntTitle, v.department)
local pos = Vec2((gfx.videoWidth - tsize.x)/2, y)
gfx:drawText(self.fntTitle, pos, v.department)
y = y + tsize.y + 20
for _, name in ipairs(v.people) do
tsize = gfx:getTextSize(self.fntNormal, name)
pos = Vec2((gfx.videoWidth - tsize.x)/2, y)
gfx:drawText(self.fntNormal, pos, name)
y = y + tsize.y + 10
end
end
end
function C:onActivate()
end
function C:onDeactivate()
end
function C:onSerialize(data)
data.gameScreenId = self.gameScreen.id
data.offset = self.offset
end
function C:onDeserialize(data)
self.gameScreen = gameScreenFromId(data.gameScreenId)
self:loadFonts()
self.offset = data.offset
end
return newInstance(C) |
local M = {}
function M.close(id)
vim.validate({id = {id, "number"}})
if not vim.api.nvim_win_is_valid(id) then
return
end
vim.api.nvim_win_close(id, true)
end
function M.enter(id)
vim.validate({id = {id, "number"}})
if not vim.api.nvim_win_is_valid(id) then
return
end
vim.api.nvim_set_current_win(id)
end
return M
|
local promised_ballot_key = KEYS[1] .. '/promise'
local accepted_ballot_key = KEYS[1] .. '/ballot'
local accepted_value_key = KEYS[1] .. '/value'
local function parse_ballot (txt_ballot)
local counter, id = txt_ballot:match("([^,]+),([^,]*)")
local ballot = {}
ballot[0] = tonumber(counter)
ballot[1] = id
return ballot
end
local function cmp_ballots (ballot_a, ballot_b)
if ballot_a[0] < ballot_b[0] then return -1 end
if ballot_b[0] < ballot_a[0] then return 1 end
if ballot_a[1] < ballot_b[1] then return -1 end
if ballot_b[1] < ballot_a[1] then return 1 end
return 0
end
if redis.call('EXISTS', promised_ballot_key) == 0 then
redis.call('SET', promised_ballot_key, "0,")
redis.call('SET', accepted_ballot_key, "0,")
redis.call('SET', accepted_value_key, "")
end
local promised_ballot = parse_ballot(redis.call('GET', promised_ballot_key))
local accepted_ballot = parse_ballot(redis.call('GET', accepted_ballot_key))
local candidate = parse_ballot(KEYS[2])
local promise = parse_ballot(KEYS[4])
if cmp_ballots(candidate, promised_ballot) < 0 then
return {'fail', tostring(promised_ballot[0]) .. "," .. promised_ballot[1] }
end
if cmp_ballots(candidate, accepted_ballot) <= 0 then
return {'fail', tostring(accepted_ballot[0]) .. "," .. accepted_ballot[1] }
end
redis.call('SET', promised_ballot_key, KEYS[4])
redis.call('SET', accepted_ballot_key, KEYS[2])
redis.call('SET', accepted_value_key, KEYS[3])
return {'ok'} |
function HandleSpawnCommand(Split, Player)
local WorldIni = cIniFile()
WorldIni:ReadFile(Player:GetWorld():GetIniFileName())
local SpawnX = WorldIni:GetValue("SpawnPosition", "X")
local SpawnY = WorldIni:GetValue("SpawnPosition", "Y")
local SpawnZ = WorldIni:GetValue("SpawnPosition", "Z")
local flag = 0
if (#Split == 2 and Split[2] ~= Player:GetName()) then
if Player:HasPermission("core.spawn.others") then
local FoundPlayerCallback = function(OtherPlayer)
if (OtherPlayer:GetName() == Split[2]) then
World = OtherPlayer:GetWorld()
local OnAllChunksAvaliable = function()
OtherPlayer:TeleportToCoords(SpawnX, SpawnY, SpawnZ)
SendMessageSuccess( Player, "Returned " .. OtherPlayer:GetName() .. " to world spawn" )
flag=1
end
World:ChunkStay({{SpawnX/16, SpawnZ/16}}, OnChunkAvailable, OnAllChunksAvaliable)
end
end
cRoot:Get():FindAndDoWithPlayer(Split[2], FoundPlayerCallback)
if flag == 0 then
SendMessageFailure( Player, "Player " .. Split[2] .. " not found!" )
end
else
SendMessageFailure( Player, "You need core.spawn.others permission to do that!" )
end
else
World = Player:GetWorld()
local OnAllChunksAvaliable = function()
Player:TeleportToCoords(SpawnX, SpawnY, SpawnZ)
SendMessageSuccess( Player, "Returned to world spawn" )
end
World:ChunkStay({{SpawnX/16, SpawnZ/16}}, OnChunkAvailable, OnAllChunksAvaliable)
end
return true
end
function HandleSetSpawnCommand(Split, Player)
local WorldIni = cIniFile()
WorldIni:ReadFile(Player:GetWorld():GetIniFileName())
local PlayerX = Player:GetPosX()
local PlayerY = Player:GetPosY()
local PlayerZ = Player:GetPosZ()
WorldIni:DeleteValue("SpawnPosition", "X")
WorldIni:DeleteValue("SpawnPosition", "Y")
WorldIni:DeleteValue("SpawnPosition", "Z")
WorldIni:SetValue("SpawnPosition", "X", PlayerX)
WorldIni:SetValue("SpawnPosition", "Y", PlayerY)
WorldIni:SetValue("SpawnPosition", "Z", PlayerZ)
WorldIni:WriteFile(Player:GetWorld():GetIniFileName())
SendMessageSuccess( Player, string.format("Changed spawn position to [X:%i Y:%i Z:%i]", PlayerX, PlayerY, PlayerZ) )
return true
end
|
function ConstructSVGName(scriptName, suffix)
local filename = scriptName:match("Gen(.*)%.lua");
if(suffix) then
return filename .. suffix .. ".svg";
end
return filename .. ".svg";
end
function StandardArrowheadPath()
local arrowheadPath = SvgWriter.Path();
arrowheadPath:M{10, 4}:L{0, 0}:L{0, 8}:Z();
return arrowheadPath;
end
function WriteStandardArrowhead(writer, name, styles)
writer:BeginMarker({10, 8}, {10, 4}, "auto", true, nil, name);
writer:Path(StandardArrowheadPath(), styles);
writer:EndMarker();
end
function WriteTipArrowhead(writer, name, styles)
writer:BeginMarker({10, 8}, {0, 4}, "auto", true, nil, name);
writer:Path(StandardArrowheadPath(), styles);
writer:EndMarker();
end
|
local INV255 = 1.0 / 255.0
COLOR_RED = color_rgba2hex(1, 0, 0, 1)
COLOR_GRAY = color_rgba2hex(0.2, 0.2, 0.2, 1)
|
--- === cp.highland2 ===
---
--- Highland 2 support.
local require = require
local class = require "middleclass"
local lazy = require "cp.lazy"
local delegator = require "cp.delegator"
local tools = require "cp.tools"
local app = require "cp.highland2.app"
local Document = require "cp.highland2.Document"
local tableFilter = tools.tableFilter
local highland2 = class("cp.highland2")
:include(lazy)
:include(delegator)
:delegateTo("app", "menu")
function highland2.lazy.value.app()
return app
end
--- cp.highland2.focusedDocument <cp.prop: cp.highland2.Document>
--- Field
--- The currently-focused [Document](cp.highland2.Document.md), if applicable.
function highland2.lazy.prop:focusedDocument()
return self.app.focusedWindow:mutate(function(original)
local window = original()
if window and window:isInstanceOf(Document) then
return window
end
end)
end
--- cp.highland2.documents <cp.prop: table of cp.highland2.Document>
--- Field
--- The list of [Documents](cp.highland2.Document.md) currently open.
function highland2.lazy.prop:documents()
return self.app.windows:mutate(function(original)
local windows = original()
if windows then
tableFilter(windows, function(t, i)
return t[i]:isInstanceOf(Document)
end)
end
return windows
end)
end
return highland2() |
require('luacov')
local pcall = pcall
local date = os.date
local remove = os.remove
local open = io.open
local assert = require('assert')
local function truncate(filename)
local f = assert(open(filename, 'w'))
f:close()
end
local function test_eval()
local testfile = date('%FT%H%M%S%Z') .. '_test.lua'
local inlinefile = date('%FT%H%M%S%Z') .. '.lua'
local ftest = assert(open(testfile, 'w'))
local finline = assert(open(inlinefile, 'w'))
ftest:setvbuf('no')
finline:setvbuf('no')
local ok, err = pcall(function()
local eval = require('testcase.eval')
local registry = require('testcase.registry')
-- test that eval a file with suffix '_test.lua'
registry.clear()
assert(eval('example/example_test.lua'))
local list, nfunc = registry.getlist()
assert.equal(#list, 1)
assert.equal(nfunc, 2)
assert.equal(list[1].name, 'example/example_test.lua')
-- test that eval a file contains inline option
registry.clear()
assert(eval('example/example_inline.lua'))
list, nfunc = registry.getlist()
assert.equal(#list, 1)
assert.equal(nfunc, 2)
assert.equal(list[1].name, 'example/example_inline.lua')
-- test that returns true if no inline option defined
registry.clear()
assert(eval(inlinefile))
assert.empty(registry.getlist())
-- test that no test functions are registered
registry.clear()
finline:seek('set', 0)
assert(finline:write([[-- lua-testcase: false]]))
assert(eval(inlinefile))
truncate(inlinefile)
assert.empty(registry.getlist())
-- test that returns error with non exits test file
local ok, err = eval('no_file_test.lua')
assert(not ok, 'eval() returns true')
assert.match(err, 'cannot .+ no_file_test.lua', false)
-- test that returns error with non exits inline file
ok, err = eval('no_file_inline.lua')
assert(not ok, 'eval() returns true')
assert.match(err, 'such file')
-- test that returns error with eval an invalid test file
assert(ftest:seek('set', 0))
assert(ftest:write([[x = nil + 1]]))
ok, err = eval(testfile)
assert(not ok, 'eval() returns true')
assert.match(err, 'arithmetic on a nil value')
-- test that returns invalid option value error
finline:seek('set', 0)
assert(finline:write([[-- lua-testcase: foo]]))
ok, err = eval(inlinefile)
truncate(inlinefile)
assert(not ok, 'eval() returns true')
assert.match(err, 'invalid inline option')
-- test that returns invalid option value error
for _, v in ipairs({
'-- lua-testcase: true',
'\n\n-- lua-testcase: true\n\n',
'\n-- lua-testcase: true\n\nlocal testcase = {}',
'--lua-testcase: true\nlocal testcase',
}) do
finline:seek('set', 0)
assert(finline:write(v))
ok, err = eval(inlinefile)
truncate(inlinefile)
assert(not ok, 'eval() returns true')
assert.match(err, 'placeholder .+ not declared at the next line',
false)
end
-- test that cannot inline option defined twice
finline:seek('set', 0)
assert(finline:write([[
--lua-testcase:true
local testcase = {}
-- lua-testcase: true
]]))
ok, err = eval(inlinefile)
truncate(inlinefile)
assert(not ok, 'eval() returns true')
assert.match(err, 'its already defined in lineno', false)
end)
for filename, f in pairs({
[testfile] = ftest,
[inlinefile] = finline,
}) do
f:close()
assert(remove(filename))
end
assert(ok, err)
end
test_eval()
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.