content
stringlengths
0
1.05M
origin
stringclasses
2 values
type
stringclasses
2 values
local utils = require('libs.utils') local g = {} function g:find_nearby_targets(x, z, is_alien) local targets = {} local distance = 1 for i = 1, #self.units do local u = self.units[i] if u.is_alien == is_alien and math.abs(u.x - x) <= distance and math.abs(u.z - z) <= distance then table.insert(targets, u) end end for i = 1, #self.buildings do local b = self.buildings[i] if b.is_alien == is_alien and math.abs(b.x - x) <= distance and math.abs(b.z - z) <= distance then table.insert(targets, b) end end if #targets > 0 then return targets end end function g:find_humans() local targets = {} for i = 1, #self.units do local u = self.units[i] if not u.is_alien then table.insert(targets, u) end end for i = 1, #self.buildings do local b = self.buildings[i] if not b.is_alien then table.insert(targets, b) end end if #targets > 0 then return targets end end function g:find_free_spot_around(around_x, around_z, is_alien) local spots = { true, true, true, true, true, true, true, true, true } for dx = -1, 1 do for dz = -1, 1 do local x = utils.clamp(around_x + dx, 0, self.map_width) local z = utils.clamp(around_z + dz, 0, self.map_height) local value = self.ground[x + (z - 1) * self.map_width] if value == 0 then spots[dx + 2 + (dz + 1) * 3] = false end end end for i = 1, #self.units do local u = self.units[i] local dx, dz = u.x - around_x, u.z - around_z if math.abs(dx) <= 1 and math.abs(dz) <= 1 then spots[dx + 2 + (dz + 1) * 3] = false end end for i = 1, #self.buildings do local b = self.buildings[i] local dx, dz = b.x - around_x, b.z - around_z if math.abs(dx) <= 1 and math.abs(dz) <= 1 then spots[dx + 2 + (dz + 1) * 3] = false end end local human_spots = {8, 7, 9, 4, 6, 2, 1, 3} local alien_spots = {2, 1, 3, 4, 6, 8, 7, 9} for j = 1, 8 do local i = is_alien and alien_spots[j] or human_spots[j] if spots[i] then local dx, dz = (i - 1) % 3 - 1, math.floor((i - 1) / 3) - 1 return around_x + dx, around_z + dz end end end function g:update_ai() for i = 1, #self.units do local u = self.units[i] if not u.is_moving then if u.target and not u.prefered_target then local distance = 1 -- Check if target is alive. if u.target.health == 0 then u.target = nil -- Check if target has moved away. elseif math.abs(u.target.x - u.x) > distance or math.abs(u.target.z - u.z) > distance then u.target = nil end else -- Check for nearby enemy. local targets = self:find_nearby_targets(u.x, u.z, not u.is_alien) if targets then if u.prefered_target then for j = 1, #targets do if targets[j] == u.prefered_target then u.target = u.prefered_target break end end u.prefered_target = nil end if not u.target then u.target = targets[math.random(1, #targets)] end elseif u.is_alien and math.random() < 0.01 then -- Move somewhere. local targets = self:find_humans() if targets then local target = targets[math.random(1, #targets)] u.prefered_target = target self:move_unit(u, target.x, target.z) end end end end end for i = 1, #self.buildings do local b = self.buildings[i] if b.action then if self.current_time >= b.last_action_time + b.cooldown then b.last_action_time = self.current_time if b.action.spawn then local x, z = self:find_free_spot_around(b.x, b.z, b.is_alien) if x then self:spawn_unit{name = b.action.spawn, x = x, z = z} end elseif b.action.is_click then self:click_resources() end end end end end return g
nilq/small-lua-stack
null
require("prototypes.item.combat-roboport") require("prototypes.item.area-defense-robot")
nilq/small-lua-stack
null
-- -*- coding: utf-8 -*- ------------------------------------------------------------------------ -- Copyright © 2011-2015, RedJack, LLC. -- All rights reserved. -- -- Please see the COPYING file in this distribution for license details. ------------------------------------------------------------------------ local AC = require "avro.c" local ACC = require "avro.constants" local AS = require "avro.schema" local AW = require "avro.wrapper" local pairs = pairs local print = print local setmetatable = setmetatable local string = string local avro = require "avro.module" ------------------------------------------------------------------------ -- Constants for k,v in pairs(ACC) do if string.sub(k,1,1) ~= "_" then avro[k] = v end end ------------------------------------------------------------------------ -- Copy a bunch of public functions from the submodules. avro.ArraySchema = AS.ArraySchema avro.EnumSchema = AS.EnumSchema avro.FixedSchema = AS.FixedSchema avro.LinkSchema = AS.LinkSchema avro.MapSchema = AS.MapSchema avro.RecordSchema = AS.RecordSchema avro.Schema = AS.Schema avro.UnionSchema = AS.UnionSchema avro.ResolvedReader = AC.ResolvedReader avro.ResolvedWriter = AC.ResolvedWriter avro.open = AC.open avro.raw_decode_value = AC.raw_decode_value avro.raw_encode_value = AC.raw_encode_value avro.raw_value = AC.raw_value avro.wrapped_value = AC.wrapped_value avro.get_wrapper_class = AW.get_wrapper_class avro.set_wrapper_class = AW.set_wrapper_class avro.Wrapper = AW.Wrapper avro.ArrayValue = AW.ArrayValue avro.CompoundValue = AW.CompoundValue avro.LongValue = AW.LongValue avro.MapValue = AW.MapValue avro.RecordValue = AW.RecordValue avro.ScalarValue = AW.ScalarValue avro.StringValue = AW.StringValue avro.UnionValue = AW.UnionValue avro.boolean = AS.boolean avro.bytes = AS.bytes avro.double = AS.double avro.float = AS.float avro.int = AS.int avro.long = AS.long avro.null = AS.null avro.string = AS.string -- need the _M b/c we import Lua's string above avro.array = AS.array avro.enum = AS.enum avro.fixed = AS.fixed avro.link = AS.link avro.map = AS.map avro.record = AS.record avro.union = AS.union return avro
nilq/small-lua-stack
null
a = "hejsan" b = "yaah" if a < b then print("Yeah.") end print("-----") qu = { z = 1 } function qu:foo(a) print("yeah: "..a) end function qu_foo(a) qu:foo(a) end functions = { qu_foo } functions[table.getn(functions)]("gargh!antuan") print("-----") LowserView = { currentIndex = 1, status = "Welcome to Lowser! (c) nCoder 2005, ncoder.nevyn.nu", res = { genericFolderIcon = "yeah" }, colors = { bg = 1, text = 2 }, contents = {}, cwd = "" } function LowserView:new() -- This is just a copypaste of Shines code... c = {} setmetatable(c, self) self.__index = self --for i, v in ipairs(self) do return c end function LowserView:cd(newdir) self.currentIndex = 1 self.cwd = newdir end foo = LowserView:new() foo:cd("kuoo") bar = LowserView:new() bar:cd("kaah") print(foo.cwd) print(bar.cwd)
nilq/small-lua-stack
null
-- Automatically generated, do not edit! -- Source: addons:zip:The Earth Strikes Back!/tesb-weather.dfcom.lua -- Asserts a specific weather type in the presence of a creature. --[=[ arguments -creature <CREATURE_TOKEN> The creature type to watch for, mandatory -weather rain|snow|clear The weather to force, defaults to "rain" Made by Dirst for use in The Earth Strikes Back mod --]=] local utils=require 'utils' local validArgs = validArgs or utils.invert({ 'help', 'creature', 'weather', }) local args = utils.processArgs({...}, validArgs) if args.help then print([[ Asserts a specific weather type in the presence of a creature. arguments -creature <CREATURE_TOKEN> The creature type to watch for, mandatory -weather rain|snow|clear The weather to force, defaults to "rain" -help Display this help message ]]) return end local weather_name = args.weather or "rain" local target_weather = 0 if weather_name ~= "rain" and weather_name ~= "snow" and weather_name ~= "clear" then qerror("Weather must be rain, snow or clear.") else if weather_name == "rain" then target_weather = 1 end if weather_name == "snow" then target_weather = 2 end end local function findRace(name) for k,v in pairs(df.global.world.raws.creatures.all) do if v.creature_id==name then return k end end qerror("Race:"..name.." not found!") end critter = findRace(args.creature) function checkForCreature() for k,v in ipairs(df.global.world.units.active) do if v.race == critter and dfhack.world.ReadCurrentWeather() ~= target_weather then dfhack.world.SetCurrentWeather(target_weather) end end end require('repeat-util').scheduleEvery('onAction',10,'ticks',checkForCreature)
nilq/small-lua-stack
null
-- serialization local serpent = require'serpent' local function serialize(...) return serpent.line({...}, {comment=false}) end local m = {} m.__index = m m.editors = {} m.loaded_fonts = {} m.focused = nil m.plugin_callbacks = {} -- the general channel is used to communicate instance name to its thread m.general_channel = lovr.thread.getChannel('lite-editors') -- create an editor instance function m.new() local self = setmetatable({}, m) self.name = 'lite-editor-' .. tostring(#m.editors + 1) self.size = {1000, 1000} self.current_frame = {} self.pose = lovr.math.newMat4() self:center() -- start the editor thread and set up the communication channels local threadcode = lovr.filesystem.read('litethread.lua') self.thread = lovr.thread.newThread(threadcode) self.thread:start() m.general_channel:push(serialize('new_thread', self.name)) -- announce self.outbount_channel = lovr.thread.getChannel(string.format('%s-events', self.name)) self.inbound_channel = lovr.thread.getChannel(string.format('%s-render', self.name)) table.insert(m.editors, self) m.set_focus(#m.editors) -- set focus to newly created editor instance return self end function m.set_focus(editorindex) m.focused = editorindex for i, editor in ipairs(m.editors) do editor.outbount_channel:push(serialize('set_focus', i == m.focused)) end end --------- keyboard handling --------- local function expand_key_names(key) if key:sub(1, 2) == "kp" then return "keypad " .. key:sub(3) end if key:sub(2) == "ctrl" or key:sub(2) == "shift" or key:sub(2) == "alt" or key:sub(2) == "gui" then if key:sub(1, 1) == "l" then return "left " .. key:sub(2) end return "right " .. key:sub(2) end return key end function m.keypressed(key, scancode, rpt) if m.editors[m.focused] then m.editors[m.focused].outbount_channel:push(serialize('keypressed', expand_key_names(key))) end end function m.keyreleased(key, scancode) if m.editors[m.focused] then m.editors[m.focused].outbount_channel:push(serialize('keyreleased', expand_key_names(key))) end end function m.textinput(text, code) if m.editors[m.focused] then m.editors[m.focused].outbount_channel:push(serialize('textinput', text)) end end --------- callbacks for all instances --------- function m.update() for plugin_name, callbacks in pairs(m.plugin_callbacks) do if callbacks.update then callbacks.update() end end for i, instance in ipairs(m.editors) do instance:update_instance() end end -- needs to be called last in draw order because drawing doesn't write to depth buffer function m.draw() for plugin_name, callbacks in pairs(m.plugin_callbacks) do if callbacks.draw then callbacks.draw() end end for i, instance in ipairs(m.editors) do instance:draw_instance() end end -- error handler that ensures the editor survives user app errors in order to be able to fix them -- should be assigned to lovr.errhand early in execution, to catch as many errors function m.errhand(message, traceback) traceback = traceback or debug.traceback('', 4) for _, instance in ipairs(m.editors) do instance.outbount_channel:push(serialize('lovr_error_message', message, traceback)) end lovr.graphics.setBackgroundColor(0x14162c) lovr.draw = m.draw lovr.update = m.update return function() -- a minimal lovr run loop, with lite still working lovr.event.pump() local dt = lovr.timer.step() for name, a, b, c, d in lovr.event.poll() do if name == 'quit' then return a or 1 elseif name == 'restart' then return 'restart' elseif lovr.handlers[name] then lovr.handlers[name](a, b, c, d) end end lovr.graphics.origin() if lovr.headset then lovr.headset.update(dt) lovr.headset.renderTo(m.draw) end lovr.update() if lovr.graphics.hasWindow() then lovr.mirror() end lovr.graphics.present() lovr.math.drain() end end -- inserts all important functions into callback chain, so they don't have to be called manually -- needs to be called at the end of `main.lua` once user app functions are already defined function m.inject_callbacks() local chained_callbacks = {'keypressed', 'keyreleased', 'textinput', 'update', 'draw'} local stored_cb = {} for _, cb in ipairs(chained_callbacks) do stored_cb[cb] = lovr[cb] end -- inject this module's cb after original callback is called for _, cb in ipairs(chained_callbacks) do lovr[cb] = function(...) if stored_cb[cb] then stored_cb[cb](...) -- call user app callback end m[cb](...) -- call own callback end end end --------- inbound event handlers --------- m.event_handlers = { begin_frame = function(self) lovr.graphics.setDepthTest('lequal', false) end, end_frame = function(self) last_time = lovr.timer.getTime() lovr.graphics.setDepthTest('lequal', true) lovr.graphics.setStencilTest() end, set_litecolor = function(self, r, g, b, a) lovr.graphics.setColor(r, g, b, a) end, set_clip_rect = function(self, x, y, w, h) lovr.graphics.stencil( function() lovr.graphics.plane("fill", x + w/2, -y - h/2, 0, w, h) end) lovr.graphics.setStencilTest('greater', 0) end, draw_rect = function(self, x, y, w, h) local cx = x + w/2 local cy = -y - h/2 lovr.graphics.plane( "fill", cx, cy, 0, w, h) end, draw_text = function(self, text, x, y, filename, size) local fontname = string.format('%q:%d', filename, size) local font = m.loaded_fonts[fontname] if not font then font = lovr.graphics.newFont(filename, size) font:setPixelDensity(1) m.loaded_fonts[fontname] = font end lovr.graphics.setFont(font) lovr.graphics.print(text, x, -y, 0, 1, 0, 0,1,0, nil, 'left', 'top') end, register_plugin = function(self, plugin_name, plugin_callbacks) local was_already_registered = not not m.plugin_callbacks[plugin_name] m.plugin_callbacks[plugin_name] = plugin_callbacks if not was_already_registered then for event, handler_fn in pairs(plugin_callbacks or {}) do if event == 'load' then plugin_callbacks.load(self) else m.event_handlers[event] = handler_fn end end end end, } --------- per-instance methods --------- function m:draw_instance() lovr.graphics.push() lovr.graphics.transform(self.pose) lovr.graphics.scale(1 / 1000)--math.max(self.size[1], self.size[2])) lovr.graphics.translate(-self.size[1] / 2, self.size[2] / 2) for i, draw_call in ipairs(self.current_frame) do local fn = m.event_handlers[draw_call[1]] fn(self, select(2, unpack(draw_call))) end lovr.graphics.pop() end function m:update_instance() local req_str = self.inbound_channel:pop(false) if req_str then local ok, current_frame = serpent.load(req_str, {safe = false}) if ok then self.current_frame = current_frame end end end function m:resize(width, height) self.size = {width, height} self.outbount_channel:push(serialize('resize', width, height)) end function m:center() if not lovr.headset then self.pose:set(-0, 0, -0.8) else local headpose = mat4(lovr.headset.getPose()) local headpos = vec3(headpose) local pos = vec3(headpose:mul(0, 0, -0.7)) self.pose:target(pos, headpos) self.pose:rotate(math.pi, 0,1,0) end end return m
nilq/small-lua-stack
null
--[[ © CloudSixteen.com do not share, re-distribute or modify without permission of its author ([email protected]). Clockwork was created by Conna Wiles (also known as kurozael.) http://cloudsixteen.com/license/clockwork.html --]] CW_KOREAN = Clockwork.lang:GetTable("Korean"); CW_KOREAN["AreaDisplayRemoved"] = "당신은 성공적으로 #1 개의 구역 디스플레이를 제거했습니다."; CW_KOREAN["AreaDisplayAdded"] = "당신은 성공적으로 '#1' 구역 디스플레이를 추가하였습니다."; CW_KOREAN["AreaDisplayMinimum"] = "최저 점을 추가하였고, 최대점을 추가하십시요."; CW_KOREAN["AreaDisplayMaximum"] = "최대 점을 추가하였고, 구역 디스플레이가 정상적으로 생성되었습니다."; CW_KOREAN["AreaDisplayNoneNearPosition"] = "주변에 구역 디스플레이가 존재하지 않습니다!"; CW_KOREAN["EnableAreaDisplay"] = "구역 디스플레이 활성화"; CW_KOREAN["EnableAreaDisplayDesc"] = "특정한 구역에 진입할 때 구역의 이름을 표기할지에 대한 여부입니다.";
nilq/small-lua-stack
null
-- ---------------------------------------------------- -- tcbn_delete.lua -- -- Sep/14/2010 -- ---------------------------------------------------- print ("*** 開始 ***") file_in=arg[1] id_in=arg[2] print (id_in) require("tokyocabinet") -- create the object bdb = tokyocabinet.bdbnew() -- open the database if not bdb:open(file_in, bdb.OWRITER + bdb.OCREAT) then ecode = bdb:ecode() print("open error: " .. bdb:errmsg(ecode)) end -- table-like usage for key, value in bdb:pairs() do if (key == id_in) then bdb:out (key) end end -- close the database if not bdb:close() then ecode = bdb:ecode() print("close error: " .. bdb:errmsg(ecode)) end print ("*** 終了 ***") -- ----------------------------------------------------
nilq/small-lua-stack
null
local hsluv = require("lush").hsluv -- stylua: ignore start ---@class LaserwaveColors local colors = { WHITE = hsluv("#ffffff"), -- Foreground, Variables RAISIN_BLACK = hsluv("#27212e"), -- Background OLD_LAVENDER = hsluv("#91889b"), -- Comments, Hints HOT_PINK = hsluv("#eb64B9"), -- Functions, Attributes, Highlighting PEARL_AQUA = hsluv("#74dfc4"), -- Operators, Tags MUSTARD = hsluv("#ffe261"), -- Builtins, Constants MAXIMUM_BLUE = hsluv("#40b4c4"), -- Keywords, Properties, Info AFRICAN_VIOLET = hsluv("#b381c5"), -- Numbers, Types POWDER_BLUE = hsluv("#b4dce7"), -- Strings ROMAN_SILVER = hsluv("#7b6995"), -- Gutter, Ignored VIVID_RASPBERRY = hsluv("#ff3e7b"), -- Errors GARDENIA = hsluv("#ffb85b"), -- Warnings } ---@class LaserwaveSemantics local semantics = { FG = colors.WHITE, BG = colors.RAISIN_BLACK, GUTTER = colors.ROMAN_SILVER, HIGHLIGHT = colors.HOT_PINK, VARIABLE = colors.WHITE, COMMENT = colors.OLD_LAVENDER, FUNCTION = colors.HOT_PINK, OPERATOR = colors.PEARL_AQUA, CONSTANT = colors.MUSTARD, KEYWORD = colors.MAXIMUM_BLUE, NUMBER = colors.AFRICAN_VIOLET, TYPE = colors.AFRICAN_VIOLET, STRING = colors.POWDER_BLUE, ERROR = colors.VIVID_RASPBERRY, WARNING = colors.GARDENIA, IGNORE = colors.ROMAN_SILVER, INFO = colors.MAXIMUM_BLUE, HINT = colors.OLD_LAVENDER, ADD = colors.MAXIMUM_BLUE, DELETE = colors.HOT_PINK, CHANGE = colors.GARDENIA, CONFLICT = colors.VIVID_RASPBERRY, NORMAL = colors.MAXIMUM_BLUE, INSERT = colors.PEARL_AQUA, COMMAND = colors.MUSTARD, VISUAL = colors.AFRICAN_VIOLET, REPLACE = colors.HOT_PINK, INACTIVE = colors.ROMAN_SILVER, } -- stylua: ignore end ---@class LaserwaveColors : LaserwaveSemantics ---@field colors LaserwaveColors ---@field semantics LaserwaveSemantics local M = { colors = colors, semantics = semantics, } M = vim.tbl_extend("error", M, colors, semantics) return M
nilq/small-lua-stack
null
add_requires("openmp") target("hello") set_kind("binary") add_files("src/*.c") add_packages("openmp")
nilq/small-lua-stack
null
local Plugin = script.Parent.Parent.Parent.Parent.Parent.Parent.Parent local Libs = Plugin.Libs local Roact = require(Libs.Roact) local ContextGetter = require(Plugin.Core.Util.ContextGetter) local Types = require(Plugin.Core.Util.Types) local getMainManager = ContextGetter.getMainManager local Loop = Roact.PureComponent:extend("Loop") function Loop:init() self.handleRef = Roact.createRef() end function Loop:render() local props = self.props local ZIndex = props.ZIndex local valid = props.valid local color = valid and Color3.new(0, 1, 0) or Color3.new(1, 0, 0) return Roact.createElement( "ViewportFrame", { Size = UDim2.new(1, 0, 1, 0), BackgroundTransparency = 1, BackgroundColor3 = color, ImageColor3 = color, ZIndex = ZIndex, CurrentCamera = workspace.CurrentCamera }, { Handle = Roact.createElement( "Model", { [Roact.Ref] = self.handleRef } ) } ) end function Loop:RenderRope() local handle = self.handleRef.current local props = self.props local hit, p, p2 = props.hit, props.p, props.p2 local shape, offset = props.shape, props.offset if self.ropeModel then self.ropeModel:Destroy() end local mainManager = getMainManager(self) local ropeModel = mainManager:DrawPreset( "PreviewOk", { curveType = Types.Curve.LOOP, shape = shape, hit = hit, p = p, p2 = p2, offset = offset } ) self.ropeModel = ropeModel if ropeModel then ropeModel.Parent = handle end end function Loop:didMount() self:RenderRope() end function Loop:didUpdate() self:RenderRope() end return Loop
nilq/small-lua-stack
null
local PANEL = {} local function TextSize(font, text) surface.SetFont(font) return surface.GetTextSize(text) end function PANEL:Init() local Panel = self self.Font = "ZEDFont40" self.TextColor = Color(210,210,210,255) self.SliderFGColor = Color(210,210,210,255) self.SliderBGColor = Color(100, 100, 100, 255) self.Decimals = true local w,h = TextSize(self.Font, "Slider") self.Label = vgui.Create( "ZLabel", self ) self.Label:SetPos( 0, 0 ) self.Label:SetText( "Slider" ) self.Label:SetColor(self.TextColor) self.Label:SetFont( self.Font ) w = w + 30 self.Slider = vgui.Create( "DSlider", self ) self.Slider:SetPos( w, self:GetTall() * 0.1 ) self.Slider:SetSize( self:GetWide() - w, self:GetTall() * 0.8 ) self.Slider.Min = 0 self.Slider.Max = 100 self.Slider.Value = 50 self.Slider.SlideX = (self.Slider.Value / (self.Slider.Max - self.Slider.Min)) * self.Slider:GetWide() self.Slider.Paint = function() surface.SetDrawColor( self.SliderBGColor ) surface.DrawRect( 0, 0, self.Slider:GetWide(), self.Slider:GetTall() ) surface.SetDrawColor( self.SliderFGColor ) surface.DrawRect( (self.Slider.SlideX or 0) - 5, 0, 10, self.Slider:GetTall() ) end self.Slider.Knob:SetVisible(false) self.Slider.TranslateValues = function( slider, x, y ) Panel.Slider.Value = Panel.Slider.Min + (Panel.Slider.Max - Panel.Slider.Min) * x if Panel.Decimals then Panel.Slider.Value = math.floor(Panel.Slider.Value + 0.5) end Panel.Slider.SlideX = (Panel.Slider.Value / (Panel.Slider.Max - Panel.Slider.Min)) * Panel.Slider:GetWide() if Panel.ValueChanged then Panel:ValueChanged(Panel.Slider.Value) end return -1,-1 end end function PANEL:SetTitle(s) self.Label:SetText(tostring(s)) local w,h = TextSize(self.Font, self:GetTitle()) w = w + 20 self.Slider:SetPos( w, self:GetTall() * 0.1 ) self.Slider:SetSize( self:GetWide() - w, self:GetTall() * 0.8 ) self.Label:SetPos(0, self:GetTall() * 0.5 - h * 0.5) end function PANEL:GetTitle() return self.Label:GetText() end function PANEL:SetFont(s) self.Label:SetFont(tostring(s)) end function PANEL:GetFont() return self.Label:GetFont() end function PANEL:SetMin(v) self.Slider.Min = tonumber(v) or 0 self.Slider.SlideX = (self.Slider.Value / (self.Slider.Max - self.Slider.Min)) * self.Slider:GetWide() end function PANEL:GetMin(v) return self.Slider.Min or 0 end function PANEL:SetValue(v) self.Slider.Value = tonumber(v) or 50 self.Slider.SlideX = (self.Slider.Value / (self.Slider.Max - self.Slider.Min)) * self.Slider:GetWide() end function PANEL:GetValue(v) return self.Slider.Value or 50 end function PANEL:SetMax(v) self.Slider.Max = tonumber(v) or 100 self.Slider.SlideX = (self.Slider.Value / (self.Slider.Max - self.Slider.Min)) * self.Slider:GetWide() end function PANEL:GetMax(v) return self.Slider.Max or 100 end function PANEL:SetSize(w,h) self.BaseClass.SetSize(self, w, h) local w,h = TextSize(self.Font, self:GetTitle()) w = w + 20 self.Slider:SetPos( w, self:GetTall() * 0.1 ) self.Slider:SetSize( self:GetWide() - w, self:GetTall() * 0.8 ) self.Label:SetPos(0, self:GetTall() * 0.5 - h * 0.5) end function PANEL:SetPos(x,y) self.BaseClass.SetPos(self, x, y) local w,h = TextSize(self.Font, self:GetTitle()) w = w + 20 self.Slider:SetPos( w, self:GetTall() * 0.1 ) self.Slider:SetSize( self:GetWide() - w, self:GetTall() * 0.8 ) self.Label:SetPos(0, self:GetTall() * 0.5 - h * 0.5) end function PANEL:Paint() end function PANEL:PerformLayout() self.BaseClass.PerformLayout(self) local w,h = TextSize(self.Font, self:GetTitle()) w = w + 20 self.Slider:SetPos( w, self:GetTall() * 0.1 ) self.Slider:SetSize( self:GetWide() - w, self:GetTall() * 0.8 ) self.Label:SetPos(0, self:GetTall() * 0.5 - h * 0.5) end vgui.Register("ZSlider",PANEL,"DPanel");
nilq/small-lua-stack
null
--[[ ############################################################################## S V U I By: Munglunch ############################################################################## credit: Kemayo. original logic from BankStack. Adapted to SVUI # ############################################################################## ########################################################## LOCALIZED LUA FUNCTIONS ########################################################## (<a href="[^0-9\"]+">) ]]-- --[[ GLOBALS ]]-- local _G = _G; local unpack = _G.unpack; local select = _G.select; local assert = _G.assert; local type = _G.type; local error = _G.error; local pcall = _G.pcall; local print = _G.print; local ipairs = _G.ipairs; local pairs = _G.pairs; local next = _G.next; local tostring = _G.tostring; local tonumber = _G.tonumber; local collectgarbage = _G.collectgarbage; local tinsert = _G.tinsert; local string = _G.string; local math = _G.math; local bit = _G.bit; local table = _G.table; --[[ STRING METHODS ]]-- local gmatch, gsub, match, split = string.gmatch, string.gsub, string.match, string.split; --[[ MATH METHODS ]]-- local floor = math.floor; --[[ BINARY METHODS ]]-- local band = bit.band; --[[ TABLE METHODS ]]-- local tremove, tcopy, twipe, tsort = table.remove, table.copy, table.wipe, table.sort; --BLIZZARD API local CreateFrame = _G.CreateFrame; local InCombatLockdown = _G.InCombatLockdown; local GameTooltip = _G.GameTooltip; local hooksecurefunc = _G.hooksecurefunc; local IsAltKeyDown = _G.IsAltKeyDown; local IsShiftKeyDown = _G.IsShiftKeyDown; local IsControlKeyDown = _G.IsControlKeyDown; local IsModifiedClick = _G.IsModifiedClick; local RAID_CLASS_COLORS = _G.RAID_CLASS_COLORS; local CUSTOM_CLASS_COLORS = _G.CUSTOM_CLASS_COLORS; local C_PetJournal = _G.C_PetJournal; local GetTime = _G.GetTime; local GetContainerNumSlots = _G.GetContainerNumSlots; local GetGuildBankTabInfo = _G.GetGuildBankTabInfo; local GetItemFamily = _G.GetItemFamily; local GetGuildBankItemInfo = _G.GetGuildBankItemInfo; local GetContainerItemInfo = _G.GetContainerItemInfo; local GetGuildBankItemLink = _G.GetGuildBankItemLink; local GetContainerItemLink = _G.GetContainerItemLink; local GetItemInfo = _G.GetItemInfo; local GetItemCount = _G.GetItemCount; local GetItemQualityColor = _G.GetItemQualityColor; local GetCursorInfo = _G.GetCursorInfo; local PickupGuildBankItem = _G.PickupGuildBankItem; local PickupContainerItem = _G.PickupContainerItem; local QueryGuildBankTab = _G.QueryGuildBankTab; local GetInventoryItemLink = _G.GetInventoryItemLink; local SplitGuildBankItem = _G.SplitGuildBankItem; local SplitContainerItem = _G.SplitContainerItem; local ARMOR = _G.ARMOR; local ENCHSLOT_WEAPON = _G.ENCHSLOT_WEAPON; local NUM_BAG_FRAMES = _G.NUM_BAG_FRAMES; local NUM_BAG_SLOTS = _G.NUM_BAG_SLOTS; local NUM_BANKBAGSLOTS = _G.NUM_BANKBAGSLOTS; local BANK_CONTAINER = _G.BANK_CONTAINER; local REAGENTBANK_CONTAINER = _G.REAGENTBANK_CONTAINER; local GetAuctionItemClasses = _G.GetAuctionItemClasses; local GetAuctionItemSubClasses = _G.GetAuctionItemSubClasses; local ContainerIDToInventoryID = _G.ContainerIDToInventoryID; local GetContainerItemID = _G.GetContainerItemID; local GetCurrentGuildBankTab = _G.GetCurrentGuildBankTab; local GetContainerNumFreeSlots = _G.GetContainerNumFreeSlots; --[[ ########################################################## GET ADDON DATA ########################################################## ]]-- local SV = _G['SVUI'] local L = SV.L; local MOD = SV.Inventory; --[[ ########################################################## LOCAL VARS ########################################################## ]]-- local WAIT_TIME = 0.05 local bagGroups = {}; local initialOrder = {}; local bagSorted = {}; local bagLocked = {}; local targetItems = {}; local sourceUsed = {}; local targetSlots = {}; local specialtyBags = {}; local emptySlots = {}; local moveRetries = 0; local moveTracker = {}; local blackListedSlots = {}; local blackList = {}; local lastItemID, lockStop, lastDestination, lastMove, itemTypes, itemSubTypes; local IterateBagsForSorting; local RefEquipmentSlots = { INVTYPE_AMMO = 0, INVTYPE_HEAD = 1, INVTYPE_NECK = 2, INVTYPE_SHOULDER = 3, INVTYPE_BODY = 4, INVTYPE_CHEST = 5, INVTYPE_ROBE = 5, INVTYPE_WAIST = 6, INVTYPE_LEGS = 7, INVTYPE_FEET = 8, INVTYPE_WRIST = 9, INVTYPE_HAND = 10, INVTYPE_FINGER = 11, INVTYPE_TRINKET = 12, INVTYPE_CLOAK = 13, INVTYPE_WEAPON = 14, INVTYPE_SHIELD = 15, INVTYPE_2HWEAPON = 16, INVTYPE_WEAPONMAINHAND = 18, INVTYPE_WEAPONOFFHAND = 19, INVTYPE_HOLDABLE = 20, INVTYPE_RANGED = 21, INVTYPE_THROWN = 22, INVTYPE_RANGEDRIGHT = 23, INVTYPE_RELIC = 24, INVTYPE_TABARD = 25 } local sortingCache = { [1] = {}, --BAG [2] = {}, --ID [3] = {}, --PETID [4] = {}, --STACK [5] = {}, --MAXSTACK [6] = {}, --MOVES } local scanningCache = { ["all"] = {}, ["bags"] = {}, ["bank"] = {BANK_CONTAINER}, ["reagent"] = {REAGENTBANK_CONTAINER}, ["guild"] = {51,52,53,54,55,56,57,58}, } for i = NUM_BAG_SLOTS + 1, (NUM_BAG_SLOTS + NUM_BANKBAGSLOTS), 1 do tinsert(scanningCache.bank, i) end for i = 0, NUM_BAG_SLOTS do tinsert(scanningCache.bags, i) end for _,i in ipairs(scanningCache.bags) do tinsert(scanningCache.all, i) end for _,i in ipairs(scanningCache.bank) do tinsert(scanningCache.all, i) end for _,i in ipairs(scanningCache.reagent) do tinsert(scanningCache.all, i) end for _,i in ipairs(scanningCache.guild) do tinsert(scanningCache.all, i) end --[[ ########################################################## SORTING UPDATES HANDLER ########################################################## ]]-- local SortUpdateTimer = CreateFrame("Frame") SortUpdateTimer.timeLapse = 0 SortUpdateTimer:Hide() --[[ ########################################################## HELPERS ########################################################## ]]-- local function ValidateBag(bagid) return (bagid == BANK_CONTAINER or ((bagid >= 0) and bagid <= (NUM_BAG_SLOTS + NUM_BANKBAGSLOTS))) end local function ValidateBank(bagid) return (bagid == BANK_CONTAINER or bagid == REAGENTBANK_CONTAINER or (bagid > NUM_BAG_SLOTS and bagid <= NUM_BANKBAGSLOTS)) end local function ValidateGuildBank(bagid) return (bagid > 50 and bagid <= 58) end local function BagEncoder(bag, slot) return (bag * 100) + slot end local function BagDecoder(int) return math.floor(int / 100), int % 100 end local function MoveEncoder(source, target) return (source * 10000) + target end local function MoveDecoder(move) local s = math.floor(move / 10000) local t = move % 10000 s = (t > 9000) and (s + 1) or s t = (t > 9000) and (t - 10000) or t return s, t end --[[ ########################################################## LOCAL FUNCTIONS ########################################################## ]]-- local function SetCacheBlacklist(...) twipe(blackList) for index = 1, select('#', ...) do local name = select(index, ...) local isLink = GetItemInfo(name) if isLink then blackList[isLink] = true end end end local function BuildSortOrder() itemTypes = {} itemSubTypes = {} for i, iType in ipairs({GetAuctionItemClasses()}) do itemTypes[iType] = i itemSubTypes[iType] = {} for ii, isType in ipairs({GetAuctionItemSubClasses(i)}) do itemSubTypes[iType][isType] = ii end end end local function UpdateLocation(from, to) if (sortingCache[2][from] == sortingCache[2][to]) and (sortingCache[4][to] < sortingCache[5][to]) then local stackSize = sortingCache[5][to] if (sortingCache[4][to] + sortingCache[4][from]) > stackSize then sortingCache[4][from] = sortingCache[4][from] - (stackSize - sortingCache[4][to]) sortingCache[4][to] = stackSize else sortingCache[4][to] = sortingCache[4][to] + sortingCache[4][from] sortingCache[4][from] = nil sortingCache[2][from] = nil sortingCache[5][from] = nil end else sortingCache[2][from], sortingCache[2][to] = sortingCache[2][to], sortingCache[2][from] sortingCache[4][from], sortingCache[4][to] = sortingCache[4][to], sortingCache[4][from] sortingCache[5][from], sortingCache[5][to] = sortingCache[5][to], sortingCache[5][from] end end local function PrimarySort(a, b) local aName, _, _, aLvl, _, _, _, _, _, _, aPrice = GetItemInfo(sortingCache[2][a]) local bName, _, _, bLvl, _, _, _, _, _, _, bPrice = GetItemInfo(sortingCache[2][b]) if aLvl ~= bLvl and aLvl and bLvl then return aLvl > bLvl end if aPrice ~= bPrice and aPrice and bPrice then return aPrice > bPrice end if aName and bName then return aName < bName end end local function DefaultSort(b, a) local aID = sortingCache[2][a] local bID = sortingCache[2][b] if (not aID) or (not bID) then return aID end if sortingCache[3][a] and sortingCache[3][b] then local aName, _, aType = C_PetJournal.GetPetInfoBySpeciesID(aID); local bName, _, bType = C_PetJournal.GetPetInfoBySpeciesID(bID); if aType and bType and aType ~= bType then return aType > bType end if aName and bName and (type(aName) == type(bName)) and aName ~= bName then return aName < bName end end local aOrder, bOrder = initialOrder[a], initialOrder[b] if aID == bID then local aCount = sortingCache[4][a] local bCount = sortingCache[4][b] if aCount and bCount and aCount == bCount then return aOrder < bOrder elseif aCount and bCount then return aCount < bCount end end local _, _, aRarity, _, _, aType, aSubType, _, aEquipLoc = GetItemInfo(aID) local _, _, bRarity, _, _, bType, bSubType, _, bEquipLoc = GetItemInfo(bID) if sortingCache[3][a] then aRarity = 1 end if sortingCache[3][b] then bRarity = 1 end if aRarity ~= bRarity and aRarity and bRarity then return aRarity > bRarity end if itemTypes[aType] ~= itemTypes[bType] then return (itemTypes[aType] or 99) < (itemTypes[bType] or 99) end if aType == ARMOR or aType == ENCHSLOT_WEAPON then local aEquipLoc = RefEquipmentSlots[aEquipLoc] or -1 local bEquipLoc = RefEquipmentSlots[bEquipLoc] or -1 if aEquipLoc == bEquipLoc then return PrimarySort(a, b) end if aEquipLoc and bEquipLoc then return aEquipLoc < bEquipLoc end end if aSubType == bSubType then return PrimarySort(a, b) end return ((itemSubTypes[aType] or {})[aSubType] or 99) < ((itemSubTypes[bType] or {})[bSubType] or 99) end local function ReverseSort(a, b) return DefaultSort(b, a) end local function ConvertLinkToID(link) if not link then return; end if tonumber(match(link, "item:(%d+)")) then return tonumber(match(link, "item:(%d+)")); else return tonumber(match(link, "battlepet:(%d+)")), true; end end local function GetSortingGroup(id) if match(id, "^[-%d,]+$") then local bags = {} for b in gmatch(id, "-?%d+") do tinsert(bags, tonumber(b)) end return bags end return scanningCache[id] end local function GetSortingInfo(bag, slot) if (ValidateGuildBank(bag)) then return GetGuildBankItemInfo(bag - 50, slot) else return GetContainerItemInfo(bag, slot) end end local function GetSortingItemLink(bag, slot) if (ValidateGuildBank(bag)) then return GetGuildBankItemLink(bag - 50, slot) else return GetContainerItemLink(bag, slot) end end --[[ ########################################################## BAG ITERATION METHOD ########################################################## ]]-- do local bagRole; local function GetNumSortingSlots(bag, role) if (ValidateGuildBank(bag)) then if not role then role = "deposit" end local name, icon, canView, canDeposit, numWithdrawals = GetGuildBankTabInfo(bag - 50) if name and canView then return 98 end else return GetContainerNumSlots(bag) end return 0 end local function IterateForwards(bagList, i) i = i + 1 local step = 1 for _,bag in ipairs(bagList) do local slots = GetNumSortingSlots(bag, bagRole) if i > slots + step then step = step + slots else for slot = 1, slots do if step == i then return i, bag, slot end step = step + 1 end end end bagRole = nil end local function IterateBackwards(bagList, i) i = i + 1 local step = 1 for ii = #bagList, 1, -1 do local bag = bagList[ii] local slots = GetNumSortingSlots(bag, bagRole) if i > slots + step then step = step + slots else for slot=slots, 1, -1 do if step == i then return i, bag, slot end step = step + 1 end end end bagRole = nil end function IterateBagsForSorting(bagList, reverse, role) bagRole = role return (reverse and IterateBackwards or IterateForwards), bagList, 0 end end --[[ ########################################################## CORE FUNCTIONS ########################################################## ]]-- -- function MOD.Compress(...) -- for i=1, select("#", ...) do -- local bags = select(i, ...) -- MOD.Stack(bags, bags, MOD.IsPartial) -- end -- end -- function MOD.Organizer(fnType, sourceBags, targetBags) -- if(fnType == 'stack') then -- MOD.Stack(sourceBags, targetBags, MOD.IsPartial) -- elseif(fnType == 'move') then -- MOD.Stack(sourceBags, targetBags, MOD.IsPartial) -- else -- MOD.Sort() -- end -- end --[[ ########################################################## EXTERNAL SORTING CALLS ########################################################## ]]-- do local function SetSortingPath(source, target) UpdateLocation(source, target) tinsert(sortingCache[6], 1, (MoveEncoder(source, target))) end local function IsPartial(bag, slot) local bagSlot = BagEncoder(bag, slot) return ((sortingCache[5][bagSlot] or 0) - (sortingCache[4][bagSlot] or 0)) > 0 end local function IsSpecialtyBag(bagID) if(bagID == 0 or (ValidateBank(bagID)) or (ValidateGuildBank(bagID))) then return false end local inventorySlot = ContainerIDToInventoryID(bagID) if not inventorySlot then return false end local bag = GetInventoryItemLink("player", inventorySlot) if not bag then return false end local family = GetItemFamily(bag) if family == 0 or family == nil then return false end return family end local function CanItemGoInBag(bag, slot, targetBag) if (ValidateGuildBank(targetBag)) then return true end local item = sortingCache[2][(BagEncoder(bag, slot))] local itemFamily = GetItemFamily(item) if itemFamily and itemFamily > 0 then local equipSlot = select(9, GetItemInfo(item)) if equipSlot == "INVTYPE_BAG" then itemFamily = 1 end end local bagFamily = select(2, GetContainerNumFreeSlots(targetBag)) if itemFamily then return (bagFamily == 0) or band(itemFamily, bagFamily) > 0 else return false; end end local function ShouldMove(source, destination) if((destination == source) or (not sortingCache[2][source])) then return; end if((sortingCache[2][source] == sortingCache[2][destination]) and (sortingCache[4][source] == sortingCache[4][destination])) then return; end return true end local function UpdateSorted(source, destination) for i, bs in pairs(bagSorted) do if bs == source then bagSorted[i] = destination elseif bs == destination then bagSorted[i] = source end end end local function Sorter(bags, sorter, reverse) if not sorter then sorter = reverse and ReverseSort or DefaultSort end if not itemTypes then BuildSortOrder() end twipe(blackListedSlots) local ignoreItems = SV.db.Inventory.ignoreItems ignoreItems = ignoreItems:gsub(',%s', ',') SetCacheBlacklist(split(",", ignoreItems)) for i, bag, slot in IterateBagsForSorting(bags, nil, 'both') do local bagSlot = BagEncoder(bag, slot) local link = GetSortingItemLink(bag, slot); if link and blackList[GetItemInfo(link)] then blackListedSlots[bagSlot] = true end if not blackListedSlots[bagSlot] then initialOrder[bagSlot] = i tinsert(bagSorted, bagSlot) end end tsort(bagSorted, sorter) local passNeeded = true while passNeeded do passNeeded = false local i = 1 for _, bag, slot in IterateBagsForSorting(bags, nil, 'both') do local destination = BagEncoder(bag, slot) local source = bagSorted[i] if not blackListedSlots[destination] then if(ShouldMove(source, destination)) then if not (bagLocked[source] or bagLocked[destination]) then SetSortingPath(source, destination) UpdateSorted(source, destination) bagLocked[source] = true bagLocked[destination] = true else passNeeded = true end end i = i + 1 end end twipe(bagLocked) end twipe(bagSorted) twipe(initialOrder) end local function SortFiller(sourceBags, targetBags, reverse, canMove) if not canMove then canMove = true end for _, bag, slot in IterateBagsForSorting(targetBags, reverse, "deposit") do local bagSlot = BagEncoder(bag, slot) if not sortingCache[2][bagSlot] then tinsert(emptySlots, bagSlot) end end for _, bag, slot in IterateBagsForSorting(sourceBags, not reverse, "withdraw") do if #emptySlots == 0 then break end local bagSlot = BagEncoder(bag, slot) local targetBag, targetSlot = BagDecoder(emptySlots[1]) if sortingCache[2][bagSlot] and CanItemGoInBag(bag, slot, targetBag) and (canMove == true or canMove(sortingCache[2][bagSlot], bag, slot)) then SetSortingPath(bagSlot, tremove(emptySlots, 1)) end end twipe(emptySlots) end function MOD.Sort(...) for i=1, select("#", ...) do local bags = select(i, ...) for _, slotNum in ipairs(bags) do local bagType = IsSpecialtyBag(slotNum) if bagType == false then bagType = 'Normal' end if not sortingCache[1][bagType] then sortingCache[1][bagType] = {} end tinsert(sortingCache[1][bagType], slotNum) end for bagType, sortedBags in pairs(sortingCache[1]) do if bagType ~= 'Normal' then MOD.Stack(sortedBags, IsPartial) SortFiller(sortingCache[1]['Normal'], sortedBags, SV.db.Inventory.sortInverted) MOD.Stack(sortingCache[1]['Normal'], IsPartial) Sorter(sortedBags, nil, SV.db.Inventory.sortInverted) twipe(sortedBags) end end if sortingCache[1]['Normal'] then MOD.Stack(sortingCache[1]['Normal'], IsPartial) Sorter(sortingCache[1]['Normal'], nil, SV.db.Inventory.sortInverted) twipe(sortingCache[1]['Normal']) end twipe(sortingCache[1]) twipe(bagGroups) end end function MOD.Transfer(sourceBags, targetBags, canMove) if not canMove then canMove = true end for _, bag, slot in IterateBagsForSorting(targetBags, nil, "deposit") do local bagSlot = BagEncoder(bag, slot) local itemID = sortingCache[2][bagSlot] if itemID and (sortingCache[4][bagSlot] ~= sortingCache[5][bagSlot]) then targetItems[itemID] = (targetItems[itemID] or 0) + 1 tinsert(targetSlots, bagSlot) end end for _, bag, slot in IterateBagsForSorting(sourceBags, true, "withdraw") do local sourceSlot = BagEncoder(bag, slot) local itemID = sortingCache[2][sourceSlot] if itemID and targetItems[itemID] and (canMove == true or canMove(itemID, bag, slot)) then for i = #targetSlots, 1, -1 do local targetedSlot = targetSlots[i] if sortingCache[2][sourceSlot] and sortingCache[2][targetedSlot] == itemID and targetedSlot ~= sourceSlot and not (sortingCache[4][targetedSlot] == sortingCache[5][targetedSlot]) and not sourceUsed[targetedSlot] then SetSortingPath(sourceSlot, targetedSlot) sourceUsed[sourceSlot] = true if sortingCache[4][targetedSlot] == sortingCache[5][targetedSlot] then targetItems[itemID] = (targetItems[itemID] > 1) and (targetItems[itemID] - 1) or nil end if sortingCache[4][sourceSlot] == 0 then targetItems[itemID] = (targetItems[itemID] > 1) and (targetItems[itemID] - 1) or nil break end if not targetItems[itemID] then break end end end end end twipe(targetItems) twipe(targetSlots) twipe(sourceUsed) end function MOD.Stack(bags, canMove) if not canMove then canMove = true end for _, bag, slot in IterateBagsForSorting(bags, nil, "deposit") do local bagSlot = BagEncoder(bag, slot) local itemID = sortingCache[2][bagSlot] if itemID and (sortingCache[4][bagSlot] ~= sortingCache[5][bagSlot]) then targetItems[itemID] = (targetItems[itemID] or 0) + 1 tinsert(targetSlots, bagSlot) end end for _, bag, slot in IterateBagsForSorting(bags, true, "withdraw") do local sourceSlot = BagEncoder(bag, slot) local itemID = sortingCache[2][sourceSlot] if itemID and targetItems[itemID] and (canMove == true or (type(canMove) == "function" and canMove(itemID, bag, slot))) then for i = #targetSlots, 1, -1 do local targetedSlot = targetSlots[i] if sortingCache[2][sourceSlot] and sortingCache[2][targetedSlot] == itemID and targetedSlot ~= sourceSlot and not (sortingCache[4][targetedSlot] == sortingCache[5][targetedSlot]) and not sourceUsed[targetedSlot] then SetSortingPath(sourceSlot, targetedSlot) sourceUsed[sourceSlot] = true if sortingCache[4][targetedSlot] == sortingCache[5][targetedSlot] then targetItems[itemID] = (targetItems[itemID] > 1) and (targetItems[itemID] - 1) or nil end if sortingCache[4][sourceSlot] == 0 then targetItems[itemID] = (targetItems[itemID] > 1) and (targetItems[itemID] - 1) or nil break end if not targetItems[itemID] then break end end end end end twipe(targetItems) twipe(targetSlots) twipe(sourceUsed) end end --[[ ########################################################## INTERNAL SORTING CALLS ########################################################## ]]-- do local function GetSortingItemID(bag, slot) if (ValidateGuildBank(bag)) then local link = GetSortingItemLink(bag, slot) return link and tonumber(string.match(link, "item:(%d+)")) else return GetContainerItemID(bag, slot) end end function SortUpdateTimer:StopStacking(message) twipe(sortingCache[6]) twipe(moveTracker) moveRetries, lastItemID, lockStop, lastDestination, lastMove = 0, nil, nil, nil, nil self:SetScript("OnUpdate", nil) self:Hide() if(message) then SV:SCTMessage(message, 1, 0.35, 0) end end function SortUpdateTimer:MoveItem(move) if GetCursorInfo() == "item" then return false, 'cursorhasitem' end local source, target = MoveDecoder(move) local sourceBag, sourceSlot = BagDecoder(source) local targetBag, targetSlot = BagDecoder(target) local _, sourceCount, sourceLocked = GetSortingInfo(sourceBag, sourceSlot) local _, targetCount, targetLocked = GetSortingInfo(targetBag, targetSlot) if sourceLocked or targetLocked then return false, 'source/target_locked' end local sourceLink = GetSortingItemLink(sourceBag, sourceSlot) local sourceItemID = GetSortingItemID(sourceBag, sourceSlot) local targetItemID = GetSortingItemID(targetBag, targetSlot) if not sourceItemID then if moveTracker[source] then return false, 'move incomplete' else return self:StopStacking(L['Confused.. Try Again!']) end end local stackSize = select(8, GetItemInfo(sourceItemID)) local sourceGuild = ValidateGuildBank(sourceBag) local targetGuild = ValidateGuildBank(targetBag) if (sourceItemID == targetItemID) and (targetCount ~= stackSize) and ((targetCount + sourceCount) > stackSize) then local amount = (stackSize - targetCount) if (sourceGuild) then SplitGuildBankItem(sourceBag - 50, sourceSlot, amount) else SplitContainerItem(sourceBag, sourceSlot, amount) end else if (sourceGuild) then PickupGuildBankItem(sourceBag - 50, sourceSlot) else PickupContainerItem(sourceBag, sourceSlot) end end if GetCursorInfo() == "item" then if (targetGuild) then PickupGuildBankItem(targetBag - 50, targetSlot) else PickupContainerItem(targetBag, targetSlot) end end if sourceGuild then QueryGuildBankTab(sourceBag - 50) end if targetGuild then QueryGuildBankTab(targetBag - 50) end return true, sourceItemID, source, targetItemID, target, sourceGuild or targetGuild end local SortUpdateTimer_OnUpdate = function(self, elapsed) self.timeLapse = self.timeLapse + (elapsed or 0.01) if(self.timeLapse > 0.05) then self.timeLapse = 0 if InCombatLockdown() then return self:StopStacking(L["Can't Clean Bags in Combat!"]) end local cursorType, cursorItemID = GetCursorInfo() if cursorType == "item" and cursorItemID then if lastItemID ~= cursorItemID then return self:StopStacking(L["Bag Cleaning Error, Try Again"]) end if moveRetries < 100 then local targetBag, targetSlot = BagDecoder(lastDestination) local _, _, targetLocked = GetSortingInfo(targetBag, targetSlot) if not targetLocked then if(ValidateGuildBank(targetBag)) then PickupGuildBankItem(targetBag - 50, targetSlot) else PickupContainerItem(targetBag, targetSlot) end WAIT_TIME = 0.1 lockStop = GetTime() moveRetries = moveRetries + 1 return end end end if lockStop then local i = 1; for slot, itemID in pairs(moveTracker) do local sourceBag, sourceSlot = BagDecoder(slot) local actualItemID = GetSortingItemID(sourceBag, sourceSlot) if actualItemID ~= itemID then WAIT_TIME = 0.1 if (GetTime() - lockStop) > 1.25 then if lastMove and moveRetries < 100 then local success, moveID, moveSource, targetID, moveTarget, wasGuild = self:MoveItem(lastMove) WAIT_TIME = wasGuild and 0.5 or 0.1 if not success then lockStop = GetTime() moveRetries = moveRetries + 1 return end moveTracker[moveSource] = targetID moveTracker[moveTarget] = moveID lastDestination = moveTarget lastMove = sortingCache[6][i] lastItemID = moveID tremove(sortingCache[6], i) return end self:StopStacking() return end return end moveTracker[slot] = nil i = i + 1; end end lastItemID, lockStop, lastDestination, lastMove = nil, nil, nil, nil twipe(moveTracker) local start, success, moveID, targetID, moveSource, moveTarget, wasGuild start = GetTime() if #sortingCache[6] > 0 then for i = #sortingCache[6], 1, -1 do success, moveID, moveSource, targetID, moveTarget, wasGuild = self:MoveItem(sortingCache[6][i]) if not success then WAIT_TIME = wasGuild and 0.3 or 0.1 lockStop = GetTime() return end moveTracker[moveSource] = targetID moveTracker[moveTarget] = moveID lastDestination = moveTarget lastMove = sortingCache[6][i] lastItemID = moveID tremove(sortingCache[6], i) if sortingCache[6][i-1] then WAIT_TIME = wasGuild and 0.3 or 0; return end end end self:StopStacking() end end function SortUpdateTimer:StartStacking() twipe(sortingCache[5]) twipe(sortingCache[4]) twipe(sortingCache[2]) twipe(moveTracker) if #sortingCache[6] > 0 then self:Show() self:SetScript("OnUpdate", SortUpdateTimer_OnUpdate) else self:StopStacking() end end end function MOD:RunSortingProcess(func, groupsDefaults, altFunc) local bagGroups = {} return function(groups) if(altFunc and IsShiftKeyDown()) then PlaySound("UI_BagSorting_01"); altFunc() else if SortUpdateTimer:IsShown() then SortUpdateTimer:StopStacking(L['Already Running.. Bailing Out!']) return; end twipe(bagGroups) if not groups or #groups == 0 then groups = groupsDefaults end for bags in (groups or ""):gmatch("[^%s]+") do if bags == "guild" then bags = GetSortingGroup(bags) if bags then tinsert(bagGroups, {bags[GetCurrentGuildBankTab()]}) end else bags = GetSortingGroup(bags) if bags then tinsert(bagGroups, bags) end end end for _, bag, slot in IterateBagsForSorting(scanningCache.all) do local bagSlot = BagEncoder(bag, slot) local itemID, isBattlePet = ConvertLinkToID(GetSortingItemLink(bag, slot)) if itemID then if isBattlePet then sortingCache[3][bagSlot] = itemID sortingCache[5][bagSlot] = 1 else sortingCache[5][bagSlot] = select(8, GetItemInfo(itemID)) end sortingCache[2][bagSlot] = itemID sortingCache[4][bagSlot] = select(2, GetSortingInfo(bag, slot)) end end if func(unpack(bagGroups)) == false then return end twipe(bagGroups) SortUpdateTimer:StartStacking() end collectgarbage("collect") end end
nilq/small-lua-stack
null
-- The world consists of a tile grid. Every tile has a texture and a type Tile = Class {} function Tile:init(height, tileType) self.textures = {} for i=1,height-1 do table.insert(self.textures, "tileDirt_full") end table.insert(self.textures, tileType) self.building = nil end -- draw the tile to the specified coordinates function Tile:draw(x, y) love.graphics.draw(tileset.base.tiles, tileset.base.quads[tile.textures[self.h]], end -- Grass tile TGrass = Class{ __includes = Tile, init = function(self, height) Class.init(self, height, "tileGrass") end } -- Grass tile TGrass = Class{ __includes = Tile, init = function(self, height) Class.init(self, height, "tileGrass") end }
nilq/small-lua-stack
null
----------------------------------- -- Area: Ro'Maeve (122) -- Mob: Eldhrimnir -- Note: Popped by qm1 -- Involved in Quest: Orastery Woes -- !pos 200.3 -11 -24.8 122 ----------------------------------- require("scripts/globals/wsquest") ----------------------------------- function onMobInitialize(mob) mob:setMobMod(tpz.mobMod.EXP_BONUS,-100) mob:setMobMod(tpz.mobMod.IDLE_DESPAWN,180) end function onMobDeath(mob,player,isKiller) tpz.wsquest.handleWsnmDeath(tpz.wsquest.black_halo,player) end
nilq/small-lua-stack
null
return { OK = '\0'; RES_TERM = '\1'; RES_CMD = '\2'; REQ_CMD = '\3'; }
nilq/small-lua-stack
null
object_tangible_quest_meatlump_mtp_hideout_quest02_droid03 = object_tangible_quest_meatlump_shared_mtp_hideout_quest02_droid03:new { } ObjectTemplates:addTemplate(object_tangible_quest_meatlump_mtp_hideout_quest02_droid03, "object/tangible/quest/meatlump/mtp_hideout_quest02_droid03.iff")
nilq/small-lua-stack
null
-- RQ Tech Fix require('prototypes/rqtechfixed')
nilq/small-lua-stack
null
require 'image' require 'cunn' require 'cudnn' x1 = image.scale(image.lena(), 96):cuda() x2 = image.scale(image.lena(), 96):cuda() input = torch.cat( x1:view(1, 3, 96, 96), x2:view(1, 3, 96, 96) , 1) net = require 'models.resnet-deconv' out = net:forward(input) print(#out)
nilq/small-lua-stack
null
-- See LICENSE for terms local table = table local AsyncRand = AsyncRand local CreateRand = CreateRand local mod_MinimumSurfaceDeposits local mod_MinimumSubsurfaceDeposits -- fired when settings are changed/init local function ModOptions(id) -- id is from ApplyModOptions if id and id ~= CurrentModId then return end mod_MinimumSurfaceDeposits = CurrentModOptions:GetProperty("MinimumSurfaceDeposits") mod_MinimumSubsurfaceDeposits = CurrentModOptions:GetProperty("MinimumSubsurfaceDeposits") end -- load default/saved settings OnMsg.ModsReloaded = ModOptions -- fired when Mod Options>Apply button is clicked OnMsg.ApplyModOptions = ModOptions -- only needed for mod_MinimumDeposits == 0; we ignore this if mod option > 0, but this is (probably slightly) faster then orig func so no need to bother checking local orig_City_CreateMapRand = City.CreateMapRand function City:CreateMapRand(which, ...) -- we don't want to mess with CreateResearchRand if which == "Exploration" then return CreateRand(true, AsyncRand(), ...) end return orig_City_CreateMapRand(self, which, ...) end local orig_InitialReveal = InitialReveal function InitialReveal(eligible, ...) if mod_MinimumSurfaceDeposits == 0 and mod_MinimumSubsurfaceDeposits == 0 then return orig_InitialReveal(eligible, ...) end -- get any sectors with min amount of deposits local found_mins = table.ifilter(eligible, function(_, deposit) return #deposit.markers.surface > mod_MinimumSurfaceDeposits and #deposit.markers.subsurface > mod_MinimumSubsurfaceDeposits end) -- pick a random sector from list of found ones if #found_mins > 0 then -- table.rand returns value, count (sending count along messes up func) local sector = table.rand(found_mins) return {sector} end -- probably too high of a min, so sort the rest and pick highest table.sort(eligible, function(a, b) return #a.markers.surface > #b.markers.surface end) -- sub after as it's more important for the long run (unless you love concrete) table.sort(eligible, function(a, b) return #a.markers.subsurface > #b.markers.subsurface end) return {eligible[1]} end
nilq/small-lua-stack
null
-- `groups` -- [groupName] = {"info", count, "created", "colour"} -- [string] = {text, nt, timestamp, bigint, varchar [json], } -- We have groups_members query to basically queue the loading in of these to avoid lag local settings = { max_members = 50, max_invites = 10, -- Maxmimum number of pending invites max_totalslots = 50, -- Pending invites and current members max_inactive = 14, -- 14 days default_info_text = "Enter information about your group here!", default_colour = {200, 0, 0}, default_chat_colour = {200, 0, 0}, } local forbidden = { whole = { "ucd", "noki", "zorque", "cunt", "cunts", "fuckserver", "cit", "ugc", "ngc", "nr7gaming", "a7a", }, partial = { "zorque", "cunt", "ngc", "arran", "cit ", "admin", "staff", "is shit", "isshit", }, } _permissions = { ["demote"] = 1, ["promote"] = 2, ["kick"] = 3, ["promoteUntilOwnRank"] = 4, ["editInfo"] = 5, ["invite"] = 6, ["delete"] = 7, ["editWhitelist"] = 8, ["editBlacklist"] = 9, ["history"] = 10, ["demoteWithSameRank"] = 11, ["deposit"] = 12, ["withdraw"] = 13, ["groupColour"] = 14, ["alliance"] = 15, ["chatColour"] = 16, ["warn"] = 17, ["gsc"] = 18, ["gmotd"] = 19, -- --[[ ["groupJob"] = 20, ["editBaseInfo"] = 21, ["editJobInfo"] = 22, ["modifySpawners"] = 23, --]] } defaultRanks = { -- [name] = {{permissions}, rankIndex}, ["Trial"] = {{}, 0}, ["Regular"] = {{[12] = true}, 1}, ["Trusted"] = {{[8] = true, [10] = true, [12] = true}, 2}, ["Deputy"] = {{[1] = true, [2] = true, [3] = true, [6] = true, [8] = true, [9] = true, [10] = true, [12] = true, [17] = true, [18] = true, [19] = true}, 3}, ["Leader"] = {{[1] = true, [2] = true, [3] = true, [4] = true, [6] = true, [8] = true, [9] = true, [10] = true, [12] = true, [15] = true, [16] = true, [17] = true, [18] = true, [19] = true}, 4}, ["Founder"] = {{}, -1}, } db = exports.UCDsql:getConnection() group = {} -- Resolves a player to a group (nil otherwise) groupTable = {} -- Contains information from the groups_ table with the group name as the index groupMembers = {} -- We can just get their player elements from their id since more caching was introduced groupRanks = {} -- Contains group ranks from groups_ranks with the rank name as the index playerInvites = {} -- When a player gets invited ([accName] = group_) playerGroupCache = {} -- Player group cache with the account name as the key onlineTime = {} -- Resolves player online time blacklistCache = {} -- Cache's a group's blacklist groupEditingRanks = {} -- A table that tells us when a group is editing ranks so we do not promote/demote anyone in the meantime -- Alliances g_alliance = {} -- Group to alliance allianceTable = {} -- groups_alliances_ allianceMembers = {} -- groups_alliances_members allianceInvites = {} addEventHandler("onResourceStart", resourceRoot, function () if (not db) then outputDebugString("["..Resource.getName(resourceRoot).."] Unable to load groups") return end db:query(cacheGroupTable, {}, "SELECT * FROM `groups_`") end ) function cacheGroupTable(qh) local result = qh:poll(-1) for _, row in ipairs(result) do groupTable[row.groupName] = {} for column, data in pairs(row) do if (column ~= "groupName") then groupTable[row.groupName][column] = data end end end if (result and #result >= 1) then db:query(cacheGroupMembers, {}, "SELECT `groupName`, `account` FROM `groups_members`") end end function cacheGroupMembers(qh) local result = qh:poll(-1) for _, row in ipairs(result) do if (groupTable[row.groupName]) then if (not groupMembers[row.groupName]) then groupMembers[row.groupName] = {} end table.insert(groupMembers[row.groupName], row.account) if (Account(row.account)) then local member = Account(row.account).player if (member) then db:exec("UPDATE `groups_members` SET `lastOnline`=? WHERE `account`=?", getRealTime().yearday, row.account) end end end end for name in pairs(groupTable) do if (not groupMembers[name] or #groupMembers[name] == 0) then outputDebugString("Group "..name.." has 0 members") end end db:query(cacheGroupRanks, {}, "SELECT * FROM `groups_ranks`") db:query(cacheGroupInvites, {}, "SELECT `account`, `groupName`, `by` FROM `groups_invites`") end function cacheGroupRanks(qh) local result = qh:poll(-1) for _, row in ipairs(result) do if (not groupRanks[row.groupName]) then groupRanks[row.groupName] = {} end if (row.rankIndex == -1) then groupRanks[row.groupName][row.rankName] = {nil, row.rankIndex} else local tbl = {} for i, v in pairs(fromJSON(row.permissions)) do tbl[tonumber(i)] = v end groupRanks[row.groupName][row.rankName] = {tbl, row.rankIndex} end end db:query(cacheAlliances, {}, "SELECT * FROM `groups_alliances_`") end function cacheGroupInvites(qh) local result = qh:poll(-1) for _, row in pairs(result) do if (not playerInvites[row.account]) then playerInvites[row.account] = {} end table.insert(playerInvites[row.account], {row.groupName, row.by}) end -- Resource should be fully loaded by now, let's load things for existing players for _, plr in pairs(Element.getAllByType("player")) do if (not plr.account.guest) then handleLogin(plr) end end end function cacheAlliances(qh) local result = qh:poll(-1) for _, row in ipairs(result) do allianceTable[row.alliance] = {row.info, row.colour, row.balance, row.created} end db:query(cacheAllianceMembers, {}, "SELECT * FROM `groups_alliances_members`") end function cacheAllianceMembers(qh) local result = qh:poll(-1) for _, row in ipairs(result) do if (not allianceMembers[row.alliance]) then allianceMembers[row.alliance] = {} end allianceMembers[row.alliance][row.groupName] = row.rank g_alliance[row.groupName] = row.alliance end db:query(cacheAllianceInvites, {}, "SELECT * FROM `groups_alliances_invites`") end function cacheAllianceInvites(qh) local result = qh:poll(-1) for _, row in ipairs(result) do if (not allianceInvites[row.groupName]) then allianceInvites[row.groupName] = {} end table.insert(allianceInvites[row.groupName], {row.alliance, row.groupBy, row.playerBy}) end end function createGroup(name) local groupName = name if (client and groupName) then if (getPlayerGroup(client)) then exports.UCDdx:new(client, "You cannot create a group because you are already in one. Leave your current group first.", 255, 0, 0) return false end if (groupTable[groupName]) then exports.UCDdx:new(client, "A group with this name already exists", 255, 0, 0) return end for g, row in pairs(groupTable) do if (g == groupName) then exports.UCDdx:new("A group with this name already exists", 255, 0, 0) return false end if (g:lower() == groupName:lower()) then exports.UCDdx:new("A group with this name, but with different case, already exists", 255, 0, 0) return false end end for type_, row in pairs(forbidden) do for _, chars in pairs(row) do if type_ == "whole" then if (groupName == chars) then exports.UCDdx:new(client, "The specified group name is prohibited. If you believe this is a mistake, please notify an administrator.", 255, 0, 0) return false end else if (groupName:lower():find(chars)) then exports.UCDdx:new(client, "The specified group name contains forbidden phrases or characters. If you believe this is a mistake, please notify an administrator.", 255, 0, 0) return false end end end end local d, t = exports.UCDutil:getTimeStamp() db:exec("INSERT INTO `groups_` SET `groupName` = ?, `colour` = ?, `chatColour` = ?, `info` = ?, `created` = ?, `gmotd` = ?, `gmotd_setter` = ?", groupName, toJSON(settings.default_colour), toJSON(settings.default_chat_colour), settings.default_info_text, d.." "..t, "", "") -- Perform the inital group creation db:exec("INSERT INTO `groups_members` (`account`, `groupName`, `rank`, `lastOnline`, `joined`, `timeOnline`, `warningLevel`) VALUES (?, ?, ?, ?, ?, ?, ?)", client.account.name, groupName, "Founder", getRealTime().yearday, d, getPlayerOnlineTime(client), 0) -- Make the client's membership official and grant founder status setDefaultRanks(groupName) groupTable[groupName] = { ["info"] = settings.default_info_text, ["memberCount"] = 1, ["created"] = d.." "..t, ["colour"] = toJSON(settings.default_colour), ["balance"] = 0, ["chatColour"] = toJSON(settings.default_chat_colour), ["gmotd"] = "", } createGroupLog(groupName, client.name.." ("..client.account.name..") has created "..groupName, true) groupMembers[groupName] = {} table.insert(groupMembers[groupName], client.account.name) client:setData("group", groupName) group[client] = groupName playerGroupCache[client.account.name] = {groupName, client.account.name, "Founder", d, getRealTime().yearday, 0, 0} -- Should I even bother? exports.UCDdx:new(client, "You have successfully created "..groupName, 0, 255, 0) triggerEvent("UCDgroups.viewUI", client, true) end end addEvent("UCDgroups.createGroup", true) addEventHandler("UCDgroups.createGroup", root, createGroup) function leaveGroup(reason) if (client) then local group_ = getPlayerGroup(client) if (group_) then local rank = getGroupLastRank(group_) if (getPlayerGroupRank(client) == rank) then -- If they are a founder if (getMembersWithRank(group_, rank) == 1) then exports.UCDdx:new(client, "You can't leave your group because you're the only one with the "..rank.." rank", 255, 255, 0) return end end if (not reason or reason == " " or reason == "" or reason:gsub(" ", "") == "") then reason = "No Reason" end createGroupLog(group_, client.name.." ("..client.account.name..") has left "..group_.." ("..reason..")") for k, v in pairs(groupMembers[group_]) do if (v == client.account.name) then table.remove(groupMembers[group_], k) break end end client:removeData("group") group[client] = nil playerGroupCache[client.account.name] = nil db:exec("DELETE FROM `groups_members` WHERE `account` = ?", client.account.name) exports.UCDdx:new(client, "You have left "..group_.." ("..reason..")", 255, 0, 0) messageGroup(group_, " has left the group ("..reason..")") triggerEvent("UCDgroups.viewUI", client, true) end end end addEvent("UCDgroups.leaveGroup", true) addEventHandler("UCDgroups.leaveGroup", root, leaveGroup) function deleteGroup() if (client) then local groupName = getPlayerGroup(client) if (not groupName) then exports.UCDdx:new(client, "You are not in a group", 255, 0, 0) return end -- Must also check if they are in an alliance local alliance = g_alliance[groupName] if (alliance) then local leaderCount = 0 for g, rank in pairs(allianceMembers[alliance]) do if (rank == "Leader" and g ~= groupName) then leaderCount = leaderCount + 1 end end if (leaderCount == 0) then exports.UCDdx:new(client, "You cannot delete this group until you give leadership of the alliance to another group, or delete the alliance", 255, 0, 0) return false end db:exec("DELETE FROM `groups_alliances_members` WHERE `groupName` = ? AND `alliance` = ?", groupName, alliance) db:exec("DELETE FROM `groups_alliances_invites` WHERE `groupName` = ?", groupName) g_alliance[groupName] = nil allianceMembers[alliance][groupName] = nil allianceInvites[groupName] = nil end createGroupLog(group_, client.name.." ("..client.account.name..") has deleted "..groupName, true) outputDebugString("Deleting group where groupName = "..groupName) db:exec("DELETE FROM `groups_` WHERE `groupName` = ?", groupName) db:exec("DELETE FROM `groups_members` WHERE `groupName` = ?", groupName) db:exec("DELETE FROM `groups_ranks` WHERE `groupName` = ?", groupName) db:exec("DELETE FROM `groups_invites` WHERE `groupName` = ?", groupName) db:exec("DELETE FROM `groups_blacklist` WHERE `groupName` = ?", groupName) db:exec("DELETE FROM `groups_whitelist` WHERE `groupName` = ?", groupName) db:exec("DELETE FROM `groups_logs` WHERE `groupName` = ? AND `important` <> 1", groupName) -- Remove the invite from the table for acc, row in pairs(playerInvites) do for i, v in pairs(row) do if (v[1] == groupName) then table.remove(playerInvites[acc], i) end end end for _, account in pairs(groupMembers[groupName]) do local plr = Account(account).player if (plr and isElement(plr) and plr.type == "player" and getPlayerGroup(plr)) then plr:removeData("group") group[plr] = nil playerGroupCache[plr.account.name] = nil exports.UCDdx:new(plr, client.name.." has decided to delete the group", 255, 0, 0) triggerEvent("UCDgroups.viewUI", plr, true) end end -- Clear from the table to free memory groupMembers[groupName] = nil groupTable[groupName] = nil groupRanks[groupName] = nil -- Let the client know he did it exports.UCDdx:new(client, "You have deleted the group "..groupName, 255, 0, 0) end end addEvent("UCDgroups.deleteGroup", true) addEventHandler("UCDgroups.deleteGroup", root, deleteGroup) function joinGroup(group_) --if (not client) then client = source end if (source and group_) then if (groupTable[group_]) then if (not exports.UCDaccounts:isPlayerLoggedIn(source) or getPlayerGroup(source)) then return end local account = source.account.name local rank = getGroupFirstRank(group_) local d, t = exports.UCDutil:getTimeStamp() db:exec("INSERT INTO `groups_members` SET `groupName`=?, `account`=?, `rank`=?, `lastOnline`=?, `timeOnline`=?", group_, account, rank, getRealTime().yearday, getPlayerOnlineTime(plr)) --groupTable[group_].memberCount = groupTable[group_].memberCount + 1 --db:exec("UPDATE `groups_` SET `memberCount`=? WHERE `groupName`=?", tonumber(groupTable[group_].memberCount), group_) createGroupLog(group_, source.name.." ("..source.account.name..") has joined "..group_) table.insert(groupMembers[group_], account) source:setData("group", group_) group[source] = group_ playerGroupCache[account] = {group_, account, rank, d, getRealTime().yearday, 0, 0} exports.UCDdx:new(source, "You have joined "..group_, 0, 255, 0) messageGroup(group_, source.name.." has joined the group", "info") triggerEvent("UCDgroups.viewUI", source, true) else exports.UCDdx:new(source, "You can't join this group because it doesn't exist", 255, 255, 0) end end end addEvent("UCDgroups.joinGroup", true) addEventHandler("UCDgroups.joinGroup", root, joinGroup) function sendInvite(plr) if (client) then if (not plr or not isElement(plr) or plr.type ~= "player") then return end if (getPlayerGroup(plr)) then return end local group_ = getPlayerGroup(client) if (group_) then if (canPlayerDoActionInGroup(client, "invite")) then if (groupTable[group_].lockInvites == 1) then exports.UCDdx:new(client, "The group is currently locked - no invites may be sent", 255, 0, 0) return end -- send invite, tell plr, tell group, add to queue, put in sql --playerInvites[plr.account.name] = {group_, client.name} if (not playerInvites[plr.account.name]) then playerInvites[plr.account.name] = {} end local result -- SQL will do less looping but it is inherently slower if (blacklistCache[group_]) then result = blacklistCache[group_] else result = db:query("SELECT `serialAccount` FROM `groups_blacklist` WHERE `groupName` = ?", group_):poll(-1) end if (result and #result > 0) then for _, ent in ipairs(result) do if (ent.serialAccount == plr.account.name) then exports.UCDdx:new(client, "You cannot invite this player as their account is blacklisted", 255, 255, 0) return end if (ent.serialAccount == plr.serial) then exports.UCDdx:new(client, "You cannot invite this player as their serial is blacklisted", 255, 255, 0) return end end end for index, row in pairs(playerInvites[plr.account.name]) do for _, data in pairs(row) do if (data == group_) then exports.UCDdx:new(client, "This player has already been invited to this group", 255, 255, 0) return end end end table.insert(playerInvites[plr.account.name], {group_, client.name}) db:exec("INSERT INTO `groups_invites` SET `account`=?, `groupName`=?, `by`=?", plr.account.name, group_, client.name) createGroupLog(group_, client.name.." ("..client.account.name..") has invited "..plr.name.." ("..plr.account.name..") to the group") messageGroup(group_, client.name.." has invited "..plr.name.." to the group", "info") exports.UCDdx:new(plr, "You have been invited to "..group_.." by "..client.name..". Press F6 -> 'Group Invites' to view your invites", 0, 255, 0) else exports.UCDdx:new(client, "You don't have permission to do this action (invite)", 200, 0, 0) end end end end addEvent("UCDgroups.sendInvite", true) addEventHandler("UCDgroups.sendInvite", root, sendInvite) function handleInvite(groupName, state) if (client and groupName and state) then -- Delete the current invite (this loop works flawlessly) for index, row in pairs(playerInvites[client.account.name]) do for _, data in pairs(row) do if (data == groupName) then table.remove(playerInvites[client.account.name], index) end end end db:exec("DELETE FROM `groups_invites` WHERE `groupName` = ? AND `account` =? ", groupName, client.account.name) if (state == "accept") then if (groupTable[groupName].lockInvites == 1) then exports.UCDdx:new(client, "Unable to accept the invite - this group is locked", 255, 0, 0) triggerEvent("UCDgroups.requestInviteList", client) return end local result if (blacklistCache[groupName]) then result = blacklistCache[groupName] else result = db:query("SELECT `serialAccount` FROM `groups_blacklist` WHERE `groupName`=?", groupName):poll(-1) end if (result and #result > 0) then for _, ent in ipairs(result) do if (ent.serialAccount == client.serial) then exports.UCDdx:new(client, "You cannot join this group as your serial is blacklisted", 255, 0, 0) triggerEvent("UCDgroups.requestInviteList", client) return end if (ent.serialAccount == client.account.name) then exports.UCDdx:new(client, "You cannot join this group as your account is blacklisted", 255, 0, 0) triggerEvent("UCDgroups.requestInviteList", client) return end end end -- Make the player join the group -- messageGroup(groupName, client.name.." has joined the group", "info") -- Already handled in joinGroup function triggerEvent("UCDgroups.joinGroup", client, groupName) elseif (state == "deny") then messageGroup(groupName, client.name.." has declined the invitation to join the group", "info") exports.UCDdx:new(client, "You have declined the invitation to join "..groupName, 255, 255, 0) end triggerEvent("UCDgroups.requestInviteList", client) end end addEvent("UCDgroups.handleInvite", true) addEventHandler("UCDgroups.handleInvite", root, handleInvite) function requestInvites() if (source) then if (exports.UCDaccounts:isPlayerLoggedIn(source)) then local invites = playerInvites[source.account.name] triggerLatentClientEvent(source, "UCDgroups.inviteList", source, invites or {}) end end end addEvent("UCDgroups.requestInviteList", true) addEventHandler("UCDgroups.requestInviteList", root, requestInvites) function promoteMember(accName, newRank, reason) if (client and accName and reason) then local group_ = getPlayerGroup(client) local acc = Account(accName) local clientRank = getPlayerGroupRank(client) local plrRank = playerGroupCache[accName][3] --local newRank = getNextRank(group_, plrRank) if (reason:gsub(" ", "") == "") then reason = "No Reason" end if (groupEditingRanks[group_]) then exports.UCDdx:new(client, "Ranks are currently being edited - you cannot warn, promote, demote or kick right now", 255, 0, 0) return end if (plrRank == getGroupLastRank(group_)) then return end if (group_ and acc) then if (canPlayerDoActionInGroup(client, "promote")) then if (isRankHigherThan(group_, clientRank, plrRank) == true) then if (newRank == clientRank and not canPlayerDoActionInGroup(client, "promoteUntilOwnRank")) then return end if (isRankHigherThan(group_, clientRank, newRank) == false) then return end playerGroupCache[accName][3] = newRank db:exec("UPDATE `groups_members` SET `rank`=? WHERE `account`=?", newRank, accName) triggerEvent("UCDgroups.viewUI", client, true) triggerEvent("UCDgroups.requestMemberList", client) createGroupLog(group_, client.name.." ("..client.account.name..") has promoted "..exports.UCDaccounts:GAD(accName, "lastUsedName").." ("..accName..") to "..newRank.." ("..reason..")") if (acc.player) then messageGroup(group_, client.name.." is promoting "..acc.player.name.." to "..newRank.." ("..reason..")", "info") triggerEvent("UCDgroups.viewUI", acc.player, true) -- Update the player's GUI else messageGroup(group_, client.name.." is promoting "..accName.." to "..newRank.." ("..reason..")", "info") end triggerClientEvent(client, "UCDgroups.promoteDemoteWindow", client) else exports.UCDdx:new(client, "You cannot promote players with same or higher rank", 200, 0, 0) end end else exports.UCDdx:new(client, "This player cannot be promoted", 200, 0, 0) end end end addEvent("UCDgroups.promoteMember", true) addEventHandler("UCDgroups.promoteMember", root, promoteMember) function demoteMember(accName, newRank, reason) if (client and accName and newRank and reason) then local group_ = getPlayerGroup(client) local acc = Account(accName) local clientRank = getPlayerGroupRank(client) local plrRank = playerGroupCache[accName][3] --local newRank = getPreviousRank(group_, plrRank) if (reason:gsub(" ", "") == "") then reason = "No Reason" end if (groupEditingRanks[group_]) then exports.UCDdx:new(client, "Ranks are currently being edited - you cannot warn, promote, demote or kick right now", 255, 0, 0) return end if (canPlayerDoActionInGroup(client, "demote")) then if (isRankHigherThan(group_, clientRank, plrRank)) then if (plrRank == clientRank and not canPlayerDoActionInGroup(client, "demoteWithSameRank")) then exports.UCDdx:new(client, "You are not allowed to demote players with the same rank as you", 255, 0, 0) return end if (isRankHigherThan(group_, clientRank, newRank) == false) then return end if (plrRank == getGroupFirstRank(group_)) then exports.UCDdx:new(client, "You cannot demote this player as they have the lowest rank already", 255, 0, 0) return end playerGroupCache[accName][3] = newRank db:exec("UPDATE `groups_members` SET `rank`=? WHERE `account`=?", newRank, accName) triggerEvent("UCDgroups.viewUI", client, true) triggerEvent("UCDgroups.requestMemberList", client) createGroupLog(group_, client.name.." ("..client.account.name..") has demoted "..exports.UCDaccounts:GAD(accName, "lastUsedName").." ("..accName..") to "..newRank.." ("..reason..")") triggerClientEvent(client, "UCDgroups.promoteDemoteWindow", client) if (acc.player) then messageGroup(group_, client.name.." is demoting "..acc.player.name.." to "..newRank.." ("..reason..")", "info") triggerEvent("UCDgroups.viewUI", acc.player, true) else messageGroup(group_, client.name.." is demoting "..accName.." to "..newRank.." ("..reason..")", "info") end else exports.UCDdx:new(client, "You can't demote players with a higher rank than you", 255, 0, 0) end end end end addEvent("UCDgroups.demoteMember", true) addEventHandler("UCDgroups.demoteMember", root, demoteMember) function kickMember(accName, reason) if (client and accName and reason) then local group_ = getPlayerGroup(client) local acc = Account(accName) local clientRank = getPlayerGroupRank(client) local plrRank = playerGroupCache[accName][3] if (reason:gsub(" ", "") == "") then reason = "No Reason" end if (groupEditingRanks[group_]) then exports.UCDdx:new(client, "Ranks are currently being edited - you cannot warn, promote, demote or kick right now", 255, 0, 0) return end if (canPlayerDoActionInGroup(client, "kick")) then if (isRankHigherThan(group_, clientRank, plrRank)) then if (plrRank == clientRank and not canPlayerDoActionInGroup(client, "demotePlayersWithSameRank")) then exports.UCDdx:new(client, "You are not allowed to kick players with the same rank as you", 255, 0, 0) return end for k, v in pairs(groupMembers[group_]) do if v == accName then table.remove(groupMembers[group_], k) --groupMembers[group_][k] = nil break end end playerGroupCache[accName] = nil --groupTable[group_].memberCount = groupTable[group_].memberCount - 1 --db:exec("UPDATE `groups_` SET `memberCount`=? WHERE `groupName`=?", tonumber(groupTable[group_].memberCount), group_) db:exec("DELETE FROM `groups_members` WHERE `account`=?", accName) createGroupLog(group_, client.name.." ("..client.account.name..") has kicked "..exports.UCDaccounts:GAD(accName, "lastUsedName").." ("..accName..") ("..reason..")") if (acc.player) then acc.player:removeData("group") local r, g, b = getGroupChatColour(group_) exports.UCDdx:new(acc.player, "You have been kicked from "..group_.." by "..client.name.." ("..reason..")", r, g, b) group[acc.player] = nil messageGroup(group_, client.name.." has kicked "..acc.player.name.." ("..reason..")", "info") triggerEvent("UCDgroups.viewUI", acc.player, true) else messageGroup(group_, client.name.." has kicked "..accName.." ("..reason..")", "info") end triggerEvent("UCDgroups.viewUI", client, true) triggerEvent("UCDgroups.requestMemberList", client) --]] else exports.UCDdx:new(client, "You can't kick players with a higher rank than you", 255, 0, 0) end end end end addEvent("UCDgroups.kickMember", true) addEventHandler("UCDgroups.kickMember", root, kickMember) function warnMember(accName, level, reason) if (client and accName and level and reason) then local group_ = getPlayerGroup(client) local clientRank = getPlayerGroupRank(client) local plrRank = playerGroupCache[accName][3] if (groupEditingRanks[group_]) then exports.UCDdx:new(client, "Ranks are currently being edited - you cannot warn, promote, demote or kick right now", 255, 0, 0) return end if (group_) then if (canPlayerDoActionInGroup(client, "warn") and isRankHigherThan(group_, clientRank, plrRank)) then if (level == playerGroupCache[accName][7]) then return end local change = level - playerGroupCache[accName][7] if (change > 0) then change = "+"..change.."%" else change = change.."%" end if (Account(accName).player) then messageGroup(group_, client.name.." has warned "..Account(accName).player.name.." ("..change..") ("..reason..")", "info") else messageGroup(group_, client.name.." has warned "..accName.." ("..change..") ("..reason..")", "info") end db:exec("UPDATE `groups_members` SET `warningLevel`=? WHERE `account`=?", level, accName) playerGroupCache[accName][7] = level createGroupLog(group_, client.name.." ("..client.account.name..") has warned "..exports.UCDaccounts:GAD(accName, "lastUsedName").." ("..accName..") ("..change..") ["..level.."] ("..reason..")") triggerEvent("UCDgroups.viewUI", client, true) triggerEvent("UCDgroups.requestMemberList", client) end end end end addEvent("UCDgroups.warnMember", true) addEventHandler("UCDgroups.warnMember", root, warnMember) function changeGroupBalance(type_, balanceChange) if (client) then if (not balanceChange or tonumber(balanceChange) == nil) then exports.UCDdx:new(client, "Something went wrong!", 255, 255, 0) return end local group_ = getPlayerGroup(client) if (group and canPlayerDoActionInGroup(client, type_)) then local currentBalance = groupTable[group_].balance if (type_ == "deposit") then if (client.money < balanceChange) then exports.UCDdx:new(client, "You can't deposit this much because you don't have it", 255, 0, 0) return end if (balanceChange <= 0) then exports.UCDdx:new(client, "You must enter a positive number", 255, 255, 0) return end groupTable[group_].balance = groupTable[group_].balance + balanceChange client.money = client.money - balanceChange db:exec("UPDATE `groups_` SET `balance`=? WHERE `groupName`=?", tonumber(groupTable[group_].balance), group_) messageGroup(group_, client.name.." has deposited $"..exports.UCDutil:tocomma(balanceChange).." into the group bank", "info") createGroupLog(group_, client.name.." ("..client.account.name..") has deposited $"..exports.UCDutil:tocomma(balanceChange).." into the group bank") triggerLatentClientEvent(client, "UCDgroups.balanceWindow", client, "update", groupTable[group_].balance) elseif (type_ == "withdraw") then if ((currentBalance - balanceChange) < 0) then exports.UCDdx:new(client, "The group doesn't have this much", 255, 255, 0) return end if (balanceChange <= 0) then exports.UCDdx:new(client, "You must enter a positive number", 255, 255, 0) return end groupTable[group_].balance = groupTable[group_].balance - balanceChange client.money = client.money + balanceChange db:exec("UPDATE `groups_` SET `balance`=? WHERE `groupName`=?", tonumber(groupTable[group_].balance), group_) messageGroup(group_, client.name.." has withdrawn $"..exports.UCDutil:tocomma(balanceChange).." from the group bank", "info") createGroupLog(group_, client.name.." ("..client.account.name..") has withdrawn $"..exports.UCDutil:tocomma(balanceChange).." from the group bank") triggerLatentClientEvent(client, "UCDgroups.balanceWindow", client, "update", groupTable[group_].balance) end end end end addEvent("UCDgroups.changeBalance", true) addEventHandler("UCDgroups.changeBalance", root, changeGroupBalance) function requestBalance() if (client or source) then local group_ = getPlayerGroup(source) if (group_) then triggerClientEvent(source, "UCDgroups.balanceWindow", source, "toggle", tonumber(groupTable[group_].balance)) end end end addEvent("UCDgroups.requestBalance", true) addEventHandler("UCDgroups.requestBalance", root, requestBalance) function updateGroupInfo(newInfo) if (client) then local groupName = getPlayerGroup(client) if (groupName) then groupTable[groupName].info = newInfo db:exec("UPDATE `groups_` SET `info`=? WHERE `groupName`=?", newInfo, groupName) messageGroup(groupName, client.name.." has updated the group information", "info") createGroupLog(group_, client.name.." ("..client.account.name..") has updated the group information") for _, plr in pairs(getGroupOnlineMembers(groupName)) do triggerEvent("UCDgroups.viewUI", plr, true) end end end end addEvent("UCDgroups.updateInfo", true) addEventHandler("UCDgroups.updateInfo", root, updateGroupInfo) function requestMemberList() if (source) then local group_ = getPlayerGroup(source) if (group_) then local members = getAdvancedGroupMembers(group_) triggerLatentClientEvent(source, "UCDgroups.memberList", source, members) end end end addEvent("UCDgroups.requestMemberList", true) addEventHandler("UCDgroups.requestMemberList", root, requestMemberList) function requestGroupList() if (client) then local temp = {} for groupName, data in pairs(groupTable) do if (getGroupMemberCount(groupName) and getGroupMemberCount(groupName) >= 1) then temp[groupName] = {members = getGroupMemberCount(groupName), slots = data.slots or 50} end end if (temp) then triggerClientEvent(client, "UCDgroups.groupList", client, temp) end end end addEvent("UCDgroups.requestGroupList", true) addEventHandler("UCDgroups.requestGroupList", root, requestGroupList) function requestGroupHistory() if (client) then local group_ = getPlayerGroup(client) if (group_) then if (canPlayerDoActionInGroup(client, "history")) then local history, rows = db:query("SELECT `log` AS `log_` FROM `groups_logs` WHERE `groupName`=? ORDER BY `log` DESC LIMIT 100", group_):poll(-1) local total = db:query("SELECT Count(*) AS `count_` FROM `groups_logs` WHERE `groupName`=?", group_):poll(-1)[1].count_ triggerLatentClientEvent(client, "UCDgroups.history", client, history or {}, total or 0, rows or 0) else exports.UCDdx:new(client, "You are not allowed to view the group history", 255, 0, 0) end end end end addEvent("UCDgroups.requestGroupHistory", true) addEventHandler("UCDgroups.requestGroupHistory", root, requestGroupHistory) function requestGroupRanks() if (source) then local group_ = getPlayerGroup(source) if (group_) then triggerLatentClientEvent(source, "UCDgroups.groupRanks", source, groupRanks[group_]) end end end addEvent("UCDgroups.requestGroupRanks", true) addEventHandler("UCDgroups.requestGroupRanks", root, requestGroupRanks) function requestGroupSettings() if (source) then local group_ = getPlayerGroup(source) if (group_) then local temp = { ["groupColour"] = fromJSON(groupTable[group_].colour) or settings.default_colour, ["chatColour"] = fromJSON(groupTable[group_].chatColour) or settings.default_chat_colour, ["gmotd"] = groupTable[group_].gmotd or "", ["enableGSC"] = groupTable[group_].enableGSC or 1, ["lockInvites"] = groupTable[group_].lockInvites or 0, } triggerLatentClientEvent(source, "UCDgroups.settings", source, temp) end end end addEvent("UCDgroups.requestGroupSettings", true) addEventHandler("UCDgroups.requestGroupSettings", root, requestGroupSettings) function requestBlacklist() if (source) then local group_ = getPlayerGroup(source) if (group_) then local blacklist if (blacklistCache[group_]) then blacklist = blacklistCache[group_] else blacklist = db:query("SELECT * FROM `groups_blacklist` WHERE `groupName`=?", group_):poll(-1) if (blacklist and #blacklist > 0) then blacklistCache[group_] = blacklist end end triggerLatentClientEvent(source, "UCDgroups.blacklist", source, blacklist or {}) end end end addEvent("UCDgroups.requestBlacklist", true) addEventHandler("UCDgroups.requestBlacklist", root, requestBlacklist) function addBlacklistEntry(serialAccount, reason) if (client and serialAccount and reason and db) then local group_ = getPlayerGroup(client) if (group_) then if (canPlayerDoActionInGroup(client, "editBlacklist")) then if (blacklistCache[group_]) then local result = blacklistCache[group_] for i = 1, #result do if (result[i].serialAccount == serialAccount) then exports.UCDdx:new(client, "This serial or account is already blacklisted", 255, 0, 0) return end end else local result = db:query("SELECT `uniqueID` FROM `groups_blacklist` WHERE `serialAccount`=? AND `groupName`=?", serialAccount, group_):poll(-1) if (result and #result > 0) then exports.UCDdx:new(client, "This serial or account is already blacklisted", 255, 0, 0) return end end if (not Account(serialAccount) and serialAccount:len() ~= 32) then exports.UCDdx:new(client, "This specified account does not exist", 255, 0, 0) return end -- Should be good to go --db:exec("INSERT INTO `groups_blacklist` SET `groupName`=?, `serialAccount`=?, `by`=?, `reason`=?", group_, serialAccount, client.account.name, reason) local d, t = exports.UCDutil:getTimeStamp() db:exec("INSERT INTO `groups_blacklist` (`groupName`, `serialAccount`, `by`, `reason`, `datum`) VALUES (?, ?, ?, ?, NOW())", group_, serialAccount, client.account.name, reason) -- CONCAT(CURDATE(), ' ', CURTIME()) if (not blacklistCache[group_]) then blacklistCache[group_] = {} end table.insert(blacklistCache[group_], {["groupName"] = group_, ["serialAccount"] = serialAccount, ["by"] = client.account.name, ["reason"] = reason, ["datum"] = tostring(d.." "..t)}) if (serialAccount:len() ~= 32) then exports.UCDdx:new(client, "You have added a blacklisting on account "..serialAccount, 255, 0, 0) createGroupLog(group_, client.name.." ("..client.account.name..") has added a blacklisting on account "..serialAccount) else exports.UCDdx:new(client, "You have added a blacklisting on serial "..serialAccount, 255, 0, 0) createGroupLog(group_, client.name.." ("..client.account.name..") has added a blacklisting on serial "..serialAccount) end triggerEvent("UCDgroups.requestBlacklist", client) else exports.UCDdx:new(client, "You are not allowed to edit the group's blacklist", 255, 0, 0) end end end end addEvent("UCDgroups.addBlacklistEntry", true) addEventHandler("UCDgroups.addBlacklistEntry", root, addBlacklistEntry) function removeBlacklistEntry(serialAccount) if (client and serialAccount and db) then local group_ = getPlayerGroup(client) if (group_) then if (canPlayerDoActionInGroup(client, "editBlacklist")) then local result = db:query("SELECT * FROM `groups_blacklist` WHERE `serialAccount`=? AND `groupName`=?", serialAccount, group_):poll(-1) if (not result or result == nil or #result >= 1) then local type1 if (serialAccount:len() == 32) then -- serial type1 = "serial" else type1 = "account" end db:exec("DELETE FROM `groups_blacklist` WHERE `serialAccount`=? AND `groupName`=?", serialAccount, group_) if (blacklistCache[group_]) then for i = 1, #blacklistCache[group_] do if (blacklistCache[group_][i].serialAccount == serialAccount) then table.remove(blacklistCache[group_], i) break end end end exports.UCDdx:new(client, "You have removed the blacklisting on "..serialAccount, 255, 0, 0) createGroupLog(group_, client.name.." ("..client.account.name..") has removed the blacklisting on "..serialAccount) triggerEvent("UCDgroups.requestBlacklist", client) else if (serialAccount:len() == 32) then exports.UCDdx:new(client, "This serial is not blacklisted", 255, 0, 0) else exports.UCDdx:new(client, "This account is not blacklisted", 255, 0, 0) end triggerEvent("UCDgroups.requestBlacklist", client) end else exports.UCDdx:new(client, "You are not allowed to edit the group's blacklist", 255, 0, 0) end end end end addEvent("UCDgroups.removeBlacklistEntry", true) addEventHandler("UCDgroups.removeBlacklistEntry", root, removeBlacklistEntry) function groupChat(plr, _, ...) if (not exports.UCDchecking:canPlayerDoAction(plr, "Chat")) then return end if (exports.UCDaccounts:isPlayerLoggedIn(plr) and getPlayerGroup(plr)) then local msg = table.concat({...}, " ") messageGroup(getPlayerGroup(plr), "("..tostring(getPlayerGroup(plr))..") "..plr.name.." #FFFFFF"..msg, "chat") for _, plr2 in ipairs(Element.getAllByType("player")) do if (getPlayerGroup(plr2) == getPlayerGroup(plr)) then exports.UCDchat:insert(plr2, "group", plr, msg) end end end end addCommandHandler("gc", groupChat, false, false) addCommandHandler("groupchat", groupChat, false, false) function groupStaffChat(plr, _, ...) if (not exports.UCDchecking:canPlayerDoAction(plr, "Chat")) then return end if (exports.UCDaccounts:isPlayerLoggedIn(plr) and getPlayerGroup(plr) and canPlayerDoActionInGroup(plr, "gsc")) then local r, g, b = getGroupChatColour(getPlayerGroup(plr)) if (groupTable[getPlayerGroup(plr)].enableGSC == 0) then exports.UCDdx:new(plr, "Group staff chat has been disabled", r, g, b) return end local msg = table.concat({...}, " ") for _, ent in ipairs(groupMembers[getPlayerGroup(plr)]) do local plr_ = Account(ent).player if (plr_ and isElement(plr_) and canPlayerDoActionInGroup(plr_, "gsc")) then outputChatBox("(GSC) "..plr.name.." #FFFFFF"..msg, plr_, r, g, b, true) end end end end addCommandHandler("gsc", groupStaffChat, false, false) addCommandHandler("groupstaffchat", groupStaffChat, false, false) addCommandHandler("gschat", groupStaffChat, false, false) addCommandHandler("gstaff", groupStaffChat, false, false) function handleLogin(plr) local account = plr.account.name if (not playerGroupCache[account]) then playerGroupCache[account] = {} db:query(handleLogin2, {plr, account}, "SELECT `groupName`, `rank`, `joined`, `timeOnline`, `warningLevel` FROM `groups_members` WHERE `account`=? LIMIT 1", account) else handleLogin2(nil, plr, account) end onlineTime[plr] = getRealTime().timestamp end addEventHandler("onPlayerLogin", root, function () handleLogin(source) end) -- We do this so the we don't always query the SQL database upon login to get group data function handleLogin2(qh, plr, account) if (qh) then local result = qh:poll(-1) if (result and #result == 1) then playerGroupCache[account] = {result[1].groupName, account, result[1].rank, result[1].joined, getRealTime().yearday, result[1].timeOnline, result[1].warningLevel} -- If a player is kicked while he is offline, we will need to delete the cache end end if (not playerGroupCache[account] or not playerGroupCache[account][1]) then return end playerGroupCache[account][5] = getRealTime().yearday local group_ = playerGroupCache[account][1] local r, g, b = getGroupChatColour(group_) local gmotd = (groupTable[group_] and groupTable[group_].gmotd) or "" plr:setData("group", group_) group[plr] = group_ if (gmotd and gmotd ~= "" and gmotd:gsub(" ", "") ~= "" and gmotd:len() > 1) then local LUN = exports.UCDaccounts:GAD(groupTable[group_].gmotd_setter, "lastUsedName") or groupTable[group_].gmotd_setter outputChatBox("GMOTD "..LUN.." #FFFFFF"..gmotd, plr, r, g, b, true) end end addEventHandler("onPlayerQuit", root, function () onlineTime[source] = nil group[source] = nil local account = source.account.name if (account and exports.UCDaccounts:isPlayerLoggedIn(source) and getPlayerGroup(source)) then db:exec("UPDATE `groups_members` SET `timeOnline`=?, `lastOnline`=? WHERE `account`=?", getPlayerOnlineTime(source), getRealTime().yearday, account) playerGroupCache[account][6] = getPlayerOnlineTime(source) onlineTime[source] = nil group[source] = nil end end ) addEventHandler("onResourceStop", resourceRoot, function () for _, plr in pairs(Element.getAllByType("player")) do if (getPlayerGroup(plr)) then plr:removeData("group") db:exec("UPDATE `groups_members` SET `timeOnline`=?, `lastOnline`=? WHERE `account`=?", getPlayerOnlineTime(plr), getRealTime().yearday, plr.account.name) end end end ) function toggleGUI(update) local groupName = getPlayerGroup(source) or "" local groupInfo = getGroupInfo(groupName) or "" local rank = getPlayerGroupRank(source) local permissions = getRankPermissions(groupName, rank) local ranks = {} local memberCount local groupSlots = 50 local created if (groupName == "" or not groupName) then created = "N/A" memberCount = "N" groupSlots = "A" else memberCount = #groupMembers[groupName] or 0 groupSlots = 50 created = groupTable[groupName].created or "N/A" end triggerLatentClientEvent(source, "UCDgroups.toggleGUI", 15000, false, source, update, groupName, groupInfo, permissions, rank, ranks, memberCount, groupSlots, created) end addEvent("UCDgroups.viewUI", true) addEventHandler("UCDgroups.viewUI", root, toggleGUI) function updateGroupSettings(newSettings) if (client and newSettings) then local group_ = getPlayerGroup(client) if (group_) then local rank = getPlayerGroupRank(client) local c = fromJSON(groupTable[group_].colour) local chat = fromJSON(groupTable[group_].chatColour) if (newSettings.chatColour[1] ~= chat[1] or newSettings.chatColour[2] ~= chat[2] or newSettings.chatColour[3] ~= chat[3]) then if (canPlayerDoActionInGroup(client, "chatColour")) then groupTable[group_].chatColour = toJSON(newSettings.chatColour) db:exec("UPDATE `groups_` SET `chatColour`=? WHERE `groupName`=?", toJSON(newSettings.chatColour), group_) messageGroup(group_, client.name.." has updated the group chat colour", "info") createGroupLog(group_, client.name.." ("..client.account.name..") has updated the group chat colour ("..newSettings.chatColour[1]..", "..newSettings.chatColour[2]..", "..newSettings.chatColour[3]..")") else exports.UCDdx:new(client, "You are not allowed to edit the group chat colour", 255, 0, 0) end end if (newSettings.groupColour[1] ~= c[1] or newSettings.groupColour[2] ~= c[2] or newSettings.groupColour[3] ~= c[3]) then if (canPlayerDoActionInGroup(client, "groupColour")) then groupTable[group_].colour = toJSON(newSettings.groupColour) db:exec("UPDATE `groups_` SET `colour`=? WHERE `groupName`=?", toJSON(newSettings.groupColour), group_) messageGroup(group_, client.name.." has updated the group colour", "info") createGroupLog(group_, client.name.." ("..client.account.name..") has updated the group colour ("..newSettings.groupColour[1]..", "..newSettings.groupColour[2]..", "..newSettings.groupColour[3]..")") -- need an event here for things like turf etc else exports.UCDdx:new(client, "You are not allowed to edit the group colour", 255, 0, 0) end end if (newSettings.lockInvites ~= groupTable[group_].lockInvites) then if (getGroupLastRank(group_) == rank) then groupTable[group_].lockInvites = newSettings.lockInvites db:exec("UPDATE `groups_` SET `lockInvites`=? WHERE `groupName`=?", newSettings.lockInvites, group_) if (groupTable[group_].lockInvites == 1) then messageGroup(group_, client.name.." has locked group invites", "info") createGroupLog(group_, client.name.." ("..client.account.name..") has locked group invites") else messageGroup(group_, client.name.." has unlocked group invites", "info") createGroupLog(group_, client.name.." ("..client.account.name..") has unlocked group invites") end else exports.UCDdx:new(client, "You are not allowed to lock/unlock group invites", 255, 0, 0) end end if (newSettings.enableGSC ~= groupTable[group_].enableGSC) then if (getGroupLastRank(group_) == rank) then local r, g, b = getGroupChatColour(group_) groupTable[group_].enableGSC = newSettings.enableGSC db:exec("UPDATE `groups_` SET `enableGSC`=? WHERE `groupName`=?", newSettings.enableGSC, group_) if (groupTable[group_].enableGSC == 1) then createGroupLog(group_, client.name.." ("..client.account.name..") has enabled group staff chat") else createGroupLog(group_, client.name.." ("..client.account.name..") has disabled group staff chat") end for _, acc in ipairs(groupMembers[group_]) do if (Account(acc).player) then if (canPlayerDoActionInGroup(Account(acc).player, "gsc")) then if (groupTable[group_].enableGSC == 1) then exports.UCDdx:new(Account(acc).player, client.name.." has enabled group staff chat /gsc", r, g, b) else exports.UCDdx:new(Account(acc).player, client.name.." has disabled group staff chat /gsc", r, g, b) end end end end else exports.UCDdx:new(client, "You are not allowed to toggle group staff chat", 255, 0, 0) end end if (newSettings.gmotd ~= groupTable[group_].gmotd) then if (canPlayerDoActionInGroup(client, "gmotd")) then groupTable[group_].gmotd = newSettings.gmotd db:exec("UPDATE `groups_` SET `gmotd`=? WHERE `groupName`=?", newSettings.gmotd, group_) groupTable[group_].gmotd_setter = client.account.name db:exec("UPDATE `groups_` SET `gmotd_setter`=? WHERE `groupName`=?", client.account.name, group_) messageGroup(group_, client.name.." has changed the group MOTD", "info") createGroupLog(group_, client.name.." ("..client.account.name..") has changed the group MOTD") else exports.UCDdx:new(client, "You are not allowed to set the GMOTD", 255, 0, 0) end end triggerEvent("UCDgroups.requestGroupSettings", client) end end end addEvent("UCDgroups.updateSettings", true) addEventHandler("UCDgroups.updateSettings", root, updateGroupSettings) function deleteRank(rankName) if (client and rankName) then local group_ = getPlayerGroup(client) if (group_) then local rank = getPlayerGroupRank(client) if (getGroupLastRank(group_) == rank) then if (not groupRanks[group_][rankName]) then exports.UCDdx:new(client, "This rank does not exist", 255, 255, 0) return end local prevRank = getPreviousRank(group_, rankName) local rankIndex = getRankIndex(group_, rankName) if (rankIndex == 0 or rankIndex == -1) then exports.UCDdx:new(client, "This rank cannot be removed", 255, 255, 0) return end if (not prevRank) then exports.UCDdx:new(client, "You can't delete this rank because there is no rank before it", 255, 255, 0) return end groupEditingRanks[group_] = true db:exec("DELETE FROM `groups_ranks` WHERE `groupName`=? AND `rankName`=?", group_, rankName) db:exec("UPDATE `groups_ranks` SET `rankIndex` = `rankIndex` - 1 WHERE `rankIndex` > ? AND `groupName`=?", rankIndex, group_) db:exec("UPDATE `groups_members` SET `rank`=? WHERE `rank`=? AND `groupName`=?", prevRank, rankName, group_) groupRanks[group_][rankName] = nil for _, ent in pairs(playerGroupCache) do if (ent[1] == group_) then if (ent[3] == rankName) then ent[3] = prevRank end end end for _, ent in pairs(groupRanks[group_]) do if (ent[2] > rankIndex) then ent[2] = ent[2] - 1 end end groupEditingRanks[group_] = nil triggerEvent("UCDgroups.requestGroupRanks", client) exports.UCDdx:new(client, "Rank "..rankName.." has been deleted", 0, 255, 0) createGroupLog(group_, client.name.." ("..client.account.name..") has deleted rank "..rankName) end end end end addEvent("UCDgroups.deleteRank", true) addEventHandler("UCDgroups.deleteRank", root, deleteRank) function addRank(rankName, prevRank, data) if (client and rankName and prevRank and data) then local group_ = getPlayerGroup(client) if (group_) then local rank = getPlayerGroupRank(client) if (getGroupLastRank(group_) == rank) then if (rankName == "Kick this player") then return end if (groupRanks[group_] and groupRanks[group_][rankName]) then exports.UCDdx:new(client, "A rank with this name already exists", 255, 255, 0) return end groupEditingRanks[group_] = true local rankIndex = getRankIndex(group_, prevRank) db:exec("UPDATE `groups_ranks` SET `rankIndex` = `rankIndex` + 1 WHERE `rankIndex` > ? AND `groupName` = ?", rankIndex, group_) db:exec("INSERT INTO `groups_ranks` (`groupName`, `rankName`, `permissions`, `rankIndex`) VALUES (?, ?, ?, ?)", group_, rankName, toJSON(data), rankIndex + 1) for _, ent in pairs(groupRanks[group_]) do if (ent[2] > rankIndex) then ent[2] = ent[2] + 1 end end groupRanks[group_][rankName] = {data, rankIndex + 1} groupEditingRanks[group_] = nil triggerEvent("UCDgroups.requestGroupRanks", client) exports.UCDdx:new(client, "Rank "..rankName.." has been added", 0, 255, 0) createGroupLog(group_, client.name.." ("..client.account.name..") has added rank "..rankName) end end end end addEvent("UCDgroups.addRank", true) addEventHandler("UCDgroups.addRank", root, addRank) function editRank(rankName, newName, data) if (client and rankName and newName and data) then local group_ = getPlayerGroup(client) if (group_ and getPlayerGroupRank(client) == getGroupLastRank(group_)) then if (newName ~= rankName) then if (groupRanks[group_][newName]) then exports.UCDdx:new(client, "That rank name is already in use", 255, 0, 0) return end end if (getGroupLastRank(group_) == rankName) then if (data[25] ~= true) then outputDebugString("Correct permissions not given for last rank in group "..group_.." with rank "..rankName) return end end if (newName ~= rankName) then local rankIndex = getRankIndex(group_, rankName) groupEditingRanks[group_] = true db:exec("UPDATE `groups_ranks` SET `rankName`=? WHERE `rankName`=? AND `groupName`=?", newName, rankName, group_) db:exec("UPDATE `groups_members` SET `rank`=? WHERE `rank`=? AND `groupName`=?", newName, rankName, group_) local r = groupRanks[group_][rankName] groupRanks[group_][newName] = r groupRanks[group_][rankName] = nil for acc, _data in pairs(playerGroupCache) do if (_data[1] == group_) then if (_data[3] == rankName) then _data[3] = newName end end end if (data and type(data) == "table" and rankIndex ~= -1) then db:exec("UPDATE `groups_ranks` SET `permissions`=? WHERE `rankName`=? AND `groupName`=?", toJSON(data), newName, group_) groupRanks[group_][newName][1] = data end groupEditingRanks[group_] = nil createGroupLog(group_, client.name.." ("..client.account.name..") has edited rank "..rankName.." --> "..newName) else groupEditingRanks[group_] = true db:exec("UPDATE `groups_ranks` SET `permissions`=? WHERE `rankName`=? AND `groupName`=?", toJSON(data), rankName, group_) groupRanks[group_][rankName][1] = data groupEditingRanks[group_] = nil createGroupLog(group_, client.name.." ("..client.account.name..") has edited rank "..rankName) end triggerEvent("UCDgroups.requestGroupRanks", client) exports.UCDdx:new(client, "Rank "..rankName.." has been updated", 0, 255, 0) end end end addEvent("UCDgroups.editRank", true) addEventHandler("UCDgroups.editRank", root, editRank) function requestGroupsForPD(demote, account) if (client and account) then local group_ = getPlayerGroup(client) if (group_) then if (groupEditingRanks[group_]) then exports.UCDdx:new(client, "Ranks are currently being edited - you cannot warn, promote, demote or kick right now", 255, 0, 0) return end local rank = playerGroupCache[tostring(account)][3] if (demote == true) then if (not canPlayerDoActionInGroup(client, "demote")) then exports.UCDdx:new(client, "You are not allowed to demote members", 255, 0, 0) return end if (rank == getGroupFirstRank(group_)) then return end if (isRankHigherThan(group_, rank, getPlayerGroupRank(client)) and getPlayerGroupRank(client) ~= getGroupLastRank(group_)) then return end if (isRankHigherThan(group_, rank, getPlayerGroupRank(client)) == "equal" and not canPlayerDoActionInGroup(client, "demoteWithSameRank")) then exports.UCDdx:new(client, "You are not allowed to demote members with the same rank as you", 255, 0, 0) return end local temp = {} local iter = 0 if (getGroupLastRank(group_) ~= rank) then for i, v in pairs(groupRanks[group_]) do if (v[2] < getRankIndex(group_, rank) and v[2] ~= -1) then temp[v[2]] = i end end else for i, v in pairs(groupRanks[group_]) do if (v[2] > -1) then temp[v[2]] = i end end end triggerClientEvent(client, "UCDgroups.promoteDemoteWindow", client, temp or {}, nil, nil, nil, account) else local clientRank = getPlayerGroupRank(client) local clientRankIndex = getRankIndex(group_, clientRank) local accountRankIndex = getRankIndex(group_, rank) if (rank == getGroupLastRank(group_)) then return end if (accountRankIndex > clientRankIndex and clientRankIndex ~= -1) then return end local temp = {} for i = accountRankIndex, getRankIndex(group_, getPreviousRank(group_, getGroupLastRank(group_))) do for k, v in pairs(groupRanks[group_]) do -- if (clientRankIndex == -1 or clientRankIndex >= i) then if (not canPlayerDoActionInGroup(client, "promoteUntilOwnRank") and clientRankIndex ~= -1) then outputDebugString("clientRankIndex >= "..i.." | and cannot promoteUntilOwnRank") break end -- If their rank is equal to or smaller than the current rank, insert into the table if (accountRankIndex < i) then if (i == v[2]) then temp[i] = k end end end --[[ if (i >= clientRankIndex and clientRankIndex ~= -1) then if (i == clientRankIndex) then if (canPlayerDoActionInGroup(client, "promoteUntilOwnRank")) then temp[i] = getGroupRankFromIndex(group_, i) outputDebugString("Is allowed to do this for rankIndex = "..i) else outputDebugString("Should not be allowed to do this for rankIndex = "..i) end end break else temp[i] = getRankFromIndex(group_, i) end --]] end end --[[local iter = getRankIndex(group_, rank) local r = getRankIndex(group_, rank) while r < getRankIndex(group_, getPreviousRank(group_, getGroupLastRank(group_))) do for k, v in pairs(groupRanks[group_]) do --if (v[2] == iter) then temp[iter] = k iter = iter + 1 --end end end ]] -- Only allow promotions to founder is the specified player is a founder if (clientRankIndex == -1) then temp[-1] = getGroupLastRank(group_) end --for k, v in pairs(temp) do -- outputDebugString(tostring(k).." | "..tostring(v)) --end triggerClientEvent(client, "UCDgroups.promoteDemoteWindow", client, temp or {}, nil, nil, nil, account) end end end end addEvent("UCDgroups.requestGroupsForPD", true) addEventHandler("UCDgroups.requestGroupsForPD", root, requestGroupsForPD) -- Alliances function createAlliance(name) if (client and name) then local groupName = getPlayerGroup(client) if (not groupName) then exports.UCDdx:new(client, "You cannot create an alliance because you are not in a group", 255, 0, 0) return false end if (not canPlayerDoActionInGroup(client, "alliance")) then exports.UCDdx:new(client, "You do not have permission to manage alliances in your group", 255, 0, 0) return false end for _, g in pairs(allianceMembers) do if (g[groupName]) then exports.UCDdx:new(client, "This group is already in an alliance", 255, 0, 0) return false end end if (allianceTable[name]) then exports.UCDdx:new(client, "An alliance with this name already exists", 255, 0, 0) return false end for g in pairs(allianceTable) do if (g:lower() == name:lower()) then exports.UCDdx:new("An alliance with this name, in different case, already exists", 255, 0, 0) return false end end for type_, row in pairs(forbidden) do for _, chars in pairs(row) do if type_ == "whole" then if (name == chars) then exports.UCDdx:new(client, "The specified alliance name is prohibited. If you believe this is a mistake, please notify an administrator.", 255, 0, 0) return false end else if (name:lower():find(chars)) then exports.UCDdx:new(client, "The specified alliance name contains forbidden phrases or characters. If you believe this is a mistake, please notify an administrator.", 255, 0, 0) return false end end end end local d, t = exports.UCDutil:getTimeStamp() db:exec("INSERT INTO `groups_alliances_` (`alliance`, `info`, `colour`, `balance`, `created`) VALUES (?, ?, ?, ?, ?)", name, "Enter alliance information here!", "[ [ 255, 255, 255 ] ]", 0, d.." "..t) db:exec("INSERT INTO `groups_alliances_members` (`alliance`, `groupName`, `rank`) VALUES (?, ?, ?)", name, groupName, "Leader") allianceMembers[name] = {} allianceMembers[name][groupName] = "Leader" allianceTable[name] = {"Enter alliance information here!", "[ [ 255, 255, 255 ] ]", 0, d.." "..t} -- [1] = info, [2] = colour, [3] = balance, [4] = created g_alliance[groupName] = name createAllianceLog(name, groupName, client.name.." ("..client.account.name..") created "..name, true) exports.UCDdx:new(client, "You have successfully created alliance "..name, 0, 255, 0) triggerEvent("UCDgroups.alliance.viewUI", client, true) end end addEvent("UCDgroups.createAlliance", true) addEventHandler("UCDgroups.createAlliance", root, createAlliance) function deleteAlliance() if (client) then local groupName = getPlayerGroup(client) if (not groupName) then exports.UCDdx:new(client, "You are not in a group", 255, 0, 0) return false end local alliance = getGroupAlliance(groupName) if (not alliance) then exports.UCDdx:new(client, "Your group is not in an alliance", 255, 0, 0) return false end if (not canPlayerDoActionInGroup(client, "alliance")) then exports.UCDdx:new(client, "You do not have permission to manage alliances in your group", 255, 0, 0) return false end if (allianceMembers[alliance][groupName] ~= "Leader") then exports.UCDdx:new(client, "You do not have permission to delete the alliance", 255, 0, 0) return false end createAllianceLog(alliance, groupName, client.name.." ("..client.account.name..") has deleted "..alliance, true) db:exec("DELETE FROM `groups_alliances_` WHERE `alliance` = ?", alliance) db:exec("DELETE FROM `groups_alliances_members` WHERE `alliance` = ?", alliance) db:exec("DELETE FROM `groups_alliances_invites` WHERE `alliance` = ?", alliance) db:exec("DELETE FROM `groups_alliances_logs` WHERE `alliance` = ? AND `important` <> 1", alliance) for _, g in ipairs(getAllianceGroups(alliance)) do g_alliance[g] = nil messageGroup(g, client.name.." ("..client.account.name..") has deleted "..alliance, "info") for i, plr in ipairs(getGroupOnlineMembers(g)) do triggerEvent("UCDgroups.alliance.viewUI", plr, true) end end allianceMembers[alliance] = nil allianceTable[alliance] = nil exports.UCDdx:new(client, "You have deleted the alliance "..alliance, 255, 0, 0) end end addEvent("UCDgroups.deleteAlliance", true) addEventHandler("UCDgroups.deleteAlliance", root, deleteAlliance) function joinAlliance(alliance) if (source and source.type == "player" and alliance) then local groupName = getPlayerGroup(source) if (not groupName) then return end if (getGroupAlliance(groupName)) then return end if (not canPlayerDoActionInGroup(source, "alliance")) then exports.UCDdx:new(source, "You do not have permission to manage alliances in your group", 255, 0, 0) return end db:exec("INSERT INTO `groups_alliances_members` (`alliance`, `groupName`, `rank`) VALUES (?, ?, ?)", alliance, groupName, "Member") allianceMembers[alliance][groupName] = "Member" g_alliance[groupName] = alliance messageGroup(groupName, source.name.." ("..source.account.name..") joined the alliance "..alliance, "info") createAllianceLog(alliance, groupName, source.name.." ("..source.account.name..") has accepted the invitation to join the alliance") triggerEvent("UCDgroups.alliance.viewUI", source, true) end end addEvent("UCDgroups.joinAlliance", true) addEventHandler("UCDgroups.joinAlliance", root, joinAlliance) function leaveAlliance() if (client) then local groupName = getPlayerGroup(client) if (not groupName) then exports.UCDdx:new(client, "You are not in a group", 255, 0, 0) return false end local alliance = getGroupAlliance(groupName) if (not alliance) then exports.UCDdx:new(client, "Your group is not in an alliance", 255, 0, 0) return false end if (not canPlayerDoActionInGroup(client, "alliance")) then exports.UCDdx:new(client, "You do not have permission to manage alliances in your group", 255, 0, 0) return false end if (allianceMembers[alliance][groupName] == "Leader") then local leaderCount = 0 for g, rank in pairs(allianceMembers[alliance]) do if (rank == "Leader" and g ~= groupName) then leaderCount = leaderCount + 1 end end if (leaderCount == 0) then exports.UCDdx:new(client, "You cannot leave this alliance as your group is the only one with the Leader rank", 255, 0, 0) return false end end createAllianceLog(alliance, groupName, client.name.." ("..client.account.name..") left the alliance") db:exec("DELETE FROM `groups_alliances_members` WHERE `groupName` = ? AND `alliance` = ?", groupName, alliance) allianceMembers[alliance][groupName] = nil g_alliance[groupName] = nil messageGroup(groupName, client.name.." ("..client.account.name..") left the alliance "..alliance, "info") for i, plr in ipairs(getGroupOnlineMembers(groupName)) do triggerEvent("UCDgroups.alliance.viewUI", plr, true) end exports.UCDdx:new(client, "You have left the alliance "..alliance, 255, 0, 0) end end addEvent("UCDgroups.leaveAlliance", true) addEventHandler("UCDgroups.leaveAlliance", root, leaveAlliance) function promoteGroup(groupName) if (client) then local clientGroup = getPlayerGroup(client) if (not clientGroup) then return false end local alliance = getGroupAlliance(clientGroup) if (not alliance) then return false end if (not getGroupAlliance(groupName) or getGroupAlliance(groupName) ~= alliance) then return false end if (not canPlayerDoActionInGroup(client, "alliance")) then exports.UCDdx:new(client, "You do not have permission to manage alliances in your group", 255, 0, 0) return false end local clientGroupRank = allianceMembers[alliance][clientGroup] if (clientGroupRank ~= "Leader") then exports.UCDdx:new(client, "Your group does not have permission to do this action", 255, 0, 0) return false end local groupRank = allianceMembers[alliance][groupName] if (groupRank == "Leader") then exports.UCDdx:new(client, "You cannot promote this group further", 255, 0, 0) return false end allianceMembers[alliance][groupName] = "Leader" db:exec("UPDATE `groups_alliances_members` SET `rank` = ? WHERE `groupName` = ? AND `alliance` = ?", "Leader", groupName, alliance) createAllianceLog(alliance, clientGroup, client.name.." ("..client.account.name..") has promoted "..groupName.." to Leader") triggerEvent("UCDgroups.alliance.requestMemberList", client) for _, plr in ipairs(getGroupOnlineMembers(groupName)) do triggerEvent("UCDgroups.alliance.viewUI", plr, true) end end end addEvent("UCDgroups.promoteGroup", true) addEventHandler("UCDgroups.promoteGroup", root, promoteGroup) function demoteGroup(groupName) if (client) then local clientGroup = getPlayerGroup(client) if (not clientGroup) then return false end local alliance = getGroupAlliance(clientGroup) if (not alliance) then return false end if (not getGroupAlliance(groupName) or getGroupAlliance(groupName) ~= alliance) then return false end if (not canPlayerDoActionInGroup(client, "alliance")) then exports.UCDdx:new(client, "You do not have permission to manage alliances in your group", 255, 0, 0) return false end local clientGroupRank = allianceMembers[alliance][clientGroup] if (clientGroupRank ~= "Leader") then exports.UCDdx:new(client, "Your group does not have permission to do this action", 255, 0, 0) return false end local groupRank = allianceMembers[alliance][groupName] if (groupRank == "Member") then exports.UCDdx:new(client, "You cannot demote this group further", 255, 0, 0) return false end allianceMembers[alliance][groupName] = "Member" db:exec("UPDATE `groups_alliances_members` SET `rank` = ? WHERE `groupName` = ? AND `alliance` = ?", "Member", groupName, alliance) createAllianceLog(alliance, clientGroup, client.name.." ("..client.account.name..") has demoted "..groupName.." to Member") triggerEvent("UCDgroups.alliance.requestMemberList", client) for _, plr in ipairs(getGroupOnlineMembers(groupName)) do triggerEvent("UCDgroups.alliance.viewUI", plr, true) end end end addEvent("UCDgroups.demoteGroup", true) addEventHandler("UCDgroups.demoteGroup", root, demoteGroup) function kickGroup(groupName) if (client) then local clientGroup = getPlayerGroup(client) if (not clientGroup) then return false end local alliance = getGroupAlliance(clientGroup) if (not alliance) then return false end if (not getGroupAlliance(groupName) or getGroupAlliance(groupName) ~= alliance) then return false end if (not canPlayerDoActionInGroup(client, "alliance")) then exports.UCDdx:new(client, "You do not have permission to manage alliances in your group", 255, 0, 0) return false end local clientGroupRank = allianceMembers[alliance][clientGroup] if (clientGroupRank ~= "Leader") then exports.UCDdx:new(client, "Your group does not have permission to do this action", 255, 0, 0) return false end createAllianceLog(alliance, clientGroup, client.name.." ("..client.account.name..") has kicked "..groupName) allianceMembers[alliance][groupName] = nil g_alliance[groupName] = nil db:exec("DELETE FROM `groups_alliances_members` WHERE `groupName` = ? AND `alliance` = ?", groupName, alliance) triggerEvent("UCDgroups.alliance.requestMemberList", client) for _, plr in ipairs(getGroupOnlineMembers(groupName)) do triggerEvent("UCDgroups.alliance.viewUI", plr, true) end end end addEvent("UCDgroups.kickGroup", true) addEventHandler("UCDgroups.kickGroup", root, kickGroup) function requestAllianceMemberList() if (source) then local groupName = getPlayerGroup(source) local alliance = getGroupAlliance(groupName) local list = {} for g, data in pairs(allianceMembers[alliance]) do table.insert(list, {groupName = g, memberCount = getGroupMemberCount(g), slots = 50, rank = data, colour = {getGroupColour(g)}}) end triggerLatentClientEvent(source, "UCDgroups.alliance.memberList", source, list) end end addEvent("UCDgroups.alliance.requestMemberList", true) addEventHandler("UCDgroups.alliance.requestMemberList", root, requestAllianceMemberList) function updateAllianceInfo(newInfo) if (client) then local groupName = getPlayerGroup(client) if (groupName) then local alliance = getGroupAlliance(groupName) if (not alliance) then return false end allianceTable[alliance][1] = newInfo db:exec("UPDATE `groups_alliances_` SET `info` = ? WHERE `alliance` = ?", newInfo, alliance) createAllianceLog(groupName, client.name.." ("..client.account.name..") has updated the alliance information") for g in pairs(allianceMembers[alliance]) do for _, plr in pairs(getGroupOnlineMembers(g)) do triggerEvent("UCDgroups.alliance.viewUI", plr, true) end end end end end addEvent("UCDgroups.alliance.updateInfo", true) addEventHandler("UCDgroups.alliance.updateInfo", root, updateAllianceInfo) function requestAllianceHistory() if (client) then local groupName = getPlayerGroup(client) if (groupName) then local alliance = getGroupAlliance(groupName) if (alliance) then local history, rows = db:query("SELECT `groupName`, `log` AS `log_` FROM `groups_alliances_logs` WHERE `alliance` = ? ORDER BY `logID` DESC LIMIT 100", alliance):poll(-1) local total = db:query("SELECT COUNT(*) AS `count_` FROM `groups_alliances_logs` WHERE `alliance` = ?", alliance):poll(-1)[1].count_ triggerLatentClientEvent(client, "UCDgroups.alliance.history", client, history or {}, total or 0, rows or 0, alliance) end end end end addEvent("UCDgroups.requestAllianceHistory", true) addEventHandler("UCDgroups.requestAllianceHistory", root, requestAllianceHistory) function toggleAllianceGUI(update) local groupName = getPlayerGroup(source) if (not groupName) then return false end local alliance, info, created local alliancePerms = {} alliance = getGroupAlliance(groupName) or false if (alliance ~= false and allianceTable[alliance]) then created = allianceTable[alliance][4] info = allianceTable[alliance][1] if (allianceMembers[alliance][groupName] == "Leader") then alliancePerms = {[3] = true, [6] = true} else alliancePerms = {[3] = false, [6] = false} end else info = "" created = "N/A" end triggerLatentClientEvent(source, "UCDgroups.alliance.toggleGUI", 15000, false, source, update, alliance, info, alliancePerms, created) end addEvent("UCDgroups.alliance.viewUI", true) addEventHandler("UCDgroups.alliance.viewUI", root, toggleAllianceGUI) function changeAllianceBalance(type_, balanceChange) if (client) then if (not balanceChange or tonumber(balanceChange) == nil) then exports.UCDdx:new(client, "Something went wrong!", 255, 255, 0) return end local group_ = getPlayerGroup(client) if (group_) then local alliance = getGroupAlliance(group_) if (not alliance) then return false end local currentBalance = allianceTable[alliance][3] if (type_ == "deposit") then if (client.money < balanceChange) then exports.UCDdx:new(client, "You can't deposit this much because you don't have it", 255, 0, 0) return end if (balanceChange <= 0) then exports.UCDdx:new(client, "You must enter a positive number", 255, 255, 0) return end allianceTable[alliance][3] = allianceTable[alliance][3] + balanceChange client.money = client.money - balanceChange db:exec("UPDATE `groups_alliances_` SET `balance` = ? WHERE `alliance` = ?", tonumber(allianceTable[alliance][3]), alliance) createAllianceLog(alliance, group_, client.name.." ("..client.account.name..") has deposited $"..exports.UCDutil:tocomma(balanceChange).." into the alliance bank") triggerLatentClientEvent(client, "UCDgroups.alliance.balanceWindow", client, "update", allianceTable[alliance][3]) elseif (type_ == "withdraw") then if ((currentBalance - balanceChange) < 0) then exports.UCDdx:new(client, "The alliance doesn't have this much", 255, 255, 0) return end if (balanceChange <= 0) then exports.UCDdx:new(client, "You must enter a positive number", 255, 255, 0) return end allianceTable[alliance][3] = allianceTable[alliance][3] - balanceChange client.money = client.money + balanceChange db:exec("UPDATE `groups_alliances_` SET `balance` = ? WHERE `alliance` = ?", tonumber(allianceTable[alliance][3]), alliance) createAllianceLog(alliance, group_, client.name.." ("..client.account.name..") has withdrawn $"..exports.UCDutil:tocomma(balanceChange).." from the alliance bank") triggerLatentClientEvent(client, "UCDgroups.alliance.balanceWindow", client, "update", allianceTable[alliance][3]) end end end end addEvent("UCDgroups.alliance.changeBalance", true) addEventHandler("UCDgroups.alliance.changeBalance", root, changeAllianceBalance) function requestAllianceBalance() if (client or source) then local group_ = getPlayerGroup(source) if (group_) then local alliance = getGroupAlliance(group_) if (not alliance) then return false end triggerClientEvent(source, "UCDgroups.alliance.balanceWindow", source, "toggle", tonumber(allianceTable[alliance][3])) end end end addEvent("UCDgroups.requestAllianceBalance", true) addEventHandler("UCDgroups.requestAllianceBalance", root, requestAllianceBalance) -- Used to request the alliance invite list function getGroupsForAlliance() --[[ if (client) then local groupName = getPlayerGroup(client) if (not groupName) then return false end local alliance = getGroupAlliance(groupName) if (not alliance) then return false end if (allianceMembers[alliance][groupName] ~= "Leader") then return false end if (canPlayerDoActionInGroup(client, "alliance")) then --]] local temp = {} for group_, _ in pairs(groupTable) do if (not getGroupAlliance(group_)) then local r, g, b = getGroupColour(group_) table.insert(temp, {group_ = group_, r = r, g = g, b = b}) end end --triggerLatentClientEvent(client, "UCDgroups.alliance.viewInviteGroups", client, temp) return temp --[[ end end --]] end function requestGroupsForAllianceInviteList() if (client) then local groupName = getPlayerGroup(client) if (not groupName) then return false end local alliance = getGroupAlliance(groupName) if (not alliance) then return false end if (allianceMembers[alliance][groupName] ~= "Leader") then return false end if (canPlayerDoActionInGroup(client, "alliance")) then local t = getGroupsForAlliance() triggerLatentClientEvent(client, "UCDgroups.alliance.viewInviteGroups", client, t) end end end addEvent("UCDgroups.alliance.requestGroupsForInvite", true) addEventHandler("UCDgroups.alliance.requestGroupsForInvite", root, requestGroupsForAllianceInviteList) function requestAllianceList() if (client) then local temp = {} for alliance, data in pairs(allianceTable) do table.insert(temp, alliance) end triggerLatentClientEvent(client, "UCDgroups.viewAllianceList", client, temp) end end addEvent("UCDgroups.requestAllianceList", true) addEventHandler("UCDgroups.requestAllianceList", root, requestAllianceList) function requestAllianceInvites() if (source and source.type == "player") then local groupName = getPlayerGroup(source) if (not groupName) then return false end --local alliance = getGroupAlliance(groupName) --if (alliance) then -- return false --end if (not canPlayerDoActionInGroup(source, "alliance")) then return false end local invites = allianceInvites[groupName] if (not invites) then invites = {} end triggerClientEvent(source, "UCDgroups.viewAllianceInvites", source, invites) end end addEvent("UCDgroups.requestAllianceInvites", true) addEventHandler("UCDgroups.requestAllianceInvites", root, requestAllianceInvites) function inviteGroup(group_) if (client) then local groupName = getPlayerGroup(client) if (not groupName) then return false end local alliance = getGroupAlliance(groupName) if (not alliance) then return false end if (allianceMembers[alliance][groupName] ~= "Leader") then return false end if (not canPlayerDoActionInGroup(client, "alliance")) then return false end if (not allianceInvites[group_]) then allianceInvites[group_] = {} end for index, row in pairs(allianceInvites[group_]) do for _, data in pairs(row) do if (data == groupName) then exports.UCDdx:new(client, "This group has already been invited to the alliance", 255, 0, 0) return end end end table.insert(allianceInvites[group_], {alliance, groupName, client.name}) exports.UCDdx:new(client, "You have invited "..tostring(group_).." to "..alliance, 255, 0, 0) db:exec("INSERT INTO `groups_alliances_invites` (`groupName`, `alliance`, `groupBy`, `playerBy`) VALUES (?, ?, ?, ?)", group_, alliance, groupName, client.name) createAllianceLog(alliance, groupName, client.name.." ("..client.account.name..") has invited the group "..group_.." to the alliance") triggerEvent("UCDgroups.alliance.viewUI", client, true) end end addEvent("UCDgroups.inviteGroup", true) addEventHandler("UCDgroups.inviteGroup", root, inviteGroup) function handleAllianceInvite(alliance_, state) if (client and alliance_ and state) then local groupName = getPlayerGroup(client) if (not groupName) then return false end if (not canPlayerDoActionInGroup(client, "alliance")) then exports.UCDdx:new(client, "You do not have permission to manage alliances in your group", 255, 0, 0) return false end for index, row in pairs(allianceInvites[groupName]) do if (row[1] == alliance_) then table.remove(allianceInvites[groupName], index) end end db:exec("DELETE FROM `groups_alliances_invites` WHERE `groupName` = ? AND `alliance` = ?", groupName, alliance_) if (state == "accept") then if (getGroupAlliance(groupName)) then exports.UCDdx:new(client, "Your group can't join this alliance because you are already in one", 255, 0, 0) triggerEvent("UCDgroups.requestAllianceInvites", client) return false end createGroupLog(groupName, client.name.." ("..client.account.name..") has accepted the invite to join alliance "..alliance_) triggerEvent("UCDgroups.joinAlliance", client, alliance_) elseif (state == "deny") then createGroupLog(groupName, client.name.." ("..client.account.name..") has declined the invite to join alliance "..alliance_) exports.UCDdx:new(client, "You have declined the invitation to join alliance "..groupName, 255, 255, 0) end triggerEvent("UCDgroups.requestAllianceInvites", client) end end addEvent("UCDgroups.alliance.handleInvite", true) addEventHandler("UCDgroups.alliance.handleInvite", root, handleAllianceInvite) function allianceChat(plr, _, ...) if (not exports.UCDchecking:canPlayerDoAction(plr, "Chat")) then return end local msg = table.concat({...}, " ") if (msg:gsub(" ", "") == "") then exports.UCDdx:new(plr, "Enter a message!", 255, 0, 0) end if (exports.UCDaccounts:isPlayerLoggedIn(plr) and getPlayerGroup(plr)) then local alliance = g_alliance[getPlayerGroup(plr)] if (not alliance) then exports.UCDdx:new(plr, "Your group is not in an alliance", 255, 0, 0) return end for groupName in pairs(allianceMembers[alliance]) do --messageGroup(groupName, "("..tostring(g_alliance[getPlayerGroup(plr)])..") "..plr.name.." #FFFFFF"..msg, "chat") for _, plr2 in ipairs(getGroupOnlineMembers(groupName)) do outputChatBox("("..tostring(alliance)..") "..plr.name.." #FFFFFF"..msg, plr2, 50, 100, 0, true) exports.UCDchat:insert(plr2, "alliance", plr, msg) end end end end addCommandHandler("ac", allianceChat, false, false) addCommandHandler("alliancec", allianceChat, false, false) addCommandHandler("achat", allianceChat, false, false) addCommandHandler("alliancechat", allianceChat, false, false)
nilq/small-lua-stack
null
local config = require("stickybuf.config") local util = require("stickybuf.util") local M = {} local function open_in_best_window(bufnr) -- Open the buffer in the first window that doesn't have a sticky buffer for winnr = 1, vim.fn.winnr("$") do local winid = vim.fn.win_getid(winnr) if not util.is_sticky_win(winid) then vim.cmd(string.format("%dwincmd w", winnr)) vim.cmd(string.format("buffer %d", bufnr)) return end end -- If none exists, open the buffer in a vsplit from the first window vim.fn.win_execute(vim.fn.win_getid(1), string.format("vertical rightbelow sbuffer %d", bufnr)) vim.cmd([[2wincmd w]]) end local function _on_buf_enter() if util.is_empty_buffer() then return end local stick_type = util.get_stick_type() if not util.is_sticky_match() then -- If this was a sticky buffer window and the buffer no longer matches, restore it util.override_bufhidden() local winid = vim.api.nvim_get_current_win() local newbuf = vim.api.nvim_get_current_buf() vim.fn.win_execute(winid, "noau buffer " .. vim.w.sticky_original_bufnr) -- Then open the new buffer in the appropriate location vim.defer_fn(function() open_in_best_window(newbuf) util.restore_bufhidden() end, 1) elseif stick_type then if stick_type == "bufnr" then M.pin_buffer() elseif stick_type == "buftype" then M.pin_buftype() elseif stick_type == "filetype" then M.pin_filetype() else error(string.format("Unknown sticky buf type '%s'", stick_type)) end end end M.on_buf_enter = function() -- Delay just in case the buffer is blank when entered but some process is -- about to set all the filetype/buftype/etc options vim.defer_fn(_on_buf_enter, 5) end M.on_buf_hidden = function(bufnr) local ok, prev_bufhidden = pcall(vim.api.nvim_buf_get_var, bufnr, "prev_bufhidden") if ok then -- We need a long delay for this to make sure we're not going to restore this buffer vim.defer_fn(function() if vim.api.nvim_buf_is_valid(bufnr) and #vim.fn.win_findbuf(bufnr) == 0 then vim.api.nvim_buf_call(bufnr, function() vim.cmd(string.format("silent! b%s!", prev_bufhidden)) end) end end, 1000) end end local function already_pinned(bang, cmd) if util.is_sticky_win() then if bang == "" then error( string.format("Window is already pinned. Use '%s!' to override or 'silent! %s' to ignore this error", cmd, cmd) ) return true end end M.unpin_buffer(true) end M.pin_buffer = function(bang) if already_pinned(bang, "PinBuffer") then return end vim.w.sticky_original_bufnr = vim.api.nvim_get_current_buf() vim.w.sticky_bufnr = vim.api.nvim_get_current_buf() util.override_bufhidden() end M.pin_buftype = function(bang) if already_pinned(bang, "PinBuftype") then return end vim.w.sticky_original_bufnr = vim.api.nvim_get_current_buf() vim.w.sticky_buftype = vim.bo.buftype util.override_bufhidden() end M.pin_filetype = function(bang) if already_pinned(bang, "PinFiletype") then return end vim.w.sticky_original_bufnr = vim.api.nvim_get_current_buf() vim.w.sticky_filetype = vim.bo.filetype util.override_bufhidden() end M.unpin_buffer = function(keep_bufhidden) vim.w.sticky_original_bufnr = nil vim.w.sticky_bufnr = nil vim.w.sticky_buftype = nil vim.w.sticky_filetype = nil if keep_bufhidden then util.restore_bufhidden() end end M.setup = function(opts) config:update(opts) vim.cmd([[ augroup StickyBuf au! autocmd BufEnter * lua require'stickybuf'.on_buf_enter() augroup END ]]) vim.cmd([[command! -bar -bang PinBuffer call luaeval("require'stickybuf'.pin_buffer(_A)", expand('<bang>'))]]) vim.cmd([[command! -bar -bang PinBuftype call luaeval("require'stickybuf'.pin_buftype(_A)", expand('<bang>'))]]) vim.cmd([[command! -bar -bang PinFiletype call luaeval("require'stickybuf'.pin_filetype(_A)", expand('<bang>'))]]) vim.cmd([[command! -bar UnpinBuffer lua require'stickybuf'.unpin_buffer()]]) local cmd = [[augroup StickyBufIntegration au! ]] for _, autocmd in pairs(config.autocmds) do if autocmd then cmd = string.format("%s\n%s", cmd, autocmd) end end cmd = string.format("%s\naugroup END", cmd) vim.cmd(cmd) end return M
nilq/small-lua-stack
null
deal_guid = '4c4cab' playing_zone_guid = '62af4a' PLAYING_ZONE = nil GAME_MACHINE = nil THIS_IS_A_SAVED_GAME = false TEAM1 = 'TEAM1' TEAM2 = 'TEAM2' TEAM_NAMES = {TEAM1='WhiteGreen', TEAM2='OrangePurple'} PLAYERS_COLOR = {'White', 'Orange', 'Green', 'Purple'} PLAYERS_TEAM = {White=TEAM1, Orange=TEAM2, Green=TEAM1, Purple=TEAM2} FIRST_DEALER = 'White' TEAMS_TRICKS_POS = {TEAM1={10.00, 3, -10.00}, TEAM2={-10.00, 3, -10.00}} TEAMS_TRICKS_ROT = {TEAM1={0.00, 180.00, 180.00}, TEAM2={0.00, 270.00, 180.00}} TEAMS_LAST_TRICKS_POS = {TEAM1={5.00, 3, -10.00}, TEAM2={-10.00, 3, -5.00}} TEAMS_LAST_TRICKS_ROT = {TEAM1={0.00, 180.00, 0.00}, TEAM2={0.00, 270.00, 0.00}} DEALER_POS = {White={10.00, 1.13, -14.00}, Orange={-14.00, 1.13, -10.00}, Green={-10.00, 1.13, 14.00}, Purple={14.00, 1.13, 10.00}} DEALER_ROT = {White={0.00, 180.00, 0.00}, Orange={0.00, 270.00, 0.00}, Green={0.00, 0.00, 0.00}, Purple={0.00, 90.00, 0.00}} SUITS = {'clubs', 'diamonds', 'hearts', 'spades'} FACES = {'Ace', 'King', 'Queen', 'Jack', 'Ten', 'Nine', 'Eight', 'Seven'} CARDS_FACE = {} CARDS_SUIT = {} SUIT_ORDER = {Ace=0, Ten=1, King=2, Queen=3, Jack=4, Nine=5, Eight=6, Seven=7} SUIT_POINT_SCALE = {Ace=11, Ten=10, King=4, Queen=3, Jack=2, Nine=0, Eight=0, Seven=0} TRUMP_ORDER = {Jack=0, Nine=1, Ace=2, Ten=3, King=4, Queen=5, Eight=6, Seven=7} TRUMP_POINT_SCALE = {Jack=20, Nine=14, Ace=11, Ten=10, King=4, Queen=3, Eight=0, Seven=0} CAPOT = 'CAPOT' GENERAL = 'GENERAL' ALLTRUMP = 'ALLTRUMP' NOTRUMP = 'NOTRUMP' --[[ Events callback --]] function onLoad(save_state) UI.hide('contractPanel') UI.hide('teamNameInput') PLAYING_ZONE = getObjectFromGUID(playing_zone_guid) DEALER_TOKEN = getObjectFromGUID(deal_guid) makeButton(DEALER_TOKEN, 'Deal', 'startRound') checkSavedGameMarker() -- Init card face value table for _, suit in ipairs(SUITS) do for _, face in ipairs(FACES) do local card_name = face .. " of " .. suit CARDS_FACE[card_name] = face CARDS_SUIT[card_name] = suit end end -- Setup steam_name for _, player in ipairs(PLAYERS_COLOR) do local ui_id = 'biddingPlayer_' .. player UI.setAttribute(ui_id, 'text', sn(player) .. ' bid') end -- Init game engine if THIS_IS_A_SAVED_GAME and save_state != "" then local lua_state = JSON.decode(save_state) if pcall(function() GAME_MACHINE = GameStateMachine:newFromState(lua_state) end) then print("*** Saved game restored ***") else print("*** Error loading saved game. Sarting a new game engine ***") end end if GAME_MACHINE == nil then GAME_MACHINE = GameStateMachine:new(FIRST_DEALER) pcall(function() findDeck().shuffle() end) end end function checkSavedGameMarker() -- In this function, we leverage the fact that new games have a dealer -- token object without a name. We wait 5 seconds to setup the name of -- the token. However it will be already set on saved game. Wait.time(function() DEALER_TOKEN.setName("Dealer token") end, 5) -- This is run immediatly, hence only saved game will be flag as such. if DEALER_TOKEN.getName() == "Dealer token" then THIS_IS_A_SAVED_GAME = true end end function onSave() return JSON.encode(GAME_MACHINE:dumpState()) end function onObjectEnterScriptingZone(zone, card) if card.tag == 'Card' then GAME_MACHINE:checkCardDrop(card) end end function onPlayerChangeColor(player) if player != 'Grey' then local ui_id = 'biddingPlayer_' .. player UI.setAttribute(ui_id, 'text', sn(player) .. ' bid') end end --[[ Small functions --]] function sn(player) return (Player[player] and Player[player].steam_name) or player end function makeButton(obj, label, fcn) local params = { click_function = fcn, label = label, function_owner = Global, position = {0, 0.2, 0}, rotation = {0, 0, 0}, width = 550, height = 1200, font_size = 250, } obj.createButton(params) end function findDeck() local all_obj = getAllObjects() for _, obj in pairs(all_obj) do if obj.tag == 'Deck' and obj.getQuantity() == 32 then return obj end end broadcastToAll("Reconstitute the original 32 cards deck before dealing", 'Black') error("No 32 cards deck found in the game", 2) end --[[ UI callback --]] function startRound() GAME_MACHINE:dealNewRound() end function setToggleGroupValue(player, value, id) local _, _, parent_id, value = string.find(id, '(%w+)_(%w+)') UI.setAttribute(parent_id, 'value', value) end function playContract(player, value, id) UI.hide('contractPanel') GAME_MACHINE:acceptContract() end function editTeamName(lua_player, value, id) local _, _, team = string.find(id, 'teamName_(%w+)') UI.setAttribute('teamNameInput', 'team', team) UI.setAttribute('teamNameInput', 'text', TEAM_NAMES[team]) UI.show('teamNameInput') UI.setAttribute('teamNameInput', 'visibility', lua_player.color) end function commitTeamName(player, value, id) UI.hide('teamNameInput') local team = UI.getAttribute('teamNameInput', 'team') local team_name_id = "teamName_" .. team TEAM_NAMES[team] = value UI.setAttribute(team_name_id, 'text', value) end function unlockAllCard() local all_obj = getAllObjects() for _, obj in pairs(all_obj) do if obj.tag == 'Card' then obj.setLock(false) end end end function undoTrick() GAME_MACHINE:undoTrick() end function restartRound() GAME_MACHINE:restartRound() end function cancelRound() GAME_MACHINE:cancelRound() end function changeDealer() GAME_MACHINE:changeDealer() end function resetScores() GAME_MACHINE.game:resetScores() end function showContractUI() UI.show('contractPanel') UI.setAttribute('contractPanel', 'visibility', 'host') -- Ensure coherency between UI and underlying data function setToggleFromGroupValue(id_prefix) local group_value = UI.getAttribute(id_prefix, 'value') if group_value != nil then local id = id_prefix .. '_' .. group_value UI.setAttribute(id, 'isOn', true) end end setToggleFromGroupValue('biddingPlayer') setToggleFromGroupValue('contractSuite') setToggleFromGroupValue('contractLevel') setToggleFromGroupValue('coincheLevel') end function hideContractUI() UI.hide('contractPanel') end function earlyScoreFailedContract() GAME_MACHINE:earlyScoreFailedContract() end --[[ Coinche game objects --]] GameStateMachine = { INVALID_STATE = 'invalid_state', CARD_DEALT = 'card_dealt', IN_FIRST_TRICK = 'in_first_trick', IN_ROUND = 'in_round', ROUND_FINISHED = 'round_finished', } function GameStateMachine:new(first_dealer) local obj = { game = CoincheGame:new(first_dealer), round = nil, trick = nil, state = self.ROUND_FINISHED, } setmetatable(obj, self) self.__index = self return obj end function GameStateMachine:changeDealer() if self.state == self.ROUND_FINISHED then self.game:changeDealer() else print("Can only change dealer between rounds") end end function GameStateMachine:dealNewRound() if self.state == self.ROUND_FINISHED then printToAll("New round", 'Black') self.game:dealCards() showContractUI() self.state = self.CARD_DEALT else print("Can't deal while game is running") end end function GameStateMachine:restartRound() if self.state == self.IN_ROUND or self.state == self.IN_FIRST_TRICK then self.state = self.INVALID_STATE printToAll("Restarting round !", 'Black') self.round:dealAgain() self.state = self.CARD_DEALT self:acceptContract() else print("Can only restart a round when one is running") end end function GameStateMachine:cancelRound() if self.state != self.ROUND_FINISHED then for _=1,3 do self.game.dealer_iterator:next() end self.state = self.ROUND_FINISHED printToAll("Game state reset. Deal a new round.", 'Black') else print("Can't reset a finished round") end end function GameStateMachine:acceptContract() if self.state == self.CARD_DEALT or self.state == self.IN_FIRST_TRICK then self.state = self.INVALID_STATE local contract = self:getContractFromUI() self.round = self.game:startRound(contract) self:startTrick() else print("Can't change contract at this stage") end end function GameStateMachine:startTrick() self.state = self.INVALID_STATE self.trick = self.round:nextTrick() if self.round.trick_count == 1 then self.state = self.IN_FIRST_TRICK else self.state = self.IN_ROUND end end function GameStateMachine:scoreTrick(played_cards) self.state = self.INVALID_STATE local trick_winner = self.trick:computeWinner(played_cards) local trick_score = self.trick:computeScore(played_cards) round_finished = self.round:scoreTrick(trick_winner, trick_score, played_cards) -- Check if the trick finishes the round if round_finished then self:finishRound() else self:startTrick() end end function GameStateMachine:undoTrick() if self.state == self.IN_ROUND then self.state = self.INVALID_STATE if self.round:undoTrick() then self:startTrick() elseif self.round.trick_count == 1 then self.state = self.IN_FIRST_TRICK else self.state = self.IN_ROUND end else print("Can only undo tricks during a round") end end function GameStateMachine:earlyScoreFailedContract() if self.state == self.IN_ROUND or self.state == self.IN_FIRST_TRICK then if self.round:earlyCheckFailedContract() then self:finishRound() else print("Contract has not failed yet") end else print("Can only finish a round when in a round") end end function GameStateMachine:finishRound() self.state = self.INVALID_STATE self.game:scoreRound(self.round) self.game:moveDealerToken() self.state = self.ROUND_FINISHED end function GameStateMachine:getContractFromUI() local trump_mode = UI.getAttribute('contractSuite', 'value') local raw_level = UI.getAttribute('contractLevel', 'value') local coinch_level = tonumber(UI.getAttribute('coincheLevel', 'value')) local level local defending_level = -1 local score if raw_level == CAPOT then level = CAPOT score = 250 elseif raw_level == GENERAL then level = GENERAL score = 500 else local base_level = tonumber(raw_level) score = tonumber(raw_level) if trump_mode == ALLTRUMP then level = math.floor(base_level * 248 / 162) level = math.max(level, 125) defending_level = 248 - level + 1 elseif trump_mode == NOTRUMP then level = math.floor(base_level * 130 / 162) level = math.max(level, 66) defending_level = 130 - level + 1 else level = math.max(base_level, 82) defending_level = 162 - level + 1 end end score = score * 2^(coinch_level) local contract = { bidding_player = UI.getAttribute('biddingPlayer', 'value'), trump_mode = trump_mode, level = level, defending_level = defending_level, score = score, } printToAll("Contract by ".. sn(contract.bidding_player), 'Black') printToAll(" Suit: ".. contract.trump_mode, 'Black') printToAll(" Level: ".. contract.level, 'Black') if defending_level > 0 then printToAll(" Defending level: ".. contract.defending_level, 'Black') end printToAll(" Score: ".. contract.score, 'Black') return contract end function GameStateMachine:dumpState() save_state = { global_state = self.state, game_state = self.game:dumpState(), } if (self.state == self.IN_ROUND) or (self.state == self.IN_FIRST_TRICK) then save_state.round_state = self.round:dumpState() end return save_state end function GameStateMachine:newFromState(state) new_machine = self:new(FIRST_DEALER) new_machine.state = state.global_state new_machine.game = CoincheGame:newFromState(state.game_state) if new_machine.state == self.IN_ROUND or new_machine.state == self.IN_FIRST_TRICK then new_machine.round = CoincheRound:newFromState(state.round_state) new_machine:startTrick() end return new_machine end function GameStateMachine:checkCardDrop(card) if self.state == self.IN_FIRST_TRICK or self.state == self.IN_ROUND and not self.round:cardAlreadyPlayed(card) then -- Using coroutine to wait 1 frame for the dropped card to be register as "in the zone" Wait.time(function() card.setLock(true) end, 0.5) function checkCardDropCoroutine() coroutine.yield(0) -- Check if last card in zone finishes the trick trick_finished, played_cards = self.trick:checkFinished(self.round) if trick_finished then self:scoreTrick(played_cards) end -- Apparently, coroutine should return 1 return 1 end startLuaCoroutine(Global, 'checkCardDropCoroutine') end end CoincheGame = {} function CoincheGame:new(first_dealer) local obj = { dealer_iterator = PlayerIterator:new(first_dealer), score_board = ScoreBoard:new(), cards_player = {}, } setmetatable(obj, self) self.__index = self return obj end function CoincheGame:startRound(contract) local first_leader = self.dealer_iterator:peek_next() return CoincheRound:new(first_leader, self.cards_player, contract) end function CoincheGame:scoreRound(round) local winning_team = round:whichTeamWon() self.score_board:scoreRound(winning_team, round.contract.score) printToAll("Final round score:", 'Black') printToAll(" Contract level: ".. round.contract.level, 'Black') printToAll(" ".. TEAM_NAMES[TEAM1] ..": ".. round.scores[TEAM1] .." points", 'Black') printToAll(" ".. TEAM_NAMES[TEAM2] ..": ".. round.scores[TEAM2] .." points", 'Black') printToAll(" ".. TEAM_NAMES[winning_team] .." scored ".. round.contract.score .." points in this round", 'Black') end function CoincheGame:resetScores() self.score_board:resetScores() end function CoincheGame:moveDealerToken() local next_dealer = self.dealer_iterator:peek_next() DEALER_TOKEN.setRotation(DEALER_ROT[next_dealer]) DEALER_TOKEN.setPositionSmooth(DEALER_POS[next_dealer], false, false) end function CoincheGame:dealCards() local deck = findDeck() local dealer = self.dealer_iterator:next() local cards_dealt_by_turns = {3, 2, 3} for _, cards_dealt in ipairs(cards_dealt_by_turns) do -- First card is dealt to the player after the dealer local player_iterator = PlayerIterator:new(dealer, 5) player_iterator:next() for player in player_iterator:iter() do deck.deal(cards_dealt, player) end end -- And assign cards to player. Wait.condition( function() for _, player in ipairs(PLAYERS_COLOR) do local player_hand = Player[player].getHandObjects() for _, card in ipairs(player_hand) do self.cards_player[card.getName()] = player end end end, -- We wait for each player to have 8 cards function() for _, player in ipairs(PLAYERS_COLOR) do if #Player[player].getHandObjects() < 8 then return false end end return true end ) end function CoincheGame:changeDealer() self.dealer_iterator:next() self:moveDealerToken() end function CoincheGame:dumpState() return { next_dealer = self.dealer_iterator:peek_next(), score_board_state = self.score_board:dumpState(), cards_player = self.cards_player, } end function CoincheGame:newFromState(state) game = self:new(FIRST_DEALER) game.dealer_iterator = PlayerIterator:new(state.next_dealer) game.score_board:restoreState(state.score_board_state) game.cards_player = state.cards_player return game end CoincheRound = {} function CoincheRound:new(first_leader, cards_player, contract) local obj = { next_leader = first_leader, contract = contract, cards_player = cards_player, trick_count = 0, cards_played = {}, scores = {TEAM1=0, TEAM2=0}, player_nb_tricks_won = {White=0, Orange=0, Green=0, Purple=0}, team_nb_tricks_won = {TEAM1=0, TEAM2=0}, previous_trick_cards = nil, previous_scoring_team = nil, trick_history = nil, } setmetatable(obj, self) self.__index = self return obj end function CoincheRound:getCardPlayer(card) return self.cards_player[card.getName()] end function CoincheRound:cardAlreadyPlayed(card) return self.cards_played[card.getName()] != nil end function CoincheRound:nextTrick() self.trick_count = self.trick_count + 1 broadcastToAll("Trick " .. self.trick_count .. ": " .. sn(self.next_leader) .. " start", self.next_leader) return CoincheTrick:new(self.next_leader, self.contract.trump_mode, self.trick_count) end function CoincheRound:scoreTrick(trick_winner, trick_score, played_cards) for _, card in pairs(played_cards) do self.cards_played[card.getName()] = true end local scoring_team = PLAYERS_TEAM[trick_winner] printToAll(sn(trick_winner) .." scored ".. trick_score .." points in this trick", trick_winner) self.scores[scoring_team] = self.scores[scoring_team] + trick_score self.player_nb_tricks_won[trick_winner] = self.player_nb_tricks_won[trick_winner] + 1 self.team_nb_tricks_won[scoring_team] = self.team_nb_tricks_won[scoring_team] + 1 local trick_undo = { played_cards = played_cards, score = trick_score, winner = trick_winner, scoring_team = scoring_team, next_leader = self.next_leader, } self.trick_history = trick_undo self.next_leader = trick_winner if self.trick_count < 8 then -- Quick wait because some sketchy grouping occurs on the last card dropped Wait.time(function() self:storeTrickCards(scoring_team, played_cards) end, 1) else -- Unlock cards of last trick. We wait for the last card lock coroutine Wait.time(function () for _, card in pairs(played_cards) do card.setLock(false) end end, 1) end return self.trick_count >= 8 end function CoincheRound:undoTrick() -- Early returns if can't undo trick if self.trick_count <= 1 then return false end if self.trick_history == nil then print("Can only undo last trick") return false end printToAll("Undoing last trick", 'Black') self.trick_count = self.trick_count - 2 -- Minus 2 because a +1 allready occured local trick = self.trick_history self.trick_history = nil self.previous_trick_cards = nil for player, card in pairs(trick.played_cards) do local player_hand_transform = Player[player].getHandTransform() card.setPosition(player_hand_transform.position) card.setRotation(player_hand_transform.rotation) self.cards_played[card.getName()] = nil end self.scores[trick.scoring_team] = self.scores[trick.scoring_team] - trick.score self.player_nb_tricks_won[trick.winner] = self.player_nb_tricks_won[trick.winner] + 1 self.team_nb_tricks_won[trick.scoring_team] = self.team_nb_tricks_won[trick.scoring_team] - 1 self.next_leader = trick.next_leader return true end function CoincheRound:whichTeamWon() local bidding_team = PLAYERS_TEAM[self.contract.bidding_player] local defending_team if bidding_team == TEAM1 then defending_team = TEAM2 else defending_team = TEAM1 end local winning_team if self.contract.level == CAPOT then if self.team_nb_tricks_won[bidding_team] == 8 then winning_team = bidding_team else winning_team = defending_team end elseif self.contract.level == GENERAL then if self.player_nb_tricks_won[self.contract.bidding_player] == 8 then winning_team = bidding_team else winning_team = defending_team end else local level_with_belote = self.contract.level if self:biddingTeamHasBelote() then level_with_belote = math.max(level_with_belote - 20, 82) end if self.scores[bidding_team] >= level_with_belote then winning_team = bidding_team else winning_team = defending_team end end if winning_team == bidding_team then broadcastToAll("Successful contract", 'Green') else broadcastToAll("Failed contract", 'Red') end return winning_team end function CoincheRound:earlyCheckFailedContract() local bidding_team = PLAYERS_TEAM[self.contract.bidding_player] local defending_team if bidding_team == TEAM1 then defending_team = TEAM2 else defending_team = TEAM1 end local contract_already_failed = false if self.contract.level == CAPOT then if self.team_nb_tricks_won[defending_team] > 0 then contract_already_failed = true end elseif self.contract.level == GENERAL then other_player_iterator = PlayerIterator:new(self.contract.bidding_player, 4) other_player_iterator:next() for player in other_player_iterator:iter() do if self.player_nb_tricks_won[player] > 0 then contract_already_failed = true break end end else local level_with_belote = self.contract.level if self:biddingTeamHasBelote() then level_with_belote = math.max(level_with_belote - 20, 82) end if self.scores[defending_team] >= self.contract.defending_level then contract_already_failed = true end end return contract_already_failed end function CoincheRound:biddingTeamHasBelote() local has_belote = false if self.contract.trump_mode != ALLTRUMP and self.contract.trump_mode != NOTRUMP then local trump_king = "King of " .. self.contract.trump_mode local trump_queen = "Queen of " .. self.contract.trump_mode local trump_king_holder = self.cards_player[trump_king] local trump_queen_holder = self.cards_player[trump_queen] local bidding_team = PLAYERS_TEAM[self.contract.bidding_player] local belote_holder_team = PLAYERS_TEAM[trump_king_holder] has_belote = (trump_king_holder == trump_queen_holder) and (belote_holder_team == bidding_team) end return has_belote end function CoincheRound:storeTrickCards(scoring_team, played_cards) if self.previous_trick_cards != nil then for _, card in pairs(self.previous_trick_cards) do if getObjectFromGUID(card.guid) != nil then card.setRotation(TEAMS_TRICKS_ROT[self.previous_scoring_team]) card.setPosition(TEAMS_TRICKS_POS[self.previous_scoring_team]) end end end local next_global_pos = TEAMS_LAST_TRICKS_POS[scoring_team] for player in PlayerIterator:new(self.trick_history.next_leader, 4):iter() do local card = played_cards[player] card.setLock(false) card.setRotation(TEAMS_LAST_TRICKS_ROT[scoring_team]) card.setPosition(next_global_pos) -- The next card is placed relative the previous card next_global_pos = card.positionToWorld({2.00, 1.00, 0.00}) end self.previous_trick_cards = played_cards self.previous_scoring_team = scoring_team end function CoincheRound:dealAgain() -- First give all card to one player local all_obj = getAllObjects() for _, obj in pairs(all_obj) do if obj.tag == 'Card' then obj.deal(1, FIRST_DEALER) elseif obj.tag == 'Deck' then for _ = 1,obj.getQuantity() do obj.deal(1, FIRST_DEALER) end end end -- Then give all card to it's respective player Wait.time(function () local player_hand = Player[FIRST_DEALER].getHandObjects() for _, card in ipairs(player_hand) do local card_player = self:getCardPlayer(card) card.deal(1, card_player) end end, 1.2) end function CoincheRound:dumpState() return { next_leader = self.next_leader, contract = self.contract, cards_player = self.cards_player, trick_count = self.trick_count, cards_played = self.cards_played, scores = self.scores, player_nb_tricks_won = self.player_nb_tricks_won, team_nb_tricks_won = self.team_nb_tricks_won, } end function CoincheRound:newFromState(state) round = self:new(nil, nil) round.next_leader = state.next_leader round.contract = state.contract round.cards_player = state.cards_player round.trick_count = state.trick_count - 1 -- Minus 1 because of the call to nextTrick round.cards_played = state.cards_played round.scores = state.scores round.player_nb_tricks_won = state.player_nb_tricks_won round.team_nb_tricks_won = state.team_nb_tricks_won return round end CoincheTrick = {} function CoincheTrick:new(leader, trump_mode, trick_number) local obj = { leader = leader, trump_mode = trump_mode, trick_number = trick_number, } setmetatable(obj, self) self.__index = self return obj end function CoincheTrick:checkFinished(round) -- Get cards in play local played_cards = {} local card_count = 0 local player_count = 0 for _, obj in pairs(PLAYING_ZONE.getObjects()) do if obj.tag == 'Card' then local card = obj if not round:cardAlreadyPlayed(card) then local player = round:getCardPlayer(card) if played_cards[player] == nil then player_count = player_count + 1 end played_cards[player] = card card_count = card_count + 1 end end end if card_count > 4 then broadcastToAll("To many cards on the table", 'Black') end local trick_is_done = (card_count == 4) and (player_count == 4) return trick_is_done, played_cards end function CoincheTrick:computeWinner(played_cards) local leader_card = played_cards[self.leader] local asked_suit = CARDS_SUIT[leader_card.getName()] -- Return value local winner = nil -- Check if check can be ruffed if self.trump_mode != NOTRUMP or self.trump_mode != ALLTRUMP or self.trump_mode != asked_suit then -- Gather trump cards local trump_cards = {} for player, card in pairs(played_cards) do local card_suit = CARDS_SUIT[card.getName()] if card_suit == self.trump_mode then trump_cards[player] = card end end -- If there is are trump cards, select a winner among them if next(trump_cards) != nil then winner = self:computeSuitWinner(trump_cards, TRUMP_ORDER) end end -- If there was no ruffing, the winner is selected among those who followed if winner == nil then -- Gather suit cards local suit_cards = {} for player, card in pairs(played_cards) do local card_suit = CARDS_SUIT[card.getName()] if card_suit == asked_suit then suit_cards[player] = card end end -- Selection of the suit order local suit_order if self.trump_mode == ALLTRUMP or self.trump_mode == asked_suit then suit_order = TRUMP_ORDER else suit_order = SUIT_ORDER end -- And select de the winner winner = self:computeSuitWinner(suit_cards, suit_order) end return winner end function CoincheTrick:computeSuitWinner(played_cards, order) local winner local winner_rank = 100 for player, card in pairs(played_cards) do local card_face = CARDS_FACE[card.getName()] local player_rank = order[card_face] if player_rank < winner_rank then winner_rank = player_rank winner = player end end return winner end function CoincheTrick:computeScore(played_cards) local default_points_scale if self.trump_mode == ALLTRUMP then default_points_scale = TRUMP_POINT_SCALE else default_points_scale = SUIT_POINT_SCALE end local score = 0 for _, card in pairs(played_cards) do local point_scale = default_points_scale local card_suit = CARDS_SUIT[card.getName()] local card_face = CARDS_FACE[card.getName()] if card_suit == self.trump_mode then point_scale = TRUMP_POINT_SCALE end score = score + point_scale[card_face] end if self.trick_number == 8 then score = score + 10 end return score end --[[ Tools -]] ScoreBoard = {} function ScoreBoard:new() local obj = { scores = {TEAM1=0, TEAM2=0}, row_height = 15, max_rows = 29, } setmetatable(obj, self) self.__index = self return obj end function ScoreBoard:scoreRound(winning_team, score) -- Here we do tedious manual navigation in the xml. Don't look. local current_table = UI.getXmlTable() self.scores[winning_team] = self.scores[winning_team] + score local team_id = (winning_team == TEAM1 and 1) or 2 -- Navigation: Scoreboard panel / Header table / Second row / Winning cell / Text local total_text = current_table[3].children[1].children[2].children[team_id].children[1] total_text.attributes.text = self.scores[winning_team] -- Navigation: Scoreboard panel / Rounds table / Rows local rounds_rows = current_table[3].children[2].children if #rounds_rows >= self.max_rows then table.remove(rounds_rows, 1) end rounds_rows[#rounds_rows+1] = self:makeRoundRow(winning_team, score) UI.setXmlTable(current_table) end function ScoreBoard:makeRoundRow(winning_team, score) local team_id = (winning_team == TEAM1 and 1) or 2 local row = { tag = 'Row', attributes = { preferredHeight=self.row_height }, children = { { tag='Cell' }, { tag='Cell' }, }, } local text = { tag = 'Text', attributes = { class='Text12', text=score }, } row.children[team_id].children = { text } return row end function ScoreBoard:resetScores() self.scores = {TEAM1=0, TEAM2=0} local current_table = UI.getXmlTable() -- Reset totals local total_texts = current_table[3].children[1].children[2].children total_texts[1].children[1].attributes.text= 0 total_texts[2].children[1].attributes.text= 0 -- Reset rounds current_table[3].children[2].children = {} UI.setXmlTable(current_table) end function ScoreBoard:dumpState() local current_table = UI.getXmlTable() return { scores = {TEAM1=0, TEAM2=0}, sb_header = current_table[3].children[1], sb_rounds = current_table[3].children[2], } end function ScoreBoard:restoreState(state) self.scores = state.scores -- We wait a little here tso that UI.getXmlTable() take into account -- the UI onLoad setup. If not we would revert changes. Wait.time(function() local current_table = UI.getXmlTable() current_table[3].children[1] = state.sb_header current_table[3].children[2] = state.sb_rounds UI.setXmlTable(current_table) end, 0.5) end PlayerIterator = {} function PlayerIterator:new(first_player, limit) local first_player = first_player or FIRST_DEALER local first_index for index, color in ipairs(PLAYERS_COLOR) do if color == first_player then first_index = index end end local obj = { next_index = first_index, limit = limit, count = 0, } setmetatable(obj, self) self.__index = self return obj end function PlayerIterator:next() local next_player if self.limit == nil or self.count < self.limit then next_player = PLAYERS_COLOR[self.next_index] self.next_index = (self.next_index % 4) + 1 self.count = self.count + 1 end return next_player end function PlayerIterator:peek_next() return PLAYERS_COLOR[self.next_index] end function PlayerIterator:iter() return function() return self:next() end end function print_table(a_table) function recursive(x, path) for k,v in pairs(x) do key_path = path .. '/' .. k if type(v) == 'table' then recursive(v, key_path) else print(key_path, ' ', v) end end end if a_table == nil then print('nil') else recursive(a_table, '') end end
nilq/small-lua-stack
null
data:extend{ { type = "recipe", name = "ultra-light-solar-panel", ingredients = { {"low-density-structure", 5}, {"advanced-circuit", 2}, }, energy_required = 20, result = "ultra-light-solar-panel", enabled = false }, { type = "recipe", name = "microwave-power-transmitter", ingredients = { {"copper-cable", 30}, {"steel-plate", 5}, {"plastic-bar", 5}, {"processing-unit", 2} }, energy_required = 30, result = "microwave-power-transmitter", enabled = false }, { type = "recipe", name = "dyson-statite", ingredients = { {"low-density-structure", 4}, {"radar", 1}, {"ultra-light-solar-panel", 4}, {"microwave-power-transmitter", 1} }, energy_required = 5, result = "dyson-statite", enabled = false }, { type = "recipe", name = "dyson-swarm-controller", ingredients = { {"low-density-structure", 20}, {"radar", 1}, {"solar-panel", 5}, {"microwave-power-transmitter", 50}, {"battery", 20}, {"processing-unit", 20} }, energy_required = 120, result = "dyson-swarm-controller", enabled = false } }
nilq/small-lua-stack
null
-- 破防种类 CONST_BREAK_ARMOR_TYPE = { avoid = { value = "avoid", label = "回避" }, invincible = { value = "invincible", label = "无敌" }, -- enchant = { value = "enchant", label = "附魔" }, }
nilq/small-lua-stack
null
SkadaPerCharDB = { ["total"] = { ["healingabsorbed"] = 0, ["dispells"] = 0, ["ccbreaks"] = 0, ["time"] = 0, ["interrupts"] = 0, ["damage"] = 67, ["players"] = { { ["healingabsorbed"] = 0, ["class"] = "ROGUE", ["damaged"] = { }, ["auras"] = { }, ["role"] = "NONE", ["time"] = 0, ["interrupts"] = 0, ["power"] = { }, ["damage"] = 67, ["damagespells"] = { ["Sinister Strike"] = { ["min"] = 67, ["hit"] = 1, ["totalhits"] = 1, ["id"] = 1752, ["max"] = 67, ["damage"] = 67, }, }, ["maxhp"] = 560, ["damagetaken"] = 2, ["deathlog"] = { { ["ts"] = 1447725128.733, ["amount"] = -1, ["hp"] = 560, ["spellid"] = 88163, ["srcname"] = "Tunneling Worm", }, -- [1] { ["absorb"] = 0, ["amount"] = 1, ["hp"] = 560, ["ts"] = 1447725128.733, ["spellid"] = 59913, ["srcname"] = "Jyggfyra", }, -- [2] { ["absorb"] = 0, ["amount"] = 1, ["hp"] = 560, ["ts"] = 1447725140.408, ["spellid"] = 59913, ["srcname"] = "Jyggfyra", }, -- [3] { ["ts"] = 1447725145.484, ["amount"] = -1, ["hp"] = 560, ["spellid"] = 88163, ["srcname"] = "Tunneling Worm", }, -- [4] { ["absorb"] = 0, ["amount"] = 1, ["hp"] = 560, ["ts"] = 1447725145.484, ["spellid"] = 59913, ["srcname"] = "Jyggfyra", }, -- [5] { ["absorb"] = 0, ["amount"] = 0, ["hp"] = 560, ["ts"] = 1447725150.607, ["spellid"] = 59913, ["srcname"] = "Jyggfyra", }, -- [6] { ["absorb"] = 0, ["amount"] = 0, ["hp"] = 574, ["ts"] = 1447725158.859, ["spellid"] = 59913, ["srcname"] = "Jyggfyra", }, -- [7] ["pos"] = 8, }, ["id"] = "Player-1403-06006097", ["overhealing"] = 56, ["damagetakenspells"] = { ["Attack"] = { ["crushing"] = 0, ["id"] = 6603, ["min"] = 1, ["absorbed"] = 0, ["critical"] = 0, ["glancing"] = 0, ["multistrike"] = 0, ["name"] = "Attack", ["blocked"] = 0, ["totalhits"] = 2, ["resisted"] = 0, ["max"] = 1, ["damage"] = 2, }, }, ["healingspells"] = { ["Swift Hand of Justice"] = { ["shielding"] = 0, ["id"] = 59913, ["healing"] = 3, ["min"] = 0, ["multistrike"] = 0, ["name"] = "Swift Hand of Justice", ["max"] = 1, ["critical"] = 0, ["absorbed"] = 0, ["overhealing"] = 56, ["hits"] = 5, }, }, ["shielding"] = 0, ["name"] = "Jyggfyra", ["healing"] = 3, ["healed"] = { ["Player-1403-06006097"] = { ["role"] = "NONE", ["name"] = "Jyggfyra", ["amount"] = 3, ["class"] = "ROGUE", ["shielding"] = 0, }, }, ["dispells"] = 0, ["ccbreaks"] = 0, ["multistrikes"] = 0, }, -- [1] }, ["deaths"] = 0, ["mobs"] = { ["Tunneling Worm"] = { ["players"] = { ["Jyggfyra"] = { ["taken"] = 67, ["done"] = 2, ["role"] = "NONE", ["class"] = "ROGUE", }, }, ["hdone"] = 0, ["htakenspell"] = { }, ["taken"] = 67, ["done"] = 2, ["htaken"] = 0, ["hdonespell"] = { }, }, }, ["mobtaken"] = 67, ["healing"] = 3, ["power"] = { }, ["multistrikes"] = 0, ["overhealing"] = 56, ["shielding"] = 0, ["name"] = "Total", ["starttime"] = 1447725128, ["damagetaken"] = 2, ["mobhdone"] = 0, ["last_action"] = 1447725128, ["mobdone"] = 2, }, ["sets"] = { }, }
nilq/small-lua-stack
null
----------------------------------- -- -- Zone: Konschtat_Highlands (108) -- ----------------------------------- local ID = require("scripts/zones/Konschtat_Highlands/IDs") require("scripts/globals/icanheararainbow") require("scripts/globals/chocobo_digging") require("scripts/globals/conquest") require("scripts/globals/missions") require("scripts/globals/chocobo") ----------------------------------- function onChocoboDig(player, precheck) return tpz.chocoboDig.start(player, precheck) end function onInitialize(zone) tpz.chocobo.initZone(zone) end function onZoneIn( player, prevZone) local cs = -1 if player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0 then player:setPos(521.922, 28.361, 747.85, 45) end if triggerLightCutscene(player) then -- Quest: I Can Hear A Rainbow cs = 104 elseif player:getCurrentMission(WINDURST) == tpz.mission.id.windurst.VAIN and player:getCharVar("MissionStatus") == 1 then cs = 106 end return cs end function onConquestUpdate(zone, updatetype) tpz.conq.onConquestUpdate(zone, updatetype) end function onRegionEnter( player, region) end function onEventUpdate( player, csid, option) if csid == 104 then lightCutsceneUpdate(player) -- Quest: I Can Hear A Rainbow elseif csid == 106 then if player:getZPos() > 855 then player:updateEvent(0, 0, 0, 0, 0, 2) elseif player:getXPos() > 32 and player:getXPos() < 370 then player:updateEvent(0, 0, 0, 0, 0, 1) end end end function onEventFinish( player, csid, option) if csid == 104 then lightCutsceneFinish(player) -- Quest: I Can Hear A Rainbow end end function onGameHour(zone) local hour = VanadielHour() if hour < 5 or hour >= 17 then local phase = VanadielMoonPhase() local haty = GetMobByID(ID.mob.HATY) local vran = GetMobByID(ID.mob.BENDIGEIT_VRAN) local time = os.time() if phase >= 90 and not haty:isSpawned() and time > haty:getLocalVar("cooldown") then SpawnMob(ID.mob.HATY) elseif phase <= 10 and not vran:isSpawned() and time > vran:getLocalVar("cooldown") then SpawnMob(ID.mob.BENDIGEIT_VRAN) end end end
nilq/small-lua-stack
null
local venn = require("venn") -- venn.nvim: enable or disable keymappings function _G.Toggle_venn() local venn_enabled = vim.inspect(vim.b.venn_enabled) if venn_enabled == "nil" then vim.b.venn_enabled = true vim.cmd[[setlocal ve=all]] -- draw a line on HJKL keystokes vim.api.nvim_buf_set_keymap(0, "n", "J", "<C-v>j:VBox<CR>", {noremap = true}) vim.api.nvim_buf_set_keymap(0, "n", "K", "<C-v>k:VBox<CR>", {noremap = true}) vim.api.nvim_buf_set_keymap(0, "n", "L", "<C-v>l:VBox<CR>", {noremap = true}) vim.api.nvim_buf_set_keymap(0, "n", "H", "<C-v>h:VBox<CR>", {noremap = true}) -- draw a box by pressing "f" with visual selection vim.api.nvim_buf_set_keymap(0, "v", "f", ":VBox<CR>", {noremap = true}) else vim.cmd[[setlocal ve=]] vim.cmd[[mapclear <buffer>]] vim.b.venn_enabled = nil end end -- toggle keymappings for venn using <leader>v vim.api.nvim_set_keymap('n', '<leader>vvv', ":lua Toggle_venn()<CR>", { noremap = true})
nilq/small-lua-stack
null
-- ({ { key, value }[], deletedKeys, actualDeletedKeysCount }) GetOrClean(long maximumEmptyLastAccessTimeInSeconds, bool whatif, params string[] keys) local maximumEmptyLastAccessTimeInSeconds = tonumber(ARGV[1]); local whatif = tonumber(ARGV[2]); -- Rest of arguments is are keys local TRUE = 1; local entries = {}; local index = 1; local deletedKeysIndex = 0; local actualDeletedKeysCount = 0; local deletedKeys = {}; for i=3,#ARGV do local key = ARGV[i]; local lastAccessTime = redis.call("OBJECT", "IDLETIME", key); local value = redis.pcall("GET", key); if (value and value.err == nil) then local locations = redis.call("BITCOUNT", key, 8, -1); if (locations == 0) then if (lastAccessTime > maximumEmptyLastAccessTimeInSeconds) then deletedKeysIndex = deletedKeysIndex + 1; if (whatif ~= TRUE) then redis.call("DEL", key); actualDeletedKeysCount = actualDeletedKeysCount + 1; end end deletedKeys[deletedKeysIndex] = key; else entries[index] = { key, value }; index = index + 1; end end end return { entries, deletedKeys, actualDeletedKeysCount};
nilq/small-lua-stack
null
data:extend({ { type = "recipe", name = "human-1", enabled = true, icon = "__factorio-not-included__/graphics/human-1/item-recipe/32.png", icon_size = 32, category = "colony-1", subgroup = "fni-item", energy_required = 5, ingredients = { { type = "fluid", name = "o2", amount = 1500 }, { type = "fluid", name = "water", amount = 1000 }, { "food-1", 1 }, }, results = { { "human-1", 5 }, { type = "fluid", name = "co2", amount = 200 }, { type = "fluid", name = "polluted-water", amount = 1400 }, } }, { type = "recipe", name = "plant-1", enabled = true, icon = "__factorio-not-included__/graphics/plant-1/item-recipe/32.png", icon_size = 32, category = "farm-1", subgroup = "fni-item", energy_required = 2, ingredients = { { "dirt", 2 }, { type = "fluid", name = "water", amount = 1000 }, { type = "fluid", name = "n2", amount = 500 }, }, results = { { "plant-1", 1 }, { type = "fluid", name = "polluted-water", amount = 100 }, } }, { type = "recipe", name = "meat-1", enabled = true, icon = "__factorio-not-included__/graphics/meat-1/item-recipe/32.png", icon_size = 32, category = "pasture-1", subgroup = "fni-item", energy_required = 2, ingredients = { { "coal", 1 }, { type = "fluid", name = "n2", amount = 200 }, }, results = { { "meat-1", 1 }, { type = "fluid", name = "polluted-oxygen", amount = 400 }, } }, { type = "recipe", name = "food-1", enabled = true, icon = "__factorio-not-included__/graphics/food-1/item-recipe/32.png", icon_size = 32, category = "cooker-1", subgroup = "fni-item", energy_required = 2, ingredients = { { "meat-1", 1 }, { "plant-1", 1 }, }, results = { { "food-1", 1 }, } }, { type = "recipe", name = "water-sieve-1", enabled = true, icon = "__factorio-not-included__/graphics/water-sieve-1/item-recipe/32.png", icon_size = 32, category = "water-sieve-1", subgroup = "fni-fluid", energy_required = 2, ingredients = { { "sand", 1 }, { type = "fluid", name = "polluted-water", amount = 1000 }, }, results = { { "polluted-dirt", 1 }, { type = "fluid", name = "water", amount = 900 }, } }, { type = "recipe", name = "compost-1", enabled = true, icon = "__factorio-not-included__/graphics/compost-1/item-recipe/32.png", icon_size = 32, category = "compost-1", subgroup = "fni-item", energy_required = 2, ingredients = { { "polluted-dirt", 1 }, }, results = { { "dirt", 1 }, { type = "fluid", name = "polluted-oxygen", amount = 500 }, { type = "fluid", name = "co2", amount = 300 }, } }, { type = "recipe", name = "air-cleaner-1", enabled = true, icon = "__factorio-not-included__/graphics/air-cleaner-1/item-recipe/32.png", icon_size = 32, category = "air-cleaner-1", subgroup = "fni-fluid", energy_required = 2, ingredients = { { "sand", 1 }, { type = "fluid", name = "polluted-oxygen", amount = 1000 }, }, results = { { "polluted-dirt", 1 }, { type = "fluid", name = "o2", amount = 500 }, } }, { type = "recipe", name = "carbon-skimmer-1", enabled = true, icon = "__factorio-not-included__/graphics/carbon-skimmer-1/item-recipe/32.png", icon_size = 32, category = "carbon-skimmer-1", subgroup = "fni-fluid", energy_required = 2, ingredients = { { type = "fluid", name = "co2", amount = 600 }, { type = "fluid", name = "water", amount = 1000 }, }, results = { { type = "fluid", name = "polluted-water", amount = 1000 }, } }, { type = "recipe", name = "gas-pump-1", enabled = true, icon = "__factorio-not-included__/graphics/gas-pump-1/item-recipe/32.png", icon_size = 32, category = "gas-pump-1", subgroup = "fni-fluid", energy_required = 2, ingredients = {}, results = { { type = "fluid", name = "o2", amount = 300 }, { type = "fluid", name = "n2", amount = 500 }, } }, { type = "recipe", name = "sand", enabled = true, icon = "__factorio-not-included__/graphics/sand-1/item-recipe/32.png", icon_size = 32, category = "crafting", subgroup = "fni-item", energy_required = 1, ingredients = { { "stone", 1 }, }, results = { { "sand", 1 }, } }, { type = "recipe", name = "human-2", enabled = false, icon = "__factorio-not-included__/graphics/human-2/item-recipe/32.png", icon_size = 32, category = "colony-2", subgroup = "fni-item", energy_required = 5, ingredients = { { type = "fluid", name = "o2", amount = 2000 }, { type = "fluid", name = "drinkable-water", amount = 1000 }, { "food-2", 1 }, }, results = { { "human-2", 5 }, { type = "fluid", name = "co2", amount = 900 }, { type = "fluid", name = "polluted-water", amount = 1200 }, } }, { type = "recipe", name = "drinkable-water-1", enabled = false, icon = "__factorio-not-included__/graphics/drinkable-water-1/item-recipe/32.png", icon_size = 32, category = "water-sieve-1", subgroup = "fni-item", energy_required = 2, ingredients = { { type = "fluid", name = "water", amount = 1000 }, { type = "fluid", name = "chlorine", amount = 600 }, }, results = { { type = "fluid", name = "drinkable-water", amount = 1200 }, { type = "fluid", name = "polluted-water", amount = 200 }, } }, { type = "recipe", name = "food-2", enabled = false, icon = "__factorio-not-included__/graphics/food-2/item-recipe/32.png", icon_size = 32, category = "cooker-1", subgroup = "fni-item", energy_required = 2, ingredients = { { "plant-2-1", 1 }, { "plant-2-2", 1 }, { "meat-2-1", 1 }, { "meat-2-2", 1 }, { type = "fluid", name = "water", amount = 200 }, }, results = { { "food-2", 1 }, { type = "fluid", name = "polluted-water", amount = 200 }, } }, { type = "recipe", name = "plant-2-1", enabled = false, icon = "__factorio-not-included__/graphics/plant-2-1/item-recipe/32.png", icon_size = 32, category = "farm-2-1", subgroup = "fni-item", energy_required = 2, ingredients = { { "dirt", 2 }, { type = "fluid", name = "polluted-water", amount = 800 }, { type = "fluid", name = "n2", amount = 400 }, }, results = { { "plant-2-1", 1 }, { type = "fluid", name = "chlorine", amount = 400 }, { type = "fluid", name = "co2", amount = 200 }, } }, { type = "recipe", name = "plant-2-2", enabled = false, icon = "__factorio-not-included__/graphics/plant-2-2/item-recipe/32.png", icon_size = 32, category = "farm-2-2", subgroup = "fni-item", energy_required = 2, ingredients = { { "polluted-dirt", 2 }, { type = "fluid", name = "o2", amount = 400 }, { type = "fluid", name = "n2", amount = 400 }, }, results = { { "plant-2-2", 1 }, { type = "fluid", name = "polluted-oxygen", amount = 200 }, { type = "fluid", name = "chlorine", amount = 100 }, } }, { type = "recipe", name = "meat-2-1", enabled = false, icon = "__factorio-not-included__/graphics/meat-2-1/item-recipe/32.png", icon_size = 32, category = "pasture-2-1", subgroup = "fni-item", energy_required = 2, ingredients = { { "plant-2-1", 1 }, { "iron-ore", 4 }, { type = "fluid", name = "chlorine", amount = 400 }, }, results = { { "meat-2-1", 1 }, { "coal", 4 }, { type = "fluid", name = "co2", amount = 200 }, } }, { type = "recipe", name = "meat-2-2", enabled = false, icon = "__factorio-not-included__/graphics/meat-2-2/item-recipe/32.png", icon_size = 32, category = "pasture-2-2", subgroup = "fni-item", energy_required = 2, ingredients = { { "plant-2-2", 1 }, { type = "fluid", name = "polluted-oxygen", amount = 1200 }, }, results = { { "meat-2-2", 1 }, { "slime", 1 }, { type = "fluid", name = "co2", amount = 200 }, } }, { type = "recipe", name = "distiller-1", enabled = false, icon = "__factorio-not-included__/graphics/distiller-1/item-recipe/32.png", icon_size = 32, category = "distiller-1", subgroup = "fni-item", energy_required = 2, ingredients = { { "slime", 1 }, { type = "fluid", name = "chlorine", amount = 400 }, }, results = { { "algae", 1 }, { type = "fluid", name = "polluted-water", amount = 200 }, } }, { type = "recipe", name = "terrarium-1", enabled = false, icon = "__factorio-not-included__/graphics/terrarium-1/item-recipe/32.png", icon_size = 32, category = "terrarium-1", subgroup = "fni-item", energy_required = 2, ingredients = { { "algae", 1 }, { type = "fluid", name = "co2", amount = 100 }, { type = "fluid", name = "water", amount = 500 }, }, results = { { type = "fluid", name = "o2", amount = 1000 }, { type = "fluid", name = "polluted-water", amount = 500 }, } }, { type = "recipe", name = "compost-plant-1", enabled = false, icon = "__factorio-not-included__/graphics/compost-plant-1/item-recipe/32.png", icon_size = 32, category = "compost-1", subgroup = "fni-item", energy_required = 2, ingredients = { { "plant-1", 1 }, { type = "fluid", name = "polluted-oxygen", amount = 400 }, }, results = { { "polluted-dirt", 1 }, { type = "fluid", name = "co2", amount = 200 }, } }, { type = "recipe", name = "compost-meat-1", enabled = false, icon = "__factorio-not-included__/graphics/compost-meat-1/item-recipe/32.png", icon_size = 32, category = "compost-1", subgroup = "fni-item", energy_required = 2, ingredients = { { "meat-1", 1 }, { type = "fluid", name = "polluted-oxygen", amount = 400 }, }, results = { { "polluted-dirt", 1 }, { type = "fluid", name = "co2", amount = 200 }, } }, { type = "recipe", name = "compost-plant-2-1", enabled = false, icon = "__factorio-not-included__/graphics/compost-plant-2-1/item-recipe/32.png", icon_size = 32, category = "compost-1", subgroup = "fni-item", energy_required = 2, ingredients = { { "plant-2-1", 4 }, { type = "fluid", name = "polluted-oxygen", amount = 400 }, }, results = { { "polluted-dirt", 3 }, { type = "fluid", name = "co2", amount = 200 }, } }, { type = "recipe", name = "compost-plant-2-2", enabled = false, icon = "__factorio-not-included__/graphics/compost-plant-2-2/item-recipe/32.png", icon_size = 32, category = "compost-1", subgroup = "fni-item", energy_required = 2, ingredients = { { "plant-2-2", 4 }, { type = "fluid", name = "polluted-oxygen", amount = 400 }, }, results = { { "polluted-dirt", 3 }, { type = "fluid", name = "co2", amount = 200 }, } }, { type = "recipe", name = "compost-meat-2-1", enabled = false, icon = "__factorio-not-included__/graphics/compost-meat-2-1/item-recipe/32.png", icon_size = 32, category = "compost-1", subgroup = "fni-item", energy_required = 2, ingredients = { { "meat-2-1", 4 }, { type = "fluid", name = "polluted-oxygen", amount = 400 }, }, results = { { "polluted-dirt", 3 }, { type = "fluid", name = "chlorine", amount = 200 }, } }, { type = "recipe", name = "compost-meat-2-2", enabled = false, icon = "__factorio-not-included__/graphics/compost-meat-2-2/item-recipe/32.png", icon_size = 32, category = "compost-1", subgroup = "fni-item", energy_required = 2, ingredients = { { "meat-2-2", 4 }, { type = "fluid", name = "polluted-oxygen", amount = 400 }, }, results = { { "polluted-dirt", 3 }, { type = "fluid", name = "chlorine", amount = 200 }, } }, -- 3 { type = "recipe", name = "human-3", enabled = false, icon = "__factorio-not-included__/graphics/human-3/item-recipe/32.png", icon_size = 32, category = "colony-3", subgroup = "fni-item", energy_required = 5, ingredients = { { type = "fluid", name = "o2", amount = 4500 }, { type = "fluid", name = "sparkling-water", amount = 2000 }, { "small-lamp", 10 }, { "clothes-1", 5 }, { "food-3", 1 }, }, results = { { "human-3", 5 }, { "general-waste", 10 }, { type = "fluid", name = "co2", amount = 1200 }, { type = "fluid", name = "polluted-water", amount = 1200 }, } }, { type = "recipe", name = "food-3", enabled = false, icon = "__factorio-not-included__/graphics/food-3/item-recipe/32.png", icon_size = 32, category = "cooker-1", subgroup = "fni-item", energy_required = 2, ingredients = { { type = "fluid", name = "drinkable-water", amount = 600 }, { "plant-3-1", 1 }, { "plant-3-2", 1 }, { "meat-3-1", 1 }, { "meat-3-2", 1 }, }, results = { { "food-3", 1 }, { type = "fluid", name = "polluted-water", amount = 600 }, } }, { type = "recipe", name = "sparkling-water", enabled = false, icon = "__factorio-not-included__/graphics/sparkling-water/item-recipe/32.png", icon_size = 32, category = "cooker-1", subgroup = "fni-item", energy_required = 2, ingredients = { { type = "fluid", name = "drinkable-water", amount = 1000 }, { type = "fluid", name = "co2", amount = 600 }, }, results = { { type = "fluid", name = "sparkling-water", amount = 400 }, { type = "fluid", name = "polluted-water", amount = 600 }, } }, { type = "recipe", name = "plant-3-1", enabled = false, icon = "__factorio-not-included__/graphics/plant-3-1/item-recipe/32.png", icon_size = 32, category = "farm-3-1", subgroup = "fni-item", energy_required = 2, ingredients = { { type = "fluid", name = "polluted-water", amount = 1600 }, { type = "fluid", name = "chlorine", amount = 400 }, { "dirt", 2 }, }, results = { { "plant-3-1", 1 }, { type = "fluid", name = "h2", amount = 400 }, } }, { type = "recipe", name = "plant-3-2", enabled = false, icon = "__factorio-not-included__/graphics/plant-3-2/item-recipe/32.png", icon_size = 32, category = "farm-3-2", subgroup = "fni-item", energy_required = 2, ingredients = { { type = "fluid", name = "n2", amount = 400 }, { type = "fluid", name = "co2", amount = 600 }, { "polluted-dirt", 2 }, }, results = { { "plant-3-2", 1 }, { type = "fluid", name = "polluted-oxygen", amount = 400 }, } }, { type = "recipe", name = "meat-3-1", enabled = false, icon = "__factorio-not-included__/graphics/meat-3-1/item-recipe/32.png", icon_size = 32, category = "pasture-3-1", subgroup = "fni-item", energy_required = 2, ingredients = { { type = "fluid", name = "h2", amount = 500 }, { "plant-1", 2 }, }, results = { { "meat-3-1", 1 }, { "fiber", 1 }, { type = "fluid", name = "co2", amount = 400 }, } }, { type = "recipe", name = "meat-3-2", enabled = false, icon = "__factorio-not-included__/graphics/meat-3-2/item-recipe/32.png", icon_size = 32, category = "pasture-3-2", subgroup = "fni-item", energy_required = 2, ingredients = { { type = "fluid", name = "co2", amount = 600 }, { "plant-3-1", 1 }, { "plant-3-2", 1 }, { "slime", 1 }, }, results = { { "meat-3-2", 1 }, { "sand", 10 }, { type = "fluid", name = "h2", amount = 200 }, } }, { type = "recipe", name = "clothes-1", enabled = false, icon = "__factorio-not-included__/graphics/clothes-1/item-recipe/32.png", icon_size = 32, category = "textile-loom-1", subgroup = "fni-item", energy_required = 2, ingredients = { { "fiber", 1 }, }, results = { { "clothes-1", 5 }, { type = "fluid", name = "h2", amount = 200 }, } }, { type = "recipe", name = "recycle-1", enabled = false, icon = "__factorio-not-included__/graphics/recycle-1/item-recipe/32.png", icon_size = 32, category = "recycler-1", subgroup = "fni-item", energy_required = 1, ingredients = { { "general-waste", 1 }, }, results = { { type = "fluid", name = "co2", amount = 300 }, { type = "fluid", name = "chlorine", amount = 300 }, { name = "iron-ore", amount = 10, probability = 0.25 }, } }, { type = "recipe", name = "electrolyse-1", enabled = false, icon = "__factorio-not-included__/graphics/electrolyse-1/item-recipe/32.png", icon_size = 32, category = "electrolyzer-1", subgroup = "fni-item", energy_required = 2, ingredients = { { type = "fluid", name = "water", amount = 600 }, }, results = { { type = "fluid", name = "o2", amount = 600 }, { type = "fluid", name = "h2", amount = 300 }, } }, { type = "recipe", name = "compost-plant-3-1", enabled = false, icon = "__factorio-not-included__/graphics/compost-plant-3-1/item-recipe/32.png", icon_size = 32, category = "compost-1", subgroup = "fni-item", energy_required = 2, ingredients = { { type = "fluid", name = "polluted-oxygen", amount = 400 }, { "plant-3-1", 4 }, }, results = { { "polluted-dirt", 3 }, { type = "fluid", name = "h2", amount = 200 }, } }, { type = "recipe", name = "compost-plant-3-2", enabled = false, icon = "__factorio-not-included__/graphics/compost-plant-3-2/item-recipe/32.png", icon_size = 32, category = "compost-1", subgroup = "fni-item", energy_required = 2, ingredients = { { type = "fluid", name = "o2", amount = 400 }, { "plant-3-2", 4 }, }, results = { { "polluted-dirt", 3 }, { type = "fluid", name = "polluted-oxygen", amount = 200 }, } }, { type = "recipe", name = "compost-meat-3-1", enabled = false, icon = "__factorio-not-included__/graphics/compost-meat-3-1/item-recipe/32.png", icon_size = 32, category = "compost-1", subgroup = "fni-item", energy_required = 2, ingredients = { { type = "fluid", name = "polluted-oxygen", amount = 400 }, { "meat-3-1", 4 }, }, results = { { "polluted-dirt", 3 }, { type = "fluid", name = "co2", amount = 200 }, } }, { type = "recipe", name = "compost-meat-3-2", enabled = false, icon = "__factorio-not-included__/graphics/compost-meat-3-2/item-recipe/32.png", icon_size = 32, category = "compost-1", subgroup = "fni-item", energy_required = 2, ingredients = { { type = "fluid", name = "polluted-oxygen", amount = 400 }, { "plant-3-1", 4 }, }, results = { { "polluted-dirt", 3 }, { type = "fluid", name = "chlorine", amount = 200 }, } }, -- 4 { type = "recipe", name = "human-4", enabled = false, icon = "__factorio-not-included__/graphics/human-4/item-recipe/32.png", icon_size = 32, category = "colony-4", subgroup = "fni-item", energy_required = 5, ingredients = { { type = "fluid", name = "o2", amount = 6000 }, { type = "fluid", name = "juice", amount = 900 }, { "tv", 1 }, { "clothes-1", 1 }, { "food-4", 1 }, }, results = { { "human-4", 5 }, { "oversize-garbage", 1 }, { "general-waste", 1 }, { type = "fluid", name = "co2", amount = 1800 }, { type = "fluid", name = "polluted-water", amount = 2200 }, } }, { type = "recipe", name = "food-4", enabled = false, icon = "__factorio-not-included__/graphics/food-4/item-recipe/32.png", icon_size = 32, category = "cooker-1", subgroup = "fni-item", energy_required = 2, ingredients = { { "plant-4-1", 1 }, { "plant-4-2", 1 }, { "plant-4-3", 1 }, { "meat-4-1", 1 }, { "meat-4-2", 1 }, { "meat-4-3", 1 }, { type = "fluid", name = "drinkable-water", amount = 600 }, }, results = { { "food-4", 1 }, { type = "fluid", name = "polluted-water", amount = 600 }, } }, { type = "recipe", name = "juice", enabled = false, icon = "__factorio-not-included__/graphics/juice/item-recipe/32.png", icon_size = 32, category = "cooker-1", subgroup = "fni-item", energy_required = 2, ingredients = { { type = "fluid", name = "sparkling-water", amount = 800 }, { "plant-1", 1 }, { "plant-2-2", 1 }, }, results = { { type = "fluid", name = "juice", amount = 600 }, { type = "fluid", name = "polluted-water", amount = 200 }, } }, { type = "recipe", name = "plant-4-1", enabled = false, icon = "__factorio-not-included__/graphics/plant-4-1/item-recipe/32.png", icon_size = 32, category = "farm-4-1", subgroup = "fni-item", energy_required = 2, ingredients = { { type = "fluid", name = "polluted-water", amount = 1600 }, { type = "fluid", name = "co2", amount = 800 }, { name = "dirt", amount = 4 }, }, results = { { "plant-4-1", 1 }, { type = "fluid", name = "h2", amount = 600 }, } }, { type = "recipe", name = "plant-4-2", enabled = false, icon = "__factorio-not-included__/graphics/plant-4-2/item-recipe/32.png", icon_size = 32, category = "farm-4-2", subgroup = "fni-item", energy_required = 2, ingredients = { { type = "fluid", name = "n2", amount = 400 }, { type = "fluid", name = "h2", amount = 1200 }, { "polluted-dirt", 4 }, }, results = { { "plant-4-2", 1 }, { type = "fluid", name = "natural-gas", amount = 600 }, } }, { type = "recipe", name = "plant-4-3", enabled = false, icon = "__factorio-not-included__/graphics/plant-4-3/item-recipe/32.png", icon_size = 32, category = "farm-4-3", subgroup = "fni-item", energy_required = 2, ingredients = { { type = "fluid", name = "n2", amount = 400 }, { type = "fluid", name = "co2", amount = 1200 }, { "slime", 2 }, }, results = { { "plant-4-3", 1 }, { type = "fluid", name = "natural-gas", amount = 600 }, } }, { type = "recipe", name = "meat-4-1", enabled = false, icon = "__factorio-not-included__/graphics/meat-4-1/item-recipe/32.png", icon_size = 32, category = "pasture-4-1", subgroup = "fni-item", energy_required = 2, ingredients = { { type = "fluid", name = "chlorine", amount = 800 }, { "plant-4-1", 1 }, { "meat-3-1", 1 }, }, results = { { "meat-4-1", 1 }, { "fiber", 2 }, { type = "fluid", name = "polluted-water", amount = 800 }, } }, { type = "recipe", name = "meat-4-2", enabled = false, icon = "__factorio-not-included__/graphics/meat-4-2/item-recipe/32.png", icon_size = 32, category = "pasture-4-2", subgroup = "fni-item", energy_required = 2, ingredients = { { type = "fluid", name = "natural-gas", amount = 1400 }, { "plant-4-2", 1 }, { "meat-3-2", 1 }, }, results = { { "meat-4-2", 1 }, { "slime", 2 }, { type = "fluid", name = "h2", amount = 400 }, } }, { type = "recipe", name = "meat-4-3", enabled = false, icon = "__factorio-not-included__/graphics/meat-4-3/item-recipe/32.png", icon_size = 32, category = "pasture-4-3", subgroup = "fni-item", energy_required = 2, ingredients = { { type = "fluid", name = "natural-gas", amount = 600 }, { "plant-4-3", 1 }, { "meat-3-2", 1 }, }, results = { { "meat-4-3", 1 }, { type = "fluid", name = "chlorine", amount = 400 }, } }, { type = "recipe", name = "recycle-2", enabled = false, icon = "__factorio-not-included__/graphics/recycle-2/item-recipe/32.png", icon_size = 32, category = "recycler-1", subgroup = "fni-item", energy_required = 2, ingredients = { { "oversize-garbage", 1 }, }, results = { { type = "fluid", name = "h2", amount = 200 }, { type = "fluid", name = "natural-gas", amount = 300 }, { name = "sand", amount = 10, probability = 0.25 }, { name = "copper-ore", amount = 10, probability = 0.25 }, } }, { type = "recipe", name = "tv", enabled = false, icon = "__factorio-not-included__/graphics/tv/item-recipe/32.png", icon_size = 32, category = "crafting", subgroup = "fni-item", energy_required = 2, ingredients = { { "copper-cable", 8 }, { "small-lamp", 4 }, }, results = { { "tv", 1 }, } }, { type = "recipe", name = "fuel-generator", enabled = false, icon = "__factorio-not-included__/graphics/fuel-generator/item-recipe/32.png", icon_size = 32, category = "fuel-generator", subgroup = "fni-item", energy_required = 2, ingredients = { { type = "fluid", name = "water", amount = 1000 }, { "solid-fuel", 1 }, }, results = { { type = "fluid", name = "co2", amount = 3000 }, { type = "fluid", name = "steam", amount = 10000 }, } }, { type = "recipe", name = "h2-generator", enabled = false, icon = "__factorio-not-included__/graphics/h2-generator/item-recipe/32.png", icon_size = 32, category = "h2-generator", subgroup = "fni-item", energy_required = 2, ingredients = { { type = "fluid", name = "h2", amount = 1000 }, }, results = { { type = "fluid", name = "polluted-water", amount = 800 }, { type = "fluid", name = "steam", amount = 10000 }, } }, { type = "recipe", name = "compost-plant-4-1", enabled = false, icon = "__factorio-not-included__/graphics/compost-plant-4-1/item-recipe/32.png", icon_size = 32, category = "compost-1", subgroup = "fni-item", energy_required = 2, ingredients = { { type = "fluid", name = "polluted-oxygen", amount = 400 }, { "plant-4-1", 1 }, }, results = { { "polluted-dirt", 1 }, { type = "fluid", name = "h2", amount = 200 }, } }, { type = "recipe", name = "compost-plant-4-2", enabled = false, icon = "__factorio-not-included__/graphics/compost-plant-4-2/item-recipe/32.png", icon_size = 32, category = "compost-1", subgroup = "fni-item", energy_required = 2, ingredients = { { type = "fluid", name = "polluted-oxygen", amount = 400 }, { "plant-4-2", 1 }, }, results = { { "polluted-dirt", 1 }, { type = "fluid", name = "h2", amount = 200 }, } }, { type = "recipe", name = "compost-plant-4-3", enabled = false, icon = "__factorio-not-included__/graphics/compost-plant-4-3/item-recipe/32.png", icon_size = 32, category = "compost-1", subgroup = "fni-item", energy_required = 2, ingredients = { { type = "fluid", name = "polluted-oxygen", amount = 400 }, { "plant-4-3", 1 }, }, results = { { "polluted-dirt", 1 }, { type = "fluid", name = "natural-gas", amount = 200 }, } }, { type = "recipe", name = "compost-meat-4-1", enabled = false, icon = "__factorio-not-included__/graphics/compost-meat-4-1/item-recipe/32.png", icon_size = 32, category = "compost-1", subgroup = "fni-item", energy_required = 2, ingredients = { { type = "fluid", name = "polluted-oxygen", amount = 400 }, { "meat-4-1", 1 }, }, results = { { "polluted-dirt", 1 }, { type = "fluid", name = "co2", amount = 200 }, } }, { type = "recipe", name = "compost-meat-4-2", enabled = false, icon = "__factorio-not-included__/graphics/compost-meat-4-2/item-recipe/32.png", icon_size = 32, category = "compost-1", subgroup = "fni-item", energy_required = 2, ingredients = { { type = "fluid", name = "polluted-oxygen", amount = 400 }, { "plant-4-2", 1 }, }, results = { { "polluted-dirt", 1 }, { type = "fluid", name = "h2", amount = 200 }, } }, { type = "recipe", name = "compost-meat-4-3", enabled = false, icon = "__factorio-not-included__/graphics/compost-meat-4-3/item-recipe/32.png", icon_size = 32, category = "compost-1", subgroup = "fni-item", energy_required = 2, ingredients = { { type = "fluid", name = "polluted-oxygen", amount = 400 }, { "plant-4-3", 1 }, }, results = { { "polluted-dirt", 1 }, { type = "fluid", name = "h2", amount = 200 }, } }, -- 5 { type = "recipe", name = "human-5", enabled = false, icon = "__factorio-not-included__/graphics/human-5/item-recipe/32.png", icon_size = 32, category = "colony-5", subgroup = "fni-item", energy_required = 5, ingredients = { { type = "fluid", name = "o2", amount = 7500 }, { type = "fluid", name = "wine", amount = 100 }, { "food-5", 1 }, { "fashionable-clothes", 1 }, { "pc", 1 }, }, results = { { "human-5", 1 }, { "electric-garbage", 10 }, { "oversize-garbage", 20 }, { "general-waste", 30 }, { type = "fluid", name = "co2", amount = 2400 }, { type = "fluid", name = "concentrated-polluted-water", amount = 1200 }, } }, { type = "recipe", name = "food-5", enabled = false, icon = "__factorio-not-included__/graphics/food-5/item-recipe/32.png", icon_size = 32, category = "cooker-1", subgroup = "fni-item", energy_required = 2, ingredients = { { type = "fluid", name = "drinkable-water", amount = 1200 }, { "plant-5-1", 1 }, { "plant-5-2", 1 }, { "plant-5-3", 1 }, { "meat-5-1", 1 }, { "meat-5-2", 1 }, { "meat-5-3", 1 }, }, results = { { "food-5", 1 }, { type = "fluid", name = "concentrated-polluted-water", amount = 600 }, } }, { type = "recipe", name = "wine", enabled = false, icon = "__factorio-not-included__/graphics/wine/item-recipe/32.png", icon_size = 32, category = "cooker-1", subgroup = "fni-item", energy_required = 2, ingredients = { { type = "fluid", name = "sparkling-water", amount = 600 }, { "plant-3-1", 1 }, { "plant-2-1", 1 }, }, results = { { type = "fluid", name = "wine", amount = 100 }, { type = "fluid", name = "concentrated-polluted-water", amount = 400 }, } }, { type = "recipe", name = "plant-5-1", enabled = false, icon = "__factorio-not-included__/graphics/plant-5-1/item-recipe/32.png", icon_size = 32, category = "farm-5-1", subgroup = "fni-item", energy_required = 2, ingredients = { { type = "fluid", name = "concentrated-polluted-water", amount = 600 }, { type = "fluid", name = "chlorine", amount = 800 }, { "dirt", 4 }, }, results = { { "plant-5-1", 1 }, { type = "fluid", name = "h2", amount = 600 }, { type = "fluid", name = "polluted-oxygen", amount = 1600 }, } }, { type = "recipe", name = "plant-5-2", enabled = false, icon = "__factorio-not-included__/graphics/plant-5-2/item-recipe/32.png", icon_size = 32, category = "farm-5-2", subgroup = "fni-item", energy_required = 2, ingredients = { { type = "fluid", name = "h2", amount = 800 }, { type = "fluid", name = "concentrated-polluted-water", amount = 600 }, { "polluted-dirt", 4 }, }, results = { { "plant-5-2", 1 }, { type = "fluid", name = "o2", amount = 1200 }, { type = "fluid", name = "chlorine", amount = 1000 }, } }, { type = "recipe", name = "plant-5-3", enabled = false, icon = "__factorio-not-included__/graphics/plant-5-3/item-recipe/32.png", icon_size = 32, category = "farm-5-3", subgroup = "fni-item", energy_required = 2, ingredients = { { type = "fluid", name = "n2", amount = 800 }, { type = "fluid", name = "natural-gas", amount = 600 }, { "slime", 4 }, }, results = { { "plant-5-3", 1 }, { "coal", 10 }, { type = "fluid", name = "concentrated-polluted-water", amount = 500 }, { type = "fluid", name = "h2", amount = 1300 }, } }, { type = "recipe", name = "meat-5-1", enabled = false, icon = "__factorio-not-included__/graphics/meat-5-1/item-recipe/32.png", icon_size = 32, category = "pasture-5-1", subgroup = "fni-item", energy_required = 2, ingredients = { { type = "fluid", name = "co2", amount = 1200 }, { "plant-5-1", 1 }, { "meat-4-1", 1 }, }, results = { { "meat-5-1", 1 }, { "slime", 4 }, { type = "fluid", name = "concentrated-polluted-water", amount = 600 }, { type = "fluid", name = "n2", amount = 1200 }, } }, { type = "recipe", name = "meat-5-2", enabled = false, icon = "__factorio-not-included__/graphics/meat-5-2/item-recipe/32.png", icon_size = 32, category = "pasture-5-2", subgroup = "fni-item", energy_required = 2, ingredients = { { "plant-5-2", 1 }, { "meat-4-2", 1 }, { type = "fluid", name = "o2", amount = 800 }, { type = "fluid", name = "polluted-water", amount = 1400 }, }, results = { { "meat-5-2", 1 }, { type = "fluid", name = "polluted-oxygen", amount = 800 }, { type = "fluid", name = "natural-gas", amount = 700 }, } }, { type = "recipe", name = "meat-5-3", enabled = false, icon = "__factorio-not-included__/graphics/meat-5-3/item-recipe/32.png", icon_size = 32, category = "pasture-5-3", subgroup = "fni-item", energy_required = 2, ingredients = { { "plant-5-3", 1 }, { "meat-4-3", 1 }, { type = "fluid", name = "h2", amount = 600 }, { type = "fluid", name = "o2", amount = 1200 }, }, results = { { "meat-5-3", 1 }, { "fiber", 6 }, { type = "fluid", name = "co2", amount = 1200 }, { type = "fluid", name = "concentrated-polluted-water", amount = 800 }, } }, { type = "recipe", name = "recycle-3", enabled = false, icon = "__factorio-not-included__/graphics/recycle-3/item-recipe/32.png", icon_size = 32, category = "recycler-1", subgroup = "fni-item", energy_required = 3, ingredients = { { "electric-garbage", 1 }, }, results = { { type = "fluid", name = "h2", amount = 200 }, { type = "fluid", name = "concentrated-polluted-water", amount = 200 }, { name = "processing-unit", amount = 1, probability = 0.25 }, { name = "plastic-bar", amount = 4, probability = 0.25 }, { name = "iron-ore", amount = 10, probability = 0.25 }, { name = "copper-ore", amount = 10, probability = 0.25 }, } }, { type = "recipe", name = "pc", enabled = false, icon = "__factorio-not-included__/graphics/pc/item-recipe/32.png", icon_size = 32, category = "crafting", subgroup = "fni-item", energy_required = 2, ingredients = { { "processing-unit", 2 }, { "copper-cable", 8 }, { "plastic-bar", 2 }, }, results = { { "pc", 1 }, } }, { type = "recipe", name = "fashionable-clothes", enabled = false, icon = "__factorio-not-included__/graphics/fashionable-clothes/item-recipe/32.png", icon_size = 32, category = "textile-loom-1", subgroup = "fni-item", energy_required = 2, ingredients = { { "fiber", 4 }, { "plastic-bar", 1 }, }, results = { { "fashionable-clothes", 1 }, { type = "fluid", name = "concentrated-polluted-water", amount = 200 }, } }, { type = "recipe", name = "natural-gas-generator", enabled = false, icon = "__factorio-not-included__/graphics/natural-gas-generator/item-recipe/32.png", icon_size = 32, category = "natural-gas-generator", subgroup = "fni-item", energy_required = 2, ingredients = { { type = "fluid", name = "natural-gas", amount = 1000 }, }, results = { { type = "fluid", name = "concentrated-polluted-water", amount = 800 }, { type = "fluid", name = "steam", amount = 10000 }, { type = "fluid", name = "co2", amount = 600 }, } }, { type = "recipe", name = "clean-concentrated-polluted-water", enabled = false, icon = "__factorio-not-included__/graphics/clean-concentrated-polluted-water/item-recipe/32.png", icon_size = 32, category = "water-sieve-1", subgroup = "fni-item", energy_required = 2, ingredients = { { type = "fluid", name = "concentrated-polluted-water", amount = 1000 }, { type = "fluid", name = "chlorine", amount = 600 }, { "sand", 8 }, }, results = { { type = "fluid", name = "natural-gas", amount = 600 }, { type = "fluid", name = "polluted-water", amount = 200 }, { "polluted-dirt", 8 }, } }, { type = "recipe", name = "compost-plant-5-1", enabled = false, icon = "__factorio-not-included__/graphics/compost-plant-5-1/item-recipe/32.png", icon_size = 32, category = "compost-1", subgroup = "fni-item", energy_required = 2, ingredients = { { type = "fluid", name = "polluted-oxygen", amount = 400 }, { "plant-5-1", 1 }, }, results = { { "polluted-dirt", 1 }, { type = "fluid", name = "h2", amount = 200 }, } }, { type = "recipe", name = "compost-plant-5-2", enabled = false, icon = "__factorio-not-included__/graphics/compost-plant-5-2/item-recipe/32.png", icon_size = 32, category = "compost-1", subgroup = "fni-item", energy_required = 2, ingredients = { { type = "fluid", name = "polluted-oxygen", amount = 400 }, { "plant-5-2", 1 }, }, results = { { "polluted-dirt", 1 }, { type = "fluid", name = "o2", amount = 200 }, } }, { type = "recipe", name = "compost-plant-5-3", enabled = false, icon = "__factorio-not-included__/graphics/compost-plant-5-3/item-recipe/32.png", icon_size = 32, category = "compost-1", subgroup = "fni-item", energy_required = 2, ingredients = { { type = "fluid", name = "polluted-oxygen", amount = 400 }, { "plant-5-3", 1 }, }, results = { { "polluted-dirt", 1 }, { type = "fluid", name = "concentrated-polluted-water", amount = 200 }, } }, { type = "recipe", name = "compost-meat-5-1", enabled = false, icon = "__factorio-not-included__/graphics/compost-meat-5-1/item-recipe/32.png", icon_size = 32, category = "compost-1", subgroup = "fni-item", energy_required = 2, ingredients = { { type = "fluid", name = "polluted-oxygen", amount = 400 }, { "meat-5-1", 1 }, }, results = { { "polluted-dirt", 1 }, { type = "fluid", name = "natural-gas", amount = 200 }, } }, { type = "recipe", name = "compost-meat-5-2", enabled = false, icon = "__factorio-not-included__/graphics/compost-meat-5-2/item-recipe/32.png", icon_size = 32, category = "compost-1", subgroup = "fni-item", energy_required = 2, ingredients = { { type = "fluid", name = "polluted-oxygen", amount = 400 }, { "meat-5-2", 1 }, }, results = { { "polluted-dirt", 1 }, { type = "fluid", name = "crude-oil", amount = 200 }, } }, { type = "recipe", name = "compost-meat-5-3", enabled = false, icon = "__factorio-not-included__/graphics/compost-meat-5-3/item-recipe/32.png", icon_size = 32, category = "compost-1", subgroup = "fni-item", energy_required = 2, ingredients = { { type = "fluid", name = "polluted-oxygen", amount = 500 }, { "meat-5-3", 1 }, }, results = { { "polluted-dirt", 1 }, { type = "fluid", name = "natural-gas", amount = 200 }, } }, -- 6 { type = "recipe", name = "human-6", enabled = false, icon = "__factorio-not-included__/graphics/human-6/item-recipe/32.png", icon_size = 32, category = "colony-6", subgroup = "fni-item", energy_required = 5, ingredients = { { type = "fluid", name = "o2", amount = 9000 }, { "food-6", 1 }, { "space-suite", 1 }, { "pc", 1 }, { "factory-game", 1 }, }, results = { { "human-6", 1 }, { "electric-garbage", 20 }, { "oversize-garbage", 30 }, { "general-waste", 40 }, { type = "fluid", name = "co2", amount = 3200 }, { type = "fluid", name = "concentrated-polluted-water", amount = 1600 }, } }, { type = "recipe", name = "food-6", enabled = false, icon = "__factorio-not-included__/graphics/food-6/item-recipe/32.png", icon_size = 32, category = "cooker-1", subgroup = "fni-item", energy_required = 2, ingredients = { { "plant-6-1", 1 }, { "plant-6-2", 1 }, { "plant-6-3", 1 }, { "meat-6-1", 1 }, { "meat-6-2", 1 }, { "meat-6-3", 1 }, { type = "fluid", name = "wine", amount = 200 }, }, results = { { "food-6", 1 }, { type = "fluid", name = "concentrated-polluted-water", amount = 1200 }, } }, { type = "recipe", name = "plant-6-1", enabled = false, icon = "__factorio-not-included__/graphics/plant-6-1/item-recipe/32.png", icon_size = 32, category = "farm-6-1", subgroup = "fni-item", energy_required = 2, ingredients = { { type = "fluid", name = "chlorine", amount = 1200 }, { type = "fluid", name = "concentrated-polluted-water", amount = 800 }, { "dirt", 4 }, }, results = { { "plant-6-1", 1 }, { type = "fluid", name = "polluted-water", amount = 1600 }, { type = "fluid", name = "h2", amount = 1200 }, } }, { type = "recipe", name = "plant-6-2", enabled = false, icon = "__factorio-not-included__/graphics/plant-6-2/item-recipe/32.png", icon_size = 32, category = "farm-6-2", subgroup = "fni-item", energy_required = 2, ingredients = { { type = "fluid", name = "polluted-water", amount = 800 }, { type = "fluid", name = "polluted-oxygen", amount = 1200 }, { "polluted-dirt", 4 }, }, results = { { "plant-6-2", 1 }, { type = "fluid", name = "chlorine", amount = 1400 }, { type = "fluid", name = "natural-gas", amount = 1200 }, } }, { type = "recipe", name = "plant-6-3", enabled = false, icon = "__factorio-not-included__/graphics/plant-6-3/item-recipe/32.png", icon_size = 32, category = "farm-6-3", subgroup = "fni-item", energy_required = 2, ingredients = { { type = "fluid", name = "chlorine", amount = 800 }, { type = "fluid", name = "h2", amount = 600 }, { "slime", 4 }, }, results = { { "plant-6-3", 1 }, { type = "fluid", name = "n2", amount = 1600 }, { type = "fluid", name = "natural-gas", amount = 1400 }, } }, { type = "recipe", name = "meat-6-1", enabled = false, icon = "__factorio-not-included__/graphics/meat-6-1/item-recipe/32.png", icon_size = 32, category = "pasture-6-1", subgroup = "fni-item", energy_required = 2, ingredients = { { "plant-6-1", 1 }, { "meat-5-1", 1 }, { "copper-cable", 4 }, { type = "fluid", name = "natural-gas", amount = 1200 }, { type = "fluid", name = "polluted-oxygen", amount = 1400 }, }, results = { { "meat-6-1", 1 }, { "fiber", 8 }, { type = "fluid", name = "polluted-water", amount = 1800 }, { type = "fluid", name = "co2", amount = 1600 }, } }, { type = "recipe", name = "meat-6-2", enabled = false, icon = "__factorio-not-included__/graphics/meat-6-2/item-recipe/32.png", icon_size = 32, category = "pasture-6-2", subgroup = "fni-item", energy_required = 2, ingredients = { { "plant-6-2", 1 }, { "meat-5-2", 1 }, { "iron-stick", 2 }, { type = "fluid", name = "polluted-water", amount = 1600 }, { type = "fluid", name = "chlorine", amount = 1400 }, }, results = { { "meat-6-2", 1 }, { type = "fluid", name = "concentrated-polluted-water", amount = 800 }, { type = "fluid", name = "o2", amount = 1200 }, } }, { type = "recipe", name = "meat-6-3", enabled = false, icon = "__factorio-not-included__/graphics/meat-6-3/item-recipe/32.png", icon_size = 32, category = "pasture-6-3", subgroup = "fni-item", energy_required = 2, ingredients = { { "plant-6-3", 1 }, { "meat-5-3", 1 }, { "plastic-bar", 2 }, { type = "fluid", name = "natural-gas", amount = 1600 }, { type = "fluid", name = "o2", amount = 1200 }, }, results = { { "meat-6-3", 1 }, { "slime", 4 }, { type = "fluid", name = "polluted-oxygen", amount = 1800 }, { type = "fluid", name = "chlorine", amount = 1200 }, } }, { type = "recipe", name = "factory-game", enabled = false, icon = "__factorio-not-included__/graphics/factory-game/item-recipe/32.png", icon_size = 32, category = "crafting", subgroup = "fni-item", energy_required = 2, ingredients = { { "processing-unit", 1 }, { "advanced-circuit", 2 }, { "electronic-circuit", 4 }, }, results = { { "factory-game", 1 }, } }, { type = "recipe", name = "space-suite", enabled = false, icon = "__factorio-not-included__/graphics/space-suite/item-recipe/32.png", icon_size = 32, category = "textile-loom-1", subgroup = "fni-item", energy_required = 2, ingredients = { { "processing-unit", 1 }, { "fiber", 8 }, { "plastic-bar", 4 }, }, results = { { "space-suite", 1 }, { type = "fluid", name = "concentrated-polluted-water", amount = 400 }, } }, { type = "recipe", name = "compost-plant-6-1", enabled = false, icon = "__factorio-not-included__/graphics/compost-plant-6-1/item-recipe/32.png", icon_size = 32, category = "compost-1", subgroup = "fni-item", energy_required = 2, ingredients = { { type = "fluid", name = "o2", amount = 400 }, { "plant-6-1", 1 }, }, results = { { "polluted-dirt", 1 }, { type = "fluid", name = "polluted-oxygen", amount = 200 }, } }, { type = "recipe", name = "compost-plant-6-2", enabled = false, icon = "__factorio-not-included__/graphics/compost-plant-6-2/item-recipe/32.png", icon_size = 32, category = "compost-1", subgroup = "fni-item", energy_required = 2, ingredients = { { type = "fluid", name = "polluted-oxygen", amount = 400 }, { "plant-6-2", 1 }, }, results = { { "polluted-dirt", 1 }, { type = "fluid", name = "natural-gas", amount = 200 }, } }, { type = "recipe", name = "compost-plant-6-3", enabled = false, icon = "__factorio-not-included__/graphics/compost-plant-6-3/item-recipe/32.png", icon_size = 32, category = "compost-1", subgroup = "fni-item", energy_required = 2, ingredients = { { type = "fluid", name = "polluted-oxygen", amount = 400 }, { "plant-6-3", 1 }, }, results = { { "polluted-dirt", 1 }, { type = "fluid", name = "h2", amount = 200 }, } }, { type = "recipe", name = "compost-meat-6-1", enabled = false, icon = "__factorio-not-included__/graphics/compost-meat-6-1/item-recipe/32.png", icon_size = 32, category = "compost-1", subgroup = "fni-item", energy_required = 2, ingredients = { { type = "fluid", name = "polluted-oxygen", amount = 400 }, { "meat-6-1", 1 }, }, results = { { "polluted-dirt", 1 }, { type = "fluid", name = "co2", amount = 200 }, } }, { type = "recipe", name = "compost-meat-6-2", enabled = false, icon = "__factorio-not-included__/graphics/compost-meat-6-2/item-recipe/32.png", icon_size = 32, category = "compost-1", subgroup = "fni-item", energy_required = 2, ingredients = { { type = "fluid", name = "polluted-oxygen", amount = 400 }, { "meat-6-2", 1 }, }, results = { { "polluted-dirt", 1 }, { type = "fluid", name = "concentrated-polluted-water", amount = 200 }, } }, { type = "recipe", name = "compost-meat-6-3", enabled = false, icon = "__factorio-not-included__/graphics/compost-meat-6-3/item-recipe/32.png", icon_size = 32, category = "compost-1", subgroup = "fni-item", energy_required = 2, ingredients = { { type = "fluid", name = "polluted-oxygen", amount = 400 }, { "meat-6-3", 1 }, }, results = { { "polluted-dirt", 1 }, { type = "fluid", name = "natural-gas", amount = 200 }, } }, })
nilq/small-lua-stack
null
function widget:GetInfo() return { name = "ShieldtargetAI", desc = "attempt to make units fire the shields of enemy units. Version 1.00", author = "terve886", date = "2019", license = "PD", -- should be compatible with Spring layer = 11, enabled = true } end local pi = math.pi local sin = math.sin local cos = math.cos local atan = math.atan local sqrt = math.sqrt local UPDATE_FRAME=10 local UnitStack = {} local GetUnitMaxRange = Spring.GetUnitMaxRange local GetUnitPosition = Spring.GetUnitPosition local GiveOrderToUnit = Spring.GiveOrderToUnit local GetGroundHeight = Spring.GetGroundHeight local GetUnitsInSphere = Spring.GetUnitsInSphere local GetUnitIsDead = Spring.GetUnitIsDead local GetMyTeamID = Spring.GetMyTeamID local GetUnitDefID = Spring.GetUnitDefID local GetUnitShieldState = Spring.GetUnitShieldState local GetTeamUnits = Spring.GetTeamUnits local GetUnitStates = Spring.GetUnitStates local GetUnitWeaponTarget = Spring.GetUnitWeaponTarget local Jack_ID = UnitDefNames.jumpassault.id local Scythe_ID = UnitDefNames.cloakheavyraid.id local Raven_ID = UnitDefNames.bomberprec.id local Phoenix_ID = UnitDefNames.bomberriot.id local Ripper_ID = UnitDefNames.vehriot.id local Ogre_ID = UnitDefNames.tankriot.id local Reaver_ID = UnitDefNames.cloakriot.id local Kodachi_ID = UnitDefNames.tankraid.id local Dirtbag_ID = UnitDefNames.shieldscout.id local Venom_ID = UnitDefNames.spideremp.id local Moderator_ID = UnitDefNames.jumpskirm.id local Dominatrix_ID = UnitDefNames.vehcapture.id local Widow_ID = UnitDefNames.spiderantiheavy.id local Bandit_ID = UnitDefNames.shieldraid.id local Scorcher_ID = UnitDefNames.vehraid.id local Redback_ID = UnitDefNames.spiderriot.id local Pyro_ID = UnitDefNames.jumpraid.id local Nimbus_ID = UnitDefNames.gunshipheavyskirm.id local Mace_ID = UnitDefNames.hoverriot.id local Dante_ID = UnitDefNames.striderdante.id local Scorpion_ID = UnitDefNames.striderscorpion.id local Ultimatum_ID = UnitDefNames.striderantiheavy.id local Halbert_ID = UnitDefNames.hoverassault.id local Lobster_ID = UnitDefNames.amphlaunch.id local Puppy_ID = UnitDefNames.jumpscout.id local Jugglenaut_ID = UnitDefNames.jumpsumo.id local Recluse_ID = UnitDefNames.spiderskirm.id local Gauss_ID = UnitDefNames.turretgauss.id local Desolator_ID = UnitDefNames.turretheavy.id local Felon_ID = UnitDefNames.shieldfelon.id local Scalpel_ID = UnitDefNames.hoverskirm.id local Stinger_ID = UnitDefNames.turretheavylaser.id local Locust_ID = UnitDefNames.gunshipraid.id local Revenant_ID = UnitDefNames.gunshipassault.id local FELON_MIN_SHIELD = UnitDefs[Felon_ID].customParams.shield_power * 0.9 local ENEMY_DETECT_BUFFER = 35 local Echo = Spring.Echo local GetSpecState = Spring.GetSpectatingState local FULL_CIRCLE_RADIANT = 2 * pi local CMD_UNIT_SET_TARGET = 34923 local CMD_UNIT_CANCEL_TARGET = 34924 local CMD_UNIT_SET_TARGET_CIRCLE = 34925 local CMD_STOP = CMD.STOP local CMD_ATTACK = CMD.ATTACK local ShieldTargettingController = { enemyNear = false, extra_range = 22, new = function(self, unitID) if(unitID)then self = deepcopy(self) self.unitID = unitID self.range = GetUnitMaxRange(self.unitID) self.pos = {GetUnitPosition(self.unitID)} self.drec = false self.isFelon = (GetUnitDefID(self.unitID) == Felon_ID) local unitDefID = GetUnitDefID(self.unitID) local weaponDefID = UnitDefs[unitDefID].weapons[1].weaponDef local wd = WeaponDefs[weaponDefID] if(weaponDefID and wd.damages[4])then self.damage = wd.damages[4] --Echo("ShieldTargettingController added:" .. unitID) return self end end return nil end, unset = function(self) --Echo("ShieldTargettingController removed:" .. self.unitID) if not self.drec then self:stop() end return nil end, isEnemyInRange = function (self) local units = GetUnitsInSphere(self.pos[1], self.pos[2], self.pos[3], self.range + self.extra_range, Spring.ENEMY_UNITS) for i=1, #units do if (GetUnitIsDead(units[i]) == false) then if (self.enemyNear == false)then self:stop() self.enemyNear = true end return true end end self.enemyNear = false return false end, isShieldInEffectiveRange = function (self) local closestShieldID = nil local closestShieldDistance = nil local closestShieldRadius = nil local rotation = nil local units = GetUnitsInSphere(self.pos[1], self.pos[2], self.pos[3], self.range+520, Spring.ENEMY_UNITS) for i=1, #units do local unitDefID = GetUnitDefID(units[i]) if not(unitDefID == nil)then if (GetUnitIsDead(units[i]) == false and UnitDefs[unitDefID].hasShield == true) then local shieldHealth = {GetUnitShieldState(units[i])} if (shieldHealth[2] and self.damage <= shieldHealth[2])then local enemyPositionX, enemyPositionY, enemyPositionZ = GetUnitPosition(units[i]) local targetShieldRadius if (UnitDefs[unitDefID].weapons[2] == nil)then targetShieldRadius = WeaponDefs[UnitDefs[unitDefID].weapons[1].weaponDef].shieldRadius else targetShieldRadius = WeaponDefs[UnitDefs[unitDefID].weapons[2].weaponDef].shieldRadius end local enemyShieldDistance = distance(self.pos[1], enemyPositionX, self.pos[3], enemyPositionZ)-targetShieldRadius if not(closestShieldDistance)then closestShieldDistance = enemyShieldDistance closestShieldID = units[i] closestShieldRadius = targetShieldRadius rotation = atan((self.pos[1]-enemyPositionX)/(self.pos[3]-enemyPositionZ)) end if (enemyShieldDistance < closestShieldDistance and enemyShieldDistance > 20) then closestShieldDistance = enemyShieldDistance closestShieldID = units[i] closestShieldRadius = targetShieldRadius rotation = atan((self.pos[1]-enemyPositionX)/(self.pos[3]-enemyPositionZ)) end end end end end if(closestShieldID ~= nil and (not self.isFelon or select(2, GetUnitShieldState(self.unitID)) > FELON_MIN_SHIELD ))then local enemyPositionX, enemyPositionY, enemyPositionZ = GetUnitPosition(closestShieldID) local targetPosRelative={ sin(rotation) * (closestShieldRadius-14), nil, cos(rotation) * (closestShieldRadius-14), } local targetPosAbsolute if (self.pos[3]<=enemyPositionZ) then targetPosAbsolute = { enemyPositionX-targetPosRelative[1], nil, enemyPositionZ-targetPosRelative[3], } else targetPosAbsolute = { enemyPositionX+targetPosRelative[1], nil, enemyPositionZ+targetPosRelative[3], } end targetPosAbsolute[2]= GetGroundHeight(targetPosAbsolute[1],targetPosAbsolute[3]) self:fire(targetPosAbsolute[1], targetPosAbsolute[2], targetPosAbsolute[3]) else local target = {GetUnitWeaponTarget(self.unitID, 1)} if(target[1]==2)then self:stop() end end end, stop=function(self) GiveOrderToUnit(self.unitID,CMD_UNIT_CANCEL_TARGET, 0, 0) end, fire=function(self, x, y, z) GiveOrderToUnit(self.unitID,CMD_UNIT_SET_TARGET, {x, y, z}, 0) end, handle=function(self) if self.drec then return end if(GetUnitStates(self.unitID).firestate~=0)then self.pos = {GetUnitPosition(self.unitID)} if(self:isEnemyInRange()) then return end self:isShieldInEffectiveRange() end end } local BuildingShieldTargettingController = { new = function(self, unitID) self = self:new(unitID) self.extra_range = 14 self.stop = function(self) GiveOrderToUnit(self.unitID,CMD_STOP, {}, {""},1) end self.fire = function(self, x, y, z) GiveOrderToUnit(self.unitID,CMD_ATTACK, {x, y, z}, 0) end local baseIsEnemyInRange = self.IsEnemyInRange self.IsEnemyInRange = function() self.pos = {GetUnitPosition(self.unitID)} return baseIsEnemyInRange() end end } function distance ( x1, y1, x2, y2 ) local dx = (x1 - x2) local dy = (y1 - y2) return sqrt ( dx * dx + dy * dy ) end function widget:UnitFinished(unitID, unitDefID, unitTeam) if (UnitDefs[unitDefID].isBuilding == false)then if(unitTeam==GetMyTeamID() and UnitDefs[unitDefID].weapons[1] and GetUnitMaxRange(unitID) < 695 and not(unitDefID == Jack_ID or unitDefID == Scythe_ID or unitDefID == Phoenix_ID or unitDefID == Raven_ID or unitDefID == Ogre_ID or unitDefID == Moderator_ID or unitDefID == Dominatrix_ID or unitDefID == Pyro_ID or unitDefID == Nimbus_ID or unitDefID == Widow_ID or unitDefID == Scorpion_ID or unitDefID == Ultimatum_ID or unitDefID == Halbert_ID or unitDefID == Puppy_ID or unitDefID == Lobster_ID or unitDefID == Jugglenaut_ID or unitDefID == Recluse_ID or unitDefID == Dirtbag_ID or unitDefID == Scalpel_ID or string.match(UnitDefs[unitDefID].name, "dyn") or unitDefID == Locust_ID or unitDefID == Revenant_ID)) then UnitStack[unitID] = ShieldTargettingController:new(unitID); end else if(unitTeam==GetMyTeamID() and (unitDefID == Gauss_ID or unitDefID == Desolator_ID or unitDefID == Stinger_ID))then UnitStack[unitID] = BuildingShieldTargettingController:new(unitID); end end end function widget:CommandNotify(id, params, options) local selectedUnits = Spring.GetSelectedUnits() for _, unitID in pairs(selectedUnits) do -- check selected units... if UnitStack[unitID] then -- was issued to one of our units. if id == CMD_UNIT_SET_TARGET or id == CMD_UNIT_SET_TARGET_CIRCLE then -- Direct order to set a priority target UnitStack[unitID].drec = true elseif id == CMD_STOP or id == CMD_UNIT_CANCEL_TARGET then -- Cancel direct order UnitStack[unitID].drec = false end end end end function widget:UnitDestroyed(unitID) if not (UnitStack[unitID]==nil) then UnitStack[unitID]=UnitStack[unitID]:unset(); end end function widget:GameFrame(n) if (n%UPDATE_FRAME==0) then for _,unit in pairs(UnitStack) do unit:handle() end end end function deepcopy(orig) local orig_type = type(orig) local copy if orig_type == 'table' then copy = {} for orig_key, orig_value in next, orig, nil do copy[deepcopy(orig_key)] = deepcopy(orig_value) end setmetatable(copy, deepcopy(getmetatable(orig))) else copy = orig end return copy end -- The rest of the code is there to disable the widget for spectators local function DisableForSpec() if GetSpecState() then widgetHandler:RemoveWidget(widget) end end function widget:Initialize() DisableForSpec() local units = GetTeamUnits(Spring.GetMyTeamID()) for i=1, #units do local unitDefID = GetUnitDefID(units[i]) if (UnitDefs[unitDefID].isBuilding == false)then if(UnitDefs[unitDefID].weapons[1] and GetUnitMaxRange(units[i]) < 695 and not(unitDefID == Jack_ID or unitDefID == Scythe_ID or unitDefID == Phoenix_ID or unitDefID == Raven_ID or unitDefID == Ogre_ID or unitDefID == Moderator_ID or unitDefID == Dominatrix_ID or unitDefID == Pyro_ID or unitDefID == Nimbus_ID or unitDefID == Widow_ID or unitDefID == Scorpion_ID or unitDefID == Ultimatum_ID or unitDefID == Halbert_ID or unitDefID == Puppy_ID or unitDefID == Lobster_ID or unitDefID == Jugglenaut_ID or unitDefID == Recluse_ID or unitDefID == Dirtbag_ID or unitDefID == Scalpel_ID or string.match(UnitDefs[unitDefID].name, "dyn") or unitDefID == Locust_ID or unitDefID == Revenant_ID)) then if (UnitStack[units[i]]==nil) then UnitStack[units[i]] = ShieldTargettingController:new(units[i]); end end else if (UnitStack[units[i]]==nil) then if(unitDefID == Gauss_ID or unitDefID == Desolator_ID or unitDefID == Stinger_ID)then UnitStack[units[i]] = BuildingShieldTargettingController:new(units[i]); end end end end end function widget:PlayerChanged (playerID) DisableForSpec() end
nilq/small-lua-stack
null
junkDealerReggiConvoTemplate = ConvoTemplate:new { initialScreen = "init", templateType = "Lua", luaClassHandler = "JunkDealerReggiConvoHandler", screens = {} } init = ConvoScreen:new { id = "init", leftDialog = "@conversation/junk_reggi_nym:s_60d2f507", -- Looking for work? I don't know that for sure but normally people who come around here are always looking for something. stopConversation = "false", options = { {"@conversation/junk_reggi_nym:s_ef8c7236", "ask_for_loot"}, -- I am always looking for work. {"@conversation/junk_reggi_nym:s_53d778d8", "true_words"}, -- Not really...work has never suited me. } } junkDealerReggiConvoTemplate:addScreen(init); true_words = ConvoScreen:new { id = "true_words", leftDialog = "@conversation/junk_reggi_nym:s_f25d9c2", -- Truer words have never been spoken. But if you ever change your mind you know where to find me. stopConversation = "true", options = {} } junkDealerReggiConvoTemplate:addScreen(true_words); ask_for_loot = ConvoScreen:new { id = "ask_for_loot", leftDialog = "@conversation/junk_reggi_nym:s_14e5bdc0", -- I don't really have to much in the way of jobs but Nym is always looking to buy weapons and such. He also has some bounties out on those cursed Blood Razors and Canyon Cosairs who haven't figured out their place yet. stopConversation = "false", options = { --{"@conversation/junk_reggi_nym:s_b8e27f3c", "start_sale"}, -- Well this looks like my lucky day. --{"@conversation/junk_reggi_nym:s_2e005077", "no_loot"}, -- It doesn't look like I have anything Nym would like to buy. } } junkDealerReggiConvoTemplate:addScreen(ask_for_loot); no_loot = ConvoScreen:new { id = "no_loot", leftDialog = "@conversation/junk_reggi_nym:s_233f3214", -- Not a problem. Like I said Nym is always looking for these things so if you run across any come on back. stopConversation = "true", options = {} } junkDealerReggiConvoTemplate:addScreen(no_loot); start_sale = ConvoScreen:new { id = "start_sale", leftDialog = "@conversation/junk_reggi_nym:s_5c453a2f", -- Being lucky is one of the best things in the world. Lets take a look at what you have to offer. Nym isn't much for bartering so you can take the price I give or you can leave it. Makes no difference to me really. stopConversation = "true", options = {} } junkDealerReggiConvoTemplate:addScreen(start_sale); addConversationTemplate("junkDealerReggiConvoTemplate", junkDealerReggiConvoTemplate);
nilq/small-lua-stack
null
local tValidSoundExtensions = { wav = true, mp3 = true, ogg = true, -- mid = false, -- flac = false } -- Since only three-letter sound extensions are valid -- This function can get away with only checking the last three characters of the string function string.IsSoundFile(str) return tValidSoundExtensions[string.sub(str, -3)] or false end
nilq/small-lua-stack
null
local Action = require(script.Parent.Action) return Action("BrushIgnoreInvisibleSet", function(ignoreInvisible) return { ignoreInvisible = ignoreInvisible } end)
nilq/small-lua-stack
null
--[[--ldoc desc @module Card @author ShuaiYang Date 2018-10-24 17:43:45 Last Modified by ShuaiYang Last Modified time 2018-10-24 17:47:33 ]] local Card = class("Card"); function Card:ctor(data) data = checktable(data) self.tByte = nil; self.value = nil; self.type = nil; if data.tByte then self.tByte = data.tByte; end end return Card;
nilq/small-lua-stack
null
AddCSLuaFile() DEFINE_BASECLASS( "widget_arrow" ) local widget_axis_arrow = { Base = "widget_arrow" } function widget_axis_arrow:Initialize() BaseClass.Initialize( self ) end function widget_axis_arrow:SetupDataTables() BaseClass.SetupDataTables( self ) self:SetDTInt( 1, 0 ); end function widget_axis_arrow:ArrowDragged( pl, mv, dist ) self:GetParent():OnArrowDragged( self:GetDTInt( 1 ), dist, pl, mv ) end scripted_ents.Register( widget_axis_arrow, "widget_axis_arrow" ) -- -- widget_axis_disc -- DEFINE_BASECLASS( "widget_disc" ) local widget_axis_disc = { Base = "widget_disc" } function widget_axis_disc:Initialize() BaseClass.Initialize( self ) end function widget_axis_disc:SetupDataTables() BaseClass.SetupDataTables( self ) self:SetDTInt( 1, 0 ); end function widget_axis_disc:ArrowDragged( pl, mv, dist ) self:GetParent():OnArrowDragged( self:GetDTInt( 1 ), dist, pl, mv ) end scripted_ents.Register( widget_axis_disc, "widget_vein_axis_disc" ) local matArrow = Material( "widgets/arrow.png" ) DEFINE_BASECLASS( "widget_base" ) function ENT:Initialize() BaseClass.Initialize( self ) self:SetCollisionBounds( Vector( -1, -1, -1 ), Vector( 1, 1, 1 ) ) self:SetSolid( SOLID_NONE ) end function ENT:OnClick( ply ) MsgN( "OnClick" ) end function ENT:OnRightClick( ply ) MsgN( "OnRightClick" ) end function ENT:PressedThink( pl, mv ) MsgN( "PressedThink" ) end function ENT:PressedShouldDraw( widget ) MsgN( "PressedShouldDraw" ) return true end function ENT:PressStart( pl, mv ) MsgN( "PressStart" ) end function ENT:PressEnd( pl, mv ) MsgN( "PressEnd" ) end function ENT:DragThink( pl, mv, dist ) MsgN( "DragThink" ) end function ENT:Setup( ent, boneid, rotate, size ) self.Rotating = rotate; self:FollowBone( ent, boneid or 0 ) self:SetLocalPos( Vector( 0, 0, 0 ) ) self:SetLocalAngles( Angle( 0, 0, 0 ) ) local EntName = "widget_axis_arrow" if ( rotate ) then EntName = "widget_axis_disc" end self.ArrowX = ents.Create( EntName ) self.ArrowX:SetParent( self ) self.ArrowX:SetColor( Color( 255, 0, 0, 255 ) ) self.ArrowX:Spawn() self.ArrowX:SetLocalPos( Vector( 0, 0, 0 ) ) self.ArrowX:SetLocalAngles( Vector(1,0,0):Angle() ) self.ArrowX:SetSize( size ); self.ArrowX:SetDTInt( 1, 1 ); self.ArrowX:SetDTInt( 0, 5 ); self.ArrowY = ents.Create( EntName ) self.ArrowY:SetParent( self ) self.ArrowY:SetColor( Color( 0, 230, 50, 255 ) ) self.ArrowY:Spawn() self.ArrowY:SetLocalPos( Vector( 0, 0, 0 ) ) self.ArrowY:SetLocalAngles( Vector(0,1,0):Angle() ) self.ArrowY:SetSize( size ); self.ArrowY:SetDTInt( 1, 2 ); self.ArrowY:SetDTInt( 0, 5 ); self.ArrowZ = ents.Create( EntName ) self.ArrowZ:SetParent( self ) self.ArrowZ:SetColor( Color( 50, 100, 255, 255 ) ) self.ArrowZ:Spawn() self.ArrowZ:SetLocalPos( Vector( 0, 0, 0 ) ) self.ArrowZ:SetLocalAngles( Vector(0,0,1):Angle() ) self.ArrowZ:SetSize( size ); self.ArrowZ:SetDTInt( 1, 3 ); self.ArrowZ:SetDTInt( 0, 5 ); end function ENT:Draw() end function ENT:InvalidateSize() self.ArrowX:InvalidateSize( self:GetParent() ); self.ArrowY:InvalidateSize( self:GetParent() ); self.ArrowZ:InvalidateSize( self:GetParent() ); end function ENT:OnArrowDragged( num, dist, pl, mv ) if( CLIENT ) then return end if( self.Rotating ) then local ent = self:GetParent(); local arrow; if ( num == 2 ) then arrow = self.ArrowX end if ( num == 3 ) then arrow = self.ArrowY end if ( num == 1 ) then arrow = self.ArrowZ end if ( !IsValid( arrow ) ) then return end local a = arrow:GetAngles(); if ( !IsValid( ent ) ) then return end local ang = ent:GetAngles(); if ( num == 2 ) then ang:RotateAroundAxis( a:Right(), -dist ); end if ( num == 3 ) then ang:RotateAroundAxis( a:Up(), dist ); end if ( num == 1 ) then ang:RotateAroundAxis( a:Up(), -dist ); end ent:SetAngles( ang ); else local ent = self:GetParent(); local arrow; if ( num == 1 ) then arrow = self.ArrowX end if ( num == 2 ) then arrow = self.ArrowY end if ( num == 3 ) then arrow = self.ArrowZ end if ( !IsValid( arrow ) ) then return end local fwd = arrow:GetAngles():Forward(); if ( !IsValid( ent ) ) then return end local v = fwd * dist; ent:SetPos( ent:GetPos() + v ); end end
nilq/small-lua-stack
null
-- Game: Collect of the most of the rarest mineral orbiting aroung the sun and outcompete your competetor. -- DO NOT MODIFY THIS FILE -- Never try to directly create an instance of this class, or modify its member variables. -- Instead, you should only be reading its variables and calling its functions. local class = require("joueur.utilities.class") local BaseGame = require("joueur.baseGame") -- <<-- Creer-Merge: requires -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. -- you can add additional require(s) here -- <<-- /Creer-Merge: requires -->> --- Collect of the most of the rarest mineral orbiting aroung the sun and outcompete your competetor. -- @classmod Game local Game = class(BaseGame) -- initializes a Game with basic logic as provided by the Creer code generator function Game:init(...) BaseGame.init(self, ...) --- The name of this game, "{game_name}". -- @field[string] self.name -- The following values should get overridden when delta states are merged, but we set them here as a reference for you to see what variables this class has. --- All the celestial bodies in the game. The first two are planets and the third is the sun. The fourth is the VP asteroid. Everything else is normal asteroids. self.bodies = Table() --- The player whose turn it is currently. That player can send commands. Other players cannot. self.currentPlayer = nil --- The current turn number, starting at 0 for the first player's turn. self.currentTurn = 0 --- The cost of dashing. self.dashCost = 0 --- The distance traveled each turn by dashing. self.dashDistance = 0 --- A mapping of every game object's ID to the actual game object. Primarily used by the server and client to easily refer to the game objects via ID. self.gameObjects = Table() --- The value of every unit of genarium. self.genariumValue = 0 --- A array-like table of all jobs. first item is corvette, second is missileboat, third is martyr, fourth is transport, and fifth is miner. self.jobs = Table() --- The value of every unit of legendarium. self.legendariumValue = 0 --- The highest amount of material, that can be in a asteroid. self.maxAsteroid = 0 --- The maximum number of turns before the game will automatically end. self.maxTurns = 100 --- The smallest amount of material, that can be in a asteroid. self.minAsteroid = 0 --- The rate at which miners grab minerals from asteroids. self.miningSpeed = 0 --- The amount of mythicite that spawns at the start of the game. self.mythiciteAmount = 0 --- The number of orbit updates you cannot mine the mithicite asteroid. self.orbitsProtected = 0 --- The rarity modifier of the most common ore. This controls how much spawns. self.oreRarityGenarium = 0 --- The rarity modifier of the rarest ore. This controls how much spawns. self.oreRarityLegendarium = 0 --- The rarity modifier of the second rarest ore. This controls how much spawns. self.oreRarityRarium = 0 --- The amount of energy a planet can hold at once. self.planetEnergyCap = 0 --- The amount of energy the planets restore each round. self.planetRechargeRate = 0 --- List of all the players in the game. self.players = Table() --- The standard size of ships. self.projectileRadius = 0 --- The amount of distance missiles travel through space. self.projectileSpeed = 0 --- Every projectile in the game. self.projectiles = Table() --- The value of every unit of rarium. self.rariumValue = 0 --- The regeneration rate of asteroids. self.regenerateRate = 0 --- A unique identifier for the game instance that is being played. self.session = "" --- The standard size of ships. self.shipRadius = 0 --- The size of the map in the X direction. self.sizeX = 0 --- The size of the map in the Y direction. self.sizeY = 0 --- The amount of time (in nano-seconds) added after each player performs a turn. self.timeAddedPerTurn = 0 --- The number of turns it takes for a asteroid to orbit the sun. (Asteroids move after each players turn). self.turnsToOrbit = 0 --- Every Unit in the game. self.units = Table() self.name = "Stardash" self._gameObjectClasses = { Body = require("games.stardash.body"), GameObject = require("games.stardash.gameObject"), Job = require("games.stardash.job"), Player = require("games.stardash.player"), Projectile = require("games.stardash.projectile"), Unit = require("games.stardash.unit"), } end -- <<-- Creer-Merge: functions -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. -- if you want to add any client side logic this is where you can add them -- <<-- /Creer-Merge: functions -->> return Game
nilq/small-lua-stack
null
local current_folder = (...):gsub('%.[^%.]+$', '') .. "." local sdl = require(current_folder .. "sdl2") local ffi = require "ffi" local system = {} function system.getClipboardText() if sdl.hasClipboardText() then return ffi.string(sdl.getClipboardText()) end end function system.setClipboardText(text) sdl.setClipboardText(text) end function system.getOS() return ffi.string(sdl.getPlatform()) end function system.getPowerInfo() local percent, seconds = ffi.new("int[1]"), ffi.new("int[1]") local state = sdl.getPowerInfo(percent, seconds) local states = { [tonumber(sdl.POWERSTATE_UNKNOWN)] = "unknown", [tonumber(sdl.POWERSTATE_ON_BATTERY)] = "battery", [tonumber(sdl.POWERSTATE_NO_BATTERY)] = "nobattery", [tonumber(sdl.POWERSTATE_CHARGING)] = "charging", [tonumber(sdl.POWERSTATE_CHARGED)] = "charged" } return states[tonumber(state)], percent[0] >= 0 and percent[0] or nil, seconds[0] >= 0 and seconds[0] or nil end function system.getProcessorCount() return tonumber(sdl.getCPUCount()) end function system.openURL(path) local osname = hate.system.getOS() local cmds = { ["Windows"] = "start \"\"", ["OS X"] = "open", ["Linux"] = "xdg-open" } if path:sub(1, 7) == "file://" then cmds["Windows"] = "explorer" -- Windows-ify if osname == "Windows" then path = path:sub(8):gsub("/", "\\") end end if not cmds[osname] then print("What /are/ birds?") return end local cmdstr = cmds[osname] .. " \"%s\"" -- print(cmdstr, path) os.execute(cmdstr:format(path)) end return system
nilq/small-lua-stack
null
local class = require('middleclass') local Utils = class('Utils') function Utils:tableMerge(t1, t2) for k,v in pairs(t2) do if type(v) == "table" then if type(t1[k] or false) == "table" then tableMerge(t1[k] or {}, t2[k] or {}) else t1[k] = v end else t1[k] = v end end return t1 end return Utils
nilq/small-lua-stack
null
--- Helper library for reading/writing files to the data folder. -- @module ix.data ix.data = ix.data or {} ix.data.stored = ix.data.stored or {} -- Create a folder to store data in. file.CreateDir("helix") --- Populates a file in the `data/helix` folder with some serialized data. -- @realm shared -- @string key Name of the file to save -- @param value Some sort of data to save -- @bool[opt=false] bGlobal Whether or not to write directly to the `data/helix` folder, or the `data/helix/schema` folder, -- where `schema` is the name of the current schema. -- @bool[opt=false] bIgnoreMap Whether or not to ignore the map and save in the schema folder, rather than -- `data/helix/schema/map`, where `map` is the name of the current map. function ix.data.Set(key, value, bGlobal, bIgnoreMap) -- Get the base path to write to. local path = "helix/" .. (bGlobal and "" or Schema.folder .. "/") .. (bIgnoreMap and "" or game.GetMap() .. "/") -- Create the schema folder if the data is not global. if (!bGlobal) then file.CreateDir("helix/" .. Schema.folder .. "/") end -- If we're not ignoring the map, create a folder for the map. file.CreateDir(path) -- Write the data using JSON encoding. file.Write(path .. key .. ".txt", util.TableToJSON({value})) -- Cache the data value here. ix.data.stored[key] = value return path end --- Retrieves the contents of a saved file in the `data/helix` folder. -- @realm shared -- @string key Name of the file to load -- @param default Value to return if the file could not be loaded successfully -- @bool[opt=false] bGlobal Whether or not the data is in the `data/helix` folder, or the `data/helix/schema` folder, -- where `schema` is the name of the current schema. -- @bool[opt=false] bIgnoreMap Whether or not to ignore the map and load from the schema folder, rather than -- `data/helix/schema/map`, where `map` is the name of the current map. -- @bool[opt=false] bRefresh Whether or not to skip the cache and forcefully load from disk. -- @return Value associated with the key, or the default that was given if it doesn't exists function ix.data.Get(key, default, bGlobal, bIgnoreMap, bRefresh) -- If it exists in the cache, return the cached value so it is faster. if (!bRefresh) then local stored = ix.data.stored[key] if (stored != nil) then return stored end end -- Get the path to read from. local path = "helix/" .. (bGlobal and "" or Schema.folder .. "/") .. (bIgnoreMap and "" or game.GetMap() .. "/") -- Read the data from a local file. local contents = file.Read(path .. key .. ".txt", "DATA") if (contents and contents != "") then local status, decoded = pcall(util.JSONToTable, contents) if (status and decoded) then local value = decoded[1] if (value != nil) then return value end end -- Backwards compatibility. -- This may be removed in the future. status, decoded = pcall(pon.decode, contents) if (status and decoded) then local value = decoded[1] if (value != nil) then return value end end end return default end --- Deletes the contents of a saved file in the `data/helix` folder. -- @realm shared -- @string key Name of the file to delete -- @bool[opt=false] bGlobal Whether or not the data is in the `data/helix` folder, or the `data/helix/schema` folder, -- where `schema` is the name of the current schema. -- @bool[opt=false] bIgnoreMap Whether or not to ignore the map and delete from the schema folder, rather than -- `data/helix/schema/map`, where `map` is the name of the current map. -- @treturn bool Whether or not the deletion has succeeded function ix.data.Delete(key, bGlobal, bIgnoreMap) -- Get the path to read from. local path = "helix/" .. (bGlobal and "" or Schema.folder .. "/") .. (bIgnoreMap and "" or game.GetMap() .. "/") -- Read the data from a local file. local contents = file.Read(path .. key .. ".txt", "DATA") if (contents and contents != "") then file.Delete(path .. key .. ".txt") ix.data.stored[key] = nil return true end return false end if (SERVER) then timer.Create("ixSaveData", 600, 0, function() hook.Run("SaveData") end) end
nilq/small-lua-stack
null
local json = require "cjson" local stringy = require "stringy" local http_client = require "kong.tools.http_client" local spec_helper = require "spec.spec_helpers" local function it_content_types(title, fn) local test_form_encoded = fn("application/www-url-formencoded") local test_json = fn("application/json") it(title.." with application/www-form-urlencoded", test_form_encoded) it(title.." with application/json", test_json) end describe("Admin API", function() local api local dao_factory = spec_helper.get_env().dao_factory setup(function() spec_helper.prepare_db() spec_helper.start_kong() end) teardown(function() spec_helper.stop_kong() end) before_each(function() local fixtures = spec_helper.insert_fixtures { api = { {name = "api-test", request_host = "api-test.com", upstream_url = "http://mockbin.com"} } } api = fixtures.api[1] end) after_each(function() spec_helper.drop_db() end) describe("/apis/", function() local BASE_URL = spec_helper.API_URL.."/apis/" describe("POST", function() it_content_types("should create an API", function(content_type) return function() local _, status = http_client.post(BASE_URL, { name = "new-api", request_host = "new-api.com", upstream_url = "http://mockbin.com" }, {["content-type"] = content_type}) assert.equal(201, status) end end) describe("errors", function() it("should notify of malformed JSON body", function() local response, status = http_client.post(BASE_URL, '{"hello":"world"', {["content-type"] = "application/json"}) assert.equal(400, status) assert.equal('{"message":"Cannot parse JSON body"}\n', response) end) it_content_types("return proper validation errors", function(content_type) return function() local response, status = http_client.post(BASE_URL, {}, {["content-type"] = content_type}) assert.equal(400, status) assert.equal([[{"upstream_url":"upstream_url is required","request_path":"At least a 'request_host' or a 'request_path' must be specified","request_host":"At least a 'request_host' or a 'request_path' must be specified"}]], stringy.strip(response)) response, status = http_client.post(BASE_URL, {request_host = "/httpbin", upstream_url = "http://mockbin.com"}, {["content-type"] = content_type}) assert.equal(400, status) assert.equal([[{"request_host":"Invalid value: \/httpbin"}]], stringy.strip(response)) end end) it_content_types("should return HTTP 409 if already exists", function(content_type) return function() local response, status = http_client.post(BASE_URL, { request_host = "api-test.com", upstream_url = "http://mockbin.com" }, {["content-type"] = content_type}) assert.equal(409, status) assert.equal([[{"request_host":"already exists with value 'api-test.com'"}]], stringy.strip(response)) end end) end) end) describe("PUT", function() it_content_types("should create if not exists", function(content_type) return function() local _, status = http_client.put(BASE_URL, { name = "new-api", request_host = "new-api.com", upstream_url = "http://mockbin.com" }, {["content-type"] = content_type}) assert.equal(201, status) end end) it_content_types("#only should not update if some required fields are missing", function(content_type) return function() local response, status = http_client.put(BASE_URL, { id = api.id, name = "api-PUT-tests-updated", request_host = "updated-api.mockbin.com", upstream_url = "http://mockbin.com" }, {["content-type"] = content_type}) assert.equal(400, status) local body = json.decode(response) assert.equal("created_at is required", body.created_at) end end) it_content_types("#only should update if exists", function(content_type) return function() local response, status = http_client.put(BASE_URL, { id = api.id, name = "api-PUT-tests-updated", request_host = "updated-api.mockbin.com", upstream_url = "http://mockbin.com", created_at = 1461276890000 }, {["content-type"] = content_type}) assert.equal(200, status) local body = json.decode(response) assert.equal("api-PUT-tests-updated", body.name) assert.truthy(body.created_at) end end) describe("errors", function() it_content_types("should return proper validation errors", function(content_type) return function() local response, status = http_client.put(BASE_URL, {}, {["content-type"] = content_type}) assert.equal(400, status) assert.equal([[{"upstream_url":"upstream_url is required","request_path":"At least a 'request_host' or a 'request_path' must be specified","request_host":"At least a 'request_host' or a 'request_path' must be specified"}]], stringy.strip(response)) end end) it_content_types("should return HTTP 409 if already exists", function(content_type) -- @TODO this test actually defeats the purpose of PUT. It should probably replace the entity return function() local response, status = http_client.put(BASE_URL, { request_host = "api-test.com", upstream_url = "http://mockbin.com" }, {["content-type"] = content_type}) assert.equal(409, status) assert.equal([[{"request_host":"already exists with value 'api-test.com'"}]], stringy.strip(response)) end end) end) end) describe("GET", function() before_each(function() spec_helper.drop_db() spec_helper.seed_db(10) end) it("should retrieve the first page", function() local response, status = http_client.get(BASE_URL) assert.equal(200, status) local body = json.decode(response) assert.truthy(body.data) assert.equal(10, table.getn(body.data)) assert.equal(10, body.total) end) it("should retrieve a paginated set", function() local response, status = http_client.get(BASE_URL, {size = 3}) assert.equal(200, status) local body_page_1 = json.decode(response) assert.truthy(body_page_1.data) assert.equal(3, #body_page_1.data) assert.truthy(body_page_1.next) assert.equal(10, body_page_1.total) response, status = http_client.get(BASE_URL, {size = 3, offset = body_page_1.next}) assert.equal(200, status) local body_page_2 = json.decode(response) assert.truthy(body_page_2.data) assert.equal(3, #body_page_2.data) assert.truthy(body_page_2.next) assert.not_same(body_page_1, body_page_2) assert.equal(10, body_page_2.total) response, status = http_client.get(BASE_URL, {size = 3, offset = body_page_2.next}) assert.equal(200, status) local body_page_3 = json.decode(response) assert.truthy(body_page_3.data) assert.equal(3, #body_page_3.data) assert.equal(10, body_page_3.total) assert.truthy(body_page_3.next) assert.not_same(body_page_2, body_page_3) response, status = http_client.get(BASE_URL, {size = 3, offset = body_page_3.next}) assert.equal(200, status) local body_page_3 = json.decode(response) assert.truthy(body_page_3.data) assert.equal(1, #body_page_3.data) assert.equal(10, body_page_3.total) assert.falsy(body_page_3.next) assert.not_same(body_page_2, body_page_3) end) it("should refuse invalid filters", function() local response, status = http_client.get(BASE_URL, {foo = "bar"}) assert.equal(400, status) assert.equal([[{"foo":"unknown field"}]], stringy.strip(response)) end) end) describe("/apis/:api", function() describe("GET", function() it("should retrieve by id", function() local response, status = http_client.get(BASE_URL..api.id) assert.equal(200, status) local body = json.decode(response) assert.same(api, body) end) it("should retrieve by name", function() local response, status = http_client.get(BASE_URL..api.name) assert.equal(200, status) local body = json.decode(response) assert.same(api, body) end) it("should reply with HTTP 404 if not found", function() local _, status = http_client.get(BASE_URL.."none") assert.equal(404, status) end) end) describe("PATCH", function() it_content_types("should update name if found", function(content_type) return function() local response, status = http_client.patch(BASE_URL..api.id, { name = "patch-updated" }, {["content-type"] = content_type}) assert.equal(200, status) local body = json.decode(response) assert.equal("patch-updated", body.name) local api, err = dao_factory.apis:find {id = api.id} assert.falsy(err) assert.equal("patch-updated", api.name) end end) it_content_types("should update name by its old name", function(content_type) return function() local response, status = http_client.patch(BASE_URL..api.name, { name = "patch-updated" }, {["content-type"] = content_type}) assert.equal(200, status) local body = json.decode(response) assert.equal("patch-updated", body.name) local api, err = dao_factory.apis:find {id = api.id} assert.falsy(err) assert.equal("patch-updated", api.name) end end) it_content_types("should update request_path", function(content_type) return function() local response, status = http_client.patch(BASE_URL..api.id, { request_path = "/httpbin-updated" }, {["content-type"] = content_type}) assert.equal(200, status) local body = json.decode(response) assert.equal("/httpbin-updated", body.request_path) local api, err = dao_factory.apis:find {id = api.id} assert.falsy(err) assert.equal("/httpbin-updated", api.request_path) end end) it_content_types("should update strip_request_path if it was not previously set", function(content_type) return function() local response, status = http_client.patch(BASE_URL..api.id, { strip_request_path = true }, {["content-type"] = content_type}) assert.equal(200, status) local body = json.decode(response) assert.True(body.strip_request_path) local api, err = dao_factory.apis:find {id = api.id} assert.falsy(err) assert.True(api.strip_request_path) end end) it_content_types("should update request_host and request_path at once", function(content_type) return function() local response, status = http_client.patch(BASE_URL..api.id, { request_path = "/httpbin-updated-path", request_host = "httpbin-updated.org" }, {["content-type"] = content_type}) assert.equal(200, status) local body = json.decode(response) assert.equal("/httpbin-updated-path", body.request_path) assert.equal("httpbin-updated.org", body.request_host) local api, err = dao_factory.apis:find {id = api.id} assert.falsy(err) assert.equal("/httpbin-updated-path", api.request_path) assert.equal("httpbin-updated.org", api.request_host) end end) describe("errors", function() it_content_types("should return 404 if not found", function(content_type) return function() local _, status = http_client.patch(BASE_URL.."hello", { name = "patch-updated" }, {["content-type"] = content_type}) assert.equal(404, status) end end) it_content_types("should return proper validation errors", function(content_type) return function() local response, status = http_client.patch(BASE_URL..api.id, { name = "api", request_host = " " }, {["content-type"] = content_type}) assert.equal(400, status) assert.equal([[{"request_host":"At least a 'request_host' or a 'request_path' must be specified"}]], stringy.strip(response)) end end) end) end) describe("DELETE", function() before_each(function() local _, err = dao_factory.apis:insert { name = "to-delete", request_host = "to-delete.com", upstream_url = "http://mockbin.com" } assert.falsy(err) end) it("delete an API by id", function() local response, status = http_client.delete(BASE_URL..api.id) assert.equal(204, status) assert.falsy(response) end) it("delete an API by name", function() local response, status = http_client.delete(BASE_URL.."to-delete") assert.equal(204, status) assert.falsy(response) end) describe("error", function() it("should return HTTP 404 if not found", function() local _, status = http_client.delete(BASE_URL.."hello") assert.equal(404, status) end) end) end) describe("/apis/:api/plugins/", function() local PLUGIN_BASE_URL local api_with_plugin local plugin before_each(function() PLUGIN_BASE_URL = BASE_URL..api.id.."/plugins/" local fixtures = spec_helper.insert_fixtures { api = { {name = "plugin-put-tests", request_host = "plugin-put-tests.com", upstream_url = "http://mockbin.com"} }, plugin = { {name = "key-auth", config = {hide_credentials = true}, __api = 1} } } api_with_plugin = fixtures.api[1] plugin = fixtures.plugin[1] end) describe("POST", function() it_content_types("should create a plugin configuration", function(content_type) return function() local response, status = http_client.post(PLUGIN_BASE_URL, { name = "key-auth", ["config.key_names"] = "apikey,key" }, {["content-type"] = content_type}) assert.equal(201, status) local body = json.decode(response) assert.equal("key-auth", body.name) assert.truthy(body.config) assert.same({"apikey", "key"}, body.config.key_names) end end) it_content_types("should create with default value", function(content_type) return function() local response, status = http_client.post(PLUGIN_BASE_URL, { name = "key-auth" }, {["content-type"] = content_type}) assert.equal(201, status) local body = json.decode(response) assert.equal("key-auth", body.name) assert.truthy(body.config) assert.same({"apikey"}, body.config.key_names) end end) describe("errors", function() it_content_types("should return proper validation errors", function(content_type) return function() local response, status = http_client.post(PLUGIN_BASE_URL, {}, {["content-type"] = content_type}) assert.equal(400, status) assert.equal([[{"name":"name is required"}]], stringy.strip(response)) end end) end) end) describe("PUT", function() it_content_types("should create if not exists", function(content_type) return function() local response, status = http_client.put(PLUGIN_BASE_URL, { name = "key-auth", ["config.key_names"] = "apikey,key" }, {["content-type"] = content_type}) assert.equal(201, status) local body = json.decode(response) assert.equal("key-auth", body.name) assert.truthy(body.config) assert.same({"apikey", "key"}, body.config.key_names) end end) it_content_types("should create with default value", function(content_type) return function() local response, status = http_client.put(PLUGIN_BASE_URL, { name = "key-auth" }, {["content-type"] = content_type}) assert.equal(201, status) local body = json.decode(response) assert.equal("key-auth", body.name) assert.truthy(body.config) assert.same({"apikey"}, body.config.key_names) end end) it_content_types("should update if exists", function(content_type) return function() local response, status = http_client.put(PLUGIN_BASE_URL, { id = plugin.id, name = "key-auth", ["config.key_names"] = "updated_apikey", created_at = 1461276890000 }, {["content-type"] = content_type}) assert.equal(200, status) local body = json.decode(response) assert.truthy(body.config) assert.equal("updated_apikey", body.config.key_names[1]) end end) it_content_types("should update with default values", function(content_type) return function() local plugin, err = dao_factory.plugins:insert { name = "key-auth", api_id = api.id, config = {hide_credentials = true} } assert.falsy(err) assert.True(plugin.config.hide_credentials) assert.same({"apikey"}, plugin.config.key_names) local response, status = http_client.put(PLUGIN_BASE_URL, { id = plugin.id, name = "key-auth", created_at = 1461276890000 }, {["content-type"] = content_type}) assert.equal(200, status) local body = json.decode(response) assert.truthy(body.config) assert.False(body.config.hide_credentials) local plugin, err = dao_factory.plugins:find { id = plugin.id, name = plugin.name } assert.falsy(err) assert.truthy(plugin.config) assert.False(plugin.config.hide_credentials) assert.same({"apikey"}, plugin.config.key_names) end end) it_content_types("should update with default values bis", function(content_type) return function() local plugin, err = dao_factory.plugins:insert { name = "rate-limiting", api_id = api.id, config = {hour = 2} } assert.falsy(err) assert.equal(2, plugin.config.hour) local response, status = http_client.put(PLUGIN_BASE_URL, { id = plugin.id, api_id = api.id, name = "rate-limiting", ["config.minute"] = 3, created_at = 1461276890000 }, {["content-type"] = content_type}) assert.equal(200, status) local body = json.decode(response) assert.truthy(body.config) assert.falsy(body.config.hour) assert.equal(3, body.config.minute) local plugin, err = dao_factory.plugins:find { id = plugin.id, name = plugin.name } assert.falsy(err) assert.truthy(plugin.config) assert.falsy(plugin.config.hour) assert.equal(3, plugin.config.minute) end end) it_content_types("should override a plugin's `config` if partial", function(content_type) return function() local response, status = http_client.put(PLUGIN_BASE_URL, { id = plugin.id, name = "key-auth", ["config.key_names"] = "api_key_updated", created_at = 1461276890000 }, {["content-type"] = content_type}) assert.equal(200, status) local body = json.decode(response) assert.same({"api_key_updated"}, body.config.key_names) assert.falsy(body.hide_credentials) end end) it_content_types("should be possible to disable and re-enable it", function(content_type) return function() local _, status = http_client.put(PLUGIN_BASE_URL, { id = plugin.id, name = "key-auth", enabled = false, ["config.key_names"] = "apikey,key", created_at = 1461276890000 }, {["content-type"] = content_type}) assert.equal(200, status) local response = http_client.get(PLUGIN_BASE_URL..plugin.id) local body = json.decode(response) assert.False(body.enabled) _, status = http_client.put(PLUGIN_BASE_URL, { id = plugin.id, name = "key-auth", enabled = true, ["config.key_names"] = "apikey,key", created_at = 1461276890000 }, {["content-type"] = content_type}) assert.equal(200, status) response = http_client.get(PLUGIN_BASE_URL..plugin.id) body = json.decode(response) assert.True(body.enabled) end end) describe("errors", function() it_content_types("should return proper validation errors", function(content_type) return function() local response, status = http_client.put(PLUGIN_BASE_URL, {}, {["content-type"] = content_type}) assert.equal(400, status) assert.equal([[{"name":"name is required"}]], stringy.strip(response)) end end) end) end) describe("GET", function() it("should retrieve the first page", function() local response, status = http_client.get(BASE_URL..api_with_plugin.id.."/plugins/") assert.equal(200, status) local body = json.decode(response) assert.truthy(body.data) assert.equal(1, #body.data) end) end) describe("/apis/:api/plugins/:plugin", function() local API_PLUGIN_BASE_URL before_each(function() API_PLUGIN_BASE_URL = BASE_URL..api_with_plugin.id.."/plugins/" end) describe("GET", function() it("should retrieve by id", function() local response, status = http_client.get(API_PLUGIN_BASE_URL..plugin.id) assert.equal(200, status) local body = json.decode(response) assert.same(plugin, body) end) it("[SUCCESS] should not retrieve a plugin that is not associated to the right API", function() local response, status = http_client.get(BASE_URL) assert.equal(200, status) local body = json.decode(response) assert.equal(2, body.total) local api_id_1 = body.data[1].id local api_id_2 = body.data[2].id local response, status = http_client.get(spec_helper.API_URL.."/plugins") assert.equal(200, status) local body = json.decode(response) local plugin_id = body.data[1].id local _, status = http_client.get(spec_helper.API_URL.."/apis/"..(body.data[1].api_id == api_id_1 and api_id_1 or api_id_2).."/plugins/"..plugin_id) assert.equal(200, status) -- Let's try to request it with the other API local _, status = http_client.get(spec_helper.API_URL.."/apis/"..(body.data[1].api_id == api_id_1 and api_id_2 or api_id_1).."/plugins/"..plugin_id) assert.equal(404, status) end) end) describe("PATCH", function() it_content_types("should update if exists", function(content_type) return function() local response, status = http_client.patch(API_PLUGIN_BASE_URL..plugin.id, { ["config.key_names"] = {"key_updated"} }, {["content-type"] = content_type}) assert.equal(200, status) local body = json.decode(response) assert.same("key_updated", body.config.key_names[1]) end end) it_content_types("should not override a plugin's `config` if partial", function(content_type) -- This is delicate since a plugin's `config` is a text field in a DB like Cassandra return function() assert.truthy(plugin.config) assert.True(plugin.config.hide_credentials) local response, status = http_client.patch(API_PLUGIN_BASE_URL..plugin.id, { ["config.key_names"] = {"key_set_null_test_updated"} }, {["content-type"] = content_type}) assert.equal(200, status) local body = json.decode(response) assert.same({"key_set_null_test_updated"}, body.config.key_names) assert.True(body.config.hide_credentials) end end) it_content_types("should be possible to disable and re-enable it", function(content_type) return function() local _, status = http_client.patch(API_PLUGIN_BASE_URL..plugin.id, { enabled = false }, {["content-type"] = content_type}) assert.equal(200, status) local plugin, err = dao_factory.plugins:find { id = plugin.id, name = plugin.name } assert.falsy(err) assert.False(plugin.enabled) _, status = http_client.patch(API_PLUGIN_BASE_URL..plugin.id, { enabled = true }, {["content-type"] = content_type}) assert.equal(200, status) plugin, err = dao_factory.plugins:find { id = plugin.id, name = plugin.name } assert.falsy(err) assert.True(plugin.enabled) end end) describe("errors", function() it_content_types("should return HTTP 404 if not found", function(content_type) return function() local _, status = http_client.patch(API_PLUGIN_BASE_URL.."b6cca0aa-4537-11e5-af97-23a06d98af51", {}, {["content-type"] = content_type}) assert.equal(404, status) end end) it_content_types("should return proper validation errors", function(content_type) return function() local response, status = http_client.patch(API_PLUGIN_BASE_URL..plugin.id, { name = "foo" }, {["content-type"] = content_type}) assert.equal(400, status) assert.equal([[{"config":"Plugin \"foo\" not found"}]], stringy.strip(response)) end end) end) end) describe("DELETE", function() it("should delete a plugin configuration", function() local response, status = http_client.delete(API_PLUGIN_BASE_URL..plugin.id) assert.equal(204, status) assert.falsy(response) end) describe("errors", function() it("should return HTTP 404 if not found", function() local _, status = http_client.delete(API_PLUGIN_BASE_URL.."b6cca0aa-4537-11e5-af97-23a06d98af51") assert.equal(404, status) end) end) end) end) end) end) end) end)
nilq/small-lua-stack
null
--------------------------------------------------------------------------------------------------- -- Proposal: https://github.com/smartdevicelink/sdl_evolution/blob/master/proposals/0178-GetInteriorVehicleData.md -- User story: TBD -- Use case: TBD -- -- Requirement summary: TBD -- -- Description: -- In case -- 1. In .ini file GetInteriorVehicleDataRequest = 3, 11 -- 2. Mobile app sends 3 GetInteriorVD(module_1, without subscribe parameter) requests per 8 sec -- 3. Mobile app starts sends a lot of requests before 1st success request processing -- SDL must -- 1. process successful 3 requests per 8 sec and send GetInteriorVD requests to HMI -- 2. rejects requests starting from 4th one -- 3. when time between received request and 1st success request is more then 11 sec process request successful and send GetInteriorVD requests to HMI --------------------------------------------------------------------------------------------------- --[[ Required Shared libraries ]] local runner = require('user_modules/script_runner') local common = require('test_scripts/RC/InteriorVehicleData_cache/common_interiorVDcache') local functionId = require('function_id') --[[ Test Configuration ]] runner.testSettings.isSelfIncluded = false -- [[ Local Variables]] local timestampArray = {} -- [[ Local Functions]] local function GetInteriorVehicleData(pModuleType, pRequestNubmer) local rpc = "GetInteriorVehicleData" local subscribe = nil local mobSession = common.getMobileSession(1) local cid = mobSession:SendRPC(common.getAppEventName(rpc), common.getAppRequestParams(rpc, pModuleType, subscribe)) local hmiRequestParams = common.getHMIRequestParams(rpc, pModuleType, 1, subscribe) timestampArray[pRequestNubmer] = timestamp() hmiRequestParams.subscribe = nil EXPECT_HMICALL(common.getHMIEventName(rpc), hmiRequestParams) :Do(function(_, data) local hmiResponseParams = common.getHMIResponseParams(rpc, pModuleType, subscribe) hmiResponseParams.subscribe = nil common.getHMIConnection():SendResponse(data.id, data.method, "SUCCESS", hmiResponseParams) end) :ValidIf(function(_, data) if data.params.subscribe then return false, "RC.GetInteriorVehicleData request contains unexpected 'subscribe' parameter" end return true end) mobSession:ExpectResponse(cid, common.getAppResponseParams(rpc, true, "SUCCESS", pModuleType, subscribe)) end local function GetInteriorVehicleDataRejectedSuccess(pModuleType, pCompareRequest) local rpc = "GetInteriorVehicleData" local subscribe = nil local mobSession = common.getMobileSession(1) local function request() mobSession:SendRPC(common.getAppEventName(rpc), common.getAppRequestParams(rpc, pModuleType, subscribe)) end request() local hmiRequestParams = common.getHMIRequestParams(rpc, pModuleType, 1, subscribe) hmiRequestParams.subscribe = nil EXPECT_HMICALL(common.getHMIEventName(rpc), hmiRequestParams) :Do(function(_, data) timestampArray[4] = timestamp() local hmiResponseParams = common.getHMIResponseParams(rpc, pModuleType, subscribe) hmiResponseParams.subscribe = nil common.getHMIConnection():SendResponse(data.id, data.method, "SUCCESS", hmiResponseParams) common.wait(2000) end) mobSession:ExpectAny() :ValidIf(function(_, data) if data.rpcFunctionId == functionId[rpc] then if data.payload.resultCode == "SUCCESS" then local timeToRequest = { [1] = timestampArray[4] - timestampArray[1], [2] = timestampArray[4] - timestampArray[2], [3] = timestampArray[4] - timestampArray[3] } if timeToRequest[pCompareRequest] >= 11000 and timeToRequest[pCompareRequest] < 11700 then return true else return false, "Time to first success request after " .. pCompareRequest .. " request is not 11 seconds.\n" .. "Actual result: time to first request " .. timeToRequest[1] .. "\n" .. "time to second request " .. timeToRequest[2] .. "\n" .. "time to third request " .. timeToRequest[3] .. "\n" end else RUN_AFTER(request, 100) end return true else return false, "Unexpected rpc " .. data.rpcFunctionId .. " came" end end) :Times(AnyNumber()) end --[[ Scenario ]] runner.Title("Preconditions") runner.Step("Clean environment", common.preconditions) runner.Step("Update GetInteriorVehicleDataRequest=3,11", common.setGetInteriorVehicleDataRequestValue, {"3,11"}) runner.Step("Start SDL, HMI, connect Mobile, start Session", common.start) runner.Step("Register app", common.registerAppWOPTU, { 1 }) runner.Step("Activate app", common.activateApp, { 1 }) runner.Title("Test") runner.Step("GetInteriorVehicleData without subscribe parameter " .. 1, GetInteriorVehicleData, {"CLIMATE", 1 }) runner.Step("Wait 5 secs", common.wait, { 5000 }) runner.Step("GetInteriorVehicleData without subscribe parameter " .. 2, GetInteriorVehicleData, {"CLIMATE", 2 }) runner.Step("Wait 3 secs", common.wait, { 3000 }) runner.Step("GetInteriorVehicleData without subscribe parameter " .. 3, GetInteriorVehicleData, {"CLIMATE", 3 }) runner.Step("GetInteriorVehicleData without subscribe parameter rejected before 11 seconds to 1st request", GetInteriorVehicleDataRejectedSuccess, { "CLIMATE", 1 }) runner.Step("GetInteriorVehicleData without subscribe parameter rejected before 11 seconds to 2st request", GetInteriorVehicleDataRejectedSuccess, { "CLIMATE", 2 }) runner.Title("Postconditions") runner.Step("Stop SDL", common.postconditions)
nilq/small-lua-stack
null
--addonName and namespace local addonName, ns = ... --container local core = CreateFrame("Frame") ns.core = core --------------------------------------------- -- FUNCTIONS --------------------------------------------- function core:CreateDropShadow(parent,edgeFile,edgeSize,padding) if parent.dropShadow then return end edgeFile = edgeFile or "" edgeSize = edgeSize or 8 padding = padding or 8 parent.dropShadow = CreateFrame("Frame", nil, parent) parent.dropShadow:SetPoint("TOPLEFT",-padding,padding) parent.dropShadow:SetPoint("BOTTOMRIGHT",padding,-padding) parent.dropShadow:SetBackdrop({ bgFile = nil, edgeFile = edgeFile, tile = false, tileSize = 16, edgeSize = edgeSize, insets = { left = 0, right = 0, top = 0, bottom = 0, }, }) local mt = getmetatable(parent).__index mt.SetDropShadowColor = function(self,r,g,b,a) self.dropShadow:SetBackdropBorderColor(r or 1, g or 1, b or 1, a or 1) end end --fontstring func function core:NewFontString(parent,family,size,outline,layer) local fs = parent:CreateFontString(nil, layer or "OVERLAY") fs:SetFont(family,size,outline) fs:SetShadowOffset(0, -2) fs:SetShadowColor(0,0,0,1) return fs end --------------------------------------------- -- TAGS --------------------------------------------- --unit name tag oUF.Tags.Methods["square_portrait:name"] = function(unit) local name = oUF.Tags.Methods["name"](unit) return "|cffffffff"..name.."|r" end oUF.Tags.Events["square_portrait:name"] = "UNIT_NAME_UPDATE UNIT_CONNECTION" --unit health tag oUF.Tags.Methods["square_portrait:health"] = function(unit) local perhp = oUF.Tags.Methods["perhp"](unit) return "|cffffffff"..perhp.."|r" end oUF.Tags.Events["square_portrait:health"] = "UNIT_HEALTH_FREQUENT UNIT_MAXHEALTH"
nilq/small-lua-stack
null
local PLAYER = FindMetaTable("Player") local ENTITY = FindMetaTable("Entity") --[[------------------------------------------------------------------------- Applying Buy functions - Run when the player attempts to use the entity ---------------------------------------------------------------------------]] --local nw_price = "nzu_UseCost" --local nw_text = "nzu_UseText" --local nw_elec = "nzu_UseElec" --[[ Structure of a Buy Function: - Price: The price. Can be 0 to be free, or negative to give points - Electricity: True if it requires electricity - Function: What to run when bought - Rebuy: True if the function should stay - False and the function disappears after use ]] --[[if SERVER then util.AddNetworkString("nzu_buyfunctions") function ENTITY:SetBuyFunction(data, nonetwork) self.nzu_BuyFunction = data data.NoNetwork = nonetwork if not nonetwork then self:SetNW2Int(nw_price, price) self:SetNW2Bool(nw_elec, elec) self:SetNW2String(nw_text, buytext) self.nzu_UseCostRebuy = rebuy end end function ENTITY:RemoveBuyFunction() if self.nzu_BuyFunction then self.nzu_BuyFunction = nil end end else -- Draw text for clients hook.Add("nzu_GetTargetIDText", "nzu_Doors_TargetID", function(ent) local price = ent:GetNW2Int(nw_price, nil) if price then local elec = ent:GetNW2Bool(nw_elec, false) if not elec then local str = ent:GetNW2String(nw_text, "") if price ~= 0 then return str, TARGETID_TYPE_USECOST, price else return str, TARGETID_TYPE_USE end else return "Requires Electricity", TARGETID_TYPE_ELECTRICITY end end end) end]] function ENTITY:GetBuyFunction() return self.nzu_BuyFunction end if SERVER then util.AddNetworkString("nzu_buyfunctions") -- Server: Broadcast an entity's buy function local networkedents = {} local function writebuyfunc(ent, data) net.WriteEntity(ent) net.WriteBool(true) net.WriteUInt(data.Price, 32) net.WriteBool(data.Electricity) net.WriteBool(data.Rebuyable) net.WriteUInt(data.TargetIDType or TARGETID_TYPE_USECOST, 4) net.WriteString(data.Text or "") end function ENTITY:SetBuyFunction(data, nonetwork) self.nzu_BuyFunction = data if not nonetwork then if data then -- Send data net.Start("nzu_buyfunctions") writebuyfunc(ent, data) net.Broadcast() networkedents[self] = true elseif networkedents[self] then -- Send removal only if previously networked net.Start("nzu_buyfunctions") net.WriteEntity(self) net.WriteBool(false) net.Broadcast() networkedents[self] = nil end else networkedents[self] = nil end end hook.Add("PlayerInitialSpawn", "nzu_PlayerUse_BuyFunctionSync", function(ply) for k,v in pairs(networkedents) do net.Start("nzu_buyfunctions") writebuyfunc(k, k.nzu_BuyFunction) net.Send(ply) end end) -- Allow blocking the entity function ENTITY:BlockUse(b) if b then self.nzu_UseBlocked = true else self.nzu_UseBlocked = nil end end else -- Clientside mirror, allows for shared creation (such as in Initialize) to save networking -- Or you can call this in your own client receiving if you can optimize networking (Door system does this) function ENTITY:SetBuyFunction(data) self.nzu_BuyFunction = data end local queue = {} local function applybuyfunc(index, data) local ent = Entity(index) if IsValid(ent) then ent.nzu_BuyFunction = data else queue[index] = data end end hook.Add("OnEntityCreated", "nzu_PlayerUse_BuyFunctionQueue", function(ent) if queue[ent:EntIndex()] then ent.nzu_BuyFunction = queue[ent:EntIndex()] queue[ent:EntIndex()] = nil end end) net.Receive("nzu_buyfunctions", function() local ent = net.ReadUInt(16) if net.ReadBool() then local tbl = {} tbl.Price = net.ReadUInt(32) if net.ReadBool() then tbl.Electricity = true end if net.ReadBool() then tbl.Rebuyable = true end tbl.TargetIDType = net.ReadUInt(4) tbl.Text = net.ReadString() if tbl.TargetIDType == 0 then tbl.TargetIDType = nil tbl.Text = nil end applybuyfunc(ent, tbl) hook.Run("nzu_BuyFunctionSet", ent, tbl) else applybuyfunc(ent, nil) hook.Run("nzu_BuyFunctionRemoved", ent) end end) -- Draw text for the buy function hook.Add("nzu_GetTargetIDText", "nzu_PlayerUse_TargetID", function(ent) local data = ent:GetBuyFunction() if data and data.TargetIDType then if data.Electricity and not ent:HasElectricity() then return translate.Get("requires_electricity"), TARGETID_TYPE_ELECTRICITY end return data.Text, data.TargetIDType, data.Price end end) end --[[------------------------------------------------------------------------- Player Use handling ---------------------------------------------------------------------------]] if SERVER then function ENTITY:UseCooldown(num) self.nzu_UseCooldown = CurTime() + num end local usecooldown = 0.1 -- We prevent using here. Another hook can easily block this though, but we do this to optimize saving a trace hook.Add("FindUseEntity", "nzu_PlayerUse_PreventDownedUse", function(ply, ent) if ply:GetIsDowned() then return NULL end end) -- Call new hooks when the player starts/stops using, or switches use target function GM:PlayerUse(ply, ent) if ply:GetIsDowned() then if ply.nzu_UseTarget then local ent2 = ply.nzu_UseTarget hook.Run("nzu_PlayerStopUse", ply, ent2) ply.nzu_UseTarget = nil ply.nzu_UseCooldown = CurTime() + usecooldown end return false -- Even if another hook should return another entity, prevent use end if ply.nzu_UseCooldown and ply.nzu_UseCooldown > CurTime() then return false end if ent.nzu_UseBlocked then return false end local ent2 = ply.nzu_UseTarget if ent2 ~= ent then ply.nzu_UseTarget = ent if IsValid(ent2) then hook.Run("nzu_PlayerStopUse", ply, ent2) end if IsValid(ent) and (not ent.nzu_UseCooldown or ent.nzu_UseCooldown < CurTime()) then hook.Run("nzu_PlayerStartUse", ply, ent) -- Buy functions! local data = ent:GetBuyFunction() if data then -- Can't use entities that require electricity it doesn't have! -- Allow use however if the FailFunction exists and returns true if data.Electricity and not ent:HasElectricity() then return data.FailFunction and data.FailFunction(ply, ent) or false end -- Free buy functions don't go through Buy - We don't want sounds if data.Price == 0 then local b = data.Function(ply, ent) -- Get the return of the function that would've been bought if b ~= false then -- If it didn't return false, it succeeded if not data.Rebuyable then ent:SetBuyFunction(nil) end -- Return only if the function explicitly returned something. Otherwise false (blocks use) return b ~= nil and b end -- Otherwise allowing use only if the FailFunction exists and returns true return data.FailFunction and data.FailFunction(ply, ent) or false else -- It has a cost, so we want to buy! local success,ret = ply:Buy(data.Price, data.Function, ent) if success then -- If the purchase was successful if not data.Rebuyable then ent:SetBuyFunction(nil) end -- Remove buy function from non-rebuyables -- Return only if the result is not explicitly nil return ret ~= nil and ret end -- Otherwise, same as before: Let fail function determine outcome return data.FailFunction and data.FailFunction(ply, ent) or false end end end else hook.Run("nzu_PlayerUse", ply, ent) end return true end -- Also stop for E hook.Add("KeyRelease", "nzu_PlayerUse_StopHoldingE", function(ply, key) if key == IN_USE and IsValid(ply.nzu_UseTarget) then local ent = ply.nzu_UseTarget ply.nzu_UseTarget = nil ply.nzu_UseCooldown = CurTime() + usecooldown hook.Run("nzu_PlayerStopUse", ply, ent) end end) end --[[------------------------------------------------------------------------- Player Buy shortcut function ---------------------------------------------------------------------------]] local buysound = Sound("nzu/purchase/accept.wav") local denysound = Sound("nzu/purchase/deny.wav") function PLAYER:Buy(cost, func, args) if self:CanAfford(cost) then local b = func and func(self, args) -- If the function returns false, it blocked the purchase if b ~= false then self:TakePoints(cost) self:EmitSound(buysound) return true, b end end self:EmitSound(denysound) return false end
nilq/small-lua-stack
null
print("nested long string [[support in Lua 5.1 [[ is ]] controlled by ]] LUA_COMPAT_LSTR\nnewlines\nare\nneeded\nto\ntrip\nthe\nunluac\nlong string\nheuristic")
nilq/small-lua-stack
null
#! /usr/bin/lua require 'Test.More' if not pcall(require, 'bc') then skip_all 'no bc' end plan(3) local c = require 'CBOR' local bc = require 'bc' local TAG_BC = 42 bc.digits(65) local number = bc.number or bc.new c.coders.userdata = function (buffer, u) if getmetatable(u) == bc then c.coders.tag(buffer, TAG_BC) c.coders.text_string(buffer, tostring(u)) else error("encode 'userdata' is unimplemented") end end c.register_tag(TAG_BC, function (data) return number(data) end) local orig = bc.sqrt(2) local dest = c.decode(c.encode(orig)) is( dest, orig, "bc" ) nok( rawequal(orig, dest) ) error_like( function () c.encode( io.stdin ) end, "encode 'userdata' is unimplemented" )
nilq/small-lua-stack
null
-- Arithmetic on the Finite Field of Integers modulo q -- Where q is the generator's subgroup order. local util = require(script.Parent.util) local sha256 = require(script.Parent.sha256) local random = require(script.Parent.random) local arith = require(script.Parent.arith) local isEqual = arith.isEqual local compare = arith.compare local add = arith.add local sub = arith.sub local addDouble = arith.addDouble local mult = arith.mult local square = arith.square local encodeInt = arith.encodeInt local decodeInt = arith.decodeInt local modQMT local q = { 9622359, 6699217, 13940450, 16775734, 16777215, 16777215, 3940351 } -- this isn't an optimization, it just shortens the amount of time I have to scroll local qMinusTwoBinary = table.create(166, 1) qMinusTwoBinary[2] = 0 qMinusTwoBinary[4] = 0 qMinusTwoBinary[6] = 0 qMinusTwoBinary[8] = 0 qMinusTwoBinary[11] = 0 qMinusTwoBinary[12] = 0 qMinusTwoBinary[14] = 0 qMinusTwoBinary[17] = 0 qMinusTwoBinary[19] = 0 qMinusTwoBinary[20] = 0 qMinusTwoBinary[22] = 0 qMinusTwoBinary[23] = 0 qMinusTwoBinary[26] = 0 qMinusTwoBinary[27] = 0 qMinusTwoBinary[28] = 0 qMinusTwoBinary[30] = 0 qMinusTwoBinary[33] = 0 qMinusTwoBinary[34] = 0 qMinusTwoBinary[35] = 0 qMinusTwoBinary[39] = 0 qMinusTwoBinary[40] = 0 qMinusTwoBinary[41] = 0 qMinusTwoBinary[44] = 0 qMinusTwoBinary[45] = 0 qMinusTwoBinary[48] = 0 qMinusTwoBinary[49] = 0 qMinusTwoBinary[51] = 0 qMinusTwoBinary[52] = 0 qMinusTwoBinary[53] = 0 qMinusTwoBinary[57] = 0 qMinusTwoBinary[60] = 0 qMinusTwoBinary[63] = 0 qMinusTwoBinary[65] = 0 qMinusTwoBinary[66] = 0 qMinusTwoBinary[68] = 0 qMinusTwoBinary[70] = 0 qMinusTwoBinary[73] = 0 qMinusTwoBinary[76] = 0 qMinusTwoBinary[79] = 0 qMinusTwoBinary[80] = 0 qMinusTwoBinary[81] = 0 qMinusTwoBinary[83] = 0 qMinusTwoBinary[158] = 0 qMinusTwoBinary[159] = 0 qMinusTwoBinary[160] = 0 qMinusTwoBinary[161] = 0 qMinusTwoBinary[162] = 0 -- We're using the Montgomery Reduction for fast modular multiplication. -- https://en.wikipedia.org/wiki/Montgomery_modular_multiplication -- r = 2^168 -- q * qInverse = -1 (mod r) -- r2 = r * r (mod q) local qInverse = { 15218585, 5740955, 3271338, 9903997, 9067368, 7173545, 6988392 } local r2 = { 1336213, 11071705, 9716828, 11083885, 9188643, 1494868, 3306114 } -- Reduces a number from [0, 2q - 1] to [0, q - 1] local function reduceModQ(a) local result = { table.unpack(a) } if compare(result, q) >= 0 then result = sub(result, q) end return setmetatable(result, modQMT) end local function addModQ(a, b) return reduceModQ(add(a, b)) end local function subModQ(a, b) local result = sub(a, b) if result[7] < 0 then result = add(result, q) end return setmetatable(result, modQMT) end -- Montgomery REDC algorithn -- Reduces a number from [0, q^2 - 1] to [0, q - 1] local function REDC(T) local m = { table.unpack(mult({ table.unpack(T, 1, 7) }, qInverse, true), 1, 7) } local t = { table.unpack(addDouble(T, mult(m, q)), 8, 14) } return reduceModQ(t) end local function multModQ(a, b) -- Only works with a, b in Montgomery form return REDC(mult(a, b)) end local function squareModQ(a) -- Only works with a in Montgomery form return REDC(square(a)) end local function montgomeryModQ(a) return multModQ(a, r2) end local function inverseMontgomeryModQ(a) local newA = { table.unpack(a) } for i = 8, 14 do newA[i] = 0 end return REDC(newA) end local ONE = montgomeryModQ({ 1, 0, 0, 0, 0, 0, 0 }) local function expModQ(base, exponentBinary) local newBase = { table.unpack(base) } local result = { table.unpack(ONE) } for i = 1, 168 do if exponentBinary[i] == 1 then result = multModQ(result, newBase) end newBase = squareModQ(newBase) end return result end local function intExpModQ(base, exponent) local newBase = { table.unpack(base) } local result = setmetatable({ table.unpack(ONE) }, modQMT) if exponent < 0 then newBase = expModQ(newBase, qMinusTwoBinary) exponent = -exponent end while exponent > 0 do if exponent % 2 == 1 then result = multModQ(result, newBase) end newBase = squareModQ(newBase) exponent = math.floor(exponent / 2) end return result end local function encodeModQ(a) local result = encodeInt(a) return setmetatable(result, util.byteTableMT) end local function decodeModQ(s) s = type(s) == "table" and { table.unpack(s, 1, 21) } or { string.byte(tostring(s), 1, 21) } local result = decodeInt(s) result[7] %= q[7] return setmetatable(result, modQMT) end local function randomModQ() while true do local s = { table.unpack(random.random(), 1, 21) } local result = decodeInt(s) if result[7] < q[7] then return setmetatable(result, modQMT) end end end local function hashModQ(data) return decodeModQ(sha256.digest(data)) end modQMT = { __index = { encode = function(self) return encodeModQ(self) end, }, __tostring = function(self) return self:encode():toHex() end, __add = function(self, other) if type(self) == "number" then return other + self end if type(other) == "number" then assert(other < 16777216, "number operand too big") other = montgomeryModQ({ other, 0, 0, 0, 0, 0, 0 }) end return addModQ(self, other) end, __sub = function(a, b) if type(a) == "number" then assert(a < 16777216, "number operand too big") a = montgomeryModQ({ a, 0, 0, 0, 0, 0, 0 }) end if type(b) == "number" then assert(b < 16777216, "number operand too big") b = montgomeryModQ({ b, 0, 0, 0, 0, 0, 0 }) end return subModQ(a, b) end, __unm = function(self) return subModQ(q, self) end, __eq = function(self, other) return isEqual(self, other) end, __mul = function(self, other) if type(self) == "number" then return other * self end -- EC point -- Use the point's metatable to handle multiplication if type(other) == "table" and type(other[1]) == "table" then return other * self end if type(other) == "number" then assert(other < 16777216, "number operand too big") other = montgomeryModQ({ other, 0, 0, 0, 0, 0, 0 }) end return multModQ(self, other) end, __div = function(a, b) if type(a) == "number" then assert(a < 16777216, "number operand too big") a = montgomeryModQ({ a, 0, 0, 0, 0, 0, 0 }) end if type(b) == "number" then assert(b < 16777216, "number operand too big") b = montgomeryModQ({ b, 0, 0, 0, 0, 0, 0 }) end local bInv = expModQ(b, qMinusTwoBinary) return multModQ(a, bInv) end, __pow = function(self, other) return intExpModQ(self, other) end, } return { hashModQ = hashModQ, randomModQ = randomModQ, decodeModQ = decodeModQ, inverseMontgomeryModQ = inverseMontgomeryModQ, }
nilq/small-lua-stack
null
local function GetPhrase(str, default) return language.GetPhrase(str) == str and default or language.GetPhrase(str) end hook.Add("AddToolMenuCategories", "DFHUDAdd", function() spawnmenu.AddToolCategory("Options", "DefaultHUDMenu", "Default HUD+") end) hook.Add("PopulateToolMenu", "DFHUDPopulate", function() // Наполняем менюшку spawnmenu.AddToolMenuOption("Options", "DefaultHUDMenu", "DFHUDOptions", GetPhrase("dfhud.options", "Options"), "", "", function(panel) panel:ClearControls() panel:Help(GetPhrase("dfhud.help", "This is Default HUD+ options!")) panel:CheckBox(GetPhrase("dfhud.enable", "Enable DefaultHUD+?"), "dfhud_enable") panel:CheckBox(GetPhrase("dfhud.3d", "Enable 3D mode?"), "dfhud_3d") panel:CheckBox(GetPhrase("dfhud.proceduralicons", "Enable procedural icons?"), "dfhud_procedural_icons") panel:CheckBox(GetPhrase("dfhud.proceduralicons.style", "Procedural icons style"), "dfhud_procedural_icons_style") panel:CheckBox(GetPhrase("dfhud.blur", "Enable blur"), "dfhud_blur") panel:NumSlider(GetPhrase("dfhud.blur.power", "Blur power"), "dfhud_blur_power", 1, 15, false) panel:ControlHelp(GetPhrase("dfhud.fpswarn", "Blur can cause performance issues.")) local picker = vgui.Create("DColorMixer") picker:SetLabel(GetPhrase("dfhud.help2", "DefaultHUD+ color")) picker:SetAlphaBar(false) picker:SetConVarR "dfhud_color_r" picker:SetConVarG "dfhud_color_g" picker:SetConVarB "dfhud_color_b" local picker2 = vgui.Create("DColorMixer") picker2:SetAlphaBar(true) picker2:SetPalette(false) picker2:SetLabel(GetPhrase("dfhud.help2", "another DefaultHUD+ box color")) picker2:SetConVarA "dfhud_box_color_a" picker2:SetConVarR "dfhud_box_color_r" picker2:SetConVarG "dfhud_box_color_g" picker2:SetConVarB "dfhud_box_color_b" panel:AddItem(picker) panel:AddItem(picker2) end) end)
nilq/small-lua-stack
null
--[[ Copyright (c) 2013 Aerys 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. ]]-- -- sdl plugin minko.plugin.sdl = {} function minko.plugin.sdl:enable() defines { "MINKO_PLUGIN_SDL" } minko.plugin.links { "sdl" } includedirs { minko.plugin.path("sdl") .. "/include", minko.plugin.path("sdl") .. "/lib/sdl/include", } configuration { "windows32", "ConsoleApp or WindowedApp" } links { "SDL2", "SDL2main", "SDL2_mixer" } libdirs { minko.plugin.path("sdl") .. "/lib/sdl/lib/windows32" } prelinkcommands { minko.action.copy(minko.plugin.path("sdl") .. "/lib/sdl/lib/windows32/*.dll") } configuration { "windows64", "ConsoleApp or WindowedApp" } links { "SDL2", "SDL2main", "SDL2_mixer" } libdirs { minko.plugin.path("sdl") .. "/lib/sdl/lib/windows64" } prelinkcommands { minko.action.copy(minko.plugin.path("sdl") .. "/lib/sdl/lib/windows64/*.dll") } configuration { "linux32", "ConsoleApp or WindowedApp" } links { "SDL2" } configuration { "linux64", "ConsoleApp or WindowedApp" } links { "SDL2" } configuration { "osx64", "ConsoleApp or WindowedApp" } links { "SDL2", -- "CoreFoundation.framework", "Carbon.framework", -- "AudioToolbox.framework", "AudioUnit.framework", "CoreAudio.framework", "ForceFeedback.framework" } libdirs { minko.plugin.path("sdl") .. "/lib/sdl/lib/osx64" } configuration { "ios", "ConsoleApp or WindowedApp" } links { "SDL2", "SDL2_mixer", "CoreAudio.framework", "AudioToolbox.framework" } libdirs { minko.plugin.path("sdl") .. "/lib/sdl/lib/ios" } configuration { "html5", "ConsoleApp or WindowedApp" } removeincludedirs { minko.plugin.path("sdl") .. "/lib/sdl/include" } includedirs { "SDL" } configuration { "android" } links { "SDL2", "SDL2_mixer" } libdirs { minko.plugin.path("sdl") .. "/lib/sdl/lib/android" } includedirs { minko.plugin.path("sdl") .. "/lib/sdl/src/core/android" } configuration { "ConsoleApp or WindowedApp" } if minko.plugin.requested("offscreen") then minko.plugin.enable { "offscreen" } end end function minko.plugin.sdl:dist(pluginDistDir) configuration { "windows32" } os.mkdir(pluginDistDir .. "/lib/sdl/lib/windows32") minko.os.copyfiles(minko.plugin.path("sdl") .. "/lib/sdl/lib/windows32", pluginDistDir .. "/lib/sdl/lib/windows32") configuration { "windows64" } os.mkdir(pluginDistDir .. "/lib/sdl/lib/windows64/lib") minko.os.copyfiles(minko.plugin.path("sdl") .. "/lib/sdl/lib/windows64", pluginDistDir .. "/lib/sdl/lib/windows64") end
nilq/small-lua-stack
null
---------------------------- --版权: --作者: liubo ([email protected]) --时间: 2016-05-31 17:55:15 --作用: 对话框 --备注: ---------------------------- cc.exports.Dialog = {} local dialog = nil local sheildLayer = nil local dialogTag = 10 local sheildLayerTag = 11 --[[ 弹出通用对话框,最多能有两个按钮, params context: 提示的文字 params text1, text2: 按钮上的文字,可以为nil params callback: 点击按钮的回调函数,会传入所点击按钮的index(1或2),可以为nil ]] function Dialog.show(context, text1, text2, callback) -- 如果原来已出现弹框,则先消失弹窗 Dialog.dismiss() local runningScene = cc.Director:getInstance():getRunningScene() --屏蔽层 Dialog.createSheildLayer() --背景 dialog = display.newSprite("dialog/dialog.png") dialog:setPosition(display.center) dialog:addTo(runningScene, 1000) dialog:setTag(dialogTag) --内容信息 local msgLabel = cc.Label:createWithSystemFont(context, "Marker Felt.ttf", 50) msgLabel:setPosition(cc.p(dialog:getContentSize().width / 2, dialog:getContentSize().height * 0.6)) msgLabel:setTextColor(cc.c4b(82, 45, 13, 255)) msgLabel:addTo(dialog) --按钮 --如果text1 为空 text2 不为空 text1 = text2, text2 = nil --如果text1为空 text2 为空 text1 = 确定 text1 = text1 == nil and (text2 == nil and "确定" or text2) or text1 text2 = text2 == text1 and nil or text2 if not text2 then --说明只有一按钮 local btn = Dialog.createButton("dialog/dialogBtn.png", text1, function() if callback then callback() end Dialog.dismiss() end) btn:addTo(dialog) btn:setAnchorPoint(cc.p(0.5, 0)) btn:setPosition(cc.p(dialog:getContentSize().width / 2, dialog:getContentSize().height * 0.1)) else if text1 then local btn = Dialog.createButton("dialog/dialogBtn.png", text1, function() Dialog.dismiss() if callback then callback(1) end end) btn:addTo(dialog) btn:setAnchorPoint(cc.p(0, 0)) btn:setPosition(cc.p(dialog:getContentSize().width * 0.1, dialog:getContentSize().height * 0.1)) end if text2 then local btn = Dialog.createButton("dialog/dialogBtn.png", text2, function() Dialog.dismiss() if callback then callback(2) end end) btn:addTo(dialog) btn:setAnchorPoint(cc.p(1, 0)) btn:setPosition(cc.p(dialog:getContentSize().width * 0.9, dialog:getContentSize().height * 0.1)) end end end function Dialog.dismiss() local runningScene = cc.Director:getInstance():getRunningScene() if runningScene:getChildByTag(dialogTag) then dialog:removeSelf() end if runningScene:getChildByTag(sheildLayerTag) then sheildLayer:removeSelf() end end --屏蔽底层按钮 function Dialog.createSheildLayer() local runningScene = cc.Director:getInstance():getRunningScene() sheildLayer = require("utils.MarkLayer").new() sheildLayer:addTo(runningScene, 1000) sheildLayer:setTag(sheildLayerTag) end function Dialog.createButton(img, text, callFunc) local btn = ccui.Button:create() btn:addTouchEventListener(callFunc) if text then btn:setTitleText(text) btn:setTitleColor(cc.c3b(254, 211, 145)) btn:setTitleFontSize(40) end if img then btn:loadTextureNormal(img) end return btn end return Dialog
nilq/small-lua-stack
null
local xx = 325; local yy = 455; local xx2 = 942; local yy2 = 520; local ofs = 25; local followchars = true; function onCreate() -- background shit makeLuaSprite('Ponyville', 'pinkie/bg', -700, -385); scaleObject('Ponyville', 1.2, 1.2); makeAnimatedLuaSprite('PonyBG','pinkie/ponybg',-320, 340)addAnimationByPrefix('PonyBG','dance','ponybg_polka',5,true) objectPlayAnimation('PonyBG','dance',false) scaleObject('PonyBG', 1.1, 1.1); makeLuaSprite('shadow', 'pinkie/shadow', -10, 759); scaleObject('shadow', 1.075, 1.075); addLuaSprite('Ponyville', false); addLuaSprite('PonyBG', false); addLuaSprite('shadow', false); end function onUpdate() if followchars == true then if mustHitSection == false then if getProperty('dad.animation.curAnim.name') == 'singLEFT' then triggerEvent('Camera Follow Pos',xx-ofs,yy) end if getProperty('dad.animation.curAnim.name') == 'singRIGHT' then triggerEvent('Camera Follow Pos',xx+ofs,yy) end if getProperty('dad.animation.curAnim.name') == 'singUP' then triggerEvent('Camera Follow Pos',xx,yy-ofs) end if getProperty('dad.animation.curAnim.name') == 'singDOWN' then triggerEvent('Camera Follow Pos',xx,yy+ofs) end if getProperty('dad.animation.curAnim.name') == 'singLEFT-alt' then triggerEvent('Camera Follow Pos',xx-ofs,yy) end if getProperty('dad.animation.curAnim.name') == 'singRIGHT-alt' then triggerEvent('Camera Follow Pos',xx+ofs,yy) end if getProperty('dad.animation.curAnim.name') == 'singUP-alt' then triggerEvent('Camera Follow Pos',xx,yy-ofs) end if getProperty('dad.animation.curAnim.name') == 'singDOWN-alt' then triggerEvent('Camera Follow Pos',xx,yy+ofs) end if getProperty('dad.animation.curAnim.name') == 'idle-alt' then triggerEvent('Camera Follow Pos',xx,yy) end if getProperty('dad.animation.curAnim.name') == 'idle' then triggerEvent('Camera Follow Pos',xx,yy) end else if getProperty('boyfriend.animation.curAnim.name') == 'singLEFT' then triggerEvent('Camera Follow Pos',xx2-ofs,yy2) end if getProperty('boyfriend.animation.curAnim.name') == 'singRIGHT' then triggerEvent('Camera Follow Pos',xx2+ofs,yy2) end if getProperty('boyfriend.animation.curAnim.name') == 'singUP' then triggerEvent('Camera Follow Pos',xx2,yy2-ofs) end if getProperty('boyfriend.animation.curAnim.name') == 'singDOWN' then triggerEvent('Camera Follow Pos',xx2,yy2+ofs) end if getProperty('boyfriend.animation.curAnim.name') == 'idle-alt' then triggerEvent('Camera Follow Pos',xx2,yy2) end if getProperty('boyfriend.animation.curAnim.name') == 'idle' then triggerEvent('Camera Follow Pos',xx2,yy2) end end else triggerEvent('Camera Follow Pos','','') end setProperty('timeTxt.visible', false); setProperty('timeBar.visible', false); setProperty('timeBarBG.visible', false); setProperty('grpNoteSplashes.visible', false); end
nilq/small-lua-stack
null
local StatusWindow = { OnGetWindowName = function (self) return "OpenUI.StatusWindow."..OpenCore.Player:GetId() end, OnGetTemplate = function (self) return "OpenUI.StatusWindow" end, OnInitialize = function (self) OpenCore.Window:RestorePosition() local player = OpenCore.Player local paperdoll = OpenCore.Paperdoll:Get(player:GetId()) local texture = paperdoll:GetTextureName() local textureData = paperdoll:GetTextureData() local x, y, scale if textureData.IsLegacy == 1 then x, y = -88, 10 scale = 1.75 else x, y = -11, -191 scale = 0.75 end WindowSetTintColor(self.Name..".PortraitBackground", 0, 0, 0) CircleImageSetTexture(self.Name..".Portrait", texture, x - textureData.xOffset, y - textureData.yOffset) --CircleImageSetTextureScale(self.Name..".Portrait", OpenCore:GetScale() * scale) player:AddStatusListener(self.Name, function () self:UpdateStatus() end) self:UpdateStatus() end, OnShutdown = function (self) OpenCore.Window:SavePosition() OpenCore.Player:RemoveStatusListener(self.Name, function () self:UpdateStatus() end) end, UpdateStatus = function (self) local player = OpenCore.Player StatusBarSetMaximumValue(self.Name..".HealthBar", player:GetMaxHealth()) StatusBarSetCurrentValue(self.Name..".HealthBar", player:GetHealth()) StatusBarSetMaximumValue(self.Name..".ManaBar", player:GetMaxMana()) StatusBarSetCurrentValue(self.Name..".ManaBar", player:GetMana()) StatusBarSetMaximumValue(self.Name..".StaminaBar", player:GetMaxStamina()) StatusBarSetCurrentValue(self.Name..".StaminaBar", player:GetStamina()) if player:IsPoisoned() then WindowSetTintColor(self.Name..".HealthBar", 0, 255, 0) elseif player:IsCursed() then WindowSetTintColor(self.Name..".HealthBar", 255, 255, 0) else WindowSetTintColor(self.Name..".HealthBar", 255, 0, 0) end end } StatusWindow.__index = StatusWindow OpenUI.StatusWindow = StatusWindow
nilq/small-lua-stack
null
object_draft_schematic_space_reactor_mining_grade_reactor = object_draft_schematic_space_reactor_shared_mining_grade_reactor:new { } ObjectTemplates:addTemplate(object_draft_schematic_space_reactor_mining_grade_reactor, "object/draft_schematic/space/reactor/mining_grade_reactor.iff")
nilq/small-lua-stack
null
--[[ This Roact component represents our entire game. ]] local ReplicatedStorage = game:GetService('ReplicatedStorage') local Modules = ReplicatedStorage:WaitForChild('Modules') local logger = require(Modules.src.utils.Logger) local clientSrc = game:GetService('StarterPlayer'):WaitForChild('StarterPlayerScripts').clientSrc local Workspace = game:GetService('Workspace') local M = require(Modules.M) local InventoryObjects = require(Modules.src.objects.InventoryObjects) local RoomObjects = InventoryObjects.RoomObjects local Roact = require(Modules.Roact) local RoactMaterial = require(Modules.RoactMaterial) local createElement = Roact.createElement local getApiFromComponent = require(clientSrc.getApiFromComponent) local InventoryAndShopButtons = require(clientSrc.Components.InventoryAndShopButtons) local FinishScreen = require(clientSrc.Components.FinishScreen) local Notifications = require(clientSrc.Components.common.Notifications) local ClockScreen = require(clientSrc.Components.ClockScreen) local Room = require(clientSrc.Components.Room) local LeaderboardsConnect = require(clientSrc.Components.LeaderboardsConnect) local Game = Roact.PureComponent:extend('Game') function Game:init(props) self.api = getApiFromComponent(self) end function Game:render(props) local children = {} function createRoom(roomObject) children[roomObject.name] = createElement( Roact.Portal, { target = Workspace }, { ['Room' .. roomObject.name] = createElement(Room, { roomId = roomObject.id }) } ) end M.each(RoomObjects, createRoom) children['InventoryContainer'] = createElement( 'Frame', { Size = UDim2.new(1, 0, 1, 0), BackgroundTransparency = 1, BorderSizePixel = 5, BorderMode = Enum.BorderMode.Inset, ZIndex = 2, }, { Inventory = createElement(InventoryAndShopButtons) } ) children['ClockScreenContainer'] = createElement( 'Frame', { Position = UDim2.new(0.5, 0, 0, -30), AnchorPoint = Vector2.new(0.5, 0), BackgroundTransparency = 1, }, { Clock = createElement(ClockScreen) } ) children['FinishScreenContainer'] = createElement( 'Frame', { Size = UDim2.new(0.8, 0, 0.6, 0), Position = UDim2.new(0.5, 0, 0.5, 0), AnchorPoint = Vector2.new(0.5, 0.5), BackgroundTransparency = 1, }, { Finish = createElement(FinishScreen) } ) children['NotificationsContainer'] = createElement(Notifications) children['LeaderboardsContainer'] = createElement( Roact.Portal, { target = Workspace }, { Leaderboards = createElement(LeaderboardsConnect) } ) return Roact.createElement( RoactMaterial.ThemeProvider, { Theme = RoactMaterial.Themes.Light }, { createElement( 'ScreenGui', { ZIndexBehavior = Enum.ZIndexBehavior.Sibling, ResetOnSpawn = false, }, children ) } ) end return Game
nilq/small-lua-stack
null
fio = require('fio') xlog = require('xlog').pairs env = require('test_run') test_run = env.new() test_run:cmd("setopt delimiter ';'") function read_xlog(file) local val = {} for k, v in xlog(file) do table.insert(val, setmetatable(v, { __serialize = "map"})) end return val end; test_run:cmd("setopt delimiter ''"); -- gh-2798 check for journal transaction encoding _ = box.schema.space.create('test'):create_index('pk') -- generate a new xlog box.snapshot() lsn = box.info.lsn -- autocommit transaction box.space.test:replace({1}) -- one row transaction box.begin() box.space.test:replace({2}) box.commit() -- two row transaction box.begin() for i = 3, 4 do box.space.test:replace({i}) end box.commit() -- four row transaction box.begin() for i = 5, 8 do box.space.test:replace({i}) end box.commit() -- open a new xlog box.snapshot() -- read a previous one lsn_str = tostring(lsn) data = read_xlog(fio.pathjoin(box.cfg.wal_dir, string.rep('0', 20 - #lsn_str) .. tostring(lsn_str) .. '.xlog')) -- check nothing changed for single row transactions data[1].HEADER.tsn == nil and data[1].HEADER.commit == nil data[2].HEADER.tsn == nil and data[2].HEADER.commit == nil -- check two row transaction data[3].HEADER.tsn == data[3].HEADER.lsn and data[3].HEADER.commit == nil data[4].HEADER.tsn == data[3].HEADER.tsn and data[4].HEADER.commit == true -- check four row transaction data[5].HEADER.tsn == data[5].HEADER.lsn and data[5].HEADER.commit == nil data[6].HEADER.tsn == data[5].HEADER.tsn and data[6].HEADER.commit == nil data[7].HEADER.tsn == data[5].HEADER.tsn and data[7].HEADER.commit == nil data[8].HEADER.tsn == data[5].HEADER.tsn and data[8].HEADER.commit == true box.space.test:drop()
nilq/small-lua-stack
null
--[[ speechBubble.lua Copyright (C) 2016 Kano Computing Ltd. License: http://www.gnu.org/licenses/gpl-2.0.txt GNU GPLv2 ]]-- local Colour = require 'system.colour' local Typewriter = require 'system.typewriter' local love = love local g = love.graphics local SpeechBubble = {} SpeechBubble.__index = SpeechBubble -- constants local STATE_INACTIVE = 1 local STATE_ACTIVE = 2 local STATE_CLOSING = 3 function SpeechBubble.create(objectManager) -- print("CREATING Speech Bubble") -- DEBUG_TAG local self = setmetatable({}, SpeechBubble) self.objectManager = objectManager self.state = STATE_INACTIVE self.closeTime = 0 self.typewriter = Typewriter.create() self.autoclose = false return self end function SpeechBubble:update(dt) if self.state == STATE_ACTIVE then self.typewriter:update(dt) if self.typewriter:complete() then self:deactivate() end elseif self.state == STATE_CLOSING then if (love.timer.getTime() - self.closeTime) > 2 then self.state = STATE_INACTIVE self.objectManager:deactivate("bubble") end end end function SpeechBubble:draw() -- Bubble Colour.set(Colour.GREY_DARK) g.rectangle("fill", self.x, self.y, self.width, self.height, 2, 2, 10) g.polygon("fill", self.x, self.y, self.x - 10, self.y + 20, self.x + 20, self.y) -- Text self.typewriter:draw() -- resetting graphics Colour.reset() end function SpeechBubble:activate(x, y, text, autoclose) -- Only activate if inactive if not self:isActive() then self.state = STATE_ACTIVE self.x = x + 30 self.y = y - 20 self:calculateSize(text) self.typewriter:init(text, self.x, self.y, 0.05, g_resMngr.DEFAULT_FONT_16) self.autoclose = autoclose end end function SpeechBubble:deactivate() if self.autoclose then self.state = STATE_CLOSING self.closeTime = love.timer.getTime() else self.state = STATE_INACTIVE end end function SpeechBubble:isActive() return self.state ~= STATE_INACTIVE end -- Calculates the size of the bubble based on the text function SpeechBubble:calculateSize(text) local lines = {} local numLines = 1 local maxLength = 0 -- look for \n for str in text:gmatch("[^\n]+") do lines[numLines] = str numLines = numLines + 1 if #str > maxLength then maxLength = #str end end -- These multipliers should depend on font size self.width = maxLength * 5 self.height = numLines * 10 end return SpeechBubble
nilq/small-lua-stack
null
local StringJoinTests = test.declare('StringJoinTests', 'string') function StringJoinTests.join_returnsNil_onNilInput() test.isNil(string.join(' ')) end function StringJoinTests.join_returnsSameValue_onSingleValue() test.isEqual('A', string.join(' ', 'A')) end function StringJoinTests.join_returnsJoinedValues_onMultipleValues() test.isEqual('A B C', string.join(' ', 'A', 'B', 'C')) end function StringJoinTests.join_skipsNilValues() test.isEqual('A C', string.join(' ', 'A', nil, 'C')) end
nilq/small-lua-stack
null
local runtime,exports = ... local bON = dofile("deps/bon.lua") function exports.serialize(data) return bON.serialize(data) end function exports.deserialize(data) return bON.deserialize(data) end -- function exports.serialize(data) -- return util.TableToJSON(data) -- end -- function exports.deserialize(data) -- return util.JSONToTable(data) -- end
nilq/small-lua-stack
null
local fio = require('fio') local t = require('luatest') local g = t.group('cartridge-without-http') local helpers = require('test.helper') g.test_http_disabled = function() t.skip_if(type(helpers) ~= 'table', 'Skip cartridge test') local cluster = helpers.init_cluster() local server = cluster.main_server server.net_box:eval([[ local cartridge = require('cartridge') _G.old_service = cartridge.service_get('httpd') cartridge.service_set('httpd', nil) ]]) local ret = helpers.set_export(cluster, { { path = '/metrics', format = 'json', }, }) t.assert_not(ret) server.net_box:eval([[ require('cartridge').service_set('httpd', _G.old_service) ]]) cluster:stop() fio.rmtree(cluster.datadir) end
nilq/small-lua-stack
null
wait(1) local plr = game.Players.LocalPlayer local char = plr.Character hum=char.Humanoid for i,v in pairs (char:GetChildren()) do if v.Name~="Humanoid" and v.ClassName~="Part" then v:Destroy() end end for i,v in pairs (char:WaitForChild("Head"):GetChildren()) do if v.ClassName=="Sound" then v:Destroy() end end spawn(function() while wait() do char:WaitForChild("Right Arm").BrickColor=BrickColor.new("Cool yellow") char:WaitForChild("Left Arm").BrickColor=BrickColor.new("Cool yellow") char:WaitForChild("Head").BrickColor=BrickColor.new("Cool yellow") char:WaitForChild("Right Leg").BrickColor=BrickColor.new("Medium blue") char:WaitForChild("Left Leg").BrickColor=BrickColor.new("Medium blue") char:WaitForChild("Torso").BrickColor=BrickColor.new("Bright yellow") end end) ac = Instance.new("Accessory",workspace) ac.AttachmentPos=Vector3.new(0, -0.1, 0.2) o2 = Instance.new("Part") o3 = Instance.new("SpecialMesh") o4 = Instance.new("Vector3Value") o2.Name = "Handle" o2.Parent = ac o2.Position = char.Torso.Position spawn(function() repeat if ac.Parent~=char then o2.Position = char.Torso.Position else break end wait() until ac.Parent==char end) o2.Rotation = Vector3.new(0, -0.75999999, 0) o2.CanCollide = false o2.Locked = true o2.FormFactor = Enum.FormFactor.Custom o2.Size = Vector3.new(1.60000014, 0.800000012, 1.60000014) o2.CFrame = CFrame.new(0.128948003, 5.08735895, -0.544525981, 0.999912918, 1.17847014e-26, -0.0131900534, -4.89980362e-24, 1, -3.70551116e-22, 0.013190059, 3.70583553e-22, 0.999912918) o2.BottomSurface = Enum.SurfaceType.Smooth o2.TopSurface = Enum.SurfaceType.Smooth o2.Position = Vector3.new(0.128948003, 5.08735895, -0.544525981) o3.Parent = o2 o3.MeshId = "http://www.roblox.com/asset/?id=120626701" o3.Scale = Vector3.new(0.899999976, 0.819999993, 0.819999993) o3.TextureId = "http://www.roblox.com/asset/?id=120626735" o3.MeshType = Enum.MeshType.FileMesh o4.Name = "OriginalSize" o4.Parent = o2 o4.Value = Vector3.new(1.60000014, 0.800000012, 1.60000014) local mouse = plr:GetMouse() local torso = char.Torso local RightArm1 = torso["Right Shoulder"] local LeftArm1 = torso["Left Shoulder"] local RightLeg1 = torso["Right Hip"] local LeftLeg1 = torso["Left Hip"] local Torso1 = char.HumanoidRootPart.RootJoint local Head1 = torso.Neck local RightArm = torso["Right Shoulder"]:Clone() local LeftArm = torso["Left Shoulder"]:Clone() local RightLeg = torso["Right Hip"]:Clone() local LeftLeg = torso["Left Hip"]:Clone() local Torso = char.HumanoidRootPart.RootJoint:Clone() local Head = torso.Neck:Clone() RightArm1:Destroy() LeftArm1:Destroy() RightLeg1:Destroy() LeftLeg1:Destroy() Torso1:Destroy() Head1:Destroy() RightArm.Parent=torso LeftArm.Parent=torso RightLeg.Parent=torso LeftLeg.Parent=torso Head.Parent=torso Torso.Parent=char.HumanoidRootPart local animpose = "Idle" cananim = true num=0 local attacking = false if char:FindFirstChildOfClass("Humanoid"):FindFirstChild("Animator") then char:FindFirstChildOfClass("Humanoid").Animator:Destroy() end if char:FindFirstChild("Animate") then char.Animate:Destroy() end spawn(function() while wait() do if torso then local velocity=torso.Velocity if hum==nil then return end if hum.MoveDirection==Vector3.new(0,0,0) then animpose="Idle" else animpose="Running" end if velocity.Y>0.5 then animpose="Jumping" end if velocity.Y<-0.5 then animpose="Falling" end end end end) function sound(id,loop,tim,endtim,eff) local s=Instance.new("Sound",char.Torso) s.SoundId=id if loop==true then s.Looped=true s.Name="Music" else s.Volume=2 if id~="rbxassetid://245537790" and id~='rbxassetid://1179921724' and id~='rbxassetid://1251737869' then s.PlaybackSpeed = 1+math.random(-100,100)/1000 end end if tim then s.TimePosition=tim end spawn(function() if endtim then repeat wait() until s.TimePosition==endtim or s.TimePosition>=endtim s:Stop() end end) if eff=="echo" then spawn(function() wait(1) local echo=Instance.new("EchoSoundEffect",s) echo.Delay=0.05 echo.WetLevel=11 echo.DryLevel=-1 end) end if eff=="quiet" then s.Volume=0.3 end s:Play() end --SCREEEEM function lazor() sound("rbxassetid://1251737869",false,5.3,7.7,'echo') cananim=false for i=1,30 do wait(1/60) Torso.C1 = Torso.C1:lerp(CFrame.new(0, 0, 0, -0.934085608, 0.339979589, -0.10907802, -0.102499805, 0.0373069048, 0.994033217, 0.342020363, 0.939692557, 0),0.2) LeftLeg.C1 = LeftLeg.C1:lerp(CFrame.new(-0.50000006, 0.365961194, 0.435137242, -0.173563123, -0.0313025787, -0.984325111, -0.00543563766, 0.999509931, -0.0308270231, 0.98480773, 0, -0.173648223),0.2) RightLeg.C1 = RightLeg.C1:lerp(CFrame.new(0.5, 1, -7.4505806e-09, 0.0094302753, 0.0843551308, 0.996391118, 0.110700019, 0.990222573, -0.0848806128, -0.993809104, 0.111100972, -4.34407745e-08),0.2) LeftArm.C1 = LeftArm.C1:lerp(CFrame.new(0.499999881, 0.49999997, 0, 0.686760783, 0.0407644771, -0.725739539, 0.724464417, 0.0430024639, 0.687969565, 0.0592533089, -0.998242974, -2.59004374e-09),0.2) RightArm.C1 = RightArm.C1:lerp(CFrame.new(-0.5, -0.0484665036, 2.98023224e-08, -0.31701979, -0.00180978479, 0.948417187, -0.948401749, -0.00541418325, -0.317024946, 0.00570865162, -0.999983728, 2.49531951e-10),0.2) Head.C1 = Head.C1:lerp(CFrame.new(0, -0.5, 0, -1, 0, 0, 0, 0, 1, 0, 1, -0),0.2) end local keeprunning=true spawn(function() while wait() do local ray = Ray.new(char['Right Arm'].CFrame.p,(mouse.Hit.p-char['Right Arm'].CFrame.p).unit*300) local part,position = workspace:FindPartOnRay(ray,char, false, true) local distance = (char['Right Arm'].CFrame.p - position).magnitude if keeprunning==false then break end if part then if part.Parent:FindFirstChild("Humanoid") then part:BreakJoints() part.Anchored=false end end local ex=Instance.new("Explosion",workspace) ex.Position=position ex.Visible=false ex.DestroyJointRadiusPercent=0 ex.BlastPressure=100001 ex.BlastRadius=1 local ex=Instance.new("Explosion",workspace) ex.Position=position ex.Visible=false ex.DestroyJointRadiusPercent=0 ex.BlastPressure=100 ex.BlastRadius=30 Torso.C1 = Torso.C1:lerp(CFrame.new(0.45384407, 3.25962901e-09, -0.163368881, -0.840329647, -0.538628399, 0.061037913, 0.12248569, -0.0789824352, 0.989322543, -0.528056264, 0.838833332, 0.132345542),0.2) LeftLeg.C1 = LeftLeg.C1:lerp(CFrame.new(-0.486327916, 0.918347716, -0.0835282654, -0.139580116, -0.193979532, -0.971024871, -0.210418463, 0.96403873, -0.162337258, 0.967595696, 0.18166253, -0.175377563),0.2) RightLeg.C1 = RightLeg.C1:lerp(CFrame.new(0.504761815, 1.01941562, -0.072208859, -0.0534072705, 0.0794541091, 0.995406747, -0.0726492628, 0.993878722, -0.083230041, -0.995926619, -0.0767606497, -0.0473080687),0.2) LeftArm.C1 = LeftArm.C1:lerp(CFrame.new(0.5, 0.49999994, -5.96046448e-08, -0.0783533007, -0.155531406, -0.984718561, -0.400697172, 0.909370303, -0.111747369, 0.912854075, 0.385818183, -0.1335731),0.2) RightArm.C1 = RightArm.C1:lerp(CFrame.new(-0.267708331, 0.709498703, -0.021721065, -0.500156283, -0.117081404, 0.85798347, -0.864884198, 0.0187412351, -0.501621544, 0.0426508784, -0.992945492, -0.110635392),0.2) Head.C1 = Head.C1:lerp(CFrame.new(0, -0.5, 0, -0.951892793, 0.28452459, 0.113780133, 0, -0.371307135, 0.928510129, 0.306431323, 0.883842111, 0.353444576),0.2) local beam = Instance.new("Part", char) beam.BrickColor = BrickColor.new("Institutional white") beam.FormFactor = "Custom" beam.Material = "Neon" beam.Transparency = 0.5 beam.Anchored = true beam.Locked = true beam.CanCollide = false beam.Size = Vector3.new(0.3, 0.3, distance) beam.CFrame = CFrame.new((char['Right Arm'].CFrame*CFrame.new(0,-3,0)).p, mouse.Hit.p) * CFrame.new(0, 0, -distance/2) spawn(function() for i=1,10 do beam.Transparency=i/10 wait() end beam:Destroy() end) spawn(function() for i=1,20 do beam.Size=Vector3.new(i,i,beam.Size.Z) wait() end end) end end) for i=1,10 do sound("rbxassetid://245537790",false) end wait(3) keeprunning=false cananim=true end dodamage=false deb=false hum.Touched:connect(function(part) local ded=part.Parent:FindFirstChildOfClass("Humanoid") if deb==true then return end deb=true if ded then if dodamage == true then ded.Health=ded.Health-(math.random(5,10)) sound("rbxassetid://386946017",false,0,0.36,'quiet') if supermode==true then local ex=Instance.new("Explosion",workspace) if math.random(1,3) ==1 then ex.Visible=false end ex.DestroyJointRadiusPercent=0 ex.Position=part.Position ex.BlastPressure=1000 part:BreakJoints() part.Anchored=false end end end wait(0.1) deb=false end) function SUPERlazor() sound("rbxassetid://1179921724",false,'echo') wait(2) cananim=false for i=1,30 do wait(1/60) Torso.C1 = Torso.C1:lerp(CFrame.new(0, 0, 0, -0.934085608, 0.339979589, -0.10907802, -0.102499805, 0.0373069048, 0.994033217, 0.342020363, 0.939692557, 0),0.2) LeftLeg.C1 = LeftLeg.C1:lerp(CFrame.new(-0.50000006, 0.365961194, 0.435137242, -0.173563123, -0.0313025787, -0.984325111, -0.00543563766, 0.999509931, -0.0308270231, 0.98480773, 0, -0.173648223),0.2) RightLeg.C1 = RightLeg.C1:lerp(CFrame.new(0.5, 1, -7.4505806e-09, 0.0094302753, 0.0843551308, 0.996391118, 0.110700019, 0.990222573, -0.0848806128, -0.993809104, 0.111100972, -4.34407745e-08),0.2) LeftArm.C1 = LeftArm.C1:lerp(CFrame.new(0.499999881, 0.49999997, 0, 0.686760783, 0.0407644771, -0.725739539, 0.724464417, 0.0430024639, 0.687969565, 0.0592533089, -0.998242974, -2.59004374e-09),0.2) RightArm.C1 = RightArm.C1:lerp(CFrame.new(-0.5, -0.0484665036, 2.98023224e-08, -0.31701979, -0.00180978479, 0.948417187, -0.948401749, -0.00541418325, -0.317024946, 0.00570865162, -0.999983728, 2.49531951e-10),0.2) Head.C1 = Head.C1:lerp(CFrame.new(0, -0.5, 0, -1, 0, 0, 0, 0, 1, 0, 1, -0),0.2) end local keeprunning=true spawn(function() while wait() do local ray = Ray.new(char['Right Arm'].CFrame.p,(mouse.Hit.p-char['Right Arm'].CFrame.p).unit*300) local part,position = workspace:FindPartOnRay(ray,char, false, true) local distance = (char['Right Arm'].CFrame.p - position).magnitude if keeprunning==false then break end if part then if part.Parent:FindFirstChild("Humanoid") then part:BreakJoints() part.Anchored=false part.Velocity = Vector3.new(math.random(-160,160),math.random(-160,160),math.random(-160,160)) if math.random(1,3) == 1 then part:Destroy() end end end local ex=Instance.new("Explosion",workspace) ex.Position=position ex.Visible=false ex.DestroyJointRadiusPercent=0 ex.BlastPressure=100 ex.BlastRadius=10 ex.Hit:connect(function(part) if part.Parent~=char and part.Parent~=char:WaitForChild("Accessory") then part:BreakJoints() end end) if math.random(1,5)==5 then sound("rbxassetid://314970761",false) end Torso.C1 = Torso.C1:lerp(CFrame.new(0.45384407, 3.25962901e-09, -0.163368881, -0.840329647, -0.538628399, 0.061037913, 0.12248569, -0.0789824352, 0.989322543, -0.528056264, 0.838833332, 0.132345542),0.2) LeftLeg.C1 = LeftLeg.C1:lerp(CFrame.new(-0.486327916, 0.918347716, -0.0835282654, -0.139580116, -0.193979532, -0.971024871, -0.210418463, 0.96403873, -0.162337258, 0.967595696, 0.18166253, -0.175377563),0.2) RightLeg.C1 = RightLeg.C1:lerp(CFrame.new(0.504761815, 1.01941562, -0.072208859, -0.0534072705, 0.0794541091, 0.995406747, -0.0726492628, 0.993878722, -0.083230041, -0.995926619, -0.0767606497, -0.0473080687),0.2) LeftArm.C1 = LeftArm.C1:lerp(CFrame.new(0.5, 0.49999994, -5.96046448e-08, -0.0783533007, -0.155531406, -0.984718561, -0.400697172, 0.909370303, -0.111747369, 0.912854075, 0.385818183, -0.1335731),0.2) RightArm.C1 = RightArm.C1:lerp(CFrame.new(-0.267708331, 0.709498703, -0.021721065, -0.500156283, -0.117081404, 0.85798347, -0.864884198, 0.0187412351, -0.501621544, 0.0426508784, -0.992945492, -0.110635392),0.2) Head.C1 = Head.C1:lerp(CFrame.new(0, -0.5, 0, -0.951892793, 0.28452459, 0.113780133, 0, -0.371307135, 0.928510129, 0.306431323, 0.883842111, 0.353444576),0.2) local beam = Instance.new("Part", char) local colorz = {"Really red","Gold","Lime green","Really blue","Royal purple"} beam.BrickColor = BrickColor.new(colorz[math.random(1,#colorz)]) beam.FormFactor = "Custom" beam.Material = "Neon" beam.Transparency = 0.5 beam.Anchored = true beam.Locked = true beam.CanCollide = false beam.Size = Vector3.new(0.3, 0.3, distance) beam.CFrame = CFrame.new((char['Right Arm'].CFrame*CFrame.new(0,-3,0)).p, mouse.Hit.p) * CFrame.new(0, 0, -distance/2) spawn(function() while beam do if beam==nil then break end beam.Anchored=true swait() end end) spawn(function() for i=1,10 do beam.Transparency=i/10 beam.CFrame=beam.CFrame*CFrame.new(0,0,-i/10) wait() end beam:Destroy() end) spawn(function() for i=5,70, 3 do beam.Size=Vector3.new(i,i,beam.Size.Z) wait() end end) end end) for i=1,10 do sound("rbxassetid://314970761",false) end wait(6) keeprunning=false cananim=true end mouse.Button1Down:connect(function() normpunch() end) supermode=false mouse.KeyDown:connect(function(key) local k=string.lower(key) if attacking==true then return end if k=="q" then attacking=true if supermode==false then lazor() else SUPERlazor() end attacking=false end if k=="l" then transition() end end) punch = 1 function normpunch() if attacking==true then return end dodamage=true attacking=true cananim=false sound("rbxassetid://138097048",false) if punch==1 then for i=1,10 do Torso.C1 = Torso.C1:lerp(CFrame.new(0, 0, 0, -0.910118103, -0.41434893, 0, 0, 0, 1, -0.41434893, 0.910118103, 0),0.3) LeftLeg.C1 = LeftLeg.C1:lerp(CFrame.new(-0.5, 1, 3.7252903e-09, 0.00116646651, 0.0136213535, -0.99990654, 0.023496937, 0.999630809, 0.0136450082, 0.999723256, -0.0235106573, 0.000845975766),0.3) RightLeg.C1 = RightLeg.C1:lerp(CFrame.new(0.5, 1, 4.65661287e-10, -4.35437997e-08, 0.0874831304, 0.996165991, 0.00556585658, 0.996150553, -0.0874817744, -0.999984503, 0.00554451346, -0.000486961944),0.3) LeftArm.C1 = LeftArm.C1:lerp(CFrame.new(0.5, 0.5, 0, 0.0391717218, -0.188973963, -0.981200516, -0.199156061, 0.960776389, -0.192991138, 0.979184568, 0.202971816, -4.2801517e-08),0.3) RightArm.C1 = RightArm.C1:lerp(CFrame.new(-0.312758863, 0.804995358, -0.0404221117, -0.349137038, 0.0591336042, 0.935203969, -0.937045753, -0.0294431858, -0.347962916, 0.0069590779, -0.997815788, 0.0656905994),0.3) Head.C1 = Head.C1:lerp(CFrame.new(0, -0.5, 0, -0.957687616, 0.287809789, 0, 0, 0, 1, 0.287809789, 0.957687616, 0),0.3) swait() end end if punch==2 then for i=1,10 do swait() Torso.C1 = Torso.C1:lerp(CFrame.new(0, 0, 0, -0.983417749, -0.116297476, 0.139156267, 0.140106976, 0, 0.990136385, -0.115150362, 0.993214428, 0.0162940882),0.3) LeftLeg.C1 = LeftLeg.C1:lerp(CFrame.new(-0.5, 0.86816901, 0, -4.32735874e-08, -0.141177684, -0.989984274, -6.17107254e-09, 0.989984274, -0.141177684, 1, 0, -4.37113883e-08),0.3) RightLeg.C1 = RightLeg.C1:lerp(CFrame.new(0.5, 1.23575175, 0.176770806, -0.0336775407, -0.11687994, 0.992574871, -0.983614028, 0.179874539, -0.0121925017, -0.177113876, -0.976721108, -0.12102247),0.3) LeftArm.C1 = LeftArm.C1:lerp(CFrame.new(0.5, 0.49999994, 0, -4.33072991e-08, -0.135659724, -0.990755498, -0.144958332, 0.98029089, -0.134226859, 0.989437759, 0.143618271, -0.0196650494),0.3) RightArm.C1 = RightArm.C1:lerp(CFrame.new(-0.5, 0.49999997, 0, 0.0339012295, 0.115021303, 0.992784381, 0.280674934, 0.952282727, -0.119913273, -0.959203959, 0.282714903, -4.19281356e-08),0.3) Head.C1 = Head.C1:lerp(CFrame.new(0, -0.5, 0, -1, 0, 0, 0, -0.0711001009, 0.997469187, 0, 0.997469187, 0.0711001009),0.3) end end if punch==3 then for i=1,10 do swait() Torso.C1 = Torso.C1:lerp(CFrame.new(0, 0, 0, -0.93749547, 0.347997427, 0, 0, 0, 1, 0.347997427, 0.93749547, 0),0.3) LeftLeg.C1 = LeftLeg.C1:lerp(CFrame.new(-0.50000006, 1, 0, 0.0109365005, -0.0829221606, -0.996496022, -0.130298764, 0.98794055, -0.083640255, 0.991414428, 0.13075693, -4.33361009e-08),0.3) RightLeg.C1 = RightLeg.C1:lerp(CFrame.new(0.49999997, 1, -3.7252903e-09, 0.114501342, 0.0127837732, 0.99334085, 5.62495939e-10, 0.999917209, -0.0128684072, -0.993423104, 0.00147345045, 0.114491865),0.3) LeftArm.C1 = LeftArm.C1:lerp(CFrame.new(0.352809936, 1.3686024, 0.0138391852, -4.37113883e-08, 0, -1, 0.999440074, -0.0334585831, -4.36869136e-08, -0.0334585831, -0.999440074, 1.4625211e-09),0.3) RightArm.C1 = RightArm.C1:lerp(CFrame.new(-0.5, 0.5, 0, -4.33629381e-08, 0.126015082, 0.992028356, 0.172522247, 0.97715348, -0.124125555, -0.985005617, 0.171146959, -0.0217404477),0.3) Head.C1 = Head.C1:lerp(CFrame.new(0, -0.5, 0, -1, 0, 0, 0, -0.07533779, 0.997158051, 0, 0.997158051, 0.07533779),0.3) end end if punch~=3 then punch=punch+1 else punch=1 end cananim=true dodamage=false attacking=false end ---transiton function transition() if supermode==false then sound("rbxassetid://1321047607",false,0,5) cananim=false attacking=true local stord = false spawn(function() wait(3) stord=true end) local ParticleEmitter0 = Instance.new("ParticleEmitter") ParticleEmitter0.Parent = torso ParticleEmitter0.Transparency = NumberSequence.new(0.20000000298023,0.20000000298023) ParticleEmitter0.Size = NumberSequence.new(3.2240438461304,1.0928964614868,3.7158470153809,0) ParticleEmitter0.Color = ColorSequence.new(Color3.new(0, 0, 0),Color3.new(0, 0, 0)) ParticleEmitter0.Texture = "http://www.roblox.com/asset/?id=232918622" ParticleEmitter0.Lifetime = NumberRange.new(3) ParticleEmitter0.Rate = 1000 ParticleEmitter0.VelocitySpread = 180 ParticleEmitter0.Color = ColorSequence.new(Color3.new(0, 0, 0),Color3.new(0, 0, 0)) repeat Torso.C1 = Torso.C1:lerp(CFrame.new(0, 0.787846208, 0.138918549, -1, 0, 0, 0, -0.173648179, 0.98480773, 0, 0.98480773, 0.173648179),0.2) LeftLeg.C1 = LeftLeg.C1:lerp(CFrame.new(-0.45286727, 0.316941619, 0.628786147, -4.36354597e-08, -0.058915928, -0.998262942, 0.21313341, 0.975326002, -0.0575622357, 0.977023065, -0.21276319, 0.0125569087),0.2) RightLeg.C1 = RightLeg.C1:lerp(CFrame.new(0.5, 0.627124608, -0.0240803957, -4.37113883e-08, 0, 1, 0.551679194, 0.834056437, 2.4114664e-08, -0.834056437, 0.551679194, -3.6457763e-08),0.2) LeftArm.C1 = LeftArm.C1:lerp(CFrame.new(0.5, 0.5, 0, 0.774880886, 0.296248376, -0.558387458, 0.52156949, 0.199403673, 0.829580307, 0.357106328, -0.934063733, -1.56096132e-08),0.2) RightArm.C1 = RightArm.C1:lerp(CFrame.new(-0.5, 0.5, 0, -0.00304316962, 0.0175396204, 0.999841511, -0.170919135, 0.985124171, -0.0178016629, -0.985280335, -0.170946226, -4.30679705e-08),0.2) Head.C1 = Head.C1:lerp(CFrame.new(0, -0.5, 0, -1, 0, 0, 0, -0.362809777, 0.931863308, 0, 0.931863308, 0.362809777),0.2) swait() until stord==true sound("rbxassetid://245537790",false) ParticleEmitter0.Speed=NumberRange.new(50) local mas = char local CharacterMesh0 = Instance.new("CharacterMesh") local CharacterMesh1 = Instance.new("CharacterMesh") local CharacterMesh2 = Instance.new("CharacterMesh") local CharacterMesh3 = Instance.new("CharacterMesh") local CharacterMesh4 = Instance.new("CharacterMesh") CharacterMesh0.Name = "GirlRocker Left Arm" CharacterMesh0.Parent = mas CharacterMesh0.MeshId = 717353151 CharacterMesh0.BodyPart = Enum.BodyPart.LeftArm CharacterMesh0.OverlayTextureId = 717346901 CharacterMesh1.Name = "GirlRocker Right Arm" CharacterMesh1.Parent = mas CharacterMesh1.MeshId = 717353483 CharacterMesh1.BodyPart = Enum.BodyPart.RightArm CharacterMesh1.OverlayTextureId = 717346901 CharacterMesh2.Name = "GirlRocker Right Leg" CharacterMesh2.Parent = mas CharacterMesh2.MeshId = 717353619 CharacterMesh2.BodyPart = Enum.BodyPart.RightLeg CharacterMesh2.OverlayTextureId = 717346901 CharacterMesh3.Name = "GirlRocker Torso" CharacterMesh3.Parent = mas CharacterMesh3.MeshId = 717353723 CharacterMesh3.BodyPart = Enum.BodyPart.Torso CharacterMesh3.OverlayTextureId = 717346901 CharacterMesh4.Name = "GirlRocker Left Leg" CharacterMesh4.Parent = mas CharacterMesh4.MeshId = 717353920 CharacterMesh4.BodyPart = Enum.BodyPart.LeftLeg CharacterMesh4.OverlayTextureId = 717346901 for i=1,90 do Torso.C1 = Torso.C1:lerp(CFrame.new(0, -1.06972265, 0, -1, 0, 0, 0, 0, 1, 0, 1, -0),0.2) LeftLeg.C1 = LeftLeg.C1:lerp(CFrame.new(-0.5, 1, 0, -4.37113883e-08, 0, -1, -0.0906665474, 0.995881319, 3.96316047e-09, 0.995881319, 0.0906665474, -4.35313545e-08),0.2) RightLeg.C1 = RightLeg.C1:lerp(CFrame.new(0.5, 1, 0, -4.37113883e-08, 0, 1, 0.0595862567, 0.998223186, 2.60459809e-09, -0.998223186, 0.0595862567, -4.36337224e-08),0.2) LeftArm.C1 = LeftArm.C1:lerp(CFrame.new(0.5, 0.5, 0, -4.34208935e-08, -0.115096748, -0.993354261, -5.0310387e-09, 0.993354261, -0.115096748, 1, 0, -4.37113883e-08),0.2) RightArm.C1 = RightArm.C1:lerp(CFrame.new(-0.5, 0.5, 0, -4.36014211e-08, 0.0708893314, 0.997484207, 3.0986711e-09, 0.997484207, -0.0708893314, -1, 0, -4.37113883e-08),0.2) Head.C1 = Head.C1:lerp(CFrame.new(0, -0.5, 0, -1, 0, 0, 0, 0.249942318, 0.968260705, 0, 0.968260705, -0.249942318),0.2) swait() end ParticleEmitter0.Enabled=false supermode=true cananim=true attacking=false end end function swait(t) if t == nil or t == 0 then game:service('RunService').Stepped:wait(0) return true else for i = 0, t do game:service('RunService').Stepped:wait(0) end return true end end function scream() sound("rbxassetid://444895479",false,5.3509586219885250102) cananim = false for i=0,1.5, 0.1 do swait() end attacking=true for i=0,1.5, 0.1 do swait() end wait() cananim = true attacking=false end spawn(function() while swait() do if animpose=="Idle" then for i=0,0.1,0.0025 do if animpose == "Idle" and cananim then swait() LeftArm.C1 = LeftArm.C1:lerp(CFrame.new(0.500000238, 0.500000238, -2.38418579e-07, 0.000574484526, -0.0482845455, -0.998833477, -0.00805476494, 0.998800993, -0.0482876077, 0.999967396, 0.0080731092, 0.000184875054),i) RightArm.C1 = RightArm.C1:lerp(CFrame.new(-0.50000006, 0.500000238, 0, -0.000810533762, 0.0540908612, 0.998535693, -0.00984518789, 0.998487175, -0.0540962256, -0.999951184, -0.00987461861, -0.000276772887),i) else break end end for i=0,0.1,0.0025 do if animpose == "Idle" and cananim then swait() LeftArm.C1 = LeftArm.C1:lerp(CFrame.new(0.50000006, 0.50000006, -9.47312119e-16, -4.35179714e-08, -0.0939683169, -0.99557513, -4.10748546e-09, 0.99557513, -0.0939683169, 1, 0, -4.37113883e-08),i) RightArm.C1 = RightArm.C1:lerp(CFrame.new(-0.5, 0.5, -1.77635684e-15, -4.34464624e-08, 0.109930925, 0.993939221, 4.80523354e-09, 0.993939221, -0.109930925, -1, 0, -4.37113883e-08),i) else break end end end end end) while swait() do num = num + 0.05 local sin = math.sin(num) if animpose == "Falling" and cananim then Torso.C1 = Torso.C1:lerp(CFrame.new(0, 0, 0, -1, 0, 0, 0, -0.089640595, 0.995974183, 0, 0.995974183, 0.089640595),0.2) LeftLeg.C1 = LeftLeg.C1:lerp(CFrame.new(-0.5, 0.940049231, 0.240459353, -4.37113883e-08, 0, -1, 0.0583860278, 0.998294055, -2.55213428e-09, 0.998294055, -0.0583860278, -4.36368204e-08),0.2) RightLeg.C1 = RightLeg.C1:lerp(CFrame.new(0.5, 1, 0, -4.37113883e-08, 0, 1, 0.144062787, 0.989568532, 6.29718455e-09, -0.989568532, 0.144062787, -4.32554152e-08),0.2) LeftArm.C1 = LeftArm.C1:lerp(CFrame.new(0.5, 0.635436773, 0, -4.28449951e-08, -0.198112398, -0.98017925, -8.65976801e-09, 0.98017925, -0.198112398, 1, 0, -4.37113883e-08),0.2) RightArm.C1 = RightArm.C1:lerp(CFrame.new(-0.5, 0.599987805, 0, -4.26205062e-08, 0.222013503, 0.975043535, 9.70451808e-09, 0.975043535, -0.222013503, -1, 0, -4.37113883e-08),0.2) Head.C1 = Head.C1:lerp(CFrame.new(0, -0.5, 0, -1, 0, 0, 0, -0.231759518, 0.972773135, 0, 0.972773135, 0.231759518),0.2) end if animpose == "Idle" and cananim then for i=0,0.1,0.001 do if animpose == "Idle" and cananim then swait() Torso.C1 = Torso.C1:lerp(CFrame.new(0, 0.200000048, 0, -0.98480767, -0.173648626, 0, 0, 0, 1, -0.173648626, 0.98480767, 0),i) LeftLeg.C1 = LeftLeg.C1:lerp(CFrame.new(-0.506504774, 0.77988106, 0.0818042755, 0.00300081098, -0.0723684728, -0.997373462, -0.186295643, 0.979876935, -0.0716594532, 0.982489169, 0.186021373, -0.0105415061),i) RightLeg.C1 = RightLeg.C1:lerp(CFrame.new(0.485123575, 0.800115585, 0.135903358, -0.000153154135, -0.00734659936, 0.999972999, -0.0196102634, 0.999780715, 0.0073421835, -0.999807715, -0.0196086094, -0.000297189312),i) Head.C1 = Head.C1:lerp(CFrame.new(0, -0.5, 0, -0.98480767, 0.173648402, 0, 0, 0, 1, 0.173648402, 0.98480767, 0),i) i=i/2 else break end end for i=0,0.1,0.001 do if animpose == "Idle" and cananim then swait() Torso.C1 = Torso.C1:lerp(CFrame.new(0, 0, 0, -0.98480767, -0.173648626, 0, 0, 0, 1, -0.173648626, 0.98480767, 0),i) LeftLeg.C1 = LeftLeg.C1:lerp(CFrame.new(-0.49999994, 1, 0, -4.3619707e-08, -0.0647336245, -0.997902572, -0.143231794, 0.98761338, -0.0640661567, 0.989689171, 0.142931372, -0.00927195605),i) RightLeg.C1 = RightLeg.C1:lerp(CFrame.new(0.5, 1.00000012, 0.0391067117, -4.37113883e-08, 0, 1, -0.0612497553, 0.998122454, -2.67731193e-09, -0.998122454, -0.0612497553, -4.3629317e-08),i) Head.C1 = Head.C1:lerp(CFrame.new(0, -0.5, 0, -0.98480767, 0.173648402, 0, 0, 0, 1, 0.173648402, 0.98480767, 0),i) i=i/2 else break end end end if animpose == "Running" and cananim then for i = 0, 0.25, 0.01 do if animpose == "Running" and cananim then Torso.C1 = Torso.C1:lerp(CFrame.new(0, 0, 0, -1, 0, 0, 0, -0.0358745977, 0.99935627, 0, 0.99935627, 0.0358745977),i) LeftLeg.C1 = LeftLeg.C1:lerp(CFrame.new(-0.5, 0.999999821, 8.94069672e-08, -4.37113883e-08, 0, -1, 0.342020363, 0.939692557, -1.49501851e-08, 0.939692557, -0.342020363, -4.10752676e-08),i) RightLeg.C1 = RightLeg.C1:lerp(CFrame.new(0.5, 1.00000024, 5.96046448e-08, -4.37113883e-08, 0, 1, 0.500000179, 0.866025269, 2.18557012e-08, -0.866025269, 0.500000179, -3.78551661e-08),i) LeftArm.C1 = LeftArm.C1:lerp(CFrame.new(0.5, 0.5, -2.98023224e-08, -4.37113883e-08, 0, -1, -0.5, 0.866025388, 2.18556941e-08, 0.866025388, 0.5, -3.78551732e-08),i) RightArm.C1 = RightArm.C1:lerp(CFrame.new(-0.5, 0.5, -1.49011612e-08, -4.37113883e-08, 0, 1, -0.5, 0.866025388, -2.18556941e-08, -0.866025388, -0.5, -3.78551732e-08),i) Head.C1 = Head.C1:lerp(CFrame.new(0, -0.5, 0, -1, 0, 0, 0, -0.106743492, 0.994286597, 0, 0.994286597, 0.106743492),i) swait() i=i/i*1.5 else break end end for i = 0, 0.25, 0.01 do if animpose == "Running" and cananim then Torso.C1 = Torso.C1:lerp(CFrame.new(0, 0, 0, -0.999985278, 0, -0.00542885857, -0.00542835938, -0.0135572571, 0.999893367, -7.36004295e-05, 0.99990809, 0.0135570578),i) LeftLeg.C1 = LeftLeg.C1:lerp(CFrame.new(-0.5, 0.999999821, -1.1920929e-07, -4.37113883e-08, 0, -1, -0.499999791, 0.866025567, 2.18556853e-08, 0.866025567, 0.499999791, -3.78551803e-08),i) RightLeg.C1 = RightLeg.C1:lerp(CFrame.new(0.5, 1.00000012, -2.38418579e-07, -4.37113883e-08, 0, 1, -0.342020005, 0.939692616, -1.49501691e-08, -0.939692616, -0.342020005, -4.10752676e-08),i) LeftArm.C1 = LeftArm.C1:lerp(CFrame.new(0.5, 0.483990371, 0.00582697988, -4.37113883e-08, 0, -1, 0.57357651, 0.819151998, -2.50718255e-08, 0.819151998, -0.57357651, -3.58062699e-08),i) RightArm.C1 = RightArm.C1:lerp(CFrame.new(-0.5, 0.49999997, -2.98023224e-08, -4.37113883e-08, 0, 1, 0.500000179, 0.866025329, 2.18557012e-08, -0.866025329, 0.500000179, -3.78551697e-08),i) Head.C1 = Head.C1:lerp(CFrame.new(0, -0.5, 0, -1, 0, 0, 0, -0.103604339, 0.994618595, 0, 0.994618595, 0.103604339),i) swait() i=i/i*1.5 else break end end end if animpose == "Jumping" and cananim then Torso.C1 = Torso.C1:lerp(CFrame.new(0, 0, 0, -1, 0, 0, 0, -0.082511276, 0.996590137, 0, 0.996590137, 0.082511276),0.2) LeftLeg.C1 = LeftLeg.C1:lerp(CFrame.new(-0.495160788, 0.605178833, 0.315436631, 0.00363327051, -0.0117048975, -0.999924898, -0.296433508, 0.95497489, -0.012255826, 0.955046594, 0.296455771, -4.17464108e-08),0.2) RightLeg.C1 = RightLeg.C1:lerp(CFrame.new(0.5, 1, 0, -4.37113883e-08, 0, 1, 0.10612049, 0.994353294, 4.63867389e-09, -0.994353294, 0.10612049, -4.34645635e-08),0.2) LeftArm.C1 = LeftArm.C1:lerp(CFrame.new(0.5, 0.5, 0, -4.36747598e-08, -0.0409301594, -0.999162018, -1.78911408e-09, 0.999162018, -0.0409301594, 1, 0, -4.37113883e-08),0.2) RightArm.C1 = RightArm.C1:lerp(CFrame.new(-0.5, 0.5, 0, -4.36556142e-08, 0.0504997671, 0.998724043, 2.20741492e-09, 0.998724043, -0.0504997671, -1, 0, -4.37113883e-08),0.2) Head.C1 = Head.C1:lerp(CFrame.new(0, -0.5, 0, -1, 0, 0, 0, 0.106113546, 0.99435401, 0, 0.99435401, -0.106113546),0.2) end end
nilq/small-lua-stack
null
-- Copyright © Vespura 2018 -- https://github.com/TomGrobbe/JoinTransition/blob/master -- Arboratory character data. Likely fetched from a database. Characters = { { id = 1, forename = "Joe", surname = "Bloggs", description = "Recently signed a Mixer contract.", balance = 1000, position = {x = -1038.121, y = -2738.279, z = 20.16929} -- Los Santos International Airport }, { id = 2, forename = "John", surname = "Everyman", description = "Author of Roleplaying 101.", balance = 20320732, position = {x = 892.55, y = -182.25, z = 73.72} -- Downtown Cab Co. } } ------- Configurable options ------- -- set the opacity of the clouds local cloudOpacity = 0.01 -- (default: 0.01) -- setting this to false will NOT mute the sound as soon as the game loads -- (you will hear background noises while on the loading screen, so not recommended) local muteSound = true -- (default: true) -- Register NUI callback RegisterNUICallback('SELECT_CHARACTER', function(data, cb) if Characters[data.id] then local pos = Characters[data.id].position -- Set player's location SetEntityCoords(PlayerPedId(), pos.x, pos.y, pos.z, false, false, false, true) -- Hide CharacterSelect NUI SendNUIMessage({type = "CHARACTERS_HIDE"}) -- Remove NUI Focus SetNuiFocus(false, false) Citizen.CreateThread(function() local timer = GetGameTimer() -- Re-enable the sound in case it was muted. ToggleSound(false) SwitchInPlayer(PlayerPedId()) ClearScreen() -- Wait for the player switch to be completed (state 12). while GetPlayerSwitchState() ~= 12 do Citizen.Wait(0) ClearScreen() end -- Reset the draw origin, just in case (allowing HUD elements to re-appear correctly) ClearDrawOrigin() end) end end) ------- Code ------- -- Mutes or un-mutes the game's sound using a short fade in/out transition. function ToggleSound(state) if state then StartAudioScene("MP_LEADERBOARD_SCENE") else StopAudioScene("MP_LEADERBOARD_SCENE") end end -- Runs the initial setup whenever the script is loaded. function InitialSetup() -- Stopping the loading screen from automatically being dismissed. SetManualShutdownLoadingScreenNui(true) -- Disable sound (if configured) ToggleSound(muteSound) -- Switch out the player if it isn't already in a switch state. if not IsPlayerSwitchInProgress() then SwitchOutPlayer(PlayerPedId(), 0, 1) end end -- Hide radar & HUD, set cloud opacity, and use a hacky way of removing third party resource HUD elements. function ClearScreen() -- SetCloudHatOpacity(cloudOpacity) HideHudAndRadarThisFrame() -- nice hack to 'hide' HUD elements from other resources/scripts. kinda buggy though. SetDrawOrigin(0.0, 0.0, 0.0, 0) end -- Sometimes this gets called too early, but sometimes it's perfectly timed, -- we need this to be as early as possible, without it being TOO early, it's a gamble! InitialSetup() Citizen.CreateThread(function() SendNUIMessage({ type = "RECIEVE_CHARACTERS", data = {characters = Characters} }) -- In case it was called too early before, call it again just in case. InitialSetup() -- Wait for the switch cam to be in the sky in the 'waiting' state (5). while GetPlayerSwitchState() ~= 5 do Citizen.Wait(0) ClearScreen() end -- Shut down the game's loading screen (this is NOT the NUI loading screen). ShutdownLoadingScreen() ClearScreen() Citizen.Wait(0) DoScreenFadeOut(0) -- Shut down the NUI loading screen. ShutdownLoadingScreenNui() ClearScreen() Citizen.Wait(0) ClearScreen() DoScreenFadeIn(500) while not IsScreenFadedIn() do Citizen.Wait(0) ClearScreen() end -- Show CharacterSelect NUI SendNUIMessage({type = "CHARACTERS_SHOW"}) SetNuiFocus(true, true) end)
nilq/small-lua-stack
null
-- addEventListener('update lightline when lsp diagnostics is updated', { 'User LspDiagnosticsChanged', 'User LspMessageUpdate', 'User LspStatusUpdate' }, function () -- vim.cmd('call lightline#update()') -- end)
nilq/small-lua-stack
null
--Automatically generated by SWGEmu Spawn Tool v0.12 loot editor. acklay = { description = "", minimumLevel = 0, maximumLevel = 0, lootItems = { {itemTemplate = "acklay_bone_armor_schematic", weight = 1600000}, {itemTemplate = "acklay_bones", weight = 2200000}, {itemTemplate = "acklay_bones_rare", weight = 200000}, {itemTemplate = "acklay_hide", weight = 2200000}, {itemTemplate = "acklay_ris_armor_schematic", weight = 1600000}, {itemTemplate = "acklay_venom", weight = 2200000} } } addLootGroupTemplate("acklay", acklay)
nilq/small-lua-stack
null
--[[ Visualization of the evolution process. Requires the lua-gnuplot [1] library. [1]: https://bitbucket.org/lucashnegri/lua-gnuplot --]] local de = require('de') local gp = require('gnuplot') math.randomseed( os.time() ) local solver = de.new(2, 40) solver.limits[1] = {-5.12, 5.12} solver.limits[2] = {-5.12, 5.12} function solver.fitness(v) -- Banana' function local t1 = v[2] - v[1]*v[1] local t2 = 1 - v[1] return -(100 * t1*t1 + t2*t2) end local err_list = {} local i = 0 function solver:step() de.step(self) table.insert(err_list, -self.fit[self.best]) if i % 5 == 0 then local x, y, z = {}, {}, {} for i = 1, self.npop do table.insert(x, self.pop[i][1]) table.insert(y, self.pop[i][2]) table.insert(z, -self.fit[i]) end gp{ height = 600, width = 600, xlabel = "x", ylabel = "y", key = "off", xrange = "[-3 to 3]", yrange = "[-3 to 3]", zrange = "[0 to 12000]", isosamples = "30", data = { gp.gpfunc { "100 * (y - x*x)*(y - x*x) + (1 - x)*(1 - x)" }, gp.array { { x, y, z, }, using = {1, 2, 3}, with = 'points' } } }:splot( string.format('banana-iter%03d.png', i) ) end i = i + 1 end solver:init() local it, fit, best = solver:run(1000, 1e-6, 50) --- error plot gp{ xlabel = "Iteration", ylabel = "Mean Squared Error", key = "off", data = { gp.array { {err_list}, using = {1}, with = 'lines' } } }:plot('banana-error.png')
nilq/small-lua-stack
null
--[[ Netherstorm -- Eye of Culuthas.lua This script was written and is protected by the GPL v2. This script was released by BlackHer0 of the BLUA Scripting Project. Please give proper accredidations when re-releasing or sharing this script with others in the emulation community. ~~End of License Agreement -- BlackHer0, July, 29th, 2008. ]] function Eye_OnEnterCombat(Unit,Event) Unit:RegisterEvent("Eye_Bursts",1000,0) end function Eye_Bursts(Unit,Event) Unit:FullCastSpellOnTarget(36414,Unit:GetClosestPlayer()) end function Eye_OnLeaveCombat(Unit,Event) Unit:RemoveEvents() end function Eye_OnDied(Unit,Event) Unit:RemoveEvents() end RegisterUnitEvent (20394, 1, "Eye_OnEnterCombat") RegisterUnitEvent (20394, 2, "Eye_OnLeaveCombat") RegisterUnitEvent (20394, 4, "Eye_OnDied")
nilq/small-lua-stack
null
sb2 = {} local MP = minetest.get_modpath(minetest.get_current_modname()) local privateSB2 = {} privateSB2.modStorage = minetest.get_mod_storage() local settings = minetest.settings local enableExperiments = settings:get_bool("scriptblocks2_enable_experiments") local function loadfileWithError(file) local func, err = loadfile(file) if not func then error(err) end return func end -- Utilities -- These are files to provide helper functions and classes, as well as a simple class mechanism. dofile(MP .. "/util/util.lua") dofile(MP .. "/util/facedir.lua") dofile(MP .. "/util/classes.lua") dofile(MP .. "/util/iterators.lua") -- Core -- This is the core of Scriptblocks 2. It defines Process, Frame and Context, their behaviour, and manages the running of processes. dofile(MP .. "/core.lua") -- Base -- This is the base of Scriptblocks 2. It defines the look and feel of scriptblocks and manages type conversions. -- The base currently depends on /blocks/lists.lua and /blocks/dictionaries.lua to convert Lua values to SB2 values. dofile(MP .. "/base.lua") -- Blocks -- These files implement the blocks available in Scriptblocks 2. They are organized into distinct 'categories'. dofile(MP .. "/blocks/special.lua") dofile(MP .. "/blocks/control.lua") dofile(MP .. "/blocks/io.lua") dofile(MP .. "/blocks/operators.lua") dofile(MP .. "/blocks/variables.lua") dofile(MP .. "/blocks/lists.lua") dofile(MP .. "/blocks/dictionaries.lua") loadfileWithError(MP .. "/blocks/procedures.lua")(privateSB2) loadfileWithError(MP .. "/blocks/closures.lua")(privateSB2) dofile(MP .. "/blocks/coroutines.lua") if enableExperiments then dofile(MP .. "/blocks/processes.lua") dofile(MP .. "/blocks/fun.lua") end if mesecon then dofile(MP .. "/blocks/mesecons.lua") end if digilines then dofile(MP .. "/blocks/digilines.lua") end
nilq/small-lua-stack
null
swirl_prong = Creature:new { objectName = "@mob/creature_names:swirl_prong", socialGroup = "prong", faction = "", level = 19, chanceHit = 0.32, damageMin = 170, damageMax = 180, baseXp = 1426, baseHAM = 4100, baseHAMmax = 5000, armor = 0, resists = {5,120,5,135,135,-1,-1,-1,-1}, meatType = "meat_herbivore", meatAmount = 125, hideType = "hide_leathery", hideAmount = 90, boneType = "bone_mammal", boneAmount = 80, milkType = "milk_wild", milk = 60, tamingChance = 0.25, ferocity = 0, pvpBitmask = ATTACKABLE, creatureBitmask = PACK, optionsBitmask = AIENABLED, diet = CARNIVORE, templates = {"object/mobile/swirl_prong_hue.iff"}, hues = { 16, 17, 18, 19, 20, 21, 22, 23 }, lootGroups = {}, weapons = {}, conversationTemplate = "", attacks = { {"stunattack",""}, {"knockdownattack",""} } } CreatureTemplates:addCreatureTemplate(swirl_prong, "swirl_prong")
nilq/small-lua-stack
null
-- Linux kernel types local require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string = require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string -- TODO add __len to metatables of more local function init(types) local abi = require "syscall.abi" local t, pt, s, ctypes = types.t, types.pt, types.s, types.ctypes local ffi = require "ffi" local bit = require "syscall.bit" local h = require "syscall.helpers" local addtype, addtype_var, addtype_fn, addraw2 = h.addtype, h.addtype_var, h.addtype_fn, h.addraw2 local ptt, reviter, mktype, istype, lenfn, lenmt, getfd, newfn = h.ptt, h.reviter, h.mktype, h.istype, h.lenfn, h.lenmt, h.getfd, h.newfn local ntohl, ntohl, ntohs, htons = h.ntohl, h.ntohl, h.ntohs, h.htons local split, trim = h.split, h.trim local c = require "syscall.linux.constants" local mt = {} -- metatables -- TODO cleanup this (what should provide this?) local signal_reasons_gen = {} local signal_reasons = {} for k, v in pairs(c.SI) do signal_reasons_gen[v] = k end signal_reasons[c.SIG.ILL] = {} for k, v in pairs(c.SIGILL) do signal_reasons[c.SIG.ILL][v] = k end signal_reasons[c.SIG.FPE] = {} for k, v in pairs(c.SIGFPE ) do signal_reasons[c.SIG.FPE][v] = k end signal_reasons[c.SIG.SEGV] = {} for k, v in pairs(c.SIGSEGV) do signal_reasons[c.SIG.SEGV][v] = k end signal_reasons[c.SIG.BUS] = {} for k, v in pairs(c.SIGBUS) do signal_reasons[c.SIG.BUS][v] = k end signal_reasons[c.SIG.TRAP] = {} for k, v in pairs(c.SIGTRAP) do signal_reasons[c.SIG.TRAP][v] = k end signal_reasons[c.SIG.CHLD] = {} for k, v in pairs(c.SIGCLD) do signal_reasons[c.SIG.CHLD][v] = k end signal_reasons[c.SIG.POLL] = {} for k, v in pairs(c.SIGPOLL or {}) do signal_reasons[c.SIG.POLL][v] = k end local addtypes = { fdset = "fd_set", clockid = "clockid_t", sighandler = "sighandler_t", aio_context = "aio_context_t", clockid = "clockid_t", } local addstructs = { ucred = "struct ucred", sysinfo = "struct sysinfo", nlmsghdr = "struct nlmsghdr", rtgenmsg = "struct rtgenmsg", ifinfomsg = "struct ifinfomsg", ifaddrmsg = "struct ifaddrmsg", rtattr = "struct rtattr", rta_cacheinfo = "struct rta_cacheinfo", nlmsgerr = "struct nlmsgerr", nda_cacheinfo = "struct nda_cacheinfo", ndt_stats = "struct ndt_stats", ndtmsg = "struct ndtmsg", ndt_config = "struct ndt_config", utsname = "struct utsname", fdb_entry = "struct fdb_entry", seccomp_data = "struct seccomp_data", rtnl_link_stats = "struct rtnl_link_stats", statfs = "struct statfs64", ifa_cacheinfo = "struct ifa_cacheinfo", input_event = "struct input_event", input_id = "struct input_id", input_absinfo = "struct input_absinfo", input_keymap_entry = "struct input_keymap_entry", ff_replay = "struct ff_replay", ff_trigger = "struct ff_trigger", ff_envelope = "struct ff_envelope", ff_constant_effect = "struct ff_constant_effect", ff_ramp_effect = "struct ff_ramp_effect", ff_condition_effect = "struct ff_condition_effect", ff_periodic_effect = "struct ff_periodic_effect", ff_rumble_effect = "struct ff_rumble_effect", ff_effect = "struct ff_effect", sock_fprog = "struct sock_fprog", bpf_attr = "union bpf_attr", user_cap_header = "struct user_cap_header", user_cap_data = "struct user_cap_data", xt_get_revision = "struct xt_get_revision", vfs_cap_data = "struct vfs_cap_data", ucontext = "ucontext_t", mcontext = "mcontext_t", tun_pi = "struct tun_pi", tun_filter = "struct tun_filter", vhost_vring_state = "struct vhost_vring_state", vhost_vring_file = "struct vhost_vring_file", vhost_vring_addr = "struct vhost_vring_addr", vhost_memory_region = "struct vhost_memory_region", vhost_memory = "struct vhost_memory", scm_timestamping = "struct scm_timestamping", } for k, v in pairs(addtypes) do addtype(types, k, v) end for k, v in pairs(addstructs) do addtype(types, k, v, lenmt) end -- these ones not in table as not helpful with vararg or arrays TODO add more addtype variants t.inotify_event = ffi.typeof("struct inotify_event") pt.inotify_event = ptt("struct inotify_event") -- still need pointer to this pt.perf_event_header = ptt("struct perf_event_header") t.aio_context1 = ffi.typeof("aio_context_t[1]") t.sock_fprog1 = ffi.typeof("struct sock_fprog[1]") t.bpf_attr1 = ffi.typeof("union bpf_attr[1]") t.perf_event_attr1 = ffi.typeof("struct perf_event_attr[1]") t.user_cap_data2 = ffi.typeof("struct user_cap_data[2]") -- luaffi gets confused if call ffi.typeof("...[?]") it calls __new so redefine as functions local iocbs = ffi.typeof("struct iocb[?]") t.iocbs = function(n, ...) return ffi.new(iocbs, n, ...) end local sock_filters = ffi.typeof("struct sock_filter[?]") t.sock_filters = function(n, ...) return ffi.new(sock_filters, n, ...) end local bpf_insns = ffi.typeof("struct bpf_insn[?]") t.bpf_insns = function(n, ...) return ffi.new(bpf_insns, n, ...) end local iocb_ptrs = ffi.typeof("struct iocb *[?]") t.iocb_ptrs = function(n, ...) return ffi.new(iocb_ptrs, n, ...) end -- types with metatypes -- Note 32 bit dev_t; glibc has 64 bit dev_t but we use syscall API which does not local function makedev(major, minor) if type(major) == "table" then major, minor = major[1], major[2] end local dev = major or 0 if minor then dev = bit.bor(bit.lshift(bit.band(minor, 0xffffff00), 12), bit.band(minor, 0xff), bit.lshift(major, 8)) end return dev end mt.device = { index = { major = function(dev) local d = dev.dev return bit.band(bit.rshift(d, 8), 0x00000fff) end, minor = function(dev) local d = dev.dev return bit.bor(bit.band(d, 0x000000ff), bit.band(bit.rshift(d, 12), 0x000000ff)) end, device = function(dev) return tonumber(dev.dev) end, }, newindex = { device = function(dev, major, minor) dev.dev = makedev(major, minor) end, }, __new = function(tp, major, minor) return ffi.new(tp, makedev(major, minor)) end, } addtype(types, "device", "struct {dev_t dev;}", mt.device) mt.sockaddr = { index = { family = function(sa) return sa.sa_family end, }, } addtype(types, "sockaddr", "struct sockaddr", mt.sockaddr) -- cast socket address to actual type based on family, defined later local samap_pt = {} mt.sockaddr_storage = { index = { family = function(sa) return sa.ss_family end, }, newindex = { family = function(sa, v) sa.ss_family = c.AF[v] end, }, __index = function(sa, k) if mt.sockaddr_storage.index[k] then return mt.sockaddr_storage.index[k](sa) end local st = samap_pt[sa.ss_family] if st then local cs = st(sa) return cs[k] end error("invalid index " .. k) end, __newindex = function(sa, k, v) if mt.sockaddr_storage.newindex[k] then mt.sockaddr_storage.newindex[k](sa, v) return end local st = samap_pt[sa.ss_family] if st then local cs = st(sa) cs[k] = v return end error("invalid index " .. k) end, __new = function(tp, init) local ss = ffi.new(tp) local family if init and init.family then family = c.AF[init.family] end local st if family then st = samap_pt[family] ss.ss_family = family init.family = nil end if st then local cs = st(ss) for k, v in pairs(init) do cs[k] = v end end return ss end, -- netbsd likes to see the correct size when it gets a sockaddr; Linux was ok with a longer one __len = function(sa) if samap_pt[sa.family] then local cs = samap_pt[sa.family](sa) return #cs else return s.sockaddr_storage end end, } -- experiment, see if we can use this as generic type, to avoid allocations. addtype(types, "sockaddr_storage", "struct sockaddr_storage", mt.sockaddr_storage) mt.sockaddr_in = { index = { family = function(sa) return sa.sin_family end, port = function(sa) return ntohs(sa.sin_port) end, addr = function(sa) return sa.sin_addr end, }, newindex = { family = function(sa, v) sa.sin_family = v end, port = function(sa, v) sa.sin_port = htons(v) end, addr = function(sa, v) sa.sin_addr = mktype(t.in_addr, v) end, }, __new = function(tp, port, addr) if type(port) == "table" then return newfn(tp, port) end return newfn(tp, {family = c.AF.INET, port = port, addr = addr}) end, __len = function(tp) return s.sockaddr_in end, } addtype(types, "sockaddr_in", "struct sockaddr_in", mt.sockaddr_in) mt.sockaddr_in6 = { index = { family = function(sa) return sa.sin6_family end, port = function(sa) return ntohs(sa.sin6_port) end, addr = function(sa) return sa.sin6_addr end, }, newindex = { family = function(sa, v) sa.sin6_family = v end, port = function(sa, v) sa.sin6_port = htons(v) end, addr = function(sa, v) sa.sin6_addr = mktype(t.in6_addr, v) end, flowinfo = function(sa, v) sa.sin6_flowinfo = v end, scope_id = function(sa, v) sa.sin6_scope_id = v end, }, __new = function(tp, port, addr, flowinfo, scope_id) -- reordered initialisers. if type(port) == "table" then return newfn(tp, port) end return newfn(tp, {family = c.AF.INET6, port = port, addr = addr, flowinfo = flowinfo, scope_id = scope_id}) end, __len = function(tp) return s.sockaddr_in6 end, } addtype(types, "sockaddr_in6", "struct sockaddr_in6", mt.sockaddr_in6) -- we do provide this directly for compatibility, only use for standard names mt.sockaddr_un = { index = { family = function(sa) return sa.sun_family end, path = function(sa) return ffi.string(sa.sun_path) end, -- only valid for proper names }, newindex = { family = function(sa, v) sa.sun_family = v end, path = function(sa, v) ffi.copy(sa.sun_path, v) end, }, __new = function(tp, path) return newfn(tp, {family = c.AF.UNIX, path = path}) end, -- TODO accept table initialiser __len = function(tp) return s.sockaddr_un end, -- TODO lenfn (default) instead } addtype(types, "sockaddr_un", "struct sockaddr_un", mt.sockaddr_un) -- this is a bit odd, but we actually use Lua metatables for sockaddr_un, and use t.sa to multiplex -- basically the lINUX unix socket structure is not possible to interpret without size, but does not have size in struct -- nasty, but have not thought of a better way yet; could make an ffi type local lua_sockaddr_un_mt = { __index = function(un, k) local sa = un.addr if k == 'family' then return sa.family end local namelen = un.addrlen - s.sun_family if namelen > 0 then if sa.sun_path[0] == 0 then if k == 'abstract' then return true end if k == 'name' then return ffi.string(sa.sun_path, namelen) end -- should we also remove leading \0? else if k == 'name' then return ffi.string(sa.sun_path) end end else if k == 'unnamed' then return true end end end, __len = function(un) return un.addrlen end, } function t.sa(addr, addrlen) local family = addr.family if family == c.AF.UNIX then -- we return Lua metatable not metatype, as need length to decode local sa = t.sockaddr_un() ffi.copy(sa, addr, addrlen) return setmetatable({addr = sa, addrlen = addrlen}, lua_sockaddr_un_mt) end return addr end local nlgroupmap = { -- map from netlink socket type to group names. Note there are two forms of name though, bits and shifts. [c.NETLINK.ROUTE] = c.RTMGRP, -- or RTNLGRP_ and shift not mask TODO make shiftflags function -- add rest of these -- [c.NETLINK.SELINUX] = c.SELNLGRP, } mt.sockaddr_nl = { index = { family = function(sa) return sa.nl_family end, pid = function(sa) return sa.nl_pid end, groups = function(sa) return sa.nl_groups end, }, newindex = { pid = function(sa, v) sa.nl_pid = v end, groups = function(sa, v) sa.nl_groups = v end, }, __new = function(tp, pid, groups, nltype) if type(pid) == "table" then local tb = pid pid, groups, nltype = tb.nl_pid or tb.pid, tb.nl_groups or tb.groups, tb.type end if nltype and nlgroupmap[nltype] then groups = nlgroupmap[nltype][groups] end -- see note about shiftflags return ffi.new(tp, {nl_family = c.AF.NETLINK, nl_pid = pid, nl_groups = groups}) end, __len = function(tp) return s.sockaddr_nl end, } addtype(types, "sockaddr_nl", "struct sockaddr_nl", mt.sockaddr_nl) mt.sockaddr_ll = { index = { family = function(sa) return sa.sll_family end, protocol = function(sa) return ntohs(sa.sll_protocol) end, ifindex = function(sa) return sa.sll_ifindex end, hatype = function(sa) return sa.sll_hatype end, pkttype = function(sa) return sa.sll_pkttype end, halen = function(sa) return sa.sll_halen end, addr = function(sa) if sa.sll_halen == 6 then return pt.macaddr(sa.sll_addr) else return ffi.string(sa.sll_addr, sa.sll_halen) end end, }, newindex = { protocol = function(sa, v) sa.sll_protocol = htons(c.ETH_P[v]) end, ifindex = function(sa, v) sa.sll_ifindex = v end, hatype = function(sa, v) sa.sll_hatype = v end, pkttype = function(sa, v) sa.sll_pkttype = v end, halen = function(sa, v) sa.sll_halen = v end, addr = function(sa, v) if ffi.istype(t.macaddr, v) then sa.sll_halen = 6 ffi.copy(sa.sll_addr, v, 6) else sa.sll_addr = v end end, }, __new = function(tp, tb) local sa = ffi.new(tp, {sll_family = c.AF.PACKET}) for k, v in pairs(tb or {}) do sa[k] = v end return sa end, __len = function(tp) return s.sockaddr_ll end, } addtype(types, "sockaddr_ll", "struct sockaddr_ll", mt.sockaddr_ll) mt.stat = { index = { dev = function(st) return t.device(st.st_dev) end, ino = function(st) return tonumber(st.st_ino) end, mode = function(st) return st.st_mode end, nlink = function(st) return tonumber(st.st_nlink) end, uid = function(st) return st.st_uid end, gid = function(st) return st.st_gid end, size = function(st) return tonumber(st.st_size) end, blksize = function(st) return tonumber(st.st_blksize) end, blocks = function(st) return tonumber(st.st_blocks) end, atime = function(st) return tonumber(st.st_atime) end, ctime = function(st) return tonumber(st.st_ctime) end, mtime = function(st) return tonumber(st.st_mtime) end, rdev = function(st) return t.device(st.st_rdev) end, type = function(st) return bit.band(st.st_mode, c.S_I.FMT) end, todt = function(st) return bit.rshift(st.type, 12) end, isreg = function(st) return st.type == c.S_I.FREG end, isdir = function(st) return st.type == c.S_I.FDIR end, ischr = function(st) return st.type == c.S_I.FCHR end, isblk = function(st) return st.type == c.S_I.FBLK end, isfifo = function(st) return st.type == c.S_I.FIFO end, islnk = function(st) return st.type == c.S_I.FLNK end, issock = function(st) return st.type == c.S_I.FSOCK end, }, } -- add some friendlier names to stat, also for luafilesystem compatibility mt.stat.index.access = mt.stat.index.atime mt.stat.index.modification = mt.stat.index.mtime mt.stat.index.change = mt.stat.index.ctime local namemap = { file = mt.stat.index.isreg, directory = mt.stat.index.isdir, link = mt.stat.index.islnk, socket = mt.stat.index.issock, ["char device"] = mt.stat.index.ischr, ["block device"] = mt.stat.index.isblk, ["named pipe"] = mt.stat.index.isfifo, } mt.stat.index.typename = function(st) for k, v in pairs(namemap) do if v(st) then return k end end return "other" end addtype(types, "stat", "struct stat", mt.stat) local signames = {} local duplicates = {IOT = true, CLD = true, POLL = true} for k, v in pairs(c.SIG) do if not duplicates[k] then signames[v] = k end end -- TODO this is broken, need to use fields from the correct union technically -- ie check which of the unions we should be using and get all fields from that -- (note as per Musl list the standard kernel,glibc definitions are wrong too...) mt.siginfo = { index = { signo = function(s) return s.si_signo end, errno = function(s) return s.si_errno end, code = function(s) return s.si_code end, pid = function(s) return s._sifields.kill.si_pid end, uid = function(s) return s._sifields.kill.si_uid end, timerid = function(s) return s._sifields.timer.si_tid end, overrun = function(s) return s._sifields.timer.si_overrun end, status = function(s) return s._sifields.sigchld.si_status end, utime = function(s) return s._sifields.sigchld.si_utime end, stime = function(s) return s._sifields.sigchld.si_stime end, value = function(s) return s._sifields.rt.si_sigval end, int = function(s) return s._sifields.rt.si_sigval.sival_int end, ptr = function(s) return s._sifields.rt.si_sigval.sival_ptr end, addr = function(s) return s._sifields.sigfault.si_addr end, band = function(s) return s._sifields.sigpoll.si_band end, fd = function(s) return s._sifields.sigpoll.si_fd end, signame = function(s) return signames[s.signo] end, }, newindex = { signo = function(s, v) s.si_signo = v end, errno = function(s, v) s.si_errno = v end, code = function(s, v) s.si_code = v end, pid = function(s, v) s._sifields.kill.si_pid = v end, uid = function(s, v) s._sifields.kill.si_uid = v end, timerid = function(s, v) s._sifields.timer.si_tid = v end, overrun = function(s, v) s._sifields.timer.si_overrun = v end, status = function(s, v) s._sifields.sigchld.si_status = v end, utime = function(s, v) s._sifields.sigchld.si_utime = v end, stime = function(s, v) s._sifields.sigchld.si_stime = v end, value = function(s, v) s._sifields.rt.si_sigval = v end, int = function(s, v) s._sifields.rt.si_sigval.sival_int = v end, ptr = function(s, v) s._sifields.rt.si_sigval.sival_ptr = v end, addr = function(s, v) s._sifields.sigfault.si_addr = v end, band = function(s, v) s._sifields.sigpoll.si_band = v end, fd = function(s, v) s._sifields.sigpoll.si_fd = v end, }, } addtype(types, "siginfo", "struct siginfo", mt.siginfo) -- Linux internally uses non standard sigaction type k_sigaction local sa_handler_type = ffi.typeof("void (*)(int)") local to_handler = function(v) return ffi.cast(sa_handler_type, t.uintptr(v)) end -- luaffi needs uintptr, and full cast mt.sigaction = { index = { handler = function(sa) return sa.sa_handler end, sigaction = function(sa) return sa.sa_handler end, mask = function(sa) return sa.sa_mask end, -- TODO would rather return type of sigset_t flags = function(sa) return tonumber(sa.sa_flags) end, }, newindex = { handler = function(sa, v) if type(v) == "string" then v = to_handler(c.SIGACT[v]) end if type(v) == "number" then v = to_handler(v) end sa.sa_handler = v end, sigaction = function(sa, v) if type(v) == "string" then v = to_handler(c.SIGACT[v]) end if type(v) == "number" then v = to_handler(v) end sa.sa_handler.sa_sigaction = v end, mask = function(sa, v) if not ffi.istype(t.sigset, v) then v = t.sigset(v) end ffi.copy(sa.sa_mask, v, ffi.sizeof(sa.sa_mask)) end, flags = function(sa, v) sa.sa_flags = c.SA[v] end, }, __new = function(tp, tab) local sa = ffi.new(tp) if tab then for k, v in pairs(tab) do sa[k] = v end end if tab and tab.sigaction then sa.sa_flags = bit.bor(sa.flags, c.SA.SIGINFO) end -- this flag must be set if sigaction set return sa end, } addtype(types, "sigaction", "struct k_sigaction", mt.sigaction) mt.rlimit = { index = { cur = function(r) if r.rlim_cur == c.RLIM.INFINITY then return -1 else return tonumber(r.rlim_cur) end end, max = function(r) if r.rlim_max == c.RLIM.INFINITY then return -1 else return tonumber(r.rlim_max) end end, }, newindex = { cur = function(r, v) if v == -1 then v = c.RLIM.INFINITY end r.rlim_cur = c.RLIM[v] -- allows use of "infinity" end, max = function(r, v) if v == -1 then v = c.RLIM.INFINITY end r.rlim_max = c.RLIM[v] -- allows use of "infinity" end, }, __new = newfn, } -- TODO some fields still missing mt.sigevent = { index = { notify = function(self) return self.sigev_notify end, signo = function(self) return self.sigev_signo end, value = function(self) return self.sigev_value end, }, newindex = { notify = function(self, v) self.sigev_notify = c.SIGEV[v] end, signo = function(self, v) self.sigev_signo = c.SIG[v] end, value = function(self, v) self.sigev_value = t.sigval(v) end, -- auto assigns based on type }, __new = newfn, } addtype(types, "sigevent", "struct sigevent", mt.sigevent) addtype(types, "rlimit", "struct rlimit64", mt.rlimit) mt.signalfd = { index = { signo = function(ss) return tonumber(ss.ssi_signo) end, code = function(ss) return tonumber(ss.ssi_code) end, pid = function(ss) return tonumber(ss.ssi_pid) end, uid = function(ss) return tonumber(ss.ssi_uid) end, fd = function(ss) return tonumber(ss.ssi_fd) end, tid = function(ss) return tonumber(ss.ssi_tid) end, band = function(ss) return tonumber(ss.ssi_band) end, overrun = function(ss) return tonumber(ss.ssi_overrun) end, trapno = function(ss) return tonumber(ss.ssi_trapno) end, status = function(ss) return tonumber(ss.ssi_status) end, int = function(ss) return tonumber(ss.ssi_int) end, ptr = function(ss) return ss.ssi_ptr end, utime = function(ss) return tonumber(ss.ssi_utime) end, stime = function(ss) return tonumber(ss.ssi_stime) end, addr = function(ss) return ss.ssi_addr end, }, __index = function(ss, k) -- TODO simplify this local sig = c.SIG[k] if sig then return tonumber(ss.ssi_signo) == sig end local rname = signal_reasons_gen[ss.ssi_code] if not rname and signal_reasons[ss.ssi_signo] then rname = signal_reasons[ss.ssi_signo][ss.ssi_code] end if rname == k then return true end if rname == k:upper() then return true end -- TODO use some metatable to hide this? if mt.signalfd.index[k] then return mt.signalfd.index[k](ss) end error("invalid index " .. k) end, } addtype(types, "signalfd_siginfo", "struct signalfd_siginfo", mt.signalfd) mt.siginfos = { __index = function(ss, k) return ss.sfd[k - 1] end, __len = function(p) return p.count end, __new = function(tp, ss) return ffi.new(tp, ss, ss, ss * s.signalfd_siginfo) end, } addtype_var(types, "siginfos", "struct {int count, bytes; struct signalfd_siginfo sfd[?];}", mt.siginfos) -- TODO convert to use constants? note missing some macros eg WCOREDUMP(). Allow lower case. Also do not create table dynamically. mt.wait = { __index = function(w, k) local WTERMSIG = bit.band(w.status, 0x7f) local EXITSTATUS = bit.rshift(bit.band(w.status, 0xff00), 8) local WIFEXITED = (WTERMSIG == 0) local tab = { WIFEXITED = WIFEXITED, WIFSTOPPED = bit.band(w.status, 0xff) == 0x7f, WIFSIGNALED = not WIFEXITED and bit.band(w.status, 0x7f) ~= 0x7f -- I think this is right????? TODO recheck, cleanup } if tab.WIFEXITED then tab.EXITSTATUS = EXITSTATUS end if tab.WIFSTOPPED then tab.WSTOPSIG = EXITSTATUS end if tab.WIFSIGNALED then tab.WTERMSIG = WTERMSIG end if tab[k] then return tab[k] end local uc = 'W' .. k:upper() if tab[uc] then return tab[uc] end end } -- cannot use metatype as just an integer function t.waitstatus(status) return setmetatable({status = status}, mt.wait) end -- termios local bits_to_speed = {} for k, v in pairs(c.B) do bits_to_speed[v] = tonumber(k) end mt.termios = { makeraw = function(termios) termios.c_iflag = bit.band(termios.c_iflag, bit.bnot(c.IFLAG["IGNBRK,BRKINT,PARMRK,ISTRIP,INLCR,IGNCR,ICRNL,IXON"])) termios.c_oflag = bit.band(termios.c_oflag, bit.bnot(c.OFLAG["OPOST"])) termios.c_lflag = bit.band(termios.c_lflag, bit.bnot(c.LFLAG["ECHO,ECHONL,ICANON,ISIG,IEXTEN"])) termios.c_cflag = bit.bor(bit.band(termios.c_cflag, bit.bnot(c.CFLAG["CSIZE,PARENB"])), c.CFLAG.CS8) termios.c_cc[c.CC.VMIN] = 1 termios.c_cc[c.CC.VTIME] = 0 return true end, index = { iflag = function(termios) return termios.c_iflag end, oflag = function(termios) return termios.c_oflag end, cflag = function(termios) return termios.c_cflag end, lflag = function(termios) return termios.c_lflag end, makeraw = function(termios) return mt.termios.makeraw end, speed = function(termios) local bits = bit.band(termios.c_cflag, c.CBAUD) return bits_to_speed[bits] end, }, newindex = { iflag = function(termios, v) termios.c_iflag = c.IFLAG(v) end, oflag = function(termios, v) termios.c_oflag = c.OFLAG(v) end, cflag = function(termios, v) termios.c_cflag = c.CFLAG(v) end, lflag = function(termios, v) termios.c_lflag = c.LFLAG(v) end, speed = function(termios, speed) local speed = c.B[speed] termios.c_cflag = bit.bor(bit.band(termios.c_cflag, bit.bnot(c.CBAUD)), speed) end, }, } mt.termios.index.ospeed = mt.termios.index.speed mt.termios.index.ispeed = mt.termios.index.speed mt.termios.newindex.ospeed = mt.termios.newindex.speed mt.termios.newindex.ispeed = mt.termios.newindex.speed for k, i in pairs(c.CC) do mt.termios.index[k] = function(termios) return termios.c_cc[i] end mt.termios.newindex[k] = function(termios, v) termios.c_cc[i] = v end end addtype(types, "termios", "struct termios", mt.termios) addtype(types, "termios2", "struct termios2", mt.termios) mt.iocb = { index = { opcode = function(iocb) return iocb.aio_lio_opcode end, data = function(iocb) return tonumber(iocb.aio_data) end, reqprio = function(iocb) return iocb.aio_reqprio end, fildes = function(iocb) return iocb.aio_fildes end, -- do not convert to fd as will already be open, don't want to gc buf = function(iocb) return iocb.aio_buf end, nbytes = function(iocb) return tonumber(iocb.aio_nbytes) end, offset = function(iocb) return tonumber(iocb.aio_offset) end, resfd = function(iocb) return iocb.aio_resfd end, flags = function(iocb) return iocb.aio_flags end, }, newindex = { opcode = function(iocb, v) iocb.aio_lio_opcode = c.IOCB_CMD[v] end, data = function(iocb, v) iocb.aio_data = v end, reqprio = function(iocb, v) iocb.aio_reqprio = v end, fildes = function(iocb, v) iocb.aio_fildes = getfd(v) end, buf = function(iocb, v) iocb.aio_buf = ffi.cast(t.int64, pt.void(v)) end, nbytes = function(iocb, v) iocb.aio_nbytes = v end, offset = function(iocb, v) iocb.aio_offset = v end, flags = function(iocb, v) iocb.aio_flags = c.IOCB_FLAG[v] end, resfd = function(iocb, v) iocb.aio_flags = bit.bor(iocb.aio_flags, c.IOCB_FLAG.RESFD) iocb.aio_resfd = getfd(v) end, }, __new = newfn, } addtype(types, "iocb", "struct iocb", mt.iocb) -- aio operations want an array of pointers to struct iocb. To make sure no gc, we provide a table with array and pointers -- easiest to do as Lua table not ffi type. -- expects Lua table of either tables or iocb as input. can provide ptr table too -- TODO check maybe the implementation actually copies these? only the posix aio says you need to keep. t.iocb_array = function(tab, ptrs) local nr = #tab local a = {nr = nr, iocbs = {}, ptrs = ptrs or t.iocb_ptrs(nr)} for i = 1, nr do local iocb = tab[i] a.iocbs[i] = istype(t.iocb, iocb) or t.iocb(iocb) a.ptrs[i - 1] = a.iocbs[i] end return a end mt.sock_filter = { __new = function(tp, code, k, jt, jf) return ffi.new(tp, c.BPF[code], jt or 0, jf or 0, k or 0) end } addtype(types, "sock_filter", "struct sock_filter", mt.sock_filter) mt.bpf_insn = { __new = function(tp, code, dst_reg, src_reg, off, imm) return ffi.new(tp, c.BPF[code], dst_reg or 0, src_reg or 0, off or 0, imm or 0) end } addtype(types, "bpf_insn", "struct bpf_insn", mt.bpf_insn) -- capabilities data is an array so cannot put metatable on it. Also depends on version, so combine into one structure. -- TODO maybe add caching local function capflags(val, str) if not str then return val end if #str == 0 then return val end local a = h.split(",", str) for i, v in ipairs(a) do local s = h.trim(v):upper() if not c.CAP[s] then error("invalid capability " .. s) end val[s] = true end return val end mt.cap = { __index = function(cap, k) local ci = c.CAP[k] if not ci then error("invalid capability " .. k) end local i, shift = h.divmod(ci, 32) local mask = bit.lshift(1, shift) return bit.band(cap.cap[i], mask) ~= 0 end, __newindex = function(cap, k, v) if v == true then v = 1 elseif v == false then v = 0 end local ci = c.CAP[k] if not ci then error("invalid capability " .. k) end local i, shift = h.divmod(ci, 32) local mask = bit.bnot(bit.lshift(1, shift)) local set = bit.lshift(v, shift) cap.cap[i] = bit.bor(bit.band(cap.cap[i], mask), set) end, __tostring = function(cap) local tab = {} for k, _ in pairs(c.CAP) do if cap[k] then tab[#tab + 1] = k end end return table.concat(tab, ",") end, __new = function(tp, str) local cap = ffi.new(tp) if str then capflags(cap, str) end return cap end, } addtype(types, "cap", "struct cap", mt.cap) mt.capabilities = { hdrdata = function(cap) local hdr, data = t.user_cap_header(cap.version, cap.pid), t.user_cap_data2() data[0].effective, data[1].effective = cap.effective.cap[0], cap.effective.cap[1] data[0].permitted, data[1].permitted = cap.permitted.cap[0], cap.permitted.cap[1] data[0].inheritable, data[1].inheritable = cap.inheritable.cap[0], cap.inheritable.cap[1] return hdr, data end, index = { hdrdata = function(cap) return mt.capabilities.hdrdata end, }, __new = function(tp, hdr, data) local cap = ffi.new(tp, c.LINUX_CAPABILITY_VERSION[3], 0) if type(hdr) == "table" then if hdr.permitted then cap.permitted = t.cap(hdr.permitted) end if hdr.effective then cap.effective = t.cap(hdr.effective) end if hdr.inheritable then cap.inheritable = t.cap(hdr.inheritable) end cap.pid = hdr.pid or 0 if hdr.version then cap.version = c.LINUX_CAPABILITY_VERSION[hdr.version] end return cap end -- not passed a table if hdr then cap.version, cap.pid = hdr.version, hdr.pid end if data then cap.effective.cap[0], cap.effective.cap[1] = data[0].effective, data[1].effective cap.permitted.cap[0], cap.permitted.cap[1] = data[0].permitted, data[1].permitted cap.inheritable.cap[0], cap.inheritable.cap[1] = data[0].inheritable, data[1].inheritable end return cap end, __tostring = function(cap) local str = "" for nm, capt in pairs{permitted = cap.permitted, inheritable = cap.inheritable, effective = cap.effective} do str = str .. nm .. ": " str = str .. tostring(capt) .. "\n" end return str end, } addtype(types, "capabilities", "struct capabilities", mt.capabilities) -- difficult to sanely use an ffi metatype for inotify events, so use Lua table mt.inotify_events = { __index = function(tab, k) if c.IN[k] then return bit.band(tab.mask, c.IN[k]) ~= 0 end error("invalid index " .. k) end } t.inotify_events = function(buffer, len) local off, ee = 0, {} while off < len do local ev = pt.inotify_event(buffer + off) local le = setmetatable({wd = ev.wd, mask = ev.mask, cookie = ev.cookie}, mt.inotify_events) if ev.len > 0 then le.name = ffi.string(ev.name) end ee[#ee + 1] = le off = off + ffi.sizeof(t.inotify_event(ev.len)) end return ee end -- TODO for input should be able to set modes automatically from which fields are set. mt.timex = { __new = function(tp, a) if type(a) == 'table' then if a.modes then a.modes = c.ADJ[a.modes] end if a.status then a.status = c.STA[a.status] end return ffi.new(tp, a) end return ffi.new(tp) end, } addtype(types, "timex", "struct timex", mt.timex) -- not sane to convert to ffi metatype, only used as adjtimex needs to return ret and a struct mt.adjtimex = { __index = function(timex, k) if c.TIME[k] then return timex.state == c.TIME[k] end return nil end } t.adjtimex = function(ret, timex) return setmetatable({state = ret, timex = timex}, mt.adjtimex) end mt.epoll_event = { index = { fd = function(e) return tonumber(e.data.fd) end, u64 = function(e) return e.data.u64 end, u32 = function(e) return e.data.u32 end, ptr = function(e) return e.data.ptr end, }, newindex = { fd = function(e, v) e.data.fd = v end, u64 = function(e, v) e.data.u64 = v end, u32 = function(e, v) e.data.u32 = v end, ptr = function(e, v) e.data.ptr = v end, }, __new = function(tp, a) local e = ffi.new(tp) if a then if type(a) == "string" then a.events = c.EPOLL[a] else if a.events then a.events = c.EPOLL[a.events] end for k, v in pairs(a) do e[k] = v end end end return e end, } for k, v in pairs(c.EPOLL) do mt.epoll_event.index[k] = function(e) return bit.band(e.events, v) ~= 0 end end addtype(types, "epoll_event", "struct epoll_event", mt.epoll_event) mt.epoll_events = { __len = function(ep) return ep.count end, __new = function(tp, n) return ffi.new(tp, n, n) end, __ipairs = function(ep) return reviter, ep.ep, ep.count end } addtype_var(types, "epoll_events", "struct {int count; struct epoll_event ep[?];}", mt.epoll_events) mt.io_event = { index = { error = function(ev) if (ev.res < 0) then return t.error(-ev.res) end end, } } addtype(types, "io_event", "struct io_event", mt.io_event) mt.io_events = { __len = function(evs) return evs.count end, __new = function(tp, n) return ffi.new(tp, n, n) end, __ipairs = function(evs) return reviter, evs.ev, evs.count end } addtype_var(types, "io_events", "struct {int count; struct io_event ev[?];}", mt.io_events) mt.cpu_set = { index = { zero = function(set) ffi.fill(set, s.cpu_set) end, set = function(set, cpu) if type(cpu) == "table" then -- table is an array of CPU numbers eg {1, 2, 4} for i = 1, #cpu do set:set(cpu[i]) end return set end local d = bit.rshift(cpu, 5) -- 5 is 32 bits set.val[d] = bit.bor(set.val[d], bit.lshift(1, cpu % 32)) return set end, clear = function(set, cpu) if type(cpu) == "table" then -- table is an array of CPU numbers eg {1, 2, 4} for i = 1, #cpu do set:clear(cpu[i]) end return set end local d = bit.rshift(cpu, 5) -- 5 is 32 bits set.val[d] = bit.band(set.val[d], bit.bnot(bit.lshift(1, cpu % 32))) return set end, get = function(set, cpu) local d = bit.rshift(cpu, 5) -- 5 is 32 bits return bit.band(set.val[d], bit.lshift(1, cpu % 32)) ~= 0 end, -- TODO add rest of interface from man(3) CPU_SET }, __index = function(set, k) if mt.cpu_set.index[k] then return mt.cpu_set.index[k] end if type(k) == "number" then return set:get(k) end error("invalid index " .. k) end, __newindex = function(set, k, v) if type(k) ~= "number" then error("invalid index " .. k) end if v then set:set(k) else set:clear(k) end end, __new = function(tp, tab) local set = ffi.new(tp) if tab then set:set(tab) end return set end, __tostring = function(set) local tab = {} for i = 0, s.cpu_set * 8 - 1 do if set:get(i) then tab[#tab + 1] = i end end return "{" .. table.concat(tab, ",") .. "}" end, } addtype(types, "cpu_set", "struct cpu_set_t", mt.cpu_set) local ulong_bit_count = ffi.sizeof('unsigned long') * 8 local function ulong_index_and_bit(n) local i = math.floor(n / ulong_bit_count) local b = bit.lshift(1ULL, n - i * ulong_bit_count) return i, b end mt.bitmask = { index = { zero = function(mask) ffi.fill(mask, s.bitmask) end, set = function(mask, node) if type(node) == "table" then -- table is an array of node numbers eg {1, 2, 4} for i = 1, #node do mask:set(node[i]) end return mask end if node >= mask.size then error("numa node too large " .. node) end local i, b = ulong_index_and_bit(node) mask.mask[i] = bit.bor(mask.mask[i], b) return mask end, clear = function(mask, node) if type(node) == "table" then -- table is an array of node numbers eg {1, 2, 4} for i = 1, #node do mask:clear(node[i]) end return mask end if node < mask.size then local i, b = ulong_index_and_bit(node) mask.mask[i] = bit.band(mask.mask[i], bit.bnot(b)) end return mask end, get = function(mask, node) local i, b = ulong_index_and_bit(node) if node >= mask.size then return false end return bit.band(mask.mask[i], b) ~= 0 end, }, __index = function(mask, k) if mt.bitmask.index[k] then return mt.bitmask.index[k] end if type(k) == "number" then return mask:get(k) end error("invalid index " .. k) end, __newindex = function(mask, k, v) if type(k) ~= "number" then error("invalid index " .. k) end if v then mask:set(k) else mask:clear(k) end end, __new = function(tp, tab, size) -- Round size to multiple of ulong bit count. if size then size = bit.band(size + ulong_bit_count - 1, bit.bnot(ulong_bit_count - 1)) else size = ulong_bit_count end local mask = ffi.new(tp, size / ulong_bit_count, size) if tab then mask:set(tab) end return mask end, __tostring = function(mask) local tab = {} for i = 0, tonumber(mask.size - 1) do if mask:get(i) then tab[#tab + 1] = i end end return "{" .. table.concat(tab, ",") .. "}" end, } addtype_var(types, "bitmask", "struct {unsigned long size; unsigned long mask[?];}", mt.bitmask) mt.mq_attr = { index = { flags = function(mqa) return tonumber(mqa.mq_flags) end, maxmsg = function(mqa) return tonumber(mqa.mq_maxmsg) end, msgsize = function(mqa) return tonumber(mqa.mq_msgsize) end, curmsgs = function(mqa) return tonumber(mqa.mq_curmsgs) end, }, newindex = { flags = function(mqa, v) mqa.mq_flags = c.OMQATTR[v] end, -- only allows O.NONBLOCK maxmsg = function(mqa, v) mqa.mq_maxmsg = v end, msgsize = function(mqa, v) mqa.mq_msgsize = v end, -- no sense in writing curmsgs }, __new = newfn, } addtype(types, "mq_attr", "struct mq_attr", mt.mq_attr) mt.ifreq = { index = { name = function(ifr) return ffi.string(ifr.ifr_ifrn.ifrn_name) end, addr = function(ifr) return ifr.ifr_ifru.ifru_addr end, dstaddr = function(ifr) return ifr.ifr_ifru.ifru_dstaddr end, broadaddr = function(ifr) return ifr.ifr_ifru.ifru_broadaddr end, netmask = function(ifr) return ifr.ifr_ifru.ifru_netmask end, hwaddr = function(ifr) return ifr.ifr_ifru.ifru_hwaddr end, flags = function(ifr) return ifr.ifr_ifru.ifru_flags end, ivalue = function(ifr) return ifr.ifr_ifru.ifru_ivalue end, -- TODO rest of fields }, newindex = { name = function(ifr, v) assert(#v <= c.IFNAMSIZ, "name too long") ifr.ifr_ifrn.ifrn_name = v end, flags = function(ifr, v) ifr.ifr_ifru.ifru_flags = c.IFREQ[v] end, ivalue = function(ifr, v) ifr.ifr_ifru.ifru_ivalue = v end, -- TODO rest of fields }, __new = newfn, } addtype(types, "ifreq", "struct ifreq", mt.ifreq) -- note t.dirents iterator is defined in common types local d_name_offset = ffi.offsetof("struct linux_dirent64", "d_name") -- d_name is at end of struct mt.dirent = { index = { ino = function(self) return tonumber(self.d_ino) end, off = function(self) return self.d_off end, reclen = function(self) return self.d_reclen end, name = function(self) return ffi.string(pt.char(self) + d_name_offset) end, type = function(self) return self.d_type end, toif = function(self) return bit.lshift(self.d_type, 12) end, -- convert to stat types }, __len = function(self) return self.d_reclen end, } -- TODO previously this allowed lower case values, but this static version does not -- could add mt.dirent.index[tolower(k)] = mt.dirent.index[k] but need to do consistently elsewhere for k, v in pairs(c.DT) do mt.dirent.index[k] = function(self) return self.type == v end end addtype(types, "dirent", "struct linux_dirent64", mt.dirent) mt.rtmsg = { index = { family = function(self) return tonumber(self.rtm_family) end, }, newindex = { family = function(self, v) self.rtm_family = c.AF[v] end, protocol = function(self, v) self.rtm_protocol = c.RTPROT[v] end, type = function(self, v) self.rtm_type = c.RTN[v] end, scope = function(self, v) self.rtm_scope = c.RT_SCOPE[v] end, flags = function(self, v) self.rtm_flags = c.RTM_F[v] end, table = function(self, v) self.rtm_table = c.RT_TABLE[v] end, dst_len = function(self, v) self.rtm_dst_len = v end, src_len = function(self, v) self.rtm_src_len = v end, tos = function(self, v) self.rtm_tos = v end, }, __new = newfn, } addtype(types, "rtmsg", "struct rtmsg", mt.rtmsg) mt.ndmsg = { index = { family = function(self) return tonumber(self.ndm_family) end, }, newindex = { family = function(self, v) self.ndm_family = c.AF[v] end, state = function(self, v) self.ndm_state = c.NUD[v] end, flags = function(self, v) self.ndm_flags = c.NTF[v] end, type = function(self, v) self.ndm_type = v end, -- which lookup? ifindex = function(self, v) self.ndm_ifindex = v end, }, __new = newfn, } addtype(types, "ndmsg", "struct ndmsg", mt.ndmsg) mt.sched_param = { __new = function(tp, v) -- allow positional parameters as only first is ever used local obj = ffi.new(tp) obj.sched_priority = v or 0 return obj end, } addtype(types, "sched_param", "struct sched_param", mt.sched_param) mt.flock = { index = { type = function(self) return self.l_type end, whence = function(self) return self.l_whence end, start = function(self) return self.l_start end, len = function(self) return self.l_len end, pid = function(self) return self.l_pid end, }, newindex = { type = function(self, v) self.l_type = c.FCNTL_LOCK[v] end, whence = function(self, v) self.l_whence = c.SEEK[v] end, start = function(self, v) self.l_start = v end, len = function(self, v) self.l_len = v end, pid = function(self, v) self.l_pid = v end, }, __new = newfn, } addtype(types, "flock", "struct flock64", mt.flock) mt.mmsghdr = { index = { hdr = function(self) return self.msg_hdr end, len = function(self) return self.msg_len end, }, newindex = { hdr = function(self, v) self.hdr = v end, }, __new = newfn, } addtype(types, "mmsghdr", "struct mmsghdr", mt.mmsghdr) mt.mmsghdrs = { __len = function(p) return p.count end, __new = function(tp, ps) if type(ps) == 'number' then return ffi.new(tp, ps, ps) end local count = #ps local mms = ffi.new(tp, count, count) for n = 1, count do mms.msg[n - 1].msg_hdr = mktype(t.msghdr, ps[n]) end return mms end, __ipairs = function(p) return reviter, p.msg, p.count end -- TODO want forward iterator really... } addtype_var(types, "mmsghdrs", "struct {int count; struct mmsghdr msg[?];}", mt.mmsghdrs) addtype(types, "bpf_attr", "union bpf_attr") -- Metatype for Linux perf events mt.perf_event_attr = { index = { type = function(self) return self.pe_type end, config = function(self) return self.pe_config end, sample_type = function(self) return self.pe_sample_type end, }, newindex = { type = function(self, v) self.pe_type = c.PERF_TYPE[v] end, config = function(self, v) self.pe_config = c.PERF_COUNT[v] end, sample_type = function(self, v) self.pe_sample_type = c.PERF_SAMPLE[v] end, }, } addtype(types, "perf_event_attr", "struct perf_event_attr", mt.perf_event_attr) -- this is declared above samap_pt = { [c.AF.UNIX] = pt.sockaddr_un, [c.AF.INET] = pt.sockaddr_in, [c.AF.INET6] = pt.sockaddr_in6, [c.AF.NETLINK] = pt.sockaddr_nl, [c.AF.PACKET] = pt.sockaddr_ll, } return types end return {init = init}
nilq/small-lua-stack
null
local core=require"hashsi.core" local M={} local meta={} local function next_closure(self) local index=0 local id=rawget(self,"__id") return function() local key,val index,key,val=core.next(id,index) return key,val end end meta.__index=function(self,k) return core.get(rawget(self,"__id"),k) end meta.__newindex=function(self,k,v) --if not v then return end return core.set(rawget(self,"__id"),k,v) end meta.__pairs=function(self) return next_closure(self),self,nil end function M.count(t) return core.count(rawget(t,"__id")) end function M.init(conf) local list={} local size=0 for k,v in pairs(conf) do if v.id>size then size=v.id end assert(list[v.id]==nil,"id exist:"..v.id) list[v.id]=v.max end assert(size==#list) core.init(list) end function M.table(id) assert(type(id)=="number" or type(id)=="string") return setmetatable({__id=id},meta) end return M
nilq/small-lua-stack
null
require("colorbuddy").setup() -- Run this line to turn function calls yellow Group.new('luaFunctionCall', c.yellow) -- Run this line to turn function calls blue Group.new('luaFunctionCall', c.blue)
nilq/small-lua-stack
null
--[[ MIT License Copyright (c) 2021 Christophe MICHEL 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. ]] local ADDON_NAME, SJ = ... local L = LibStub("AceLocale-3.0"):GetLocale(ADDON_NAME, true) -- upvalues for frequent API calls local isQuestCompleted = C_QuestLog.IsQuestFlaggedCompleted local function isarray(t) return type(t) == "table" and #t > 0 end local DatabaseMixin = { } function DatabaseMixin:Sort() -- For the moment default to natural order on names table.sort(self.soulshapes, function(left, right) return left.name < right.name end) end function DatabaseMixin:Update() for _, soulshape in ipairs(self.soulshapes) do soulshape.collected = soulshape.collected or self:IsCollected(soulshape) end end function DatabaseMixin:CountTotal() return #self.soulshapes end function DatabaseMixin:CountCollected() local collected = 0 for _, soulshape in ipairs(self.soulshapes) do if soulshape.collected then collected = collected + 1 end end return collected end function DatabaseMixin:AddUntrackable(soulshape) if soulshape.untrackable then SJ.saved.char.collectedUntrackable[soulshape.untrackable] = true return true end return false end function DatabaseMixin:IsCollected(soulshape) if soulshape.questID then return isQuestCompleted(soulshape.questID) else return soulshape.untrackable and SJ.saved.char.collectedUntrackable[soulshape.untrackable] end end local function CostFormatter(cost) if not isarray(cost) then cost = { cost } end rendered = {} for _, currency in ipairs(cost) do if currency.custom then -- FIXME Find a better way to handle regular items as currencies? tinsert(rendered, (currency.amount and currency.amount or "") .. currency.custom) elseif currency.gold then tinsert(rendered, GetCoinTextureString(currency.gold * 10000)) else local info = C_CurrencyInfo.GetBasicCurrencyInfo(currency.id, currency.amount) tinsert(rendered, info.displayAmount .. "|T" .. info.icon .. ":0|t") end end return table.concat(rendered, " ") end local function FactionFormatter(faction) local name if faction.id then name, _ = GetFactionInfoByID(faction.id) else -- We can't fetch all factions by id because GetFactionInfoByID will return nil -- on convenant-specific factions when the player has currently chosen another covenant name = faction.name end if faction.level then local genderSuffix = UnitSex("player") == 3 and "_FEMALE" or "" local levelString = _G["FACTION_STANDING_LABEL" .. faction.level .. genderSuffix] return string.format("%s - %s", name, levelString) end end local function CampaignQuestFormatter(quest) return "|A:quest-campaign-available:12:12|a" .. quest end local function Label(name) if GetLocale() == "frFR" then -- French typography requires a space after colons return format("|cffffd100%s :|r ", name) else return format("|cffffd100%s:|r ", name) end end local function JoiningFormatter(values) if isarray(values) then return table.concat(values, ", ") end return values end local function Item(icon, name, rarity) return format("|T%d:0|t%s", icon, rarity:WrapTextInColorCode(name)) end local function CreateSourceString(soulshape) local source = {} function addMultiLine(value, renderer) if value then if isarray(value) then for _, entry in ipairs(value) do renderer(entry) end else renderer(value) end end end function addLine(label, value, transformation) if value then if transformation then value = transformation(value) end tinsert(source, Label(label) .. value) end end function renderVendor(vendor) addLine(L["Vendor"], vendor.name) addLine(L["Region"], vendor.region) addLine(L["Cost"], vendor.cost, CostFormatter) end addLine(L["Loot"], soulshape.loot) addLine(L["Quest"], soulshape.quest) addLine(L["Quest"], soulshape.campaignQuest, CampaignQuestFormatter) addLine(L["Campaign"], soulshape.campaign) addLine(L["World Event"], soulshape.worldEvent) addLine(L["World Quest"], soulshape.worldQuest) addLine(L["NPC"], soulshape.npc) addLine(L["Profession"], soulshape.profession) addLine(L["Region"], soulshape.region) addLine(L["Cost"], soulshape.cost, CostFormatter) addLine(L["Faction"], soulshape.faction, FactionFormatter) addMultiLine(soulshape.vendor, renderVendor) addLine(L["Covenant Feature"], soulshape.covenantFeature) addLine(L["Difficulty"], soulshape.difficulty, JoiningFormatter) addLine(L["Renown"], soulshape.renown) addLine(L["Spell"], soulshape.spell) return table.concat(source, "\n") end local function CreateGuideString(soulshape) local guide = soulshape.guide if type(guide) == "table" and guide.text and guide.args and isarray(guide.args) then return string.format(guide.text, unpack(guide.args)) else return guide end end --- Concats and transforms to lowercase all searchable text related to a soulshape. local function CreateSearchText(soulshape) local guide = soulshape.guide or "" local values = { soulshape.name:lower(), soulshape.source:lower(), guide:lower() } return table.concat(values, " ") end --- Filters soulshapes from a future build local function RemoveUpcomingSoulshapes(soulshapes) local function GetBuildNumber() local _, buildNumber = GetBuildInfo() return tonumber(buildNumber) end local currentSoulshapes = {} local currentBuild = GetBuildNumber() for _, soulshape in ipairs(soulshapes) do if not soulshape.buildNumber or soulshape.buildNumber <= currentBuild then table.insert(currentSoulshapes, soulshape) end end return currentSoulshapes end local function CreateLocations(soulshape) if soulshape.pinData then soulshape.pins = {} soulshape.maps = {} local addedMaps = {} for _, pin in ipairs(soulshape.pinData) do local mapID = pin[1] if not addedMaps[mapID] then tinsert(soulshape.maps, { mapID, SJ:GetMapName(mapID) }) addedMaps[mapID] = true end tinsert(soulshape.pins, { mapID = mapID, x = pin[2], y = pin[3], creatureDisplayID = pin[4], iconID = pin[5], label = pin[6], details = pin[7], }) end soulshape.pinData = nil end end local function ResolveRegion(soulshape) local function ResolveRegionForVendor(vendor) if vendor and vendor.zoneID then vendor.region = SJ:GetMapName(vendor.zoneID) vendor.zoneID = nil end end if soulshape.zoneID then soulshape.region = SJ:GetMapName(soulshape.zoneID) soulshape.zoneID = nil end if isarray(soulshape.vendor) then for _,v in ipairs(soulshape.vendor) do ResolveRegionForVendor(v) end else ResolveRegionForVendor(soulshape.vendor) end end local PIN_DATA_OLEA_MANU = { { 1970, 37.0, 44.6, 101851, nil, L["Olea Manu"], L["Olea Manu Tooltip"] } } local function CreateDatabase() local soulshapes = { { name = L["Alpaca Soul"], loot = L["Shadowlands World Bosses"], questID = 65010, icon = 2061352, model = 103074, scale = 3.5, buildNumber = SJ.BUILD_9_1_5, }, { name = L["Ardenmoth Soul"], campaignQuest = L["Drust and Ashes"], campaign = L["Drust and Ashes"], renown = 22, questID = 62422, icon = 3255388, model = 96511, modelSceneID = 34, buildNumber = SJ.BUILD_9_0, }, { name = L["Boar Soul"], worldEvent = L["Warlords of Draenor Timewalking"], guide = L["Boar Soul Guide"], questID = 65025, icon = 1044799, model = 103082, scale = 3, buildNumber = SJ.BUILD_9_1_5, }, { name = L["Bunny Soul"], worldQuest = L["Pet Battle"], zoneID = 1550, guide = L["Bunny Soul Guide"], critter = true, questID = 64984, icon = 2399274, model = 102364, scale = 4, buildNumber = SJ.BUILD_9_1_5, }, { name = L["Cat Soul"], npc = L["Lost Soul"], zoneID = 1565, guide = L["Cat Soul Guide"], pinData = { { 1565, 37.6, 36.2, 103084, nil, L["Lost Soul"], nil }, { 1565, 51.2, 31, 103084, nil, L["Lost Soul"], nil }, { 1565, 65, 36.4, 103084, nil, L["Lost Soul"], nil }, { 1565, 60, 55, 103084, nil, L["Lost Soul"], nil }, { 1565, 51.8, 69.2, 103084, nil, L["Lost Soul"], nil }, }, critter = true, questID = 64961, icon = 656574, model = 103084, buildNumber = SJ.BUILD_9_1_5, }, { name = L["Cat Soul (Well Fed)"], npc = L["Ma'oh"], zoneID = 1565, guide = L["Cat Soul (Well Fed) Guide"], pinData = { { 1702, 58, 69, 103084, nil, L["Ma'oh"], nil }, { 1525, 63.7, 61.6, nil, 134058, L["Spectral Feed"], L["Spectral Feed Tooltip"] } }, critter = true, questID = 64982, icon = 656577, model = 100636, scale = 4, buildNumber = SJ.BUILD_9_1_5, }, { name = L["Chicken Soul"], npc = L["Lost Soul"], zoneID = 1525, pinData = { { 1525, 63.18, 42.76, 102363, nil, L["Lost Soul"], nil }, { 1525, 63.7, 61.6, nil, 134058, L["Spectral Feed"], L["Spectral Feed Tooltip"] } }, guide = L["Chicken Soul Guide"], critter = true, questID = 64941, icon = 2027864, model = 102363, scale = 4, buildNumber = SJ.BUILD_9_1_5, }, { name = L["Cloud Serpent Soul"], worldEvent = L["Mists of Pandaria Timewalking"], guide = L["Cloud Serpent Soul Guide"], questID = 65024, icon = 1247267, model = 103080, scale = 6, buildNumber = SJ.BUILD_9_1_5, }, { name = L["Cobra Soul"], loot = PLAYER_V_PLAYER, guide = L["Cobra Soul Guide"], questID = 64651, icon = 2399271, model = 96525, scale = 4, buildNumber = SJ.BUILD_9_1, }, { name = L["Corgi Soul"], npc = L["Sparkle"], zoneID = 1565, guide = L["Corgi Soul Guide"], critter = true, questID = 64938, icon = 1339013, model = 100634, scale = 4, buildNumber = SJ.BUILD_9_1_5, }, { name = L["Crane Soul"], faction = { id = 2465, level = 6 }, vendor = { { name = L["Aithlyn"], zoneID = 1565, cost = { id = 1813, amount = 2500 }, }, { name = L["Liawyn"], zoneID = 1670, cost = { id = 1813, amount = 2500 }, } }, pinData = { { 1701, 59.6, 32.6, 99153, nil, L["Aithlyn"], nil }, { 1670, 47.0, 76.8, 99156, nil, L["Liawyn"], nil } }, questID = 62424, icon = 605484, model = 96519, scale = 4, buildNumber = SJ.BUILD_9_0, }, { name = L["Cricket Soul"], vendor = { name = L["Spindlenose"], zoneID = 1565, cost = { { id = 1813, amount = 15000 }, { id = 1885, amount = 25 }, }, }, pinData = { { 1565, 59.6, 52.8, 99751, nil, L["Spindlenose"], nil }, }, critter = true, questID = 64990, icon = 646325, model = 103069, scale = 4, buildNumber = SJ.BUILD_9_1_5, }, { name = L["Direhorn Soul"], loot = L["The Grand Menagerie"], zoneID = 1990, questID = 63607, icon = 791593, model = 100626, scale = 5, buildNumber = SJ.BUILD_9_1, }, { name = L["Eagle Soul"], vendor = { name = L["Master Clerk Salorn"], zoneID = 1565, cost = { id = 1813, amount = 20000 }, }, pinData = { { 1565, 43.0, 47.0, 99767, nil, L["Master Clerk Salorn"], nil }, }, questID = 65021, icon = 132172, model = 103076, modelSceneID = 34, buildNumber = SJ.BUILD_9_1_5, }, { name = L["Equine Soul"], campaignQuest = L["Mending a Broken Hart"], campaign = L["Night Warrior's Curse"], renown = 11, questID = 62428, icon = 2153980, model = 96517, scale = 4.5, buildNumber = SJ.BUILD_9_0, }, { name = L["Frog Soul"], profession = PROFESSIONS_FISHING, zoneID = 1550, guide = L["Frog Soul Guide"], critter = true, questID = 64994, icon = 2399262, model = 100638, scale = 4, buildNumber = SJ.BUILD_9_1_5, }, { name = L["Goat Soul"], loot = L["Covenant Callings reward chests"], zoneID = 1550, guide = L["Goat Soul Guide"], questID = 65008, icon = 877477, model = 103072, scale = 3, buildNumber = SJ.BUILD_9_1_5, }, { name = L["Gryphon Soul"], loot = PLAYER_V_PLAYER, guide = L["Gryphon Soul Guide"], questID = 62426, icon = 537515, model = 96539, scale = 5.5, buildNumber = SJ.BUILD_9_0, }, { name = L["Gulper Soul"], loot = L["Queen's Conservatory Cache"], covenantFeature = L["Queen's Conservatory"], guide = { text = L["Gulper Soul Guide"], args = { Item(960671, L["Wildseed Root Grain"], EPIC_PURPLE_COLOR) }, }, questID = 62421, icon = 2481372, model = 97394, scale = 3, buildNumber = SJ.BUILD_9_0, }, { name = L["Hippo Soul"], loot = Item(3753378, L["War Chest of the Wild Hunt"], RARE_BLUE_COLOR), zoneID = 1543, guide = L["Hippo Soul Guide"], questID = 63608, icon = 1044490, model = 100627, scale = 3.4, buildNumber = SJ.BUILD_9_1, }, { name = L["Hippogryph Soul"], campaignQuest = L["The Power of Elune"], campaign = L["The Power of Night"], renown = 54, questID = 62427, icon = 1455896, model = 96538, scale = 4.5, buildNumber = SJ.BUILD_9_1, }, { name = L["Hyena Soul"], loot = L["Mythic+ dungeons"], guide = L["Hyena Soul Guide"], questID = 64650, icon = 132190, model = 96524, scale = 4, buildNumber = SJ.BUILD_9_1, }, { name = L["Jormungar Soul"], worldEvent = L["Wrath of the Lich King Timewalking"], guide = L["Jormungar Soul Guide"], questID = 65023, icon = 1531518, model = 103079, scale = 5, buildNumber = SJ.BUILD_9_1_5, }, { name = L["Kodo Soul"], worldEvent = L["Cataclysm Timewalking"], guide = L["Kodo Soul Guide"], questID = 63609, icon = 132243, model = 100629, scale = 5, buildNumber = SJ.BUILD_9_0_5, }, { name = L["Leonine Soul"], faction = { id = 2464, level = 5 }, vendor = { name = L["Spindlenose"], zoneID = 1565, cost = { { id = 1813, amount = 1500 }, { id = 1885, amount = 5 }, }, }, pinData = { { 1565, 59.6, 52.8, 99751, nil, L["Spindlenose"], nil }, }, questID = 62429, icon = 464140, model = 96520, scale = 5.5, buildNumber = SJ.BUILD_9_0, }, { name = L["Lupine Soul"], faction = { id = 2464, level = 5 }, vendor = { name = L["Spindlenose"], zoneID = 1565, cost = { { id = 1813, amount = 1500 }, { id = 1885, amount = 5 }, }, }, pinData = { { 1565, 59.6, 52.8, 99751, nil, L["Spindlenose"], nil }, }, questID = 62438, icon = 464162, model = 96534, scale = 5, buildNumber = SJ.BUILD_9_0, }, { name = L["Mammoth Soul"], loot = Item(3753378, L["Wild Hunt Supplies"], RARE_BLUE_COLOR), faction = { id = 2465, level = 8 }, guide = L["Paragon reward."], questID = 63610, icon = 236240, model = 100630, buildNumber = SJ.BUILD_9_1_5, }, { name = L["Moose Soul"], vendor = { name = L["Master Clerk Salorn"], zoneID = 1565, cost = { id = 1813, amount = 1500 }, }, guide = L["Moose Soul Guide"], pinData = { { 1565, 43.0, 47.0, 99767, nil, L["Master Clerk Salorn"], nil }, }, questID = 62430, icon = 1390637, model = 96533, buildNumber = SJ.BUILD_9_0, }, { name = L["Otter Soul"], npc = L["Lost Soul"], zoneID = 1533, guide = L["Otter Soul Guide"], pinData = { { 1533, 49.8, 46.8, 100637, nil, L["Lost Soul"], nil }, }, critter = true, questID = 64959, icon = 645906, model = 100637, scale = 4, buildNumber = SJ.BUILD_9_1_5, }, { name = L["Owl Soul"], worldEvent = L["Legion Timewalking"], guide = L["Owl Soul Guide"], questID = 65026, icon = 1387709, model = 103083, modelSceneID = 34, buildNumber = SJ.BUILD_9_1_5, }, { name = L["Owlcat Soul"], loot = L["Lady Sylvanas Windrunner"], zoneID = 2002, difficulty = L["Heroic"], questID = 62432, icon = 132192, model = 96529, scale = 5.5, buildNumber = SJ.BUILD_9_1, }, { name = L["Porcupine Soul"], loot = Item(3753378, L["Wild Hunt Supplies"], RARE_BLUE_COLOR), faction = { id = 2465, level = 8 }, guide = L["Paragon reward."], critter = true, questID = 64989, icon = 838549, model = 100640, buildNumber = SJ.BUILD_9_1_5, }, { name = L["Prairie Dog Soul"], vendor = { name = L["Master Clerk Salorn"], zoneID = 1565, cost = { id = 1813, amount = 10000 }, }, pinData = { { 1565, 43.0, 47.0, 99767, nil, L["Master Clerk Salorn"], nil }, }, critter = true, questID = 64992, icon = 656176, model = 103070, scale = 6.5, buildNumber = SJ.BUILD_9_1_5, }, { name = L["Ram Soul"], vendor = { name = L["Spindlenose"], zoneID = 1565, cost = { { id = 1813, amount = 25000 }, { id = 1885, amount = 50 }, }, }, pinData = { { 1565, 59.6, 52.8, 99751, nil, L["Spindlenose"], nil }, }, questID = 65009, icon = 132248, model = 103075, buildNumber = SJ.BUILD_9_1_5, }, { name = L["Raptor Soul"], loot = L["Mueh'Zala"], zoneID = 1680, difficulty = L["Any"], questID = 62433, icon = 838683, model = 96531, scale = 5, buildNumber = SJ.BUILD_9_0, }, { name = L["Rat Soul"], vendor = { name = L["Shopkeeper"], zoneID = 1989, cost = { { gold = 750 }, { custom = Item(1542861, L["Synvir Lockbox"], UNCOMMON_GREEN_COLOR), amount = 2 }, { custom = Item(1542849, L["Stygian Lockbox"], UNCOMMON_GREEN_COLOR), amount = 2 }, }, }, guide = L["Rat Soul Guide"], critter = true, questID = 64985, icon = 647701, model = 100639, scale = 5, buildNumber = SJ.BUILD_9_1_5, }, { name = L["Runestag Soul"], loot = L["Mystic Rainbowhorn"], zoneID = 1565, guide = L["Runestag Soul Guide"], questID = 62434, icon = 3087326, model = 95614, buildNumber = SJ.BUILD_9_0, }, { name = L["Saurid Soul"], npc = L["Lost Soul"], zoneID = 1536, guide = L["Saurid Soul Guide"], pinData = { { 1536, 44.8, 67.8, 103067, nil, L["Lost Soul"], nil }, }, critter = true, questID = 64995, icon = 2399239, model = 103067, buildNumber = SJ.BUILD_9_1_5, }, { name = L["Saurolisk Hatchling Soul"], loot = L["The Adamant Vaults"], zoneID = 1833, critter = true, questID = 64993, icon = 2027844, model = 97505, scale = 3, buildNumber = SJ.BUILD_9_1_5, }, { name = L["Saurolisk Soul"], loot = L["The Adamant Vaults"], zoneID = 1833, questID = 63605, icon = 2027929, model = 100624, scale = 5, buildNumber = SJ.BUILD_9_0_5, }, { name = L["Shadowstalker Soul"], loot = L["Valfir the Unrelenting"], zoneID = 1565, pinData = { { 1565, 30.6, 55.0, 96087, nil, L["Valfir the Unrelenting"], nil }, }, questID = 62431, icon = 2475038, model = 96530, scale = 5.5, buildNumber = SJ.BUILD_9_0, }, { name = L["Shoveltusk Soul"], loot = PLAYER_V_PLAYER, guide = L["Shoveltusk Soul Guide"], questID = 63604, icon = 134060, model = 100623, scale = 4, buildNumber = SJ.BUILD_9_1_5, }, { name = L["Shrieker Soul"], loot = L["Mistcaller"], zoneID = 1669, difficulty = L["Any"], questID = 62436, icon = 952507, model = 96518, scale = 5, buildNumber = SJ.BUILD_9_0, }, { name = L["Snake Soul"], loot = L["Covenant Callings reward chests"], zoneID = 1550, guide = L["Goat Soul Guide"], critter = true, questID = 64988, icon = 2399227, model = 103068, scale = 4, buildNumber = SJ.BUILD_9_1_5, }, { name = L["Snapper Soul"], loot = L["Queen's Conservatory Cache"], covenantFeature = L["Queen's Conservatory"], guide = { text = L["Gulper Soul Guide"], -- not a typo, same as Gulper args = { Item(960671, L["Wildseed Root Grain"], EPIC_PURPLE_COLOR) }, }, questID = 62420, icon = 1339043, model = 96527, scale = 4, buildNumber = SJ.BUILD_9_0, }, { name = L["Spider Soul"], loot = L["Riftbound Cache"], zoneID = 1961, guide = { text = L["Spider Soul Guide"], args = { Item(528693, L["Repaired Riftkey"], UNCOMMON_GREEN_COLOR) }, }, questID = 63606, icon = 2027946, model = 100625, scale = 4, buildNumber = SJ.BUILD_9_1, }, { name = L["Sporebat Soul"], worldEvent = L["Burning Crusade Timewalking"], guide = L["Sporebat Soul Guide"], questID = 65022, icon = 132197, model = 103078, buildNumber = SJ.BUILD_9_1_5, }, { name = L["Stag Soul"], quest = L["Night Fae dailies"], zoneID = 1961, guide = L["Stag Soul Guide"], questID = 62435, icon = 1396983, model = 96528, buildNumber = SJ.BUILD_9_1, }, { name = L["Squirrel Soul"], spell = L["Soulshape"], zoneID = 1565, guide = L["Squirrel Soul Guide"], critter = true, icon = 3749003, model = 100635, scale = 5, collected = true, buildNumber = SJ.BUILD_9_1_5, }, { name = L["Tiger Soul"], faction = { name = L["Marasmius"], level = 5 }, vendor = { name = L["Cortinarius"], zoneID = 1819, cost = { id = 1813, amount = 1500 }, }, questID = 62437, icon = 620832, model = 96521, scale = 5.5, buildNumber = SJ.BUILD_9_0, }, { name = L["Turkey Soul"], worldEvent = L["Pilgrim's Bounty"], guide = L["Turkey Soul Guide"], critter = true, questID = 65467, icon = 250626, model = 105220, scale = 3, buildNumber = SJ.BUILD_9_1_5, }, { name = L["Ursine Soul"], faction = { name = L["Marasmius"], level = 5 }, vendor = { name = L["Cortinarius"], zoneID = 1819, cost = { id = 1813, amount = 1500 }, }, questID = 62423, icon = 132183, model = 96532, scale = 4.5, buildNumber = SJ.BUILD_9_0, }, { name = L["Veilwing Soul"], loot = L["Sire Denathrius"], zoneID = 1747, difficulty = { L["Heroic"], L["Mythic"] }, questID = 62425, icon = 303867, model = 96535, scale = 5.5, buildNumber = SJ.BUILD_9_0, }, { name = L["Vulpine Soul"], spell = L["Soulshape"], guide = L["Vulpine Soul Guide"], icon = 3586268, model = 93949, scale = 5, collected = true, buildNumber = SJ.BUILD_9_0, }, { name = L["Wolfhawk Soul"], loot = L["Skuld Vit"], zoneID = 1565, guide = L["Wolfhawk Soul Guide"], pinData = { { 1565, 36.9, 60.2, 96776, nil, L["Skuld Vit"], nil }, }, questID = 62439, icon = 1279719, model = 96537, scale = 5.5, buildNumber = SJ.BUILD_9_0, }, { name = L["Wyvern Soul"], loot = PLAYER_V_PLAYER, guide = L["Gryphon Soul Guide"], -- not a typo, same as Gryphon questID = 62440, icon = 537531, model = 96540, scale = 5.5, buildNumber = SJ.BUILD_9_0, }, { name = L["Yak Soul"], loot = L["So'leah"], zoneID = 1993, difficulty = L["Hardmode"], questID = 63603, icon = 900317, model = 100622, scale = 4, buildNumber = SJ.BUILD_9_1, }, -- 9.2 Soulshapes { name = L["Armadillo Soul"], vendor = { name = L["Olea Manu"], zoneID = 1970, cost = { id = 1979, amount = 500 }, }, pinData = PIN_DATA_OLEA_MANU, questID = 65514, icon = 464159, model = 105260, critter = true, buildNumber = SJ.BUILD_9_2, }, { name = L["Bat Soul"], npc = L["Lost Soul"], zoneID = 1833, guide = L["Torghast 9.2 Soulshape Guide"], questID = 65509, icon = 132182, model = 105256, modelSceneID = 34, buildNumber = SJ.BUILD_9_2, }, { name = L["Bee Soul"], loot = L["Lost Comb"], zoneID = 1970, guide = L["Bee Soul Guide"], pinData = { { 1970, 63.3, 60.6, nil, 3066348, L["Lost Comb"], nil } }, questID = 65518, icon = 2027853, model = 105264, modelSceneID = 34, buildNumber = SJ.BUILD_9_2, }, { name = L["Brutosaur Soul"], vendor = { name = L["Olea Manu"], zoneID = 1970, cost = { id = 1979, amount = 1000 }, }, pinData = PIN_DATA_OLEA_MANU, questID = 65510, icon = 1881827, model = 105257, scale = 5, buildNumber = SJ.BUILD_9_2, }, { name = L["Cervid Soul"], loot = L["Prototype Pantheon"], difficulty = L["Heroic"], zoneID = 2049, questID = 65640, icon = 3747644, model = 105366, buildNumber = SJ.BUILD_9_2, }, { name = L["Dragonhawk Soul"], npc = L["Lost Soul"], zoneID = 1833, guide = L["Torghast 9.2 Soulshape Guide"], questID = 65504, icon = 132188, model = 105251, modelSceneID = 34, buildNumber = SJ.BUILD_9_2, }, { name = L["Elekk Soul"], npc = L["Lost Soul"], zoneID = 1833, guide = L["Torghast 9.2 Soulshape Guide"], questID = 65507, icon = 132254, model = 105254, scale = 4, buildNumber = SJ.BUILD_9_2, }, { name = L["Gromit Soul"], loot = L["Shrouded Cypher Cache"], guide = L["Gromit Soul Guide"], zoneID = 1970, pinData = { { 1970, 36.3, 48.1, nil, 4066374, L["Shrouded Cypher Cache"], L["Shrouded Cypher Cache Tooltip"] }, { 1970, 40.3, 62.7, nil, 4066374, L["Shrouded Cypher Cache"], L["Shrouded Cypher Cache Tooltip"] }, { 1970, 43.9, 84.2, nil, 4066374, L["Shrouded Cypher Cache"], L["Shrouded Cypher Cache Tooltip"] }, { 1970, 54.5, 77.8, nil, 4066374, L["Shrouded Cypher Cache"], L["Shrouded Cypher Cache Tooltip"] }, }, questID = 65513, icon = 3931157, model = 105259, buildNumber = SJ.BUILD_9_2, }, { name = L["Penguin Soul"], npc = L["Lost Soul"], guide = L["Penguin Soul Guide"], zoneID = 1970, pinData = { { 1970, 31.48, 50.42, 105263, nil, L["Lost Soul"], nil } }, coordinates = { x = 31.48, y = 50.42 }, questID = 65517, icon = 655866, model = 105263, buildNumber = SJ.BUILD_9_2, }, { name = L["Pig Soul"], npc = L["Lost Soul"], zoneID = 1833, guide = L["Torghast 9.2 Soulshape Guide"], questID = 65515, icon = 1721030, model = 105261, critter = true, buildNumber = SJ.BUILD_9_2, }, { name = L["Ray Soul"], loot = Item(4066374, L["Enlightened Broker Supplies"], RARE_BLUE_COLOR), faction = { id = 2478, level = 8 }, guide = L["Paragon reward."], zoneID = 1970, questID = 65506, icon = 2620775, model = 105253, modelSceneID = 34, buildNumber = SJ.BUILD_9_2, }, { name = L["Scorpid Soul"], loot = L["Shifting Stargorger"], zoneID = 1970, pinData = { { 1970, 42.2, 21.6, 101916, nil, L["Shifting Stargorger"], nil } }, questID = 65505, icon = 132195, model = 105252, buildNumber = SJ.BUILD_9_2, }, { name = L["Sheep Soul"], npc = L["Lost Soul"], guide = L["Sheep Soul Guide"], zoneID = 1970, pinData = { { 1970, 37.2, 34.2, 105262, nil, L["Lost Soul"], nil }, { 1970, 37.6, 77.0, 105262, nil, L["Lost Soul"], nil }, { 1970, 44.0, 79.8, 105262, nil, L["Lost Soul"], nil }, { 1970, 49.9, 80.1, 105262, nil, L["Lost Soul"], nil }, { 1970, 38.6, 80.6, 105262, nil, L["Lost Soul"], nil }, { 1970, 38.6, 80.6, 105262, nil, L["Lost Soul"], nil }, { 1970, 38.2, 71.8, 105262, nil, L["Lost Soul"], nil }, { 1970, 30.6, 67.2, 105262, nil, L["Lost Soul"], nil }, { 1970, 58.4, 75.0, 105262, nil, L["Lost Soul"], nil }, }, questID = 65516, icon = 136071, model = 105262, buildNumber = SJ.BUILD_9_2, }, { name = L["Silithid Soul"], loot = L["The Jailer"], difficulty = L["Heroic"], zoneID = 2051, questID = 65512, icon = 1623378, model = 105258, buildNumber = SJ.BUILD_9_2, }, { name = L["Snail Soul"], loot = L["High Value Cache"], difficulty = { L["Normal"], L["Heroic"], L["Mythic"] }, zoneID = 2061, guide = L["Snail Soul Guide"], pinData = { { 2061, 24.5, 36.9, nil, 4062292, L["High Value Cache"], L["High Value Cache Tooltip"] }, { 2061, 20.5, 40, 98515, nil, L["Taskmaster Xy'pro"], L["Taskmaster Xy'pro Tooltip"] }, }, questID = 65519, icon = 2530489, model = 105265, critter = true, buildNumber = SJ.BUILD_9_2, }, { name = L["Tallstrider Soul"], npc = L["Lost Soul"], zoneID = 1833, guide = L["Torghast 9.2 Soulshape Guide"], questID = 65508, icon = 132198, model = 105255, buildNumber = SJ.BUILD_9_2, }, } -- This is a safety against showing soulshapes from a future build soulshapes = RemoveUpcomingSoulshapes(soulshapes) -- Generate source and guide fields for soulshapes for _, soulshape in ipairs(soulshapes) do ResolveRegion(soulshape) CreateLocations(soulshape) soulshape.source = CreateSourceString(soulshape) soulshape.guide = CreateGuideString(soulshape) soulshape.searchText = CreateSearchText(soulshape) end SJ.Database = CreateFromMixins({ soulshapes = soulshapes, }, DatabaseMixin) end SJ.CreateDatabase = function() CreateDatabase() SJ.Database:Sort() end
nilq/small-lua-stack
null
-- -- Please see the license.html file included with this distribution for -- attribution and copyright information. -- -- Some values to cache to reduce processing local isMisc = false; local sNotePath = nil; local widget = nil; local sMiscFieldName = nil; -- NOTE: We purposely do not define onInit() as it appears doing so overrides some other low-level template's onInit() -- and then the number field does not function properly. Use onFirstLayout() instead. function onFirstLayout() if super and super.onFirstLayout then super.onFirstLayout() end -- We aren't doing anything with read-only fields. if isReadOnly() then return false; end -- If it is a field with "misc" in its name, then continue processing. local name = self.getName(); if name:find("misc",1,true) then -- Figure out where to store the misc note. We can't just append it onto the existing DB path -- as it could be contained within a structure that something else is parsing and relying on the exact format. -- -- So... we will create a new XML section called "miscnotes" for the char (PC or NPC cohort) and then use -- the existing path to the misc value to mimic its unique position in the list of "miscnotes". isMisc = true; local sPath = DB.getPath(self.getDatabaseNode()); -- First check for cohorts, then regular PC if no cohort found local sCharSheetPath, sMiscPath = sPath:match("^(charsheet%..+%.cohorts%.id%-%d+)%.(.-)$"); if not sCharSheetPath then sCharSheetPath, sMiscPath = sPath:match("^(charsheet.id%-%d+)%.(.-)$"); end -- Only add the widget if this is a charsheet node. if sCharSheetPath then sMiscFieldName = sMiscPath; sNotePath = sCharSheetPath .. ".miscnotes." .. sMiscPath; -- Get the path to where the note should be in the database. local dbNode = DB.findNode(sNotePath .. ".text"); local sNoteText = ""; if dbNode then sNoteText = dbNode.getText(); end -- If the note exists, show the tooltip, and set the appropriate widget for status. if sNoteText and sNoteText ~= "" then widget = addBitmapWidget("combobox_button_active"); setTooltipText(sNoteText); else widget = addBitmapWidget("combobox_button"); setTooltipText("CTRL-click to add note."); end widget.setPosition("bottomright", 0, 0); end -- We want to get notified whenever the value of the note changes. DB.addHandler(DB.getPath(sNotePath), "onChildUpdate", sourceupdate); end end function onClose() DB.removeHandler(DB.getPath(sNotePath), "onChildUpdate", sourceupdate); end function sourceupdate() if self.onSourceUpdate() then self.onSourceUpdate(); end end function onSourceUpdate() -- We got notifed the note changed, so fetch the text -- and update the note's status icon and tooltip. local dbNode = DB.findNode(sNotePath .. ".text"); local sNoteText = ""; -- If the status icon already exists, destroy it. We'll recreate it. -- TODO: Would it be more efficient to have both widgets always present and just toggle their visibility? -- How much memory does a widget take at runtime? if widget then widget.destroy(); widget = nil; end -- TODO: this is duplicate code from the end of onFirstLayout - make a common function. if dbNode then sNoteText = dbNode.getText(); end if sNoteText and sNoteText ~= "" then widget = addBitmapWidget("combobox_button_active"); setTooltipText(sNoteText); else widget = addBitmapWidget("combobox_button"); setTooltipText("CTRL-click to add note."); end widget.setPosition("bottomright", 0, 0); end function onClickDown(button, x, y) -- Always return nil so lower level controls continue to process the click. -- If this is not done, then you can never click to set the focus of the field -- for typing values. local returnCode = nil; if super and super.onClickDown then returnCode = super.onClickDown(button, x, y); end -- Bail if not what we want if (not isMisc) or isReadOnly() or (not Input.isControlPressed()) then return returnCode; end if button and button == 1 then local w = Interface.openWindow("misc_note", sNotePath); w.title.setValue(sMiscFieldName); return nil; end return returnCode; end
nilq/small-lua-stack
null
-- ========== THIS IS AN AUTOMATICALLY GENERATED FILE! ========== PlaceObj('StoryBit', { ActivationEffects = {}, Category = "Tick_FounderStageDone", Effects = { PlaceObj('ForEachExecuteEffects', { 'Label', "Colonist", 'Filters', {}, 'RandomPercent', 20, 'Effects', { PlaceObj('ModifyObject', { 'Prop', "base_morale", 'Amount', "<morale_boost>", 'Sols', "<morale_boost_duration>", 'ModifyId', "MultiplanetSpecies", }), }, }), }, Enabled = true, Image = "UI/Messages/Events/07_explorer_flag.tga", Prerequisites = { PlaceObj('IsSponsors', { 'Sponsors', { "Brazil", "IMM", "NewArk", "SpaceY", }, }), PlaceObj('CheckObjectCount', { 'Label', "Colonist", 'Filters', {}, 'Condition', ">=", 'Amount', 1000, }), }, ScriptDone = true, Text = T(415338252937, --[[StoryBit MultiplanetSpecies Text]] "As the commander of the Colony, you have been awarded with a lifetime award for your achievements.\n\nSpeech, speech!"), TextReadyForValidation = true, TextsDone = true, Title = T(369698469654, --[[StoryBit MultiplanetSpecies Title]] "Multi-planetary Species"), VoicedText = T(680814829271, --[[voice:narrator]] "Thanks to your ongoing efforts, humanity's foothold on Mars has been cemented. "), group = "Sponsor", id = "MultiplanetSpecies", qa_info = PlaceObj('PresetQAInfo', { data = { { action = "Modified", time = 1552477358, user = "Momchil", }, }, }), PlaceObj('StoryBitReply', { 'Text', T(107842659681, --[[StoryBit MultiplanetSpecies Text]] "This honor is not my own. All our brave colonists routinely risk their lives to make our dream a reality."), }), PlaceObj('StoryBitReply', { 'Text', T(838483919945, --[[StoryBit MultiplanetSpecies Text]] "Our success on Mars is a stepping stone on humanity's path towards the Cosmos!"), }), PlaceObj('StoryBitReply', { 'Text', T(657981397745, --[[StoryBit MultiplanetSpecies Text]] "I hope we have the wisdom to avoid the mistakes of the past as we move forward."), }), PlaceObj('StoryBitReply', { 'Text', T(121358935731, --[[StoryBit MultiplanetSpecies Text]] "Human ingenuity knows no bounds. Colonizing Mars is our collective success as a species."), 'Prerequisite', PlaceObj('IsCommander', { 'CommanderProfile', "author", }), }), PlaceObj('StoryBitReply', { 'Text', T(104549427575, --[[StoryBit MultiplanetSpecies Text]] "Built in the human psyche is that no veil will be left unlifted, no secret will remain unknown. "), 'Prerequisite', PlaceObj('IsCommander', { 'CommanderProfile', "psychologist", }), }), PlaceObj('StoryBitParamNumber', { 'Name', "morale_boost", 'Value', 20, }), PlaceObj('StoryBitParamSols', { 'Name', "morale_boost_duration", 'Value', 7200000, }), })
nilq/small-lua-stack
null
-------------------------------- -- @module CameraBackgroundBrush -- @extend Ref -- @parent_module cc -------------------------------- -- get brush type<br> -- return BrushType -- @function [parent=#CameraBackgroundBrush] getBrushType -- @param self -- @return int#int ret (return value: int) -------------------------------- -- draw the background -- @function [parent=#CameraBackgroundBrush] drawBackground -- @param self -- @param #cc.Camera -- @return CameraBackgroundBrush#CameraBackgroundBrush self (return value: cc.CameraBackgroundBrush) -------------------------------- -- -- @function [parent=#CameraBackgroundBrush] init -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- -- @function [parent=#CameraBackgroundBrush] isValid -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- Creates a Skybox brush with 6 textures.<br> -- param positive_x texture for the right side of the texture cube face.<br> -- param negative_x texture for the up side of the texture cube face.<br> -- param positive_y texture for the top side of the texture cube face<br> -- param negative_y texture for the bottom side of the texture cube face<br> -- param positive_z texture for the forward side of the texture cube face.<br> -- param negative_z texture for the rear side of the texture cube face.<br> -- return A new brush inited with given parameters. -- @function [parent=#CameraBackgroundBrush] createSkyboxBrush -- @param self -- @param #string positive_x -- @param #string negative_x -- @param #string positive_y -- @param #string negative_y -- @param #string positive_z -- @param #string negative_z -- @return CameraBackgroundSkyBoxBrush#CameraBackgroundSkyBoxBrush ret (return value: cc.CameraBackgroundSkyBoxBrush) -------------------------------- -- Creates a color brush<br> -- param color Color of brush<br> -- param depth Depth used to clear depth buffer<br> -- return Created brush -- @function [parent=#CameraBackgroundBrush] createColorBrush -- @param self -- @param #color4f_table color -- @param #float depth -- @return CameraBackgroundColorBrush#CameraBackgroundColorBrush ret (return value: cc.CameraBackgroundColorBrush) -------------------------------- -- Creates a none brush, it does nothing when clear the background<br> -- return Created brush. -- @function [parent=#CameraBackgroundBrush] createNoneBrush -- @param self -- @return CameraBackgroundBrush#CameraBackgroundBrush ret (return value: cc.CameraBackgroundBrush) -------------------------------- -- Creates a depth brush, which clears depth buffer with a given depth.<br> -- param depth Depth used to clear depth buffer<br> -- return Created brush -- @function [parent=#CameraBackgroundBrush] createDepthBrush -- @param self -- @return CameraBackgroundDepthBrush#CameraBackgroundDepthBrush ret (return value: cc.CameraBackgroundDepthBrush) -------------------------------- -- -- @function [parent=#CameraBackgroundBrush] CameraBackgroundBrush -- @param self -- @return CameraBackgroundBrush#CameraBackgroundBrush self (return value: cc.CameraBackgroundBrush) return nil
nilq/small-lua-stack
null
set = {2, 2, 2, 3, 3, 5} dim = 6 enum = {} denom = {} whl = {} enum_p = {} value = {} qq = {} reply = {""} choice = math.random(4) for i = 1,2 do qq = lib.math.random_shuffle(set) index = 1 + math.random(2) denom[i] = 1 for j = 1,index do if (i == choice and qq[j] == 3) then denom[i] = denom[i] * 5; else denom[i] = denom[i] * qq[j]; end end enum[i] = 1 + math.random(5*denom[i] - 1); value[i] = enum[i] / denom[i] end aver = (value[1] + value[2])/2 for i = 1,2 do q = lib.math.gcd(enum[i], denom[i]) enum[i] = enum[i]/q denom[i] = denom[i]/q whl[i] = math.floor(enum[i]/denom[i]) enum_p[i] = enum[i] - denom[i] * whl[i] end imenilac = 2 * denom[1] * denom[2] brojilac = enum[1] * denom[2] + enum[2] * denom[1] g = lib.math.gcd(imenilac, brojilac) broj = brojilac/ g imen = imenilac / g ceo = math.floor(broj/imen) broj = broj - ceo * imen out = "" if (choice < 3) then chind = 3 for j = 1,3 do temp = value[choice] * 10^(4-j) if (lib.math.round(temp) == temp) then chind = 4-j end end out = lib.dec_to_str(lib.math.round_dec(value[choice], chind)) end for i = 1,2 do reply[i] = "" if (i == choice) then reply[i] = out else if (whl[i] ~= 0) then reply[i] = reply[i] .. whl[i] end if (enum_p[i] ~= 0) then reply[i] = reply[i] .. "\(\frac{" .. tostring(math.floor(enum_p[i])) .. "}{" .. tostring(math.floor(denom[i])) .. "}\)" end end end ans = "" if (ceo == 0) then condition = "is_ok = math.eq(numerator/denominator, "..tostring(aver)..");" sln = "numerator="..tostring(broj)..";denominator="..tostring(imen)..";" ans = lib.check_fraction_condition(condition, nil, nil, sln) else if (broj == 0) then ans = lib.check_number(ceo,20) else condition = "is_ok = math.eq(whole + numerator/denominator, "..tostring(aver)..");" sln = "numerator="..tostring(broj)..";denominator="..tostring(imen)..";whole="..tostring(ceo)..";" ans = lib.check_fraction_condition(condition, true, nil, sln) end end
nilq/small-lua-stack
null
local mod = DBM:NewMod("d288", "DBM-WorldEvents", 1) local L = mod:GetLocalizedStrings() mod:SetRevision(("$Revision: 17278 $"):sub(12, -3)) mod:SetCreatureID(36272, 36296, 36565) mod:SetModelID(16176) mod:SetZone() mod:SetReCombatTime(10) mod:RegisterCombat("combat") mod:RegisterEvents( "CHAT_MSG_MONSTER_SAY" ) mod:RegisterEventsInCombat( "SPELL_CAST_START 68821", "SPELL_PERIODIC_DAMAGE 68927 68934", "SPELL_PERIODIC_MISSED 68927 68934" ) local warnChainReaction = mod:NewCastAnnounce(68821, 3, nil, nil, "Melee", 2) local specWarnGTFO = mod:NewSpecialWarningGTFO(68927, nil, nil, nil, 1, 2) local timerHummel = mod:NewTimer(10.5, "HummelActive", "Interface\\Icons\\ability_warrior_offensivestance", nil, false, "TrioActiveTimer") local timerBaxter = mod:NewTimer(17.5, "BaxterActive", "Interface\\Icons\\ability_warrior_offensivestance", nil, false, "TrioActiveTimer") local timerFrye = mod:NewTimer(25.5, "FryeActive", "Interface\\Icons\\ability_warrior_offensivestance", nil, false, "TrioActiveTimer") mod:AddBoolOption("TrioActiveTimer", true, "timer", nil, 1) local timerChainReaction = mod:NewCastTimer(3, 68821, nil, "Melee") function mod:SPELL_CAST_START(args) if args.spellId == 68821 then warnChainReaction:Show() timerChainReaction:Start() end end function mod:SPELL_PERIODIC_DAMAGE(_, _, _, _, destGUID, _, _, _, spellId, spellName) if (spellId == 68927 or spellId == 68934) and destGUID == UnitGUID("player") and self:AntiSpam() then specWarnGTFO:Show(spellName) specWarnGTFO:Play("runaway") end end mod.SPELL_PERIODIC_MISSED = mod.SPELL_PERIODIC_DAMAGE function mod:CHAT_MSG_MONSTER_SAY(msg) if msg == L.SayCombatStart or msg:find(L.SayCombatStart) then self:SendSync("TrioPulled") end end function mod:OnSync(msg) if msg == "TrioPulled" then if self.Options.TrioActiveTimer then timerHummel:Start() timerBaxter:Start() timerFrye:Start() end end end
nilq/small-lua-stack
null
------------------------ -- Object class -- The parent class from which all other classes are derived. See the [middleclass documentation](https://github.com/kikito/middleclass/wiki) for more information. -- @cl Object -- THIS IS A FAKE IMPLEMENTATION JUST TO ASSIST DOCUMENTATION GENERATION. DO NOT INCLUDE IN THE FRAMEWORK. --- @type Object local Object = class("Object") --- Returns if object is an instance of the specified class. -- @tparam class class -- @treturn bool function Object:isInstanceOf( class ) end --- Returns if object is in a subclass of the specified class. -- @tparam class class -- @treturn bool function Object:isSubclassOf( class ) end --- Returns true if this object uses this mixin. -- @tparam Mixin mixin -- @treturn bool function Object:includes( mixin ) end
nilq/small-lua-stack
null
rRoot = getResourceRootElement(getThisResource()) --- function onMTstart() outputDebugString("Started AUR driver mission") -- setUpMarkers() -- -- MISSION_TIME = MISSION_TIME_MIN * 60 * 1000 tFlood = {} -- end addEventHandler("onResourceStart",rRoot,onMTstart) function requestDx() if ( DXTEXT == true and DXTEXT_MAX_DISTINANCE and transPosz and type(transPosz) == "table" ) then triggerClientEvent(source,"startDxDrawing",source,transPosz,DXTEXT_MAX_DISTINANCE) end end addEvent("requestDx",true) addEventHandler("requestDx",root,requestDx) function setUpMarkers() transMarkers = {} if ( transPosz and type(transPosz) == "table" ) then for k,v in ipairs ( transPosz ) do x,y,z = v[1],v[2],v[3] createBlip(x,y,z,42,1,255,255,0,255) if ( x and y and z ) then transMarkers[k] = createMarker(x,y,z,MARKER_TYPE,MARKER_SIZE,255,255,0,100) if ( transMarkers[k] ) then function onHit(hitter) if ( hitter and getElementType(hitter) == "player" ) then if not tFlood[hitter] == true then if not missionOn then showTransWin(hitter) else exports.NGCdxmsg:createNewDxMessage(hitter,"This mission is not available now.",255,255,255,true) end else exports.NGCdxmsg:createNewDxMessage(hitter,"You can't do the mission now, try again later!",255,255,255,true) end end end addEventHandler("onMarkerHit",transMarkers[k],onHit) end end end end exports.NGCdxmsg:createNewDxMessage(root,"Mission is available now !",255,0,0,true) missionOn = false end function showTransWin(plr) -- showing the Driver window if plr then triggerClientEvent(plr,"showTransWin",plr) end end function startDriverMission(plr) -- starting new Driver mission if plr then missionOn = true exports.NGCdxmsg:createNewDxMessage("Driver Mission is available now, try it now and gain money!",255,255,255,true) -- --easytext(plr,05551, "Driver Mission Started", 5 * 1000, 0.5, 0.7, 0, 255, 0, 255,2) -- fadeCamera(plr,false) setTimer(function() fadeCamera(plr,true,2) x,y,z = getElementPosition(plr) firstX,firstY,firstZ = x,y,z transVeh = createVehicle(Driver_CAR_MODEL,x-10,y,z+1) transPed = createPed(Driver_PED_MODEL,x,y,z) if transVeh and transPed then warpPedIntoVehicle(transPed,transVeh,3) setTimer(function() easytextout(plr,05551, "Get in the car", 1000 * 1000, 0.5, 0.7, 0, 255, 0, 255,2) vx,vy,vz = getElementPosition(transVeh) if vx and vy and vz then vehArrow = createMarker(vx,vy,vz+2,"arrow",1,255,255,0) if vehArrow then function onVehEnter(enterer,seat) if enterer ~= plr then cancelEvent() elseif ( enterer == plr and seat == 0 ) then -- removeEventHandler("onVehicleEnter",root,onVehEnter) -- if isElement(vehArrow) then destroyElement(vehArrow) end -- randomDrop = math.random(#dropPosz) if randomDrop then dropX,dropY,dropZ = dropPosz[randomDrop][1],dropPosz[randomDrop][2],dropPosz[randomDrop][3] x,y,z = getElementPosition(plr) theDriverPrize = math.floor ( getDistanceBetweenPoints3D(x,y,z,dropX,dropY,dropZ) / 2 ) dropMarker = createMarker(dropX,dropY,dropZ,DROP_MARKER_TYPE,DROP_MARKER_SIZE,255,255,0,100,plr) dropBlip = createBlip(dropX,dropY,dropZ,24,5,255,255,0,255,1,900000,plr) function onDrop(hitter ) if ( hitter == plr and getPedOccupiedVehicle(hitter) == transVeh ) then removeEventHandler("onMarkerHit",dropMarker,onDrop) missionDone(hitter,true) end end addEventHandler("onMarkerHit",dropMarker,onDrop) end -- easytextout(plr,05551, "Go to the D blip to earn money", 5 * 1000, 0.5, 0.8, 0, 255, 0, 255,2) startMissionTime(plr) sortCheckShit(plr,transVeh,transPed) -- triggerServerEvent("TstartMissionTimer",lp, MISSION_TIME, true, "%m:%s:%cs", 0.5, 0.7,true,"default-bold",1,255,255,255) end end addEventHandler("onVehicleEnter",root,onVehEnter) end end end , 3 * 1000 ,1) end end,2500,1) destroyAllMarkers () end end addEvent("startDriverMission",true) addEventHandler("startDriverMission",root,startDriverMission) function easytextout(plr,id,msg,time,x,y,c1,c2,c3,c4,size) -- output in easytext resource exports.easytext:displayMessageForPlayer(plr,id,msg,time,x,y,c1,c2,c3,c4,size) end function destroyAllMarkers () -- to clean all markers if transMarkers and type(transMarkers) then for k,v in ipairs ( transMarkers ) do removeEventHandler("onMarkerHit",v,onHit) destroyElement(v) end end end function missionDone(Player,Won) -- on mission finish ( player = the player | Won = did he finished it successfuly or not ) if Player then stopMissionTime(Player) killCheckShit(Player) if isElement(dropMarker) then destroyElement(dropMarker) end if isElement(dropBlip) then destroyElement(dropBlip) end if isElement(vehArrow) then destroyElement(vehArrow) end if isElement(transPed) then destroyElement(transPed) end if isElement(transVeh) then destroyElement(transVeh) end -- if Won == true then -- If he won the mission triggerClientEvent(Player,"missionDone",true) -- givePlayerMoney(Player,15000) easytextout(Player,05551, "Driver Mission Done ! , Earned 15000$", 8 * 1000, 0.5, 0.7, 0, 255, 0, 255,2) exports.NGCdxmsg:createNewDxMessage(root,"Successfully, "..getPlayerName(Player).." Has Done the Driver misssion and earned 15000$",0,255,255,true) -- triggerClientEvent(Player,"missionDone",Player,true) else triggerClientEvent(Player,"missionDone",Player,false) easytextout(Player,05551, "Driver Mission Failed ! ", 8 * 1000, 0.5, 0.7, 255, 0, 0, 255,2) end fadeCamera(Player,false) setTimer(function() if firstX and firstY and firstZ then setElementPosition(Player,firstX - 10 , firstY , firstZ) firstX , firstY , firstZ = nil,nil,nil end fadeCamera(Player,true,2) end , 8 * 1000 , 1 ) setUpMarkers() startFloodTimer(Player) -- end end function startFloodTimer(plr) -- to start anti-flood timer .. if plr then tFlood[plr] = true setTimer ( function (plr) tFlood[plr] = false end , tonumber(FLOOD_TIME) * 60 * 1000 , 1 , plr ) end end addEventHandler("onPlayerQuit",root,function() tFlood[source] = nil end ) addEventHandler("onPlayerJoin",root,function() tFlood[source] = nil end ) function startMissionTime(Player) -- to start mission timer .. if Player then TimerDisplay = textCreateDisplay() theTime = MISSION_TIME m,s,cs = msToTimeStr(theTime) fullTime = m..":"..s TimerText = textCreateTextItem ( "Time Left : "..tostring(fullTime).."", 0.39, 0.7 ,"medium",0,255,0,255,2.0,"left","center",255) textDisplayAddText ( TimerDisplay, TimerText ) textDisplayAddObserver ( TimerDisplay, Player ) sortTimerShit(Player,TimerText,theTime) end end --Robbed from missiontimer resource , and it was robbed from arc_ :p function msToTimeStr(ms) if not ms then return '' end if ms < 0 then return "0","00","00" end local centiseconds = tostring(math.floor(math.fmod(ms, 1000)/10)) if #centiseconds == 1 then centiseconds = '0' .. centiseconds end local s = math.floor(ms / 1000) local seconds = tostring(math.fmod(s, 60)) if #seconds == 1 then seconds = '0' .. seconds end local minutes = tostring(math.floor(s / 60)) return minutes, seconds, centiseconds end function sortTimerShit(plr,timer,time) -- to sort timer's shit .. if timer and time then if isTimer(timerShitTimer) then killTimer(timerShitTimer) end timerShitTimer = setTimer(function(plr) time = time - 70 m,s,cs = msToTimeStr(time) fullTime = m..":"..s textItemSetText(timer,"Time Left : "..tostring(fullTime).."") if ( tonumber(m) <= 0 and tonumber(s) <= 0 and tonumber(cs) <= 0 ) then onTimerFinish(plr,timer) end end , 50 , 0 ,plr ) end end function stopMissionTime(Player) textDestroyDisplay(TimerDisplay) if TimerText then textDestroyTextItem(TimerText) end if isTimer(timerShitTimer) then killTimer(timerShitTimer) end end function onTimerFinish(Player) -- on timer end stopMissionTime(Player) missionDone(Player,false) end function sortCheckShit(player,car,ped) -- for check the health of ped & car if car and ped then checkShitTimer = setTimer ( function (player,car,ped) if car and ped then carH = math.floor(getElementHealth(car)/10) pedH = math.floor(getElementHealth(ped)) if ( carH and pedH ) then if ( carH < 30 or pedH < 30 ) then missionDone(player,false) killCheckShit(player) end end end end , 1000 , 0 , player,car,ped ) end end function killCheckShit(player) if isTimer (checkShitTimer) then killTimer(checkShitTimer) end end
nilq/small-lua-stack
null
local config = require('vfiler/actions/config') local action_modules = { 'bookmark', 'buffer', 'cursor', 'directory', 'file_operation', 'open', 'preview', 'select', 'view', 'yank', } local M = setmetatable({}, { __index = function(t, key) for _, name in ipairs(action_modules) do local module = require('vfiler/actions/' .. name) local func = module[key] if func then t[key] = func return func end end error(('"%s" action is undefined.'):format(key)) return nil end, }) function M.setup(configs) config.setup(configs) end return M
nilq/small-lua-stack
null
slot0 = 100 Dntgtest_RenderOrder = { longwang = 40000 + 27, sunwukong = 40000 + 30, shandian = 30000 + 5000, shandianmenu = 30000 + 200, shandianxianjie = 30000 + 250, jinyumantang = 30000 + 300, danaotiangong = 30000 + 600, yijianshuangdiao = 30000 + 700, yishisanyu = 30000 + 800, foshou = 30000 + 500, jingubang = 30000 + 1001, wudifenghuolun = 30000 + 1002, dingping = 30000 + 1000, zhangyuguai = 40000 + 23, jinlong = 40000 + 22, shayuhuangjinban = 40000 + 19, shenxianchuan = 40000 + 25, haiyao = 40000 + 24, longxia = 40000 + 18, yinlong = 40000 + 21, shajinghuangjinban = 40000 + 17, shuimuhuangjinban = 40000 + 20, shajing = 40000 + 16, bianfuyu = 40000 + 15, jianyu = 40000 + 14, buyu12 = 40000 + 13, buyu7 = 40000 + 12, houtouyu = 40000 + 11, xiaohaigui = 40000 + 10, denglongyu = 40000 + 9, buyu13 = 40000 + 8, hetun = 40000 + 7, xiaochouyu = 40000 + 6, buyu10 = 40000 + 5, buyu8 = 40000 + 4, xiaolanyu = 40000 + 3, xiaolvyu2 = 40000 + 2, xiaolvyu = 40000 + 1, dntgtest_Bullet_1_1 = 20000 + 1, dntgtest_Bullet_1_2 = 20000 + 2, dntgtest_Bullet_2_1 = 20000 + 3, dntgtest_Bullet_2_2 = 20000 + 4, dntgtest_Bullet_3_1 = 20000 + 5, dntgtest_Bullet_3_2 = 20000 + 6, dntgtest_Net_1_1 = 10000 + 1, dntgtest_Net_1_2 = 10000 + 2, dntgtest_Net_2_1 = 10000 + 3, dntgtest_Net_2_2 = 10000 + 4, dntgtest_Net_3_1 = 10000 + 5, dntgtest_Net_3_2 = 10000 + 6, dntgtest_bullet = 10000 + 1 } return
nilq/small-lua-stack
null
local Direction = require('__stdlib__/stdlib/area/direction') --Global static variables TILE_ENTITY = "modular-storage-stockpileTile" CONTROLLER_ENTITY = "modular-storage-controller" INPUT_ENTITY = "modular-storage-input" OUTPUT_ENTITY = "modular-storage-output" INTERFACE_ENTITY = "modular-storage-interface" PANEL_ENTITY = "modular-storage-inventory-panel" function setScreenText (surface,textkey,position,color) local flyingTexts = surface.find_entities_filtered{name = "flying-text", position = position, radius = 2} local exists = Table.any(flyingTexts,function(entity) return entity.text[1] == textkey end) if not exists then flyingText = surface.create_entity{ name = "flying-text", position = position, color = color, text = {textkey} } end end function setScreenErrorText (surface,textkey,position) setScreenText (surface,textkey,position,{r = 255, g = 0, b = 0}) end function isGhost(en) return Entity.has(en,"ghost_name") end function getEntityName(en) --Get name of entity or the ghost if isGhost(en) then return en.ghost_name else return en.name end end function setStockpileID(entity,ID) local data = Entity.get_data(entity) if data == nil then Entity.set_data(entity, { stockpileID = ID }) else data.stockpileID = ID Entity.set_data(entity,data) end end function resetStockpileID(entity) if entity.valid then setStockpileID(entity,nil) end end function getStockpileID(entity) local data = Entity.get_data(entity) if data ~= nil then return data.stockpileID end return nil end function areStockpilesTheSame(foundStockpiles,en) if #foundStockpiles == 1 then if foundStockpiles[1].id ~= 0 then Stockpiles.getStockpileByID(foundStockpiles[1].id):prepareTile(en) end return true elseif #foundStockpiles > 1 then --Check if stockpiles are the same local stockipelesNoZero = Table.filter(foundStockpiles, function(v) return v.id ~=0 end) if #stockipelesNoZero > 1 then for i = 2, #stockipelesNoZero do if stockipelesNoZero[i].id ~= stockipelesNoZero[i-1].id then return false end end end if #stockipelesNoZero >= 1 and en.name== TILE_ENTITY then --all are the same local stockipelesZero = Table.filter(foundStockpiles, function(v) return v.id ==0 end) if #stockipelesZero ~= 0 then --If connected to multiple tiles with no ID, update ID of those tiles resetVisited() for i = 1, #stockipelesZero do --Start recursive function to find connected empty tiles en = stockipelesZero[i].entity if isVisited(en) == false then findConnectedTiles (stockipelesNoZero[1].id,en) end end else Stockpiles.getStockpileByID(stockipelesNoZero[1].id):prepareTile(en) end end end return true end function findConnectedTiles (stockpileID,entity) local nameToSearch = TILE_ENTITY if isGhost(entity) then nameToSearch = entity.name end --Check if already has an ID local ID = getStockpileID(entity) if ID ~= nil and ID ~= 0 then return true end if isVisited(entity) == false then Stockpiles.getStockpileByID(stockpileID):prepareTile(entity) end setVisited(entity) local x = entity.position.x local y = entity.position.y --check y positive position local neighbor = entity.surface.find_entity(nameToSearch,{x, y + 1}) if neighbor ~= nil and isVisited(neighbor) == false then findConnectedTiles(stockpileID, neighbor) end --check y negative position local neighbor = entity.surface.find_entity(nameToSearch,{x, y - 1}) if neighbor ~= nil and isVisited(neighbor) == false then findConnectedTiles(stockpileID, neighbor) end --check x positive position local neighbor = entity.surface.find_entity(nameToSearch,{x + 1, y}) if neighbor ~= nil and isVisited(neighbor)== false then findConnectedTiles(stockpileID, neighbor) end --check x negative position local neighbor = entity.surface.find_entity(nameToSearch,{x - 1, y}) if neighbor ~= nil and isVisited(neighbor) == false then findConnectedTiles(stockpileID, neighbor) end end function removeEntityFromTable(tab,en) tab[en.unit_number] = nil end function beltAdjecentInterfering(placedEntity) --Get sideways direction local direction = Direction.next_direction(placedEntity.direction) local positionToSearchPos = Position.translate(placedEntity.position, direction, 1) local positionToSearchNeg = Position.translate(placedEntity.position, direction, -1) if isBeltAtPositionAimedAtEntity(placedEntity,positionToSearchPos) then return true end if isBeltAtPositionAimedAtEntity(placedEntity,positionToSearchNeg) then return true end return false end function isBeltAtPositionAimedAtEntity(placedEntity,position) foundEntities = placedEntity.surface.find_entities_filtered({position=position,type="transport-belt"}) for _, entity in pairs(foundEntities) do if Position.translate(entity.position, entity.direction, 1) == Position.new(placedEntity.position) then return true end end return false end local visited = {} function resetVisited() visited = {} end function setVisited(entity) visited[entity.position.x .. "," .. entity.position.y] = true end function isVisited(entity) return visited[entity.position.x .. "," .. entity.position.y] ~= nil end function cancelBuild(e) if isGhost(e.created_entity) then e.created_entity.destroy() else if e.robot ~= nil then -- IF placed by robot --Robot placed the item, schedule it for removal e.created_entity.order_deconstruction(e.robot.force) elseif e.created_entity.destroy() then game.players[e.player_index].cursor_stack.count = game.players[e.player_index].cursor_stack.count + 1; end end end function cancelRemove(e) local en = e.entity local data = Entity.get_data(en) if e.robot ~= nil then -- IF picked up by robot e.buffer.remove({name=en.name,count=1}) else game.players[e.player_index].remove_item({name=en.name,count=1}) end --Physicly put it back replacedEntity = en.surface.create_entity{ name = en.name, position = en.position, force=game.forces.player } Entity.set_data(replacedEntity,data) return replacedEntity end function CopyTable (oldTable) local newTable = {} for k,v in pairs(oldTable) do newTable[k] = v end return newTable end
nilq/small-lua-stack
null
------------------------------------------------ -- Sample App : wrap.lua example -- This is the same example code from wrap.lua -- It should work just like the original script ------------------------------------------------ -- Define a global script object with event handlers script = {} function script.onStart () -- Display some text screen.setCenteredText("script started") -- Create some timers to show that the script is working unit.setTimer("a", 2) -- timer id "a", ticks every 2 seconds unit.setTimer("b", 3) -- timer id "b", ticks every 3 seconds end function script.onStop () screen.setCenteredText("script stopped") end function script.onActionStart (actionName) screen.setCenteredText(actionName .. " key pressed") end function script.onActionStop (actionName) screen.setCenteredText(actionName .. " key released") end function script.onTick (timerId) screen.setCenteredText("timer " .. timerId .. " ticked") end -- Other events that are available by default: -- * onActionLoop(actionName): action key is held -- * onUpdate(): executed once per frame -- * onFlush(): executed 60 times per second, for physics calculations only; setEngineCommand must be called from here -- Slot events are available if slot type is set with the --slot command line option. function script.onMouseDown (x, y) screen.setCenteredText("mouse down: x=" .. x .. " , y=" .. y) end -- Call the start event handler -- Alternatively, initialization code can be placed anywhere in this file. -- The only requirement is that there is a global "script" object with event handlers script.onStart()
nilq/small-lua-stack
null
--- A LogHandler for save log to a file. -- @author zrong -- Creation: 2014-11-14 local FileHandler = class('LogHandler', import(".LogHandler")) -- @file A file to write info or a opened file handler. It must be a absolute path. -- @mode A mode for opened file, it is only available when file is a file name. -- @autoflush Default value is false。 -- @starttime A timestamp that start application. Default value is nil (Do not show time). -- @gettime A function, return current time. function FileHandler:ctor(file, mode, autoflush, starttime, gettime) FileHandler.super.ctor(self, starttime, gettime) mode = mode or 'w+b' if type(file) == 'string' then self.filename = filename self._file = io.open(file, mode) else self._file = file end self._autoflush = autoflush end function FileHandler:emit(level, fmt, args) str = self:getString(level, fmt, args) self._file:write(str..'\n') if self._autoflush then self:flush() end end function FileHandler:flush() self._file:flush() end return FileHandler
nilq/small-lua-stack
null
local http = game:GetService("HttpService") local utils = {} local cache = {} function utils.get(url) local result; local success, err = pcall(function() result = http:GetAsync(url) end) if success and not err then return result else warn('Error occured, "'..err.."'") return err end end function utils.encode(data) -- json encode return http:JSONEncode(data) end function utils.decode(data) -- json decode return http:JSONDecode(data) end function utils.getinfo(tbl) local data = {} for index,value in pairs(tbl.data) do local name = value.name local id = value.id data[name] = id end return data end function utils.getTemplateId(assetId) local key = '.' .. assetId if cache[key] then return cache[key] else local info = utils.get("https://coolestwebsiteverrr.000webhostapp.com/getTemplate.php?assetId=" .. assetId) cache[key] = info return info end end return utils;
nilq/small-lua-stack
null
local cpus=require'leda'.scheduler.cpu() return [===[<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Leda HTTP Controller: Real-time updates</title> <link href="leda.css" rel="stylesheet" type="text/css"> <script language="javascript" type="text/javascript" src="jquery.js"></script> <script language="javascript" type="text/javascript" src="jquery.flot.js"></script> <script language="javascript" type="text/javascript" src="arbor.js"></script> <script language="javascript" type="text/javascript" src="graphics.js"></script> <script language="javascript" type="text/javascript" src="jquery.flot.navigate.js"></script> <script type="text/javascript"> var clear_pan=function() { plotStageLatency = $.plot("#stage_latency", stagesLatency, { series: { shadowSize: 1 // Drawing is faster without shadows }, zoom: { interactive: true }, pan: { interactive: true } }); plotStageThroughput = $.plot("#stage_throughput", stagesThrouhput, { series: { shadowSize: 0 }, zoom: { interactive: true }, pan: { interactive: true } }); plotStageQueue = $.plot("#stage_queue", stagesQueue, { series: { shadowSize: 0 }, zoom: { interactive: true }, pan: { interactive: true } }); plotStageInstances = $.plot("#stage_instances", stagesInstances, { series: { shadowSize: 0 }, zoom: { interactive: true }, pan: { interactive: true } }); plotConnectorLatency = $.plot("#connectors_latency", connectorsLatency, { series: { shadowSize: 0 }, zoom: { interactive: true }, pan: { interactive: true } }); plotConnectorThroughput = $.plot("#connectors_throughput", connectorsThroughput, { series: { shadowSize: 0 }, zoom: { interactive: true }, pan: { interactive: true } }); } var clear_graphs=function() { latencyData={} throughputData={} queueData={} instancesData={} stagesLatency=[] stagesThrouhput=[] stagesQueue=[] stagesInstances=[] latencyCData={} throughputCData={} connectorsLatency=[] connectorsThroughput=[] colors={} var i=0 info.stages.forEach(function(entry) { latencyData[entry.name]=[[info.uptime,entry.latency]] throughputData[entry.name]=[[info.uptime,entry.throughput]] queueData[entry.name]=[[info.uptime,entry.queue]] instancesData[entry.name]=[[info.uptime,entry.ready]] stagesLatency.push({label: entry.name,data: latencyData[entry.name]}) stagesThrouhput.push({label: entry.name,data: throughputData[entry.name]}) stagesQueue.push({label: entry.name,data: queueData[entry.name]}) stagesInstances.push({label: entry.name,data: instancesData[entry.name]}) colors[entry.name]=i++; }); i=0 info.connectors.forEach(function(entry) { latencyCData[entry.name]=[[info.uptime,entry.latency]] throughputCData[entry.name]=[[info.uptime,entry.throughput]] connectorsLatency.push({label: entry.name,data: latencyCData[entry.name]}) connectorsThroughput.push({label: entry.name,data: throughputCData[entry.name]}) colors[entry.name]=i++; }); } var main=function () { var updateInterval = 1000; $("#updateInterval").val(updateInterval).change(function () { var v = $(this).val(); if (v && !isNaN(+v)) { updateInterval = +v; if (updateInterval < 1) { updateInterval = 1; } else if (updateInterval > 2000) { updateInterval = 2000; } $(this).val("" + updateInterval); } }); function getInfo() { var stage={} function onDataReceived(series) { stage=series $("#app-name")[0].innerHTML=series.name } function onError(error,i,str) { alert('ERROR: '+str) } $.ajax({ url: "stats", type: "GET", dataType: "json", success: onDataReceived, error: onError, async: false }); return stage } info=getInfo() clear_graphs(); clear_pan(); // insert checkboxes var choiceContainer = $("#stage_choices"); $.each(stagesLatency, function(key, val) { choiceContainer.append("&nbsp;<input type='checkbox' name='" + key + "' checked='checked' value='" + val.label +"' id='stage_id" + key + "' onClick='drawGraphs();'></input>" + "<label for='id" + key + "'>" + val.label + "</label>"); }); var choiceContainerC = $("#connector_choices"); $.each(connectorsLatency, function(key, val) { choiceContainerC.append("&nbsp;<input type='checkbox' name='" + key + "' checked='checked' value='" + val.label +"' id='connector_id" + key + "' onClick='drawGraphs();'></input>" + "<label for='id" + key + "'>" + val.label + "</label>"); }); drawGraphs=function () { var dataLatency=[] var dataThroughput=[] var dataQueue=[] var dataInstances=[] var dataCLatency=[] var dataCThroughput=[] choiceContainer.find("input:checked").each(function () { var key = $(this).attr("name"); var name = $(this).attr("value"); dataLatency.push({label: name,data: latencyData[name], color:colors[name]}) dataThroughput.push({label: name,data: throughputData[name], color:colors[name]}) dataQueue.push({label: name,data: queueData[name], color:colors[name]}) dataInstances.push({label: name,data: instancesData[name], color:colors[name]}) }); choiceContainerC.find("input:checked").each(function () { var key = $(this).attr("name"); var name = $(this).attr("value"); dataCLatency.push({label: name,data: latencyCData[name], color:colors[name]}) dataCThroughput.push({label: name,data: throughputCData[name], color:colors[name]}) }); plotStageLatency.setData(dataLatency); plotStageThroughput.setData(dataThroughput); plotStageQueue.setData(dataQueue); plotStageInstances.setData(dataInstances); plotConnectorLatency.setData(dataCLatency); plotConnectorThroughput.setData(dataCThroughput); plotStageLatency.setupGrid() plotStageLatency.draw(); plotStageThroughput.setupGrid() plotStageThroughput.draw(); plotStageQueue.setupGrid() plotStageQueue.draw(); plotStageInstances.setupGrid() plotStageInstances.draw(); plotConnectorLatency.setupGrid() plotConnectorLatency.draw(); plotConnectorThroughput.setupGrid() plotConnectorThroughput.draw(); } var update=0; var onDataError=function(error,i,str) { $("#status-text")[0].innerHTML="Offline" $("#status-text")[0].style.color="#770000" $("#uptime-text")[0].style.color="#770000" $(".links").each(function (i,e) { e.style.display="none" }); } var updateData=function () { function onDataReceived(series) { info.uptime=series.uptime $("#uptime-text")[0].innerHTML=(series.uptime).toFixed(3)+"s" $("#threads-text")[0].innerHTML=series.active_threads+"/"+series.thread_pool_size $("#memory-usage")[0].innerHTML=(series.mem.Rss/1024).toFixed(2)+"MB / "+(series.mem.total/(1024*1024)).toFixed(2)+"GB ("+series.mem.percentage.toFixed(2)+"%)" series.stages.forEach(function(entry) { latencyData[entry.name].push([series.uptime,entry.latency]) throughputData[entry.name].push([series.uptime,entry.throughput]) queueData[entry.name].push([series.uptime,entry.queue]) instancesData[entry.name].push([series.uptime,entry.ready]) }); series.connectors.forEach(function(entry) { latencyCData[entry.name].push([series.uptime,entry.latency]) throughputCData[entry.name].push([series.uptime,entry.throughput]) }); drawGraphs() setTimeout(updateData, updateInterval); } $.ajax({ url: "stats", type: "GET", dataType: "json", success: onDataReceived, error: onDataError }); } increase_threads=function () { function onDataReceived(series) { } $.ajax({ url: "increase_threads", type: "POST", data: "increment=1", success: onDataReceived, error: onDataError }); } trim_memory=function () { function onDataReceived(series) { } $.ajax({ url: "trim", type: "GET", success: onDataReceived, error: onDataError }); } inc_threads=function () { function onDataReceived(series) { } $.ajax({ url: "increase_threads", type: "GET", success: onDataReceived, error: onDataError }); } dec_threads=function () { function onDataReceived(series) { } $.ajax({ url: "decrease_threads", type: "GET", success: onDataReceived, error: onDataError }); } //GRAPH Renderer = function(canvas){ var canvas = $(canvas).get(0) var ctx = canvas.getContext("2d"); var gfx = arbor.Graphics(canvas) var particleSystem = null var that = { init:function(system){ particleSystem = system particleSystem.screenSize(canvas.width, canvas.height) particleSystem.screenPadding(40) that.initMouseHandling() }, redraw:function(){ if (!particleSystem) return gfx.clear() // convenience ƒ: clears the whole canvas rect // draw the nodes & save their bounds for edge drawing var nodeBoxes = {} particleSystem.eachNode(function(node, pt){ // node: {mass:#, p:{x,y}, name:"", data:{}} // pt: {x:#, y:#} node position in screen coords // determine the box size and round off the coords if we'll be // drawing a text label (awful alignment jitter otherwise...) var label = node.data.label||"" var w = ctx.measureText(""+label).width + 10 if (!(""+label).match(/^[ \t]*$/)){ pt.x = Math.floor(pt.x) pt.y = Math.floor(pt.y) }else{ label = null } // draw a rectangle centered at pt if (node.data.color) ctx.fillStyle = node.data.color else ctx.fillStyle = "rgba(0,0,0,.2)" if (node.data.color=='none') ctx.fillStyle = "white" if (node.data.shape=='dot'){ gfx.oval(pt.x-w/2, pt.y-w/2, w,w, {fill:ctx.fillStyle}) nodeBoxes[node.name] = [pt.x-w/2, pt.y-w/2, w,w] }else{ gfx.rect(pt.x-w/2, pt.y-10, w,20, 4, {fill:ctx.fillStyle}) nodeBoxes[node.name] = [pt.x-w/2, pt.y-11, w, 22] } // draw the text if (label){ ctx.font = "12px Helvetica" ctx.textAlign = "center" ctx.fillStyle = "white" if (node.data.color=='none') ctx.fillStyle = '#333333' ctx.fillText(label||"", pt.x, pt.y+4) ctx.fillText(label||"", pt.x, pt.y+4) } }) // draw the edges particleSystem.eachEdge(function(edge, pt1, pt2){ // edge: {source:Node, target:Node, length:#, data:{}} // pt1: {x:#, y:#} source position in screen coords // pt2: {x:#, y:#} target position in screen coords var weight = edge.data.weight var color = edge.data.color if (!color || (""+color).match(/^[ \t]*$/)) color = null // find the start point var tail = intersect_line_box(pt1, pt2, nodeBoxes[edge.source.name]) var head = intersect_line_box(tail, pt2, nodeBoxes[edge.target.name]) ctx.save() ctx.beginPath() ctx.lineWidth = (!isNaN(weight)) ? parseFloat(weight) : 1 ctx.strokeStyle = (color) ? color : "#cccccc" ctx.fillStyle = null ctx.moveTo(tail.x, tail.y) ctx.lineTo(head.x, head.y) ctx.stroke() ctx.restore() // draw an arrowhead if this is a -> style edge if (edge.data.directed){ ctx.save() // move to the head position of the edge we just drew var wt = !isNaN(weight) ? parseFloat(weight) : 1 var arrowLength = 6 + wt var arrowWidth = 2 + wt ctx.fillStyle = (color) ? color : "#cccccc" ctx.translate(head.x, head.y); ctx.rotate(Math.atan2(head.y - tail.y, head.x - tail.x)); // delete some of the edge that's already there (so the point isn't hidden) ctx.clearRect(-arrowLength/2,-wt/2, arrowLength/2,wt) // draw the chevron ctx.beginPath(); ctx.moveTo(-arrowLength, arrowWidth); ctx.lineTo(0, 0); ctx.lineTo(-arrowLength, -arrowWidth); ctx.lineTo(-arrowLength * 0.8, -0); ctx.closePath(); ctx.fill(); // ctx.restore() // ctx.save() // draw the text if (edge.data.label){ ctx.font = "18px Helvetica" ctx.textAlign = "left" // ctx.fillStyle = "white" if (edge.data.color) ctx.fillStyle = edge.data.color; ctx.fillStyle = '#333333' ctx.translate(-100, 10); ctx.fillText(edge.data.label||"", 0, 0) // ctx.fillText(edge.data.label||"", head.x, head.y) } ctx.restore() } }) }, initMouseHandling:function(){ // no-nonsense drag and drop (thanks springy.js) selected = null; nearest = null; var dragged = null; var oldmass = 1 // set up a handler object that will initially listen for mousedowns then // for moves and mouseups while dragging var handler = { clicked:function(e){ var pos = $(canvas).offset(); _mouseP = arbor.Point(e.pageX-pos.left, e.pageY-pos.top) selected = nearest = dragged = particleSystem.nearest(_mouseP); if (dragged.node !== null) dragged.node.fixed = true $(canvas).bind('mousemove', handler.dragged) $(window).bind('mouseup', handler.dropped) return false }, dragged:function(e){ var old_nearest = nearest && nearest.node._id var pos = $(canvas).offset(); var s = arbor.Point(e.pageX-pos.left, e.pageY-pos.top) if (!nearest) return if (dragged !== null && dragged.node !== null){ var p = particleSystem.fromScreen(s) dragged.node.p = p } return false }, dropped:function(e){ if (dragged===null || dragged.node===undefined) return if (dragged.node !== null) dragged.node.fixed = false dragged.node.tempMass = 50 dragged = null selected = null $(canvas).unbind('mousemove', handler.dragged) $(window).unbind('mouseup', handler.dropped) _mouseP = null return false } } $(canvas).mousedown(handler.clicked); } } // helpers for figuring out where to draw arrows (thanks springy.js) var intersect_line_line = function(p1, p2, p3, p4) { var denom = ((p4.y - p3.y)*(p2.x - p1.x) - (p4.x - p3.x)*(p2.y - p1.y)); if (denom === 0) return false // lines are parallel var ua = ((p4.x - p3.x)*(p1.y - p3.y) - (p4.y - p3.y)*(p1.x - p3.x)) / denom; var ub = ((p2.x - p1.x)*(p1.y - p3.y) - (p2.y - p1.y)*(p1.x - p3.x)) / denom; if (ua < 0 || ua > 1 || ub < 0 || ub > 1) return false return arbor.Point(p1.x + ua * (p2.x - p1.x), p1.y + ua * (p2.y - p1.y)); } var intersect_line_box = function(p1, p2, boxTuple) { var p3 = {x:boxTuple[0], y:boxTuple[1]}, w = boxTuple[2], h = boxTuple[3] var tl = {x: p3.x, y: p3.y}; var tr = {x: p3.x + w, y: p3.y}; var bl = {x: p3.x, y: p3.y + h}; var br = {x: p3.x + w, y: p3.y + h}; return intersect_line_line(p1, p2, tl, tr) || intersect_line_line(p1, p2, tr, br) || intersect_line_line(p1, p2, br, bl) || intersect_line_line(p1, p2, bl, tl) || false } return that } var sys = arbor.ParticleSystem(1000, 400,1); sys.parameters({gravity:true}); sys.renderer = Renderer("#gviewport") ; function getGraph() { var graph={} function onDataReceived(series) { graph=series } function onError(error,i,str) { } $.ajax({ url: "graph", type: "GET", dataType: "json", success: onDataReceived, error: onError, async: false }); return graph } var data=getGraph() sys.graft(data); updateData(); } $(main); </script> </head> <body> <div id="header"> <h2><img src='leda.svg' height='180' style="float:right"/>Leda Real-time Statistics</h2> </div> <div id="commands"> <h2>Application: <a href="#" onClick="$('#app-graph').toggle(1); return false;"><span id="app-name"></span></a></h2> <div id="app-graph"> <canvas id="gviewport" width="800" height="600"></canvas> </div> <p>Lua version: ]===]..((jit and jit.version) or _VERSION or "Unknown").." Leda version: "..(leda._VERSION or "Unknown")..[===[</p> <p>Controller status: <span id="status-text" style="color: #007700;">Online</span>. Uptime: <span id="uptime-text" style="color: #007700;"></span></p> <p>Memory usage: <span id="memory-usage"></span> <span class='links'>- <a href="#" onCLick="trim_memory(); return false;">Trim</a></span></p> <p>Active threads: <span id="threads-text"></span> (]===]..cpus..[===[ cores) <span class='links'>- <a href="#" onCLick="inc_threads(); return false;">Increase</a> <a href="#" onCLick="dec_threads(); return false;">Decrease</a></span></p> <p>Graphs: <a href="#" onCLick="clear_graphs(); return false;">Clear data</a> <a href="#" onCLick="clear_pan(); return false;">Reset pan</a></p> </div> <div id="content"> <p id='status'></p> <p>Time between updates: <input id="updateInterval" type="text" value="" style="text-align: right; width:5em"> milliseconds</p> <div id="stage_choices" class="choices"><h2>Stages:</h2></div> <div class="div-text-1">Stage Latency (s)</div> <div class="div-text-2">Stage's Queue size</div> <div class="div-text-3">Stage Throughput (ev/s)</div> <div class="div-text-4">Stage Instances</div> <div class="stages" id="stages-div"> <div id="stage_latency" class="stage-graph"></div> <div id="stage_throughput" class="stage-graph-1"></div> <div id="stage_queue" class="stage-graph-2"></div> <div id="stage_instances" class="stage-graph-3"></div> </div> <div id="connector_choices" class="choices"><h2>Connectors:</h2></div> <div class="div-text-1">Connector Latency (s)</div> <div class="div-text-2">Connector Throughput (ev/s)</div> <div class="connectors"> <div id="connectors_latency" class="connector-graph"></div> <div id="connectors_throughput" class="connector-graph-2"></div> </div> </div> </body> </html> ]===]
nilq/small-lua-stack
null
include "map_builder.lua" include "trajectory_builder.lua" options = { map_builder = MAP_BUILDER, trajectory_builder = TRAJECTORY_BUILDER, map_frame = "map", tracking_frame = "imu_link", published_frame = "odom", odom_frame = "", provide_odom_frame = false, publish_frame_projected_to_2d = true, use_odometry = false, -- if IMU works, it seems better to use it, and disable odometry use_nav_sat = false, use_landmarks = false, num_laser_scans = 0, num_multi_echo_laser_scans = 0, num_subdivisions_per_laser_scan = 1, num_point_clouds = 1, lookup_transform_timeout_sec = 1.0, submap_publish_period_sec = 0.3, pose_publish_period_sec = 0.1, trajectory_publish_period_sec = 0.1, rangefinder_sampling_ratio = 1.0, odometry_sampling_ratio = 0.1, -- workaround for use_odometry: Check failed: data.time > std::prev(trajectory.end())->first fixed_frame_pose_sampling_ratio = 1.0, imu_sampling_ratio = 1.0, landmarks_sampling_ratio = 1.0, } MAP_BUILDER.use_trajectory_builder_2d = true TRAJECTORY_BUILDER_2D.use_imu_data = true TRAJECTORY_BUILDER_2D.ceres_scan_matcher.translation_weight = 10 TRAJECTORY_BUILDER_2D.ceres_scan_matcher.rotation_weight = 10 return options
nilq/small-lua-stack
null
assert(_ACTION ~= nil, "no action (vs20**, gmake or xcode for example) provided!") include("config.lua") newoption({ trigger = "workspace", description = "Sets the path for the workspace directory", value = "path for workspace directory" }) function CleanPath(p) if p == nil then return end local last = p:sub(-1) if last == "/" or last == "\\" then p = p:sub(1, -2) end return p end _GARRYSMOD_COMMON_DIRECTORY = CleanPath(_SCRIPT_DIR) includeexternal("premake/lua_shared.lua") includeexternal("premake/detouring.lua") includeexternal("premake/scanning.lua") includeexternal("premake/sourcesdk.lua") includeexternal("premake/pkg_config.lua") function CreateWorkspace(config) assert(type(config) == "table", "supplied argument is not a table!") local name = config.name assert(type(name) == "string", "'name' is not a string!") local directory = config.path or _OPTIONS["workspace"] or DEFAULT_WORKSPACE_DIRECTORY assert(type(directory) == "string", "workspace path is not a string!") directory = CleanPath(directory) local _workspace = workspace(name) assert(_workspace.directory == nil, "a workspace with the name '" .. name .. "' already exists!") local abi_compatible if config.allow_debug ~= nil then assert(type(config.allow_debug) == "boolean", "'allow_debug' is not a boolean!") print("WARNING: The 'allow_debug' option has been deprecated in favor of 'abi_compatible' (same functionality, better name, takes precedence over 'allow_debug', allows setting per project where the workspace setting takes precedence if set to true)") abi_compatible = not config.allow_debug end if config.abi_compatible ~= nil then abi_compatible = config.abi_compatible assert(type(abi_compatible) == "boolean", "'abi_compatible' is not a boolean!") _workspace.abi_compatible = abi_compatible end _workspace.directory = directory language("C++") location(_workspace.directory) warnings("Extra") flags({"NoPCH", "MultiProcessorCompile"}) staticruntime("On") characterset("MBCS") platforms("x86") architecture("x32") if abi_compatible then configurations("Release") filter("system:linux or macosx") defines("_GLIBCXX_USE_CXX11_ABI=0") else configurations({"Release", "Debug"}) end filter("configurations:Release") optimize("On") vectorextensions("SSE2") defines("NDEBUG") objdir(_workspace.directory .. "/intermediate") targetdir(_workspace.directory .. "/release") if not abi_compatible then filter("configurations:Debug") symbols("On") defines({"DEBUG", "_DEBUG"}) objdir(_workspace.directory .. "/intermediate") targetdir(_workspace.directory .. "/debug") end filter("system:windows") defines({ "_CRT_NONSTDC_NO_WARNINGS", "_CRT_SECURE_NO_WARNINGS", "STRICT" }) filter("system:windows") cppdialect("C++17") filter("system:linux or macosx") cppdialect("GNU++17") filter({}) end newoption({ trigger = "source", description = "Sets the path to the source directory", value = "path to source directory" }) newoption({ trigger = "autoinstall", description = "Automatically installs the module to GarrysMod/garrysmod/bin (works as a flag and a receiver for a path)" }) local function GetSteamLibraryDirectories() local dir if os.istarget("windows") then if os.getWindowsRegistry("HKCU:\\Software\\Valve\\Steam\\SteamPath") then dir = os.getWindowsRegistry("HKCU:\\Software\\Valve\\Steam\\SteamPath") .. "/SteamApps/" else local p = io.popen("wmic logicaldisk get caption") for line in p:read("*a"):gmatch("%S+") do if line ~= "Caption" then local steamDir1 = string.format("%s\\Program Files (x86)\\Steam\\SteamApps\\", line) local steamDir2 = string.format("%s\\Program Files\\Steam\\SteamApps\\", line) if os.isdir(steamDir1) then dir = steamDir1 elseif os.isdir(steamDir2) then dir = steamDir2 end end end p:close() end elseif os.istarget("linux") then dir = path.join(os.getenv("HOME") or "~", ".local/share/Steam/SteamApps/") elseif os.istarget("macosx") then dir = path.join(os.getenv("HOME") or "~", "Library/Application Support/Steam/SteamApps/") end if dir then local dirs = {dir} if os.isfile(dir .. "libraryfolders.vdf") then local f = io.open(dir .. "libraryfolders.vdf","r") for _, libdir in f:read("*a"):gmatch("\n%s*\"(%d+)\"%s*\"(.-)\"") do if os.isdir(libdir) then if os.isdir(libdir .. "\\steamapps") then libdir = libdir .. "\\steamapps" end dirs[#dirs + 1] = libdir:gsub("\\\\","\\") local pathSep = dirs[#dirs]:match("[/\\]") if dirs[#dirs]:sub(-1, -1) ~= pathSep then dirs[#dirs] = dirs[#dirs] .. pathSep end end end f:close() end return dirs end return {} end local function FindGarrysModDirectory() local dirs = GetSteamLibraryDirectories() for _, dir in ipairs(dirs) do if os.isdir(dir .. "common/GarrysMod/") then return dir .. "common/GarrysMod/" elseif os.isdir(dir .. "common/garrysmod/") then return dir .. "common/garrysmod/" end end return end local function FindGarrysModLuaBinDirectory() local dir = FindGarrysModDirectory() if not dir then return end if not os.isdir(dir .. "garrysmod/lua/bin") then os.mkdir(dir .. "garrysmod/lua/bin") end return dir .. "garrysmod/lua/bin/" end function CreateProject(config) assert(type(config) == "table", "supplied argument is not a table!") local is_server = config.serverside assert(type(is_server) == "boolean", "'serverside' option is not a boolean!") local sourcepath = config.source_path or _OPTIONS["source"] or DEFAULT_SOURCE_DIRECTORY assert(type(sourcepath) == "string", "source code path is not a string!") local manual_files = config.manual_files if manual_files == nil then manual_files = false else assert(type(manual_files) == "boolean", "'manual_files' is not a boolean!") end local _workspace = workspace() local abi_compatible = _workspace.abi_compatible if not abi_compatible then if config.abi_compatible ~= nil then abi_compatible = config.abi_compatible assert(type(abi_compatible) == "boolean", "'abi_compatible' is not a boolean!") else abi_compatible = false end end local name = (is_server and "gmsv_" or "gmcl_") .. _workspace.name if abi_compatible and os.istarget("windows") and _ACTION ~= "vs2017" then error("The only supported compilation platform for this project (" .. name .. ") on Windows is Visual Studio 2017.") end local _project = project(name) assert(_project.directory == nil, "a project with the name '" .. name .. "' already exists!") _project.directory = CleanPath(sourcepath) _project.serverside = is_server if abi_compatible then removeconfigurations("Debug") configurations("Release") else configurations({"Release", "Debug"}) end kind("SharedLib") language("C++") defines({ "GMMODULE", string.upper(string.gsub(_workspace.name, "%.", "_")) .. (_project.serverside and "_SERVER" or "_CLIENT"), "IS_SERVERSIDE=" .. tostring(is_server) }) sysincludedirs(_GARRYSMOD_COMMON_DIRECTORY .. "/include") includedirs(_project.directory) if not manual_files then files({ _project.directory .. "/*.h", _project.directory .. "/*.hpp", _project.directory .. "/*.hxx", _project.directory .. "/*.c", _project.directory .. "/*.cpp", _project.directory .. "/*.cxx" }) end vpaths({ ["Header files/*"] = { _project.directory .. "/**.h", _project.directory .. "/**.hpp", _project.directory .. "/**.hxx" }, ["Source files/*"] = { _project.directory .. "/**.c", _project.directory .. "/**.cpp", _project.directory .. "/**.cxx" } }) if abi_compatible then files(_GARRYSMOD_COMMON_DIRECTORY .. "/source/ABICompatibility.cpp") vpaths({["Source files/garrysmod_common"] = _GARRYSMOD_COMMON_DIRECTORY .. "/source/ABICompatibility.cpp"}) end targetprefix("") targetextension(".dll") filter("system:windows") targetsuffix("_win32") filter("system:linux") targetsuffix("_linux") linkoptions({"-static-libgcc", "-static-libstdc++"}) filter("system:macosx") targetsuffix("_osx") if _OPTIONS["autoinstall"] then local binDir = _OPTIONS["autoinstall"] ~= "" and _OPTIONS["autoinstall"] or os.getenv("GARRYSMOD_LUA_BIN") or FindGarrysModLuaBinDirectory() or DEFAULT_GARRYSMOD_LUA_BIN_DIRECTORY assert(type(binDir) == "string", "The path to GarrysMod/garrysmod/lua/bin is not a string!") filter("system:windows") postbuildcommands({"{COPY} %{cfg.buildtarget.abspath} \"" .. binDir .. "\""}) filter("system:not windows") postbuildcommands({"{COPY} %{cfg.buildtarget.abspath} \"" .. binDir .. "%{cfg.buildtarget.name}\""}) end filter({}) end function HasIncludedPackage(name) local _project = project() _project.packages = _project.packages or {} return _project.packages[name] == true end function IncludePackage(name) assert(not HasIncludedPackage(name), "a project with the name '" .. name .. "' already exists!") project().packages[name] = true end
nilq/small-lua-stack
null
local cartridge_opts = { 'advertise_uri', 'alias', 'auth_backend_name', 'auth_enabled', 'bucket_count', 'console_sock', 'http_enabled', 'http_host', 'http_port', 'roles', 'roles_reload_allowed', 'swim_broadcast', 'upgrade_schema', 'upload_prefix', 'vshard_groups', 'webui_blacklist', 'webui_enabled', 'webui_enforce_root_redirect', 'webui_prefix', 'workdir', } local box_opts = { 'background', 'checkpoint_count', 'checkpoint_interval', 'checkpoint_wal_threshold', 'custom_proc_title', 'election_mode', 'election_timeout', 'feedback_enabled', 'feedback_host', 'feedback_interval', 'feedback_crashinfo', 'force_recovery', 'hot_standby', 'instance_uuid', 'io_collect_interval', 'iproto_threads', 'listen', 'log', 'log_format', 'log_level', 'log_nonblock', 'memtx_dir', 'memtx_max_tuple_size', 'memtx_memory', 'memtx_allocator', 'memtx_min_tuple_size', 'memtx_use_mvcc_engine', 'net_msg_max', 'pid_file', 'read_only', 'readahead', 'replicaset_uuid', 'replication', 'replication_anon', 'replication_connect_quorum', 'replication_connect_timeout', 'replication_skip_conflict', 'replication_sync_lag', 'replication_sync_timeout', 'replication_synchro_quorum', 'replication_synchro_timeout', 'replication_timeout', 'replication_threads', 'slab_alloc_factor', 'slab_alloc_granularity', 'snap_io_rate_limit', 'sql_cache_size', 'strip_core', 'too_long_threshold', 'username', 'vinyl_bloom_fpr', 'vinyl_cache', 'vinyl_dir', 'vinyl_max_tuple_size', 'vinyl_memory', 'vinyl_page_size', 'vinyl_range_size', 'vinyl_read_threads', 'vinyl_run_count_per_level', 'vinyl_run_size_ratio', 'vinyl_timeout', 'vinyl_write_threads', 'wal_dir', 'wal_dir_rescan_delay', 'wal_max_size', 'wal_queue_max_size', 'wal_cleanup_delay', 'wal_mode', 'work_dir', 'worker_pool_threads', 'txn_timeout', } return { box_opts = box_opts, cartridge_opts = cartridge_opts, }
nilq/small-lua-stack
null
--[[ This file was extracted by 'EsoLuaGenerator' at '2021-09-04 16:42:26' using the latest game version. NOTE: This file should only be used as IDE support; it should NOT be distributed with addons! **************************************************************************** CONTENTS OF THIS FILE IS COPYRIGHT ZENIMAX MEDIA INC. **************************************************************************** ]] ZO_SmithingExtractionSlot = ZO_CraftingMultiSlotBase:Subclass() function ZO_SmithingExtractionSlot:New(...) return ZO_CraftingMultiSlotBase.New(self, ...) end function ZO_SmithingExtractionSlot:Initialize(owner, control, craftingInventory) local NO_EMPTY_TEXTURE = "" local NO_MULTIPLE_ITEMS_TEXTURE = "" ZO_CraftingMultiSlotBase.Initialize(self, owner, control, SLOT_TYPE_PENDING_CRAFTING_COMPONENT, NO_EMPTY_TEXTURE, NO_MULTIPLE_ITEMS_TEXTURE, craftingInventory) self.nameLabel = control:GetNamedChild("Name") end function ZO_SmithingExtractionSlot:AddItem(bagId, slotIndex) if ZO_CraftingMultiSlotBase.AddItem(self, bagId, slotIndex) then PlaySound(SOUNDS.SMITHING_ITEM_TO_EXTRACT_PLACED) return true end return false end function ZO_SmithingExtractionSlot:RemoveItem(bagId, slotIndex) if ZO_CraftingMultiSlotBase.RemoveItem(self, bagId, slotIndex) then PlaySound(SOUNDS.SMITHING_ITEM_TO_EXTRACT_REMOVED) return true end return false end function ZO_SmithingExtractionSlot:ClearItems() if ZO_CraftingMultiSlotBase.ClearItems(self) then PlaySound(SOUNDS.SMITHING_ITEM_TO_EXTRACT_REMOVED) return true end return false end function ZO_SmithingExtractionSlot:IsInRefineMode() return self.craftingInventory:GetCurrentFilterType() == SMITHING_FILTER_TYPE_RAW_MATERIALS end function ZO_SmithingExtractionSlot:Refresh() ZO_CraftingMultiSlotBase.Refresh(self) if self.nameLabel then if self:HasOneItem() then local bagId, slotIndex = self:GetItemBagAndSlot(1) self.nameLabel:SetText(zo_strformat(SI_TOOLTIP_ITEM_NAME, GetItemName(bagId, slotIndex))) if not self:HasAnimationRefs() then local displayQuality = GetItemDisplayQuality(bagId, slotIndex) self.nameLabel:SetColor(GetInterfaceColor(INTERFACE_COLOR_TYPE_ITEM_QUALITY_COLORS, displayQuality)) end elseif self:HasMultipleItems() then self.nameLabel:SetText(zo_strformat(SI_CRAFTING_SLOT_MULTIPLE_SELECTED, ZO_CommaDelimitNumber(self:GetStackCount()))) self.nameLabel:SetColor(ZO_SELECTED_TEXT:UnpackRGBA()) else self.nameLabel:SetColor(ZO_NORMAL_TEXT:UnpackRGBA()) if self:IsInRefineMode() then self.nameLabel:SetText(zo_strformat(SI_SMITHING_NEED_MORE_TO_EXTRACT, GetRequiredSmithingRefinementStackSize())) else self.nameLabel:SetText(GetString(SI_SMITHING_SELECT_ITEMS_TO_DECONSTRUCT)) end end end if self:IsInRefineMode() and self:HasOneItem() then local ALWAYS_SHOW_STACK_COUNT = true local minQuantity = GetRequiredSmithingRefinementStackSize() ZO_ItemSlot_SetAlwaysShowStackCount(self.control, ALWAYS_SHOW_STACK_COUNT, minQuantity) else local AUTO_SHOW_STACK_COUNT = false local MIN_QUANTITY = 0 ZO_ItemSlot_SetAlwaysShowStackCount(self.control, AUTO_SHOW_STACK_COUNT, MIN_QUANTITY) end end function ZO_SmithingExtractionSlot:ShowDropCallout() self.dropCallout:SetHidden(false) self.dropCallout:SetTexture("EsoUI/Art/Crafting/crafting_alchemy_goodSlot.dds") end ZO_SharedSmithingExtraction = ZO_Object:Subclass() function ZO_SharedSmithingExtraction:New(...) local smithingExtraction = ZO_Object.New(self) smithingExtraction:Initialize(...) return smithingExtraction end function ZO_SharedSmithingExtraction:Initialize(extractionSlotControl, extractLabel, owner) self.extractionSlotControl = extractionSlotControl self.extractLabel = extractLabel self.questItemId = nil self.owner = owner CRAFT_ADVISOR_MANAGER:RegisterCallback("QuestInformationUpdated", function(updatedQuestInfo) self.questItemId = updatedQuestInfo.smithingItemId end) end function ZO_SharedSmithingExtraction:InitExtractionSlot(sceneName) self.extractionSlot = ZO_SmithingExtractionSlot:New(self, self.extractionSlotControl, self.inventory) self.extractionSlot:RegisterCallback("ItemsChanged", function() self:OnSlotChanged() end) self.slotAnimation = ZO_CraftingSmithingExtractSlotAnimation:New(sceneName, function() return not self.extractionSlotControl:IsHidden() end) self.slotAnimation:AddSlot(self.extractionSlot) end function ZO_SharedSmithingExtraction_DoesItemMeetRefinementStackRequirement(bagId, slotIndex, stackCount) if ZO_SharedSmithingExtraction_IsRefinableItem(bagId, slotIndex) then return stackCount >= GetRequiredSmithingRefinementStackSize() end return true end function ZO_SharedSmithingExtraction_IsExtractableItem(itemData) return CanItemBeDeconstructed(itemData.bagId, itemData.slotIndex, GetCraftingInteractionType()) and not IsItemPlayerLocked(itemData.bagId, itemData.slotIndex) end function ZO_SharedSmithingExtraction_IsRefinableItem(bagId, slotIndex) return CanItemBeRefined(bagId, slotIndex, GetCraftingInteractionType()) end function ZO_SharedSmithingExtraction_IsExtractableOrRefinableItem(bagId, slotIndex) return CanItemBeRefined(bagId, slotIndex, GetCraftingInteractionType()) or CanItemBeDeconstructed(bagId, slotIndex, GetCraftingInteractionType()) end function ZO_SharedSmithingExtraction_DoesItemPassFilter(bagId, slotIndex, filterType) return ZO_CraftingUtils_GetSmithingFilterFromItem(bagId, slotIndex) == filterType end function ZO_SharedSmithingExtraction:OnInventoryUpdate(validItems, filterType) -- since we use this class for both refinement and extraction, but the lists for each are generated in different ways -- we need to branch our logic when dealing with those lists so that they can be handled properly if filterType == SMITHING_FILTER_TYPE_RAW_MATERIALS then local requiredStackSize = GetRequiredSmithingRefinementStackSize() self.extractionSlot:ValidateItemId(validItems, function(bagId, slotIndex) return self.inventory:GetStackCount(bagId, slotIndex) >= requiredStackSize end) else self.extractionSlot:ValidateSlottedItem(validItems) end end function ZO_SharedSmithingExtraction:ShowAppropriateSlotDropCallouts() self.extractionSlot:ShowDropCallout(true) end function ZO_SharedSmithingExtraction:HideAllSlotDropCallouts() self.extractionSlot:HideDropCallout() end function ZO_SharedSmithingExtraction:OnSlotChanged() self:OnFilterChanged() self.inventory:HandleVisibleDirtyEvent() self.owner:OnExtractionSlotChanged() end function ZO_SharedSmithingExtraction:OnItemReceiveDrag(slotControl, bagId, slotIndex) if self:CanItemBeAddedToCraft(bagId, slotIndex) then self:AddItemToCraft(bagId, slotIndex) end end function ZO_SharedSmithingExtraction:IsItemAlreadySlottedToCraft(bagId, slotIndex) return self.extractionSlot:ContainsBagAndSlot(bagId, slotIndex) end function ZO_SharedSmithingExtraction:CanItemBeAddedToCraft(bagId, slotIndex) return self:DoesItemMeetStackRequirement(bagId, slotIndex) end function ZO_SharedSmithingExtraction:AddItemToCraft(bagId, slotIndex) local newStackCount = self.extractionSlot:GetStackCount() + zo_max(1, self.inventory:GetStackCount(bagId, slotIndex)) -- non virtual items will have a stack count of 0, but still count as 1 item local stackCountPerIteration = self:IsInRefineMode() and GetRequiredSmithingRefinementStackSize() or 1 local maxStackCount = MAX_ITERATIONS_PER_DECONSTRUCTION * stackCountPerIteration if self.extractionSlot:GetNumItems() >= MAX_ITEM_SLOTS_PER_DECONSTRUCTION then ZO_Alert(UI_ALERT_CATEGORY_ERROR, SOUNDS.NEGATIVE_CLICK, GetString("SI_TRADESKILLRESULT", CRAFTING_RESULT_TOO_MANY_CRAFTING_INPUTS)) elseif self.extractionSlot:HasItems() and newStackCount > maxStackCount then -- prevent slotting if it would take us above the iteration limit, but allow it if nothing else has been slotted yet so we can support single stacks that are larger than the limit ZO_Alert(UI_ALERT_CATEGORY_ERROR, SOUNDS.NEGATIVE_CLICK, GetString("SI_TRADESKILLRESULT", CRAFTING_RESULT_TOO_MANY_CRAFTING_ITERATIONS)) else self.extractionSlot:AddItem(bagId, slotIndex) end end function ZO_SharedSmithingExtraction:RemoveItemFromCraft(bagId, slotIndex) self.extractionSlot:RemoveItem(bagId, slotIndex) end function ZO_SharedSmithingExtraction:DoesItemMeetStackRequirement(bagId, slotIndex) if ZO_SharedSmithingExtraction_IsRefinableItem(bagId, slotIndex) then return self.inventory:GetStackCount(bagId, slotIndex) >= GetRequiredSmithingRefinementStackSize() end return true end function ZO_SharedSmithingExtraction:IsSlotted(bagId, slotIndex) return self.extractionSlot:ContainsBagAndSlot(bagId, slotIndex) end function ZO_SharedSmithingExtraction:CanRefineToQuestItem(bagId, slotIndex) if self.questItemId then local refinedItemId = GetSmithingRefinedItemId(bagId, slotIndex) return refinedItemId == self.questItemId else return false end end function ZO_SharedSmithingExtraction:ExtractSingle() PrepareDeconstructMessage() local bagId, slotIndex = self.extractionSlot:GetItemBagAndSlot(1) local quantity = self:IsInRefineMode() and GetRequiredSmithingRefinementStackSize() or 1 if AddItemToDeconstructMessage(bagId, slotIndex, quantity) then SendDeconstructMessage() end end function ZO_SharedSmithingExtraction:ExtractPartialStack(quantity) PrepareDeconstructMessage() local bagId, slotIndex = self.extractionSlot:GetItemBagAndSlot(1) if AddItemToDeconstructMessage(bagId, slotIndex, quantity) then SendDeconstructMessage() end end do local function CompareExtractingItems(left, right) return left.quantity < right.quantity end function ZO_SharedSmithingExtraction:ExtractAll() PrepareDeconstructMessage() local sortedItems = {} for index = 1, self.extractionSlot:GetNumItems() do local bagId, slotIndex = self.extractionSlot:GetItemBagAndSlot(index) local quantity = self.inventory:GetStackCount(bagId, slotIndex) local step = self:IsInRefineMode() and GetRequiredSmithingRefinementStackSize() or 1 quantity = zo_floor(quantity / step) * step -- round quantity to next step down table.insert(sortedItems, {bagId = bagId, slotIndex = slotIndex, quantity = quantity}) end table.sort(sortedItems, CompareExtractingItems) local addedAllItems = true for _, item in ipairs(sortedItems) do if not AddItemToDeconstructMessage(item.bagId, item.slotIndex, item.quantity) then addedAllItems = false break end end if addedAllItems then SendDeconstructMessage() end end end function ZO_SharedSmithingExtraction:ConfirmExtractAll() if not self:IsMultiExtract() then -- single extracts do not need a confirmation dialog self:ExtractSingle() return end local dialogData = { deconstructFn = function() self:ExtractAll() end, verb = self:IsInRefineMode() and DECONSTRUCT_ACTION_NAME_REFINE or DECONSTRUCT_ACTION_NAME_DECONSTRUCT, } ZO_Dialogs_ShowPlatformDialog("CONFIRM_DECONSTRUCT_MULTIPLE_ITEMS", dialogData, {mainTextParams = {ZO_CommaDelimitNumber(self.extractionSlot:GetStackCount())}}) end function ZO_SharedSmithingExtraction:IsExtractable() return self.extractionSlot:HasItems() end function ZO_SharedSmithingExtraction:IsMultiExtract() return self.extractionSlot:HasMultipleItems() end function ZO_SharedSmithingExtraction:HasSelections() return self.extractionSlot:HasItems() end function ZO_SharedSmithingExtraction:ClearSelections() self.extractionSlot:ClearItems() end function ZO_SharedSmithingExtraction:GetFilterType() return self.inventory:GetCurrentFilterType() end function ZO_SharedSmithingExtraction:IsInRefineMode() return self:GetFilterType() == SMITHING_FILTER_TYPE_RAW_MATERIALS end do local CRAFTING_TYPE_TO_DECONSTRUCTION_TYPE = { [CRAFTING_TYPE_BLACKSMITHING] = SMITHING_DECONSTRUCTION_TYPE_WEAPONS_AND_ARMOR, [CRAFTING_TYPE_CLOTHIER] = SMITHING_DECONSTRUCTION_TYPE_ARMOR, [CRAFTING_TYPE_WOODWORKING] = SMITHING_DECONSTRUCTION_TYPE_WEAPONS_AND_ARMOR, [CRAFTING_TYPE_JEWELRYCRAFTING] = SMITHING_DECONSTRUCTION_TYPE_JEWELRY, } function ZO_SharedSmithingExtraction:GetDeconstructionType() if self:IsInRefineMode() then return SMITHING_DECONSTRUCTION_TYPE_RAW_MATERIALS else local craftingType = GetCraftingInteractionType() return CRAFTING_TYPE_TO_DECONSTRUCTION_TYPE[craftingType] end end end function ZO_SharedSmithingExtraction:OnFilterChanged() if self.extractLabel then self.extractLabel:SetText(GetString("SI_SMITHINGDECONSTRUCTIONTYPE", self:GetDeconstructionType())) end end
nilq/small-lua-stack
null
describe("metis.timer", function() describe("timeout", function() local timeout = require "metis.timer".timeout it("terminates a function", function() local then_ = os.clock() local ok = timeout(0, sleep, 1) local now = os.clock() expect(ok):eq(false) if now - then_ > 0.1 then fail("Slept for too long") end end) it("allows a function to run", function() os.queueEvent("foo") os.queueEvent("bar") os.queueEvent("baz") local got_event = false local ok = timeout(1, function() os.pullEvent() expect(os.pullEvent("baz")):eq("baz") got_event = true end) expect(ok):eq(true) expect(got_event):eq(true) end) it("returns its result", function() local res = { timeout(1, function() return 2, "foo" end) } expect(res):same { true, 2, "foo" } end) end) end)
nilq/small-lua-stack
null
local helpers = require("/dynamic/helpers/mesh_helpers.lua") function create_box(color) local mesh = helpers.new_mesh() helpers.add_vertical_cylinder_to_mesh(mesh, {0,0,0}, 40, 22, 7, color) return mesh end meshes = { create_box(0xffff00ff), -- Yellow box (used by the Shield box) create_box(0xffffffff), -- White box (used by the Shoot box) }
nilq/small-lua-stack
null
--[[ ]] local slider = {} slider.__index = slider slider._version = "0.3.5" -- aliases local lm = love.mouse local lg = love.graphics local ORIGIN = {x = 0, y = 0} -------------------------------- --------local functions--------- -------------------------------- local function clamp(n, low, high) return math.max(math.min(n, high), low) end local function distance(x1, y1, x2, y2, squared) local dx = x1 - x2 local dy = y1 - y2 local s = dx * dx + dy * dy return squared and s or math.sqrt(s) end local function vector(angle, magnitude) return math.cos(angle) * magnitude, math.sin(angle) * magnitude end local function angle(x1, y1, x2, y2) return math.atan2(y2 - y1, x2 - x1) end local function map(n, start1, stop1, start2, stop2, Clamp) local mapped = (n - start1) / (stop1 - start1) * (stop2 - start2) + start2 if not Clamp then return mapped end if start2 < stop2 then return clamp(mapped, start2, stop2) else return clamp(mapped, stop2, start2) end end -------------------------------- ----------Constructors---------- -------------------------------- function slider.new(x1, y1, angle, length, width, segments) -- slider at any angle -- segments not implimented yet. -- if you desire custom segment locations, (array) segments to designate where they will be 0-1. -- example: {0, 0.1, 0.9, 1} puts segments at the start, 10% in, 90% in and at the end. local quickAngles = { left = 0, right = math.pi, bottom = math.pi/2*3, top = math.pi/2 } angle = quickAngles[angle] or angle -- simplify common angles local b = {vector(angle, length)} local default = { parent = ORIGIN, a = {x = x1, y = y1}, b = {x = b[1] + x1, y = b[2] + y1}, angle = angle, length = length, width = width or 5, -- how wide the slider is. -- if the bar is horizontal, the hoverPerpendicularBuffer is amount above or below -- -- and the hoverParallelBuffer is left and right hoverPerpendicularBuffer = 5, hoverParallelBuffer = 0, -- segments = segments, knobImage = nil, knobOnHover = false, -- if false, it will always show. If you don't want a know, don't make one. knobScale = {1,1}, fillColor = {0.7, 0.1, 0.1, 1}, -- part of the slider not filled fill = 0.4, -- percent [0-1] of the bar that is filled. baseColor = {0.65,0.65,0.65,0.7}, -- fill portion of the slider baseImage = nil, minKnobColor = {1,1,1,1}, maxKnobColor = {1,1,1,1}, maxKnob = false, knobOffset = {0, 0}, lockCursor = false, -- this will attempt to keep the cursor locked in range of the slider. range = {0, 1}, triggerMouse = {1, 2}, triggerKeyboard = {}, requireSelfClick = true, -- require press to happen in this slider, then release in this slider. origPress = false, -- if mousepress was originally over this slider } return setmetatable(default, slider) end -------------------------------- --------main functions---------- -------------------------------- function slider:update(dt) if self.requireSelfClick and self.origPress or not self.requireSelfClick then if self:keyPressed() then self:slide(lm.getPosition()) end end end function slider:draw() lg.setColor(self.baseColor) lg.setLineWidth(self.width) local ax, ay, bx, by = self.a.x + self.parent.x, self.a.y + self.parent.y, self.b.x + self.parent.x, self.b.y + self.parent.y lg.line(ax, ay, bx, by) lg.setColor(self.fillColor) local bx, by = vector(angle(ax, ay, bx, by), self.fill * self.length) bx, by = bx + ax, by + ay lg.line(ax, ay, bx, by) if self.knobImage then if self.knobOnHover and self:inBounds(lm.getPosition()) or not self.knobOnHover then lg.setColor(1,1,1,1) lg.draw( self.knobImage, bx, by, 0, self.knobScale[1], self.knobScale[2], self.knobImage:getWidth()/2, self.knobImage:getHeight()/2 ) end end end function slider:mousepressed(x, y, b, isTouch, presses) if self:inBounds(x,y) then if self:keyPressed(b) then self.origPress = true end end end function slider:mousereleased(x, y, b, isTouch, presses) self.origPress = false end ------------------------------------------------------------------------ ------------------------------Methods----------------------------------- ------------------------------------------------------------------------ function slider:slide(mx, my) -- local nx, ny = self:nearestPointToLine(mx, my) self.fill = self:pointFill(mx, my) self.callback() end function slider:nearestPointToLine(px, py) -- for geometric line. -- returns a point on the infinite line nearest px, py local ax, ay, bx, by = self.a.x + self.parent.x, self.a.y + self.parent.y, self.b.x + self.parent.x, self.b.y + self.parent.y local a_p = {px - ax, py - ay} local a_b = {bx - ax, by - ay} local atb2 = a_b[1]^2 + a_b[2]^2 -- same as distance local atp_dot_atb = a_p[1] * a_b[1] + a_p[2] * a_b[2] local t = atp_dot_atb / atb2 return ax + a_b[1] * t, ay + a_b[2] * t end function slider:distanceToLine(px, py) -- geometric line local nx, ny = self:nearestPointToLine(px, py) return distance(nx, ny, px, py) end function slider:pointFill(px, py) -- point px, py to fill percent 0-1 from point -- gets the fill level of px, py on slider. local ax, ay, bx, by = self.a.x + self.parent.x, self.a.y + self.parent.y, self.b.x + self.parent.x, self.b.y + self.parent.y local npx, npy = self:nearestPointToLine(px, py) local a_b = distance(ax, ay, bx, by, false) local a_p = distance(ax, ay, npx, npy, false) local a_np = distance(ax, ay, npx, npy, false) local b_np = distance(bx, by, npx, npy, false) if a_np < a_b and b_np < a_b then return a_p / a_b end -- percent 0-1 if a_np < b_np then return 0 end -- clamp if b_np < a_np then return 1 end end function slider:setPosition(x, y) local b = {vector(self.angle, self.length)} self.a = {x = x + self.parent.x, y = y + self.parent.y} self.b = {x = b[1] + x + self.parent.x, y = b[2] + y + self.parent.y} end -------------------------------- ---------Get functions---------- -------------------------------- function slider:inBounds(mx, my) local npx, npy = self:nearestPointToLine(mx, my) local np_a = distance(npx, npy, self.a.x + self.parent.x, self.a.y + self.parent.y, false) local np_b = distance(npx, npy, self.b.x + self.parent.x, self.b.y + self.parent.y, false) return self:distanceToLine(mx, my) <= self.hoverPerpendicularBuffer + self.width and np_b < self.hoverParallelBuffer + self.length and np_a < self.hoverParallelBuffer + self.length end -- if not passed, it will check if it is down. function slider:keyPressed(key) for i = 1, #self.triggerMouse do if key and key == self.triggerMouse[i] or not key and love.mouse.isDown(self.triggerMouse[i]) then return true, self.triggerMouse[i] end end for i = 1, #self.triggerKeyboard do if key and key == self.triggerKeyboard[i] or not key and love.keyboard.isDown(self.triggerKeyboard[i]) then return true, self.triggerKeyboard[i] end end return false end -- get value from range function slider:getValue() return map(self.fill, 0, 1, self.range[1], self.range[2], true) end -------------------------------- ---------Set functions---------- -------------------------------- -- range(optional) is to fill based on position in range -- if range is true, pass a number to fill based on that numbers position in the range. function slider:setFill(fill, range) self.fill = range and fill / (self.range[2] - self.range[1]) or fill -- didn't finish this. If range, then set fill percent to it's place in range end function slider:addFill(fill) self.fill = clamp(self.fill + fill, 0, 1) end function slider:setAngle(angle) self.angle = angle local b = {vector(self.angle, self.length)} self.b = {x = b[1] + self.a.x + self.parent.x, y = b[2] + self.a.y + self.parent.y} end function slider:addAngle(angle) self:setAngle(self.angle + angle) end function slider:callback() end return slider
nilq/small-lua-stack
null
-- Copyright (C) Dejiang Zhu(doujiang24) local bit = require "bit" local setmetatable = setmetatable local byte = string.byte local sub = string.sub local lshift = bit.lshift local bor = bit.bor local strbyte = string.byte local _M = {} local mt = { __index = _M } function _M.new(self, str, api_version) local resp = setmetatable({ str = str, offset = 1, correlation_id = 0, api_version = api_version, }, mt) resp.correlation_id = resp:int32() return resp end function _M.int8(self) local str = self.str local offset = self.offset self.offset = offset + 1 return byte(str, offset) end function _M.int16(self) local str = self.str local offset = self.offset self.offset = offset + 2 local high = byte(str, offset) -- high padded return bor((high >= 128) and 0xffff0000 or 0, lshift(high, 8), byte(str, offset + 1)) end local function to_int32(str, offset) local offset = offset or 1 local a, b, c, d = strbyte(str, offset, offset + 3) return bor(lshift(a, 24), lshift(b, 16), lshift(c, 8), d) end _M.to_int32 = to_int32 function _M.int32(self) local str = self.str local offset = self.offset self.offset = offset + 4 return to_int32(str, offset) end -- XX return cdata: LL function _M.int64(self) local offset = self.offset self.offset = offset + 8 local a, b, c, d, e, f, g, h = strbyte(self.str, offset, offset + 7) --[[ -- only 52 bit accuracy local hi = bor(lshift(a, 24), lshift(b, 16), lshift(c, 8), d) local lo = bor(lshift(f, 16), lshift(g, 8), h) return hi * 4294967296 + 16777216 * e + lo --]] return 4294967296LL * bor(lshift(a, 56), lshift(b, 48), lshift(c, 40), lshift(d, 32)) + 16777216LL * e + bor(lshift(f, 16), lshift(g, 8), h) end function _M.string(self) local len = self:int16() local offset = self.offset self.offset = offset + len return sub(self.str, offset, offset + len - 1) end function _M.bytes(self) local len = self:int32() local offset = self.offset self.offset = offset + len return sub(self.str, offset, offset + len - 1) end function _M.nullable_string(self) local len = self:int16() if len < 0 then return "" end local offset = self.offset self.offset = offset + len return sub(self.str, offset, offset + len - 1) end function _M.correlation_id(self) return self.correlation_id end return _M
nilq/small-lua-stack
null
--[[ Netherstorm -- Ethereum Gladiator.lua This script was written and is protected by the GPL v2. This script was released by BlackHer0 of the BLUA Scripting Project. Please give proper accredidations when re-releasing or sharing this script with others in the emulation community. ~~End of License Agreement -- BlackHer0, July, 29th, 2008. ]] function Gladiator_OnEnterCombat(Unit,Event) Unit:RegisterEvent("Gladiator_Cleave",1000,0) Unit:RegisterEvent("Gladiator_Hamstring",1000,0) Unit:RegisterEvent("Gladiator_Strike",1000,0) end function Gladiator_Cleave(Unit,Event) Unit:FullCastSpellOnTarget(15284,Unit:GetClosestPlayer()) end function Gladiator_Hamstring(Unit,Event) Unit:FullCastSpellOnTarget(9080,Unit:GetClosestPlayer()) end function Gladiator_Strike(Unit,Event) Unit:FullCastSpellOnTarget(16856,Unit:GetClosestPlayer()) end function Gladiator_OnLeaveCombat(Unit,Event) Unit:RemoveEvents() end function Gladiator_OnDied(Unit,Event) Unit:RemoveEvents() end RegisterUnitEvent (20854, 1, "Gladiator_OnEnterCombat") RegisterUnitEvent (20854, 2, "Gladiator_OnEnterCombat") RegisterUnitEvent (20854, 4, "Gladiator_OnEnterCombat")
nilq/small-lua-stack
null
require("libs/addon") require("system") require("examples/object") font_size_small = math.floor((love.graphics.getHeight()/20)+1) font_small = love.graphics.newFont("libs/comicsans.ttf", font_size_small) font_size_big = math.floor((love.graphics.getHeight()/10)+1) font_big = love.graphics.newFont("libs/umeboshi.ttf", font_size_big) font_size_main = math.floor((love.graphics.getHeight()/15)+1) font_main = love.graphics.newFont("libs/umeboshi.ttf", font_size_main) love.graphics.setFont(font_main) -- Timer = require("libs/hump") -- addon.drawgroup.create(1) addon.updategroup.create(1) -- addon.drawgroup.create(2) addon.updategroup.create(2) -- addon.drawgroup.create(3) addon.updategroup.create(3) -- addon.drawgroup.create(4) addon.updategroup.create(4) -- require("menu/bg") require("menu/langmenu") require("menu/menu") require("menu/optionsmenu") require("menu/thankstomenu") require("menu/startmenu") require("menu/records") require("game/grid") require("game/stone") require("game/algorithms") require("game/bonus") require("game/ui") if(loadSettings()==false)then defaultSettings() settings.language = "_en" saveSettings() end checkSettings() if(loadRecords()==false)then defaultRecords() saveRecords() end POP = love.audio.newSource("sounds/pop.flac","static") POP:setLooping(false) POP:setVolume(0.5) BGM = love.audio.newSource("sounds/bgm.flac","stream") BGM:play() BGM:setLooping(true) BGM:setVolume(settings.musicvolume) MainMenu = menu_main.create(1) OptionsMenu = menu_options.create(1) StartMenu = menu_startgame.create(1) ThanksTo = menu_thanks.create(1) Grid = grid.create(1) Grid.perform(false) UI = ui.create(4) if(settings.firstLaunch==1)then LangMenu = menu_lang.create(1) LangMenu.perform(true) else swapLanguage() MainMenu.perform(true) end
nilq/small-lua-stack
null
local prototype = dtrequire("prototype") local Agent, State = dtrequire("agent").common() local editable = {} local Interaction = Agent:subtype() editable.Interaction = Interaction do function Interaction:isActive() return false end function Interaction:setCamera(camera) self.camera = camera end end local interactions = {} editable.interactions = interactions do local inactive = State:new({ mousepressed = function(agent, x, y, button) if button == agent.button then agent:pushState("dragging") end end, }) local dragging = State:new({ mousepressed = function(agent, x, y, button) agent:callback("mouse", x, y) end, mousereleased = function(agent, x, y, button) agent:callback("mouse", x, y) if button == agent.button then agent:popState() end end, mousemoved = function(agent, x, y) agent:callback("mouse", x, y) end, wheelmoved = function(agent, x, y) agent:callback("wheel", x, y) end, }) local DragInteraction = Interaction:subtype() editable.interactions.DragInteraction = DragInteraction do function DragInteraction:init(callback, button) Agent.init(self, {init = inactive, dragging = dragging}) self.button = button self.callback = callback end function DragInteraction:isActive() return self:getState() ~= "init" end end end local Editable = {} function Editable.newDefault() end function Editable:updateUI(Slab) end function Editable:updateInteractableShapes(hc, shapes, camera) end editable.Editable = prototype.newInterface(Editable) editable.registeredComponents = {} editable.registeredComponentNames = {} function editable.registerComponent(component, methods) prototype.registerInterface(Editable, component, methods) local name = component:getPrototypeName() editable.registeredComponents[name] = component table.insert(editable.registeredComponentNames, name) end editable.registeredSystems = {} editable.registeredSystemNames = {} function editable.registerSystem(system, methods) prototype.registerInterface(Editable, system, methods) local name = system:getPrototypeName() editable.registeredSystems[name] = system table.insert(editable.registeredSystemNames, name) end local Container = {} function Container:getWorld() end editable.Container = prototype.newInterface(Container) function editable.registerContainer(container, methods) prototype.registerInterface(Container, container, methods) end return editable
nilq/small-lua-stack
null
return {'git','gitaar','gitaarband','gitaarduo','gitaargeluid','gitaargeweld','gitaarheld','gitaarmuziek','gitaarplaat','gitaarpop','gitaarriff','gitaarrock','gitaarsolo','gitaarspel','gitaarspelende','gitaarspeler','gitaarstijl','gitaarvirtuoos','gitaarwerk','gitarist','gitariste','gitten','gitzwart','gitaarakkoord','gitaarles','gitaarleraar','gitaarzak','gitaarbegeleiding','gitaarbouwer','gitaarhals','gitaarkoffer','gitaarpartij','gitaarsnaar','gitaarsound','gitaarversterker','githion','gits','gita','gitta','gitte','gitaarbands','gitaargroepen','gitaarlessen','gitaarpartijen','gitaarriffs','gitaarsolos','gitaarspelers','gitaren','gitaristen','gitzwarte','gitaarspelen','gitas','gittas','gittes','gitaarbandjes','gitaarsnaren','gitaarversterkers','gitaarbandje','gitaarbouwers','gitaarplaten','gitaarhelden','gitaarkoffers','gitaarbanden','gitaarpartijtjes','gitaarwerken','gitaartje'}
nilq/small-lua-stack
null
function onCreate() setPropertyFromClass('GameOverSubstate', 'characterName', 'rtbf'); --Character json file for the death animation setPropertyFromClass('GameOverSubstate', 'loopSoundName', 'heartbreak'); --put in mods/music/ setPropertyFromClass('GameOverSubstate', 'endSoundName', 'heartbreakend'); --put in mods/music/ end
nilq/small-lua-stack
null
---- -- @file PhysicsCloseContact ---- Brief description. -- <#Description#> -- @return <#return value description#> function PhysicsCloseContact:calculateSerializeBufferSize() end ---- Brief description. -- @author James Folk, 16-02-11 15:02:48 -- <#Description#> -- @param dataBuffer <#dataBuffer description#> -- @param btSerializer <#btSerializer description#> -- @return function PhysicsCloseContact:serialize(dataBuffer, btSerializer) end ---- Brief description. -- <#Description#> -- @return <#return value description#> function PhysicsCloseContact:getClassName() end ---- Brief description. -- <#Description#> -- @return <#return value description#> function PhysicsCloseContact:getType() end ---- Brief description. -- <#Description#> -- @param size <#size description#> -- @return <#return value description#> function NJLI.PhysicsCloseContact.createArray(size) end ---- Brief description. -- <#Description#> -- @param array <#array description#> -- @return <#return value description#> function NJLI.PhysicsCloseContact.destroyArray(array) end ---- Brief description. -- <#Description#> -- @return <#return value description#> function NJLI.PhysicsCloseContact.create() end ---- Brief description. -- <#Description#> -- @param builder <#builder description#> -- @return <#return value description#> function NJLI.PhysicsCloseContact.create(builder) end ---- Brief description. -- <#Description#> -- @param object <#object description#> -- @return <#return value description#> function NJLI.PhysicsCloseContact.clone(object) end ---- Brief description. -- <#Description#> -- @param object <#object description#> -- @return <#return value description#> function NJLI.PhysicsCloseContact.copy(object) end ---- Brief description. -- <#Description#> -- @param object <#object description#> -- @return <#return value description#> function NJLI.PhysicsCloseContact.destroy(object) end ---- Brief description. -- <#Description#> -- @param object <#object description#> -- @param L <#L description#> -- @param stack_index <#stack_index description#> -- @return <#return value description#> function NJLI.PhysicsCloseContact.load(object, L, stack_index) end ---- Brief description. -- <#Description#> -- @return <#return value description#> function NJLI.PhysicsCloseContact.type() end
nilq/small-lua-stack
null
package.path = package.path .. ";../?.lua" -- Hack to disable color support local getenv = os.getenv os.getenv = function(sym) return (sym == "TERM") and "dumb" or getenv(sym) end -- Do color test output COLOR_RED = string.char(27) .. "[31m" COLOR_GREEN = string.char(27) .. "[32m" COLOR_RESET = string.char(27) .. "[0m" local function print_red(str) print(COLOR_RED..str..COLOR_RESET) end local function print_green(str) print(COLOR_GREEN..str..COLOR_RESET) end local dbg = require("debugger"); local dbg_read = dbg.read local dbg_write = dbg.write -- The global Lua versions will be overwritten in some tests. local lua_assert = assert local lua_error = error local LOG_IO = false function string.strip(str) return str:match("^%s*(.-)%s*$") end local module = {} -- Debugger command line string to run next. local commands = {} local function cmd(str) table.insert(commands, str) end dbg.read = function(prompt) local str = table.remove(commands, 1) lua_assert(str, COLOR_RED.."Command not set!"..COLOR_RESET) if LOG_IO then print(prompt..str) end return str end local function sanity_write(str) print_red "ERROR: dbg.write called unexpectedly?!" if LOG_IO then print(str) end end local function expect(str, cmd) local str2 = coroutine.yield():strip() if LOG_IO then print(str2) end if str ~= str2 then print_red("FAILURE (expect)") print("expected: "..str) print("got : "..str2) end end local function expect_match(pattern, cmd) pattern = "^"..pattern.."$" local str = coroutine.yield():strip() if LOG_IO then print(str2) end if not str:match(pattern) then print_red("FAILURE (expect_match)") print("expected: "..pattern) print("got : "..str) end end -- Used for setting up new tests. local function show() print("expect \""..coroutine.yield():strip().."\"") end local function ignore() local str = coroutine.yield():strip() if LOG_IO then print(str) end end function module.repl(_, test_body) dbg.read = dbg_read dbg.write = dbg_write test_body() end function module.run_test(test, test_body) local coro = coroutine.create(test) coroutine.resume(coro) dbg.write = function(str) coroutine.resume(coro, str) end test_body() dbg.write = sanity_write if coroutine.status(coro) ~= "dead" then print_red("FAILURE: test coroutine not finished") end end function module.step() expect "break via dbg() => test.lua:8 in upvalue 'func1'"; cmd "s" expect "test.lua:12 in upvalue 'func2'"; cmd "s" expect "test.lua:13 in upvalue 'func2'"; cmd "s" expect "test.lua:17 in upvalue 'func3'"; cmd "s" expect "test.lua:4 in upvalue 'do_nothing'"; cmd "s" expect "test.lua:18 in upvalue 'func3'"; cmd "s" expect "test.lua:22 in local 'test_body'"; cmd "c" print_green "STEP TESTS COMPLETE" end function module.next() expect "break via dbg() => test.lua:8 in upvalue 'func1'"; cmd "n" expect "test.lua:12 in upvalue 'func2'"; cmd "n" expect "test.lua:13 in upvalue 'func2'"; cmd "n" expect "test.lua:17 in upvalue 'func3'"; cmd "n" expect "test.lua:18 in upvalue 'func3'"; cmd "n" expect "test.lua:26 in local 'test_body'"; cmd "c" print_green "NEXT TESTS COMPLETE" end function module.finish() expect "break via dbg() => test.lua:8 in upvalue 'func1'"; cmd "f" expect "test.lua:12 in upvalue 'func2'"; cmd "f" expect "test.lua:17 in upvalue 'func3'"; cmd "f" expect "test.lua:30 in local 'test_body'"; cmd "c" print_green "FINISH TESTS COMPLETE" end function module.continue() expect "break via dbg() => test.lua:8 in upvalue 'func1'"; cmd "c" expect "break via dbg() => test.lua:8 in upvalue 'func1'"; cmd "c" expect "break via dbg() => test.lua:8 in upvalue 'func1'"; cmd "c" print_green "CONTINUE TESTS COMPLETE" end function module.trace() ignore(); -- Stack frame info that will be in the trace anyway. cmd "t" expect "Inspecting frame 0" expect "0 => test.lua:8 in upvalue 'func1'" expect "1 test.lua:11 in upvalue 'func2'" expect "2 test.lua:16 in upvalue 'func3'" expect "3 test.lua:39 in local 'test_body'" expect_match "4 ./test_util%.lua:%d+ in field 'run_test'" expect "5 test.lua:38 in chunk at test.lua:0" expect "6 [C]:-1 in chunk at [C]:-1" cmd "c" print_green "TRACE TESTS COMPLETE" end function module.updown() ignore(); cmd "u" expect "Already at the top of the stack." cmd "d" expect "Inspecting frame: test.lua:11 in upvalue 'func2'" cmd "d" expect "Inspecting frame: test.lua:16 in upvalue 'func3'" cmd "d" expect "Inspecting frame: test.lua:43 in local 'test_body'" cmd "d" expect_match "Inspecting frame: %./test_util%.lua:%d+ in field 'run_test'" cmd "d" expect "Inspecting frame: test.lua:42 in chunk at test.lua:0" cmd "d" expect "Already at the bottom of the stack." cmd "c" print_green "UP/DOWN TESTES COMPLETE" end function module.where() ignore() cmd "w 1" expect_match "7%s+dbg%(%)" expect_match "8%s+=> end" expect "9" cmd "c" ignore() cmd "w" expect_match "1%s+require%(\"debugger\"%)%(%)" expect_match "2%s+=>%s+_ = _" cmd "c" print_green "WHERE TESTS COMPLETE" end function module.eval() ignore(); cmd "e var = true" expect "debugger.lua => Set local variable var"; cmd "c" ignore(); cmd "e upvar = true" expect "debugger.lua => Set upvalue upvar"; cmd "c" ignore(); cmd "e GLOBAL = true" expect "debugger.lua => Set global variable GLOBAL"; cmd "c" print_green "EVAL TESTS COMPLETE" end function module.print() ignore() -- Basic types cmd "p 1+1"; expect "1+1 => 2" cmd "p 1, 2, 3, 4"; expect "1, 2, 3, 4 => 1, 2, 3, 4" cmd 'p "str"'; expect '"str" => "str"' cmd 'p "\\0"'; expect_match '"\\0" => "\\0+"' cmd "p {}"; expect "{} => {}" -- Kinda light on table examples because I want to avoid iteration order issues. cmd "p {1, 2, 3}"; expect "{1, 2, 3} => {1 = 1, 2 = 2, 3 = 3}" cmd "p {{}}"; expect "{{}} => {1 = {}}" cmd "p nil, false"; expect "nil, false => nil, false" cmd "p nil, nil, false"; expect "nil, nil, false => nil, nil, false" cmd "p nil, nil, nil, false"; expect "nil, nil, nil, false => nil, nil, nil, false" cmd "p nil"; expect "nil => nil" cmd "p false, nil"; expect "false, nil => false, nil" cmd "p false, nil, nil"; expect "false, nil, nil => false, nil, nil" cmd "p false, nil, nil, nil"; expect "false, nil, nil, nil => false, nil, nil, nil" CIRCULAR_REF = {} CIRCULAR_REF.ref = CIRCULAR_REF -- Don't particularly care about the result as long as it doesn't get stuck in a loop. cmd "p CIRCULAR_REF"; ignore() cmd "c" print_green "PRINT TESTS COMPLETE" end function module.locals() ignore() cmd "l" expect 'upvar => true' expect 'var => "foobar"' cmd "c" print_green "LOCALS TESTS COMPLETE" end module.print_red = print_red module.print_green = print_green return module
nilq/small-lua-stack
null