content
stringlengths
0
1.05M
origin
stringclasses
2 values
type
stringclasses
2 values
local type = type local print = print local pairs = pairs local tostring = tostring local assert = assert local format = string.format local rep = string.rep local io_open = io.open local io_write = io.write local os_date = os.date local os_time = os.time local mz = require 'minizip_ffi' -- local zip = mz.zip local zip = mz.zipTable local comp_level = mz.comp_level local function dump_val(val) if type(val) ~= 'table' then print(val) return end local max_len = 0 for k in pairs(val) do len = #tostring(k) max_len = len > max_len and len or max_len end for k, v in pairs(val) do len = #tostring(k) if type(v) == 'string' then print(rep(' ', max_len - len) .. k, format('%q', v)) else print(rep(' ', max_len - len) .. k, v) end end end print() print(zip) print() dump_val(comp_level) print() local zf = assert(zip(comp_level.better + 10)) print(#zf, zf:len(), zf) print() local t = os_time() local d = os_date('*t', t - 3600) local t = t - 3600 *2 local fn = 'test_zip.lua' local f = io_open(fn, 'r') local s = f:read('*a') f:close() print('archive(empty.file)') assert(zf:archive('empty.file', {comment = 'null file'})) print(#zf, zf:len(), zf) print() print('archive(empty.dir/)') assert(zf:archive('empty.dir/', {comment = 'null dir', date = d})) print(#zf, zf:len(), zf) print() print('archive(' .. fn .. ')') assert(zf:archive(fn, {comp_level = comp_level.faster, comment = 'lua file', date = t}, s)) print(#zf, zf:len(), zf) print() print('close:') local stream = assert(zf:close('注释 by HSQ')) print(#zf, zf:len(), zf) print('#stream', #stream) print() --assert(zf:close('注释2 by HSQ')) local fn = 'zip.zip' print('save to ' .. fn) local f = io_open(fn, 'w') f:write(stream) f:close() print() print('version:', mz.version) print()
nilq/small-lua-stack
null
-- water.lua -- adding a water block via lua module water_block_id = 0; function startup() io.write("adding a 'water' block\n"); water_block_id = api.add_block_type('water', {31, 31, 31, 31, 31, 31, 0}, false, false, true, false); end function shutdown() io.write("water module shutting down\n"); end function after_terrain_generated() io.write("fires after a block of terrain is generated"); end
nilq/small-lua-stack
null
---@class Unit Unit = {} Unit.__index = Unit ---@param id player|integer ---@param unitid integer|string ---@param x real ---@param y real ---@param face real ---@return Unit function Unit.create(id, unitid, x, y, face) local self = setmetatable({}, Unit) if type(id) == 'number' then id = Player(id) end if type(unitid) == 'string' then unitid = FourCC(unitid) end self.unit = CreateUnit(id, unitid, x, y, face) return self end ---@return Unit function Unit.triggering() local self = setmetatable({}, Unit) self.unit = GetTriggerUnit() return self end ---@param self Unit ---@param x real|nil ---@return Unit|real function Unit.x(self, x) if x == nil then return GetUnitX(self.unit) end SetUnitX(self.unit, x) return self end ---@param self Unit ---@param y real|nil ---@return Unit|real function Unit.y(self, y) if y == nil then return GetUnitY(self.unit) end SetUnitY(self.unit, y) return self end ---@param self Unit ---@param z real|nil ---@return Unit|real function Unit.z(self, z) if z == nil then return BlzGetUnitZ(self.unit) end --SetUnitFlyHeight(self.unit, z) return self end ---@param self Unit ---@param x real|nil ---@param y real|nil ---@return Unit|real, real function Unit.xy(self, x, y) if x == nil then return GetUnitX(self.unit), GetUnitY(self.unit) end SetUnitX(self.unit, x) SetUnitY(self.unit, y) return self end ---@param self Unit ---@param rad real|nil ---@return Unit|real function Unit.rad(self, rad) if rad == nil then return math.rad(GetUnitFacing(self.unit)) end SetUnitFacing(self.unit, math.rad(rad)) return self end ---@param self Unit ---@param deg real|nil ---@return Unit|real function Unit.deg(self, deg) if deg == nil then return GetUnitFacing(self.unit) end SetUnitFacing(self.unit, deg) return self end ---@param self Unit ---@return boolean function Unit.alive(self) return UnitAlive(self.unit) end
nilq/small-lua-stack
null
#!/usr/bin/env lua package.path = package.path..";../?.lua" local gl = require("moongl") local glfw = require("moonglfw") local glmath = require("moonglmath") local new_camera = require("common.camera") -- A few shortcuts: local vec3, mat4 = glmath.vec3, glmath.mat4 local rotate, translate, scale = glmath.rotate, glmath.translate, glmath.scale local transpose = glmath.transpose local clamp = glmath.clamp local perspective = glmath.perspective local rad, sin, cos = math.rad, math.sin, math.cos local SCR_WIDTH, SCR_HEIGHT = 1280, 720 -- camera: local camera = new_camera(vec3(0.0, 0.0, 3.0)) local last_x, last_y = SCR_WIDTH/2, SCR_HEIGHT/2 -- initially at the center local first_mouse = true -- glfw inits and window creation --------------------------------------------- glfw.version_hint(3, 3, 'core') local window = glfw.create_window(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL") glfw.make_context_current(window) gl.init() -- this loads all OpenGL function pointers -- build, compile, and link our shader programs -------------------------------- local prog, vsh, fsh = gl.make_program({ vertex="shaders/11.2.anti_aliasing.vert", fragment="shaders/11.2.anti_aliasing.frag", }) gl.delete_shaders(vsh, fsh) local prog1, vsh, fsh = gl.make_program({ vertex="shaders/11.2.aa_post.vert", fragment="shaders/11.2.aa_post.frag", }) gl.delete_shaders(vsh, fsh) -- set up vertex data (and buffer(s)) and configure vertex attributes local cube_vertices = { -- positions -0.5, -0.5, -0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, 0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, 0.5, -0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, -0.5, 0.5, -0.5, -0.5, 0.5, -0.5, -0.5, 0.5, -0.5, 0.5, 0.5, 0.5, 0.5, -0.5, -0.5, -0.5, 0.5, -0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, 0.5, -0.5, -0.5, 0.5, -0.5, -0.5, -0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, -0.5, 0.5, 0.5, -0.5, 0.5, -0.5 } -- vertex attributes for a quad that fills the entire screen in Normalized Device Coordinates. local quad_vertices = { -- positions -- texCoords -1.0, 1.0, 0.0, 1.0, -1.0, -1.0, 0.0, 0.0, 1.0, -1.0, 1.0, 0.0, -1.0, 1.0, 0.0, 1.0, 1.0, -1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0 } -- setup cube VAO local cube_vao = gl.new_vertex_array() local cube_vbo = gl.new_buffer('array') gl.buffer_data('array', gl.packf(cube_vertices), 'static draw') gl.enable_vertex_attrib_array(0) gl.vertex_attrib_pointer(0, 3, 'float', false, 3*gl.sizeof('float'), 0) -- setup screen VAO local quad_vao = gl.new_vertex_array() local quad_vbo = gl.new_buffer('array') gl.buffer_data('array', gl.packf(quad_vertices), 'static draw') gl.enable_vertex_attrib_array(0) gl.vertex_attrib_pointer(0, 2, 'float', false, 4*gl.sizeof('float'), 0) gl.enable_vertex_attrib_array(1) gl.vertex_attrib_pointer(1, 2, 'float', false, 4*gl.sizeof('float'), 2*gl.sizeof('float')) -- configure MSAA framebuffer local msaa_fbo = gl.new_framebuffer('draw read') -- create a multisampled color attachment texture local msaa_tex = gl.new_texture('2d multisample') gl.texture_image_multisample('2d multisample', 4, 'rgb', true, SCR_WIDTH, SCR_HEIGHT) gl.unbind_texture('2d multisample') gl.framebuffer_texture_2d('draw read', 'color attachment 0', '2d multisample', msaa_tex, 0) -- create a (also multisampled) renderbuffer object for depth and stencil attachments local rbo = gl.new_renderbuffer('renderbuffer') gl.renderbuffer_storage_multisample('renderbuffer', 4, 'depth24 stencil8', SCR_WIDTH, SCR_HEIGHT) gl.unbind_renderbuffer('renderbuffer') gl.framebuffer_renderbuffer('draw read', 'depth stencil attachment', 'renderbuffer', rbo) assert(gl.check_framebuffer_status('draw read')=='complete', "framebuffer is not complete!") gl.unbind_framebuffer('draw read') -- configure second post-processing framebuffer local intermediate_fbo = gl.new_framebuffer('draw read') -- create a color attachment texture local screen_texture = gl.new_texture('2d') gl.texture_image('2d', 0, 'rgb', 'rgb', 'ubyte', nil, SCR_WIDTH, SCR_HEIGHT) gl.texture_parameter('2d', 'min filter', 'linear') gl.texture_parameter('2d', 'mag filter', 'linear') gl.framebuffer_texture_2d('draw read', 'color attachment 0', '2d', screen_texture, 0) -- we only need a color buffer assert(gl.check_framebuffer_status('draw read')=='complete', "framebuffer is not complete!") gl.unbind_framebuffer('draw read') -- get the locations of the uniforms: local loc = {} -- holds the locations for prog (indexed by the uniform variables names) gl.use_program(prog) loc.model = gl.get_uniform_location(prog, "model") loc.view = gl.get_uniform_location(prog, "view") loc.projection = gl.get_uniform_location(prog, "projection") local loc1 = {} -- holds the locations for prog1 (indexed by the uniform variables names) gl.use_program(prog1) loc1.screenTexture = gl.get_uniform_location(prog1, "screenTexture") gl.uniformi(loc1.screenTexture, 0) glfw.set_framebuffer_size_callback(window, function (window, w, h) gl.viewport(0, 0, w, h) SCR_WIDTH, SCR_HEIGHT = w, h end) glfw.set_cursor_pos_callback(window, function(window, xpos, ypos) -- whenever the mouse moves, this callback is called if first_mouse then last_x, last_y = xpos, ypos first_mouse = false end local xoffset = xpos - last_x local yoffset = last_y - ypos -- reversed since y-coordinates go from bottom to top last_x, last_y = xpos, ypos camera:process_mouse(xoffset, yoffset, true) end) -- tell GLFW to capture our mouse: glfw.set_input_mode(window, 'cursor', 'disabled') -- configure global opengl state gl.enable('depth test') local last_frame_time = 0.0 -- last frame time local function keypressed(x) return glfw.get_key(window, x)=='press' end -- render loop while not glfw.window_should_close(window) do local t = glfw.get_time() local dt = t - last_frame_time last_frame_time = t -- process input if keypressed('escape') then glfw.set_window_should_close(window, true) end -- camera movement controlled either by WASD keys or arrow keys: if keypressed('w') or keypressed('up') then camera:process_keyboard('forward', dt) end if keypressed('a') or keypressed('left') then camera:process_keyboard('left', dt) end if keypressed('s') or keypressed('down') then camera:process_keyboard('backward', dt) end if keypressed('d') or keypressed('right') then camera:process_keyboard('right', dt) end -- 1. draw scene as normal in multisampled buffers gl.bind_framebuffer('draw read', msaa_fbo) gl.clear_color(0.1, 0.1, 0.1, 1.0) gl.clear('color', 'depth') gl.enable('depth test') -- set transformation matrices local projection = perspective(rad(camera.zoom), SCR_WIDTH/SCR_HEIGHT, 1.0, 1000.0) gl.use_program(prog) gl.uniform_matrix4f(loc.projection, true, projection) gl.uniform_matrix4f(loc.view, true, camera:view()) gl.uniform_matrix4f(loc.model, true, mat4()) gl.bind_vertex_array(cube_vao) gl.draw_arrays('triangles', 0, 36) -- 2. now blit multisampled buffer(s) to normal colorbuffer of intermediate FBO. -- Image is stored in screen_texture gl.bind_framebuffer('read', msaa_fbo) gl.bind_framebuffer('draw', intermediate_fbo) gl.blit_framebuffer(0, 0, SCR_WIDTH, SCR_HEIGHT, 0, 0, SCR_WIDTH, SCR_HEIGHT, 'nearest', 'color') -- 3. now render quad with scene's visuals as its texture image gl.unbind_framebuffer('draw read') gl.clear_color(1.0, 1.0, 1.0, 1.0) gl.clear('color') gl.disable('depth test') -- draw screen quad gl.use_program(prog1) gl.bind_vertex_array(quad_vao) gl.active_texture(0) gl.bind_texture('2d', screen_texture) -- use the now resolved color attachment as the quad's texture gl.draw_arrays('triangles', 0, 6) -- swap buffers and poll IO events glfw.swap_buffers(window) glfw.poll_events() end
nilq/small-lua-stack
null
require 'nn' require 'cunn' require 'cudnn' require 'optim' require 'xlua' require 'torch' require 'hdf5' opt_string = [[ --model (default "logs/model.net") torch model file path --h5_list_path (default "data/volume_data0.h5") h5 data path --gpu_index (default 0) GPU index --output_file (default "feat.txt") Ouput filename --output_name_file (default "names.txt") --file_label_file (default "train_file_label.txt") --partial_data use partial data as input --classes_file (default "") limit classes ]] opt = lapp(opt_string) -- print help or chosen options if opt.help == true then print('Usage: th train.lua') print('Options:') print(opt_string) os.exit() else print(opt) end nchannels = 1 if opt.partial_data then nchannels = 2 end print('#channels = ' .. nchannels) function getClassesSet(file) assert(paths.filep(file)) classes = {} for line in io.lines(file) do --split line by whitespace parts = {} for p in line:gmatch("%w+") do table.insert(parts, p) end classes[tonumber(parts[1])+1] = true end return classes end -- find set of classes class_set = getClassesSet(opt.classes_file) -- set gpu cutorch.setDevice(opt.gpu_index+1) -- output file outfile = assert(io.open(opt.output_file, "w")) outnamefile = assert(io.open(opt.output_name_file, "w")) -- specify which layer's output we would use as feature OUTPUT_LAYER_INDEX = 33 print('Loading model...') model = torch.load(opt.model):cuda() model:evaluate() print(model) function getLinesFromFile(file) assert(paths.filep(file)) lines = {} for line in io.lines(file) do lines[#lines + 1] = line end return lines end -- load h5 file data into memory function loadDataFile(file_name) local current_file = hdf5.open(file_name,'r') local current_data = current_file:read('data'):all():float() local current_label = torch.squeeze(current_file:read('label'):all():add(1)) current_file:close() return current_data, current_label end constant_ones = torch.ones(1,1,30,30,30):float() filenames = getLinesFromFile(opt.h5_list_path) print('#filenames = ' .. #filenames) instancenames = getLinesFromFile(opt.file_label_file) print('first instance:') print(instancenames[1]) fidx = 1 local count = 0 local total = 0 for fn = 1,#filenames do print('Loading data...') local current_data, current_label = loadDataFile(filenames[fn]) print(#current_data) print('Starting testing...') for t = 1,current_data:size(1) do local inputs = current_data[t][{{1,nchannels},{},{},{}}]:reshape(1,nchannels,30,30,30) --print(inputs:size()) --print(inputs:sum()) if not opt.partial_data then inputs = torch.cat(inputs, constant_ones, 2) end -- all voxels are known --print(inputs:size()) --print(inputs:sum()) local target = current_label[t] if class_set[target] then total = total + 1 local outputs = model:forward(inputs:cuda()) val, idx = torch.max(outputs:double(), 1) if idx[1] == target then count = count + 1 end --print('pred ' .. idx[1] .. ', target ' .. target) --print(instancenames[fidx]) --io.read() --print(outputs) feat = model:get(OUTPUT_LAYER_INDEX).output:double() splitter = ',' for i=1,feat:size(1) do outfile:write(string.format("%.6f", feat[i])) if i < feat:size(1) then outfile:write(splitter) end end outfile:write('\n') outnamefile:write(string.format("%s\n", instancenames[fidx])) --else -- print('warning: ignoring target ' .. target .. ' not in class set') -- io.read() end fidx = fidx + 1 end print('\tcur acc = ' .. count/total .. '\t(' .. count .. '/' .. total .. ')') end
nilq/small-lua-stack
null
------------------------ --- 2011 -03 -15 Terry@bf -- 迁移一些UI相关的功能到这里 -- UI的独立控件也会放到这里 ------------------------ --框体保存功能 local function roundUpFrameLocations(_id) local _val = BF_Frames_Config[_id] if _val then ----------这里修改一个报错。point 为string 如何 floor---------------------- BF_Frames_Config[_id].point = _val.point BF_Frames_Config[_id].refPoint = floor(_val.refPoint) BF_Frames_Config[_id].offX = floor(_val.offX) BF_Frames_Config[_id].offY = floor(_val.offY) end end function __BigFoot_Frame_Save(__frame, __id) if (__frame and __frame:IsVisible()) then BF_Frames_Config[__id]={}; local point,region,refPoint,x,y = __frame:GetPoint(1) if not region or not region:GetName() then region = "UIParent" else region = region:GetName() end BF_Frames_Config[__id] = {}; BF_Frames_Config[__id].point = point BF_Frames_Config[__id].region = region BF_Frames_Config[__id].refPoint = refPoint BF_Frames_Config[__id].offX = x BF_Frames_Config[__id].offY = y roundUpFrameLocations(__id) end end function __BigFoot_Frame_Load(__frame, __id) local point,region,refPoint,x,y if (__frame and BF_Frames_Config[__id]) then point = BF_Frames_Config[__id].point region = BF_Frames_Config[__id].region refPoint = BF_Frames_Config[__id].refPoint x = BF_Frames_Config[__id].offX y = BF_Frames_Config[__id].offY if not __frame:IsProtected() then __frame:ClearAllPoints(); __frame:SetPoint(point, region, refPoint, x,y); __frame.__user_placed = true; else BFSecureCall(__frame.ClearAllPoints,__frame); BFSecureCall(__frame.SetPoint,__frame,point, region, refPoint, x,y); __frame.__user_placed = true; end end end function __BigFoot_Frame_StopMovingOrSizing(__self) if (__self.__originalStopMovingOrSizing) then __self.__originalStopMovingOrSizing(__self); end BigFoot_DelayCall(__BigFoot_Frame_Save, 1, __self, __self.__layout_id); end function RegisterForSaveFrame(__frame, __id, __no_load) assert(__frame ~= nil, "frame must be assigned."); assert(type(__frame) == "table", "RegisterForSaveFrame: the first parameter must be frame object."); if (not __id) then __id = __frame:GetName(); end assert(__id ~= nil, "The frame has no name, can not be used as default id."); __frame.__layout_id = __id; if (not __frame.rfsf_hooked) then __frame.rfsf_hooked = true; __frame.__originalStopMovingOrSizing = __frame.StopMovingOrSizing; __frame.StopMovingOrSizing = __BigFoot_Frame_StopMovingOrSizing; end if (not __no_load) then roundUpFrameLocations(_id); __BigFoot_Frame_Load(__frame, __id); end end ---鼠标提示功能 function BigFoot_Tooltip_Init() local __index = 1; while (true) do local __TextLeft = getglobal("BigFootTooltipTextLeft"..__index); local __TextRight = getglobal("BigFootTooltipTextRight"..__index); if (__TextLeft) then __TextLeft:SetText(""); end if (__TextRight) then __TextRight:SetText(""); end if (not __TextLeft and not __TextRight) then break; else __index = __index + 1; end end; BigFootTooltip:SetOwner(UIParent, "ANCHOR_NONE"); -- BigFootTooltip:SetPoint("TOPLEFT", "UIParent", "BOTTOMRIGHT", 5, -5); BigFootTooltip:SetText("BigFootTooltip"); BigFootTooltip:Show(); end function BigFoot_Tooltip_GetText(__tooltip, __newlinechar) if (not __tooltip) then __tooltip = BigFootTooltip; end if (not __newlinechar) then __newlinechar = "<n>"; end local __strDesc = ""; __tooltip:Show(); local __index = 1; while (true) do local __TextLeft = getglobal(__tooltip:GetName().."TextLeft"..__index); local __TextRight = getglobal(__tooltip:GetName().."TextRight"..__index); local __strLeft; local __strRight; __strLeft = __TextLeft and __TextLeft:GetText(); __strRight = __TextRight and __TextRight:GetText(); local __strFull = ""; if ( __index == 1 ) then if ( __strLeft == nil ) then return; end __strTitle = __strLeft; end if ( __strLeft == nil and __strRight == nil ) then __strFull = ""; else if ( __strLeft == nil ) then __strLeft = ""; end if ( __strRight == nil ) then __strRight = ""; end if ( __strRight ~= "" ) then __strFull = __strLeft.."<t>"..__strRight; else __strFull = __strLeft; end end if ( __strFull ~= "" ) then __strDesc = __strDesc..__strFull..__newlinechar; end if (not __TextLeft and not __TextRight) then break; else __index = __index + 1; end end return __strDesc; end -- 新手提示功能 function BigFoot_ShowNewbieTooltip(__title, ...) if not __title then return end GameTooltip_SetDefaultAnchor(GameTooltip, UIParent); GameTooltip:SetText(__title, 1.0, 1.0, 1.0); local args = {...}; local i; for i = 1, table.maxn(args), 1 do GameTooltip:AddLine(args[i], NORMAL_FONT_COLOR.r, NORMAL_FONT_COLOR.g, NORMAL_FONT_COLOR.b, 1.0, 1); end GameTooltip:Show(); end function BigFoot_HideNewbieTooltip() GameTooltip:Hide(); end --[[ 无调用 --URL框体功能 function BigFoot_LaunchURL(__title, __url) BigFootURLFrameTitle:SetText("|cffffd100"..__title.."|r"); BigFootURLFrameText:SetText(BF_URL_TEXT); -- Revise url to url encoding local __new_url = ""; local __code; for __i = 1, string.len(__url), 1 do __code = string.byte(__url, __i); if (__code >= 128) then __new_url = __new_url .. string.format("%%%02X", __code); else __new_url = __new_url .. string.sub(__url, __i, __i); end end BigFootURLFrameURL.url = "bfurl:"..__new_url; BigFootURLFrameURL:SetText(BigFootURLFrameURL.url); BigFootURLFrame:Show(); end --字体颜色 function BigFoot_SetTextColor(fontInstance, r, g, b, a) local __text = fontInstance:GetText(); fontInstance:SetText(__text, r, g, b, a); end ]]
nilq/small-lua-stack
null
-- Copyright 2008 Steven Barth <[email protected]> -- Copyright 2011-2018 Jo-Philipp Wich <[email protected]> -- Licensed to the public under the Apache License 2.0. module("luci.controller.admin.network", package.seeall) function index() local page -- if page.inreq then page = entry({"admin", "system", "wireless"}, view("network/wireless"), _('Wireless'), 15) page.uci_depends = { wireless = { ["@wifi-device[0]"] = "wifi-device" } } page.leaf = true -- end end
nilq/small-lua-stack
null
--[[ Adapted from PolyBool (github.com/voidqk/polybooljs) under the MIT license. (c) 2016 Sean Connelly (@voidqk) Original Lua port by EgoMoose. Refactor and optimisations by Elttob. ]] --[[ Provides the raw computation functions that take epsilon into account. Zero is defined to be between (-epsilon, epsilon), exclusive. ]] local Epsilon = {} local epsilon = 0.0000000001 function Epsilon.epsilon(newEpsilon) if typeof(newEpsilon) == "number" then epsilon = newEpsilon end return epsilon end function Epsilon.pointAboveOrOnLine(pt, left, right) local Ax = left[1] local Ay = left[2] local Bx = right[1] local By = right[2] local Cx = pt[1] local Cy = pt[2] return (Bx - Ax) * (Cy - Ay) - (By - Ay) * (Cx - Ax) >= -epsilon end function Epsilon.pointBetween(p, left, right) -- p must be collinear with left->right -- returns false if p == left, p == right, or left == right local d_py_ly = p[2] - left[2] local d_rx_lx = right[1] - left[1] local d_px_lx = p[1] - left[1] local d_ry_ly = right[2] - left[2] local dot = d_px_lx * d_rx_lx + d_py_ly * d_ry_ly -- if `dot` is 0, then `p` == `left` or `left` == `right` (reject) -- if `dot` is less than 0, then `p` is to the left of `left` (reject) if (dot < epsilon) then return false end local sqlen = d_rx_lx * d_rx_lx + d_ry_ly * d_ry_ly -- if `dot` > `sqlen`, then `p` is to the right of `right` (reject) -- therefore, if `dot - sqlen` is greater than 0, then `p` is to the right of `right` (reject) if (dot - sqlen > -epsilon) then return false end return true end function Epsilon.pointsSameX(p1, p2) return math.abs(p1[1] - p2[1]) < epsilon end function Epsilon.pointsSameY(p1, p2) return math.abs(p1[2] - p2[2]) < epsilon end function Epsilon.pointsSame(p1, p2) return math.abs(p1[1] - p2[1]) < epsilon and math.abs(p1[2] - p2[2]) < epsilon end function Epsilon.pointsCompare(p1, p2) -- returns -1 if p1 is smaller, 1 if p2 is smaller, 0 if equal if math.abs(p1[1] - p2[1]) < epsilon then if math.abs(p1[2] - p2[2]) < epsilon then return 0 elseif p1[2] < p2[2] then return -1 else return 1 end elseif p1[1] < p2[1] then return -1 else return 1 end end function Epsilon.pointsCollinear(pt1, pt2, pt3) -- does pt1->pt2->pt3 make a straight line? -- essentially this is just checking to see if the slope(pt1->pt2) === slope(pt2->pt3) -- if slopes are equal, then they must be collinear, because they share pt2 local dx1 = pt1[1] - pt2[1] local dy1 = pt1[2] - pt2[2] local dx2 = pt2[1] - pt3[1] local dy2 = pt2[2] - pt3[2] return math.abs(dx1 * dy2 - dx2 * dy1) < epsilon end function Epsilon.linesIntersect(a0, a1, b0, b1) -- returns false if the lines are coincident (e.g., parallel or on top of each other) -- -- returns an object if the lines intersect: -- { -- pt: [x, y], where the intersection point is at -- alongA: where intersection point is along A, -- alongB: where intersection point is along B -- } -- -- alongA and alongB will each be one of: -2, -1, 0, 1, 2 -- -- with the following meaning: -- -- -2 intersection point is before segment's first point -- -1 intersection point is directly on segment's first point -- 0 intersection point is between segment's first and second points (exclusive) -- 1 intersection point is directly on segment's second point -- 2 intersection point is after segment's second point local adx = a1[1] - a0[1] local ady = a1[2] - a0[2] local bdx = b1[1] - b0[1] local bdy = b1[2] - b0[2] local axb = adx * bdy - ady * bdx if math.abs(axb) < epsilon then return false -- lines are coincident end local dx = a0[1] - b0[1] local dy = a0[2] - b0[2] local A = (bdx * dy - bdy * dx) / axb local B = (adx * dy - ady * dx) / axb local ret = { alongA = 0, alongB = 0, pt = { a0[1] + A * adx, a0[2] + A * ady } }; -- categorize where intersection point is along A and B if A <= -epsilon then ret.alongA = -2 elseif A < epsilon then ret.alongA = -1 elseif A - 1 <= -epsilon then ret.alongA = 0 elseif A - 1 < epsilon then ret.alongA = 1 else ret.alongA = 2 end if B <= -epsilon then ret.alongB = -2 elseif B < epsilon then ret.alongB = -1 elseif B - 1 <= -epsilon then ret.alongB = 0 elseif B - 1 < epsilon then ret.alongB = 1 else ret.alongB = 2 end return ret end function Epsilon.pointInsideRegion(pt, region) local x = pt[1] local y = pt[2] local lastPoint = region[#region] local last_x = lastPoint[1] local last_y = lastPoint[2] local inside = false for index, currPoint in ipairs(region) do local curr_x = currPoint[1] local curr_y = currPoint[2] -- if y is between curr_y and last_y, and -- x is to the right of the boundary created by the line if index ~= 1 and (curr_y - y > epsilon) ~= (last_y - y > epsilon) and (last_x - curr_x) * (y - curr_y) / (last_y - curr_y) + curr_x - x > epsilon then inside = not inside end last_x = curr_x last_y = curr_y end return inside end return Epsilon
nilq/small-lua-stack
null
fx_version 'bodacious' game 'gta5' ui_page { 'html/ui.html', } shared_scripts { 'config.lua', } client_scripts { 'client/client.lua', } server_scripts { '@async/async.lua', '@mysql-async/lib/MySQL.lua', 'server/server.lua', 'config.lua' } files { 'html/ui.html', 'html/assets/*.png', 'html/css/*.css', 'html/js/*.js', }
nilq/small-lua-stack
null
-- -- Hello World server -- Connects REP socket to tcp://*:5560 -- Expects "Hello" from client, replies with "World" -- -- Author: Robert G. Jakabosky <[email protected]> -- require"zmq" require"zhelpers" local context = zmq.init(1) -- Socket to talk to clients local responder = context:socket(zmq.REP) responder:connect("tcp://localhost:5560") while true do -- Wait for next request from client local msg = responder:recv() printf ("Received request: [%s]\n", msg) -- Do some 'work' s_sleep (1000) -- Send reply back to client responder:send("World") end -- We never get here but clean up anyhow responder:close() context:term()
nilq/small-lua-stack
null
local error = error local pairs = pairs local setmetatable = setmetatable local Card = {} Card.__index = Card Card.__eq = function (c1, c2) return c1:tostring() == c2:tostring() end Card.SUIT_TO_STRING = { "S", "H", "D", "C" } Card.RANK_TO_STRING = { [2] = "2", [3] = "3", [4] = "4", [5] = "5", [6] = "6", [7] = "7", [8] = "8", [9] = "9", [10] = "T", [11] = "J", [12] = "Q", [13] = "K", [14] = "A" } Card.STRING_TO_SUIT = {} Card.STRING_TO_RANK = {} for k, v in pairs(Card.SUIT_TO_STRING) do Card.STRING_TO_SUIT[v] = k end for k, v in pairs(Card.RANK_TO_STRING) do Card.STRING_TO_RANK[v] = k end setmetatable(Card, { __call = function (cls, ...) return cls.new(...) end, }) function Card.new(rank, suit) local self = setmetatable({}, Card) if not suit then rank = rank:upper() self.rank = self.STRING_TO_RANK[rank:sub(1, 1)] self.suit = self.STRING_TO_SUIT[rank:sub(2, 2)] else self.rank = rank self.suit = suit end if self.rank < 2 or self.rank > 14 then error("invalid card rank!") end if self.suit < 1 or self.suit > 4 then error("invalid card suit!") end return self end function Card:tostring() return self.RANK_TO_STRING[self.rank] .. self.SUIT_TO_STRING[self.suit] end return Card
nilq/small-lua-stack
null
local CATEGORY_NAME = "TTT" function ulx.cc_credits( ply, targs ) for _, v in ipairs( targs ) do ply:AddCredits(100) end SendFullStateUpdate() ulx.fancyLogAdmin( ply, true, "#A gave #T credits", targs ) end local credits = ulx.command( CATEGORY_NAME, "ulx credits", ulx.cc_credits, "!credits", true ) credits:addParam{type=ULib.cmds.PlayersArg, hint = "<user(s)>"} credits:defaultAccess( ULib.ACCESS_SUPERADMIN ) credits:help( "gives 100 credits" )
nilq/small-lua-stack
null
local Timer = require 'vendor/timer' local sound = require 'vendor/TEsound' return{ name = 'humbug', die_sound = 'acorn_crush', position_offset = { x = 0, y = -1 }, height = 40, width = 58, bb_width = 44, bb_height = 26, bb_offset = {x=2, y=7}, damage = 10, hp = 1, velocity = { x = 60, y = 30 }, vulnerabilities = {'blunt'}, tokens = 1, tokenTypes = { -- p is probability ceiling and this list should be sorted by it, with the last being 1 { item = 'coin', v = 1, p = 0.9 }, { item = 'health', v = 1, p = 1 } }, antigravity = true, animations = { dying = { right = {'once', {'7,2'}, 0.4}, left = {'once',{'7,1'}, 0.4} }, default = { right = {'loop', {'1-6, 2'}, 0.1}, left = {'loop', {'1-6, 1'}, 0.1} }, hurt = { right = {'loop', {'1-6, 2'}, 0.1}, left = {'loop', {'1-6, 1'}, 0.1} }, attack = { right = {'loop', {'1-6, 4'}, 0.05}, left = {'loop', {'1-6, 3'}, 0.05} }, }, enter = function(enemy) enemy.start_y = enemy.position.y enemy.end_y = enemy.start_y - (enemy.height*2) enemy.start_x = enemy.position.x end, attack = function(enemy) enemy.state = 'attack' Timer.add(30, function() if enemy.state ~= 'dying' then enemy.state = 'default' end end) end, update = function( dt, enemy, player ) if enemy.position.x > player.position.x then enemy.direction = 'left' else enemy.direction = 'right' end if enemy.state == 'default' then if enemy.position.x ~= enemy.start_x and (math.abs(enemy.position.x - enemy.start_x) > 3) then if enemy.position.x > enemy.start_x then enemy.direction = 'left' enemy.velocity.x = enemy.props.velocity.x else enemy.direction = 'right' enemy.velocity.x = -enemy.props.velocity.x end end if enemy.position.y > enemy.start_y then enemy.going_up = true end if enemy.position.y < enemy.end_y then enemy.going_up = false end if enemy.going_up then enemy.velocity.y = -enemy.props.velocity.y else enemy.velocity.y = enemy.props.velocity.y end end if enemy.state == 'attack' then local rage_factor = 4 if(math.abs(enemy.position.x - player.position.x) > 1) then if enemy.direction == 'left' then enemy.velocity.x = enemy.props.velocity.x * rage_factor * 0.5 else enemy.velocity.x = -enemy.props.velocity.x * rage_factor * 0.5 end else enemy.velocity.x = 0 end if (math.abs(enemy.position.y - player.position.y) > 1) then if enemy.position.y < player.position.y then enemy.velocity.y = enemy.props.velocity.y * rage_factor else enemy.velocity.y = -enemy.props.velocity.y * rage_factor end else enemy.velocity.y = 0 end end end, floor_pushback = function() end, }
nilq/small-lua-stack
null
-------------------------------- -- @module WebView -- @extend Widget -- @parent_module ccui ---@class ccui.WebView:ccui.Widget local WebView = {} ccui.WebView = WebView -------------------------------- --- SetOpacity of webview. ---@param opacity number ---@return ccui.WebView function WebView:setOpacityWebView(opacity) end -------------------------------- --- Gets whether this WebView has a back history item. --- return WebView has a back history item. ---@return boolean function WebView:canGoBack() end -------------------------------- --- Sets the main page content and base URL. --- param string The content for the main page. --- param baseURL The base URL for the content. ---@param string string ---@param baseURL string ---@return ccui.WebView function WebView:loadHTMLString(string, baseURL) end -------------------------------- --- Goes forward in the history. ---@return ccui.WebView function WebView:goForward() end -------------------------------- --- Goes back in the history. ---@return ccui.WebView function WebView:goBack() end -------------------------------- --- Set WebView should support zooming. The default value is false. ---@param scalesPageToFit boolean ---@return ccui.WebView function WebView:setScalesPageToFit(scalesPageToFit) end -------------------------------- --- Loads the given fileName. --- param fileName Content fileName. ---@param fileName string ---@return ccui.WebView function WebView:loadFile(fileName) end -------------------------------- --- Loads the given URL with cleaning cached data or not.<br> -- param url Content URL.<br> -- cleanCachedData Whether to clean cached data. ---@param url string ---@param cleanCachedData boolean ---@return ccui.WebView ---@overload fun(self:ccui.WebView, url:string):ccui.WebView function WebView:loadURL(url, cleanCachedData) end -------------------------------- --- Set whether the webview bounces at end of scroll of WebView. ---@param bounce boolean ---@return ccui.WebView function WebView:setBounces(bounce) end -------------------------------- --- Evaluates JavaScript in the context of the currently displayed page. ---@param js string ---@return ccui.WebView function WebView:evaluateJS(js) end -------------------------------- --- set the background transparent ---@return ccui.WebView function WebView:setBackgroundTransparent() end -------------------------------- --- Get the Javascript callback. ---@return function function WebView:getOnJSCallback() end -------------------------------- --- Gets whether this WebView has a forward history item. --- return WebView has a forward history item. ---@return boolean function WebView:canGoForward() end -------------------------------- --- Stops the current load. ---@return ccui.WebView function WebView:stopLoading() end -------------------------------- --- getOpacity of webview. ---@return number function WebView:getOpacityWebView() end -------------------------------- --- Reloads the current URL. ---@return ccui.WebView function WebView:reload() end -------------------------------- --- Set javascript interface scheme. --- see WebView::setOnJSCallback() ---@param scheme string ---@return ccui.WebView function WebView:setJavascriptInterfaceScheme(scheme) end -------------------------------- --- Allocates and initializes a WebView. ---@return ccui.WebView function WebView:create() end -------------------------------- --- ---@return ccui.WebView function WebView:onEnter() end -------------------------------- --- Toggle visibility of WebView. ---@param visible boolean ---@return ccui.WebView function WebView:setVisible(visible) end -------------------------------- --- ---@return ccui.WebView function WebView:onExit() end -------------------------------- --- Default constructor. ---@return ccui.WebView function WebView:WebView() end return nil
nilq/small-lua-stack
null
----------------------------------- -- -- tpz.effect.VISITANT -- ----------------------------------- function onEffectGain(target, effect) end function onEffectTick(target, effect) --[[ local duration = effect:getDuration() if (target:getCharVar("Abyssea_Time") >= 3) then target:setCharVar("Abyssea_Time", duration) end Some messages about remaining time.will need to handled outside of this effect (zone ejection warnings after visitant is gone). ]] end function onEffectLose(target, effect) end
nilq/small-lua-stack
null
object_tangible_quest_avatar_cold_storage = object_tangible_quest_shared_avatar_cold_storage:new { } ObjectTemplates:addTemplate(object_tangible_quest_avatar_cold_storage, "object/tangible/quest/avatar_cold_storage.iff")
nilq/small-lua-stack
null
-- Utility functions for calculating the Intersection over Union for evaluation -- By: Kiana Ehsani function clean_mask_output(result) if torch.sum(result) == 0 then return result:float() end local thr = 0.5 return torch.ge(result,thr):float() end function calc_iou(gt, result) local output = clean_mask_output(result) local clean_gt = clean_mask_output(gt) local sum = clean_gt sum:add(output) local intersection = torch.ge(sum, 2):float() local union = torch.ge(sum, 1):float() local iou = 0 if torch.sum(union) ~= 0 then iou = torch.sum(intersection) / torch.sum(union) end return iou end -- Calulate the IOU for just the SI mask for evaluation function calcIouJustAmodal(outputi, modali, amodali) local out = clean_mask(outputi) local amod = clean_mask(amodali) local mod = clean_mask(modali) local res = torch.csub(out, mod) res = torch.gt(res, 0):float() local target = torch.csub(amod, mod) target = torch.gt(target, 0):float() if torch.sum(res) == 0 and torch.sum(target) == 0 then return 1 end return calc_iou(target, res) end -- Calculate the SI based on the SV and SF from groundtruth and the predicted output -- @param modal_resized groundtruth SV -- @param amodal_resized groundtruth SF -- @param output predicted SF -- @param tag Different tags in case we are calculating the IOU for different models function calc_SV_SI(modal_resized, amodal_resized, output, tag) local output = clean_mask_output(output):squeeze() local weights = get_mask(modal_resized, amodal_resized) local justSIoutput = output:clone():cuda() justSIoutput[torch.ne(weights, 2)] = 0 local justSIgt = amodal_resized:clone():cuda() justSIgt[torch.ne(weights, 2)] = 0 local justSIIOU = calc_iou(justSIgt, justSIoutput) if tag == 'output' then ind = 1 else ind = 2 end if not just_iou_SI then just_iou_SI = {0,0} counter_SI_iou = 0 end counter_SI_iou = counter_SI_iou + 1 just_iou_SI[ind] = just_iou_SI[ind] + justSIIOU print('Average IOU for SI ' .. just_iou_SI[ind] / counter_SI_iou) end
nilq/small-lua-stack
null
local tap = require('util/tap') local test = tap.test test("Get all local http addresses", function(expect, uv) assert(uv.getaddrinfo(nil, "http", nil, expect(function(err, res) console.log(#res, res[1]) assert(not err, err) assert(res[1].port == 80) end))) end) test("Get all local http addresses sync", function(expect, uv) local res = assert(uv.getaddrinfo(nil, "http")) console.log(#res, res[1]) assert(res[1].port == 80) end) test("Get only ipv4 tcp adresses for baidu.com", function(expect, uv) local options = { socktype = "stream", family = "inet" } assert(uv.getaddrinfo("baidu.com", nil, options, expect(function(err, res) assert(not err, err) console.log(#res, res[1]) assert(#res >= 1) end))) end) if _G.isWindows then test("Get only ipv6 tcp adresses for baidu.com", function(expect, uv) local options = { socktype = "stream", family = "inet6" } assert(uv.getaddrinfo("baidu.com", nil, options, expect(function(err, res) assert(not err, err) console.log(res, #res) assert(#res == 1) end))) end) end test("Get ipv4 and ipv6 tcp adresses for baidu.com", function(expect, uv) assert(uv.getaddrinfo("baidu.com", nil, { socktype = "stream"}, expect(function(err, res) assert(not err, err) -- console.log(res, #res) assert(#res > 0) console.log(#res, res[1]) end))) end) test("Get all adresses for baidu.com", function(expect, uv) assert(uv.getaddrinfo("baidu.com", nil, nil, expect(function(err, res) assert(not err, err) --console.log(res, #res) assert(#res > 0) console.log(#res, res[1]) end))) end) test("Lookup local ipv4 address", function(expect, uv) assert(uv.getnameinfo({family = "inet"}, expect(function(err, hostname, service) console.log{err = err, hostname = hostname, service = service} assert(not err, err) assert(hostname) assert(service) end))) end) test("Lookup local ipv4 address sync", function(expect, uv) local hostname, service = assert(uv.getnameinfo({family = "inet"})) console.log{hostname = hostname, service = service} assert(hostname) assert(service) end) test("Lookup local 127.0.0.1 ipv4 address", function(expect, uv) assert(uv.getnameinfo({ip = "127.0.0.1"}, expect(function(err, hostname, service) console.log{err = err, hostname = hostname, service = service} assert(not err, err) assert(hostname) assert(service) end))) end) test("Lookup local ipv6 address", function(expect, uv) assert(uv.getnameinfo({family = "inet6"},expect(function(err, hostname, service) console.log{err = err, hostname = hostname, service = service} assert(not err, err) assert(hostname) assert(service) end))) end) test("Lookup local ::1 ipv6 address", function(expect, uv) assert(uv.getnameinfo({ip = "::1"}, expect(function(err, hostname, service) console.log{err = err, hostname = hostname, service = service} assert(not err, err) assert(hostname) assert(service) end))) end) test("Lookup local port 80 service", function(expect, uv) assert(uv.getnameinfo({port = 80, family = "inet6"}, expect(function(err, hostname, service) console.log{err = err, hostname = hostname, service = service} assert(not err, err) assert(hostname) assert(service == "http") end))) end) tap.run()
nilq/small-lua-stack
null
PLUGIN = PLUGIN Clockwork.kernel:IncludePrefixed("sv_plugin.lua");
nilq/small-lua-stack
null
-- Created by Elfansoer --[[ Ability checklist (erase if done/checked): - Scepter Upgrade - Break behavior - Linken/Reflect behavior - Spell Immune/Invulnerable/Invisible behavior - Illusion behavior - Stolen behavior ]] -------------------------------------------------------------------------------- modifier_razor_eye_of_the_storm_lua_debuff = class({}) -------------------------------------------------------------------------------- -- Classifications function modifier_razor_eye_of_the_storm_lua_debuff:IsHidden() return false end function modifier_razor_eye_of_the_storm_lua_debuff:IsDebuff() return true end function modifier_razor_eye_of_the_storm_lua_debuff:IsPurgable() return false end -------------------------------------------------------------------------------- -- Initializations function modifier_razor_eye_of_the_storm_lua_debuff:OnCreated( kv ) if not IsServer() then return end -- send init data from server to client self:SetHasCustomTransmitterData( true ) self.armor = kv.armor self:SetStackCount( self.armor ) end function modifier_razor_eye_of_the_storm_lua_debuff:OnRefresh( kv ) if not IsServer() then return end self.armor = self.armor + kv.armor self:SetStackCount( self.armor ) end function modifier_razor_eye_of_the_storm_lua_debuff:OnRemoved() end function modifier_razor_eye_of_the_storm_lua_debuff:OnDestroy() end -------------------------------------------------------------------------------- -- Transmitter data function modifier_razor_eye_of_the_storm_lua_debuff:AddCustomTransmitterData() -- on server local data = { armor = self.armor } return data end function modifier_razor_eye_of_the_storm_lua_debuff:HandleCustomTransmitterData( data ) -- on client self.armor = data.armor end -------------------------------------------------------------------------------- -- Modifier Effects function modifier_razor_eye_of_the_storm_lua_debuff:DeclareFunctions() local funcs = { MODIFIER_PROPERTY_PHYSICAL_ARMOR_BONUS, } return funcs end function modifier_razor_eye_of_the_storm_lua_debuff:GetModifierPhysicalArmorBonus() return -self.armor end
nilq/small-lua-stack
null
local tonumber = tonumber local debug = debug function IsNull(ptr) return ptr == nil end function NotNull(ptr) return ptr ~= nil end local ffi = require("ffi") local uint_t = ffi.typeof("unsigned int") function PtrToNum(ptr) return tonumber(ffi.cast(uint_t, ptr)) end require("luaextensions.math") require("luaextensions.table") require("luaextensions.string")
nilq/small-lua-stack
null
local Concord = require("lib.concord") local Animation = Concord.component(function(e, animations, initialState) e.animations = animations e.current = initialState end) function Animation:switch(newState) local animation = self.animations[newState] animation.currentTime = 0 animation.currentFrame = 1 self.current = newState end return Animation
nilq/small-lua-stack
null
function GM:PlayerNoClip(client) return client:IsAdmin() end -- luacheck: globals HOLDTYPE_TRANSLATOR HOLDTYPE_TRANSLATOR = {} HOLDTYPE_TRANSLATOR[""] = "normal" HOLDTYPE_TRANSLATOR["physgun"] = "smg" HOLDTYPE_TRANSLATOR["ar2"] = "smg" HOLDTYPE_TRANSLATOR["crossbow"] = "shotgun" HOLDTYPE_TRANSLATOR["rpg"] = "shotgun" HOLDTYPE_TRANSLATOR["slam"] = "normal" HOLDTYPE_TRANSLATOR["grenade"] = "grenade" HOLDTYPE_TRANSLATOR["fist"] = "normal" HOLDTYPE_TRANSLATOR["melee2"] = "melee" HOLDTYPE_TRANSLATOR["passive"] = "normal" HOLDTYPE_TRANSLATOR["knife"] = "melee" HOLDTYPE_TRANSLATOR["duel"] = "pistol" HOLDTYPE_TRANSLATOR["camera"] = "smg" HOLDTYPE_TRANSLATOR["magic"] = "normal" HOLDTYPE_TRANSLATOR["revolver"] = "pistol" -- luacheck: globals PLAYER_HOLDTYPE_TRANSLATOR PLAYER_HOLDTYPE_TRANSLATOR = {} PLAYER_HOLDTYPE_TRANSLATOR[""] = "normal" PLAYER_HOLDTYPE_TRANSLATOR["fist"] = "normal" PLAYER_HOLDTYPE_TRANSLATOR["pistol"] = "normal" PLAYER_HOLDTYPE_TRANSLATOR["grenade"] = "normal" PLAYER_HOLDTYPE_TRANSLATOR["melee"] = "normal" PLAYER_HOLDTYPE_TRANSLATOR["slam"] = "normal" PLAYER_HOLDTYPE_TRANSLATOR["melee2"] = "normal" PLAYER_HOLDTYPE_TRANSLATOR["passive"] = "normal" PLAYER_HOLDTYPE_TRANSLATOR["knife"] = "normal" PLAYER_HOLDTYPE_TRANSLATOR["duel"] = "normal" PLAYER_HOLDTYPE_TRANSLATOR["bugbait"] = "normal" local getModelClass = ix.anim.GetModelClass local IsValid = IsValid local string = string local type = type local PLAYER_HOLDTYPE_TRANSLATOR = PLAYER_HOLDTYPE_TRANSLATOR local HOLDTYPE_TRANSLATOR = HOLDTYPE_TRANSLATOR function GM:TranslateActivity(client, act) local model = string.lower(client.GetModel(client)) local modelClass = getModelClass(model) or "player" local weapon = client.GetActiveWeapon(client) if (modelClass == "player") then if (!ix.config.Get("wepAlwaysRaised") and IsValid(weapon) and !client.IsWepRaised(client) and client.OnGround(client)) then if (string.find(model, "zombie")) then local tree = ix.anim.zombie if (string.find(model, "fast")) then tree = ix.anim.fastZombie end if (tree[act]) then return tree[act] end end local holdType = IsValid(weapon) and (weapon.HoldType or weapon.GetHoldType(weapon)) or "normal" if (!ix.config.Get("wepAlwaysRaised") and IsValid(weapon) and !client.IsWepRaised(client) and client:OnGround()) then holdType = PLAYER_HOLDTYPE_TRANSLATOR[holdType] or "passive" end local tree = ix.anim.player[holdType] if (tree and tree[act]) then if (type(tree[act]) == "string") then client.CalcSeqOverride = client.LookupSequence(client, tree[act]) return else return tree[act] end end end return self.BaseClass.TranslateActivity(self.BaseClass, client, act) end local tree = ix.anim[modelClass] if (tree) then local subClass = "normal" if (client.InVehicle(client)) then local vehicle = client.GetVehicle(client) local vehicleClass = vehicle:IsChair() and "chair" or vehicle:GetClass() if (tree.vehicle and tree.vehicle[vehicleClass]) then act = tree.vehicle[vehicleClass][1] local fixvec = tree.vehicle[vehicleClass][2] if (fixvec) then client:SetLocalPos(Vector(16.5438, -0.1642, -20.5493)) end if (type(act) == "string") then client.CalcSeqOverride = client.LookupSequence(client, act) return else return act end else act = tree.normal[ACT_MP_CROUCH_IDLE][1] if (type(act) == "string") then client.CalcSeqOverride = client:LookupSequence(act) end return end elseif (client.OnGround(client)) then client.ManipulateBonePosition(client, 0, vector_origin) if (IsValid(weapon)) then subClass = weapon.HoldType or weapon.GetHoldType(weapon) subClass = HOLDTYPE_TRANSLATOR[subClass] or subClass end if (tree[subClass] and tree[subClass][act]) then local act2 = tree[subClass][act][client.IsWepRaised(client) and 2 or 1] if (type(act2) == "string") then client.CalcSeqOverride = client.LookupSequence(client, act2) return end return act2 end elseif (tree.glide) then return tree.glide end end end function GM:CanPlayerUseBusiness(client, uniqueID) local itemTable = ix.item.list[uniqueID] if (!client:GetChar()) then return false end if (itemTable.noBusiness) then return false end if (itemTable.factions) then local allowed = false if (type(itemTable.factions) == "table") then for _, v in pairs(itemTable.factions) do if (client:Team() == v) then allowed = true break end end elseif (client:Team() != itemTable.factions) then allowed = false end if (!allowed) then return false end end if (itemTable.classes) then local allowed = false if (type(itemTable.classes) == "table") then for _, v in pairs(itemTable.classes) do if (client:GetChar():GetClass() == v) then allowed = true break end end elseif (client:GetChar():GetClass() == itemTable.classes) then allowed = true end if (!allowed) then return false end end if (itemTable.flag) then if (!client:GetChar():HasFlags(itemTable.flag)) then return false end end return true end function GM:DoAnimationEvent(client, event, data) local model = client:GetModel():lower() local class = ix.anim.GetModelClass(model) if (class == "player") then return self.BaseClass:DoAnimationEvent(client, event, data) else local weapon = client:GetActiveWeapon() if (IsValid(weapon)) then local holdType = weapon.HoldType or weapon:GetHoldType() holdType = HOLDTYPE_TRANSLATOR[holdType] or holdType local animation = ix.anim[class][holdType] if (event == PLAYERANIMEVENT_ATTACK_PRIMARY) then client:AnimRestartGesture(GESTURE_SLOT_ATTACK_AND_RELOAD, animation.attack or ACT_GESTURE_RANGE_ATTACK_SMG1, true) return ACT_VM_PRIMARYATTACK elseif (event == PLAYERANIMEVENT_ATTACK_SECONDARY) then client:AnimRestartGesture(GESTURE_SLOT_ATTACK_AND_RELOAD, animation.attack or ACT_GESTURE_RANGE_ATTACK_SMG1, true) return ACT_VM_SECONDARYATTACK elseif (event == PLAYERANIMEVENT_RELOAD) then client:AnimRestartGesture(GESTURE_SLOT_ATTACK_AND_RELOAD, animation.reload or ACT_GESTURE_RELOAD_SMG1, true) return ACT_INVALID elseif (event == PLAYERANIMEVENT_JUMP) then client:AnimRestartMainSequence() return ACT_INVALID elseif (event == PLAYERANIMEVENT_CANCEL_RELOAD) then client:AnimResetGestureSlot(GESTURE_SLOT_ATTACK_AND_RELOAD) return ACT_INVALID end end end return ACT_INVALID end function GM:EntityEmitSound(data) if (data.Entity.ixIsMuted) then return false end end local vectorAngle = FindMetaTable("Vector").Angle local normalizeAngle = math.NormalizeAngle function GM:CalcMainActivity(client, velocity) client:SetPoseParameter("move_yaw", normalizeAngle(vectorAngle(velocity)[2] - client:EyeAngles()[2])) local oldSeqOverride = client.CalcSeqOverride local seqIdeal = self.BaseClass:CalcMainActivity(client, velocity) --client.CalcSeqOverride is being -1 after this line. if (client.ixForceSeq and client:GetSequence() != client.ixForceSeq) then client:SetCycle(0) end return seqIdeal, client.ixForceSeq or oldSeqOverride or client.CalcSeqOverride end local KEY_BLACKLIST = IN_ATTACK + IN_ATTACK2 function GM:StartCommand(client, command) local isRaised, weapon = client:IsWepRaised() if (!isRaised and (!weapon or !weapon.FireWhenLowered)) then command:RemoveKey(KEY_BLACKLIST) end end function GM:OnCharVarChanged(char, varName, oldVar, newVar) if (ix.char.varHooks[varName]) then for _, v in pairs(ix.char.varHooks[varName]) do v(char, oldVar, newVar) end end end function GM:CanPlayerThrowPunch(client) if (!client:IsWepRaised()) then return false end return true end function GM:OnCharCreated(client, character) local faction = ix.faction.Get(character:GetFaction()) if (faction and faction.OnCharCreated) then faction:OnCharCreated(client, character) end end function GM:GetDefaultCharName(client, faction) local info = ix.faction.indices[faction] if (info and info.GetDefaultName) then return info:GetDefaultName(client) end end function GM:CanPlayerUseChar(client, char) local banned = char:GetData("banned") if (banned) then if (type(banned) == "number" and banned < os.time()) then return end return false, "@charBanned" end end function GM:CanProperty(client, property, entity) if (client:IsAdmin()) then return true end if (CLIENT and (property == "remover" or property == "collision")) then return true end return false end function GM:PhysgunPickup(client, entity) local bPickup = false if (client:IsSuperAdmin()) then bPickup = true elseif (client:IsAdmin() and !(entity:IsPlayer() and entity:IsSuperAdmin())) then bPickup = true elseif (self.BaseClass:PhysgunPickup(client, entity) == false) then return false end if (bPickup and entity:IsPlayer()) then entity:SetMoveType(MOVETYPE_NONE) end return bPickup end function GM:PhysgunDrop(client, entity) if (entity:IsPlayer()) then entity:SetMoveType(MOVETYPE_WALK) end end local TOOL_SAFE = {} TOOL_SAFE["lamp"] = true TOOL_SAFE["camera"] = true local TOOL_DANGEROUS = {} TOOL_DANGEROUS["dynamite"] = true function GM:CanTool(client, trace, tool) if (client:IsAdmin()) then return true end if (TOOL_DANGEROUS[tool]) then return false end local entity = trace.Entity if (IsValid(entity)) then if (TOOL_SAFE[tool]) then return true end else return true end return false end function GM:Move(client, moveData) local char = client:GetChar() if (char) then if (client:GetNetVar("actAng")) then moveData:SetForwardSpeed(0) moveData:SetSideSpeed(0) moveData:SetVelocity(Vector(0, 0, 0)) end if (client:GetMoveType() == MOVETYPE_WALK and moveData:KeyDown(IN_WALK)) then local mf, ms = 0, 0 local speed = client:GetWalkSpeed() local ratio = ix.config.Get("walkRatio") if (moveData:KeyDown(IN_FORWARD)) then mf = ratio elseif (moveData:KeyDown(IN_BACK)) then mf = -ratio end if (moveData:KeyDown(IN_MOVELEFT)) then ms = -ratio elseif (moveData:KeyDown(IN_MOVERIGHT)) then ms = ratio end moveData:SetForwardSpeed(mf * speed) moveData:SetSideSpeed(ms * speed) end end end function GM:CanItemBeTransfered(itemObject, curInv, inventory) if (itemObject and itemObject.isBag) then if (inventory.id != 0 and curInv.id != inventory.id) then if (inventory.vars and inventory.vars.isBag) then local owner = itemObject:GetOwner() if (IsValid(owner)) then owner:NotifyLocalized("nestedBags") end return false end elseif (inventory.id != 0 and curInv.id == inventory.id) then return end inventory = ix.item.inventories[itemObject:GetData("id")] if (inventory) then for _, v in pairs(inventory:GetItems()) do if (v:GetData("equip") == true) then local owner = itemObject:GetOwner() if (owner and IsValid(owner)) then owner:NotifyLocalized("equippedBag") end return false end end end end end function GM:ShowHelp() end function GM:PreGamemodeLoaded() hook.Remove("PostDrawEffects", "RenderWidgets") hook.Remove("PlayerTick", "TickWidgets") hook.Remove("RenderScene", "RenderStereoscopy") end function GM:PostGamemodeLoaded() baseclass.Set("ix_character", ix.meta.character) baseclass.Set("ix_inventory", ix.meta.inventory) baseclass.Set("ix_item", ix.meta.item) end
nilq/small-lua-stack
null
local libd = _G.library_directory local class = require(libd .. "middleclass") local Timer = class("Timer") function Timer:initialize(max) self.time = 0 self.max = max end function Timer:update(dt, callback) self.time = self.time + dt if self.time > self.max then callback() self.time = 0 end end return Timer
nilq/small-lua-stack
null
Config = {} Config.Locations = { [1] = { ["model"] = { ["coords"] = vector3(-1070.1, -279.26, 36.74), ["h"] = 252.18, ["hash"] = "g_f_y_lost_01", }, }, [2] = { ["model"] = { ["coords"] = vector3(-1070.53, -280.57, 36.74), ["h"] = 266.41, ["hash"] = "u_m_m_jesus_01", }, }, [3] = { ["model"] = { ["coords"] = vector3(-1069.91, -279.92, 36.74), ["h"] = 266.41, ["hash"] = "a_c_pug", }, }, }
nilq/small-lua-stack
null
local t = require('luatest') local g = t.group() local utils = require('test.utils') local Average = require('metrics.collectors.average') g.test_collect = function() local instance = Average:new('latency') instance:observe(1) instance:observe(2) instance:observe(3, {tag = 'a'}) instance:observe(4, {tag = 'a'}) instance:observe(5, {tag = 'b'}) utils.assert_observations(instance:collect(), { {'latency_count', 2, {}}, {'latency_avg', 1.5, {}}, {'latency_count', 2, {tag = 'a'}}, {'latency_avg', 3.5, {tag = 'a'}}, {'latency_count', 1, {tag = 'b'}}, {'latency_avg', 5, {tag = 'b'}}, }) utils.assert_observations(instance:collect(), { {'latency_count', 2, {}}, {'latency_avg', 0, {}}, {'latency_count', 2, {tag = 'a'}}, {'latency_avg', 0, {tag = 'a'}}, {'latency_count', 1, {tag = 'b'}}, {'latency_avg', 0, {tag = 'b'}}, }) end
nilq/small-lua-stack
null
-- luyi7338 汉化 -- Sharak@BigFoot 增加繁体版数据 if (GetLocale() == "zhCN") then TrinketMenu.CheckOptInfo = { {"ShowIcon","ON","迷你地图按钮","显示或隐藏小地图按钮."}, {"SquareMinimap","OFF","方形迷你地图","如果迷你地图是方形移动迷你地图按钮.","ShowIcon"}, {"CooldownCount","OFF","冷却计时","在按钮上显示剩余冷却时间."}, {"TooltipFollow","OFF","跟随鼠标","提示信息跟随鼠标.","ShowTooltips"}, {"KeepOpen","OFF","保持列表开启","保持饰物列表始终开启."}, {"KeepDocked","ON","保持列表粘附","保持饰物列表粘附在当前装备列表."}, {"Notify","OFF","可使用提示","饰物冷却后提示玩家."}, {"DisableToggle","OFF","禁止开关","止使用点击小地图按钮来控制列表的显示/隐藏.","ShowIcon"}, {"NotifyChatAlso","OFF","在聊天窗口提示","在饰物冷却结束后在聊天窗口也发出提示信息."}, {"Locked","OFF","锁定窗口","不能移动,缩放,转动饰品列表."}, {"ShowTooltips","ON","显示提示信息","显示提示信息."}, {"NotifyThirty","ON","三十秒提示","在饰品冷却前三十秒时提示玩家."}, {"MenuOnShift","OFF","Shift显示列表","只有按下Shift才会显示饰品选择列表."}, {"TinyTooltips","OFF","迷你提示","简化饰品的提示信息变为只有名字, 用途, 冷却.","ShowTooltips"}, {"SetColumns","OFF","设置列表列数","设置饰品选择列表的列数.\n\n不选择此项 TrinketMenu 会自动排列."}, {"LargeCooldown","ON","大字体","用更大的字体显示冷却时间.","CooldownCount"}, {"ShowHotKeys","ON","显示快捷键","在饰品上显示绑定的快捷键."}, {"StopOnSwap","OFF","被动饰品停止排队","当换上一个被动饰品时停止自动排队. 选中这个选项时, 当一个可点击饰品通过 TrinketMenu 被手动换上时同样会停止自动排队. 当频繁标记饰品为优先时这个选项尤其有用"}, {"HideOnLoad","OFF","当配置载入时关闭","当你载入一个配置时关闭这个窗口."}, {"RedRange","OFF","射程警告","当有效目标在饰品的射程外时饰品变红警告. 例如, 侏儒死亡射线和侏儒捕网器."}, {"MenuOnRight","OFF","右击菜单","防止菜单出现除非一个警告饰品被右击.\n\n提示: 战斗中不能改变这个选项."} } TrinketMenu.TooltipInfo = { {"TrinketMenu_LockButton","锁定窗口","不能移动,缩放,转动饰品列表."}, {"TrinketMenu_Trinket0Check","上面饰品栏自动排队","选中这个选项会让饰品自动排队替换到上面的饰品栏. 你也可以Alt+点击饰品来开关自动排队."}, {"TrinketMenu_Trinket1Check","下面饰品栏自动排队","选中这个选项会让饰品自动排队替换到下面的饰品栏. 你也可以Alt+点击饰品来开关自动排队."}, {"TrinketMenu_SortPriority","高优先权","当选中这个选项时, 这个饰品会被第一时间装备上, 而不管装备着的饰品是否在冷却中.\n\n当没选中时, 这个饰品不会替换掉没有在冷却中的已装备饰品."}, {"TrinketMenu_SortDelay","延迟替换","设置一个饰品被替换的时间 (秒). 比如, 你需要20秒得到大地之击的20秒BUFF."}, {"TrinketMenu_SortKeepEquipped","暂停自动排队","选中这个选项,当这个饰品被装备时会暂停自动排队替换. 比如, 你有一个自动换装的插件在你骑马时把棍子上的胡萝卜装备上了."}, {"TrinketMenu_Profiles","配置文件","你可以载入或保存一个队列配置."}, {"TrinketMenu_Delete","删除","从列表中删这个饰品. 更下面的饰品完全不会影响. 这个选项仅仅用来保持列表的可控性. 提示: 你包包里的饰品将回到列表的最下面."}, {"TrinketMenu_ProfilesDelete","删除配置","移除这个配置Remove this profile."}, {"TrinketMenu_ProfilesLoad","载入配置","为选中饰品槽载入一个队列. 你也可以双击一个配置来载入它."}, {"TrinketMenu_ProfilesSave","保存配置","保存选中饰品槽的队列. 任一饰品槽都可以使用它."}, {"TrinketMenu_ProfileName","配置名","为这个配置输入一个名字. 保存后, 你可以载入给任一饰品槽."}, {"TrinketMenu_OptBindButton","绑定饰品","单击这里为你的上/下面饰品绑定一个热键."} } TrinketMenu.Tooltip1 = "点击: 开关选项窗口\n拖动: 移动设置按钮"; TrinketMenu.Tooltip2 = "左键点击: 开关饰物窗口\n右键点击: 开关选项窗口\n拖动: 移动设置按钮"; StopQueueHereText1 = "-- 停止排队线 --"; StopQueueHereText2 = "停止排队线"; StopQueueHereTooltip = "移动这个来标记让下面的饰品不自动排队. 当你想让一个被动饰品只允许手动换上时, 就把它移动到这条线的下面."; TrinketMenu_Tab1:SetText("选项"); TrinketMenu_Tab2:SetText("下面 "); TrinketMenu_Tab3:SetText("上面 "); TrinketMenu_SortDelayText1:SetText("延迟"); TrinketMenu_SortDelayText2:SetText("秒"); TrinketMenu_ProfileNameText:SetText("配置"); TrinketMenu_ProfilesDelete:SetText("删除"); TrinketMenu_ProfilesLoad:SetText("载入"); TrinketMenu_ProfilesSave:SetText("保存"); TrinketMenu_ProfilesCancel:SetText("取消"); --TrinketMenu_OptBindButton:SetText("热键绑定"); TrinketMenu.Message1 = "|cFFFFFF00TrinketMenu 缩放:"; TrinketMenu.Message2 = "/trinket scale main (number) : 设置主列表缩放比"; TrinketMenu.Message3 = "/trinket scale menu (number) : 设置选择列表缩放比"; TrinketMenu.Message4 = "比如: /trinket scale menu 0.85"; TrinketMenu.Message5 = "提示: 你可以拖动右下角调整缩放比."; TrinketMenu.Message6= "|cFFFFFF00TrinketMenu 帮助:"; TrinketMenu.Message7 = "/trinket or /trinketmenu : 开关列表"; TrinketMenu.Message8 = "/trinket reset : 重置所有设置"; TrinketMenu.Message9 = "/trinket opt : 打开设置窗口"; TrinketMenu.Message10 = "/trinket lock|unlock : 锁定/解锁窗口"; TrinketMenu.Message11 = "/trinket scale main|menu (number) : 缩放主/列表"; TrinketMenu.Message12 = "|cFFFFFF00TrinketMenu 载入:"; TrinketMenu.Message13 = "/trinket load (top|bottom) profilename\nie: /trinket load bottom PvP"; TrinketMenu.Message14 = "/trinket load top|bottom profilename : 为上/下饰品载入一个配置文件"; BINDING_NAME_TOGGLE_TRINKETMENU = "打开/关闭饰品管理"; BINDING_HEADER_TRINKETMENU = "饰品管理"; _G['BINDING_NAME_CLICK TrinketMenu_Trinket0:LeftButton'] = "使用1号饰品"; _G['BINDING_NAME_CLICK TrinketMenu_Trinket1:LeftButton'] = "使用2号饰品"; elseif (GetLocale() == "zhTW") then TrinketMenu.CheckOptInfo = { {"ShowIcon","ON","迷你地圖按鈕","顯示或隱藏小地圖按鈕."}, {"SquareMinimap","OFF","方形迷你地圖","如果迷你地圖是方形移動迷你地圖按鈕.","ShowIcon"}, {"CooldownCount","OFF","冷卻計時","在按鈕上顯示剩餘冷卻時間."}, {"TooltipFollow","OFF","跟隨滑鼠","提示資訊跟隨滑鼠.","ShowTooltips"}, {"KeepOpen","OFF","保持列表開啟","保持飾物列表始終開啟."}, {"KeepDocked","ON","保持列表粘附","保持飾物列表粘附在當前裝備列表."}, {"Notify","OFF","可使用提示","飾物冷卻後提示玩家."}, {"DisableToggle","OFF","禁止開關","止使用點擊小地圖按鈕來控制列表的顯示/隱藏.","ShowIcon"}, {"NotifyChatAlso","OFF","在聊天窗口提示","在飾物冷卻結束後在聊天視窗也發出提示資訊."}, {"Locked","OFF","鎖定視窗","不能移動,縮放,轉動飾品列表."}, {"ShowTooltips","ON","顯示提示資訊","顯示提示資訊."}, {"NotifyThirty","ON","三十秒提示","在飾品冷卻前三十秒時提示玩家."}, {"MenuOnShift","OFF","Shift顯示列表","只有按下Shift才會顯示飾品選擇列表."}, {"TinyTooltips","OFF","迷你提示","簡化飾品的提示資訊變為只有名字, 用途, 冷卻.","ShowTooltips"}, {"SetColumns","OFF","設置列表列數","設置飾品選擇列表的列數.\n\n不選擇此項 TrinketMenu 會自動排列."}, {"LargeCooldown","ON","大字體","用更大的字體顯示冷卻時間.","CooldownCount"}, {"ShowHotKeys","ON","顯示快捷鍵","在飾品上顯示綁定的快捷鍵."}, {"StopOnSwap","OFF","被動飾品停止排隊","當換上一個被動飾品時停止自動排隊. 選中這個選項時, 當一個可點擊飾品通過 TrinketMenu 被手動換上時同樣會停止自動排隊. 當頻繁標記飾品為優先時這個選項尤其有用"}, {"HideOnLoad","OFF","當配置載入時關閉","當你載入一個配置時關閉這個視窗."}, {"RedRange","OFF","射程警告","當有效目標在飾品的射程外時飾品變紅警告. 例如, 侏儒死亡射線和侏儒捕網器."}, {"MenuOnRight","OFF","右擊功能表","防止功能表出現除非一個警告飾品被右擊.\n\n提示: 戰鬥中不能改變這個選項."} } TrinketMenu.TooltipInfo = { {"TrinketMenu_LockButton","鎖定視窗","不能移動,縮放,轉動飾品列表."}, {"TrinketMenu_Trinket0Check","上面飾品欄自動排隊","選中這個選項會讓飾品自動排隊替換到上面的飾品欄. 你也可以Alt+點擊飾品來開關自動排隊."}, {"TrinketMenu_Trinket1Check","下面飾品欄自動排隊","選中這個選項會讓飾品自動排隊替換到下面的飾品欄. 你也可以Alt+點擊飾品來開關自動排隊."}, {"TrinketMenu_SortPriority","高優先權","當選中這個選項時, 這個飾品會被第一時間裝備上, 而不管裝備著的飾品是否在冷卻中.\n\n當沒選中時, 這個飾品不會替換掉沒有在冷卻中的已裝備飾品."}, {"TrinketMenu_SortDelay","延遲替換","設置一個飾品被替換的時間 (秒). 比如, 你需要20秒得到大地之擊的20秒BUFF."}, {"TrinketMenu_SortKeepEquipped","暫停自動排隊","選中這個選項,當這個飾品被裝備時會暫停自動排隊替換. 比如, 你有一個自動換裝的插件在你騎馬時把棍子上的胡蘿蔔裝備上了."}, {"TrinketMenu_Profiles","配置檔","你可以載入或保存一個佇列配置."}, {"TrinketMenu_Delete","刪除","從列表中刪這個飾品. 更下面的飾品完全不會影響. 這個選項僅僅用來保持列表的可控性. 提示: 你包包裏的飾品將回到列表的最下麵."}, {"TrinketMenu_ProfilesDelete","刪除配置","移除這個配置Remove this profile."}, {"TrinketMenu_ProfilesLoad","載入配置","為選中飾品槽載入一個佇列. 你也可以雙擊一個配置來載入它."}, {"TrinketMenu_ProfilesSave","保存配置","保存選中飾品槽的佇列. 任一飾品槽都可以使用它."}, {"TrinketMenu_ProfileName","配置名","為這個配置輸入一個名字. 保存後, 你可以載入給任一飾品槽."}, {"TrinketMenu_OptBindButton","綁定飾品","單擊這裏為你的上/下面飾品綁定一個熱鍵."} } TrinketMenu.Tooltip1 = "點擊: 開關選項視窗\n拖動: 移動設置按鈕"; TrinketMenu.Tooltip2 = "左鍵點擊: 開關飾物視窗\n右鍵點擊: 開關選項視窗\n拖動: 移動設置按鈕"; StopQueueHereText1 = "-- 停止排隊線 --"; StopQueueHereText2 = "停止排隊線"; StopQueueHereTooltip = "移動這個來標記讓下面的飾品不自動排隊. 當你想讓一個被動飾品只允許手動換上時, 就把它移動到這條線的下麵."; TrinketMenu_Tab1:SetText("選項"); TrinketMenu_Tab2:SetText("下麵 "); TrinketMenu_Tab3:SetText("上面 "); TrinketMenu_SortDelayText1:SetText("延遲"); TrinketMenu_SortDelayText2:SetText("秒"); TrinketMenu_ProfileNameText:SetText("配置"); TrinketMenu_ProfilesDelete:SetText("刪除"); TrinketMenu_ProfilesLoad:SetText("載入"); TrinketMenu_ProfilesSave:SetText("保存"); TrinketMenu_ProfilesCancel:SetText("取消"); --TrinketMenu_OptBindButton:SetText("熱鍵綁定"); TrinketMenu.Message1 = "|cFFFFFF00TrinketMenu 縮放:"; TrinketMenu.Message2 = "/trinket scale main (number) : 設置主列表縮放比"; TrinketMenu.Message3 = "/trinket scale menu (number) : 設置選擇列表縮放比"; TrinketMenu.Message4 = "比如: /trinket scale menu 0.85"; TrinketMenu.Message5 = "提示: 你可以拖動右下角調整縮放比."; TrinketMenu.Message6= "|cFFFFFF00TrinketMenu 説明:"; TrinketMenu.Message7 = "/trinket or /trinketmenu : 開關列表"; TrinketMenu.Message8 = "/trinket reset : 重置所有設置"; TrinketMenu.Message9 = "/trinket opt : 打開設置視窗"; TrinketMenu.Message10 = "/trinket lock|unlock : 鎖定/解鎖窗口"; TrinketMenu.Message11 = "/trinket scale main|menu (number) : 縮放主/列表"; TrinketMenu.Message12 = "|cFFFFFF00TrinketMenu 載入:"; TrinketMenu.Message13 = "/trinket load (top|bottom) profilename\nie: /trinket load bottom PvP"; TrinketMenu.Message14 = "/trinket load top|bottom profilename : 為上/下飾品載入一個配置檔"; BINDING_NAME_TOGGLE_TRINKETMENU = "打開/關閉飾品管理"; BINDING_HEADER_TRINKETMENU = "飾品管理"; _G['BINDING_NAME_CLICK TrinketMenu_Trinket0:LeftButton'] = "使用1號飾品"; _G['BINDING_NAME_CLICK TrinketMenu_Trinket1:LeftButton'] = "使用2號飾品"; else TrinketMenu.Tooltip1 ="Click: toggle options\nDrag: move icon"; TrinketMenu.Tooltip2 = "Left click: toggle trinkets\nRight click: toggle options\nDrag: move icon"; StopQueueHereText1 = "-- stop queue here --"; StopQueueHereText2 = "Stop Queue Here"; StopQueueHereTooltip = "Move this to mark the lowest trinket to auto queue. Sometimes you may want a passive trinket with a click effect to be the end (Burst of Knowledge, Second Wind, etc)."; TrinketMenu.Message1 = "|cFFFFFF00TrinketMenu scale:"; TrinketMenu.Message2 = "/trinket scale main (number) : set exact main scale"; TrinketMenu.Message3 = "/trinket scale menu (number) : set exact menu scale"; TrinketMenu.Message4 = "ie, /trinket scale menu 0.85"; TrinketMenu.Message5 = "Note: You can drag the lower-right corner of either window to scale. This slash command is for those who want to set an exact scale."; TrinketMenu.Message6= "|cFFFFFF00TrinketMenu useage:"; TrinketMenu.Message7 = "/trinket or /trinketmenu : toggle the window"; TrinketMenu.Message8 = "/trinket reset : reset all settings"; TrinketMenu.Message9 = "/trinket opt : summon options window"; TrinketMenu.Message10 = "/trinket lock|unlock : toggles window lock"; TrinketMenu.Message11 = "/trinket scale main|menu (number) : sets an exact scale"; TrinketMenu.Message12 = "|cFFFFFF00TrinketMenu load:"; TrinketMenu.Message13 = "/trinket load (top|bottom) profilename\nie: /trinket load bottom PvP"; TrinketMenu.Message14 = "/trinket load top|bottom profilename : loads a profile to top or bottom trinket"; BINDING_NAME_TOGGLE_TRINKETMENU = "Toggle TrinketMenu"; BINDING_HEADER_TRINKETMENU = "TrinketMenu"; _G['BINDING_NAME_CLICK TrinketMenu_Trinket0:LeftButton'] = "Use first trinket"; _G['BINDING_NAME_CLICK TrinketMenu_Trinket1:LeftButton'] = "Use second trinket"; end
nilq/small-lua-stack
null
SWEP.Base = "tfa_nmrimelee_base" SWEP.Category = "TFA NMRIH - CotZ" SWEP.Spawnable = true SWEP.AdminSpawnable = true SWEP.PrintName = "Fire Axe" SWEP.ViewModel = "models/weapons/tfa_nmrih/v_me_axe_fire.mdl" --Viewmodel path SWEP.ViewModelFOV = 50 SWEP.Slot = 3 SWEP.WorldModel = "models/weapons/tfa_nmrih/w_me_axe_fire.mdl" --Viewmodel path SWEP.HoldType = "melee2" SWEP.DefaultHoldType = "melee2" SWEP.Offset = { --Procedural world model animation, defaulted for CS:S purposes. Pos = { Up = -6, Right = 1, Forward = 3, }, Ang = { Up = -1, Right = -4, Forward = 178 }, Scale = 1.0 } SWEP.Primary.Ammo = "Pistol" SWEP.Primary.Sound = ""--Sound("Weapon_Melee.HatchetLight") SWEP.Secondary.Sound = ""--Sound("Weapon_Melee.FireaxeHeavy") SWEP.MoveSpeed = 0.9 SWEP.IronSightsMoveSpeed = SWEP.MoveSpeed SWEP.InspectPos = Vector(5.5, 1.424, -3.131) SWEP.InspectAng = Vector(17.086, 3.938, 14.836) SWEP.Primary.RPM = 50 SWEP.Primary.Damage = 130 SWEP.Secondary.Damage = 250 SWEP.Secondary.BashDelay = 0.3 SWEP.ViewModelBoneMods = { ["ValveBiped.Bip01_R_Finger1"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0.254, 0.09), angle = Angle(15.968, -11.193, 1.437) }, ["ValveBiped.Bip01_R_Finger0"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(3.552, 4.526, 0) }, ["Thumb04"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(6, 0, 0) }, ["Middle04"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(-8.212, 1.121, 1.263) }, ["Pinky05"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(11.793, 4.677, 11.218) } }
nilq/small-lua-stack
null
model.dlg={} function model.dlg.updateEnabledDisabledItems() if model.dlg.ui then local simStopped=sim.getSimulationState()==sim.simulation_stopped local config=model.readInfo() simUI.setEnabled(model.dlg.ui,1365,simStopped,true) simUI.setEnabled(model.dlg.ui,30,simStopped,true) end end function model.dlg.refresh() if model.dlg.ui then local config=model.readInfo() local sel=simBWF.getSelectedEditWidget(model.dlg.ui) simUI.setEditValue(model.dlg.ui,1365,simBWF.getObjectAltName(model.handle),true) simUI.setCheckboxValue(model.dlg.ui,30,simBWF.getCheckboxValFromBool(sim.boolAnd32(config['bitCoded'],1)~=0),true) local connectionHandle,p=simBWF.getInputOutputBoxConnectedItem(model.handle) local tmp=simBWF.getObjectAltNameOrNone(connectionHandle) if connectionHandle>=0 then tmp=tmp..' (on port '..tonumber(p)..')' end simUI.setLabelText(model.dlg.ui,31,tmp) local tx='low' if config.signalState then tx='high' end simUI.setLabelText(model.dlg.ui,32,tx) model.dlg.updateEnabledDisabledItems() simBWF.setSelectedEditWidget(model.dlg.ui,sel) end end function model.dlg.hiddenDuringSimulation_callback(ui,id,newVal) local c=model.readInfo() c['bitCoded']=sim.boolOr32(c['bitCoded'],1) if newVal==0 then c['bitCoded']=c['bitCoded']-1 end simBWF.markUndoPoint() model.writeInfo(c) model.dlg.refresh() end function model.dlg.manualTriggerLow_callback(ui,id) local c=model.readInfo() c.signalState=false model.writeInfo(c) model.updatePluginRepresentation() model.dlg.updateEnabledDisabledItems() model.signalWasToggled(false) end function model.dlg.manualTriggerHigh_callback(ui,id) local c=model.readInfo() c.signalState=true model.writeInfo(c) model.updatePluginRepresentation() model.dlg.updateEnabledDisabledItems() model.signalWasToggled(true) end function model.dlg.nameChange(ui,id,newVal) if simBWF.setObjectAltName(model.handle,newVal)>0 then simBWF.markUndoPoint() model.updatePluginRepresentation() simUI.setTitle(ui,simBWF.getUiTitleNameFromModel(model.handle,model.modelVersion,model.codeVersion)) end model.dlg.refresh() end function model.dlg.createDlg() if (not model.dlg.ui) and simBWF.canOpenPropertyDialog() then local xml =[[ <tabs id="77"> <tab title="General"> <group layout="form" flat="false"> <label text="Name"/> <edit on-editing-finished="model.dlg.nameChange" id="1365" style="* {min-width: 300px;}"/> <label text="Connected to"/> <label text="x" id="31"/> <label text="Signal state"/> <label text="x" id="32"/> </group> </tab> <tab title="More"> <group layout="form" flat="false"> <label text="Hidden during simulation"/> <checkbox text="" checked="false" on-change="model.dlg.hiddenDuringSimulation_callback" id="30"/> </group> </tab> </tabs> ]] model.dlg.ui=simBWF.createCustomUi(xml,simBWF.getUiTitleNameFromModel(model.handle,model.modelVersion,model.codeVersion),model.dlg.previousDlgPos,false,nil,false,false,false) model.dlg.refresh() simUI.setCurrentTab(model.dlg.ui,77,model.dlg.mainTabIndex,true) end end function model.dlg.showDlg() if not model.dlg.ui then model.dlg.createDlg() end end function model.dlg.removeDlg() if model.dlg.ui then local x,y=simUI.getPosition(model.dlg.ui) model.dlg.previousDlgPos={x,y} model.dlg.mainTabIndex=simUI.getCurrentTab(model.dlg.ui,77) simUI.destroy(model.dlg.ui) model.dlg.ui=nil end end function model.dlg.showOrHideDlgIfNeeded() local s=sim.getObjectSelection() if s and #s>=1 and s[#s]==model.handle then model.dlg.showDlg() else model.dlg.removeDlg() end end function model.dlg.init() model.dlg.mainTabIndex=0 model.dlg.previousDlgPos=simBWF.readSessionPersistentObjectData(model.handle,"dlgPosAndSize") end function model.dlg.cleanup() simBWF.writeSessionPersistentObjectData(model.handle,"dlgPosAndSize",model.dlg.previousDlgPos) end
nilq/small-lua-stack
null
Citizen.CreateThread(function() while true do Citizen.Wait(100) if IsControlPressed(0, 22) then SendNUIMessage("dismiss") end end end)
nilq/small-lua-stack
null
object_tangible_holiday_love_day_love_day_ewok_cupid_familiar_deed = object_tangible_holiday_love_day_shared_love_day_ewok_cupid_familiar_deed:new { } ObjectTemplates:addTemplate(object_tangible_holiday_love_day_love_day_ewok_cupid_familiar_deed, "object/tangible/holiday/love_day/love_day_ewok_cupid_familiar_deed.iff")
nilq/small-lua-stack
null
require "objc" require "cocoa" local Hoge = objc.runtime.createClass("Hoge",cocoa.NSObject,{}) objc.runtime.class_addMethod(Hoge,"test1:",function(self,_cmd,a) print("Hoge -test1:",a) end,"v0@0:0i0") objc.runtime.class_addMethod(Hoge,"test2:",function(self,_cmd,a) print("Hoge -test2:",a) end,"v0@0:0i0") objc.runtime.class_addMethod(Hoge,"dealloc",function(self,_cmd) print("Hoge -dealloc") self.__super(cocoa.NSObject):dealloc() end,"v0@0:0") local Piyo = objc.runtime.createClass("Piyo",Hoge,{}) objc.runtime.class_addMethod(Piyo,"test1:",function(self,_cmd,a) print("Piyo -test1:",a) self.__super(Hoge):test1_(a) end,"v0@0:0i0") objc.runtime.class_addMethod(Piyo,"dealloc",function(self,_cmd) print("Piyo -dealloc") self.__super(Hoge):dealloc() end,"v0@0:0") local o = Piyo:new() print(o) print(o:isKindOfClass_(Hoge)) o:test1_(123) o:test2_(123)
nilq/small-lua-stack
null
--Beetrooper Landing --Scripted by: XGlitchy30 function c101106090.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_SPECIAL_SUMMON+CATEGORY_FUSION_SUMMON) e1:SetDescription(aux.Stringid(101106090,0)) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetTarget(c101106090.target) e1:SetOperation(c101106090.activate) c:RegisterEffect(e1) --recycle local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(101106090,1)) e2:SetCategory(CATEGORY_TOHAND) e2:SetType(EFFECT_TYPE_IGNITION) e2:SetRange(LOCATION_GRAVE) e2:SetCountLimit(1,101106090) e2:SetCondition(aux.exccon) e2:SetCost(c101106090.thcost) e2:SetTarget(c101106090.thtg) e2:SetOperation(c101106090.thop) c:RegisterEffect(e2) end function c101106090.filter1(c,e) return not c:IsImmuneToEffect(e) end function c101106090.filter2(c,e,tp,m,f,chkf) return c:IsType(TYPE_FUSION) and c:IsRace(RACE_INSECT) and (not f or f(c)) and c:IsCanBeSpecialSummoned(e,SUMMON_TYPE_FUSION,tp,false,false) and c:CheckFusionMaterial(m,nil,chkf) end function c101106090.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then local chkf=tp local mg1=Duel.GetFusionMaterial(tp) local res=Duel.IsExistingMatchingCard(c101106090.filter2,tp,LOCATION_EXTRA,0,1,nil,e,tp,mg1,nil,chkf) if not res then local ce=Duel.GetChainMaterial(tp) if ce~=nil then local fgroup=ce:GetTarget() local mg2=fgroup(ce,e,tp) local mf=ce:GetValue() res=Duel.IsExistingMatchingCard(c101106090.filter2,tp,LOCATION_EXTRA,0,1,nil,e,tp,mg2,mf,chkf) end end return res end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_EXTRA) end function c101106090.activate(e,tp,eg,ep,ev,re,r,rp) local chkf=tp local mg1=Duel.GetFusionMaterial(tp):Filter(c101106090.filter1,nil,e) local sg1=Duel.GetMatchingGroup(c101106090.filter2,tp,LOCATION_EXTRA,0,nil,e,tp,mg1,nil,chkf) local mg2=nil local sg2=nil local ce=Duel.GetChainMaterial(tp) if ce~=nil then local fgroup=ce:GetTarget() mg2=fgroup(ce,e,tp) local mf=ce:GetValue() sg2=Duel.GetMatchingGroup(c101106090.filter2,tp,LOCATION_EXTRA,0,nil,e,tp,mg2,mf,chkf) end if sg1:GetCount()>0 or (sg2~=nil and sg2:GetCount()>0) then local sg=sg1:Clone() if sg2 then sg:Merge(sg2) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local tg=sg:Select(tp,1,1,nil) local tc=tg:GetFirst() if sg1:IsContains(tc) and (sg2==nil or not sg2:IsContains(tc) or not Duel.SelectYesNo(tp,ce:GetDescription())) then local mat1=Duel.SelectFusionMaterial(tp,tc,mg1,nil,chkf) tc:SetMaterial(mat1) Duel.SendtoGrave(mat1,REASON_EFFECT+REASON_MATERIAL+REASON_FUSION) Duel.BreakEffect() Duel.SpecialSummon(tc,SUMMON_TYPE_FUSION,tp,tp,false,false,POS_FACEUP) else local mat2=Duel.SelectFusionMaterial(tp,tc,mg2,nil,chkf) local fop=ce:GetOperation() fop(ce,e,tp,tc,mat2,SUMMON_TYPE_FUSION) end tc:CompleteProcedure() end end function c101106090.cfilter(c) return c:IsRace(RACE_INSECT) and c:IsAbleToRemoveAsCost() end function c101106090.thcost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c101106090.cfilter,tp,LOCATION_GRAVE,0,2,e:GetHandler()) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE) local g=Duel.SelectMatchingCard(tp,c101106090.cfilter,tp,LOCATION_GRAVE,0,2,2,e:GetHandler()) if #g>0 then Duel.Remove(g,POS_FACEUP,REASON_COST) end end function c101106090.thtg(e,tp,eg,ep,ev,re,r,rp,chk) local c=e:GetHandler() if chk==0 then return c:IsAbleToHand() end Duel.SetOperationInfo(0,CATEGORY_TOHAND,c,1,0,0) end function c101106090.thop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if c:IsRelateToEffect(e) then Duel.SendtoHand(c,nil,REASON_EFFECT) end end
nilq/small-lua-stack
null
-- -- Licensed to the Apache Software Foundation (ASF) under one or more -- contributor license agreements. See the NOTICE file distributed with -- this work for additional information regarding copyright ownership. -- The ASF licenses this file to You under the Apache License, Version 2.0 -- (the "License"); you may not use this file except in compliance with -- the License. You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- local uuid = require "resty.jit-uuid" local const = require("app.const") local log = require("app.core.log") local ngx = ngx local _M = { name = "tracing", desc = "链路跟踪插件", optional = true, version = "v1.0" } function _M.do_in_init() -- automatic seeding with os.time(), LuaSocket, or ngx.time() uuid.seed() log.info("jit-uuid init") end function _M.do_in_access() local req = ngx.req local req_id = req.get_headers()[const.HEADER_TRACE_ID] if not req_id then local trace_id = uuid() log.debug("gen trace id: ", trace_id, " ", const.HEADER_TRACE_ID) req.set_header(const.HEADER_TRACE_ID, trace_id) end end return _M
nilq/small-lua-stack
null
data:extend( { { type = "technology", name = "iron-oxide", icon = "__MiningStation__/graphics/icons/adv-iron.png", prerequisites = { "steel-processing" }, effects = { { type = "unlock-recipe", recipe = "iron-oxide" }, { type = "unlock-recipe", recipe = "adv-iron" }, }, unit = { count = 150, ingredients = { {"science-pack-1", 3}, {"science-pack-2", 1}, }, time = 30 }, upgrade = false, order = "d-b-a1" }, { type = "technology", name = "iron-oxide-2", icon = "__MiningStation__/graphics/icons/adv-iron.png", prerequisites = { "iron-oxide" }, effects = { { type = "unlock-recipe", recipe = "iron-oxide-2" }, }, unit = { count = 450, ingredients = { {"science-pack-1", 5}, {"science-pack-2", 3}, {"science-pack-3", 1}, }, time = 30 }, upgrade = true, order = "d-b-a1" }, { type = "technology", name = "lead-oxide-2", icon = "__bobplates__/graphics/icons/lead-silver.png", prerequisites = { "lead-processing" }, effects = { { type = "unlock-recipe", recipe = "lead-oxide-2" }, }, unit = { count = 450, ingredients = { {"science-pack-1", 5}, {"science-pack-2", 3}, {"science-pack-3", 1}, }, time = 30 }, upgrade = true, order = "d-b-a1" }, { type = "technology", name = "nickel-processing-2", icon = "__MiningStation__/graphics/icons/adv-nickel.png", prerequisites = { "nickel-processing" }, effects = { { type = "unlock-recipe", recipe = "adv-nickel" }, }, unit = { count = 150, ingredients = { {"science-pack-1", 3}, {"science-pack-2", 1}, }, time = 30 }, upgrade = true, order = "d-b-a1" }, } )
nilq/small-lua-stack
null
spawnpoint 'a_m_y_hipster_01' { x = -1045.18, y = -2751.07, z = 21.31 } spawnpoint 'a_m_y_hipster_02' { x = -1045.18, y = -2751.07, z = 21.31 }
nilq/small-lua-stack
null
-- $Id: //depot/Projects/StarWars_Expansion/Run/Data/Scripts/GameObject/Demo_Land_Controller_R.lua#2 $ --///////////////////////////////////////////////////////////////////////////////////////////////// -- -- (C) Petroglyph Games, Inc. -- -- -- ***** ** * * -- * ** * * * -- * * * * * -- * * * * * * * * -- * * *** ****** * ** **** *** * * * ***** * *** -- * ** * * * ** * ** ** * * * * ** ** ** * -- *** ***** * * * * * * * * ** * * * * -- * * * * * * * * * * * * * * * -- * * * * * * * * * * ** * * * * -- * ** * * ** * ** * * ** * * * * -- ** **** ** * **** ***** * ** *** * * -- * * * -- * * * -- * * * -- * * * * -- **** * * -- --///////////////////////////////////////////////////////////////////////////////////////////////// -- C O N F I D E N T I A L S O U R C E C O D E -- D O N O T D I S T R I B U T E --///////////////////////////////////////////////////////////////////////////////////////////////// -- -- $File: //depot/Projects/StarWars_Expansion/Run/Data/Scripts/GameObject/Demo_Land_Controller_R.lua $ -- -- Original Author: Dan Etter -- -- $Author: Dan_Etter $ -- -- $Change: 42961 $ -- -- $DateTime: 2006/05/04 11:30:48 $ -- -- $Revision: #2 $ -- --///////////////////////////////////////////////////////////////////////////////////////////////// require("PGStateMachine") require("PGStoryMode") function Definitions() -- Object isn't valid at this point so don't do any operations that -- would require it. State_Init is the first chance you have to do -- operations on Object DebugMessage("%s -- In Definitions", tostring(Script)) Define_State("State_Init", State_Init); empire_player = Find_Player("Empire") rebel_player = Find_Player("Rebel") underworld_player = Find_Player("Underworld") move_command = true controller = Find_First_Object("DEMO_CONTROLLER_LAND") mptl = Find_Object_Type("MPTL") t4b = Find_Object_Type("T4B_TANK") t2b = Find_Object_Type("T2B_TANK") luke = Find_Object_Type("LUKE_SKYWALKER_JEDI") yoda = Find_Object_Type("YODA") speeder = Find_Object_Type("SNOWSPEEDER") r_infantry_squad = Find_Object_Type("REBEL_INFANTRY_SQUAD") r_infantry = Find_Object_Type("SQUAD_REBEL_TROOPER") destroyer_squad = Find_Object_Type("DESTROYER_DROID_COMPANY") destroyer = Find_Object_Type("DESTROYER_DROID") disruptor_squad = Find_Object_Type("UNDERWORLD_DISRUPTOR_MERC_SQUAD") disruptor = Find_Object_Type("UNDERWORLD_DISRUPTOR_MERC") merc_squad = Find_Object_Type("UNDERWORLD_MERC_SQUAD") merc = Find_Object_Type("UNDERWORLD_MERC") spmat = Find_Object_Type("SPMAT_WALKER") juggernaut = Find_Object_Type("HAV_JUGGERNAUT") dark_phase_1_squad = Find_Object_Type("DARKTROOPER_P1_COMPANY") dark_phase_1 = Find_Object_Type("DARK_TROOPER_PHASEI") dark_phase_2_squad = Find_Object_Type("DARKTROOPER_P2_COMPANY") dark_phase_2 = Find_Object_Type("DARK_TROOPER_PHASEII") dark_phase_3_squad = Find_Object_Type("DARKTROOPER_P3_COMPANY") dark_phase_3 = Find_Object_Type("DARK_TROOPER_PHASEIII") stormtrooper_squad = Find_Object_Type("IMPERIAL_STORMTROOPER_SQUAD") stormtrooper = Find_Object_Type("SQUAD_STORMTROOPER") lancet = Find_Object_Type("LANCET_AIR_ARTILLERY") end function State_Init(message) if (move_command == true) then empire_unit_list = Find_All_Objects_Of_Type(empire_player) rebel_unit_list = Find_All_Objects_Of_Type(rebel_player) underworld_unit_list = Find_All_Objects_Of_Type(underworld_player) empire_reveal = FogOfWar.Reveal_All(empire_player) rebel_reveal = FogOfWar.Reveal_All(rebel_player) uw_reveal = FogOfWar.Reveal_All(underworld_player) eg_list = Find_All_Objects_With_Hint("eg") rg_list = Find_All_Objects_With_Hint("rg") bossk = Find_First_Object("BOSSK") ig88 = Find_First_Object("IG-88") yoda = Find_First_Object("YODA") speeder_list = Find_All_Objects_Of_Type("SNOWSPEEDER") lancet_list = Find_All_Objects_Of_Type("LANCET_AIR_ARTILLERY") dest0_list = Find_All_Objects_With_Hint("dest0") dest0 = Find_Hint("STORY_TRIGGER_ZONE_00", "dest0") dest1_list = Find_All_Objects_With_Hint("dest1") dest1 = Find_Hint("STORY_TRIGGER_ZONE_00", "dest1") Create_Thread("Move_IG88", ig88) Create_Thread("Move_Bossk", bossk) Create_Thread("Move_Destroyer_group", eg_list) Create_Thread("Move_Destroyer_group1", rg_list) Create_Thread("Guard_Self", empire_unit_list) Create_Thread("Guard_Self", rebel_unit_list) Create_Thread("Yoda_Attack", yoda) --MessageBox("Fleets Defined") move_command = false end end function Yoda_Attack(unit) while true do if TestValid(unit) then closest_enemy = Find_Nearest(unit, underworld_player, true) if TestValid(closest_enemy) then unit.Activate_Ability("BERSERKER", closest_enemy) end end Sleep(1) end end function Guard_Self(group) for k, unit in pairs(group) do if TestValid(unit) then if unit.Is_Category("Infantry") or unit.Is_Category("Vehicle") then if not (unit.Get_Type() == stormtrooper) and not (unit.Get_Type() == r_infantry) then unit.Guard_Target(unit.Get_Position()) end end end end end function Move_Air_Units(group) for k, unit in pairs(group) do if TestValid(unit) then unit.Attack_Move(dest0.Get_Position()) end end end function Move_Air_Units1(group) for k, unit in pairs(group) do if TestValid(unit) then unit.Attack_Move(dest1.Get_Position()) end end end function Move_IG88(unit) rand_loc = GameRandom(1,3) if TestValid(unit) then unit.Attack_Move(dest0_list[rand_loc].Get_Position()) end end function Move_Bossk(unit) rand_loc = GameRandom(1,3) if TestValid(unit) then unit.Attack_Move(dest1_list[rand_loc].Get_Position()) end end function Move_Destroyer_group(group) rand_loc = GameRandom(1,3) for k, unit in pairs(group) do if TestValid(unit) then unit.Attack_Move(dest0_list[rand_loc].Get_Position()) end end -- sleeptimer = GameRandom(8, 11) -- Sleep(sleeptimer) -- Deploy_Destroyer_group(group, dest0_list[rand_loc]) end function Move_Destroyer_group1(group) rand_loc = GameRandom(1,3) for k, unit in pairs(group) do if TestValid(unit) then unit.Attack_Move(dest1_list[rand_loc].Get_Position()) end end -- sleeptimer = GameRandom(12, 14) -- Sleep(sleeptimer) -- Deploy_Destroyer_group(group, dest0_list[rand_loc]) end --function Deploy_Destroyer_group(group, loc) -- for k, unit in pairs(group) do -- if TestValid(unit) then -- unit.Activate_Ability("DEPLOY", true) -- end -- end -- --end
nilq/small-lua-stack
null
--[[ module:LimitSupport author:DylanYang time:2021-02-11 17:38:27 ]]local super = require("patterns.behavioral.chainOfResponsibility.Support") local _M = Class("LimitSupport", super) _M.limit = nil function _M:ctor(name, limit) self.super:ctor(name) self.limit = limit end function _M.protected:Resolve(trouble) return trouble.number < self.limit end return _M
nilq/small-lua-stack
null
local json = GLOBAL.json local pcall = GLOBAL.pcall local RADIUS = GetModConfigData("RADIUS") local CHESTERON = GetModConfigData("CHESTERON") function GetOverflowContainers(player) --[[if GLOBAL.TheNet:GetIsClient() then --apparently this check is not needed because clients have access to TheSim and their own Transform component. return {} end]] local x,y,z = player.Transform:GetWorldPosition() local chests = GLOBAL.TheSim:FindEntities(x,y,z, RADIUS, nil, {"quantum", "burnt"}, {"chest", "cellar", "fridge", CHESTERON and "chester" or "", CHESTERON and "hutch" or ""}) return #chests > 0 and chests or nil end function getNumItems(list) --the value of the table must be a number local amount = 0 if list == nil then return amount end for k,v in pairs(list) do amount = amount + v end return amount end -------------------------------------------------Begin for host local function HasOverride(component) local OldHas = component.Has component.Has = function(self, item, amount, runoriginal) -- Search in inventory, active item, & backpack HasItem, ItemCount = OldHas(self, item, amount) -- Search in nearby containers local num_left_to_find = amount - ItemCount local overflows = GetOverflowContainers(self.inst) if overflows ~= nil then for k,chest in pairs(overflows) do local chestHas, chestAmount = chest.components.container:Has(item, num_left_to_find) ItemCount = ItemCount + chestAmount end HasItem = ItemCount >= amount end return HasItem, ItemCount end end AddComponentPostInit("inventory", HasOverride) local function GetItemByNameOverride(component) local OldGetItemByName = component.GetItemByName component.GetItemByName = function(self, item, amount) -- Search in inventory, active item, & backpack local items = OldGetItemByName(self, item, amount) -- Search in nearby containers local itemsCount = getNumItems(items) local amount_left = amount - itemsCount if amount_left > 0 then local chests = GetOverflowContainers(self.inst) if chests ~= nil then for i,chest in pairs(chests) do local chestItems = chest.components.container:GetItemByName(item, amount_left) if getNumItems(chestItems) > 0 then for k,v in pairs(chestItems) do items[k] = v end amount_left = amount_left - getNumItems(chestItems) if amount_left <= 0 then break end end end end end return items end end AddComponentPostInit("inventory", GetItemByNameOverride) local function RemoveItemRemote(component) local OldRemoveItem = component.RemoveItem component.RemoveItem = function(self, item, wholestack) -- Remove from inventory, active item, or backpack local oldItem = OldRemoveItem(self, item, wholestack) --since this function was meant to always work, we pickup here if OldItem returns nil -- Remove from nearby containers if oldItem == nil then local chests = GetOverflowContainers(self.inst) for k,chest in pairs(chests) do local remoteOldItem = chest.components.container:RemoveItem(item, wholestack) if remoteOldItem ~= nil then return remoteOldItem end end else return oldItem end end end AddComponentPostInit("inventory", RemoveItemRemote) -------------------------------------------------End for host -------------------------------------------------Begin for client local function HasClient(prefab) local OldHas = prefab.Has prefab.Has = function(inst, item, amount, runoriginal) -- Search in inventory, active item, & backpack HasItem, ItemCount = OldHas(inst, item, amount) -- Search in nearby containers, available on client via variable on player, '_itemTable' local num_left_to_find = amount - ItemCount for name,count in pairs(inst._parent.player_classified._itemTable) do if name == item then ItemCount = ItemCount + count break end end HasItem = ItemCount >= amount return HasItem, ItemCount end end AddPrefabPostInit("inventory_classified", HasClient) local function RemoveIngredientsClient(prefab) local OldRemoveIngredients = prefab.RemoveIngredients prefab.RemoveIngredients = function(inst, recipe, ingredientmod) if inst:IsBusy() then return false end local chests = GetOverflowContainers(inst._parent) or {} for k,chest in pairs(chests) do local chestClassified = chest.replica.container.classified if chestClassified ~= nil and chestClassified:IsBusy() then return false end end local allItems = {} for k,v in ipairs(recipe.ingredients) do local _, total = inst:Has(v.type, v.amount) allItems[v.type] = total end -- Remove recipe ingredients from inventory, active item, or backpack OldRemoveIngredients(inst, recipe, ingredientmod) -- Remove recipe ingredients from nearby containers local newAllItems = {} for k,v in ipairs(recipe.ingredients) do local _, total = inst:Has(v.type, v.amount) newAllItems[v.type] = total end for k,v in ipairs(recipe.ingredients) do local amountRemoved = allItems[v.type] - newAllItems[v.type] local amountLeft = v.amount - amountRemoved if amountLeft > 0 then for k,chest in pairs(chests) do local chestHas, chestAmount = chest.replica.container:Has(v.type, amountLeft) if chest.replica.container.classified ~= nil then if chestHas then chest.replica.container.classified:ConsumeByName(v.type, amountLeft) else chest.replica.container.classified:ConsumeByName(v.type, chestAmount) amountLeft = amountLeft - chestAmount end end end end end return true end end AddPrefabPostInit("inventory_classified", RemoveIngredientsClient) -- Get all prefabs stored in 'chests' and the amount for each local function findAllFromChest(chests) if not chests or #chests == 0 then return {} end local items = {} for k, v in pairs(chests) do if v.components.container then local prefabs = {} for _, i in pairs(v.components.container.slots) do prefabs[i.prefab] = true end for t, _ in pairs(prefabs) do local found, amount = v.components.container:Has(t, 1) items[t] = (items[t] or 0) + amount end end end return items end -- Publish available items in nearby containers to net variable on player, '_items' local function allItemUpdate(inst) local chests = GetOverflowContainers(inst._parent) local items = findAllFromChest(chests) local r, result = pcall(json.encode, items) if not r then print("Could not encode all items: "..tostring(items)) end if result then inst._items:set(result) end end -- When '_items' changes, store available items in '_itemTable' local function itemsDirty(inst) --print("itemsDirty: "..inst._items:value()) local r, result = pcall(json.decode, inst._items:value()) if not r then print("Could not decode JSON: "..inst._items:value()) end if result then inst._itemTable = result end if GLOBAL.TheNet:GetIsClient() then inst._parent:PushEvent("refreshcrafting") --stacksizechange end end AddPrefabPostInit("player_classified", function(inst) inst._itemTable = {} inst._items = GLOBAL.net_string(inst.GUID, "_items", "itemsDirty") inst._items:set("") inst:ListenForEvent("itemsDirty", itemsDirty) inst.allItemUpdate = allItemUpdate if GLOBAL.TheWorld.ismastersim then inst.smashtask = inst:DoPeriodicTask(15 * GLOBAL.FRAMES, allItemUpdate) end end) -------------------------------------------------End for client -- These functions override the FindItems functionality defined in Gem Core API making Gem Core compatible with this mod. -- Host local function FindItemsOverride(component) local OldFindItems = component.FindItems component.FindItems = function(self, fn) -- Search in inventory, active item, & backpack local items = OldFindItems(self, fn) -- Search in nearby containers local overflows = GetOverflowContainers(self.inst) or {} for k, overflow in pairs(overflows) do for _, item in pairs(overflow.components.container:FindItems(fn)) do table.insert(items, item) end end return items end end AddComponentPostInit("inventory", FindItemsOverride) --'FindItems' exists in the main game so we do not need to check if GemCore is enabled -- Client local function FindItemsClient(prefab) local OldFindItems = prefab.FindItems prefab.FindItems = function(inst, fn) -- Search in inventory, active item, & backpack local items = OldFindItems(inst, fn) -- Search in nearby containers local overflows = GetOverflowContainers(inst._parent) or {} for k, overflow in pairs(overflows) do for _, item in pairs(overflow.replica.container:FindItems(fn)) do table.insert(items, item) end end return items end end if GLOBAL.KnownModIndex:IsModEnabled("workshop-1378549454") then --This is the name of the Gem Core API Mod AddPrefabPostInit("inventory_classified", FindItemsClient) end ------------------------------------------End of Gem Core Compatibility Section AddPrefabPostInitAny(function(inst) if inst and (inst:HasTag("chest") or inst:HasTag("cellar") or inst:HasTag("fridge") or inst:HasTag(CHESTERON and "chester" or "")) then inst:AddComponent("remoteinventory") inst.components.remoteinventory:SetDist(RADIUS, RADIUS) end end)
nilq/small-lua-stack
null
output_dir = '%{cfg.buildcfg}_%{cfg.architecture}_%{cfg.system}' workspace 'Roman' architecture 'x64' configurations { 'Debug', 'Release' } flags { 'MultiProcessorCompile' } startproject 'Roman' language 'C++' cppdialect 'C++latest' warnings 'Extra' conformancemode 'On' staticruntime 'On' buildoptions { '/Zc:rvalueCast' } files { '**.cc', '**.hh' } objdir ( '.bin_int/' .. output_dir .. '/%{prj.name}' ) targetdir ( '.bin/' .. output_dir .. '/%{prj.name}' ) debugdir ( '.bin/' .. output_dir .. '/%{prj.name}' ) filter 'files:**.cc' compileas 'Module' filter 'files:**.hh' compileas 'HeaderUnit' filter 'configurations:Debug' runtime 'Debug' symbols 'On' defines 'DEBUG' filter 'configurations:Release' runtime 'Release' optimize 'Speed' buildoptions '/Ob3' flags { 'LinkTimeOptimization' } project 'Roman' location 'Roman' entrypoint 'mainCRTStartup' kind 'ConsoleApp'
nilq/small-lua-stack
null
local TestCase = {} function TestCase.run(...) print('Core/Helper/GUIDHelper test:') local gen_count = 100 print('Generate 100 GUIDs...') for i = 1,gen_count do print(tostring(i) .. ': ' .. llbc.GUID.generate()) end print('GUID test success!') end return TestCase
nilq/small-lua-stack
null
LinkLuaModifier("modifier_item_bottle_arena_heal", "items/item_bottle.lua", LUA_MODIFIER_MOTION_NONE) item_bottle_arena = class({}) function item_bottle_arena:GetAbilityTextureName() return self:GetNetworkableEntityInfo("ability_texture") or "item_arena/bottle_3" end if IsServer() then function item_bottle_arena:OnCreated() self:SetCurrentCharges(3) end function item_bottle_arena:SetCurrentCharges(charges) local texture = self.RuneStorage ~= nil and "item_arena/bottle_rune_" .. self.RuneStorage or "item_arena/bottle_" .. charges self:SetNetworkableEntityInfo("ability_texture", texture) return self.BaseClass.SetCurrentCharges(self, charges) end function item_bottle_arena:OnSpellStart() self:GetCaster():EmitSound("Bottle.Drink") if self.RuneStorage then CustomRunes:ActivateRune(self:GetCaster(), self.RuneStorage, self:GetSpecialValueFor("rune_multiplier")) self.RuneStorage = nil self:SetCurrentCharges(3) else local charges = self:GetCurrentCharges() if charges > 0 then self:GetCaster():AddNewModifier(self:GetCaster(), self, "modifier_item_bottle_arena_heal", {duration = self:GetSpecialValueFor("restore_time")}) self:SetCurrentCharges(charges - 1) end end end function item_bottle_arena:SetStorageRune(type) self:GetCaster():EmitSound("Bottle.Cork") if self:GetCaster().GetPlayerID then CustomGameEventManager:Send_ServerToTeam(self:GetCaster():GetTeam(), "create_custom_toast", { type = "generic", text = "#custom_toast_BottledRune", player = self:GetCaster():GetPlayerID(), runeType = type }) end self.RuneStorage = type self:SetCurrentCharges(3) end end modifier_item_bottle_arena_heal = class({ GetTexture = function() return "item_arena/bottle_3" end, IsPurgable = function() return false end, GetEffectName = function() return "particles/items_fx/bottle.vpcf" end, GetEffectAttachType = function() return PATTACH_ABSORIGIN_FOLLOW end, }) function modifier_item_bottle_arena_heal:DeclareFunctions() return { MODIFIER_PROPERTY_HEALTH_REGEN_CONSTANT, MODIFIER_PROPERTY_MANA_REGEN_CONSTANT } end function modifier_item_bottle_arena_heal:GetModifierConstantHealthRegen() return self:GetAbility():GetSpecialValueFor("health_restore") / self:GetDuration() end function modifier_item_bottle_arena_heal:GetModifierConstantManaRegen() return self:GetAbility():GetSpecialValueFor("mana_restore") / self:GetDuration() end
nilq/small-lua-stack
null
do ---Represents the server; only one instance in the global variable `server`. ---@class Server ---@field class string 🔒 "Server" ---@field TPS integer 🔒 How many ticks are in 1 second according to in-game timers (60). ---@field port integer 🔒 ---@field name string Name shown on the server list, max length of 31. ---@field adminPassword string The admin password used in the /admin command. ---@field password string Empty string for no password, otherwise people will need to type this to join. ---@field maxPlayers integer ---@field maxBytesPerSecond integer ---@field worldTraffic integer How many traffic cars there should be in world mode. ---@field worldStartCash integer ---@field worldMinCash integer ---@field worldShowJoinExit boolean ---@field worldRespawnTeam boolean ---@field worldCrimeCivCiv integer ---@field worldCrimeCivTeam integer ---@field worldCrimeTeamCiv integer ---@field worldCrimeTeamTeam integer ---@field worldCrimeTeamTeamInBase integer ---@field worldCrimeNoSpawn integer ---@field roundRoundTime integer How long rounds are in round mode, in minutes. ---@field roundStartCash integer ---@field roundIsWeekly boolean ---@field roundHasBonusRatio boolean ---@field roundTeamDamage integer ---@field type integer Gamemode number. ---@field loadedLevel string 🔒 Name of the currently loaded map. ---@field levelToLoad string ---@field isLevelLoaded boolean ---@field gravity number ---@field defaultGravity number 🔒 ---@field state integer Game state enum. Always networked. ---@field time integer Time remaining in ticks (see TPS). Always networked. ---@field sunTime integer Time of day in ticks, where noon is 2592000 (12*60*60*TPS). Always networked. ---@field version string 🔒 Game build, ex. "36a" ---@field versionMajor integer 🔒 Major version number, ex. 36 ---@field versionMinor integer 🔒 Minor version number, ex. 1 local Server ---Reset the game with reason RESET_REASON_LUACALL. function Server:reset() end ---Set the title displayed on the terminal the server is running on. ---@param title string The title to set. function Server:setConsoleTitle(title) end ---The global Server instance. server = Server end do ---Represents a 3D point in the level. ---Available in worker threads. ---@class Vector ---@field class string 🔒 "Vector" ---@field x number ---@field y number ---@field z number local Vector ---Add other to self. ---@param other Vector The vector to add. function Vector:add(other) end ---Multiply self by scalar. ---@param scalar number The scalar to multiply each coordinate by. function Vector:mult(scalar) end ---Replace values with those in another vector. ---@param other Vector The vector to inherit values from. function Vector:set(other) end ---Create a copy of self. ---@return Vector clone The created copy. function Vector:clone() end ---Calculate the distance between self and other. ---@param other Vector The vector to calculate distance to. ---@return number distance The distance between self and other. function Vector:dist(other) end ---Calculate the distance between self and other, squared. ---Much faster as it does not square root the value. ---@param other Vector The vector to calculate distance to. ---@return number distanceSquared The distance, squared. function Vector:distSquare(other) end ---Calculate the length of the vector. ---@return number length The length of the vector. function Vector:length() end ---Calculate the length of the vector, squared. ---Much faster as it does not square root the value. ---@return number length The length of the vector, squared. function Vector:lengthSquare() end ---Calculate the dot product of self and other. ---@param other Vector The vector to calculate the dot product with. ---@return number dotProduct The dot product of self and other. function Vector:dot(other) end ---Get the coordinates of the level block the vector is in. ---@return integer blockX ---@return integer blockY ---@return integer blockZ function Vector:getBlockPos() end ---Normalize the vector's values so that it has a length of 1. function Vector:normalize() end end do ---Represents the rotation of an object as a 3x3 matrix. ---Available in worker threads. ---@class RotMatrix ---@field class string 🔒 "RotMatrix" ---@field x1 number ---@field y1 number ---@field z1 number ---@field x2 number ---@field y2 number ---@field z2 number ---@field x3 number ---@field y3 number ---@field z3 number local RotMatrix ---Replace values with those in another matrix. ---@param other RotMatrix The matrix to inherit values from. function RotMatrix:set(other) end ---Create a copy of self. ---@return RotMatrix clone The created copy. function RotMatrix:clone() end ---Get a normal vector pointing in the rotation's +X direction. ---@return Vector forward The normal vector. function RotMatrix:getForward() end ---Get a normal vector pointing in the rotation's +Y direction. ---@return Vector up The normal vector. function RotMatrix:getUp() end ---Get a normal vector pointing in the rotation's +Z direction. ---@return Vector right The normal vector. function RotMatrix:getRight() end end do ---Represents a player's transmitting voice chat. ---@class Voice ---@field class string 🔒 "Voice" ---@field volumeLevel integer The volume of the voice. 0 = whisper, 1 = normal, 2 = yell. ---@field currentFrame integer The current frame being sent, 0-63. ---@field isSilenced boolean Whether the voice is not transmitting. local Voice ---Get a specific encoded Opus frame. ---@param index integer The index between 0 and 63. ---@return string frame The encoded Opus frame. function Voice:getFrame(index) end ---Set a specific encoded Opus frame. ---@param index integer The index between 0 and 63. ---@param frame string The encoded Opus frame. ---@param volumeLevel integer The volume of the frame. 0 = whisper, 1 = normal, 2 = yell. function Voice:setFrame(index, frame, volumeLevel) end end do ---Represents a connected player, who may or may not be spawned in. ---💾 = To network changed value to clients, the `update` method needs to be called. ---💲 = To network changed value to clients, the `updateFinance` method needs to be called. ---@class Player ---@field class string 🔒 "Player" ---@field data table A Lua table which persists throughout the lifespan of this object. ---@field subRosaID integer See Account.subRosaID ---@field phoneNumber integer 💲 See Account.phoneNumber ---@field money integer 💲 ---@field teamMoney integer The value of their team's balance in world mode. ---@field budget integer The value of their team's budget in world mode. ---@field corporateRating integer ---@field criminalRating integer ---@field team integer 💾 ---@field teamSwitchTimer integer Ticks remaining until they can switch teams again. ---@field stocks integer 💲 The amount of shares they own in their company. ---@field spawnTimer integer How long this person has to wait to spawn in, in seconds. ---@field gearX number Left to right stick shift position, 0 to 2. ---@field leftRightInput number Left to right movement input, -1 to 1. ---@field gearY number Forward to back stick shift position, -1 to 1. ---@field forwardBackInput number Backward to forward movement input, -1 to 1. ---@field viewYawDelta number Radians. ---@field viewPitch number Radians. ---@field freeLookYaw number Radians. ---@field freeLookPitch number Radians. ---@field viewYaw number Radians. ---@field inputFlags integer Bitflags of current buttons being pressed. ---@field lastInputFlags integer Input flags from the last tick. ---@field zoomLevel integer 0 = run, 1 = walk, 2 = aim. ---@field inputType integer What the input fields are used for. 0 = none, 1 = human, 2 = car, 3 = helicopter. Defaults to 0. ---@field menuTab integer What tab in the menu they are currently in. ---@field numActions integer ---@field lastNumActions integer ---@field gender integer 💾 0 = female, 1 = male. ---@field skinColor integer 💾 Starts at 0. ---@field hairColor integer 💾 ---@field hair integer 💾 ---@field eyeColor integer 💾 ---@field model integer 💾 0 = casual, 1 = suit. ---@field head integer 💾 ---@field suitColor integer 💾 ---@field tieColor integer 💾 0 = no tie, 1 = the first color. ---@field necklace integer 💾 ---@field index integer 🔒 The index of the array in memory this is (0-255). ---@field isActive boolean 💾 Whether or not this exists, only change if you know what you are doing. ---@field name string 💾 Nickname of this player. ---@field isAdmin boolean ---@field isReady boolean ---@field isBot boolean 💾 ---@field isZombie boolean 💾 Whether the bot player should always run towards it's target. ---@field human? Human 💾 The human they currently control. ---@field connection? Connection 🔒 Their network connection. ---@field account? Account Their account. ---@field voice Voice Their voice. ---@field botDestination? Vector The location this bot will walk towards. local Player ---Get a specific action. ---@param index integer The index between 0 and 63. ---@return Action action The desired action. function Player:getAction(index) end ---Get a specific menu button. ---@param index integer The index between 0 and 31. ---@return MenuButton menuButton The desired menu button. function Player:getMenuButton(index) end ---Fire a network event containing basic info. ---@return Event event The created event. function Player:update() end ---Fire a network event containing financial info. ---@return Event event The created event. function Player:updateFinance() end ---Remove self safely and fire a network event. function Player:remove() end ---Create a red chat message only this player receives. ---@param message string The message to send. function Player:sendMessage(message) end end do ---Represents a human, including dead bodies. ---@class Human ---@field class string 🔒 "Human" ---@field data table A Lua table which persists throughout the lifespan of this object. ---@field stamina integer ---@field maxStamina integer ---@field vehicleSeat integer Seat index of the vehicle they are in. ---@field despawnTime integer Ticks remaining until removal if dead. ---@field movementState integer 0 = normal, 1 = in midair, 2 = sliding, rest unknown. ---@field zoomLevel integer 0 = run, 1 = walk, 2 = aim. ---@field damage integer Level of screen blackness, 0-60. ---@field pos Vector Position. ---@field viewYaw number Radians. ---@field viewPitch number Radians. ---@field viewYaw2 number Radians. ---@field strafeInput number Left to right movement input, -1 to 1. ---@field walkInput number Backward to forward movement input, -1 to 1. ---@field viewPitch2 number Radians. ---@field inputFlags integer Bitflags of current buttons being pressed. ---@field lastInputFlags integer Input flags from the last tick. ---@field health integer Dynamic health, 0-100. ---@field bloodLevel integer How much blood they have, 0-100. <50 and they will collapse. ---@field chestHP integer Dynamic chest health, 0-100. ---@field headHP integer ---@field leftArmHP integer ---@field rightArmHP integer ---@field leftLegHP integer ---@field rightLegHP integer ---@field progressBar integer Progress bar displayed in the center of the screen, 0-255. 0 = disabled. ---@field inventoryAnimationFlags integer ---@field inventoryAnimationProgress integer ---@field inventoryAnimationDuration number ---@field inventoryAnimationHand integer ---@field inventoryAnimationSlot integer ---@field inventoryAnimationCounter integer ---@field inventoryAnimationCounterFinished integer ---@field gender integer See Player.gender. ---@field head integer See Player.head. ---@field skinColor integer See Player.skinColor. ---@field hairColor integer See Player.hairColor. ---@field hair integer See Player.hair. ---@field eyeColor integer See Player.eyeColor. ---@field model integer See Player.model. ---@field suitColor integer See Player.suitColor. ---@field tieColor integer See Player.tieColor. ---@field necklace integer See Player.necklace. ---@field lastUpdatedWantedGroup integer 0 = white, 1 = yellow, 2 = red. Change to a different value (ex. -1) to re-network appearance fields (model, gender, etc.) ---@field index integer 🔒 The index of the array in memory this is (0-255). ---@field isActive boolean Whether or not this exists, only change if you know what you are doing. ---@field isAlive boolean ---@field isImmortal boolean Whether they are immune to bullet and physics damage. ---@field isOnGround boolean 🔒 ---@field isStanding boolean 🔒 ---@field isBleeding boolean ---@field player? Player The player controlling this human. ---@field account? Account The disconnected account that owns this human. ---@field vehicle? Vehicle The vehicle they are inside. local Human ---Remove self safely and fire a network event. function Human:remove() end ---Teleport safely to a different position. ---@param position Vector The position to teleport to. function Human:teleport(position) end ---Speak a message. ---@param message string The message to say. ---@param volumeLevel integer The volume to speak at. 0 = whisper, 1 = normal, 2 = yell. function Human:speak(message, volumeLevel) end ---Arm with a gun and magazines. ---@param weaponType integer The ID of the item type. Must be a weapon. ---@param magazineCount integer The number of magazines to give. function Human:arm(weaponType, magazineCount) end ---Get a specific bone. ---@param index integer The index between 0 and 15. ---@return Bone bone The desired bone. function Human:getBone(index) end ---Get a specific rigid body. ---@param index integer The index between 0 and 15. ---@return RigidBody rigidBody The desired rigid body. function Human:getRigidBody(index) end ---Get a specific inventory slot. ---@param index integer The index between 0 and 6. ---@return InventorySlot inventorySlot The desired inventory slot. function Human:getInventorySlot(index) end ---Set the velocity of every rigid body. ---@param velocity Vector The velocity to set. function Human:setVelocity(velocity) end ---Add velocity to every rigid body. ---@param velocity Vector The velocity to add. function Human:addVelocity(velocity) end ---Mount an item to an inventory slot. ---@param childItem Item The item to mount. ---@param slot integer The slot to mount to. ---@return boolean success Whether the mount was successful. function Human:mountItem(childItem, slot) end ---Apply damage points to a specific bone. ---@param boneIndex integer The index of the bone to apply damage to. ---@param damage integer The amount of damage to apply. function Human:applyDamage(boneIndex, damage) end end do ---Represents a type of item that exists. ---@class ItemType ---@field class string 🔒 "ItemType" ---@field price integer How much money is taken when bought. Not networked. ---@field mass number In kilograms, kind of. ---@field fireRate integer How many ticks between two shots. ---@field magazineAmmo integer ---@field bulletType integer ---@field bulletVelocity number ---@field bulletSpread number ---@field numHands integer ---@field rightHandPos Vector ---@field leftHandPos Vector ---@field primaryGripStiffness number ---@field primaryGripRotation number In radians. ---@field secondaryGripStiffness number ---@field secondaryGripRotation number In radians. ---@field gunHoldingPos Vector The offset of where the item is held if it is a gun. ---@field boundsCenter Vector ---@field index integer 🔒 The index of the array in memory this is. ---@field name string Not networked. ---@field isGun boolean local ItemType ---Get whether this type can be mounted to another type. ---@param parent ItemType ---@return boolean canMount function ItemType:getCanMountTo(parent) end ---Set whether this type can be mounted to another type. ---@param parent ItemType ---@param canMount boolean function ItemType:setCanMountTo(parent, canMount) end end do ---Represents an item in the world or someone's inventory. ---💾 = To network changed value to clients, the `update` method needs to be called. ---@class Item ---@field class string 🔒 "Item" ---@field data table A Lua table which persists throughout the lifespan of this object. ---@field type ItemType 💾 ---@field despawnTime integer Ticks remaining until removal. ---@field parentSlot integer The slot this item occupies if it has a parent. ---@field parentHuman? Human The human this item is mounted to, if any. ---@field parentItem? Item The item this item is mounted to, if any. ---@field pos Vector Position. ---@field vel Vector Velocity. ---@field rot RotMatrix Rotation. ---@field bullets integer How many bullets are inside this item. ---@field cooldown integer ---@field cashSpread integer ---@field cashAmount integer ---@field cashPureValue integer ---@field computerCurrentLine integer ---@field computerTopLine integer Which line is at the top of the screen. ---@field computerCursor integer The location of the cursor, -1 for no cursor. ---@field index integer 🔒 The index of the array in memory this is (0-1023). ---@field isActive boolean Whether or not this exists, only change if you know what you are doing. ---@field hasPhysics boolean Whether this item is currently physically simulated. ---@field physicsSettled boolean Whether this item is settled by gravity. ---@field physicsSettledTimer integer How many ticks the item has been settling. Once it has reached 60, it will be settled. ---@field isStatic boolean Whether the item is immovable. ---@field rigidBody RigidBody The rigid body representing the physics of this item. ---@field vehicle? Vehicle The vehicle which this item is a key for. ---@field grenadePrimer? Player The player who primed this grenade. ---@field phoneTexture integer 💾 The phone's texture ID. 0 for white, 1 for black. ---@field phoneNumber integer The number used to call this phone. ---@field displayPhoneNumber integer 💾 The number currently displayed on the phone. ---@field enteredPhoneNumber integer The number that has been entered on the phone. Will reset upon reaching 4 digits. ---@field connectedPhone? Item The phone that this phone is connected to. local Item ---Remove self safely and fire a network event. function Item:remove() end ---Mount another item onto this item. ---Ex. a magazine to this gun. ---@param childItem Item The child item to mount to this item. ---@param slot integer The slot to mount the child item to. ---@return boolean success Whether the mount was successful. function Item:mountItem(childItem, slot) end ---Remove this item from any parent, back into the world. ---@return boolean success Whether the unmount was successful. function Item:unmount() end ---Speak a message. ---The item does not need to be a phone type. ---@param message string The message to say. ---@param volumeLevel integer The volume to speak at. 0 = whisper, 1 = normal, 2 = yell. function Item:speak(message, volumeLevel) end ---Explode like a grenade, whether or not it is one. ---Does not alter or remove the item. function Item:explode() end ---Set the text displayed on this item. ---Visible if it is a Memo or a Newspaper item. ---@param memo string The memo to set. Max 1023 characters. function Item:setMemo(memo) end ---Update the color and text of a line and network it. ---Only works if this item is a computer. ---@param lineIndex integer Which line to transmit. function Item:computerTransmitLine(lineIndex) end ---Increment the current line of a computer. ---Only works if this item is a computer. function Item:computerIncrementLine() end ---Set the text to display on a line. Does not immediately network. ---Only works if this item is a computer. ---@param lineIndex integer Which line to edit. ---@param text string The text to set the line to. Max 63 characters. function Item:computerSetLine(lineIndex, text) end ---Set the colors to display on a line. Does not immediately network. ---Only works if this item is a computer. ---@param lineIndex integer Which line to edit. ---@param colors string The colors to set the line to, where every character represents a color value from 0x00 to 0xFF. Max 63 characters. function Item:computerSetLineColors(lineIndex, colors) end ---Set the color of a character on screen. Does not immediately network. ---Only works if this item is a computer. ---Uses the 16 CGA colors for foreground and background separately. ---@param lineIndex integer Which line to edit. ---@param columnIndex integer Which column to edit. ---@param color integer The color to set, between 0x00 and 0xFF. function Item:computerSetColor(lineIndex, columnIndex, color) end ---Add a bank bill to the stack of cash. ---Only works if this item is a stack of cash. ---@param position integer The relative position on the stack to add the bill, in no particular range. ---@param value integer The denomination type of the bill (0-7). function Item:cashAddBill(position, value) end ---Remove a bank bill from the stack of cash. ---Only works if this item is a stack of cash. ---@param position integer The relative position on the stack to find the bill to remove, in no particular range. function Item:cashRemoveBill(position) end ---Get the total value of the stack of cash. ---Only works if this item is a stack of cash. ---@return integer value The total value in dollars. function Item:cashGetBillValue() end end do ---Represents a car, train, or helicopter. ---💾 = To network changed value to clients, the `updateType` method needs to be called. ---@class Vehicle ---@field class string 🔒 "Vehicle" ---@field data table A Lua table which persists throughout the lifespan of this object. ---@field type VehicleType 💾 ---@field isLocked boolean Whether or not this has a key and is locked. ---@field controllableState integer 0 = cannot be controlled, 1 = car, 2 = helicopter. ---@field health integer 0-100 ---@field color integer 💾 0 = black, 1 = red, 2 = blue, 3 = silver, 4 = white, 5 = gold. ---@field pos Vector Position. ---@field vel Vector Velocity. ---@field rot RotMatrix Rotation. ---@field gearX number Left to right stick shift position, 0 to 2. ---@field gearY number Forward to back stick shift position, -1 to 1. ---@field steerControl number Left to right wheel position, -0.75 to 0.75. ---@field gasControl number Brakes to full gas, -1 to 1. ---@field engineRPM integer The RPM of the engine to be networked, 0 to 8191. ---@field numSeats integer The number of accessible seats. ---@field index integer 🔒 The index of the array in memory this is (0-511). ---@field isActive boolean Whether or not this exists, only change if you know what you are doing. ---@field lastDriver? Player 🔒 The last person to drive the vehicle. ---@field rigidBody RigidBody 🔒 The rigid body representing the physics of this vehicle. ---@field trafficCar? TrafficCar The traffic car the vehicle belongs to. local Vehicle ---Fire a network event containing basic info. ---@return Event event The created event. function Vehicle:updateType() end ---Fire a network event to make a part appear to break. ---Also used to visually toggle train doors. ---@param kind integer The kind of part. 0 = window, 1 = tire, 2 = entire body, 6 = repair window. ---@param position Vector The global position of the destruction. ---@param normal Vector The normal of the destruction. ---@return Event event The created event. function Vehicle:updateDestruction(kind, partIndex, position, normal) end ---Remove self safely and fire a network event. function Vehicle:remove() end ---Get whether a specific window is broken. ---@param index integer The index between 0 and 7. ---@return boolean isWindowBroken function Vehicle:getIsWindowBroken(index) end ---Set whether a specific window is broken. ---@param index integer The index between 0 and 7. ---@param isWindowBroken boolean function Vehicle:setIsWindowBroken(index, isWindowBroken) end end do ---Represents a rigid body currently in use by the physics engine. ---@class RigidBody ---@field class string 🔒 "RigidBody" ---@field data table A Lua table which persists throughout the lifespan of this object. ---@field type integer 0 = bone, 1 = car body, 2 = wheel, 3 = item. ---@field mass number In kilograms, kind of. ---@field pos Vector Position. ---@field vel Vector Velocity. ---@field rot RotMatrix Rotation. ---@field rotVel RotMatrix Rotational velocity. ---@field index integer 🔒 The index of the array in memory this is (0-8191). ---@field isActive boolean Whether or not this exists, only change if you know what you are doing. ---@field isSettled boolean Whether this rigid body is settled by gravity. local RigidBody ---Create a bond between this body and another at specific local coordinates. ---@param otherBody RigidBody The second body in the bond. ---@param thisLocalPos Vector The local position relative to this body. ---@param otherLocalPos Vector The local position relative to the other body. ---@return Bond? bond The created bond, if successful. function RigidBody:bondTo(otherBody, thisLocalPos, otherLocalPos) end ---Link rotation between this body and another. ---Does not seem to be very strong. ---@param otherBody RigidBody The second body in the bond. ---@return Bond? bond The created bond, if successful. function RigidBody:bondRotTo(otherBody) end ---Bond a local coordinate of this body to a static point in space. ---@param localPos Vector The local position relative to this body. ---@param globalPos Vector The global position in the level. ---@return Bond? bond The created bond, if successful. function RigidBody:bondToLevel(localPos, globalPos) end ---Collide with the level for one tick. ---@param localPos Vector The local position relative to this body. ---@param normal Vector The normal of the collision. ---@param a number ---@param b number ---@param c number ---@param d number function RigidBody:collideLevel(localPos, normal, a, b, c, d) end end do ---Represents a street. ---@class Street ---@field class string 🔒 "Street" ---@field trafficCuboidA Vector The first corner of a cuboid, where points inside are considered to be on the street by traffic AI. ---@field trafficCuboidB Vector The second corner of a cuboid, where points inside are considered to be on the street by traffic AI. ---@field numTraffic integer How many AI vehicles are currently on the street. ---@field index integer 🔒 The index of the array in memory this is. ---@field name string 🔒 The name of the street, ex. "First Street" ---@field intersectionA StreetIntersection 🔒 The intersection that the street starts at. ---@field intersectionB StreetIntersection 🔒 The intersection that the street ends at. ---@field numLanes integer 🔒 How many lanes the street has. local Street ---Get a lane on the street. ---@param index integer The index between 0 and numLanes-1. ---@return StreetLane lane The desired lane. function Street:getLane(index) end end do ---Represents a special building. ---@class Building ---@field class string 🔒 "Building" ---@field type integer The type of building. 1 = base, 3 = car shop, 4 = laboratory, 5 = cosmetics shop, 6 = bank, 8 = gun shop, 9 = burger shop. ---@field pos Vector The origin point of the building. May not be inside. ---@field spawnRot RotMatrix The rotation which this building spawns things (players in a base, cars in a car shop, etc.) ---@field interiorCuboidA Vector The first corner of a cuboid, where the interior of the building is contained inside. ---@field interiorCuboidB Vector The second corner of a cuboid, where the interior of the building is contained inside. ---@field numShopCars integer How many cars are for sale at this car shop. ---@field shopCarSales integer How many cars have been sold at this car shop. ---@field index integer 🔒 The index of the array in memory this is. local Building ---Get a car slot at this car shop. ---@param index integer The index between 0 and 15. ---@return ShopCar shopCar The desired shop car. function Building:getShopCar(index) end end do ---Represents an active client network connection. ---Connections can be moved around in memory every tick, so don't hold onto references. ---@class Connection ---@field class string 🔒 "Connection" ---@field port integer ---@field timeoutTime integer How many ticks the connection has not responded, will be deleted after 30 seconds. ---@field address string 🔒 IPv4 address ("x.x.x.x") ---@field adminVisible boolean Whether this connection is sent admin only events (admin messages). ---@field player? Player The connected player. ---@field spectatingHuman? Human The human this connection is currently spectating, if any. local Connection ---Get a specific voice earshot. ---@param index integer The index between 0 and 7. ---@return EarShot earShot The desired earshot. function Connection:getEarShot(index) end ---Check whether or not the connection has received an event, at which point the event won't be transmitted to them anymore. ---@param event Event The event to compare. ---@return boolean function Connection:hasReceivedEvent(event) end end do ---Represents a worker thread. ---@class Worker Worker = {} ---Create a new Worker using a given lua file path. ---@param fileName string The path to a lua file to execute on the worker thread. ---@return Worker worker The created Worker. function Worker.new(fileName) end ---Indicate that the worker should stop what it's doing. ---This is automatically done whenever a Worker is garbage collected. ---@see sleep function Worker:stop() end ---Send a message to the worker thread. ---Adds to a queue such that when receiveMessage is called in the worker thread, this message can be returned. ---@param message string The message to send to the worker thread. ---@see receiveMessage function Worker:sendMessage(message) end ---Pop a message from the queue of messages received from the worker thread. ---@return string? message The oldest remaining message received from the worker thread, or nil if none are left. ---@see sendMessage function Worker:receiveMessage() end end do ---Represents a child process. ---@class ChildProcess ChildProcess = {} ---Create a new ChildProcess. ---@param fileName string The path to a lua file to execute in the child process. ---@return ChildProcess childProcess The created ChildProcess. function ChildProcess.new(fileName) end ---Check if the child process is currently running. ---@return boolean isRunning Whether the child process is running. function ChildProcess:isRunning() end ---Terminate the child process. ---Sends SIGTERM. function ChildProcess:terminate() end ---Get the exit code of the process. ---@return integer? exitCode The exit code of the child process, or nil if it has not exited. function ChildProcess:getExitCode() end ---Send a message to the child process. ---Adds to a queue such that when `receiveMessage() -> string?` is called in the child process, this message can be returned. ---@param message string The message to send to the child process. function ChildProcess:sendMessage(message) end ---Pop a message from the queue of messages received from the child process. ---@return string? message The oldest remaining message received from the child process, or nil if none are left. function ChildProcess:receiveMessage() end ---Set CPU limits of the child process. ---@param softLimit integer The soft limit, in seconds. ---@param hardLimit integer The hard limit, in seconds. May not have permission to increase once initially set. function ChildProcess:setCPULimit(softLimit, hardLimit) end ---Set memory limits of the child process. ---@param softLimit integer The soft limit, in bytes. ---@param hardLimit integer The hard limit, in bytes. May not have permission to increase once initially set. function ChildProcess:setMemoryLimit(softLimit, hardLimit) end ---Set maximum file size writing limits of the child process. ---@param softLimit integer The soft limit, in bytes. ---@param hardLimit integer The hard limit, in bytes. May not have permission to increase once initially set. function ChildProcess:setFileSizeLimit(softLimit, hardLimit) end ---Get the priority (nice value) of the child process. ---@return integer priority The priority of the child process. function ChildProcess:getPriority() end ---Set the priority (nice value) of the child process. ---@param priority integer The new priority of the child process. function ChildProcess:setPriority(priority) end end do ---Represents a raster image. ---Available in worker threads. ---@class Image ---@field width integer 🔒 The width in pixels. ---@field height integer 🔒 The height in pixels. ---@field numChannels integer 🔒 The number of channels, typically 3 or 4. Image = {} ---Create a new Image. ---@return Image image The created Image. function Image.new() end ---Free the image data. ---This is automatically done whenever an Image is garbage collected, ---but it's still better to call it explicitly when you're done reading. function Image:free() end ---Load an image from a file. ---Many file formats are supported. ---@param filePath string The path to the image file to load. function Image:loadFromFile(filePath) end ---Load a blank image with desired dimensions. ---@param width integer How wide the image should be. ---@param height integer How tall the image should be. ---@param numChannels integer How many channels the image should have (1-4). function Image:loadBlank(width, height, numChannels) end ---Get the RGB pixel color at a given coordinate. ---Coordinate (0, 0) is the top left of the image. ---@param x integer The X pixel coordinate. ---@param y integer The Y pixel coordinate. ---@return integer red The value of the red channel (0-255). ---@return integer green The value of the green channel (0-255). ---@return integer blue The value of the blue channel (0-255). function Image:getRGB(x, y) end ---Get the RGBA pixel color at a given coordinate. ---Coordinate (0, 0) is the top left of the image. ---@param x integer The X pixel coordinate. ---@param y integer The Y pixel coordinate. ---@return integer red The value of the red channel (0-255). ---@return integer green The value of the green channel (0-255). ---@return integer blue The value of the blue channel (0-255). ---@return integer alpha The value of the alpha channel (0-255). function Image:getRGBA(x, y) end ---Set the color of a pixel. ---@param x integer The X pixel coordinate. ---@param y integer The Y pixel coordinate. ---@param red integer The red channel value. ---@param green integer The green channel value. ---@param blue integer The blue channel value. function Image:setPixel(x, y, red, green, blue) end ---@param x integer The X pixel coordinate. ---@param y integer The Y pixel coordinate. ---@param red integer The red channel value. ---@param green integer The green channel value. ---@param blue integer The blue channel value. ---@param alpha integer The alpha channel value. function Image:setPixel(x, y, red, green, blue, alpha) end ---Get the PNG representation of an image. ---@return string png The buffer of a PNG file representing the image. function Image:getPNG() end end do ---A connection to an SQLite 3 database. ---Available in worker threads. ---@class SQLite SQLite = {} ---Create a new SQLite using a given database file path. ---@param fileName string The path to a database file to connect to. If ':memory:', this will be a temporary in-memory database. If an empty string, this will be a temporary on-disk database. ---@return SQLite db The created SQLite. function SQLite.new(fileName) end ---Close the database. ---This is automatically done whenever an SQLite is garbage collected, ---but it's still better to call it explicitly when you're done using it. function SQLite:close() end ---Execute an SQL query. ---@param sql string The SQL string to execute. ---@vararg nil|string|number|boolean The optional arguments if this is a parameterized query. ---@return integer|table[] result The number of changes or the returned rows, if the query generates any, where each row is a table of columns. Values can be `nil`, `string`, or `number`. ---@return string? err The error from preparing/running the query, if there was one. function SQLite:query(sql, ...) end end do ---An object which can listen for file system events. ---Available in worker threads. ---@class FileWatcher FileWatcher = {} ---Create a new FileWatcher. ---@return FileWatcher fileWatcher The created FileWatcher. function FileWatcher.new() end ---Add a new directory/file to watch. ---@param path string The path to watch. ---@param mask integer The flags for the watch. See FILE_WATCH_* constants. function FileWatcher:addWatch(path, mask) end ---Remove a watch if it exists. ---@param path string The path to remove. ---@return boolean success Whether the path was an existing watch. function FileWatcher:removeWatch(path) end ---@class FileWatchEvent ---@field descriptor string The path of the watch the event was for. ---@field mask integer The flags for the event. See FILE_WATCH_* constants. ---@field name string The name of the directory/file where the event took place. ---Read the next event. ---@return FileWatchEvent? event The next event, or nil if there was no event. function FileWatcher:receiveEvent() end end do ---An Opus audio encoder. ---Available in worker threads. ---@class OpusEncoder ---@field bitRate integer The bit rate used when encoding audio, in bits/second. OpusEncoder = {} ---Create a new OpusEncoder. ---@return OpusEncoder encoder The created OpusEncoder. function OpusEncoder.new() end ---Close the opened file, if there is any. ---This is automatically done whenever an OpusEncoder is garbage collected, ---but it's still better to call it explicitly when you're done encoding. function OpusEncoder:close() end ---Open a file for encoding. Closes any previously opened file. ---Throws if the file cannot be opened. ---@param fileName string The path to a 48000Hz signed 16-bit raw PCM file to use for encoding. function OpusEncoder:open(fileName) end ---Rewind the opened file to the beginning. function OpusEncoder:rewind() end ---Encode a single 20ms Opus frame. ---Throws if the file is not opened, or there is a problem when reading or encoding. ---@return string? frame The next encoded frame, or nil if there is nothing left to read. function OpusEncoder:encodeFrame() end ---Encode a single 20ms Opus frame. ---Throws if input is the wrong length, or there is a problem when encoding. ---@param input string The raw PCM bytes, which contains either 960 32-bit floats or 960 16-bit signed integers. ---@return string frame The encoded frame. function OpusEncoder:encodeFrame(input) end end do ---A graph of nodes representing points in space. ---Available in worker threads. ---@class PointGraph PointGraph = {} ---Create a new PointGraph. ---@param squareRootCacheSize integer The number of integers to cache the square root of for use in findShortestPath. If the square of the Euclidean distance between two node positions is >= this number, the square root will have to be calculated on the fly, leading to much longer processing time. ---@return PointGraph pointGraph The created PointGraph. function PointGraph.new(squareRootCacheSize) end ---Get the number of nodes in the graph. ---@return integer size The number of nodes in the graph. function PointGraph:getSize() end ---Add a node. ---@param x integer The x coordinate of the node in space used when finding paths. ---@param y integer The y coordinate of the node in space used when finding paths. ---@param z integer The z coordinate of the node in space used when finding paths. function PointGraph:addNode(x, y, z) end ---Get the coordinates of a node by its index. ---@param index integer The index of the node. ---@return integer x ---@return integer y ---@return integer z function PointGraph:getNodePoint(index) end ---Add a unidirected link from one node to another. ---@param fromIndex integer The index of the start node. ---@param toIndex integer The index of the end node. ---@param cost integer The cost of the link used when finding paths, typically corresponding to distance. function PointGraph:addLink(fromIndex, toIndex, cost) end ---Get the index of a node by its coordinates. ---Runs in O(1) time. ---@param x integer ---@param y integer ---@param z integer ---@return integer? index The index of the node, or nil if there isn't one at those coordinates. function PointGraph:getNodeByPoint(x, y, z) end ---Find the shortest path from a start node to an end node. ---Uses the A* algorithm. ---@param startIndex integer The index of the starting node. ---@param endIndex integer The index of the end/goal node. ---@return integer[]? path The list of node indices of the shortest path, or nil if no path was found. function PointGraph:findShortestPath(startIndex, endIndex) end end ---Represents a real number used in hooks whose value can be changed before its parent is called. ---@class HookFloat ---@field value number The underlying float value. ---Represents a 32-bit integer used in hooks whose value can be changed before its parent is called. ---@class HookInteger ---@field value integer The underlying int value. ---Represents a 32-bit unsigned integer used in hooks whose value can be changed before its parent is called. ---@class HookUnsignedInteger ---@field value integer The underlying unsigned int value. ---Represents a persistent player account stored on the server. ---@class Account ---@field class string 🔒 "Account" ---@field data table A Lua table which persists throughout the duration of the server. ---@field subRosaID integer Unique account index given by the master server, should not be used. ---@field phoneNumber integer Unique public ID tied to the account, ex. 2560001 ---@field money integer ---@field corporateRating integer ---@field criminalRating integer ---@field spawnTimer integer How long this person has to wait to spawn in, in seconds. ---@field playTime integer How many world mode minutes this person has played for. ---@field banTime integer Remaining ban time in minutes. ---@field index integer 🔒 The index of the array in memory this is (0-255). ---@field name string 🔒 Last known player name. ---@field steamID string 🔒 SteamID64 ---Represents a type of vehicle that exists. ---@class VehicleType ---@field class string 🔒 "VehicleType" ---@field usesExternalModel boolean ---@field controllableState integer 0 = cannot be controlled, 1 = car, 2 = helicopter. ---@field index integer 🔒 The index of the array in memory this is. ---@field name string Not networked. ---@field price integer How much money is taken when bought. ---@field mass number In kilograms, kind of. ---Represents a bullet currently flying through the air. ---Bullets can be moved around in memory every tick, so don't hold onto references. ---@class Bullet ---@field class string 🔒 "Bullet" ---@field type integer ---@field time integer How many ticks this bullet has left until it despawns. ---@field lastPos Vector Where the bullet was last tick. ---@field pos Vector Position. ---@field vel Vector Velocity. ---@field player? Player Who shot this bullet. ---Represents a bone in a human. ---@class Bone ---@field class string 🔒 "Bone" ---@field pos Vector Position. ---@field pos2 Vector Second position. ---@field vel Vector Velocity. ---@field rot RotMatrix Rotation. ---@class InventorySlot ---@field class string 🔒 "InventorySlot" ---@field primaryItem? Item 🔒 The first item in the slot, if any. ---@field secondaryItem? Item 🔒 The second item in the slot, if any. ---Represents a bond between one or two rigid bodies. ---@class Bond ---@field class string 🔒 "Bond" ---@field type integer ---@field despawnTime integer How many ticks until removal, 65536 for never. ---@field globalPos Vector ---@field localPos Vector ---@field otherLocalPos Vector ---@field index integer 🔒 The index of the array in memory this is (0-16383). ---@field isActive boolean Whether or not this exists, only change if you know what you are doing. ---@field body RigidBody The rigid body of this bond. ---@field otherBody RigidBody The second rigid body of this bond, if there is one. ---Represents a networked action sent from a player. ---@class Action ---@field class string 🔒 "Action" ---@field type integer ---@field a integer ---@field b integer ---@field c integer ---@field d integer ---Represents a button in the world base menu. ---@class MenuButton ---@field class string 🔒 "MenuButton" ---@field id integer The ID of the button. ---@field text string The text displayed on the button. ---Represents a lane on a street. ---@class StreetLane ---@field class string 🔒 "StreetLane" ---@field direction integer The direction of the lane, either 0 or 1. ---@field posA Vector The first point in the lane path. ---@field posB Vector The second point in the lane path. ---Represents an intersection of one or more streets. ---@class StreetIntersection ---@field class string 🔒 "StreetIntersection" ---@field pos Vector The centre point of the intersection. ---@field lightsState integer A number used internally by the traffic AI, which changes when the timer resets. ---@field lightsTimer integer A timer used internally by the traffic AI, which increments every tick until it reaches lightsTimerMax. ---@field lightsTimerMax integer The maximum value of the traffic timer before it resets. ---@field lightEast integer The colour of the east light. 0 = red, 1 = yellow, 2 = green. ---@field lightSouth integer The colour of the south light. 0 = red, 1 = yellow, 2 = green. ---@field lightWest integer The colour of the west light. 0 = red, 1 = yellow, 2 = green. ---@field lightNorth integer The colour of the north light. 0 = red, 1 = yellow, 2 = green. ---@field index integer 🔒 The index of the array in memory this is. ---@field streetEast? Street 🔒 The street connected to the east, if any. ---@field streetSouth? Street 🔒 The street connected to the south, if any. ---@field streetWest? Street 🔒 The street connected to the west, if any. ---@field streetNorth? Street 🔒 The street connected to the north, if any. ---@class TrafficCar ---@field class string 🔒 "TrafficCar" ---@field index integer 🔒 The index of the array in memory this is. ---@field type VehicleType The type of the car. ---@field human? Human The human driving the car. ---@field isBot boolean ---@field isAggressive boolean ---@field vehicle? Vehicle The real vehicle used by the car. ---@field pos Vector Position. ---@field vel Vector Velocity. ---@field yaw number Radians. ---@field rot RotMatrix Rotation. ---@field color integer The color of the car. ---@field state integer ---Represents a car for sale at a car shop. ---@class ShopCar ---@field class string 🔒 "ShopCar" ---@field price integer How much money is taken when bought. Note that if the key is sold, the price of the VehicleType is used for refunds. ---@field color integer The color of the car. ---@field type VehicleType The type of the car. ---Represents a state of someone being able to hear another person's voice chat. ---@class EarShot ---@field class string 🔒 "EarShot" ---@field isActive boolean Whether or not this exists. ---@field player? Player The player that the voice is coming from. ---@field human? Human The human that the voice appears to come from. ---@field receivingItem? Item The item that the voice appears to come from. ---@field transmittingItem? Item The item that the other person is using to transmit their voice. ---@field distance number The distance of the voice. ---@field volume number The estimated volume of the voice, 0 to 1. ---Represents an occurrence that is synchronized to all connections. ---@class Event ---@field class string 🔒 "Event" ---@field index integer 🔒 The index of the array in memory this is. ---@field type integer The type of the event. Different types use different data fields. ---@field tickCreated integer The number of ticks since the last game reset at which the event was created. ---@field vectorA Vector ---@field vectorB Vector ---@field a integer ---@field b integer ---@field c integer ---@field d integer ---@field floatA number ---@field floatB number ---@field message string Max length of 63.
nilq/small-lua-stack
null
require('./b.lua') local function test(hey) return hey end
nilq/small-lua-stack
null
Config = {} Config.DrawDistance = 100.0 Config.MarkerType = 31 Config.MarkerSize = { x = 1.5, y = 1.5, z = 1.0 } Config.MarkerColor = { r = 50, g = 50, b = 204 } Config.Locale = 'es' Config.CustomPeds = { CustomPeds = { Blip = { Pos = { x = 219.42, y = -855.55, z = 30.25 }, Sprite = 442, Display = 4, Scale = 1.2, Colour = 27, }, Cloakrooms = { { x = 219.42, y = -855.55, z = 30.25 }, }, } }
nilq/small-lua-stack
null
players = {} local playerCount = 0 function getPlayers() if (players) then return players else return false end end function refreshTable() players = {} --empty the table for k,v in ipairs(getElementsByType("player")) do name = getPlayerName(v) occupation = getElementData(v,"Occupation") if (occupation == false) then occupation = "None" end money = exports.server:convertNumber(getPlayerMoney(v)) playtime = getElementData(v,"playTime") if (playtime == false) then playtime = 0 end group = getElementData(v,"Group") if (group == false) then group = "None" end ping = getPlayerPing(v) team = getPlayerTeam(v) if (team) then r,g,b = getTeamColor(team) else r,g,b = 100,100,100 end if (getPlayerTeam(v) ~= nil) then if (isElement(team)) and (getTeamName(team) == "Staff") then r,g,b = 200,200,200 end end fps = exports.server:getPlayerFPS(v) city = exports.server:getPlayChatZone(v) sortID = getSortIDByTeam(v) if not (city) then city = "N/A" end table.insert(players,{name,occupation,money,math.floor(playtime/60),group,ping,r,g,b,fps,city,sortID}) end table.sort(players,function(a,b) return a[12] < b[12] end) end addEventHandler("onResourceStart",resourceRoot,refreshTable) setTimer(refreshTable,math.random(5000,10000),0) function getSortIDByTeam(player) if (isElement(player)) then local team = getPlayerTeam(player) if not (team) then return 0 end _name = getTeamName(team) end if (_name == "Staff") then return 1 elseif (_name == "Unemployed") then return 2 elseif (_name == "Unoccupied") then return 3 elseif (_name == "Civilian Workers") then return 4 elseif (_name == "Paramedics") then return 5 elseif (_name == "Government") then return 6 elseif (_name == "Criminals") then return 7 else return 0 end end --[[function getServerInformation() if (data) then return data else return false end end function updateServerInformation() data = {} gamemode = getGameType() local playerCount for k,v in ipairs(getElementsByType("player")) do playerCount = playerCount + 1 end local staff for k,v in ipairs(getElementsByType("player")) do if (exports.CSGstaff:isPlayerStaff(v)) then staff = staff + 1 end end table.insert(data,{gamemode,playerCount,staff}) end setTimer(updateServerInformation,5000,0) function getAllPlayers() return playerCount end ]]-- function getVersion() return "2.3" end
nilq/small-lua-stack
null
pfDatabase = {} local loc = GetLocale() local dbs = { "items", "quests", "objects", "units", "zones", "professions" } -- detect localized databases pfDatabase.dbstring = "" for id, db in pairs(dbs) do -- assign existing locale pfDB[db]["loc"] = pfDB[db][loc] or pfDB[db]["enUS"] pfDatabase.dbstring = pfDatabase.dbstring .. " |cffcccccc[|cffffffff" .. db .. "|cffcccccc:|cff33ffcc" .. ( pfDB[db][loc] and loc or "enUS" ) .. "|cffcccccc]" end -- add database shortcuts local items = pfDB["items"]["data"] local units = pfDB["units"]["data"] local objects = pfDB["objects"]["data"] local quests = pfDB["quests"]["data"] local zones = pfDB["zones"]["loc"] local professions = pfDB["professions"]["loc"] local bitraces = { [1] = "Human", [2] = "Orc", [4] = "Dwarf", [8] = "NightElf", [16] = "Scourge", [32] = "Tauren", [64] = "Gnome", [128] = "Troll" } local bitclasses = { [1] = "WARRIOR", [2] = "PALADIN", [4] = "HUNTER", [8] = "ROGUE", [16] = "PRIEST", [64] = "SHAMAN", [128] = "MAGE", [256] = "WARLOCK", [1024] = "DRUID" } -- PlayerHasSkill -- Returns false if the player has the required skill function pfDatabase:PlayerHasSkill(skill) if not professions[skill] then return false end for i=0,GetNumSkillLines() do if GetSkillLineInfo(i) == professions[skill] then return true end end return false end -- GetBitByRace -- Returns bit of the current race function pfDatabase:GetBitByRace(model) -- local _, model == UnitRace("player") for bit, v in pairs(bitraces) do if model == v then return bit end end end -- GetBitByClass -- Returns bit of the current class function pfDatabase:GetBitByClass(class) -- local _, class == UnitClass("player") for bit, v in pairs(bitclasses) do if class == v then return bit end end end local function strcomp(old, new) local prv = {} for o = 0, string.len(old) do prv[o] = "" end for n = 1, string.len(new) do local nxt = {[0] = string.sub(new,1, n)} local nn = string.sub(new, n, n) for o = 1, string.len(old) do local result if nn == string.sub(old, o, o) then result = prv[o-1] else result = prv[o]..nn if string.len(nxt[o-1]) <= string.len(result) then result = nxt[o-1] end end nxt[o] = result end prv = nxt end local diff = strlen(prv[string.len(old)]) if diff == 0 then return 0 else return diff/strlen(old) end end -- CompareString -- Shows a score based on the similarity of two strings function pfDatabase:CompareString(old, new) local s1 = strcomp(old, new) local s2 = strcomp(new, old) return (math.abs(s1) + math.abs(s2))/2 end -- GetHexDifficultyColor -- Returns a string with the difficulty color of the given level function pfDatabase:GetHexDifficultyColor(level, force) if force and UnitLevel("player") < level then return "|cffff5555" else local c = GetDifficultyColor(level) return string.format("|cff%02x%02x%02x", c.r*255, c.g*255, c.b*255) end end -- GetRaceMaskByID function pfDatabase:GetRaceMaskByID(id, db) -- 64 + 8 + 4 + 1 = 77 = Alliance -- 128 + 32 + 16 + 2 = 178 = Horde local factionMap = {["A"]=77, ["H"]=178, ["AH"]=255, ["HA"]=255} local raceMask = 0 if db == "quests" then raceMask = quests[id]["race"] or raceMask if (quests[id]["start"]) then local questStartRaceMask = 0 -- get quest starter faction if (quests[id]["start"]["U"]) then for _, startUnitId in ipairs(quests[id]["start"]["U"]) do if units[startUnitId]["fac"] and factionMap[units[startUnitId]["fac"]] then questStartRaceMask = bit.bor(factionMap[units[startUnitId]["fac"]]) end end end -- get quest object starter faction if (quests[id]["start"]["O"]) then for _, startObjectId in ipairs(quests[id]["start"]["O"]) do if objects[startObjectId]["fac"] and factionMap[objects[startObjectId]["fac"]] then questStartRaceMask = bit.bor(factionMap[objects[startObjectId]["fac"]]) end end end -- apply starter faction as racemask if questStartRaceMask > 0 and questStartRaceMask ~= raceMask then raceMask = questStartRaceMask end end elseif pfDB[db] and pfDB[db]["data"] and pfDB[db]["data"]["fac"] then raceMask = factionMap[pfDB[db]["data"]["fac"]] end return raceMask end -- GetIDByName -- Scans localization tables for matching IDs -- Returns table with all IDs function pfDatabase:GetIDByName(name, db, partial) if not pfDB[db] then return nil end local ret = {} for id, loc in pairs(pfDB[db]["loc"]) do if db == "quests" then loc = loc["T"] end if loc and name then if partial == true and strfind(strlower(loc), strlower(name)) then ret[id] = loc elseif partial == "LOWER" and strlower(loc) == strlower(name) then ret[id] = loc elseif loc == name then ret[id] = loc end end end local count = 0 for _ in pairs(ret) do count = count + 1 end if count == 0 then DEFAULT_CHAT_FRAME:AddMessage("No results for your search of "..name..".") elseif count > 1 then DEFAULT_CHAT_FRAME:AddMessage("Multiple results were found for your search of "..name..":") local multi = "" for i,j in pairs(ret) do multi = multi..j.." ("..i.."); " end DEFAULT_CHAT_FRAME:AddMessage(multi) end return ret end -- GetIDByIDPart -- Scans localization tables for matching IDs -- Returns table with all IDs function pfDatabase:GetIDByIDPart(idPart, db) if not pfDB[db] then return nil end local ret = {} for id, loc in pairs(pfDB[db]["loc"]) do if db == "quests" then loc = loc["T"] end if idPart and loc and strfind(tostring(id), idPart) then ret[id] = loc end end return ret end -- GetBestMap -- Scans a map table for all spawns -- Returns the map with most spawns function pfDatabase:GetBestMap(maps) local bestmap, bestscore = nil, 0 -- calculate best map results for map, count in pairs(maps or {}) do if count > bestscore then bestscore = count bestmap = map end end return bestmap or nil, bestscore or nil end -- SearchMobID -- Scans for all mobs with a specified ID -- Adds map nodes for each and returns its map table function pfDatabase:SearchMobID(id, meta, maps) if not units[id] or not units[id]["coords"] then return maps end local maps = maps or {} for _, data in pairs(units[id]["coords"]) do local x, y, zone, respawn = unpack(data) if pfMap:IsValidMap(zone) and zone > 0 then -- add all gathered data meta = meta or {} meta["spawn"] = pfDB.units.loc[id] meta["spawnid"] = id meta["title"] = meta["quest"] or meta["item"] or meta["spawn"] meta["zone"] = zone meta["x"] = x meta["y"] = y meta["level"] = units[id]["lvl"] or UNKNOWN meta["spawntype"] = "Unit" meta["respawn"] = respawn > 0 and SecondsToTime(respawn) maps[zone] = maps[zone] and maps[zone] + 1 or 1 pfMap:AddNode(meta) end end return maps end -- Search MetaRelation -- Scans for all entries within the specified meta name -- Adds map nodes for each and returns its map table -- query = { relation-name, relation-min, relation-max } function pfDatabase:SearchMetaRelation(query, meta, show) local maps = {} local relname = query[1] -- search name (chests) local relmins = query[2] -- min skill level local relmaxs = query[3] -- max skill level if pfDB["meta"] and pfDB["meta"][relname] then for id, skill in pairs(pfDB["meta"][relname]) do if ( not relmins or tonumber(relmins) <= skill ) and ( not relmaxs or tonumber(relmaxs) >= skill ) then if id < 0 then pfDatabase:SearchObjectID(math.abs(id), meta, maps) else pfDatabase:SearchMobID(id, meta, maps) end end end end return maps end -- SearchMob -- Scans for all mobs with a specified name -- Adds map nodes for each and returns its map table function pfDatabase:SearchMob(mob, meta, partial) local maps = {} for id in pairs(pfDatabase:GetIDByName(mob, "units", partial)) do if units[id] and units[id]["coords"] then maps = pfDatabase:SearchMobID(id, meta, maps) end end return maps end -- Scans for all objects with a specified ID -- Adds map nodes for each and returns its map table function pfDatabase:SearchObjectID(id, meta, maps) if not objects[id] or not objects[id]["coords"] then return maps end local maps = maps or {} for _, data in pairs(objects[id]["coords"]) do local x, y, zone, respawn = unpack(data) if pfMap:IsValidMap(zone) and zone > 0 then -- add all gathered data meta = meta or {} meta["spawn"] = pfDB.objects.loc[id] meta["spawnid"] = id meta["title"] = meta["quest"] or meta["item"] or meta["spawn"] meta["zone"] = zone meta["x"] = x meta["y"] = y meta["level"] = nil meta["spawntype"] = "Object" meta["respawn"] = respawn and SecondsToTime(respawn) maps[zone] = maps[zone] and maps[zone] + 1 or 1 pfMap:AddNode(meta) end end return maps end -- SearchObject -- Scans for all objects with a specified name -- Adds map nodes for each and returns its map table function pfDatabase:SearchObject(obj, meta, partial) local maps = {} for id in pairs(pfDatabase:GetIDByName(obj, "objects", partial)) do if objects[id] and objects[id]["coords"] then maps = pfDatabase:SearchObjectID(id, meta, maps) end end return maps end -- SearchItemID -- Scans for all items with a specified ID -- Adds map nodes for each drop and vendor -- Returns its map table function pfDatabase:SearchItemID(id, meta, maps, allowedTypes) if not items[id] then return maps end local maps = maps or {} local meta = meta or {} meta["itemid"] = id meta["item"] = pfDB.items.loc[id] local minChance = tonumber(pfQuest_config.mindropchance) if not minChance then minChance = 0 end -- search unit drops if items[id]["U"] and ((not allowedTypes) or allowedTypes["U"]) then for unit, chance in pairs(items[id]["U"]) do if chance >= minChance then meta["texture"] = nil meta["droprate"] = chance meta["sellcount"] = nil maps = pfDatabase:SearchMobID(unit, meta, maps) end end end -- search object loot (veins, chests, ..) if items[id]["O"] and ((not allowedTypes) or allowedTypes["O"]) then for object, chance in pairs(items[id]["O"]) do if chance >= minChance and chance > 0 then meta["texture"] = nil meta["droprate"] = chance meta["sellcount"] = nil maps = pfDatabase:SearchObjectID(object, meta, maps) end end end -- search vendor goods if items[id]["V"] and ((not allowedTypes) or allowedTypes["V"]) then for unit, chance in pairs(items[id]["V"]) do meta["texture"] = "Interface\\AddOns\\pfQuest\\img\\icon_vendor" meta["droprate"] = nil meta["sellcount"] = chance maps = pfDatabase:SearchMobID(unit, meta, maps) end end return maps end -- SearchItem -- Scans for all items with a specified name -- Adds map nodes for each drop and vendor -- Returns its map table function pfDatabase:SearchItem(item, meta, partial) local maps = {} local bestmap, bestscore = nil, 0 for id in pairs(pfDatabase:GetIDByName(item, "items", partial)) do maps = pfDatabase:SearchItemID(id, meta, maps) end return maps end -- SearchVendor -- Scans for all items with a specified name -- Adds map nodes for each vendor -- Returns its map table function pfDatabase:SearchVendor(item, meta) local maps = {} local meta = meta or {} local bestmap, bestscore = nil, 0 for i,id in pairs(pfDatabase:GetIDByName(item, "items")) do meta["itemid"] = id meta["item"] = pfDB.items.loc[id] -- search vendor goods if items[id] and items[id]["V"] then for unit, chance in pairs(items[id]["V"]) do meta["texture"] = "Interface\\AddOns\\pfQuest\\img\\icon_vendor" meta["droprate"] = nil meta["sellcount"] = chance maps = pfDatabase:SearchMobID(unit, meta, maps) end end end return maps end -- SearchQuestID -- Scans for all quests with a specified ID -- Adds map nodes for each objective and involved units -- Returns its map table function pfDatabase:SearchQuestID(id, meta, maps) local maps = maps or {} local meta = meta or {} meta["questid"] = id meta["quest"] = pfDB.quests.loc[id].T meta["qlvl"] = quests[id]["lvl"] meta["qmin"] = quests[id]["min"] if pfQuest_config["currentquestgivers"] == "1" then -- search quest-starter if quests[id]["start"] and not meta["qlogid"] then -- units if quests[id]["start"]["U"] then for _, unit in pairs(quests[id]["start"]["U"]) do meta = meta or {} meta["layer"] = meta["layer"] or 4 meta["texture"] = "Interface\\AddOns\\pfQuest\\img\\available_c" maps = pfDatabase:SearchMobID(unit, meta, maps) end end -- objects if quests[id]["start"]["O"] then for _, object in pairs(quests[id]["start"]["O"]) do meta = meta or {} meta["texture"] = "Interface\\AddOns\\pfQuest\\img\\available_c" maps = pfDatabase:SearchObjectID(object, meta, maps) end end end -- search quest-ender if quests[id]["end"] then -- units if quests[id]["end"]["U"] then for _, unit in pairs(quests[id]["end"]["U"]) do meta = meta or {} if meta["qlogid"] then local _, _, _, _, _, complete = GetQuestLogTitle(meta["qlogid"]) complete = complete or GetNumQuestLeaderBoards(meta["qlogid"]) == 0 and true or nil if complete then meta["texture"] = "Interface\\AddOns\\pfQuest\\img\\complete_c" else meta["texture"] = "Interface\\AddOns\\pfQuest\\img\\complete" end else meta["texture"] = "Interface\\AddOns\\pfQuest\\img\\complete_c" end maps = pfDatabase:SearchMobID(unit, meta, maps) end end -- objects if quests[id]["end"]["O"] then for _, object in pairs(quests[id]["end"]["O"]) do meta = meta or {} if meta["qlogid"] then local _, _, _, _, _, complete = GetQuestLogTitle(meta["qlogid"]) complete = complete or GetNumQuestLeaderBoards(meta["qlogid"]) == 0 and true or nil if complete then meta["texture"] = "Interface\\AddOns\\pfQuest\\img\\complete_c" else meta["texture"] = "Interface\\AddOns\\pfQuest\\img\\complete" end else meta["texture"] = "Interface\\AddOns\\pfQuest\\img\\complete_c" end maps = pfDatabase:SearchObjectID(object, meta, maps) end end end end local parse_obj = { ["U"] = {}, ["O"] = {}, ["I"] = {}, } -- If QuestLogID is given, scan and add all finished objectives to blacklist if meta["qlogid"] then local objectives = GetNumQuestLeaderBoards(meta["qlogid"]) local _, _, _, _, _, complete = GetQuestLogTitle(meta["qlogid"]) if objectives and not complete then for i=1, objectives, 1 do local text, type, done = GetQuestLogLeaderBoard(i, meta["qlogid"]) -- spawn data if type == "monster" then local i, j, monsterName, objNum, objNeeded = strfind(text, pfUI.api.SanitizePattern(QUEST_MONSTERS_KILLED)) for id in pairs(pfDatabase:GetIDByName(monsterName, "units")) do parse_obj["U"][id] = ( objNum + 0 >= objNeeded + 0 or done ) and "DONE" or "PROG" end for id in pairs(pfDatabase:GetIDByName(monsterName, "objects")) do parse_obj["O"][id] = ( objNum + 0 >= objNeeded + 0 or done ) and "DONE" or "PROG" end end -- item data if type == "item" then local i, j, itemName, objNum, objNeeded = strfind(text, pfUI.api.SanitizePattern(QUEST_OBJECTS_FOUND)) for id in pairs(pfDatabase:GetIDByName(itemName, "items")) do parse_obj["I"][id] = ( objNum + 0 >= objNeeded + 0 or done ) and "DONE" or "PROG" end end end end end -- search quest-objectives if quests[id]["obj"] then if meta["qlogid"] then local _, _, _, _, _, complete = GetQuestLogTitle(meta["qlogid"]) if complete then return maps end end -- units if quests[id]["obj"]["U"] then for _, unit in pairs(quests[id]["obj"]["U"]) do if not parse_obj["U"][unit] or parse_obj["U"][unit] ~= "DONE" then meta = meta or {} meta["texture"] = nil maps = pfDatabase:SearchMobID(unit, meta, maps) end end end -- objects if quests[id]["obj"]["O"] then for _, object in pairs(quests[id]["obj"]["O"]) do if not parse_obj["O"][object] or parse_obj["O"][object] ~= "DONE" then meta = meta or {} meta["texture"] = nil meta["layer"] = 2 maps = pfDatabase:SearchObjectID(object, meta, maps) end end end -- items if quests[id]["obj"]["I"] then for _, item in pairs(quests[id]["obj"]["I"]) do if not parse_obj["I"][item] or parse_obj["I"][item] ~= "DONE" then meta = meta or {} meta["texture"] = nil meta["layer"] = 2 maps = pfDatabase:SearchItemID(item, meta, maps) end end end end return maps end -- SearchQuest -- Scans for all quests with a specified name -- Adds map nodes for each objective and involved unit -- Returns its map table function pfDatabase:SearchQuest(quest, meta, partial) local maps = {} for id in pairs(pfDatabase:GetIDByName(quest, "quests", partial)) do maps = pfDatabase:SearchQuestID(id, meta, maps) end return maps end -- SearchQuests -- Scans for all available quests -- Adds map nodes for each quest starter and ender -- Returns its map table function pfDatabase:SearchQuests(meta, maps) local level, minlvl, maxlvl, race, class, prof local maps = maps or {} local meta = meta or {} local plevel = UnitLevel("player") local pfaction = UnitFactionGroup("player") if pfaction == "Horde" then pfaction = "H" elseif pfaction == "Alliance" then pfaction = "A" else pfaction = "GM" end local _, race = UnitRace("player") local prace = pfDatabase:GetBitByRace(race) local _, class = UnitClass("player") local pclass = pfDatabase:GetBitByClass(class) local currentQuests = {} for id=1, GetNumQuestLogEntries() do local title = GetQuestLogTitle(id) currentQuests[title] = true end for id in pairs(quests) do minlvl = quests[id]["min"] or quests[id]["lvl"] maxlvl = quests[id]["lvl"] if pfDB.quests.loc[id] and currentQuests[pfDB.quests.loc[id].T] then -- hide active quest elseif pfQuest_history[id] then -- hide completed quests elseif quests[id]["pre"] and not pfQuest_history[quests[id]["pre"]] then -- hide missing pre-quests elseif quests[id]["race"] and not ( bit.band(quests[id]["race"], prace) == prace ) then -- hide non-available quests for your race elseif quests[id]["class"] and not ( bit.band(quests[id]["class"], pclass) == pclass ) then -- hide non-available quests for your class elseif quests[id]["lvl"] and quests[id]["lvl"] < plevel - 9 and pfQuest_config["showlowlevel"] == "0" then -- hide lowlevel quests elseif quests[id]["lvl"] and quests[id]["lvl"] > plevel + 10 then -- hide highlevel quests elseif quests[id]["min"] and quests[id]["min"] > plevel + 3 then -- hide highlevel quests elseif math.abs(minlvl - maxlvl) >= 30 and pfQuest_config["showfestival"] == "0" then -- hide event quests elseif minlvl > plevel and pfQuest_config["showhighlevel"] == "0" then -- hide level+3 quests elseif quests[id]["skill"] and not pfDatabase:PlayerHasSkill(quests[id]["skill"]) then -- hide non-available quests for your class else -- set metadata meta["quest"] = ( pfDB.quests.loc[id] and pfDB.quests.loc[id].T ) or UNKNOWN meta["questid"] = id meta["texture"] = "Interface\\AddOns\\pfQuest\\img\\available_c" meta["qlvl"] = quests[id]["lvl"] meta["qmin"] = quests[id]["min"] meta["vertex"] = { 0, 0, 0 } meta["layer"] = 3 -- tint high level quests red if minlvl > plevel then meta["texture"] = "Interface\\AddOns\\pfQuest\\img\\available" meta["vertex"] = { 1, .6, .6 } meta["layer"] = 2 end -- tint low level quests grey if maxlvl + 9 < plevel then meta["texture"] = "Interface\\AddOns\\pfQuest\\img\\available" meta["vertex"] = { 1, 1, 1 } meta["layer"] = 2 end -- treat big difference in level requirements as daily quests if math.abs(minlvl - maxlvl) >= 30 then meta["texture"] = "Interface\\AddOns\\pfQuest\\img\\available" meta["vertex"] = { .2, .8, 1 } meta["layer"] = 2 end -- iterate over all questgivers if quests[id]["start"] then -- units if quests[id]["start"]["U"] then for _, unit in pairs(quests[id]["start"]["U"]) do if units[unit] and strfind(units[unit]["fac"] or pfaction, pfaction) then maps = pfDatabase:SearchMobID(unit, meta, maps) end end end -- objects if quests[id]["start"]["O"] then for _, object in pairs(quests[id]["start"]["O"]) do if objects[object] and strfind(objects[object]["fac"] or pfaction, pfaction) then maps = pfDatabase:SearchObjectID(object, meta, maps) end end end end end end end function pfDatabase:FormatQuestText(questText) questText = string.gsub(questText, "$[Nn]", UnitName("player")) questText = string.gsub(questText, "$[Cc]", strlower(UnitClass("player"))) questText = string.gsub(questText, "$[Rr]", strlower(UnitRace("player"))) questText = string.gsub(questText, "$[Bb]", "\n") -- UnitSex("player") returns 2 for male and 3 for female -- that's why there is an unused capture group around the $[Gg] return string.gsub(questText, "($[Gg])(.+):(.+);", "%"..UnitSex("player")) end -- GetQuestIDs -- Try to guess the quest ID based on the questlog ID -- automatically runs a deep scan if no result was found. -- Returns possible quest IDs function pfDatabase:GetQuestIDs(qid, deep) local oldID = GetQuestLogSelection() SelectQuestLogEntry(qid) local text, objective = GetQuestLogQuestText() local title, level, _, header = GetQuestLogTitle(qid) SelectQuestLogEntry(oldID) local _, race = UnitRace("player") local prace = pfDatabase:GetBitByRace(race) local _, class = UnitClass("player") local pclass = pfDatabase:GetBitByClass(class) local best = 0 local results = {} for id, data in pairs(pfDB["quests"]["loc"]) do local score = 0 if quests[id] and (data.T == title or ( deep and strsub(pfDatabase:FormatQuestText(pfDB.quests.loc[id]["O"]),0,10) == strsub(objective,0,10))) then if quests[id]["lvl"] == level then score = score + 1 end if pfDB.quests.loc[id]["O"] == objective then score = score + 2 end if quests[id]["race"] and ( bit.band(quests[id]["race"], prace) == prace ) then score = score + 4 end if quests[id]["class"] and ( bit.band(quests[id]["class"], pclass) == pclass ) then score = score + 4 end local dbtext = strsub(pfDatabase:FormatQuestText(pfDB.quests.loc[id]["D"]),0,10) local qstext = strsub(text,0,10) if pfDatabase:CompareString(dbtext, qstext) < 0.1 then score = score + 8 end if score > best then best = score end results[score] = results[score] or {} table.insert(results[score], id) end end return results[best] or ( not deep and pfDatabase:GetQuestIDs(qid, 1) or {} ) end -- browser search related defaults and values pfDatabase.lastSearchQuery = "" pfDatabase.lastSearchResults = {["items"] = {}, ["quests"] = {}, ["objects"] = {}, ["units"] = {}} -- BrowserSearch -- Search for a list of IDs of the specified `searchType` based on if `query` is -- part of the name or ID of the database entry it is compared against. -- -- `query` must be a string. If the string represents a number, the search is -- based on IDs, otherwise it compares names. -- -- `searchType` must be one of these strings: "items", "quests", "objects" or -- "units" -- -- Returns a table and an integer, the latter being the element count of the -- former. The table contains the ID as keys for the name of the search result. -- E.g.: {{[5] = "Some Name", [231] = "Another Name"}, 2} -- If the query doesn't satisfy the minimum search length requiered for its -- type (number/string), the favourites for the `searchType` are returned. function pfDatabase:BrowserSearch(query, searchType) local queryLength = strlen(query) -- needed for some checks local queryNumber = tonumber(query) -- if nil, the query is NOT a number local results = {} -- save results local resultCount = 0; -- count results -- Set the DB to be searched local minChars = 3 local minInts = 1 if (queryLength >= minChars) or (queryNumber and (queryLength >= minInts)) then -- make sure this is no fav display if ((queryLength > minChars) or (queryNumber and (queryLength > minInts))) and (pfDatabase.lastSearchQuery ~= "" and queryLength > strlen(pfDatabase.lastSearchQuery)) then -- there are previous search results to use local searchDatabase = pfDatabase.lastSearchResults[searchType] -- iterate the last search for id, _ in pairs(searchDatabase) do local dbLocale = pfDB[searchType]["loc"][id] if (dbLocale) then local compare local search = query if (queryNumber) then -- do number search compare = tostring(id) else -- do name search search = strlower(query) if (searchType == "quests") then compare = strlower(dbLocale["T"]) else compare = strlower(dbLocale) end end -- search and save on match if (strfind(compare, search)) then results[id] = dbLocale resultCount = resultCount + 1 end end end return results, resultCount else -- no previous results, search whole DB if (queryNumber) then results = pfDatabase:GetIDByIDPart(query, searchType) else results = pfDatabase:GetIDByName(query, searchType, true) end local resultCount = 0 for _,_ in pairs(results) do resultCount = resultCount + 1 end return results, resultCount end else -- minimal search length not satisfied, reset search results and return favourites return pfBrowser_fav[searchType], -1 end end
nilq/small-lua-stack
null
return { {"wbthomason/packer.nvim", disable = false}, {"nvim-lua/plenary.nvim", disable = false}, {"norcalli/nvim-colorizer.lua", disable = false}, {"folke/twilight.nvim", disable = false}, {"folke/zen-mode.nvim", disable = false}, {"b3nj5m1n/kommentary", disable = false}, {"chrisbra/Colorizer", disable = true}, {"nathom/filetype.nvim", disable = false}, {"luukvbaal/stabilize.nvim", disable = false}, {"Shatur/neovim-session-manager", disable = true}, { "folke/trouble.nvim", requires = "kyazdani42/nvim-web-devicons", disable = false }, {"numToStr/Comment.nvim", disable = false}, {"kyazdani42/nvim-tree.lua", disable = false}, {"nvim-telescope/telescope.nvim", disable = false, opts = false}, {"LinArcX/telescope-command-palette.nvim", disable = false}, {"LinArcX/telescope-env.nvim"}, { 'sudormrfbin/cheatsheet.nvim', requires = { {'nvim-telescope/telescope.nvim'}, {'nvim-lua/popup.nvim'}, {'nvim-lua/plenary.nvim'} }, disable = false }, { "AckslD/nvim-neoclip.lua", requires = { {'tami5/sqlite.lua', module = 'sqlite'}, {'nvim-telescope/telescope.nvim'} }, disable = false }, {"xiyaowong/telescope-emoji.nvim", disable = false}, {'crispgm/telescope-heading.nvim', disable = false}, { 'dhruvmanila/telescope-bookmarks.nvim', requires = {'tami5/sqlite.lua'}, disable = false }, { "nvim-telescope/telescope-frecency.nvim", requires = {"tami5/sqlite.lua"}, disable = false }, {"tami5/sqlite.lua", disable = false}, { 'pwntester/octo.nvim', requires = { 'nvim-lua/plenary.nvim', 'nvim-telescope/telescope.nvim', 'kyazdani42/nvim-web-devicons' }, disable = false }, {"gbrlsnchs/telescope-lsp-handlers.nvim", disable = false}, {"TC72/telescope-tele-tabby.nvim", disable = false}, {"cljoly/telescope-repo.nvim", disable = false}, {"nvim-telescope/telescope-symbols.nvim", disable = false}, {"nvim-telescope/telescope-fzf-writer.nvim", disable = false}, {"nvim-telescope/telescope-media-files.nvim", disable = false}, {"nvim-telescope/telescope-github.nvim", disable = false}, {"nvim-telescope/telescope-project.nvim", disable = false}, {"nvim-telescope/telescope-packer.nvim", disable = false}, {"akinsho/toggleterm.nvim", disable = false} }
nilq/small-lua-stack
null
--[[ /////// ////////////////// /////// PROJECT: MTA iLife - German Fun Reallife Gamemode /////// VERSION: 1.7.2 /////// DEVELOPERS: See DEVELOPERS.md in the top folder /////// LICENSE: See LICENSE.md in the top folder /////// ///////////////// ]] GangAreas = {} GangwarUnderAttack = false CGangArea = {} function CGangArea:constructor(iID, sName, tColShapes, iFactionID, iLastAttacked, bUseable, iIncome) self.ID = iID self.Name = sName self.ColShapes = {} self.RadarAreas = {} self.DimRadarAreas = {} self.Faction = Factions[iFactionID] self.LastAttacked = iLastAttacked self.Useable = bUseable self.Income = iIncome for k,v in pairs(tColShapes) do if (self.Useable ~= 0) then table.insert(self.ColShapes, createColCuboid(v["X"], v["Y"], v["Z"], v["W"], v["H"], v["D"])) local r,g,b = self.Faction:getColors() table.insert(self.RadarAreas, createRadarArea(v["X"], v["Y"], v["W"], v["H"], r, g, b, 70, getRootElement())) table.insert(self.DimRadarAreas, createRadarArea(v["X"], v["Y"], v["W"], v["H"], r, g, b, 0, getRootElement())) end end for k,v in pairs(self.ColShapes) do setElementDimension(v, 60000) addEventHandler("onColShapeHit", v, bind(CGangArea.onColShapeHit, self)) addEventHandler("onColShapeLeave", v, bind(CGangArea.onColShapeLeave, self)) end self.isUnderAttack = false self.Peds = {} self.Attacker = nil self.endTimer = nil self.CapturePoints = {} self.ActiveDefender = {} self.ActiveAttacker = {} self.StartDefender = {} self.StartAttacker = {} self.PreLeaveTimers = {} self.LeaveTimers = {} self.CountAttacker = 0 self.CountDefender = 0 self.TicketsAttacker = 2000 self.TicketsDefender = 2000 self.LastTick = getTickCount() GangAreas[self.Name] = self end function CGangArea:destructor() end function CGangArea:addPed(thePed) table.insert(self.Peds, thePed) end function CGangArea:onColShapeHit(hitElement, matchingDimension) if (self.isUnderAttack) then if (getElementType(hitElement) == "player") then if (matchingDimension) then --returned to gw? local vehicle = false if (isPedInVehicle(hitElement)) then vehicle = getPedOccupiedVehicle(hitElement) end if (self.PreLeaveTimers[hitElement:getName()] and isTimer(self.PreLeaveTimers[hitElement:getName()])) then killTimer(self.PreLeaveTimers[hitElement:getName()]) end if (self.LeaveTimers[hitElement:getName()] and isTimer(self.LeaveTimers[hitElement:getName()])) then killTimer(self.LeaveTimers[hitElement:getName()]) end else -- new to gw? local vehicle = false if (isPedInVehicle(hitElement)) then vehicle = getPedOccupiedVehicle(hitElement) end if (self.ActiveDefender[hitElement:getName()]) then setElementDimension(hitElement, 60000) if (vehicle) then setElementDimension(vehicle, 60000) end hitElement:incrementStatistics("GangWar", "GangWars_betreten", 1) end end end end end function CGangArea:onColShapeLeave(leaveElement, matchingDimension) if (self.isUnderAttack) then if (getElementType(leaveElement) == "player") then if (matchingDimension) then --left or died? local vehicle = false if (isPedInVehicle(leaveElement)) then vehicle = getPedOccupiedVehicle(leaveElement) end self.PreLeaveTimers[leaveElement:getName()] = setTimer( function() if (getElementDimension(leaveElement) == 60000) then -- Give him a chance to return! if (getElementZoneName(leaveElement) == self.Name) then return false end outputChatBox("Du hast 10 Sekunden Zeit um das Gebiet erneut zu betreten!", leaveElement, 255,0,0) self.LeaveTimers[leaveElement:getName()] = setTimer( function() if (getElementZoneName(leaveElement) == self.Name) then return false end setElementDimension(leaveElement, 0) if (vehicle) then setElementDimension(vehicle, 0) end self.ActiveDefender[leaveElement:getName()] = nil self.ActiveAttacker[leaveElement:getName()] = nil outputChatBox("Du hast die Schlacht verlassen! Schäme dich!", leaveElement, 255,0,0) end , 10000, 1) end end , 1000, 1) else -- Died self.ActiveDefender[leaveElement:getName()] = nil self.ActiveAttacker[leaveElement:getName()] = nil end end end end function CGangArea:startGangWar(thePlayer) if (GangwarUnderAttack) then thePlayer:showInfoBox("error", "Es wird bereits ein Gebiet umkämpft!") return false end if ( (thePlayer:getFaction():getType() == 2) and (self.Faction ~= thePlayer:getFaction())) then if (thePlayer:getRank() >= 4) then GangwarUnderAttack = true self.isUnderAttack = true self.Attacker = thePlayer:getFaction() else thePlayer:showInfoBox("error", "Dafür benötigst du mindestens Rang 4!") return false end else return false end for k,v in ipairs(getElementsByType("pickup")) do if (getElementData(v, "h:iFactionID") and getElementData(v, "h:iFactionID") ~= 0) then if (getElementZoneName(v) == getElementZoneName(thePlayer)) then thePlayer:showInfoBox("error", "Dieses Gebiet ist ein Hauptquartier!") GangwarUnderAttack = false return false end end end for k,v in ipairs(getElementsByType("player")) do if (getElementData(v, "online")) and (v:getFaction() == self.Faction) then self.ActiveDefender[v:getName()] = true table.insert(self.StartDefender, v) end end for k,v in ipairs(self:getElementsIn("player")) do if (getElementData(v, "online")) and (v:getFaction() == self.Attacker) then self.ActiveAttacker[v:getName()] = true table.insert(self.StartAttacker, v) if (getElementDimension(v) == 0) then setElementDimension(v, 60000) end v:incrementStatistics("GangWar", "GangWars_betreten", 1) end if (v:getFaction() == self.Faction) then self.ActiveDefender[v:getName()] = true if (getElementDimension(v) == 0) then setElementDimension(v, 60000) end v:incrementStatistics("GangWar", "GangWars_betreten", 1) end end for k,v in ipairs(self:getElementsIn("vehicle")) do if (getElementData(v, "Fraktion") and (getElementData(v, "Fraktion") == thePlayer:getFaction():getID())) then setElementDimension(v, 60000) end end self.CountAttacker = #self.StartAttacker self.CountDefender = #self.StartDefender local minAttacker = 3 if (self.CountAttacker < minAttacker) then thePlayer:showInfoBox("error", "Es werden mindestens "..minAttacker.." Angreifer benötigt!") self:reset() return false end if (self.CountAttacker > self.CountDefender) then thePlayer:showInfoBox("error", "Es müssen weniger Angreifer als Verteidiger teilnehmen!") self:reset() return false end local time = getRealTime() if ((self.LastAttacked +(60*60*24)) > time["timestamp"]) then thePlayer:showInfoBox("error", "Dieses Gebiet wurde heute bereits umkämpft!") self:reset() return false end self.LastAttacked = time["timestamp"] for k,v in ipairs(self.Peds) do local x,y,z = getElementPosition(v) local rx,ry,rz = getElementRotation(v) table.insert(self.CapturePoints, new(CCapturePoint, createPed(getElementModel(v), x,y,z, rz, true), createMarker(x,y,z-1, "cylinder", 6, 125, 0, 0, 50, getRootElement()), self.Faction, self.Attacker)) end self.Timer = setTimer( function() if (getTickCount()-self.LastTick > 5000) and (getTickCount()-self.AttackStamp > 180000) then for k,v in ipairs(self.CapturePoints) do v:update() if (v:getPoints() <= 0) then self.TicketsAttacker = self.TicketsAttacker - ((1*(math.abs(v:getPoints())/100))*5/#self.CapturePoints) else self.TicketsDefender = self.TicketsDefender - ((1*(math.abs(v:getPoints())/100))*5/#self.CapturePoints) end if (self.TicketsAttacker <= 0) or (self.TicketsDefender <= 0) then self:finish(self.TicketsAttacker > 0) return true end end RPCCall("updateGangWarRenderer", self.TicketsDefender, self.TicketsAttacker) else for k,v in ipairs(self.CapturePoints) do v:update() end end end, 1500, 0) for k,v in ipairs(self.RadarAreas) do setRadarAreaColor(v, 255, 0 ,0 ,125) setRadarAreaFlashing(v, true) end for k,v in ipairs(self.DimRadarAreas) do setElementDimension(v, 60000) setRadarAreaColor(v, 255, 0 ,0 ,125) setRadarAreaFlashing(v, true) end self.AttackStamp = getTickCount() local tblMarkers = {} for k,v in ipairs(self.CapturePoints) do table.insert(tblMarkers, v.Marker) end RPCCall("initializeGangWarRenderer", self.Faction:getName(), self.Attacker:getName(), tblMarkers) self.Faction:sendMessage("Ein Ganggebiet ("..self.Name..") wird angegriffen!") self.Attacker:sendMessage("Ihr habt ein Ganggebiet ("..self.Name..") angegriffen!") end function CGangArea:finish(bSuccess) if (bSuccess) then self.Faction:sendMessage("Ein Ganggebiet ("..self.Name..") wurde verloren!") self.Attacker:sendMessage("Ihr habt ein Ganggebiet ("..self.Name..") erobert!") self.Faction = self.Attacker self.Income = 200 for k,v in ipairs(self.Peds) do setElementModel(v, self.Faction:getRankSkin(math.random(1,4))) end for k,v in ipairs(self.StartAttacker) do if ((v) and (getElementType(v) == player)) then v:incrementStatistics("GangWar", "GangWars_gewonnen", 1) end end else self.Faction:sendMessage("Ein Ganggebiet ("..self.Name..") wurde verteidigt!") self.Attacker:sendMessage("Ihr habt es nicht geschafft ein Ganggebiet ("..self.Name..") zu erobern!") for k,v in ipairs(self.StartDefender) do if ((v) and (getElementType(v) == player)) then v:incrementStatistics("GangWar", "GangWars_gewonnen", 1) end end end RPCCall("finshGangWarRenderer", self.Faction:getName()) self:save() self:reset() end function CGangArea:reset() for k,v in ipairs(self:getElementsIn("player")) do if (getElementDimension(v) == 60000) then setElementDimension(v, 0) end end for k,v in ipairs(self:getElementsIn("vehicle")) do if (getElementDimension(v) == 60000) then setElementDimension(v, 0) end end self.isUnderAttack = false self.Attacker = nil if (isTimer(self.Timer)) then killTimer(self.Timer) end self.Timer = nil self.ActiveDefender = {} self.ActiveAttacker = {} self.StartDefender = {} self.StartAttacker = {} self.CountAttacker = 0 self.CountDefender = 0 self.TicketsAttacker = 2000 self.TicketsDefender = 2000 local r,g,b = self.Faction:getColors() for k,v in ipairs(self.RadarAreas) do setRadarAreaColor(v, r, g ,b ,70) setRadarAreaFlashing(v, false) end for k,v in ipairs(self.DimRadarAreas) do setRadarAreaColor(v, 255, 0 ,0 ,0) setRadarAreaFlashing(v, false) end for k,v in ipairs(self.CapturePoints) do delete(v) end GangwarUnderAttack = false end function CGangArea:save() CDatabase:getInstance():query("UPDATE Gangareas SET FactionID=?, LastAttacked=?, Income=? WHERE ID=?", self.Faction:getID(), self.LastAttacked, self.Income, self.ID) end function CGangArea:getFaction() return self.Faction end function CGangArea:setIncome(iAmount) self.Income = iAmount end function CGangArea:getIncome() return self.Income end function CGangArea:getElementsIn(typ) local tabk = {} local tab = {} for k,v in ipairs(self.ColShapes) do for kk,vv in ipairs(getElementsWithinColShape(v, typ)) do tabk[vv] = true end end for k,v in pairs(tabk) do table.insert(tab, k) end return tab end function CGangArea:isElementIn(element) for k,v in ipairs(self.ColShapes) do if isElementWithinColShape(element, v) then return true end end return false end addEvent("onGangwarStartConfirm", true) addEventHandler("onGangwarStartConfirm", getRootElement(), function() local x,y,z = getElementPosition(client) if (type(GangAreas[getZoneName(x,y,z,false)]) == "table") then GangAreas[getZoneName(x,y,z,false)]:startGangWar(client) end end) --[[ addCommandHandler("markarea", function(player, cmd, t) local zone = getElementZoneName(player) if (GangAreas[zone]) then if (tonumber(t) == 1) then for k,v in ipairs(GangAreas[zone].RadarAreas) do setRadarAreaColor(v, 255,0,0,120) end else for k,v in ipairs(GangAreas[zone].RadarAreas) do local r,g,b = GangAreas[zone].Faction:getColors() setRadarAreaColor(v, r,g,b,70) end end end end) ]] --[[ addCommandHandler("enablega", function(pl, cmd) local x,y,z = getElementPosition(pl) local zonename = getZoneName(x,y,z, false) CDatabase:getInstance():query("UPDATE Gangareas SET Useable='1' WHERE Name=?", zonename) end )]] --[[ addCommandHandler("rand", function(pl, cmd) for k,v in pairs(GangAreas) do CDatabase:getInstance():query("UPDATE Gangareas SET FactionID = ? WHERE ID=? ", math.random(3,5), v.ID) end end ) ]] --[[ - ]]
nilq/small-lua-stack
null
Locales['pl'] = { ['actions'] = 'menu', ['boss_menu'] = 'menu zarządzania', ['money_generic'] = '$%s', ['deposit_amount'] = 'ilość wpłaty', ['deposit_society_money'] = 'wpłać pieniądze na konto firmy', ['do_you_want_to_recruit'] = 'czy chcesz zrekrutować %s?', ['employee'] = 'pracownik', ['employee_list'] = 'lista pracowników', ['employee_management'] = 'zarządzanie pracownikami', ['fire'] = 'zwolnij', ['grade'] = 'stopień', ['have_deposited'] = 'wpłacono ~r~$%s~s~ na konto firmy', ['have_withdrawn'] = 'wypłacono ~g~$%s~s~ z konta firmy', ['invalid_amount'] = 'nieprawidłowa wartość', ['invalid_amount_max'] = 'takie wynagrodzenie nie jest dozwolone', ['no'] = 'nie', ['promote'] = 'zmień stopień', ['promote_employee'] = 'zmień %s', ['recruit'] = 'zatrudnianie', ['recruiting'] = 'zatrudnianie', ['salary_amount'] = 'wartość wynagrodzenia', ['salary_management'] = 'zarządzanie wynagrodzeniem', ['wash_money'] = 'wypierz pieniądze', ['wash_money_amount'] = 'ilość do wyprania', ['withdraw_amount'] = 'wartość wypłaty', ['withdraw_society_money'] = 'wypłać pieniadze z konta firmy', ['yes'] = 'tak', ['you_have'] = 'masz ~g~%s$~s~ czekanie ~y~w pralni pieniędzmi~s~ (24h).', ['you_have_laundered'] = '~r~Wyprałeś~s~ twoje pieniądze: ~g~$%s~s~', ['you_have_hired'] = 'zatrudniono %s', ['you_have_been_hired'] = 'zostałeś/aś zatrudniony/a przez %s', ['you_have_fired'] = 'zwolniono %s', ['you_have_been_fired'] = 'zwolniono cie. Jesteś %s', ['you_have_promoted'] = 'zmienono stopień %s na %s', ['you_have_been_promoted'] = 'twój stopień został zmieniony', }
nilq/small-lua-stack
null
local commandHandlers = {} commandHandlers["start"] = function (player, resourceName) if type(resourceName) ~= "string" then outputDebugString("Bad resource name '" .. tostring(resourceName) .. "'") return end if hasObjectPermissionTo(player, "command.start", false) then local resource = getResourceFromName(resourceName) if not resource then outputDebugString("Resource not found '" .. tostring(resourceName) .. "'") return end resource:start() end end commandHandlers["stop"] = function (player, resourceName) if type(resourceName) ~= "string" then return end if hasObjectPermissionTo(player, "command.stop", false) then local resource = getResourceFromName(resourceName) if not resource then return end resource:stop() end end commandHandlers["restart"] = function (player, resourceName) if type(resourceName) ~= "string" then return end if hasObjectPermissionTo(player, "command.restart", false) then local resource = getResourceFromName(resourceName) if not resource then return end resource:restart() end end addEvent("dpChat.command", true) addEventHandler("dpChat.command", root, function(tabName, command, ...) if commandHandlers[command] then commandHandlers[command](client, ...) end end)
nilq/small-lua-stack
null
StaffChat = {} local c = {} -- Config file -- You can add multiple chat rooms with different chat commands and permissions -- Please keep numbers in [] ordered (1, 2, 3...) or it won't work properly -- Example: --[[ c[2] = { cmds = {"/staff", "/staffchat"}, -- List of commands that can be used to write to this chat, separated by commas write = {"superadmin", "admin"}, -- List of usergroups that can write to this chat read = {"superadmin", "admin"}, -- List of usergroups that can read this chat title = "Example Chat" -- Title that will be displayed in chat for messages in this chat } ]]-- c[1] = { cmds = {"/s"}, write = {"superadmin", "admin"}, read = {"superadmin", "admin"}, title = "Staff Chat" } -- Error message: No permission -- Will be displayed when a user attempts to write to a chat they don't have permission to write to -- {title} will be replaces with its name (e.g. "Staff Chat") -- Set to "" to disable. StaffChat.noperm = "You don't have permission to use the {title}!" -- Error message: Empty message -- Will be used when a user attempts to use a command without typing any text (i. e. just "/s") -- Set to "" to disable. StaffChat.emptymsg = "Please enter a message." -- Colors for messages StaffChat.colors = { Color(255, 100, 100), -- 1 - Error messages (e.g. 'no permission') Color(255, 144, 0), -- 2 - Staff chat messages color 1 (room title) Color(255, 55, 0), -- 3 - Staff chat messages color 2 (player nickname) Color(122, 122, 122), -- 4 - Staff chat messages color 3 (player steamid) Color(255, 100, 100), -- 5 - Staff chat messages color 4 (message content) Color(255, 255, 255) -- 6 - Staff chat messages color 4 alternate (message content if sender doesn't have permission to read messages from that chat) } -- End of config file StaffChat.cmds = {} StaffChat.write = {} StaffChat.read = {} StaffChat.titles = {} for i = 1, #c do StaffChat.cmds[i] = {} for cm = 1, #c[i].cmds do StaffChat.cmds[c[i].cmds[cm]] = i end StaffChat.write[i] = {} for w = 1, #c[i].write do StaffChat.write[i][c[i].write[w]] = true end StaffChat.read[i] = {} for r = 1, #c[i].read do StaffChat.read[i][c[i].read[r]] = true end StaffChat.titles[i] = c[i].title end
nilq/small-lua-stack
null
function switchWaterRef( wrOn ) if (wrOn) then enableWaterRef() else disableWaterRef() end end addEvent( "switchWaterRef", true ) addEventHandler( "switchWaterRef", root, switchWaterRef )
nilq/small-lua-stack
null
Inventory = classExtends(Controller, function(user, xsize, ysize, style, align, x, y) self.user = user self.xsize = xsize self.ysize = ysize self.style = style self.align = align self.data = InventoryData.new(user, xsize, ysize) self.window = user:newWindow(style, align, x, y) end)
nilq/small-lua-stack
null
signs_lib.unicode_install({195,128,"00c0"}) signs_lib.unicode_install({195,134,"00c6"}) signs_lib.unicode_install({195,135,"00c7"}) signs_lib.unicode_install({195,136,"00c8"}) signs_lib.unicode_install({195,137,"00c9"}) signs_lib.unicode_install({195,138,"00ca"}) signs_lib.unicode_install({195,148,"00d4"}) signs_lib.unicode_install({195,153,"00d9"}) signs_lib.unicode_install({195,160,"00e0"}) signs_lib.unicode_install({195,166,"00e6"}) signs_lib.unicode_install({195,167,"00e7"}) signs_lib.unicode_install({195,168,"00e8"}) signs_lib.unicode_install({195,169,"00e9"}) signs_lib.unicode_install({195,170,"00ea"}) signs_lib.unicode_install({195,180,"00f4"}) signs_lib.unicode_install({195,185,"00f9"})
nilq/small-lua-stack
null
------------------------------------------------ -- Copyright © 2013-2014 Hugula: Arpg game Engine -- asset -- author pu ------------------------------------------------ local CUtils=CUtils local LuaHelper=LuaHelper local GAMEOBJECT_ATLAS = GAMEOBJECT_ATLAS Asset = class(function(self,url,names) self.base = false self.url = url --CUtils.GetAssetFullPath(url) self.fullUrl=CUtils.GetAssetFullPath(url) -- print(url) self.key = CUtils.GetKeyURLFileName(url) self.names = names if names then local len =#names local name for i=1,len do name=names[i] names[name]=name end end self.items = {} self.root = nil end) function Asset:clear() -- if self.type == SINGLE then print("clear"..self.root.name) if self.root then LuaHelper.Destroy(self.root) end self.root = nil GAMEOBJECT_ATLAS[self.key]=nil self.items={} -- self.names=nil --self.names=nil -- elseif self.items then -- for k,v in pairs(self.items) do -- LuaHelper.Destory(v) -- end -- self.items=nil -- end end function Asset:show(...) if self.names then for k,v in pairs(self.names) do self.items[v]:SetActive(true) end if self.root.activeSelf==false then self.root:SetActive(true) end else if self.root then self.root:SetActive(true) end end end function Asset:hide(...) if self.names then local kill for k,v in pairs(self.names) do kill = self.items[v] if kill then kill:SetActive(false) end end else if self.root then self.root:SetActive(false) end end end -- function Asset:copyTo(asse) if asse.type == nil then asse.type = self.type end asse.key = self.key asse.url = self.url asse.fullUrl = self.fullUrl local names=asse.names if names then asse.items={} for k,v in pairs(names) do local ref=self.items[v] asse.items[v] = ref end else asse.items=self.items end asse.root = self.root return asse end function Asset:__tostring() return string.format("asset.key = %s ,url =%s ", self.key,self.url) end
nilq/small-lua-stack
null
return { legend = { { "SocketFile", "SocketGroup", "SocketPerms" }, { }, { } }, label = _("UnixSock"), category = "output" }
nilq/small-lua-stack
null
-- -- A wrapper for inspect.lua. It discards metatables and supports multiple -- arguments. -- local inspect = require("inspect") local remove_all_metatables = function(item, path) if path[#path] ~= inspect.METATABLE then return item end end function repr(...) local args = table.pack(...) -- Don't touch single userdata results in order to support -- inline images in IPython notebook. if args.n == 1 and type(args[1]) == 'userdata' then return ... end -- run 'inspect' on all parts in case of multiple arguments for i=1,args.n do args[i] = inspect(args[i], {process = remove_all_metatables}) end return table.concat(args, ', ') end return repr
nilq/small-lua-stack
null
local playsession = { {"mewmew", {1005687}}, {"snoetje", {976867}}, {"Akhrem", {1000228}}, {"morcup", {163826}}, {"Dr.MoonShine", {665165}}, {"flooxy", {537698}}, {"Danzou", {270732}}, {"dpoba", {560297}}, {"TiTaN", {191312}}, {"squishp", {3683}} } return playsession
nilq/small-lua-stack
null
function onCreate() makeLuaSprite('theWall','sanctum/wall',-1000,-300) addLuaSprite('theWall',false) setLuaSpriteScrollFactor('theWall',.8,.8) makeLuaSprite('p1','sanctum/painting 1',-200,50) addLuaSprite('p1',false) setLuaSpriteScrollFactor('p1',.8,.8) makeLuaSprite('p2','sanctum/painting 2',700,0) addLuaSprite('p2',false) setLuaSpriteScrollFactor('p2',.8,.8) makeLuaSprite('theFloor','sanctum/floor',-900,500) addLuaSprite('theFloor',false) setLuaSpriteScrollFactor('theFloor',.9,.9) makeLuaSprite('lamp1','sanctum/lamp',-500,80) addLuaSprite('lamp1',false) setLuaSpriteScrollFactor('lamp1',.9,.9) makeLuaSprite('lamp2','sanctum/lamp',1200,80) addLuaSprite('lamp2',false) setLuaSpriteScrollFactor('lamp2',.9,.9) makeLuaSprite('desk','sanctum/desk',0,90) addLuaSprite('desk',false) setLuaSpriteScrollFactor('desk',.9,.9) close(true) end function onBeatHit()--for every beat end function onStepHit()--for every step end function update()-- for every frame end
nilq/small-lua-stack
null
local core = require "sys.core" local testaux = require "testaux" local context = {} local total = 30 local WAIT local function gen_closure(n) local now = core.now() return function (s) assert(context[s] == n) local delta = core.now() - now delta = math.abs(delta - 100 - n) --precise is 50ms testaux.assertle(delta, 100, "timer check delta") total = total - 1 if total == 0 then core.wakeup(WAIT) end end end return function() for i = 1, total do local n = i * 50 local f = gen_closure(n) local s = core.timeout(100 + n, f) context[s] = n end WAIT = core.running() core.wait(WAIT) end
nilq/small-lua-stack
null
vehicles = { --{vehicleID,"VEHICLE NAME",engine,tires,tankpart,fuel,MAXSLOTS} {470,"Patriot",1,4,1,0,1,80,100}, {468,"Sanchez",1,2,1,0,1,80,100}, {433,"Barracks",1,6,1,0,1,80,100}, }
nilq/small-lua-stack
null
ITEM.name = "Płyta pancerza" ITEM.model = Model("models/gibs/metal_gib4.mdl") ITEM.description = "chuj" ITEM.protectionlevel = 2 ITEM.hitgroup = HITGROUP_CHEST
nilq/small-lua-stack
null
-- Challenge class for island value cChallengeValues = {} cChallengeValues.__index = cChallengeValues function cChallengeValues.new() local self = setmetatable({}, cChallengeValues) setmetatable(cChallengeValues, {__index = cChallengeInfo}) self.m_Calculations = {} -- self.m_BlocksCounted = {} return self end function cChallengeValues:CalculateValue(a_PlayerName) self.callback = function(a_World) local foundPlayer = SKYBLOCK:DoWithPlayer(a_PlayerName, function() end) if not(foundPlayer) then -- Player left the skyblock world, abort calculating return end local position = self.m_Calculations[a_PlayerName].position local chunks = self.m_Calculations[a_PlayerName].chunks local points = self.m_Calculations[a_PlayerName].points local counter = 1 while true do local cx = chunks[position + counter][1] * 16 local cz = chunks[position + counter][2] * 16 local blockArea = cBlockArea() blockArea:Read(SKYBLOCK, cx - 15, cx + 15, 0, 255, cz - 15, cz + 15, 3) -- Let's calculate if blockArea:CountNonAirBlocks() > 0 then -- ## Very slow... (35 to 62ms) -- local sw = cStopWatch.new() -- sw:Start() -- local tbCounted = {} -- local maxX, maxY, maxZ = blockArea:GetSize() -- for x = 0, maxX - 1 do -- for y = 0, maxY - 1 do -- for z = 0, maxZ - 1 do -- local id, meta = blockArea:GetRelBlockTypeMeta(x, y, z) -- if id ~= 0 then -- if tbCounted[id] == nil then -- tbCounted[id] = {} -- end -- -- if tbCounted[id][meta] == nil then -- tbCounted[id][meta] = 1 -- else -- tbCounted[id][meta] = tbCounted[id][meta] + 1 -- end -- end -- end -- end -- end -- print("Calc: ", sw:GetElapsedMilliseconds()) -- for id, metaAmount in pairs(tbCounted) do -- for meta, amount in pairs(metaAmount) do -- if BLOCK_VALUES[id] ~= nil then -- if BLOCK_VALUES[id][meta] == nil then -- points = points + (BLOCK_VALUES[id][0] * amount) -- else -- points = points + (BLOCK_VALUES[id][meta] * amount) -- end -- end -- end -- end -- ## Fastest solution: Needs extra code in cuberite (PC: 0 to 3ms, PI: 1 to 3 ms) -- local blocksCounted = blockArea:CountAllNonAirBlocksAndMetas() -- for idMeta, amount in pairs(blocksCounted) do -- local tbIdMeta = StringSplit(idMeta, "-") -- local id = tonumber(tbIdMeta[1]) -- local meta = tonumber(tbIdMeta[2]) -- -- if (BLOCK_VALUES[id] ~= nil) then -- if BLOCK_VALUES[id][meta] == nil then -- points = points + (BLOCK_VALUES[id][0] * amount) -- else -- points = points + (BLOCK_VALUES[id][meta] * amount) -- end -- end -- end -- ## Faster, but still slow (13 to 20 ms) -- local sw = cStopWatch.new() -- sw:Start() for id, metaPoint in pairs(BLOCK_VALUES) do for meta, point in pairs(metaPoint) do local amount = blockArea:CountSpecificBlocks(id, meta) if (amount > 0) and (BLOCK_VALUES[id] ~= nil) then if BLOCK_VALUES[id][meta] == nil then points = points + (BLOCK_VALUES[id][0] * amount) else points = points + (BLOCK_VALUES[id][meta] * amount) end end end end end if (position + counter) == #chunks then local value = round(self.m_Calculations[a_PlayerName].points / 1000) self.m_Calculations[a_PlayerName] = nil if (value >= self.m_Default.required.value) then SKYBLOCK:DoWithPlayer(a_PlayerName, function(a_Player) self:Complete(a_Player) CallHook("OnIslandValueCalculated", a_Player, value) end) return end SKYBLOCK:DoWithPlayer(a_PlayerName, function(a_Player) a_Player:SendMessageInfo(GetLanguage(a_Player):Get("challenges.value.calculated", { ["%1"] = value, ["%2"] = self.m_Default.required.value})) CallHook("OnIslandValueCalculated", a_Player, value) end) return elseif counter == 1 then self.m_Calculations[a_PlayerName].position = position + counter self.m_Calculations[a_PlayerName].points = points SKYBLOCK:ScheduleTask(5, self.callback) return end counter = counter + 1 end end SKYBLOCK:ScheduleTask(5, self.callback) end -- Override function cChallengeValues:IsCompleted(a_Player) local playerInfo = GetPlayerInfo(a_Player) if (self.m_Calculations[a_Player:GetName()] ~= nil) then a_Player:SendMessageInfo(GetLanguage(a_Player):Get("challenges.value.calculatingWait")) return end if (not self:HasRequirements(a_Player)) then return end local posX, posZ = GetIslandPosition(playerInfo.m_IslandNumber) local chunks = GetChunks(posX, posZ, ISLAND_DISTANCE / 2) self.m_Calculations[a_Player:GetName()] = {} self.m_Calculations[a_Player:GetName()].position = 0 self.m_Calculations[a_Player:GetName()].points = 0 self.m_Calculations[a_Player:GetName()].chunks = chunks a_Player:SendMessageInfo(GetLanguage(a_Player):Get("challenges.value.calculatingStarted")) self:CalculateValue(a_Player:GetName()) end -- Override function cChallengeValues:GetChallengeType() return "VALUES" end -- Override function cChallengeValues:InfoText(a_Player) return GetLanguage(a_Player):Get("challenges.info.valueInfo") end -- Override function cChallengeValues:ToString() return "cChallengeValues" end -- Override function cChallengeValues:Load(a_LevelName, a_ChallengeName, a_Json) -- Read basic info from challenge cChallengeInfo.Load(self, a_LevelName, a_ChallengeName, a_Json) self.m_Default.required.value = tonumber(a_Json.required.value) end
nilq/small-lua-stack
null
#!/usr/bin/env lua -- MoonODE space_collide() tests -- Derived from ode/demo/demo_space.cpp local ode = require("moonode") local glmath = require("moonglmath") ode.glmath_compat(true) -- testing procedure: -- create a bunch of random boxes -- test for intersections directly, put results in n^2 array -- get space to report collisions: -- - all correct collisions reported -- - no pair reported more than once -- - no incorrect collisions reported local randomf = ode.randomf local now, since = ode.now, ode.since local stats, dumpdata = glmath.stats, glmath.dumpdata local function printf(...) io.write(string.format(...)) end local N = 20 -- number of boxes to test local seed = 37 local bounds = {} local boxes = {} local data = {} -- data associated with boxes (dGeomSetData) local hits = {} -- number of collisions a box has local good_matrix = {} local function init_test(space) local scale = 0.5 -- set random boxes math.randomseed(seed) for i=1, N do local b = {} b[1] = randomf() b[2] = b[1] + randomf()*scale b[3] = randomf() b[4] = b[3] + randomf()*scale b[5] = 2*randomf() b[6] = b[5] + randomf()*scale local box = ode.create_box(space, b[2]-b[1], b[4]-b[3], b[6]-b[5]) box:set_position({(b[2]+b[1])/2, (b[4]+b[3])/2, (b[6]+b[5])/2}) if boxes[i] then boxes[i]:destroy() end boxes[i] = box bounds[i] = b data[box] = i end -- compute all intersections and put the results in "good_matrix" good_matrix, test_matrix, hits = {}, {}, {} for i = 1, N do hits[i] = 0 good_matrix[i],test_matrix[i] = {}, {} for j = 1, N do good_matrix[i][j] = 0 end end for i= 1, N do for j= i+1, N do local b1 = bounds[i] local b2 = bounds[j] if not (b1[1] > b2[2] or b1[2] < b2[1] or b1[3] > b2[4] or b1[4] < b2[3] or b1[5] > b2[6] or b1[6] < b2[5]) then good_matrix[i][j] = true good_matrix[j][i] = true hits[i] = hits[i] + 1 hits[j] = hits[j] + 1 end end end end local function check_results() for i= 1, N do for j= i+1, N do if good_matrix[i][j] and not test_matrix[i][j] then -- printf("failed to report collision(%d,%d)(seed=%d)\n",i,j,seed) end end end end local function near_callback(o1, o2) local i, j = data[o1], data[o2] -- dGeomGetData if i==j then printf("collision(%d,%d) is between the same object\n", i, j) end if not good_matrix[i][j] or not good_matrix[j][i] then printf("collision(%d,%d) is incorrect\n", i, j) end if test_matrix[i][j] or test_matrix[j][i] then printf("collision(%d,%d) reported more than once\n", i, j) end test_matrix[i][j] = true test_matrix[j][i] = true end local space if not arg[1] or arg[1] == '-simple' then space = ode.create_simple_space() elseif arg[1] == '-hash' then space = ode.create_hash_space() space:set_levels(-10, 10) elseif arg[1] == '-quadtree' then space = ode.create_quadtree_space(nil, {0, 0, 0}, {10, 0, 10}, 7) elseif arg[1] == '-sap' then space = ode.create_sap_space(nil, 'xzy') else error("invalid option '"..arg[1].."'") end ode.set_near_callback(near_callback) local NTESTS = 10000 local tmeas = {} collectgarbage() collectgarbage('stop') for i = 1, NTESTS do init_test(space) local t = now() ode.space_collide(space) t = since(t) tmeas[i] = t*1e6 -- printf("space_collide() executed in about %.3f ms\n", t*1e3) check_results() seed = seed + 1 -- draw ... if i%100==0 then printf("space_collide() calls: %d\n", i) collectgarbage() end end -- compute stats and dump measurements to file local tmean, tvar, tmin, tmax = stats(tmeas) printf("space_collide() execution time: mean=%.0f, var=%.0f, min=%.0f, max=%.0f [us]\n", tmean, tvar, tmin, tmax) dumpdata(tmeas, 'data.log') -- gnuplot> plot "data.log" using 1:2 with lines
nilq/small-lua-stack
null
local tBotNameList = { --"npc_dota_hero_abaddon",// 不会放技能,只会物品和A人 --"npc_dota_hero_antimage",// 不会放技能,只会物品和A人 --"npc_dota_hero_spirit_breaker",// 不会放技能,只会物品和A人 --"npc_dota_hero_silencer",// 不会放技能,只会物品和A人 "npc_dota_hero_axe", "npc_dota_hero_bane", "npc_dota_hero_bounty_hunter", "npc_dota_hero_bloodseeker", "npc_dota_hero_bristleback", "npc_dota_hero_chaos_knight", "npc_dota_hero_crystal_maiden", "npc_dota_hero_dazzle", "npc_dota_hero_death_prophet", "npc_dota_hero_dragon_knight", "npc_dota_hero_drow_ranger", "npc_dota_hero_earthshaker", "npc_dota_hero_jakiro", "npc_dota_hero_juggernaut", "npc_dota_hero_kunkka", "npc_dota_hero_lich", "npc_dota_hero_lina", "npc_dota_hero_lion", "npc_dota_hero_luna", -- "npc_dota_hero_mirana", // 不会放技能,只会物品和A人 "npc_dota_hero_nevermore", "npc_dota_hero_necrolyte", -- "npc_dota_hero_ogre_magi", // 不会放技能,只会物品和A人 "npc_dota_hero_omniknight", "npc_dota_hero_oracle", "npc_dota_hero_phantom_assassin", "npc_dota_hero_pudge", "npc_dota_hero_riki", -- "npc_dota_hero_razor", // 在泉水站着完全不动 -- "npc_dota_hero_shadow_shaman", // 不会放技能,只会物品和A人 "npc_dota_hero_sand_king", "npc_dota_hero_skywrath_mage", "npc_dota_hero_sniper", "npc_dota_hero_sven", -- "npc_dota_hero_tidehunter", // 在泉水站着完全不动 "npc_dota_hero_tiny", "npc_dota_hero_vengefulspirit", "npc_dota_hero_viper", "npc_dota_hero_warlock", "npc_dota_hero_windrunner", "npc_dota_hero_witch_doctor", "npc_dota_hero_skeleton_king", "npc_dota_hero_zuus", } local tSkillCustomNameList = { "npc_dota_hero_crystal_maiden", "npc_dota_hero_queenofpain", "npc_dota_hero_mirana", "npc_dota_hero_earthshaker", "npc_dota_hero_nevermore", } local tAPLevelList = { 17, 19, 21, 22, 23, 24, 26, } function AIGameMode:ArrayShuffle(array) local size = #array for i = size, 1, -1 do local rand = math.random(size) array[i], array[rand] = array[rand], array[i] end return array end function AIGameMode:GetFreeHeroName() for i,v in ipairs(tBotNameList) do if PlayerResource:WhoSelectedHero(v, false) < 0 then return v end end return "npc_dota_hero_luna" -- Should never get here end function AIGameMode:InitHumanPlayerListAndSetHumanStartGold() if self.PreGameOptionsSet then print("[AIGameMode] InitSettings") self.tHumanPlayerList = {} for i=0, (DOTA_MAX_TEAM_PLAYERS - 1) do if PlayerResource:IsValidPlayer(i) then -- set human player list self.tHumanPlayerList[i] = true -- set start gold PlayerResource:SetGold(i, (self.iStartingGoldPlayer-600),true) end end else Timers:CreateTimer(0.5, function () print("[AIGameMode] Try InitSettings in 0.5s") AIGameMode:InitHumanPlayerListAndSetHumanStartGold() end) end end function AIGameMode:OnGameStateChanged(keys) local state = GameRules:State_Get() if state == DOTA_GAMERULES_STATE_HERO_SELECTION then if IsServer() == true then self:InitHumanPlayerListAndSetHumanStartGold() end elseif state == DOTA_GAMERULES_STATE_STRATEGY_TIME then if not self.PreGameOptionsSet then print("[AIGameMode] Setting pre-game options STRATEGY_TIME") self:PreGameOptions() end for i=0, (DOTA_MAX_TEAM_PLAYERS - 1) do if PlayerResource:IsValidPlayer(i) then if PlayerResource:GetPlayer(i) and not PlayerResource:HasSelectedHero(i) then PlayerResource:GetPlayer(i):MakeRandomHeroSelection() end end end -- Eanble bots and fill empty slots if IsServer() == true then local iPlayerNumRadiant = PlayerResource:GetPlayerCountForTeam(DOTA_TEAM_GOODGUYS) local iPlayerNumDire = PlayerResource:GetPlayerCountForTeam(DOTA_TEAM_BADGUYS) math.randomseed(math.floor(Time()*1000000)) -- 随机英雄列表 if not self.DebugMode then print("[AIGameMode] Random hero list") self:ArrayShuffle(tBotNameList) end local sDifficulty = "unfair" if self.iDesiredRadiant > iPlayerNumRadiant then for i = 1, self.iDesiredRadiant - iPlayerNumRadiant do Tutorial:AddBot(self:GetFreeHeroName(), "", sDifficulty, true) end end if self.iDesiredDire > iPlayerNumDire then for i = 1, self.iDesiredDire - iPlayerNumDire do Tutorial:AddBot(self:GetFreeHeroName(), "", sDifficulty, false) end end GameRules:GetGameModeEntity():SetBotThinkingEnabled(true) Tutorial:StartTutorialMode() -- set bot start gold for i=0, (DOTA_MAX_TEAM_PLAYERS - 1) do if PlayerResource:IsValidPlayer(i) then if not self.tHumanPlayerList[i] then PlayerResource:SetGold(i, (self.iStartingGoldBot-600),true) end end end end Timers:CreateTimer(1, function () self:EndScreenStats(true, false) end) elseif state == DOTA_GAMERULES_STATE_PRE_GAME then -- modifier towers local tTowers = Entities:FindAllByClassname("npc_dota_tower") for k, v in pairs(tTowers) do if v:GetTeamNumber() == DOTA_TEAM_GOODGUYS then v:AddNewModifier(v, nil, "modifier_tower_power", {}):SetStackCount(self.iRadiantTowerPower) v:AddNewModifier(v, nil, "modifier_tower_endure", {}):SetStackCount(self.iRadiantTowerEndure) v:AddNewModifier(v, nil, "modifier_tower_heal", {}):SetStackCount(self.iRadiantTowerHeal) elseif v:GetTeamNumber() == DOTA_TEAM_BADGUYS then v:AddNewModifier(v, nil, "modifier_tower_power", {}):SetStackCount(self.iDireTowerPower) v:AddNewModifier(v, nil, "modifier_tower_endure", {}):SetStackCount(self.iDireTowerEndure) v:AddNewModifier(v, nil, "modifier_tower_heal", {}):SetStackCount(self.iDireTowerHeal) end -- set tower split local towerName = v:GetName() if string.find(towerName, "tower4") then local towerSplitShot = v:AddAbility("tower_split_shot") if towerSplitShot then towerSplitShot:SetLevel(1) towerSplitShot:ToggleAbility() end end end local barracks = Entities:FindAllByClassname("npc_dota_barracks") for k, v in pairs(barracks) do if v:GetTeamNumber() == DOTA_TEAM_GOODGUYS then v:AddNewModifier(v, nil, "modifier_tower_endure", {}):SetStackCount(self.iRadiantTowerEndure) v:AddNewModifier(v, nil, "modifier_tower_heal", {}):SetStackCount(self.iRadiantTowerHeal) elseif v:GetTeamNumber() == DOTA_TEAM_BADGUYS then v:AddNewModifier(v, nil, "modifier_tower_endure", {}):SetStackCount(self.iDireTowerEndure) v:AddNewModifier(v, nil, "modifier_tower_heal", {}):SetStackCount(self.iDireTowerHeal) end end local healer = Entities:FindAllByClassname("npc_dota_healer") for k, v in pairs(healer) do if v:GetTeamNumber() == DOTA_TEAM_GOODGUYS then v:AddNewModifier(v, nil, "modifier_tower_endure", {}):SetStackCount(self.iRadiantTowerEndure) v:AddNewModifier(v, nil, "modifier_tower_heal", {}):SetStackCount(self.iRadiantTowerHeal) elseif v:GetTeamNumber() == DOTA_TEAM_BADGUYS then v:AddNewModifier(v, nil, "modifier_tower_endure", {}):SetStackCount(self.iDireTowerEndure) v:AddNewModifier(v, nil, "modifier_tower_heal", {}):SetStackCount(self.iDireTowerHeal) end end local fort = Entities:FindAllByClassname("npc_dota_fort") for k, v in pairs(fort) do if v:GetTeamNumber() == DOTA_TEAM_GOODGUYS then v:AddNewModifier(v, nil, "modifier_tower_power", {}):SetStackCount(self.iRadiantTowerPower) v:AddNewModifier(v, nil, "modifier_tower_endure", {}):SetStackCount(self.iRadiantTowerEndure) v:AddNewModifier(v, nil, "modifier_tower_heal", {}):SetStackCount(self.iRadiantTowerHeal) v:AddNewModifier(v, nil, "modifier_multi", {}):SetStackCount(math.floor(self.fPlayerGoldXpMultiplier*10)) elseif v:GetTeamNumber() == DOTA_TEAM_BADGUYS then v:AddNewModifier(v, nil, "modifier_tower_power", {}):SetStackCount(self.iDireTowerPower) v:AddNewModifier(v, nil, "modifier_tower_endure", {}):SetStackCount(self.iDireTowerEndure) v:AddNewModifier(v, nil, "modifier_multi", {}):SetStackCount(self.iDireTowerHeal) v:AddNewModifier(v, nil, "modifier_multi", {}):SetStackCount(math.floor(self.fBotGoldXpMultiplier*10)) end -- set fort split local towerSplitShot = v:AddAbility("tower_split_shot") if towerSplitShot then towerSplitShot:SetLevel(2) towerSplitShot:ToggleAbility() end end Timers:CreateTimer(1, function () AIGameMode:RefreshGameStatus10sec() end) elseif state == DOTA_GAMERULES_STATE_GAME_IN_PROGRESS then self.fGameStartTime = GameRules:GetGameTime() GameRules:SpawnNeutralCreeps() -- start loop in 30 seconds if IsClient() then return end Timers:CreateTimer(30, function () AIGameMode:SpawnNeutralCreeps30sec() end) elseif state == DOTA_GAMERULES_STATE_POST_GAME then self:EndScreenStats(true, true) end end function AIGameMode:SpawnNeutralCreeps30sec() local GameTime = GameRules:GetDOTATime(false, false) print("SpawnNeutral at GetDOTATime " .. GameTime) GameRules:SpawnNeutralCreeps() -- callback every minute Timers:CreateTimer(60, function () AIGameMode:SpawnNeutralCreeps30sec() end) end function AIGameMode:RefreshGameStatus10sec() -- save player info self:EndScreenStats(true, false) -- set global state local GameTime = GameRules:GetDOTATime(false, false) if (GameTime >= ((AIGameMode.botPushMin * 4) * 60)) then -- LATEGAME GameRules:GetGameModeEntity():SetBotsMaxPushTier(-1) elseif (GameTime >= ((AIGameMode.botPushMin + 4) * 60)) then -- MIDGAME if AIGameMode.tower3PushedGood >= 2 or AIGameMode.tower3PushedBad >= 2 then GameRules:GetGameModeEntity():SetBotsMaxPushTier(4) end if AIGameMode.barrackPushedGood > 5 or AIGameMode.barrackPushedBad > 5 then GameRules:GetGameModeEntity():SetBotsMaxPushTier(-1) elseif AIGameMode.barrackPushedGood > 2 or AIGameMode.barrackPushedBad > 2 then GameRules:GetGameModeEntity():SetBotsMaxPushTier(5) end elseif (GameTime >= (AIGameMode.botPushMin * 60)) then -- MIDGAME GameRules:GetGameModeEntity():SetBotsInLateGame(true) GameRules:GetGameModeEntity():SetBotsAlwaysPushWithHuman(true) GameRules:GetGameModeEntity():SetBotsMaxPushTier(3) else -- EARLYGAME GameRules:GetGameModeEntity():SetBotsInLateGame(false) GameRules:GetGameModeEntity():SetBotsAlwaysPushWithHuman(false) GameRules:GetGameModeEntity():SetBotsMaxPushTier(1) end -- set creep buff level local buffLevelGood = 0 local buffLevelBad = 0 local buffLevelMegaGood = 0 local buffLevelMegaBad = 0 if AIGameMode.tower1PushedGood > 0 then buffLevelGood = buffLevelGood + 1 end if AIGameMode.tower1PushedBad > 0 then buffLevelBad = buffLevelBad + 1 end if AIGameMode.tower2PushedGood > 0 then buffLevelGood = buffLevelGood + 1 end if AIGameMode.tower2PushedBad > 0 then buffLevelBad = buffLevelBad + 1 end if AIGameMode.tower3PushedGood > 0 then buffLevelGood = buffLevelGood + 1 end if AIGameMode.tower3PushedBad > 0 then buffLevelBad = buffLevelBad + 1 end if AIGameMode.tower4PushedGood > 1 then buffLevelGood = buffLevelGood + 1 buffLevelMegaGood = buffLevelMegaGood + 1 end if AIGameMode.tower4PushedBad > 1 then buffLevelBad = buffLevelBad + 1 buffLevelMegaBad = buffLevelMegaBad + 1 end buffLevelMegaGood = buffLevelMegaGood + AIGameMode.creepBuffLevel buffLevelMegaBad = buffLevelMegaBad + AIGameMode.creepBuffLevel if (GameTime >= (15 * 60)) then buffLevelGood = buffLevelGood + 1 buffLevelBad = buffLevelBad + 1 buffLevelMegaGood = buffLevelMegaGood + 1 buffLevelMegaBad = buffLevelMegaBad + 1 end if (GameTime >= (30 * 60)) then buffLevelGood = buffLevelGood + 1 buffLevelBad = buffLevelBad + 1 buffLevelMegaGood = buffLevelMegaGood + 1 buffLevelMegaBad = buffLevelMegaBad + 1 end if (GameTime >= (45 * 60)) then buffLevelGood = buffLevelGood + 1 buffLevelBad = buffLevelBad + 1 buffLevelMegaGood = buffLevelMegaGood + 1 buffLevelMegaBad = buffLevelMegaBad + 1 end if (GameTime >= (60 * 60)) then buffLevelGood = buffLevelGood + 1 buffLevelBad = buffLevelBad + 1 buffLevelMegaGood = buffLevelMegaGood + 1 buffLevelMegaBad = buffLevelMegaBad + 1 end buffLevelGood = math.min(buffLevelGood, 8) buffLevelBad = math.min(buffLevelBad, 8) buffLevelMegaGood = math.min(buffLevelMegaGood, 8) buffLevelMegaBad = math.min(buffLevelMegaBad, 8) AIGameMode.creepBuffLevelGood = buffLevelGood AIGameMode.creepBuffLevelBad = buffLevelBad AIGameMode.creepBuffLevelMegaGood = buffLevelMegaGood AIGameMode.creepBuffLevelMegaBad = buffLevelMegaBad print("creep buff level good " .. buffLevelGood) print("creep buff level bad " .. buffLevelBad) print("creep buff level mega good " .. buffLevelMegaGood) print("creep buff level mega bad " .. buffLevelMegaBad) -- callback every 10 seconds Timers:CreateTimer(10, function () AIGameMode:RefreshGameStatus10sec() end) end function AIGameMode:OnEntityKilled(keys) local hEntity = EntIndexToHScript(keys.entindex_killed) -- on hero killed if hEntity:IsRealHero() and hEntity:IsReincarnating() == false then HeroKilled(keys) -- drop items only when killed by hero if EntIndexToHScript(keys.entindex_attacker):GetPlayerOwner() then AIGameMode:RollDrops(EntIndexToHScript(keys.entindex_killed)) end end -- on barrack killed if hEntity:GetClassname() == "npc_dota_barracks" then RecordBarrackKilled(hEntity) end -- on tower killed if hEntity:GetClassname() == "npc_dota_tower" then RecordTowerKilled(hEntity) end end function RecordBarrackKilled(hEntity) local team = hEntity:GetTeamNumber() if DOTA_TEAM_GOODGUYS == team then AIGameMode.barrackPushedBad = AIGameMode.barrackPushedBad + 1 print("barrackPushedBad ", AIGameMode.barrackPushedBad) elseif DOTA_TEAM_BADGUYS == team then AIGameMode.barrackPushedGood = AIGameMode.barrackPushedGood + 1 print("barrackPushedGood ", AIGameMode.barrackPushedGood) end end function RecordTowerKilled(hEntity) local team = hEntity:GetTeamNumber() local sName = hEntity:GetUnitName() if string.find(sName, "tower1") then if DOTA_TEAM_GOODGUYS == team then AIGameMode.tower1PushedBad = AIGameMode.tower1PushedBad + 1 print("tower1PushedBad ", AIGameMode.tower1PushedBad) elseif DOTA_TEAM_BADGUYS == team then AIGameMode.tower1PushedGood = AIGameMode.tower1PushedGood + 1 print("tower1PushedGood ", AIGameMode.tower1PushedGood) end elseif string.find(sName, "tower2") then if DOTA_TEAM_GOODGUYS == team then AIGameMode.tower2PushedBad = AIGameMode.tower2PushedBad + 1 print("tower2PushedBad ", AIGameMode.tower2PushedBad) elseif DOTA_TEAM_BADGUYS == team then AIGameMode.tower2PushedGood = AIGameMode.tower2PushedGood + 1 print("tower2PushedGood ", AIGameMode.tower2PushedGood) end elseif string.find(sName, "tower3") then if DOTA_TEAM_GOODGUYS == team then AIGameMode.tower3PushedBad = AIGameMode.tower3PushedBad + 1 print("tower3PushedBad ", AIGameMode.tower3PushedBad) elseif DOTA_TEAM_BADGUYS == team then AIGameMode.tower3PushedGood = AIGameMode.tower3PushedGood + 1 print("tower3PushedGood ", AIGameMode.tower3PushedGood) end elseif string.find(sName, "tower4") then if DOTA_TEAM_GOODGUYS == team then AIGameMode.tower4PushedBad = AIGameMode.tower4PushedBad + 1 print("tower4PushedBad ", AIGameMode.tower4PushedBad) elseif DOTA_TEAM_BADGUYS == team then AIGameMode.tower4PushedGood = AIGameMode.tower4PushedGood + 1 print("tower4PushedGood ", AIGameMode.tower4PushedGood) end end end function HeroKilled(keys) local hHero = EntIndexToHScript(keys.entindex_killed) local fRespawnTime = 0 local iLevel = hHero:GetLevel() local tDOTARespawnTime = {4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 60} if iLevel <= 40 then fRespawnTime = math.ceil(tDOTARespawnTime[iLevel]*AIGameMode.iRespawnTimePercentage/100.0) else fRespawnTime = math.ceil((iLevel/4 + 50)*AIGameMode.iRespawnTimePercentage/100.0) end if hHero:FindModifierByName('modifier_necrolyte_reapers_scythe') then fRespawnTime = fRespawnTime+hHero:FindModifierByName('modifier_necrolyte_reapers_scythe'):GetAbility():GetLevel()*10 end -- 复活时间至少1s if fRespawnTime < 1 then fRespawnTime = 1 end hHero:SetTimeUntilRespawn(fRespawnTime) end function AIGameMode:RollDrops(hHero) if GameRules.DropTable then for item_name,chance in pairs(GameRules.DropTable) do for i = 0, 8 do local hItem = hHero:GetItemInSlot(i) if hItem then local hItem_name = hItem:GetName() if item_name == hItem_name then if RollPercentage(chance) then -- Remove the item hHero:RemoveItem(hItem) -- Create the item AIGameMode:CreateItem(item_name, hHero) end end end end end end end function AIGameMode:CreateItem(sItemName, hEntity) local item = CreateItem(sItemName, nil, nil) if AIGameMode.DebugMode then item:SetPurchaseTime(-100) end local pos = hEntity:GetAbsOrigin() local drop = CreateItemOnPositionSync( pos, item ) local pos_launch = pos+RandomVector(RandomFloat(150,200)) item:LaunchLoot(false, 200, 0.75, pos_launch) end function AIGameMode:OnNPCSpawned(keys) if GameRules:State_Get() < DOTA_GAMERULES_STATE_PRE_GAME then Timers:CreateTimer(1, function () AIGameMode:OnNPCSpawned(keys) end) return end local hEntity = EntIndexToHScript(keys.entindex) if hEntity:IsNull() then return end if hEntity:IsCourier() and self.bFastCourier == 1 then hEntity:AddNewModifier(hEntity, nil, "modifier_courier_speed", {}) return end local sName = hEntity:GetName() if sName == "npc_dota_creep_lane" or sName == "npc_dota_creep_siege" then local sUnitName = hEntity:GetUnitName() local team = hEntity:GetTeamNumber() local buffLevel = 0 local buffLevelMega = 0 if DOTA_TEAM_GOODGUYS == team then buffLevel = AIGameMode.creepBuffLevelGood buffLevelMega = AIGameMode.creepBuffLevelMegaGood elseif DOTA_TEAM_BADGUYS == team then buffLevel = AIGameMode.creepBuffLevelBad buffLevelMega = AIGameMode.creepBuffLevelMegaBad end if buffLevel > 0 then if not string.find(sUnitName, "upgraded") and not string.find(sUnitName, "mega") then -- normal creep local ability = hEntity:AddAbility("creep_buff") ability:SetLevel(buffLevel) return end end if buffLevelMega > 0 then if string.find(sUnitName, "upgraded") and not string.find(sUnitName, "mega") then -- upgrade creep local ability = hEntity:AddAbility("creep_buff_upgraded") ability:SetLevel(buffLevel) return elseif string.find(sUnitName, "mega") then -- mega creep local ability = hEntity:AddAbility("creep_buff_mega") ability:SetLevel(buffLevel) return end end end if hEntity:IsCreep() then if sName == "npc_dota_roshan" then local ability_roshan_buff = hEntity:FindAbilityByName("roshan_buff") ability_roshan_buff:SetLevel(self.roshanNumber) local ability_gold_bag = hEntity:FindAbilityByName("generic_gold_bag_fountain") ability_gold_bag:SetLevel(self.roshanNumber) self.roshanNumber = self.roshanNumber + 1 if self.roshanNumber > 4 then self.roshanNumber = 4 end return end end if sName == "npc_dota_lone_druid_bear" then hEntity:AddNewModifier(hEntity, nil, "modifier_melee_resistance", {}) end if hEntity:IsRealHero() and not hEntity.bInitialized then if hEntity:GetAttackCapability() == DOTA_UNIT_CAP_MELEE_ATTACK or sName == "npc_dota_hero_troll_warlord" or sName == "npc_dota_hero_lone_druid" then hEntity:AddNewModifier(hEntity, nil, "modifier_melee_resistance", {}) end if sName == "npc_dota_hero_sniper" and not self.bSniperScepterThinkerApplierSet then require('heroes/hero_sniper/sniper_init') SniperInit(hEntity, self) end if not self.tHumanPlayerList[hEntity:GetPlayerOwnerID()] then if not hEntity:FindModifierByName("modifier_bot_think_strategy") then hEntity:AddNewModifier(hEntity, nil, "modifier_bot_think_strategy", {}) print("modifier_bot_think_strategy added "..sName) end if not hEntity:FindModifierByName("modifier_bot_think_item_use") then hEntity:AddNewModifier(hEntity, nil, "modifier_bot_think_item_use", {}) end hEntity:SetControllableByPlayer(-1, true) end hEntity.bInitialized = true end end function AIGameMode:OnPlayerLevelUp(keys) local iEntIndex=PlayerResource:GetPlayer(keys.player-1):GetAssignedHero():entindex() local iLevel=keys.level -- Set DeathXP 击杀经验 Timers:CreateTimer(0.5, function () local hEntity = EntIndexToHScript(iEntIndex) if hEntity:IsNull() then return end if iLevel <= 30 then hEntity:SetCustomDeathXP(40 + hEntity:GetCurrentXP()*0.09) else hEntity:SetCustomDeathXP(3500 + hEntity:GetCurrentXP()*0.03) end end) -- Set Ability Points local hero = EntIndexToHScript(keys.player):GetAssignedHero() local level = keys.level for i,v in ipairs(tSkillCustomNameList) do if v == hero:GetName() then for _,lv in ipairs(tAPLevelList) do if lv == level then print("-----------------debug-----------------", hero:GetName().."level:"..level.." Add AP") -- Save current unspend AP local unspendAP = hero:GetAbilityPoints() hero:SetAbilityPoints(1 + unspendAP) break end end break end end end function AIGameMode:OnItemPickedUp( event ) -- if not courier if not event.HeroEntityIndex then return end local item = EntIndexToHScript( event.ItemEntityIndex ) local hHero = EntIndexToHScript( event.HeroEntityIndex ) if event.PlayerID ~= nil and item ~= nil and hHero ~= nil and item:GetAbilityName() == "item_bag_of_gold" then local iGold = item:GetSpecialValueFor("bonus_gold") hHero:ModifyGoldFiltered(iGold, true, DOTA_ModifyGold_RoshanKill) SendOverheadEventMessage(hHero, OVERHEAD_ALERT_GOLD, hHero, iGold, nil) end end function AIGameMode:OnGetLoadingSetOptions(eventSourceIndex, args) if tonumber(args.host_privilege) ~= 1 then return end self.iDesiredRadiant = tonumber(args.game_options.radiant_player_number) self.iDesiredDire = tonumber(args.game_options.dire_player_number) self.fPlayerGoldXpMultiplier = tonumber(args.game_options.player_gold_xp_multiplier) self.fBotGoldXpMultiplier = tonumber(args.game_options.bot_gold_xp_multiplier) self.iRespawnTimePercentage = tonumber(args.game_options.respawn_time_percentage) self.iMaxLevel = tonumber(args.game_options.max_level) self.iRadiantTowerPower = tonumber(args.game_options.radiant_tower_power) self.iDireTowerPower = tonumber(args.game_options.dire_tower_power) self.iRadiantTowerEndure = tonumber(args.game_options.radiant_tower_power) self.iDireTowerEndure = tonumber(args.game_options.dire_tower_power) self.iRadiantTowerHeal = tonumber(args.game_options.radiant_tower_heal) self.iDireTowerHeal = tonumber(args.game_options.dire_tower_heal) self.iStartingGoldPlayer = tonumber(args.game_options.starting_gold_player) self.iStartingGoldBot = tonumber(args.game_options.starting_gold_bot) self.bSameHeroSelection = args.game_options.same_hero_selection self.bFastCourier = args.game_options.fast_courier if args.game_options.radiant_bot_same_multi == 1 or args.game_options.radiant_bot_same_multi == "1" then self.bRadiantBotSameMulti = true else self.bRadiantBotSameMulti = false end self:PreGameOptions() end function AIGameMode:OnGameOptionChange(keys) local optionName = keys.optionName local optionValue = keys.optionValue -- 对应的游戏选择项目设定 GameRules.GameOption[optionName]=optionValue CustomNetTables:SetTableValue('game_options_table', 'game_option', GameRules.GameOption) end -- 测试密码 local developerSteamAccountID = {} developerSteamAccountID[136407523]="windy" developerSteamAccountID[1194383041]="咸鱼" developerSteamAccountID[143575444]="茶神" developerSteamAccountID[314757913]="孤尘" developerSteamAccountID[916506173]="Arararara" -- 会员 local memberSteamAccountID = Set { -- 开发贡献者 136407523,1194383041,143575444,314757913, -- 初始会员 136668998, 128984820, 108208968, -- 测试 -- 916506173, } -- saber local saberSteamAccountID = Set { -- windy 136407523, -- 洛书 136668998, -- 测试 916506173, } function AIGameMode:OnPlayerChat( event ) local iPlayerID = event.playerid local sChatMsg = event.text if not iPlayerID or not sChatMsg then return end local steamAccountID = PlayerResource:GetSteamAccountID(iPlayerID) if developerSteamAccountID[steamAccountID] then if sChatMsg:find( '^-greedisgood$' ) then -- give money to the player -- get hero local hHero = PlayerResource:GetSelectedHeroEntity(iPlayerID) local iGold = 10000 hHero:ModifyGold(iGold, true, DOTA_ModifyGold_Unspecified) GameRules:SendCustomMessage( "号外号外!开发者:"..developerSteamAccountID[steamAccountID].." 用自己的菊花交换了增加10000金币", DOTA_TEAM_GOODGUYS, 0 ) return end end if saberSteamAccountID[steamAccountID] then if sChatMsg:find( '^圣剑.*解放.*$' ) then local hHero = PlayerResource:GetSelectedHeroEntity(iPlayerID) local pszHeroClass = "npc_dota_hero_broodmother" PlayerResource:ReplaceHeroWith(iPlayerID, pszHeroClass, hHero:GetGold(), hHero:GetCurrentXP()) saberSteamAccountID[steamAccountID] = false return end end end function AIGameMode:EndScreenStats(isWinner, bTrueEnd) local time = GameRules:GetDOTATime(false, true) --local matchID = tostring(GameRules:GetMatchID()) local data = { version = "1.18", --matchID = matchID, mapName = GetMapName(), players = {}, options = {}, isWinner = isWinner, duration = math.floor(time), flags = {} } data.options = { playerGoldXpMultiplier = self.fPlayerGoldXpMultiplier, botGoldXpMultiplier = self.fBotGoldXpMultiplier, radiantTowerPower = AIGameMode:StackToPercentage(self.iRadiantTowerPower), direTowerPower = AIGameMode:StackToPercentage(self.iDireTowerPower), } for playerID = 0, DOTA_MAX_TEAM_PLAYERS - 1 do if PlayerResource:IsValidPlayerID(playerID) and PlayerResource:IsValidPlayer(playerID) and PlayerResource:GetSelectedHeroEntity(playerID) then local hero = PlayerResource:GetSelectedHeroEntity(playerID) if hero and IsValidEntity(hero) and not hero:IsNull() then -- local tip_points = WebServer.TipCounter[playerID] or 0 local steamAccountID = PlayerResource:GetSteamAccountID(playerID) local membership = memberSteamAccountID[steamAccountID] and true or false local damage = PlayerResource:GetRawPlayerDamage(playerID) local damagereceived = 0 for victimID = 0, DOTA_MAX_TEAM_PLAYERS - 1 do if PlayerResource:IsValidPlayerID(victimID) and PlayerResource:IsValidPlayer(victimID) and PlayerResource:GetSelectedHeroEntity(victimID) then if PlayerResource:GetTeam(victimID) ~= PlayerResource:GetTeam(playerID) then damagereceived = damagereceived + PlayerResource:GetDamageDoneToHero(victimID, playerID) end end end local playerInfo = { steamid = tostring(PlayerResource:GetSteamID(playerID)), steamAccountID = steamAccountID, membership = membership, kills = PlayerResource:GetKills(playerID) or 0, deaths = PlayerResource:GetDeaths(playerID) or 0, assists = PlayerResource:GetAssists(playerID) or 0, damage = damage or 0, damagereceived = damagereceived or 0, heroName = hero:GetUnitName() or "Haachama", lasthits = PlayerResource:GetLastHits(playerID) or 0, heroHealing = PlayerResource:GetHealing(playerID) or 0, str = hero:GetStrength() or 0, agi = hero:GetAgility() or 0, int = hero:GetIntellect() or 0, items = {}, } for item_slot = DOTA_ITEM_SLOT_1, DOTA_STASH_SLOT_6 do local item = hero:GetItemInSlot(item_slot) if item then playerInfo.items[item_slot] = item:GetAbilityName() end end local hNeutralItem = hero:GetItemInSlot(DOTA_ITEM_NEUTRAL_SLOT) if hNeutralItem then playerInfo.items[DOTA_ITEM_NEUTRAL_SLOT] = hNeutralItem:GetAbilityName() end data.players[playerID] = playerInfo end end end local sTable = "ending_stats" CustomNetTables:SetTableValue(sTable, "player_data", data) end function AIGameMode:StackToPercentage(iStackCount) if iStackCount == 1 then return "50%" elseif iStackCount == 2 then return "75%" elseif iStackCount == 3 then return "100%" elseif iStackCount == 4 then return "125%" elseif iStackCount == 5 then return "150%" elseif iStackCount == 6 then return "175%" elseif iStackCount == 7 then return "200%" elseif iStackCount == 8 then return "250%" elseif iStackCount == 9 then return "300%" elseif iStackCount == 10 then return "500%" else return "100%" end end
nilq/small-lua-stack
null
---@class LuaInterface.InjectType : System.Enum ---@field value__ int ---@field None LuaInterface.InjectType ---@field After LuaInterface.InjectType ---@field Before LuaInterface.InjectType ---@field Replace LuaInterface.InjectType ---@field ReplaceWithPreInvokeBase LuaInterface.InjectType ---@field ReplaceWithPostInvokeBase LuaInterface.InjectType local m = {} LuaInterface = {} LuaInterface.InjectType = m return m
nilq/small-lua-stack
null
local event = require 'utils.event' local coin_yield = { ["rock-big"] = 3, ["rock-huge"] = 6, ["sand-rock-big"] = 3 } local function on_player_mined_entity(event) if coin_yield[event.entity.name] then event.entity.surface.spill_item_stack(event.entity.position,{name = "coin", count = math.random(math.ceil(coin_yield[event.entity.name] * 0.5), math.ceil(coin_yield[event.entity.name] * 2))}, true) end end event.add(defines.events.on_player_mined_entity, on_player_mined_entity)
nilq/small-lua-stack
null
-- -- cmake vim.g['cmake_link_compile_commands'] = 1 -- vim.g['cmake_generate_options'] = {'-GNinja', '-DCMAKE_TOOLCHAIN_FILE=../cmake/toolchain.cmake'} vim.g['cmake_generate_options'] = {'-GNinja'} vim.g['cmake_root_markers'] = {'.'}
nilq/small-lua-stack
null
--[[ Copyright (c) 2016 Calvin Rose Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]] --- The main application object. -- @module moonmint.server local uv = require 'luv' local httpCodec = require 'moonmint.deps.httpCodec' local router = require 'moonmint.router' local httpHeaders = require 'moonmint.deps.http-headers' local getHeaders = httpHeaders.getHeaders local coroWrap = require 'moonmint.deps.coro-wrapper' local wrapStream = require 'moonmint.deps.stream-wrap' local setmetatable = setmetatable local type = type local match = string.match local tostring = tostring local assert = assert local xpcall = xpcall local wrap = coroutine.wrap local Server = {} local Server_mt = { __index = Server } local function makeServer() return setmetatable({ bindings = {}, netServers = {}, _router = router() }, Server_mt) end local function makeResponseHead(res) local head = { code = res.code or 200 } local contentLength local chunked local headers = res.headers if headers then for i = 1, #headers do local header = headers[i] local key, value = tostring(header[1]), tostring(header[2]) key = key:lower() if key == "content-length" then contentLength = value elseif key == "content-encoding" and value:lower() == "chunked" then chunked = true end head[#head + 1] = headers[i] end end local body = res.body if type(body) == "string" then if not chunked and not contentLength then head[#head + 1] = {"Content-Length", #body} end end return head end local function onConnect(self, binding, socket) local rawRead, rawWrite, close = wrapStream(socket) local read, updateDecoder = coroWrap.reader(rawRead, httpCodec.decoder()) local write, updateEncoder = coroWrap.writer(rawWrite, httpCodec.encoder()) while true do local head = read() if type(head) ~= 'table' then break end local url = head.path or "" local path, rawQuery = match(url, "^([^%?]*)[%?]?(.*)$") local req = { app = self, socket = socket, method = head.method, url = url, path = path, originalPath = path, rawQuery = rawQuery, binding = binding, read = read, close = close, headers = getHeaders(head), version = head.version, keepAlive = head.keepAlive } local res = self._router:doRoute(req) if type(res) ~= 'table' then break end -- Write response write(makeResponseHead(res)) local body = res.body write(body and tostring(body) or nil) write() -- Drop non-keepalive and unhandled requets if not (res.keepAlive and head.keepAlive) then break end -- Handle upgrade requests if res.upgrade then res.upgrade(read, write, updateDecoder, updateEncoder, socket) break end end return close() end function Server:bind(options) options = options or {} if not options.host then options.host = '0.0.0.0' end if not options.port then options.port = uv.getuid() == 0 and (options.tls and 443 or 80) or (options.tls and 8443 or 8080) end self.bindings[#self.bindings + 1] = options return self end function Server:close() local netServers = self.netServers for i = 1, #netServers do local s = netServers[i] s:close() end end local function addOnStart(fn, a, b) if fn then local timer = uv.new_timer() timer:start(0, 0, coroutine.wrap(function() timer:close() return fn(a, b) end)) end end function Server:startLater(options) if not options then options = {} end if options.port or options.host then self:bind(options) end if #self.bindings < 1 then self:bind() end local bindings = self.bindings for i = 1, #bindings do local binding = bindings[i] local tls = binding.tls or options.tls binding.tls = not not tls local socketWrap if tls then local secureSocket = require('moonmint.deps.secure-socket') local tlsOptions = {} for k, v in pairs(tls) do tlsOptions[k] = v end tlsOptions.server = true socketWrap = function(x) return assert(secureSocket(x, tlsOptions)) end else socketWrap = function(x) return x end end local server = uv.new_tcp() -- Set the err handler. False explicitely disables it. local onErr = binding.errHand if onErr == nil then onErr = options.errHand if onErr == nil then onErr = debug and debug.traceback or print end end table.insert(self.netServers, server) assert(server:bind(binding.host, binding.port)) assert(server:listen(256, function(err) assert(not err, err) local socket = uv.new_tcp() server:accept(socket) wrap(function() if onErr then return xpcall(function() return onConnect(self, binding, socketWrap(socket)) end, onErr) else return onConnect(self, binding, socketWrap(socket)) end end)() end)) addOnStart(binding.onStart, self, binding) end addOnStart(options.onStart, self) self._startPending = true return self end function Server:start(options) if not self._startPending then self:startLater(options) self._startPending = false end uv.run() return self end -- Duplicate router functions for the server, so routes and middleware can be placed -- directly on the server. local function alias(fname) Server[fname] = function(self, ...) local r = self._router r[fname](r, ...) return self end end alias("use") alias("route") alias("all") -- HTTP version 1.1 alias('get') alias('put') alias('post') alias('delete') alias('head') alias('options') alias('trace') alias('connect') -- WebDAV alias('bcopy') alias('bdelete') alias('bmove') alias('bpropfind') alias('bproppatch') alias('copy') alias('lock') alias('mkcol') alias('move') alias('notify') alias('poll') alias('propfind') alias('search') alias('subscribe') alias('unlock') alias('unsubscribe') return makeServer
nilq/small-lua-stack
null
local jass = require 'jass.common' local dbg = require 'jass.debug' local Point = require 'war3library.libraries.ac.point' local Destructable = {} setmetatable(Destructable, Destructable) local mt = {} Destructable.__index = mt mt.type = 'destructable' --现存的所有可破坏物 Destructable.all_destrucables = nil --根据handle创建可破坏物 function Destructable.new(handle) if handle == 0 or not handle then return nil end local war3_id = base.id2string(jass.GetDestructableTypeId(handle)) local data = ac.destructable[war3_id] if type(data) == 'function' then data = Destructable end local dest = {} setmetatable(dest, dest) dest.__index = data dest.handle = handle dest.id = war3_id dest.war3_id = war3_id dest.name = jass.GetDestructableName(handle) Destructable.all_destrucables[handle] = dest return dest end --根据句柄获取可破坏物 function Destructable:__call(handle) if not handle or handle == 0 then return nil end local dest = Destructable.all_destrucables[handle] if not dest then dest = Destructable.new(handle) end return dest end --创建可破坏物 -- 可破坏物名字 -- 面向角度 -- 放缩 -- 样式 function Destructable.create_destructable(id, x, y, facing, scale, variation) local handle = jass.CreateDestructable(base.string2id(id), x, y, facing or 0, scale or 1, variation or 0) dbg:handle_ref(handle) local dest = Destructable.new(handle) if not dest then return end return dest end --删除可破坏物 function mt:remove() if not self.removed then return end if self.on_remove then self:on_remove() end self.removed = true self._is_alive = false self._last_point = Point:new(jass.GetDestructableX(self.handle), jass.GetDestructableY(self.handle)) jass.RemoveDestructable(self.handle) dbg.handle_unref(self.handle) Destructable.all_destrucables[self.handle] = nil self.handle = nil end function mt:open() self:killed() self:set_animation('death alternate') end function mt:close() if not self:is_alive() then self:restore() end self:set_animation('stand') end function mt:killed( ) if self:is_alive() then jass.KillDestructable(self.handle) self._is_alive = false end end --显示复活效果 function mt:restore( is_show_candy ) self._is_alive = true jass.DestructableRestoreLife(self.handle, jass.GetDestructableMaxLife(self.handle), is_show_candy == nil or (is_show_candy and true) ) end function mt:is_alive( ) if self._is_alive == nil then self._is_alive = self:get_life() > 0 end return self._is_alive end function mt:get_life( ) return jass.GetDestructableLife(self.handle) end --播放动画 function mt:set_animation( animation ) jass.SetDestructableAnimation(self.handle, animation) end --获取点 function mt:get_point() if self.removed then return self._last_point:copy() else return Point:new(jass.GetDestructableX(self.handle), jass.GetDestructableY(self.handle)) end end --在点创建可破坏物 -- 可破坏物名字 -- 面向角度 -- 放缩 -- 样式 function Point.__index:add_destructable( name, facing, scale, variation ) local id = Registry:name_to_id('destructable', name) local x, y = self:get() local dest = Destructable.create_destructable(id, x, y, facing, scale, variation) end local function register_destructure(self, name, data) local war3_id = data.war3_id if not war3_id or war3_id == '' then Log.error(('注册%s可破坏物时,不能没有war3_id'):format(name) ) return end Registry:register('destructable', name, war3_id) setmetatable(data, data) data.__index = Destructable local dest = {} setmetatable(dest, dest) dest.__index = data dest.__call = function(self, data) self.data = data return self end dest.name = name dest.data = data self[name] = dest self[war3_id] = dest return dest end local function init( ) Destructable.all_destrucables = {} ac.destructable = setmetatable({}, {__index = function ( self, name ) return function ( data ) return register_destructure(self, name, data) end end}) end init() return Destructable
nilq/small-lua-stack
null
local awful = require('awful') local wibox = require('wibox') local beautiful = require('beautiful') local gears = require('gears') local clickable_container = require('widget.clickable-container') local dpi = require('beautiful').xresources.apply_dpi local colors = require('themes.dracula.colors') local modkey = require('config.keys.mod').modKey local icons = require('themes.icons') local return_button = function(s, main_color, occupied_color, width) local taglist_buttons = gears.table.join( awful.button( {}, 1, function(t) t:view_only() end ), awful.button( {modkey}, 1, function(t) if client.focus then client.focus:move_to_tag(t) end end ), awful.button( {}, 3, awful.tag.viewtoggle ), awful.button( {modkey}, 3, function(t) if client.focus then client.focus:toggle_tag(t) end end ), awful.button( {}, 4, function(t) awful.tag.viewprev(t.screen) end ), awful.button( {}, 5, function(t) awful.tag.viewnext(t.screen) end ) ) s.mytaglist = awful.widget.taglist { screen = s, filter = awful.widget.taglist.filter.all, buttons = taglist_buttons, } local widget_button = wibox.widget { { { { { s.mytaglist, layout = wibox.layout.fixed.horizontal, }, top = dpi(6), bottom = dpi(6), left = dpi(12), right = dpi(12), widget = wibox.container.margin }, shape = gears.shape.rounded_bar, bg = 'transparent', fg = 'transparent', shape_border_width = dpi(width), shape_border_color = main_color, widget = wibox.container.background }, forced_width = icon_size, forced_height = icon_size, widget = clickable_container }, top = dpi(5), widget = wibox.container.margin } beautiful.taglist_shape = gears.shape.circle beautiful.taglist_shape_border_width = dpi(1) beautiful.taglist_fg_focus = main_color beautiful.taglist_bg_focus = main_color beautiful.taglist_shape_border_color_focus = main_color beautiful.taglist_bg_empty = 'transparent' beautiful.taglist_shape_border_color_empty = main_color beautiful.taglist_bg_volatile = 'transparent' beautiful.taglist_shape_border_color_volatile = vol_color beautiful.taglist_bg_occupied = 'transparent' beautiful.taglist_shape_border_color = occupied_color --occupied border variable doesnt exist (?) so all set to cyan and focus/empty are overrided return widget_button end return return_button
nilq/small-lua-stack
null
TOOL.Category = "Lite Tools" TOOL.Name = "#tool.lite_push_pull.name" TOOL.Information = { {name = "left"}, {name = "right"} } TOOL.ClientConVar["power"] = "5" TOOL.ClientConVar["undo"] = "1" if CLIENT then language.Add("tool.lite_push_pull.name", "Push/Pull") language.Add("tool.lite_push_pull.desc", "Push/Pull a prop in a direction.") language.Add("tool.lite_push_pull.left", "Push the entity away.") language.Add("tool.lite_push_pull.right", "Pull the entity closer.") language.Add("tool.lite_push_pull.power", "Push/Pull Power") language.Add("tool.lite_push_pull.power.help", "How powerful the push/pull action should be.") language.Add("tool.lite_push_pull.undo", "Register Undo") language.Add("tool.lite_push_pull.undo.help", "Add this action to your undo list.") end function TOOL:ValidateEntity(entity) if not IsValid(entity) then return false end if entity:IsPlayer() then return false end return true end function TOOL:MoveEntity(trace, dir) local ent = trace.Entity local phys = ent:GetPhysicsObjectNum(trace.PhysicsBone) local oldPos = phys:GetPos() local target = phys:GetPos() + trace.HitNormal * math.Clamp(self:GetClientNumber("power"), 0, 50) * dir phys:SetPos(target) phys:Wake() -- if not util.IsInWorld(ent:GetPos()) then -- ent:Remove() -- end ent:GetPhysicsObject():EnableMotion(false) if self:GetClientNumber("undo") == 1 then undo.Create("lite_push_pull") undo.SetPlayer(self:GetOwner()) undo.AddFunction( function(_, phys, oldPos) if not IsValid(phys) then return end phys:SetPos(oldPos) phys:Wake() end, phys, oldPos) undo.Finish() end end function TOOL:LeftClick(trace) if CLIENT then return true end if not self:ValidateEntity(trace.Entity) then return end self:MoveEntity(trace, -1) return true end function TOOL:RightClick(trace) if CLIENT then return true end if not self:ValidateEntity(trace.Entity) then return end self:MoveEntity(trace, 1) end function TOOL.BuildCPanel(panel) panel:AddControl("Header", {Text = "#tool.lite_push_pull.name", Description = "#tool.lite_push_pull.desc"}) panel:AddControl("Slider", {Label = "#tool.lite_push_pull.power", Command = "lite_push_pull_power", Type = "Float", Min = 0, Max = 50}) panel:AddControl("Checkbox", {Label = "#tool.lite_push_pull.undo", Command = "lite_push_pull_undo"}) end
nilq/small-lua-stack
null
addEvent("gra.cPersonalSettings.set", true, true) local playersSettings = {} cPersonalSettings = {} addEventHandler("onResourceStart", resourceRoot, function() for i, player in ipairs(getElementsByType("player")) do playersSettings[player] = {} end end ) addEventHandler("onPlayerJoin", root, function() playersSettings[source] = {} end ) addEventHandler("onPlayerQuit", root, function() playersSettings[source] = nil end ) addEventHandler("gra.cPersonalSettings.set", root, function(setting, value) local client = client if not playersSettings[client] then return warn(eventName..": client '"..getPlayerName(client).."' not found in table", 0) and false end if not setting then return warn(eventName..": invalid setting '"..tostring(setting).."'", 0) and false end playersSettings[client][setting] = value end ) function cPersonalSettings.get(player, setting) if not scheck("u:element:player|u:element:root|u:element:console,s") then return false end if not playersSettings[player] then return nil end return playersSettings[player][setting] end
nilq/small-lua-stack
null
-- MasterMerchant Russian Localization File -- Last Updated September 6, 2014 -- Written July 2014 by Dan Stone (@khaibit) - [email protected] -- Extended February 2015 by Chris Lasswell (@Philgo68) - [email protected] -- Released under terms in license accompanying this file. -- Distribution without license is prohibited! -- Options Menu ZO_CreateStringId("SK_ALERT_ANNOUNCE_NAME", "Предупреждения") ZO_CreateStringId("SK_ALERT_ANNOUNCE_TIP", "Выводит предупреждения на экран.") ZO_CreateStringId("SK_ALERT_CYRODIIL_NAME", "Пред. в Сиродиле") ZO_CreateStringId("SK_ALERT_CYRODIIL_TIP", "Выводит предупреждения на экран, когда вы в Сиродиле. Предупреждения в чате, если включены, выводятся в любом случае.") ZO_CreateStringId("SK_MULT_ALERT_NAME", "Мульти-предупреждения") ZO_CreateStringId("SK_MULT_ALERT_TIP", "Выводит предупреждение отдельно по каждому проданному предмету вместо одного предупреждения с общей суммой всех проданных предметов.") ZO_CreateStringId("SK_OPEN_MAIL_NAME", "Открывать с почтой") ZO_CreateStringId("SK_OPEN_MAIL_TIP", "Открывать историю продаж Master Merchant с открытием окна почты.") ZO_CreateStringId("SK_OPEN_STORE_NAME", "Открывать с магазином") ZO_CreateStringId("SK_OPEN_STORE_TIP", "Открывать историю продаж Master Merchant с открытием окна магазина.") ZO_CreateStringId("SK_FULL_SALE_NAME", "Полная цена") ZO_CreateStringId("SK_FULL_SALE_TIP", "Показывать цену продажи предмета без учета налога с магазина.") ZO_CreateStringId("SK_SCAN_FREQ_NAME", "Частота сканирования") ZO_CreateStringId("SK_SCAN_FREQ_TIP", "Время ожидания (в секундах) между проверками продаж в гильдейских магазинах.") ZO_CreateStringId("SK_HISTORY_DEPTH_NAME", "Размер истории") ZO_CreateStringId("SK_HISTORY_DEPTH_TIP", "Сколько дней продаж должны сохраняться в истории. Снижение этого параметра может повысить производительность этого аддона.") ZO_CreateStringId("SK_SHOW_PRICING_NAME", "Информация о ценах") ZO_CreateStringId("SK_SHOW_PRICING_TIP", "Включает подсказку о цене предметов в подсказках к предмету, на основе базы данных о прошлых продажах.") ZO_CreateStringId("SK_SHOW_CRAFT_COST_NAME", "Show Crafting Cost Info") ZO_CreateStringId("SK_SHOW_CRAFT_COST_TIP", "Include crafting cost based on ingredient costs in item tooltips.") ZO_CreateStringId("SK_CALC_NAME", "Калькулятор стаков") ZO_CreateStringId("SK_CALC_TIP", "Показывает небольшой калькулятор при выставлении предмета на продажу в магазине.") ZO_CreateStringId("SK_WINDOW_FONT_NAME", "Шрифт") ZO_CreateStringId("SK_WINDOW_FONT_TIP", "Шрифт текста окна Master Merchant.") ZO_CreateStringId("SK_ALERT_OPTIONS_NAME", "Настройка предупреждений") ZO_CreateStringId("SK_ALERT_OPTIONS_TIP", "Настройки типов и звуков предупреждений.") ZO_CreateStringId("SK_ALERT_TYPE_NAME", "Звук") ZO_CreateStringId("SK_ALERT_TYPE_TIP", "Звук, проигрываемый при продаже вашего предмета, если выбрано.") ZO_CreateStringId("SK_ALERT_CHAT_NAME", "Чат") ZO_CreateStringId("SK_ALERT_CHAT_TIP", "Показывает предупреждение о продаже в чате.") ZO_CreateStringId("SK_ACCOUNT_WIDE_NAME", "Настройки на аккаунт") ZO_CreateStringId("SK_ACCOUNT_WIDE_TIP", "Применяет все сделанные вами настройки для всех персонажей на вашем аккаунте.") ZO_CreateStringId("SK_OFFLINE_SALES_NAME", "Оффлайн отчет") ZO_CreateStringId("SK_OFFLINE_SALES_TIP", "Выводит предупреждение в чат о проданных, пока вы были оффлайн, предметах при логине.") ZO_CreateStringId("SK_TRIM_OUTLIERS_NAME", "Игнорировать подозрительные цены") ZO_CreateStringId("SK_TRIM_OUTLIERS_TIP", "Игнорировать сделки с ценами, сильно отклоняющимися от привычных.") ZO_CreateStringId("SK_TRIM_DECIMALS_NAME", "Округление цен") ZO_CreateStringId("SK_TRIM_DECIMALS_TIP", "Округляет все цены до золота.") ZO_CreateStringId("SK_DELAY_INIT_NAME", "Задержка инициализации") ZO_CreateStringId("SK_DELAY_INIT_TIP", "Если у вас есть проблемы с входом, установите задержку, пока ваш персонаж полностью не загрузится.") ZO_CreateStringId("SK_ROSTER_INFO_NAME", "Инфо в ростере гильдии") ZO_CreateStringId("SK_ROSTER_INFO_TIP", "Показывает число покупок и продаж в ростере гильдии, основанных на настройках времени в окне MM.") ZO_CreateStringId("SK_SHOW_GRAPH_NAME", "Граф истории цен") ZO_CreateStringId("SK_SHOW_GRAPH_TIP", "Включает график истории цен предмета в подсказке к нему.") -- Main window ZO_CreateStringId("SK_VIEW_ALL_SALES", "Вся инфо") ZO_CreateStringId("SK_VIEW_YOUR_SALES", "Ваша инфо") ZO_CreateStringId("SK_ALL_SALES_TITLE", "Вся информация") ZO_CreateStringId("SK_YOUR_SALES_TITLE", "Ваша информация") ZO_CreateStringId("SK_GUILD_SALES_TITLE", "Ранги в гильдии") ZO_CreateStringId("SK_SHOW_UNIT", "Цена за штуку") ZO_CreateStringId("SK_SHOW_TOTAL", "Общая цена") ZO_CreateStringId("SK_BUYER_COLUMN", "Покупатель") ZO_CreateStringId("SK_GUILD_COLUMN", "Гильдия") ZO_CreateStringId("SK_ITEM_COLUMN", "Предмет") ZO_CreateStringId("SK_TIME_COLUMN", "Время продажи") ZO_CreateStringId("SK_PRICE_COLUMN", "Цена") ZO_CreateStringId("SK_PRICE_EACH_COLUMN", "Цена(шт.)") ZO_CreateStringId("SK_ITEM_TOOLTIP", "Двойной клик на предмете - ссылка в чат.") ZO_CreateStringId("SK_BUYER_TOOLTIP", "Двойной клик по имени для связи.") ZO_CreateStringId("SK_SORT_TIME_TOOLTIP", "Клик для сортировки по времени продаж.") ZO_CreateStringId("SK_SORT_PRICE_TOOLTIP", "Клик для сортировки по цене.") ZO_CreateStringId("SK_STATS_TOOLTIP", "Открыть окно статистики.") ZO_CreateStringId("SK_SELLER_TOOLTIP", "Продавцы") ZO_CreateStringId("SK_ITEMS_TOOLTIP", "Предметы") ZO_CreateStringId("SK_TIME_SECONDS", "<<1[Прямо сейчас/%d секунд назад]>>") ZO_CreateStringId("SK_TIME_MINUTES", "<<1[%d минуты назад/%d минут назад]>>") ZO_CreateStringId("SK_TIME_HOURS", "<<1[%d часа назад/%d часов назад]>>") ZO_CreateStringId("SK_TIME_DAYS", "<<1[Вчера/%d дней назад]>>") ZO_CreateStringId("SK_TIME_SECONDS_LC", "<<1[прямо сейчас/%d секунд назад]>>") ZO_CreateStringId("SK_TIME_MINUTES_LC", "<<1[%d минуты назад/%d минут назад]>>") ZO_CreateStringId("SK_TIME_HOURS_LC", "<<1[%d часа назад/%d часов назад]>>") ZO_CreateStringId("SK_TIME_DAYS_LC", "<<1[вчера/%d дней назад]>>") ZO_CreateStringId("SK_THOUSANDS_SEP", ",") -- Chat and center screen alerts/messages ZO_CreateStringId("SK_FIRST_SCAN", "Сканирование ваших гильдий первый раз. Это может занять несколько минут!") ZO_CreateStringId("SK_REFRESH_LABEL", "Обновить") ZO_CreateStringId("SK_REFRESH_START", "Начинаем обновление.") ZO_CreateStringId("SK_REFRESH_DONE", "Обновление завершено.") ZO_CreateStringId("SK_REFRESH_WAIT", "Пожалуйста, подождите минуту или около того между обновлениями.") ZO_CreateStringId("SK_RESET_LABEL", "Сброс") ZO_CreateStringId("SK_RESET_CONFIRM_TITLE", "Подтвердить сброс") ZO_CreateStringId("SK_RESET_CONFIRM_MAIN", "Вы уверены, что хотите сбросить историю ваших продаж? Все данные будут заменены свежими данными с сервера.") ZO_CreateStringId("SK_RESET_DONE", "История продаж сброшена.") ZO_CreateStringId("SK_SALES_ALERT", "Вы продали %s x%d зa %s |t16:16:EsoUI/Art/currency/currency_gold.dds|t в %s %s.") ZO_CreateStringId("SK_SALES_ALERT_COLOR", "Вы продали %s x%d зa |cD5B526%s |t16:16:EsoUI/Art/currency/currency_gold.dds|t |cFFFFFFв %s %s.") ZO_CreateStringId("SK_SALES_ALERT_SINGLE", "Вы продали %s зa %s |t16:16:EsoUI/Art/currency/currency_gold.dds|t в %s %s.") ZO_CreateStringId("SK_SALES_ALERT_SINGLE_COLOR", "Вы продали %s зa |cD5B526%s |t16:16:EsoUI/Art/currency/currency_gold.dds|t |cFFFFFFв %s %s.") ZO_CreateStringId("SK_SALES_ALERT_GROUP", "Вы продали %d предметов на сумму %s |t16:16:EsoUI/Art/currency/currency_gold.dds|t в гильдейских магазинах.") ZO_CreateStringId("SK_SALES_ALERT_GROUP_COLOR", "Вы продали %d предметов на сумму |cD5B526%s |t16:16:EsoUI/Art/currency/currency_gold.dds|t |cFFFFFFв гильдейских магазинах.") ZO_CreateStringId("SK_SALES_REPORT", "Отчет о продажах:") ZO_CreateStringId("SK_SALES_REPORT_END", "Конец отчета.") -- Stats Window ZO_CreateStringId("SK_STATS_TITLE", "Статистика продаж") ZO_CreateStringId("SK_STATS_TIME_ALL", "Все данные") ZO_CreateStringId("SK_STATS_TIME_SOME", "В течение <<1[%d дня/%d дней]>>") ZO_CreateStringId("SK_STATS_ITEMS_SOLD", "Проданные предметы: %s (%s%% через гильдейского торговца)") ZO_CreateStringId("SK_STATS_TOTAL_GOLD", "Вceгo зoлoтa: %s |t16:16:EsoUI/Art/currency/currency_gold.dds|t (%s |t16:16:EsoUI/Art/currency/currency_gold.dds|t в дeнь)") ZO_CreateStringId("SK_STATS_BIGGEST", "Нaибoльшaя пpoдaжa: %s (%s |t16:16:EsoUI/Art/currency/currency_gold.dds|t)") ZO_CreateStringId("SK_STATS_DAYS", "Дней: ") ZO_CreateStringId("SK_STATS_ALL_GUILDS", "Все гильдии") -- Tooltip Pricing ZO_CreateStringId("SK_PRICETIP_SALES", "<<1[%d продажа/%d продаж]>>") ZO_CreateStringId("SK_PRICETIP_ONEDAY", "Цeнa Master Merchant (%s, <1 дня): %.2f|t16:16:EsoUI/Art/currency/currency_gold.dds|t") ZO_CreateStringId("SK_PRICETIP_MULTDAY", "Цeнa Master Merchant (%s, %d днeй): %.2f|t16:16:EsoUI/Art/currency/currency_gold.dds|t") -- Keybindings ZO_CreateStringId("SI_BINDING_NAME_MasterMerchant_TOGGLE", "Показать/скрыть главное окно") ZO_CreateStringId("SI_BINDING_NAME_MasterMerchant_STATS_TOGGLE", "Показать/скрыть окно статистики") -- New values ZO_CreateStringId("MM_TIP_FORMAT_SINGLE", "Цена M.M. (%s, %d день): %.2f") ZO_CreateStringId("MM_TIP_FORMAT_MULTI", "Цена M.M. (%s, %d дней): %.2f") ZO_CreateStringId("MM_TIP_FORMAT_NONE", "Нет данных M.M.") ZO_CreateStringId("MM_TIP_FORMAT_NONE_RANGE", "У M.M. нет данных за прошедшие %d дней") ZO_CreateStringId("MM_TIP_FOR", "за") ZO_CreateStringId("MM_LINK_TO_CHAT", "В чат") ZO_CreateStringId("MM_STATS_TO_CHAT", "Статистика в чат") ZO_CreateStringId("MM_APP_NAME", "Master Merchant") ZO_CreateStringId("MM_APP_AUTHOR", "Khaibit & Philgo68") ZO_CreateStringId("MM_APP_MESSAGE_NAME", "[Master Merchant]") ZO_CreateStringId("MM_APP_TEXT_TIMES", " x ") ZO_CreateStringId("MM_ADVICE_ERROR", "Master Merchant не может предоставить консультации в данном торговом доме.") ZO_CreateStringId("MM_POSTED_FOR", "размещено") ZO_CreateStringId("MM_TOTAL_TITLE", "Всего: ") ZO_CreateStringId("MM_VET_RANK_SEARCH", "vr") ZO_CreateStringId("MM_CP_RANK_SEARCH", "cp") ZO_CreateStringId("MM_REGULAR_RANK_SEARCH", "rr") ZO_CreateStringId("MM_COLOR_WHITE", "обычное") ZO_CreateStringId("MM_COLOR_GREEN", "хорошее") ZO_CreateStringId("MM_COLOR_BLUE", "превосходное") ZO_CreateStringId("MM_COLOR_PURPLE", "эпическое") ZO_CreateStringId("MM_COLOR_GOLD", "легендарное") ZO_CreateStringId("MM_PERCENT_CHAR", "%") ZO_CreateStringId("MM_ENTIRE_GUILD", "Вся гильдия") ZO_CreateStringId("MM_INDEX_TODAY", "Сегодня") ZO_CreateStringId("MM_INDEX_3DAY", "Вчера") ZO_CreateStringId("MM_INDEX_THISWEEK", "Эта неделя") ZO_CreateStringId("MM_INDEX_LASTWEEK", "Прошедшая неделя") ZO_CreateStringId("MM_INDEX_PRIORWEEK", "Предыдущая неделя") ZO_CreateStringId("MM_INDEX_7DAY", "7 дней") ZO_CreateStringId("MM_INDEX_10DAY", "10 дней") ZO_CreateStringId("MM_INDEX_28DAY", "30 дней") ZO_CreateStringId("SK_SELLER_COLUMN", "Продавец") ZO_CreateStringId("SK_RANK_COLUMN", "Ранг") ZO_CreateStringId("SK_SALES_COLUMN", "Продажи") ZO_CreateStringId("SK_PURCHASES_COLUMN", "Покупки") ZO_CreateStringId("SK_TAX_COLUMN", "Налог") ZO_CreateStringId("SK_COUNT_COLUMN", "Сделки") ZO_CreateStringId("SK_PERCENT_COLUMN", "Процент") ZO_CreateStringId("MM_NOTHING", "Ничего") ZO_CreateStringId("MM_LISTING_ALERT", "Вы выложили %s x%d за %s |t16:16:EsoUI/Art/currency/currency_gold.dds|t в %s.") ZO_CreateStringId("MM_CALC_OPTIONS_NAME", "Настройки подсчета и подсказок") ZO_CreateStringId("MM_CALC_OPTIONS_TIP", "Настройки подсчета цен MM для подсказок и их отображение.") ZO_CreateStringId("MM_DAYS_FOCUS_ONE_NAME", "Вариант 1: Дней") ZO_CreateStringId("MM_DAYS_FOCUS_ONE_TIP", "Число дней продаж для первого варианта.") ZO_CreateStringId("MM_DAYS_FOCUS_TWO_NAME", "Вариант 2: Дней") ZO_CreateStringId("MM_DAYS_FOCUS_TWO_TIP", "исло дней продаж для второго варианта.") ZO_CreateStringId("MM_DEFAULT_TIME_NAME", "Дней по умолчанию") ZO_CreateStringId("MM_DEFAULT_TIME_TIP", "Число дней истории продаж, используемое по умолчанию. (Нет чтобы не отображать.)") ZO_CreateStringId("MM_SHIFT_TIME_NAME", "<Shift> Промежуток дней") ZO_CreateStringId("MM_SHIFT_TIME_TIP", "Число дней истории когда удерживаете <Shift>.") ZO_CreateStringId("MM_CTRL_TIME_NAME", "<Crtl> Промежуток дней") ZO_CreateStringId("MM_CTRL_TIME_TIP", "Число дней истории когда удерживаете <Crtl>.") ZO_CreateStringId("MM_CTRLSHIFT_TIME_NAME", "<Crtl-Shift> Промежуток дней") ZO_CreateStringId("MM_CTRLSHIFT_TIME_TIP", "Число дней истории когда удерживаете <Crtl-Shift>.") ZO_CreateStringId("MM_RANGE_ALL", "Все") ZO_CreateStringId("MM_RANGE_FOCUS1", "Вариант 1") ZO_CreateStringId("MM_RANGE_FOCUS2", "Вариант 2") ZO_CreateStringId("MM_RANGE_NONE", "Нет") ZO_CreateStringId("MM_BLACKLIST_NAME", "Черный список игроков и гильдий") ZO_CreateStringId("MM_BLACKLIST_TIP", "Списиок имен игроков и гильдий, которые вы хотите исключить из подсчета цен аддоном MM.") ZO_CreateStringId("MM_CUSTOM_TIMEFRAME_NAME", "Custom Timeframe") ZO_CreateStringId("MM_CUSTOM_TIMEFRAME_TIP", "An extra timeframe to choose from in the item and guild lists.") ZO_CreateStringId("MM_CUSTOM_TIMEFRAME_SCALE_NAME", "Custom Timeframe Units") ZO_CreateStringId("MM_CUSTOM_TIMEFRAME_SCALE_TIP", "The time unit in which the Custom Timeframe is expressed.") ZO_CreateStringId("MM_CUSTOM_TIMEFRAME_HOURS", "Hours") ZO_CreateStringId("MM_CUSTOM_TIMEFRAME_DAYS", "Days") ZO_CreateStringId("MM_CUSTOM_TIMEFRAME_WEEKS", "Weeks") ZO_CreateStringId("MM_CUSTOM_TIMEFRAME_GUILD_WEEKS", "Full Guild Weeks") ZO_CreateStringId("MM_SAUCY_NAME", "Показывать прибыль вместо наценки") ZO_CreateStringId("MM_SAUCY_TIP", "В магазине отображает потенциальную прибыль, вместо процента наценки.") ZO_CreateStringId("MM_MIN_PROFIT_FILTER_NAME","Фильтр по прибыли") ZO_CreateStringId("MM_MIN_PROFIT_FILTER_TIP", "Добавляет в аддон АGS дополнительный фильтр, основаный на прибыли.") ZO_CreateStringId("MM_AUTO_ADVANCE_NAME", "Авто. след. страница") ZO_CreateStringId("MM_AUTO_ADVANCE_TIP", "Если все товары на странице уже отфильтрованы, переходит к следующей станице, пока не заполнит страницу отфильтрованными результатми.") ZO_CreateStringId("MM_PRICETIP_ITEMS", "/<<1[%d предмете/%d проданных]>>") ZO_CreateStringId("MM_MIN_ITEM_COUNT_NAME", "Мин. кол-во предметов") ZO_CreateStringId("MM_MIN_ITEM_COUNT_TIP", "Минимальное кол-во продаж предмета для сохранения в истории.") ZO_CreateStringId("MM_MAX_ITEM_COUNT_NAME", "Макс. кол-во предметов") ZO_CreateStringId("MM_MAX_ITEM_COUNT_TIP", "Максимальное кол-во продаж предмета для сохранения в истории.") ZO_CreateStringId("MM_REPLACE_INVENTORY_VALUES_NAME", "Заменить цену в инвентаре") ZO_CreateStringId("MM_REPLACE_INVENTORY_VALUES_TIP", "Отображать в инвентаре цену MM вместо обычной цены.") ZO_CreateStringId("MM_DISPLAY_LISTING_MESSAGE_NAME", "Выкладываемый товар в чат") ZO_CreateStringId("MM_DISPLAY_LISTING_MESSAGE_TIP", "Отображать в окне чата сообщение для каждого выкладываемого на продажу в гильд.магазин товара.") ZO_CreateStringId("SK_PER_CHANGE_COLUMN", "Налоги") ZO_CreateStringId("SK_PER_CHANGE_TIP", "Доход гильдии за счет налога с Ваших продаж.") ZO_CreateStringId("MM_POPUP_ITEM_DATA", "Popup Item Data") ZO_CreateStringId("MM_GRAPH_TIP", "В %s %s продан %s x %d to %s за %s|t16:16:EsoUI/Art/currency/currency_gold.dds|t каждый.") ZO_CreateStringId("MM_GRAPH_TIP_SINGLE", "В %s %s продан %s to %s за %s|t16:16:EsoUI/Art/currency/currency_gold.dds|t.") ZO_CreateStringId("MM_NO_DATA_DEAL_NAME", "Рейтинг товара без истории") ZO_CreateStringId("MM_NO_DATA_DEAL_TIP", "Рейтинг сделки для товара без истории продаж.") ZO_CreateStringId("MM_GRAPH_INFO_NAME", "Подсказ.для точек графика") ZO_CreateStringId("MM_GRAPH_INFO_TIP", "Отображать всплывающее окно с информацией о продажах для точек графика.") ZO_CreateStringId("MM_LEVEL_QUALITY_NAME", "Переключатель Уровень/Качество") ZO_CreateStringId("MM_LEVEL_QUALITY_TIP", "Отображать во всплывающем окне предмета кнопки настройки Уровень/Качество.") ZO_CreateStringId("MM_VERBOSE_NAME", "Подробные сообщения") ZO_CreateStringId("MM_VERBOSE_TIP", "Отображает больше сообщений о состоянии в окне чата во время операций MM.") ZO_CreateStringId("MM_SIMPLE_SCAN_NAME", "Простое сканирование истории гильдии") ZO_CreateStringId("MM_SIMPLE_SCAN_TIP", "Сканирование гильдий менее интенсивно для получения данных быстрее, но может оставить пробелы в вашей истории.") ZO_CreateStringId("MM_SKIP_INDEX_NAME", "Минимальная индексация") ZO_CreateStringId("MM_SKIP_INDEX_TIP", "Индексы истории продаж пропускаются, чтобы сэкономить память, но поиск на экране MM намного медленнее.") ZO_CreateStringId("MM_DAYS_ONLY_NAME", "Use Sales History Size Only") ZO_CreateStringId("MM_DAYS_ONLY_TIP", "Will use Sales History Size only when trimming sales history. This will ignore mix and max count.")
nilq/small-lua-stack
null
MultiBarRight:ClearAllPoints(); MultiBarRight:SetPoint("RIGHT", 510, 390); MultiBarRight.SetPoint = function() end
nilq/small-lua-stack
null
local key = KEYS[1] local capacity = tonumber(ARGV[1]) local timestamp = tonumber(ARGV[2]) local id = ARGV[3] local count = redis.call("zcard", key) local allowed = count < capacity if allowed then redis.call("zadd", key, timestamp, id) end redis.call("setex", key, timestamp) return { allowed, count }
nilq/small-lua-stack
null
-- This is an OOP-style class system module local assert, pairs, type, tostring, setmetatable = assert, pairs, type, tostring, setmetatable local baseMt, _instances, _classes, _class = {}, setmetatable({},{__mode='k'}), setmetatable({},{__mode='k'}) local function assert_class(class, method) assert(_classes[class], ('Wrong method call. Expected class:%s.'):format(method)) end local function deep_copy(t, dest, aType) t = t or {}; local r = dest or {} for k,v in pairs(t) do if aType and type(v)==aType then r[k] = v elseif not aType then if type(v) == 'table' and k ~= "__index" then r[k] = deep_copy(v) else r[k] = v end end end; return r end local function instantiate(self,...) assert_class(self, 'new(...) or class(...)'); local instance = {class = self}; _instances[instance] = tostring(instance); setmetatable(instance,self) if self.init then if type(self.init) == 'table' then deep_copy(self.init, instance) else self.init(instance, ...) end; end; return instance end local function extend(self, name, extra_params) assert_class(self, 'extend(...)'); local heir = {}; _classes[heir] = tostring(heir); deep_copy(extra_params, deep_copy(self, heir)); heir.name, heir.__index, heir.super = extra_params and extra_params.name or name, heir, self; return setmetatable(heir,self) end baseMt = { __call = function (self,...) return self:new(...) end, __tostring = function(self,...) if _instances[self] then return ("instance of '%s' (%s)"):format(rawget(self.class,'name') or '?', _instances[self]) end return _classes[self] and ("class '%s' (%s)"):format(rawget(self,'name') or '?',_classes[self]) or self end}; _classes[baseMt] = tostring(baseMt); setmetatable(baseMt, {__tostring = baseMt.__tostring}) local class = {isClass = function(class, ofsuper) local isclass = not not _classes[class]; if ofsuper then return isclass and (class.super == ofsuper) end; return isclass end, isInstance = function(instance, ofclass) local isinstance = not not _instances[instance]; if ofclass then return isinstance and (instance.class == ofclass) end; return isinstance end}; _class = function(name, attr) local c = deep_copy(attr); c.mixins=setmetatable({},{__mode='k'}); _classes[c] = tostring(c); c.name, c.__tostring, c.__call = name or c.name, baseMt.__tostring, baseMt.__call c.include = function(self,mixin) assert_class(self, 'include(mixin)'); self.mixins[mixin] = true; return deep_copy(mixin, self, 'function') end c.new, c.extend, c.__index, c.includes = instantiate, extend, c, function(self,mixin) assert_class(self,'includes(mixin)') return not not (self.mixins[mixin] or (self.super and self.super:includes(mixin))) end c.extends = function(self, class) assert_class(self, 'extends(class)') local super = self; repeat super = super.super until (super == class or super == nil); return class and (super == class) end return setmetatable(c, baseMt) end; class._DESCRIPTION = '30 lines library for object orientation in Lua'; class._VERSION = '30log v1.0.0'; class._URL = 'http://github.com/Yonaba/30log'; class._LICENSE = 'MIT LICENSE <http://www.opensource.org/licenses/mit-license.php>' return setmetatable(class,{__call = function(_,...) return _class(...) end })
nilq/small-lua-stack
null
SceneManager = require("SceneManager") ArchiveManager = require("ArchiveManager") FailureScene = {} FailureScene.name = "FailureScene" local _FONT_ = nil local _TEXT_ = "别灰心,你还有机会……" local _COLOR_TEXT_ = {r = 226, g = 4, b = 27, a = 255} local _TEXT_SHOW_DELAY_ = 120 local _RECT_TEXT_ = nil local _window_width, _window_height = GetWindowSize() local _image_Text = nil local _texture_Text = nil local _width_image_text, _height_image_text = nil, nil local _start_FadeIn = true local _timer_show = 0 local _alpha = 255 local function _FadeOut() SetDrawColor({r = 0, g = 0, b = 0, a = 15}) for i = 1, 100 do FillRectangle({x = 0, y = 0, w = _window_width, h = _window_height}) UpdateWindow() Sleep(10) end end function FailureScene.Init() SceneManager.ClearWindowWhenUpdate = false _FONT_ = LoadFont("./Resource/Font/YGYCY.TTF", 90) _image_Text = CreateUTF8TextImageBlended(_FONT_, _TEXT_, _COLOR_TEXT_) _texture_Text = CreateTexture(_image_Text) _width_image_text, _height_image_text = GetImageSize(_image_Text) _RECT_TEXT_ = {x = _window_width / 2 - _width_image_text / 2, y = _window_height / 2 - _height_image_text, w = _width_image_text, h = _height_image_text} end function FailureScene.Update() UpdateEvent() if _start_FadeIn and _alpha > 0 then _alpha = _alpha - 5 end if _timer_show > _TEXT_SHOW_DELAY_ then _FadeOut() SceneManager.SetQuitHandler(function() return true end) SceneManager.Quit() return else _timer_show = _timer_show + 1 end CopyTexture(_texture_Text, _RECT_TEXT_) SetDrawColor({r = 0, g = 0, b = 0, a = _alpha}) FillRectangle({x = 0, y = 0, w = _window_width, h = _window_height}) end function FailureScene.Unload() ArchiveManager.DumpArchive() ArchiveManager.CloseArchive() UnloadFont(_FONT_) DestroyTexture(_texture_Text) UnloadImage(_image_Text) end return FailureScene
nilq/small-lua-stack
null
object_tangible_jedi_jedi_holocron_generic = object_tangible_jedi_shared_jedi_holocron_generic:new { noTrade = 1, objectMenuComponent = "LightJediMenuComponent", } ObjectTemplates:addTemplate(object_tangible_jedi_jedi_holocron_generic, "object/tangible/jedi/jedi_holocron_generic.iff")
nilq/small-lua-stack
null
-- package.path = package.path .. ";D:/www/_nneesshh_git/ZeroBraneStudio53/lualibs/?/?.lua;D:/www/_nneesshh_git/ZeroBraneStudio53/lualibs/?.lua" package.cpath = package.cpath .. ";D:/www/_nneesshh_git/ZeroBraneStudio53/bin/?.dll;D:/www/_nneesshh_git/ZeroBraneStudio53/bin/clibs/?.dll" require('mobdebug').start('192.168.1.110') -- <-- only insert this line --[[]] local redis_pass = require "redis.redis_pass" pool = redis_pass:new( { ip = "127.0.0.1", port = "6379", auth = false } ) pool:run() --[[]]
nilq/small-lua-stack
null
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <[email protected]> Copyright 2008 Jo-Philipp Wich <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local dpt = require "luci.dispatcher" local product = require "luci.product" local section_cfg = {} local loop = 1 if product.verifyFeature('SNMP_AGENT', 'STATE') then section_cfg[loop] = {name=ROOTNODE, tag="State", note="State", multiple=false, addremove=false} loop = loop + 1 end if product.verifyFeature('SNMP_AGENT', 'COMMUNITIES') then section_cfg[loop] = {name="communities", tag="SNMP V1/V2C Communities", note="", multiple=true, addremove=true} loop = loop + 1 end if product.verifyFeature('SNMP_AGENT', 'USERS') then section_cfg[loop] = {name="users", tag="SNMP V3 Users", note="", multiple=true, addremove=true} loop = loop + 1 end section_cfg[loop] = {name="trap-hosts", tag="Trap Hosts", note="", multiple=true, addremove=true} --[[ initial mdForm instance ]]-- mdForm = MdForm("agent", "/config/snmp/agent", PRIVILEGE_SUPER, section_cfg, translate("Agent Configuration")) mdForm:prepare_all() --[[ get the basic config ]]-- if product.verifyFeature('SNMP_AGENT', 'STATE') then baseConfig = mdForm:get_section_obj(ROOTNODE) baseConfig:option(TfFlag, "state", translate("Enabled")) end --[[ list the communities for snmp agent ]]-- if product.verifyFeature('SNMP_AGENT', 'COMMUNITIES') then communitiesConfig = mdForm:get_section_obj("communities") communitiesConfig.sectionhead = translate("Community Name") communitiesConfig.keydesc = "Community Name: 1-31 characters, [a-z][A-Z][0-9][_.]" communitiesConfig.keymaxlen = "31" communitiesConfig:option(TfFlag, "state", translate("Enabled")).default = "true" fc = communitiesConfig:option(TfFlag, "full-access", translate("Full Access")) fc:depends({state="true"}) end --[[ list the users for snmp agent ]]-- if product.verifyFeature('SNMP_AGENT', 'USERS') then usersConfig = mdForm:get_section_obj("users") usersConfig.sectionhead = translate("Username") usersConfig.keydesc = translate("Username: 1-31 characters, [a-z][A-Z][0-9][_.]") usersConfig.keymaxlen = "31" usersConfig:option(TfFlag, "state", translate("Enabled")).default = "true" auth = usersConfig:option(ListValue, "auth", translate("Authentication Protocol")) auth:value('sha', 'sha') auth:value('md5', 'md5') auth:depends({state="true"}) fc = usersConfig:option(TfFlag, "full-access", translate("Full Access")) fc:depends({state="true"}) pw = usersConfig:option(Value, "password-tmp", translate("Password")) pw.password = true -- pw.datatype = "minlength(8)" pw:depends({state="true"}) end --[[ list the hosts for snmp agent ]]-- hostsConfig = mdForm:get_section_obj("trap-hosts") hostsConfig.description = "** Note for SNMP V3: INFORMS are used rather than simple TRAPS" hostsConfig.sectionhead = translate("Host") hostsConfig.keydesc = translate("Host: IPV4 Address") hostsConfig.keydatatype = "ip4addr" hostsConfig:option(TfFlag, "state", translate("Enabled")).default = "true" version = hostsConfig:option(ListValue, "version", translate("Version")) version:value('v1', 'SNMP V1') version:value('v2c', 'SNMP V2C') version:value('v3', 'SNMP V3') --version:depends({state="true"}) communityConfig = hostsConfig:option(Value, "community", translate("Community/SNMPv3 User")) --[[ for i, v in pairs(mdForm.curr_data['communities']) do --if type(v) == 'table' then --for ii, iv in pairs(v) do communityConfig:value(i, i) --end --end end ]]-- communityConfig.datatype = "minlength(1)" communityConfig:depends({state="true"}) auth = hostsConfig:option(ListValue, "auth", translate("Auth")) auth:value('', '') auth:value('sha', 'sha') auth:value('md5', 'md5') --auth:depends({state="true"}) pw = hostsConfig:option(Value, "password-tmp", translate("Password")) pw.password = true --pw:depends({state="true"}) function mdForm.post_commit() local mgmtdclient = require "mgmtdclient" mgmtdclient.action("/action/snmp/apply") end mdForm.template = "admin/agent_mdform" return mdForm
nilq/small-lua-stack
null
vim.g.gutentags_file_list_command = 'rg --files --follow --ignore-file "/home/ayo/.vimignore"'
nilq/small-lua-stack
null
return { { ref = "physgun", name = "physgun", trait = "physgun", amount = 1, tier = 2, alwaysUnlocked = true }, { { { ref = "fr1", name = "fire_rate", trait = "towerFireRate", amount = 1, parent = "physgun", links = "parent", pos = {4,4}, }, { ref = "fr2", name = "fire_rate", trait = "towerFireRate", amount = 1, parent = "fr1", links = "parent", pos = {0,1}, }, { ref = "fr3", name = "fire_rate", trait = "towerFireRate", amount = 1, parent = "fr1", links = "parent", pos = {1,0}, }, { ref = "fr4", name = "fire_rate", trait = "towerFireRate", amount = 1, parent = "fr2", links = "parent", pos = {0,1}, }, { ref = "fr5", name = "fire_rate", trait = "towerFireRate", amount = 1, parent = "fr3", links = "parent", pos = {1,0}, }, { ref = "fr6", name = "fire_rate", trait = "towerFireRate", amount = 1, parent = "fr4", links = "parent", pos = {1,0}, }, { ref = "fr7", name = "fire_rate", trait = "towerFireRate", amount = 1, parent = "fr5", links = "parent", pos = {0,1}, }, { ref = "fr8", name = "fire_rate", trait = "towerFireRate", amount = 1, parent = "fr6", links = "parent", pos = {1,1}, }, { ref = "fr9", name = "fire_rate", trait = "towerFireRate", amount = 1, parent = "fr7", links = "parent", pos = {1,1}, }, { ref = "fr10", name = "fire_rate", trait = "towerFireRate", amount = 1, parent = "fr8", links = "parent", pos = {1,1}, }, { ref = "fr11", name = "fire_rate", trait = "towerFireRate", amount = 1, parent = "fr9", links = "parent", pos = {1,1}, }, }, { { ref = "fr12", name = "fire_rate", trait = "towerFireRate", amount = 1, parent = "fr6", links = {"fr6","fr7"}, pos = {1,0}, }, { ref = "extraBatteries", name = "extra_batteries", trait = "electrostaticBarrelBounces", amount = 1, tier = 1, parent = "fr12", links = "parent", pos = {-1,-1}, } }, { { ref = "fastCaliberTechnique", name = "fast_caliber_technique", trait = "sniperQueenFireRate", amount = 15, tier = 1, parent = "fr10", links = "parent", pos = {1,1}, }, { ref = "bigBombs", name = "bigger_bombs", trait = "mortarTowerBombRadius", amount = 25, tier = 1, parent = "fr11", links = {"fr11", "fastCaliberTechnique"}, pos = {1,1}, } }, { { ref = "range1", name = "range", trait = "towerRange", amount = 2, parent = "fastCaliberTechnique", links = "parent", pos = {-1,1}, }, { ref = "range3", name = "range", trait = "towerRange", amount = 2, parent = "range1", links = "parent", pos = {0,1}, }, { ref = "range5", name = "range", trait = "towerRange", amount = 2, parent = "range3", links = "parent", pos = {-1,1}, }, { ref = "range2", name = "range", trait = "towerRange", amount = 2, parent = "bigBombs", links = "parent", pos = {1,-1}, }, { ref = "range4", name = "range", trait = "towerRange", amount = 2, parent = "range2", links = "parent", pos = {1,0}, }, { ref = "range6", name = "range", trait = "towerRange", amount = 2, parent = "range4", links = "parent", pos = {1,-1}, } }, { { ref = "biggerMines", name = "bigger_mines", trait = "proximityMineRange", amount = 25, tier = 1, parent = "range5", links = "parent", pos = {0,1}, }, { ref = "betterGattlerDesign", name = "better_gattler_design", trait = "gatlingGunKnightSpread", amount = -15, tier = 1, parent = "range6", links = "parent", pos = {1,0}, } }, { { ref = "range7", name = "range", trait = "towerRange", amount = 2, parent = "biggerMines", links = "parent", pos = {1,0}, }, { ref = "range9", name = "range", trait = "towerRange", amount = 2, parent = "range7", links = "parent", pos = {1,-1}, }, { ref = "range11", name = "range", trait = "towerRange", amount = 2, parent = "range9", links = "parent", pos = {1,-1}, }, { ref = "range8", name = "range", trait = "towerRange", amount = 2, parent = "betterGattlerDesign", links = "parent", pos = {0,1}, }, { ref = "range10", name = "range", trait = "towerRange", amount = 2, parent = "range8", links = "parent", pos = {-1,1}, }, { ref = "range12", name = "range", trait = "towerRange", amount = 2, parent = "range10", links = "parent", pos = {-1,1}, } }, { { ref = "strongerSawblades", name = "stronger_sawblades", trait = "sawbladeLauncherPierce", amount = 1, tier = 1, parent = "range11", links = "parent", pos = {0,-1}, }, { ref = "pyroTraining", name = "pyro_training", trait = {"fireCubeFireRate", "fireCubeRange"}, amount = {10, 15}, tier = 1, parent = "range12", links = "parent", pos = {-1,0}, } }, { { ref = "motivation1", name = "motivation", trait = "towerEarlyFireRate", amount = 3, parent = "range11", links = "parent", pos = {1,1}, }, { ref = "motivation2", name = "motivation", trait = "towerEarlyFireRate", amount = 3, parent = "motivation1", links = "parent", pos = {1,1}, }, { ref = "motivation3", name = "motivation", trait = "towerEarlyFireRate", amount = 3, parent = "motivation2", links = "parent", pos = {1,1}, }, { ref = "motivation4", name = "motivation", trait = "towerEarlyFireRate", amount = 3, parent = "motivation3", links = "parent", pos = {1,1}, }, { ref = "motivation5", name = "motivation", trait = "towerEarlyFireRate", amount = 3, parent = "motivation4", links = "parent", pos = {1,1}, }, { ref = "motivation6", name = "motivation", trait = "towerEarlyFireRate", amount = 3, parent = "motivation5", links = "parent", pos = {1,1}, }, { ref = "motivation7", name = "motivation", trait = "towerEarlyFireRate", amount = 3, parent = "motivation6", links = "parent", pos = {1,1}, }, { ref = "motivation8", name = "motivation", trait = "towerEarlyFireRate", amount = 3, parent = "motivation7", links = "parent", pos = {1,1}, }, }, { { ref = "warHorn1", name = "war_horn", trait = "towerAbilityD3FireRate", amount = 5, parent = "strongerSawblades", links = {"strongerSawblades", "pyroTraining"}, pos = {1,0}, }, { ref = "warHorn2", name = "war_horn", trait = "towerAbilityD3FireRate", amount = 5, parent = "warHorn1", links = "parent", pos = {1,1}, }, { ref = "warHorn3", name = "war_horn", trait = "towerAbilityD3FireRate", amount = 5, parent = "warHorn2", links = "parent", pos = {1,1}, }, { ref = "warHorn4", name = "war_horn", trait = "towerAbilityD3FireRate", amount = 5, parent = "warHorn3", links = "parent", pos = {1,1}, }, { ref = "warHorn5", name = "war_horn", trait = "towerAbilityD3FireRate", amount = 5, parent = "warHorn4", links = "parent", pos = {1,1}, }, { ref = "warHorn6", name = "war_horn", trait = "towerAbilityD3FireRate", amount = 5, parent = "warHorn5", links = "parent", pos = {1,1}, }, { ref = "warHorn7", name = "war_horn", trait = "towerAbilityD3FireRate", amount = 5, parent = "warHorn6", links = "parent", pos = {1,1}, }, { ref = "warHorn8", name = "war_horn", trait = "towerAbilityD3FireRate", amount = 5, parent = "warHorn7", links = "parent", pos = {1,1}, }, }, { { ref = "mip1", name = "money_is_power", trait = "towerMoneyFireRate", amount = 0.15, parent = "range12", links = "parent", pos = {1,1}, }, { ref = "mip2", name = "money_is_power", trait = "towerMoneyFireRate", amount = 0.15, parent = "mip1", links = "parent", pos = {1,1}, }, { ref = "mip3", name = "money_is_power", trait = "towerMoneyFireRate", amount = 0.15, parent = "mip2", links = "parent", pos = {1,1}, }, { ref = "mip4", name = "money_is_power", trait = "towerMoneyFireRate", amount = 0.15, parent = "mip3", links = "parent", pos = {1,1}, }, { ref = "mip5", name = "money_is_power", trait = "towerMoneyFireRate", amount = 0.15, parent = "mip4", links = "parent", pos = {1,1}, }, { ref = "mip6", name = "money_is_power", trait = "towerMoneyFireRate", amount = 0.15, parent = "mip5", links = "parent", pos = {1,1}, }, { ref = "mip7", name = "money_is_power", trait = "towerMoneyFireRate", amount = 0.15, parent = "mip6", links = "parent", pos = {1,1}, }, { ref = "mip8", name = "money_is_power", trait = "towerMoneyFireRate", amount = 0.15, parent = "mip7", links = "parent", pos = {1,1}, }, }, { { ref = "betterDiffraction", name = "better_diffraction", trait = "microwaveGeneratorMicrowaveAngle", amount = 25, tier = 1, parent = "motivation8", links = "parent", pos = {1,0}, }, { ref = "fasterAssembly", name = "faster_assembly", trait = "turretFactoryAbilityCooldown", amount = -15, tier = 1, parent = "warHorn8", links = "parent", pos = {1,1}, }, { ref = "reshapedPills", name = "reshaped_pills", trait = {"pillLobberFlyTime", "pillLobberExploRadius", "pillLobberDirectDamage"}, amount = {-15, 15, 1}, tier = 1, parent = "mip8", links = "parent", pos = {0,1}, } }, { ref = "rcmb", name = "rainbow_coloured_master_beam", trait = "rainbowBeamerDamage", amount = 100, tier = 2, parent = "betterDiffraction", links = {"betterDiffraction", "fasterAssembly", "reshapedPills"}, pos = {1,0} }, }, { { ref = "dr1", name = "defence", trait = "targetDefence", amount = 2, parent = "physgun", links = "parent", pos = {4,4}, ang = 90 }, { { ref = "dr2", name = "defence", trait = "targetDefence", amount = 2, parent = "dr1", links = "parent", pos = {1.5,0}, }, { ref = "dr3", name = "defence", trait = "targetDefence", amount = 2, parent = "dr2", links = "parent", pos = {1.5,0}, }, { ref = "dr4", name = "defence", trait = "targetDefence", amount = 2, parent = "dr3", links = "parent", pos = {1.5,0}, }, { ref = "dr5", name = "defence", trait = "targetDefence", amount = 2, parent = "dr4", links = "parent", pos = {1.5,0}, }, { ref = "dr6", name = "defence", trait = "targetDefence", amount = 2, parent = "dr5", links = "parent", pos = {1.5,0}, }, { ref = "dr7", name = "defence", trait = "targetDefence", amount = 2, parent = "dr1", links = "parent", pos = {0,1.5}, }, { ref = "dr8", name = "defence", trait = "targetDefence", amount = 2, parent = "dr7", links = "parent", pos = {0,1.5}, }, { ref = "dr9", name = "defence", trait = "targetDefence", amount = 2, parent = "dr8", links = "parent", pos = {0,1.5}, }, { ref = "dr10", name = "defence", trait = "targetDefence", amount = 2, parent = "dr9", links = "parent", pos = {0,1.5}, }, { ref = "dr11", name = "defence", trait = "targetDefence", amount = 2, parent = "dr10", links = "parent", pos = {0,1.5}, } }, { { ref = "mh1", name = "maximum_health", trait = "targetHealth", amount = 2, parent = "dr1", links = "parent", pos = {1,1}, }, { ref = "oneShotProtection1", name = "one_shot_protection", trait = "targetOSP", amount = 1, tier = 1, parent = "dr6", links = "parent", pos = {1.5,0}, }, { ref = "regeneration1", name = "regeneration", trait = "targetRegeneration", amount = 1, tier = 1, parent = "mh1", links = "parent", pos = {1,1}, }, { ref = "oneShotProtection2", name = "one_shot_protection", trait = "targetOSP", amount = 1, tier = 1, parent = "dr11", links = "parent", pos = {0,1.5}, }, }, { { ref = "es1", name = "energy_shield", trait = "targetShield", amount = 0.5, parent = "oneShotProtection1", links = "parent", pos = {1,0.5}, }, { ref = "es2", name = "energy_shield", trait = "targetShield", amount = 0.5, parent = "es1", links = "parent", pos = {1,0.5}, }, { ref = "es3", name = "energy_shield", trait = "targetShield", amount = 0.5, parent = "es2", links = "parent", pos = {1,1}, }, { ref = "es4", name = "energy_shield", trait = "targetShield", amount = 0.5, parent = "es3", links = "parent", pos = {1,1}, }, { ref = "es5", name = "energy_shield", trait = "targetShield", amount = 0.5, parent = "es4", links = "parent", pos = {1,1}, }, { ref = "es6", name = "energy_shield", trait = "targetShield", amount = 0.5, parent = "oneShotProtection2", links = "parent", pos = {0.5,1}, }, { ref = "es7", name = "energy_shield", trait = "targetShield", amount = 0.5, parent = "es6", links = "parent", pos = {0.5,1}, }, { ref = "es8", name = "energy_shield", trait = "targetShield", amount = 0.5, parent = "es7", links = "parent", pos = {1,1}, }, { ref = "es9", name = "energy_shield", trait = "targetShield", amount = 0.5, parent = "es8", links = "parent", pos = {1,1}, }, { ref = "es10", name = "energy_shield", trait = "targetShield", amount = 0.5, parent = "es9", links = "parent", pos = {1,1}, }, }, { { ref = "mh2", name = "maximum_health", trait = "targetHealth", amount = 2, parent = "regeneration1", links = "parent", pos = {1,0}, }, { ref = "mh3", name = "maximum_health", trait = "targetHealth", amount = 2, parent = "mh2", links = "parent", pos = {1,0}, }, { ref = "mh4", name = "maximum_health", trait = "targetHealth", amount = 2, parent = "mh3", links = "parent", pos = {1,0}, }, { ref = "mh5", name = "maximum_health", trait = "targetHealth", amount = 2, parent = "mh4", links = "parent", pos = {1,0}, }, { ref = "mh6", name = "maximum_health", trait = "targetHealth", amount = 2, parent = "mh5", links = "parent", pos = {1,0}, }, { ref = "mh7", name = "maximum_health", trait = "targetHealth", amount = 2, parent = "regeneration1", links = "parent", pos = {0,1}, }, { ref = "mh8", name = "maximum_health", trait = "targetHealth", amount = 2, parent = "mh7", links = "parent", pos = {0,1}, }, { ref = "mh9", name = "maximum_health", trait = "targetHealth", amount = 2, parent = "mh8", links = "parent", pos = {0,1}, }, { ref = "mh10", name = "maximum_health", trait = "targetHealth", amount = 2, parent = "mh9", links = "parent", pos = {0,1}, }, { ref = "mh11", name = "maximum_health", trait = "targetHealth", amount = 2, parent = "mh10", links = "parent", pos = {0,1}, }, }, { { ref = "targetArmor1", name = "armor", trait = "targetArmor", amount = 1, tier = 1, parent = "es5", links = "parent", pos = {1,1}, }, { ref = "targetArmor2", name = "armor", trait = "targetArmor", amount = 1, tier = 1, parent = "es10", links = "parent", pos = {1,1}, }, { ref = "regeneration2", name = "regeneration", trait = "targetRegeneration", amount = 1, tier = 1, parent = "mh6", links = "parent", pos = {1,0}, }, { ref = "regeneration3", name = "regeneration", trait = "targetRegeneration", amount = 1, tier = 1, parent = "mh11", links = "parent", pos = {0,1}, }, }, { { ref = "dodge1", name = "desperate_measures", trait = "targetDodge", amount = 1, parent = "targetArmor1", links = "parent", pos = {-1,1}, }, { ref = "dodge2", name = "desperate_measures", trait = "targetDodge", amount = 1, parent = "dodge1", links = "parent", pos = {-1,0}, }, { ref = "dodge3", name = "desperate_measures", trait = "targetDodge", amount = 1, parent = "dodge2", links = "parent", pos = {-1,1}, }, { ref = "dodge4", name = "desperate_measures", trait = "targetDodge", amount = 1, parent = "dodge3", links = "parent", pos = {-1,1}, }, { ref = "dodge5", name = "desperate_measures", trait = "targetDodge", amount = 1, parent = "dodge4", links = "parent", pos = {0,1}, }, { ref = "dodge6", name = "desperate_measures", trait = "targetDodge", amount = 1, parent = "dodge5", links = "parent", pos = {0,1}, }, { ref = "dodge7", name = "desperate_measures", trait = "targetDodge", amount = 1, parent = "targetArmor2", links = "parent", pos = {1,-1}, }, { ref = "dodge8", name = "desperate_measures", trait = "targetDodge", amount = 1, parent = "dodge7", links = "parent", pos = {0,-1}, }, { ref = "dodge9", name = "desperate_measures", trait = "targetDodge", amount = 1, parent = "dodge8", links = "parent", pos = {1,-1}, }, { ref = "dodge10", name = "desperate_measures", trait = "targetDodge", amount = 1, parent = "dodge9", links = "parent", pos = {1,-1}, }, { ref = "dodge11", name = "desperate_measures", trait = "targetDodge", amount = 1, parent = "dodge10", links = "parent", pos = {1,0}, }, { ref = "dodge12", name = "desperate_measures", trait = "targetDodge", amount = 1, parent = "dodge11", links = "parent", pos = {1,0}, }, }, { { ref = "gh1", name = "golden_health", trait = "targetGoldenHealth", amount = 2, parent = "regeneration2", links = "parent", pos = {1,1}, }, { ref = "gh2", name = "golden_health", trait = "targetGoldenHealth", amount = 2, parent = "gh1", links = "parent", pos = {1,1}, }, { ref = "gh3", name = "golden_health", trait = "targetGoldenHealth", amount = 2, parent = "gh2", links = "parent", pos = {0,1}, }, { ref = "gh4", name = "golden_health", trait = "targetGoldenHealth", amount = 2, parent = "gh3", links = "parent", pos = {0,1}, }, { ref = "gh5", name = "golden_health", trait = "targetGoldenHealth", amount = 2, parent = "gh4", links = "parent", pos = {-1,1}, }, { ref = "gh6", name = "golden_health", trait = "targetGoldenHealth", amount = 2, parent = "gh5", links = "parent", pos = {-1,0}, }, { ref = "gh7", name = "golden_health", trait = "targetGoldenHealth", amount = 2, parent = "regeneration3", links = "parent", pos = {1,1}, }, { ref = "gh8", name = "golden_health", trait = "targetGoldenHealth", amount = 2, parent = "gh7", links = "parent", pos = {1,1}, }, { ref = "gh9", name = "golden_health", trait = "targetGoldenHealth", amount = 2, parent = "gh8", links = "parent", pos = {1,0}, }, { ref = "gh10", name = "golden_health", trait = "targetGoldenHealth", amount = 2, parent = "gh9", links = "parent", pos = {1,0}, }, { ref = "gh11", name = "golden_health", trait = "targetGoldenHealth", amount = 2, parent = "gh10", links = "parent", pos = {1,-1}, }, { ref = "gh12", name = "golden_health", trait = "targetGoldenHealth", amount = 2, parent = "gh11", links = "parent", pos = {0,-1}, }, }, { { ref = "queenOfHearts", name = "hail_the_heart_king", trait = "hoverballFactoryHealthAmplifier", amount = 20, tier = 1, parent = "gh6", links = {"gh6", "gh12"}, pos = {-1,0}, }, { ref = "gh13", name = "golden_health", trait = "targetGoldenHealth", amount = 2, parent = "queenOfHearts", links = "parent", pos = {1,1}, }, { ref = "gh14", name = "golden_health", trait = "targetGoldenHealth", amount = 2, parent = "gh13", links = "parent", pos = {1,1}, }, { ref = "gh15", name = "golden_health", trait = "targetGoldenHealth", amount = 2, parent = "gh14", links = "parent", pos = {1,1}, }, }, { ref = "ydihylh", name = "ydihylh", trait = {"targetHealth", "targetHealthEffectiveness"}, amount = {50, 100}, tier = 2, parent = "dodge6", links = {"dodge6", "dodge12", "gh15"}, pos = {0,1}, }, { ref = "mh12", name = "maximum_health", trait = "targetHealth", amount = 2, parent = "ydihylh", links = "parent", pos = {1,1}, }, { ref = "mh13", name = "maximum_health", trait = "targetHealth", amount = 2, parent = "mh12", links = "parent", pos = {1,1}, }, }, { { { ref = "gg1", name = "gold_glitters", trait = "cashFromBalloons", amount = 1, parent = "physgun", links = "parent", pos = {4,4}, ang = 180 }, { ref = "gg2", name = "gold_glitters", trait = "cashFromBalloons", amount = 1, parent = "gg1", links = "parent", pos = {1,1} }, { ref = "incomeGrower1", name = "income_grower", trait = "waveWaveIncome", amount = 1, tier = 1, parent = "gg2", links = "parent", pos = {1,1} }, }, { { ref = "wb1", name = "wave_bonus", trait = "waveIncome", amount = 2, parent = "incomeGrower1", links = "parent", pos = {-1,1} }, { ref = "wb2", name = "wave_bonus", trait = "waveIncome", amount = 2, parent = "wb1", links = {"incomeGrower1", "wb1"}, pos = {1,0} }, { ref = "wb3", name = "wave_bonus", trait = "waveIncome", amount = 2, parent = "wb1", links = "parent", pos = {0,1} }, { ref = "wb4", name = "wave_bonus", trait = "waveIncome", amount = 2, parent = "wb2", links = {"wb2", "wb3"}, pos = {0,1} }, { ref = "wb5", name = "wave_bonus", trait = "waveIncome", amount = 2, parent = "wb3", links = "parent", pos = {0,1} }, { ref = "wb6", name = "wave_bonus", trait = "waveIncome", amount = 2, parent = "wb4", links = {"wb4", "wb5"}, pos = {0,1} }, { ref = "wb7", name = "wave_bonus", trait = "waveIncome", amount = 2, parent = "wb5", links = "parent", pos = {0,1} }, { ref = "wb8", name = "wave_bonus", trait = "waveIncome", amount = 2, parent = "wb6", links = {"wb6", "wb7"}, pos = {0,1} }, { ref = "wb9", name = "wave_bonus", trait = "waveIncome", amount = 2, parent = "wb7", links = "parent", pos = {0,1} }, { ref = "wb10", name = "wave_bonus", trait = "waveIncome", amount = 2, parent = "wb8", links = {"wb8", "wb9"}, pos = {0,1} }, }, { ref = "incomeGrower2", name = "income_grower", trait = "waveWaveIncome", amount = 1, tier = 1, parent = "wb10", links = {"wb9", "wb10"}, pos = {0,1} }, { { ref = "sc1", name = "starting_cash", trait = "startingCash", amount = 25, parent = "incomeGrower1", links = {"incomeGrower1", "wb2"}, pos = {1,0} }, { ref = "sc2", name = "starting_cash", trait = "startingCash", amount = 25, parent = "sc1", links = {"incomeGrower1", "sc1"}, pos = {0,-1} }, { ref = "sc3", name = "starting_cash", trait = "startingCash", amount = 25, parent = "sc1", links = "parent", pos = {1,0} }, { ref = "sc4", name = "starting_cash", trait = "startingCash", amount = 25, parent = "sc2", links = {"sc2", "sc3"}, pos = {1,0} }, { ref = "sc5", name = "starting_cash", trait = "startingCash", amount = 25, parent = "sc3", links = "parent", pos = {1,0} }, { ref = "sc6", name = "starting_cash", trait = "startingCash", amount = 25, parent = "sc4", links = {"sc4", "sc5"}, pos = {1,0} }, { ref = "sc7", name = "starting_cash", trait = "startingCash", amount = 25, parent = "sc5", links = "parent", pos = {1,0} }, { ref = "sc8", name = "starting_cash", trait = "startingCash", amount = 25, parent = "sc6", links = {"sc6", "sc7"}, pos = {1,0} }, { ref = "sc9", name = "starting_cash", trait = "startingCash", amount = 25, parent = "sc7", links = "parent", pos = {1,0} }, { ref = "sc10", name = "starting_cash", trait = "startingCash", amount = 25, parent = "sc8", links = {"sc8", "sc9"}, pos = {1,0} }, }, { ref = "outsourcedHoverballParts", name = "outsourced_hoverball_parts", trait = "hoverballFactoryCosts", amount = -10, tier = 1, parent = "sc9", links = {"sc9", "sc10"}, pos = {1,0} }, { { ref = "gg3", name = "gold_glitters", trait = "cashFromBalloons", amount = 1, parent = "incomeGrower1", links = "parent", pos = {1,1}, }, { ref = "gg4", name = "gold_glitters", trait = "cashFromBalloons", amount = 1, parent = "gg3", links = "parent", pos = {1,1} }, { ref = "gg5", name = "gold_glitters", trait = "cashFromBalloons", amount = 1, parent = "gg4", links = "parent", pos = {1,1} }, { ref = "gg6", name = "gold_glitters", trait = "cashFromBalloons", amount = 1, parent = "gg5", links = "parent", pos = {1,1} }, { ref = "rainbowMassProduction", name = "rainbow_factorization", trait = "rainbowBeamerCosts", amount = -10, tier = 1, parent = "gg6", links = "parent", pos = {1,1} }, { ref = "cheaperMines", name = "cheaper_mines", trait = "proximityMineCosts", amount = -10, tier = 1, parent = "rainbowMassProduction", links = "parent", pos = {1,1} }, }, { { ref = "sc11", name = "starting_cash", trait = "startingCash", amount = 25, parent = "cheaperMines", links = {"cheaperMines", "rainbowMassProduction"}, pos = {0,-1} }, { ref = "sc12", name = "starting_cash", trait = "startingCash", amount = 25, parent = "sc11", links = {"cheaperMines", "sc11"}, pos = {1,0} }, { ref = "sc13", name = "starting_cash", trait = "startingCash", amount = 25, parent = "sc11", links = {"sc11", "rainbowMassProduction"}, pos = {0,-1} }, { ref = "sc14", name = "starting_cash", trait = "startingCash", amount = 25, parent = "sc12", links = {"sc12", "sc13"}, pos = {0,-1} }, { ref = "sc15", name = "starting_cash", trait = "startingCash", amount = 25, parent = "sc13", links = "parent", pos = {0,-1} }, { ref = "sc16", name = "starting_cash", trait = "startingCash", amount = 25, parent = "sc14", links = {"sc14", "sc15"}, pos = {0,-1} }, { ref = "sc17", name = "starting_cash", trait = "startingCash", amount = 25, parent = "sc15", links = "parent", pos = {0,-1} }, { ref = "sc18", name = "starting_cash", trait = "startingCash", amount = 25, parent = "sc16", links = {"sc16", "sc17"}, pos = {0,-1} }, { ref = "sc19", name = "starting_cash", trait = "startingCash", amount = 25, parent = "sc17", links = {"sc17", "outsourcedHoverballParts", "sc9"}, pos = {0,-1} }, { ref = "sc20", name = "starting_cash", trait = "startingCash", amount = 25, parent = "sc18", links = {"sc18", "sc19", "outsourcedHoverballParts"}, pos = {0,-1} }, }, { { ref = "tcg1", name = "tower_cash_generation", trait = "towerIncome", amount = 1, parent = "rainbowMassProduction", links = "parent", pos = {-1,1} }, { ref = "tcg2", name = "tower_cash_generation", trait = "towerIncome", amount = 1, parent = "tcg1", links = {"rainbowMassProduction", "tcg1", "cheaperMines"}, pos = {1,0} }, { ref = "tcg3", name = "tower_cash_generation", trait = "towerIncome", amount = 1, parent = "tcg1", links = "parent", pos = {0,1} }, { ref = "tcg4", name = "tower_cash_generation", trait = "towerIncome", amount = 1, parent = "tcg2", links = {"tcg2", "tcg3", "cheaperMines"}, pos = {0,1} }, { ref = "tcg5", name = "tower_cash_generation", trait = "towerIncome", amount = 1, parent = "tcg3", links = "parent", pos = {0,1} }, { ref = "tcg6", name = "tower_cash_generation", trait = "towerIncome", amount = 1, parent = "tcg4", links = {"tcg4", "tcg5"}, pos = {0,1} }, { ref = "tcg7", name = "tower_cash_generation", trait = "towerIncome", amount = 1, parent = "tcg5", links = "parent", pos = {0,1} }, { ref = "tcg8", name = "tower_cash_generation", trait = "towerIncome", amount = 1, parent = "tcg6", links = {"tcg6", "tcg7"}, pos = {0,1} }, { ref = "tcg9", name = "tower_cash_generation", trait = "towerIncome", amount = 1, parent = "tcg7", links = "parent", pos = {0,1} }, { ref = "tcg10", name = "tower_cash_generation", trait = "towerIncome", amount = 1, parent = "tcg8", links = {"tcg8", "tcg9"}, pos = {0,1} }, }, { ref = "valuableHoverballs", name = "valuable_hoverballs", trait = "hoverballFactoryIncome", amount = 15, tier = 1, parent = "tcg10", links = {"tcg9", "tcg10"}, pos = {0,1} }, { { ref = "tcg11", name = "tower_cash_generation", trait = "towerIncome", amount = 1, parent = "valuableHoverballs", links = "parent", pos = {1,1} }, { ref = "tcg12", name = "tower_cash_generation", trait = "towerIncome", amount = 1, parent = "tcg11", links = {"valuableHoverballs", "tcg10", "tcg11"}, pos = {0,-1} }, { ref = "tcg13", name = "tower_cash_generation", trait = "towerIncome", amount = 1, parent = "tcg11", links = "parent", pos = {1,0} }, { ref = "tcg14", name = "tower_cash_generation", trait = "towerIncome", amount = 1, parent = "tcg12", links = {"tcg12", "tcg13"}, pos = {1,0} }, { ref = "tcg15", name = "tower_cash_generation", trait = "towerIncome", amount = 1, parent = "tcg13", links = "parent", pos = {1,0} }, { ref = "tcg16", name = "tower_cash_generation", trait = "towerIncome", amount = 1, parent = "tcg14", links = {"tcg14", "tcg15"}, pos = {1,0} }, { ref = "tcg17", name = "tower_cash_generation", trait = "towerIncome", amount = 1, parent = "tcg15", links = "parent", pos = {1,0} }, { ref = "tcg18", name = "tower_cash_generation", trait = "towerIncome", amount = 1, parent = "tcg16", links = {"tcg16", "tcg17"}, pos = {1,0} }, { ref = "tcg19", name = "tower_cash_generation", trait = "towerIncome", amount = 1, parent = "tcg17", links = "parent", pos = {1,0} }, { ref = "tcg20", name = "tower_cash_generation", trait = "towerIncome", amount = 1, parent = "tcg18", links = {"tcg18", "tcg19"}, pos = {1,0} }, }, { { ref = "gg7", name = "gold_glitters", trait = "cashFromBalloons", amount = 1, parent = "cheaperMines", links = "parent", pos = {1,1}, }, { ref = "gg8", name = "gold_glitters", trait = "cashFromBalloons", amount = 1, parent = "gg7", links = "parent", pos = {1,1} }, { ref = "gg9", name = "gold_glitters", trait = "cashFromBalloons", amount = 1, parent = "gg8", links = "parent", pos = {1,1} }, { ref = "gg10", name = "gold_glitters", trait = "cashFromBalloons", amount = 1, parent = "gg9", links = "parent", pos = {1,1} }, { ref = "freeAllyPawn", name = "free_ally_pawn", trait = "allyPawnFirstFree", amount = 1, tier = 1, parent = "gg10", links = {"gg10", "tcg19", "tcg20"}, pos = {1,1} }, }, { { ref = "tc1", name = "tower_costs", trait = "towerCosts", amount = -1, parent = "freeAllyPawn", links = {"freeAllyPawn", "tcg20"}, pos = {0,-1} }, { ref = "tc2", name = "tower_costs", trait = "towerCosts", amount = -1, parent = "tc1", links = {"tc1", "freeAllyPawn"}, pos = {1,0} }, { ref = "tc3", name = "tower_costs", trait = "towerCosts", amount = -1, parent = "tc1", links = "parent", pos = {0,-1} }, { ref = "tc4", name = "tower_costs", trait = "towerCosts", amount = -1, parent = "tc2", links = {"tc2", "tc3"}, pos = {0,-1} }, { ref = "tc5", name = "tower_costs", trait = "towerCosts", amount = -1, parent = "tc3", links = "parent", pos = {0,-1} }, { ref = "tc6", name = "tower_costs", trait = "towerCosts", amount = -1, parent = "tc4", links = {"tc4", "tc5"}, pos = {0,-1} }, { ref = "tc7", name = "tower_costs", trait = "towerCosts", amount = -1, parent = "tc5", links = "parent", pos = {0,-1} }, { ref = "tc8", name = "tower_costs", trait = "towerCosts", amount = -1, parent = "tc6", links = {"tc6", "tc7"}, pos = {0,-1} }, { ref = "tc9", name = "tower_costs", trait = "towerCosts", amount = -1, parent = "tc7", links = "parent", pos = {0,-1} }, { ref = "tc10", name = "tower_costs", trait = "towerCosts", amount = -1, parent = "tc8", links = {"tc8", "tc9"}, pos = {0,-1} }, }, { ref = "modularMicrowaveEmitters", name = "modular_microwave_emitters", trait = "microwaveGeneratorCosts", amount = -10, tier = 1, parent = "tc9", links = {"tc9", "tc10"}, pos = {0,-1} }, { { ref = "gg11", name = "gold_glitters", trait = "cashFromBalloons", amount = 1, parent = "freeAllyPawn", links = "parent", pos = {1,1}, }, { ref = "atgig", name = "all_that_glitters_is_gold", trait = "gBlimpOuterHealthCash", amount = 1000, tier = 2, parent = "gg11", links = "parent", pos = {1,1}, }, }, }, { { { ref = "mgb1", name = "misconfigured_gballoons", trait = "gBalloonMissingProperty", amount = 1, links = "parent", pos = {4,4}, parent = "physgun", ang = 270 }, { ref = "mgb2", name = "misconfigured_gballoons", trait = "gBalloonMissingProperty", amount = 1, links = "parent", pos = {1,1}, parent = "mgb1", }, { ref = "mgb3", name = "misconfigured_gballoons", trait = "gBalloonMissingProperty", amount = 1, links = "parent", pos = {1,1}, parent = "mgb2", }, { ref = "mgb4", name = "misconfigured_gballoons", trait = "gBalloonMissingProperty", amount = 1, links = "parent", pos = {-1,1}, parent = "mgb3", }, { ref = "mgb5", name = "misconfigured_gballoons", trait = "gBalloonMissingProperty", amount = 1, links = "parent", pos = {-1,1}, parent = "mgb4", }, { ref = "mgb6", name = "misconfigured_gballoons", trait = "gBalloonMissingProperty", amount = 1, links = "parent", pos = {1,0}, parent = "mgb5", }, { ref = "mgb7", name = "misconfigured_gballoons", trait = "gBalloonMissingProperty", amount = 1, links = "parent", pos = {1,-1}, parent = "mgb3", }, { ref = "mgb8", name = "misconfigured_gballoons", trait = "gBalloonMissingProperty", amount = 1, links = "parent", pos = {1,-1}, parent = "mgb7", }, { ref = "mgb9", name = "misconfigured_gballoons", trait = "gBalloonMissingProperty", amount = 1, links = "parent", pos = {0,1}, parent = "mgb8", }, }, { { ref = "cloglessGlueNozzle", name = "clogless_glue_nozzle", trait = "bishopOfGlueFireRate", amount = 15, tier = 1, links = "parent", pos = {1,0}, parent = "mgb6" }, { ref = "excessFreezing", name = "excess_freezing", trait = "orbOfColdSpeedPercent", amount = -15, tier = 1, links = "parent", pos = {0,1}, parent = "mgb9" }, { ref = "gbs1", name = "gballoon_sabotage", trait = "gBalloonSpeed", amount = -1, links = {"cloglessGlueNozzle", "excessFreezing"}, pos = {1,-1}, parent = "cloglessGlueNozzle" } }, { { ref = "gbs2", name = "gballoon_sabotage", trait = "gBalloonSpeed", amount = -1, links = "parent", pos = {0,1}, parent = "cloglessGlueNozzle" }, { ref = "gbs3", name = "gballoon_sabotage", trait = "gBalloonSpeed", amount = -1, links = "parent", pos = {0,1}, parent = "gbs2" }, { ref = "gbs4", name = "gballoon_sabotage", trait = "gBalloonSpeed", amount = -1, links = "parent", pos = {0,1}, parent = "gbs3" }, { ref = "gbs5", name = "gballoon_sabotage", trait = "gBalloonSpeed", amount = -1, links = "parent", pos = {0,1}, parent = "gbs4" }, { ref = "gbs6", name = "gballoon_sabotage", trait = "gBalloonSpeed", amount = -1, links = "parent", pos = {0,1}, parent = "gbs5" }, { ref = "gbs7", name = "gballoon_sabotage", trait = "gBalloonSpeed", amount = -1, links = "parent", pos = {0.5,1}, parent = "gbs6" }, { ref = "gbs8", name = "gballoon_sabotage", trait = "gBalloonSpeed", amount = -1, links = "parent", pos = {0.5,1}, parent = "gbs7" }, }, { { ref = "gbs9", name = "gballoon_sabotage", trait = "gBalloonSpeed", amount = -1, links = "parent", pos = {1,0}, parent = "excessFreezing" }, { ref = "gbs10", name = "gballoon_sabotage", trait = "gBalloonSpeed", amount = -1, links = "parent", pos = {1,0}, parent = "gbs9" }, { ref = "gbs11", name = "gballoon_sabotage", trait = "gBalloonSpeed", amount = -1, links = "parent", pos = {1,0}, parent = "gbs10" }, { ref = "gbs12", name = "gballoon_sabotage", trait = "gBalloonSpeed", amount = -1, links = "parent", pos = {1,0}, parent = "gbs11" }, { ref = "gbs13", name = "gballoon_sabotage", trait = "gBalloonSpeed", amount = -1, links = "parent", pos = {1,0}, parent = "gbs12" }, { ref = "gbs14", name = "gballoon_sabotage", trait = "gBalloonSpeed", amount = -1, links = "parent", pos = {1,0.5}, parent = "gbs13" }, { ref = "gbs15", name = "gballoon_sabotage", trait = "gBalloonSpeed", amount = -1, links = "parent", pos = {1,0.5}, parent = "gbs14" }, }, { { ref = "notSoFast", name = "not_so_fast", trait = "gBalloonFastSpeed", amount = -15, tier = 1, links = "parent", pos = {1,1}, parent = "gbs8" }, { ref = "notSoHealthy", name = "not_so_healthy", trait = "gBalloonRegenRate", amount = -15, tier = 1, links = "parent", pos = {1,1}, parent = "gbs15" } }, { { ref = "agbs1", name = "advanced_gballoon_sabotage", trait = "gBlimpOuterHealth", amount = -1, links = "parent", pos = {1,-1}, parent = "notSoFast" }, { ref = "agbs2", name = "advanced_gballoon_sabotage", trait = "gBlimpOuterHealth", amount = -1, links = "parent", pos = {1,-1}, parent = "agbs1" }, { ref = "agbs3", name = "advanced_gballoon_sabotage", trait = "gBlimpOuterHealth", amount = -1, links = "parent", pos = {1,-1}, parent = "agbs2" }, { ref = "agbs4", name = "advanced_gballoon_sabotage", trait = "gBlimpOuterHealth", amount = -1, links = "parent", pos = {-1,1}, parent = "notSoHealthy" }, { ref = "agbs5", name = "advanced_gballoon_sabotage", trait = "gBlimpOuterHealth", amount = -1, links = "parent", pos = {-1,1}, parent = "agbs4" }, { ref = "agbs6", name = "advanced_gballoon_sabotage", trait = "gBlimpOuterHealth", amount = -1, links = "parent", pos = {-1,1}, parent = "agbs5" }, { ref = "causalityExplosions", name = "causality_explosions", trait = "gBalloonErrorExplosionUnimmune", amount = 1, tier = 1, links = {"agbs3", "agbs6"}, pos = {1,-1}, parent = "agbs3" }, }, { { ref = "agbs7", name = "advanced_gballoon_sabotage", trait = "gBlimpOuterHealth", amount = -1, links = "parent", pos = {1,1}, parent = "causalityExplosions" }, { ref = "agbs8", name = "advanced_gballoon_sabotage", trait = "gBlimpOuterHealth", amount = -1, links = "parent", pos = {1,1}, parent = "agbs7" }, { ref = "bigArmorMalfunction", name = "big_armor_malfunction", trait = "gBlimpArmoredArmor", amount = -2, tier = 1, links = "parent", pos = {1,1}, parent = "agbs8" }, { ref = "agbs9", name = "advanced_gballoon_sabotage", trait = "gBlimpOuterHealth", amount = -1, links = "parent", pos = {-1,-1}, parent = "causalityExplosions" }, { ref = "agbs10", name = "advanced_gballoon_sabotage", trait = "gBlimpOuterHealth", amount = -1, links = "parent", pos = {-1,-1}, parent = "agbs9" }, { ref = "fimtrtm", name = "fimtrtm", trait = "gBalloonFireGeneric", amount = 1, tier = 1, links = "parent", pos = {-1,-1}, parent = "agbs10" }, }, { { ref = "fab1", name = "fair_and_balanced", trait = "gBalloonCritChance", amount = 1, links = "parent", pos = {0,math.sqrt(2)}, parent = "causalityExplosions" }, { ref = "fab2", name = "fair_and_balanced", trait = "gBalloonCritChance", amount = 1, links = "parent", pos = {0,math.sqrt(2)}, parent = "fab1" }, { ref = "id1", name = "instant_deflator", trait = "gBalloonChildrenSuppressChance", amount = 5, tier = 1, links = "parent", pos = {0,math.sqrt(2)}, parent = "fab2" } }, { { ref = "fab3", name = "fair_and_balanced", trait = "gBalloonCritChance", amount = 1, links = "parent", pos = VectorTable(math.sqrt(2),0), parent = "causalityExplosions" }, { ref = "fab4", name = "fair_and_balanced", trait = "gBalloonCritChance", amount = 1, links = "parent", pos = VectorTable(math.sqrt(2),0), parent = "fab3" }, { ref = "id2", name = "instant_deflator", trait = "gBalloonChildrenSuppressChance", amount = 5, tier = 1, links = "parent", pos = VectorTable(math.sqrt(2),0), parent = "fab4" } }, { { ref = "fab5", name = "fair_and_balanced", trait = "gBalloonCritChance", amount = 1, links = "parent", pos = {0,-math.sqrt(2)}, parent = "causalityExplosions" }, { ref = "fab6", name = "fair_and_balanced", trait = "gBalloonCritChance", amount = 1, links = "parent", pos = {0,-math.sqrt(2)}, parent = "fab5" }, { ref = "id3", name = "instant_deflator", trait = "gBalloonChildrenSuppressChance", amount = 5, tier = 1, links = "parent", pos = {0,-math.sqrt(2)}, parent = "fab6" } }, { { ref = "fab7", name = "fair_and_balanced", trait = "gBalloonCritChance", amount = 1, links = "parent", pos = VectorTable(-math.sqrt(2),0), parent = "causalityExplosions" }, { ref = "fab8", name = "fair_and_balanced", trait = "gBalloonCritChance", amount = 1, links = "parent", pos = VectorTable(-math.sqrt(2),0), parent = "fab7" }, { ref = "id4", name = "instant_deflator", trait = "gBalloonChildrenSuppressChance", amount = 5, tier = 1, links = "parent", pos = VectorTable(-math.sqrt(2),0), parent = "fab8" } }, { { ref = "gbls1", name = "gblimp_sabotage", trait = "gBlimpSpeed", amount = -1, links = "parent", pos = {1,1}, parent = "notSoFast" }, { ref = "gbls2", name = "gblimp_sabotage", trait = "gBlimpSpeed", amount = -1, links = "parent", pos = {1,1}, parent = "gbls1" }, { ref = "gbls3", name = "gblimp_sabotage", trait = "gBlimpSpeed", amount = -1, links = "parent", pos = {1,0.5}, parent = "gbls2" }, { ref = "gbls4", name = "gblimp_sabotage", trait = "gBlimpSpeed", amount = -1, links = "parent", pos = {1,0.5}, parent = "gbls3" }, { ref = "gbls5", name = "gblimp_sabotage", trait = "gBlimpSpeed", amount = -1, links = "parent", pos = {1,0}, parent = "gbls4" }, { ref = "gbls6", name = "gblimp_sabotage", trait = "gBlimpSpeed", amount = -1, links = "parent", pos = {1,0}, parent = "gbls5" }, { ref = "gbls7", name = "gblimp_sabotage", trait = "gBlimpSpeed", amount = -1, links = "parent", pos = {1,-0.5}, parent = "gbls6" }, { ref = "gbls8", name = "gblimp_sabotage", trait = "gBlimpSpeed", amount = -1, links = "parent", pos = {1,-0.5}, parent = "gbls7" }, }, { { ref = "gbls9", name = "gblimp_sabotage", trait = "gBlimpSpeed", amount = -1, links = "parent", pos = {1,1}, parent = "notSoHealthy" }, { ref = "gbls10", name = "gblimp_sabotage", trait = "gBlimpSpeed", amount = -1, links = "parent", pos = {1,1}, parent = "gbls9" }, { ref = "gbls11", name = "gblimp_sabotage", trait = "gBlimpSpeed", amount = -1, links = "parent", pos = {0.5,1}, parent = "gbls10" }, { ref = "gbls12", name = "gblimp_sabotage", trait = "gBlimpSpeed", amount = -1, links = "parent", pos = {0.5,1}, parent = "gbls11" }, { ref = "gbls13", name = "gblimp_sabotage", trait = "gBlimpSpeed", amount = -1, links = "parent", pos = {0,1}, parent = "gbls12" }, { ref = "gbls14", name = "gblimp_sabotage", trait = "gBlimpSpeed", amount = -1, links = "parent", pos = {0,1}, parent = "gbls13" }, { ref = "gbls15", name = "gblimp_sabotage", trait = "gBlimpSpeed", amount = -1, links = "parent", pos = {-0.5,1}, parent = "gbls14" }, { ref = "gbls16", name = "gblimp_sabotage", trait = "gBlimpSpeed", amount = -1, links = "parent", pos = {-0.5,1}, parent = "gbls15" }, }, { ref = "hdtgpqa", name = "hdtgpqa", trait = "gBalloonOuterArmor", amount = -1, tier = 2, links = {"gbls8", "gbls16"}, pos = {1,-1}, parent = "gbls8" }, } }
nilq/small-lua-stack
null
local colors = { black = {gui = '#fbfbfb', cterm = '236'}, blue = {gui = '#94aadb', cterm = '39'}, cyan = { gui = '#89bdff', cterm = '38'}, green = {gui = '#babb63', cterm = '113'}, grey_comment = {gui = "#a8a8a8", cterm = "59"}, grey_cursor = {gui = "#bdbdbd", cterm = "236"}, grey_menu = {gui = "#d5d5d5", cterm = "237"}, purple = {gui = '#675e6e', cterm = '163'}, red = {gui = '#a03b1e', cterm = '166'}, white = {gui = '#f2f2f2', cterm = '251'}, yellow = {gui = '#c59820', cterm = '178'}, } local inactive = { guifg = colors.grey_comment.gui, guibg = colors.grey_cursor.gui, ctermfg = colors.grey_comment.cterm, ctermbg = colors.grey_cursor.cterm, } return { mode = { inactive = inactive, normal = { guifg = colors.black.gui, guibg = colors.blue.gui, ctermfg = colors.black.cterm, ctermbg = colors.blue.cterm, }, insert = { guifg = colors.black.gui, guibg = colors.green.gui, ctermfg = colors.black.cterm, ctermbg = colors.green.cterm, }, replace = { guifg = colors.black.gui, guibg = colors.cyan.gui, ctermfg = colors.black.cterm, ctermbg = colors.cyan.cterm, }, visual = { guifg = colors.black.gui, guibg = colors.purple.gui, ctermfg = colors.black.cterm, ctermbg = colors.purple.cterm, }, command = { guifg = colors.black.gui, guibg = colors.red.gui, ctermfg = colors.black.cterm, ctermbg = colors.red.cterm, }, }, low = { active = { guifg = colors.white.gui, guibg = colors.grey_cursor.gui, ctermfg = colors.white.cterm, ctermbg = colors.grey_cursor.cterm, }, inactive = inactive, }, med = { active = { guifg = colors.yellow.gui, guibg = colors.grey_cursor.gui, ctermfg = colors.yellow.cterm, ctermbg = colors.grey_cursor.cterm, }, inactive = inactive, }, high = { active = { guifg = colors.white.gui, guibg = colors.grey_menu.gui, ctermfg = colors.white.cterm, ctermbg = colors.grey_menu.cterm, }, inactive = inactive, }, error = { active = { guifg = colors.black.gui, guibg = colors.red.gui, ctermfg = colors.black.cterm, ctermbg = colors.red.cterm, }, inactive = inactive, }, warning = { active = { guifg = colors.black.gui, guibg = colors.yellow.gui, ctermfg = colors.black.cterm, ctermbg = colors.yellow.cterm, }, inactive = inactive, }, bufferline = { separator = inactive, current = { guifg = colors.black.gui, guibg = colors.blue.gui, ctermfg = colors.black.cterm, ctermbg = colors.blue.cterm, }, current_modified = { guifg = colors.black.gui, guibg = colors.green.gui, ctermfg = colors.black.cterm, ctermbg = colors.green.cterm, }, background = { guifg = colors.blue.gui, guibg = colors.black.gui, ctermfg = colors.blue.cterm, ctermbg = colors.black.cterm, }, background_modified = { guifg = colors.yellow.gui, guibg = colors.black.gui, ctermfg = colors.yellow.cterm, ctermbg = colors.black.cterm, }, }, }
nilq/small-lua-stack
null
script = {} function script.Initialize() script.maxSpeed = 2 script.updateTime = 0 script.panicDistance = 100 end function script.DoUpdate(delta) script.updateTime = script.updateTime - delta if script.updateTime <= 0 then local enemies = entity:GetNearbyEnemies() if enemies then local targetEntity = array.first(enemies) if targetEntity then script.target = vector.create(targetEntity.Position.X, targetEntity.Position.Y) end end local objective = entity:GetNearestTarget() if objective then script.objective = vector.create(objective.Position.X, objective.Position.Y) end script.updateTime = 120 end if script.objective then local movement = steering.flee(entity.Position, script.target, script.panicDistance, script.maxSpeed) if not movement or (movement.X == 0 and movement.Y == 0) then movement = steering.seek(entity.Position, script.objective, script.maxSpeed) end if movement then entity:Move(movement.X, movement.Y) end end end return script
nilq/small-lua-stack
null
--[[ # `the` = globals --]] local the= { cocomo = {lo=1,hi=1}, dec1list= {max = 1024, min=4}, divnum = { min = 0.5, cohen = 0.3, better = 1.05}, data = '../test/data/raw/' } return the
nilq/small-lua-stack
null
--[[----------------------------------------------------------------------------- * Infected Wars, an open source Garry's Mod game-mode. * * Infected Wars is the work of multiple authors, * a full list can be found in CONTRIBUTORS.md. * For more information, visit https://github.com/JarnoVgr/InfectedWars * * Infected Wars is free software: you can redistribute it and/or modify * it under the terms of the MIT License. * * A full copy of the MIT License can be found in LICENSE.txt. -----------------------------------------------------------------------------]] TEAM_UNDEAD = 3 TEAM_HUMAN = 4 if SERVER then AddCSLuaFile("sh_init.lua") AddCSLuaFile("sh_obj_player_extend.lua") AddCSLuaFile("sh_options.lua") AddCSLuaFile("sh_hands.lua") end include( 'sh_obj_player_extend.lua' ) include( 'sh_options.lua' ) include( 'sh_hands.lua' ) -- Don't change any of these GM.* variables GM.Name = "Infected Wars "..GM.Version GM.Author = "ClavusElite" GM.Email = "[email protected]" GM.Website = "www.clavusstudios.com" COLOR_UNDEAD = Color(200,40,40,255) COLOR_HUMAN = Color(0,90,200,255) team.SetUp(TEAM_UNDEAD, "Undead Legion", COLOR_UNDEAD) team.SetUp(TEAM_HUMAN, "Special Forces", COLOR_HUMAN) for k=1,#HumanClass do util.PrecacheModel(HumanClass[k].Model) end for k=1,#UndeadClass do util.PrecacheModel(UndeadClass[k].Model) end util.PrecacheSound("npc/strider/fire.wav") util.PrecacheSound("weapons/physcannon/superphys_launch2.wav") for k=1, 4 do util.PrecacheSound("physics/body/body_medium_impact_soft"..k..".wav") end HumanGibs = {"models/gibs/antlion_gib_medium_2.mdl", "models/gibs/Antlion_gib_Large_1.mdl", "models/gibs/Strider_Gib4.mdl", "models/gibs/HGIBS.mdl", "models/gibs/HGIBS_rib.mdl", "models/gibs/HGIBS_scapula.mdl", "models/gibs/HGIBS_spine.mdl" } for k, v in pairs( HumanGibs ) do util.PrecacheModel( v ) end for k, v in pairs( suitsData ) do for j, prop in pairs(v.suit) do util.PrecacheModel( prop.model ) end end TurretStatus = { inactive = 1, active = 2, destroyed = 3 } /*for _, funcname in pairs({"Exists", "ExistsEx", "Read", "Size", "IsDir", "Find"}) do local old = file[funcname] if not old then continue end file[funcname] = function(a, b) if a and not b and (string.sub(a, 1, 3) == "../" or string.sub(a, 1, 3) == "..\\") then b = true a = string.sub(a, 4) end return old(a, b) end end*/ /*--------------------------------------------------------- Name: gamemode:PropBreak( ) Desc: Prop has been broken ---------------------------------------------------------*/ function GM:PropBreak( attacker, prop ) end /*--------------------------------------------------------- Name: gamemode:PhysgunPickup( ) Desc: Return true if player can pickup entity ---------------------------------------------------------*/ function GM:PhysgunPickup( ply, ent ) // Don't pick up players --what if we do? --if ( ent:GetClass() == "player" ) then return false end return true end /*--------------------------------------------------------- Name: gamemode:GravGunPunt( ) Desc: We're about to punt an entity (primary fire). Return true if we're allowed to. ---------------------------------------------------------*/ function GM:GravGunPunt( ply, ent ) return true end /* Checks if it's a valid title */ local validchars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789><:;[]/()!?.,@#$%^&*-_=+ " local forbiddenwords = { "admin", "moderator", "host", "server" } function ValidTitle( pl, str ) // 24 character limit if not str then return false end if (string.len(str) > 24) then return false end for i = 1, string.len( str ) do local char = string.sub( str, i, i ) if not string.find(validchars,char) then return false end end if not ((CLIENT and PlayerIsAdmin) or (SERVER and pl:IsAdmin())) then for k, word in pairs(forbiddenwords) do if string.find(string.lower(str),word) then return false end end end return true end function util.Blood(pos, amount, dir, force, noprediction) local effectdata = EffectData() effectdata:SetOrigin(pos) effectdata:SetMagnitude(amount) effectdata:SetNormal(dir) effectdata:SetScale(math.max(128, force)) util.Effect("bloodstream", effectdata, nil, noprediction) end /* Thank you Garry for this great function in GMod update 65 */ function GM:ShouldCollide( ent1, ent2 ) if ent1:IsPlayer() and ent2:IsPlayer() and SOFT_COLLISIONS then local collide = ent1:Team() != ent2:Team() if SERVER and !collide then local pl, other_pl = ent1, ent2 if not pl.LastMove then pl.LastMove = 0 end if not other_pl.LastMove then other_pl.LastMove = 0 end if pl:GetVelocity():Length() > 1 then pl.LastMove = CurTime() end if other_pl:GetVelocity():Length() > 1 then other_pl.LastMove = CurTime() end local dis = pl:GetPos():Distance(other_pl:GetPos()) if dis < 20 then local pushVec local force = 70 - (70*0.3) * dis/20 if pl.LastMove < other_pl.LastMove then pushVec = other_pl:GetPos()-pl:GetPos() pushVec.z = 0 pushVec = pushVec:GetNormal() * force other_pl:SetVelocity(pushVec) elseif pl.LastMove > other_pl.LastMove then pushVec = pl:GetPos()-other_pl:GetPos() pushVec.z = 0 pushVec = pushVec:GetNormal() * force pl:SetVelocity(pushVec) else pushVec = other_pl:GetPos()-pl:GetPos() if pushVec == Vector(0,0,0) then pushVec = Vector(1,0,0) end pushVec.z = 0 pushVec = pushVec:GetNormal() * force other_pl:SetVelocity(pushVec) pl:SetVelocity(pushVec*(-1)) end end end return collide end return true end if (SERVER) then /*--------------------------------------------------------- Name: gamemode:GravGunPickupAllowed( ) Desc: Return true if we're allowed to pickup entity ---------------------------------------------------------*/ function GM:GravGunPickupAllowed( ply, ent ) return true end /*--------------------------------------------------------- Name: gamemode:GravGunOnPickedUp( ) Desc: The entity has been picked up ---------------------------------------------------------*/ function GM:GravGunOnPickedUp( ply, ent ) end /*--------------------------------------------------------- Name: gamemode:GravGunOnDropped( ) Desc: The entity has been dropped ---------------------------------------------------------*/ function GM:GravGunOnDropped( ply, ent ) end end --Add new footsteps sounds here function GM:PlayerFootstep( ply, pos, foot, sound, volume, rf ) if ply:Team() == TEAM_HUMAN then local cls = ply:GetPlayerClass() or 1 if HumanClass and HumanClass[cls or 1] and HumanClass[cls or 1].FootSounds then local nr = #HumanClass[cls or 1].FootSounds if nr>0 then//and math.random(0,1) == foot ply:EmitSound(HumanClass[cls].FootSounds[foot+1],math.random(3,9),100) return true end end end return false end function GM:PlayerStepSoundTime( ply, iType, bWalking ) local fStepTime = 350 local fMaxSpeed = ply:GetMaxSpeed() if ( iType == STEPSOUNDTIME_NORMAL || iType == STEPSOUNDTIME_WATER_FOOT ) then if ( fMaxSpeed <= 100 ) then fStepTime = 400 elseif ( fMaxSpeed <= 300 ) then fStepTime = 350 else fStepTime = 250 end if ply:Team() == TEAM_HUMAN then local cls = ply:GetPlayerClass() or 1 if HumanClass and HumanClass[cls or 1] and HumanClass[cls or 1].FootSounds then local nr = #HumanClass[cls or 1].FootSounds if nr>0 then fStepTime = 415 end end end elseif ( iType == STEPSOUNDTIME_ON_LADDER ) then fStepTime = 450 elseif ( iType == STEPSOUNDTIME_WATER_KNEE ) then fStepTime = 600 end // Step slower if crouching if ( ply:Crouching() ) then fStepTime = fStepTime + 50 end return fStepTime end
nilq/small-lua-stack
null
module('love.sound') function newDecoder() end function newSoundData() end
nilq/small-lua-stack
null
-- Invalid module (syntax error) for utils.load_module_if_exists unit tests. -- Assert that load_module_if_exists throws an error helps for development, where one could -- be confused as to the reason why his or her plugin doesn't load. (not implemented or has an error) local a = "hello",
nilq/small-lua-stack
null
COLOR_HALFLIFE = Color(251,126,20)
nilq/small-lua-stack
null
local ls = require('luasnip') ls.snippets = { -- When trying to expand a snippet, luasnip first searches the tables for -- each filetype specified in 'filetype' followed by 'all'. -- If ie. the filetype is 'lua.c' -- - luasnip.lua -- - luasnip.c -- - luasnip.all -- are searched in that order. all = {} } -- Beside defining your own snippets you can also load snippets from 'vscode-like' packages -- that expose snippets in json files, for example <https://github.com/rafamadriz/friendly-snippets>. -- Mind that this will extend `ls.snippets` so you need to do it after your own snippets or you -- will need to extend the table yourself instead of setting a new one. -- Lazy loading so you only get in memory snippets of languages you use require('luasnip/loaders/from_vscode').lazy_load({ include = { 'python', 'html', 'css', 'javascript', } })
nilq/small-lua-stack
null
-- lite-xl 1.16 local core = require "core" local command = require "core.command" local translate = require "core.doc.translate" local function gmatch_to_array(text, ptn) local res = {} for x in text:gmatch(ptn) do table.insert(res, x) end return res end local function tabularize_lines(lines, delim) local rows = {} local cols = {} -- split lines at delimiters and get maximum width of columns local ptn = "[^" .. delim:sub(1,1):gsub("%W", "%%%1") .. "]+" for i, line in ipairs(lines) do rows[i] = gmatch_to_array(line, ptn) for j, col in ipairs(rows[i]) do cols[j] = math.max(#col, cols[j] or 0) end end -- pad columns with space for _, row in ipairs(rows) do for i = 1, #row - 1 do row[i] = row[i] .. string.rep(" ", cols[i] - #row[i]) end end -- write columns back to lines array for i, line in ipairs(lines) do lines[i] = table.concat(rows[i], delim) end end command.add("core.docview", { ["tabularize:tabularize"] = function() core.command_view:enter("Tabularize On Delimiter", function(delim) if delim == "" then delim = " " end local doc = core.active_view.doc local line1, col1, line2, col2, swap = doc:get_selection(true) line1, col1 = doc:position_offset(line1, col1, translate.start_of_line) line2, col2 = doc:position_offset(line2, col2, translate.end_of_line) doc:set_selection(line1, col1, line2, col2, swap) doc:replace(function(text) local lines = gmatch_to_array(text, "[^\n]*\n?") tabularize_lines(lines, delim) return table.concat(lines) end) end) end, })
nilq/small-lua-stack
null
-- luacheck: globals audio display easing graphics lfs media native network Runtime system timer transition package.path = "./?.lua;" .. package.path local Composer = require "composer" -- hide the status bar display.setStatusBar (display.DefaultStatusBar) -- load menu screen Composer.gotoScene "vitesse.main"
nilq/small-lua-stack
null
bot_token = "239047385:AAEbPXGvm7Hs4mQS2CNx2AVOBLLa2Jo-Q_w" send_api = "https://api.telegram.org/bot"..bot_token bot_version = "1.7" sudo_name = "khajeh_amir" sudo_id = 216507730 sudo_user = "khajeh_amir" nerkh = "5"
nilq/small-lua-stack
null
-- User defined commands local commands = {} -- Use this template to add new commands. Replace XXXX and add the body: -- commands.XXXX = function (host, user, args) -- if args then -- -- What to do if called with format "!XXXX args" -- send_to_chat(host, "add a message to be posted to chat") -- else -- -- What to do if called with format "!XXXX" -- send_to_chat(host, "add a message to be posted to chat") -- end -- end commands.roll = function(host, user, args) if args then -- What to do if called with format "!roll args" send_to_chat(host, user .. " rolls the dice: " .. math.random(100)) return else -- What to do if called with format "!roll" send_to_chat(host, user .. " rolls the dice: " .. math.random(100)) end end local deaths = 0 commands.deaths = function(host, user, args) args = args or "" deaths = deaths + 1 local str = _channel .. " has died " .. deaths .. " times." if deaths > 10 then str = str .. " has reached bot500!" -- Overwatch top500 joke end send_to_chat(host, str) end math.randomseed(os.time()) math.random() math.random() math.random() return commands
nilq/small-lua-stack
null
--[==[ - Author: [email protected] - CreateTime: 2017-11-15 16:07:58 - Orgnization: #ORGNIZATION# - Description: --]==] local M = require("ezlua.module"):module() ----- CODE ----- function M.LuaAwake(injector) local self = M:new() injector:Inject(self) self.gameObject = injector.gameObject self.transform = self.gameObject.transform self.rigidbody = self.gameObject:GetComponent("Rigidbody") return self end function M:LuaStart() self.rigidbody.velocity = self.transform.forward * self.n_Speed end ----- CODE ----- return M
nilq/small-lua-stack
null
local __exports = LibStub:NewLibrary("ovale/scripts/ovale_trinkets_wod", 80300) if not __exports then return end __exports.registerWodTrinkets = function(OvaleScripts) local name = "ovale_trinkets_wod" local desc = "[6.2] Ovale: Trinkets (Warlords of Draenor)" local code = [[ # Trinkets from Warlords of Draenor. ### ### Legendary ring ### Define(legendary_ring_agility 124636) Define(legendary_ring_bonus_armor 124637) Define(legendary_ring_intellect 124635) Define(legendary_ring_spirit 124638) Define(legendary_ring_strength 124634) Define(etheralus_buff 187618) SpellInfo(etheralus_buff duration=15) Define(maalus_buff 187620) SpellInfo(maalus_buff duration=15) Define(nithramus_buff 187616) SpellInfo(nithramus_buff duration=15) Define(sanctus_buff 187617) SpellInfo(sanctus_buff duration=15) Define(thorasus_buff 187619) SpellInfo(thorasus_buff duration=15) ### ### Agility ### Define(call_of_conquest_buff 126690) SpellInfo(call_of_conquest_buff buff_cd=60 duration=20 stat=agility) Define(lucky_flip_buff 177597) SpellInfo(lucky_flip_buff buff_cd=120 duration=20 stat=agility) Define(surge_of_conquest_buff 126707) SpellInfo(surge_of_conquest_buff buff_cd=55 duration=20 stat=agility) Define(lucky_double_sided_coin 118876) ItemInfo(lucky_double_sided_coin buff=lucky_flip_buff) ItemList(primal_combatants_badge_of_conquest primal_combatants_badge_of_conquest_alliance primal_combatants_badge_of_conquest_horde) Define(primal_combatants_badge_of_conquest_alliance 115149) ItemInfo(primal_combatants_badge_of_conquest_alliance buff=call_of_conquest_buff) Define(primal_combatants_badge_of_conquest_horde 119926) ItemInfo(primal_combatants_badge_of_conquest_horde buff=call_of_conquest_buff) ItemList(primal_combatants_insignia_of_conquest primal_combatants_insignia_of_conquest_alliance primal_combatants_insignia_of_conquest_horde) Define(primal_combatants_insignia_of_conquest_alliance 115150) ItemInfo(primal_combatants_insignia_of_conquest_alliance buff=surge_of_conquest_buff) Define(primal_combatants_insignia_of_conquest_horde 119927) ItemInfo(primal_combatants_insignia_of_conquest_horde buff=surge_of_conquest_buff) ItemList(primal_gladiators_badge_of_conquest primal_gladiators_badge_of_conquest_alliance primal_gladiators_badge_of_conquest_horde) Define(primal_gladiators_badge_of_conquest_alliance 115749) ItemInfo(primal_gladiators_badge_of_conquest_alliance buff=call_of_conquest_buff) Define(primal_gladiators_badge_of_conquest_horde 111222) ItemInfo(primal_gladiators_badge_of_conquest_horde buff=call_of_conquest_buff) ItemList(primal_gladiators_insignia_of_conquest primal_gladiators_insignia_of_conquest_alliance primal_gladiators_insignia_of_conquest_horde) Define(primal_gladiators_insignia_of_conquest_alliance 115750) ItemInfo(primal_gladiators_insignia_of_conquest_alliance buff=surge_of_conquest_buff) Define(primal_gladiators_insignia_of_conquest_horde 111223) ItemInfo(primal_gladiators_insignia_of_conquest_horde buff=surge_of_conquest_buff) ### ### Bonus armor ### Define(gazing_eye_buff 177053) SpellInfo(gazing_eye_buff buff_cd=65 duration=10 stat=bonus_armor) Define(turnbuckle_terror_buff 176873) SpellInfo(turnbuckle_terror_buff buff_cd=120 duration=20 stat=bonus_armor) Define(evergaze_arcane_eidolon 113861) ItemInfo(evergaze_arcane_eidolon buff=gazing_eye_buff) Define(tablet_of_turnbuckle_teamwork 113905) ItemInfo(tablet_of_turnbuckle_teamwork buff=turnbuckle_terror_buff) ### ### Critical Strike ### Define(critical_strike_proc_buff 165830) SpellInfo(critical_strike_proc_buff buff_cd=65 duration=10 stat=critical_strike) Define(critical_strike_use_buff 165532) SpellInfo(critical_strike_use_buff buff_cd=120 duration=20 stat=critical_strike) Define(detonation_buff 177067) SpellInfo(177067 buff_cd=65 max_stacks=20 duration=10 stat=critical_strike) Define(howling_soul_buff 177046) SpellInfo(howling_soul_buff buff_cd=65 duration=10 stat=critical_strike) Define(immaculate_living_mushroom_buff 176978) SpellInfo(immaculate_living_mushroom_buff buff_cd=65 duration=10 stat=critical_strike) Define(nightmare_fire_buff 162919) SpellInfo(nightmare_fire_buff buff_cd=115 duration=20 stat=critical_strike) Define(spirit_of_the_warlords_buff 162915) SpellInfo(spirit_of_the_warlords_buff buff_cd=115 duration=20 stat=critical_strike) Define(stoneheart_idol_buff 176982) SpellInfo(stoneheart_idol_buff buff_cd=65 duration=10 stat=critical_strike) Define(strength_of_steel_buff 162917) SpellInfo(strength_of_steel_buff buff_cd=115 duration=20 stat=critical_strike) Define(tectus_heartbeat_buff 177040) SpellInfo(tectus_heartbeat_buff buff_cd=65 duration=10 stat=critical_strike) Define(bloodcasters_charm 118777) ItemInfo(bloodcasters_charm buff=critical_strike_proc_buff) Define(bonemaws_big_toe 110012) ItemInfo(bonemaws_big_toe buff=critical_strike_use_buff) Define(goren_soul_repository 119194) ItemInfo(goren_soul_repository buff=howling_soul_buff) Define(humming_blackiron_trigger 113985) ItemInfo(humming_blackiron_trigger buff=detonation_buff) Define(immaculate_living_mushroom 116291) ItemInfo(immaculate_living_mushroom buff=immaculate_living_mushroom_buff) Define(knights_badge 112319) ItemInfo(knights_badge buff=strength_of_steel_buff) Define(munificent_emblem_of_terror 114427) ItemInfo(munificent_emblem_of_terror buff=critical_strike_proc_buff) Define(sandmans_pouch 112320) ItemInfo(sandmans_pouch buff=nightmare_fire_buff) Define(skull_of_war 112318) ItemInfo(skull_of_war buff=spirit_of_the_warlords_buff) Define(stoneheart_idol 116318) ItemInfo(stoneheart_idol buff=stoneheart_idol_buff) Define(tectus_beating_heart 113645) ItemInfo(tectus_beating_heart buff=tectus_heartbeat_buff) Define(voidmenders_shadowgem 110007) ItemInfo(voidmenders_shadowgem buff=critical_strike_use_buff) ### ### Haste ### Define(battering_buff 177102) SpellInfo(battering_buff buff_cd=65 duration=10 max_stacks=20 stat=haste) Define(caustic_healing_buff 176879) SpellInfo(caustic_healing_buff buff_cd=120 duration=20 stat=haste) Define(haste_proc_buff 165822) SpellInfo(haste_proc_buff buff_cd=65 duration=10 stat=haste) Define(haste_use_buff 165531) SpellInfo(haste_use_buff buff_cd=120 duration=20 stat=haste) Define(heart_of_the_fury_buff 176980) SpellInfo(heart_of_the_fury_buff buff_cd=65 duration=10 stat=haste) Define(instability_buff 177051) SpellInfo(instability_buff buff_cd=65 duration=10 stat=haste) Define(meaty_dragonspine_trophy_buff 177035) SpellInfo(meaty_dragonspine_trophy_buff buff_cd=65 duration=10 stat=haste) Define(sanitizing_buff 177086) SpellInfo(sanitizing_buff buff_cd=65 duration=10 max_stacks=20 stat=haste) Define(turbulent_focusing_crystal_buff 176882) SpellInfo(turbulent_focusing_crystal_buff buff_cd=120 duration=20 stat=haste) Define(turbulent_seal_of_defiance_buff 176885) SpellInfo(turbulent_seal_of_defiance_buff buff_cd=90 duration=15 stat=haste) Define(void_shards_buff 176875) SpellInfo(void_shards_buff buff_cd=120 duration=20 stat=haste) Define(auto_repairing_autoclave 113986) ItemInfo(auto_repairing_autoclave buff=sanitizing_buff) Define(battering_talisman 113987) ItemInfo(battering_talisman buff=battering_buff) Define(darmacs_unstable_talisman 113948) ItemInfo(darmacs_unstable_talisman buff=instability_buff) Define(emblem_of_caustic_healing 113842) ItemInfo(emblem_of_caustic_healing buff=caustic_healing_buff) Define(fleshrenders_meathook 110002) ItemInfo(fleshrenders_meathook buff=haste_use_buff) Define(furyheart_talisman 116315) ItemInfo(furyheart_talisman buff=heart_of_the_fury_buff) Define(meaty_dragonspine_trophy 118114) ItemInfo(meaty_dragonspine_trophy buff=meaty_dragonspine_trophy_buff) Define(munificent_bonds_of_fury 114430) ItemInfo(munificent_bonds_of_fury buff=haste_proc_buff) Define(shards_of_nothing 113835) ItemInfo(shards_of_nothing buff=void_shards_buff) Define(spores_of_alacrity 110014) ItemInfo(spores_of_alacrity buff=haste_proc_buff) Define(turbulent_focusing_crystal 114489) ItemInfo(turbulent_focusing_crystal buff=turbulent_focusing_crystal_buff) Define(turbulent_seal_of_defiance 114492) ItemInfo(turbulent_seal_of_defiance buff=turbulent_seal_of_defiance_buff) Define(witherbarks_branch 109999) ItemInfo(witherbarks_branch buff=haste_proc_buff) ### ### Intellect ### Define(call_of_dominance_buff 126683) SpellInfo(call_of_dominance_buff buff_cd=60 duration=20 stat=intellect) Define(surge_of_dominance_buff 126705) SpellInfo(surge_of_dominance_buff buff_cd=55 duration=20 stat=intellect) ItemList(primal_combatants_badge_of_dominance primal_combatants_badge_of_dominance_alliance primal_combatants_badge_of_dominance_horde) Define(primal_combatants_badge_of_dominance_alliance 115154) ItemInfo(primal_combatants_badge_of_dominance_alliance buff=call_of_dominance_buff) Define(primal_combatants_badge_of_dominance_horde 119931) ItemInfo(primal_combatants_badge_of_dominance_horde buff=call_of_dominance_buff) ItemList(primal_combatants_insignia_of_dominance primal_combatants_insignia_of_dominance_alliance primal_combatants_insignia_of_dominance_horde) Define(primal_combatants_insignia_of_dominance_alliance 115155) ItemInfo(primal_combatants_insignia_of_dominance_alliance buff=surge_of_dominance_buff) Define(primal_combatants_insignia_of_dominance_horde 119932) ItemInfo(primal_combatants_insignia_of_dominance_horde buff=surge_of_dominance_buff) ItemList(primal_gladiators_badge_of_dominance primal_gladiators_badge_of_dominance_alliance primal_gladiators_badge_of_dominance_horde) Define(primal_gladiators_badge_of_dominance_alliance 115754) ItemInfo(primal_gladiators_badge_of_dominance_alliance buff=call_of_dominance_buff) Define(primal_gladiators_badge_of_dominance_horde 111227) ItemInfo(primal_gladiators_badge_of_dominance_horde buff=call_of_dominance_buff) ItemList(primal_gladiators_insignia_of_dominance primal_gladiators_insignia_of_dominance_alliance primal_gladiators_insignia_of_dominance_horde) Define(primal_gladiators_insignia_of_dominance_alliance 115755) ItemInfo(primal_gladiators_insignia_of_dominance_alliance buff=surge_of_dominance_buff) Define(primal_gladiators_insignia_of_dominance_horde 111228) ItemInfo(primal_gladiators_insignia_of_dominance_horde buff=surge_of_dominance_buff) ### ### Mastery ### Define(blast_furnace_buff 177056) SpellInfo(blast_furnace_buff buff_cd=65 duration=10 stat=mastery) Define(mastery_proc_buff 165824) SpellInfo(mastery_proc_buff buff_cd=65 duration=10 stat=mastery) Define(mastery_short_use_buff 165535) SpellInfo(mastery_short_use_buff buff_cd=90 duration=15 stat=mastery) Define(mastery_use_buff 165485) SpellInfo(mastery_use_buff buff_cd=120 duration=20 stat=mastery) Define(screaming_spirits_buff 177042) SpellInfo(screaming_spirits_buff buff_cd=65 duration=10 stat=mastery) Define(turbulent_vial_of_toxin_buff 176883) SpellInfo(turbulent_vial_of_toxin_buff buff_cd=90 duration=15 stat=mastery) Define(turbulent_relic_of_mendacity_buff 176884) SpellInfo(turbulent_relic_of_mendacity_buff buff_cd=90 duration=15 stat=mastery) Define(vision_of_the_cyclops_buff 176876) SpellInfo(vision_of_the_cyclops_buff buff_cd=120 duration=20 stat=mastery) Define(blast_furnace_door 113893) ItemInfo(blast_furnace_door buff=blast_furnace_buff) Define(horn_of_screaming_spirits 119193) ItemInfo(horn_of_screaming_spirits buff=screaming_spirits_buff) Define(kihras_adrenaline_injector 109997) ItemInfo(kihras_adrenaline_injector buff=mastery_use_buff) Define(kyraks_vileblood_serum 110018) ItemInfo(kyraks_vileblood_serum buff=mastery_short_use_buff) Define(munificent_censer_of_tranquility 114429) ItemInfo(munificent_censer_of_tranquility buff=mastery_proc_buff) Define(petrified_flesh_eating_spore 113663) ItemInfo(petrified_flesh_eating_spore buff=mastery_proc_buff) Define(pols_blinded_eye 113834) ItemInfo(pols_blinded_eye buff=vision_of_the_cyclops_buff) Define(tharbeks_lucky_pebble 110008) ItemInfo(tharbeks_lucky_pebble buff=mastery_short_use_buff) Define(turbulent_vial_of_toxin 114488) ItemInfo(turbulent_vial_of_toxin buff=turbulent_vial_of_toxin_buff) Define(turbulent_relic_of_mendacity 114490) ItemInfo(turbulent_relic_of_mendacity buff=turbulent_relic_of_mendacity_buff) Define(xeritacs_unhatched_egg_sac 110019) ItemInfo(xeritacs_unhatched_egg_sac buff=mastery_proc_buff) ### ### Crit Strike (Multistrike removed) ### Define(blackheart_enforcers_medallion_buff 176984) SpellInfo(blackheart_enforcers_medallion_buff buff_cd=65 duration=10 stat=critical_strike) Define(balanced_fate_buff 177038) SpellInfo(balanced_fate_buff buff_cd=65 duration=10 stat=critical_strike) Define(convulsive_shadows_buff 176874) SpellInfo(convulsive_shadows_buff buff_cd=120 duration=15 stat=critical_strike) Define(elemental_shield_buff 177063) SpellInfo(elemental_shield_buff buff_cd=65 duration=10 stat=critical_strike) Define(forgemasters_vigor_buff 177096) SpellInfo(forgemasters_vigor_buff buff_cd=65 duration=10 max_stacks=20 stat=critical_strike) Define(lub_dub_buff 176878) SpellInfo(lub_dub_buff buff_cd=120 duration=20 stat=critical_strike) Define(molten_metal_buff 177081) SpellInfo(molten_metal_buff buff_cd=65 duration=10 max_stacks=20 stat=critical_strike) Define(multi_strike_buff 165542) SpellInfo(multi_strike_use_buff buff_cd=90 duration=15 stat=critical_strike) Define(crit_strike_proc_buff 165832) SpellInfo(crit_strike_proc_buff buff_cd=65 duration=10 stat=critical_strike) Define(turbulent_emblem_buff 176881) SpellInfo(turbulent_emblem_buff buff_cd=120 duration=20 stat=critical_strike) Define(beating_heart_of_the_mountain 113931) ItemInfo(beating_heart_of_the_mountain buff=lub_dub_buff) Define(blackheart_enforcers_medallion 116314) ItemInfo(blackheart_enforcers_medallion buff=blackheart_enforcers_medallion_buff) Define(blackiron_micro_crucible 113984) ItemInfo(blackiron_micro_crucible buff=molten_metal_buff) Define(coagulated_genesaur_blood 110004) ItemInfo(coagulated_genesaur_blood buff=crit_strike_proc_buff) Define(elementalists_shielding_talisman 113889) ItemInfo(elementalists_shielding_talisman buff=elemental_shield_buff) Define(forgemasters_insignia 113983) ItemInfo(forgemasters_insignia buff=forgemasters_vigor_buff) Define(gorashans_lodestone_spike 109998) ItemInfo(gorashans_lodestone_spike buff=multi_strike_buff) Define(scales_of_doom 113612) ItemInfo(scales_of_doom buff=balanced_fate_buff) Define(turbulent_emblem 114491) ItemInfo(turbulent_emblem buff=turbulent_emblem_buff) Define(vial_of_convulsive_shadows 113969) ItemInfo(vial_of_convulsive_shadows buff=convulsive_shadows_buff) ### ### Spellpower ### Define(sudden_clarity_buff 177594) SpellInfo(sudden_clarity_buff buff_cd=120 duration=20 stat=spellpower) Define(copelands_clarity 118878) ItemInfo(copelands_clarity buff=sudden_clarity_buff) ### ### Spirit ### Define(squeak_squeak_buff 177060) SpellInfo(squeak_squeak_buff buff_cd=65 duration=10 stat=spirit) Define(visions_of_the_future_buff 162913) SpellInfo(visions_of_the_future_buff buff_cd=115 duration=20 stat=spirit) Define(ironspike_chew_toy 119192) ItemInfo(ironspike_chew_toy buff=squeak_squeak_buff) Define(winged_hourglass 112317) ItemInfo(winged_hourglass buff=visions_of_the_future_buff) ### ### Strength ### Define(call_of_victory_buff 126679) SpellInfo(call_of_victory_buff buff_cd=60 duration=20 stat=strength) Define(surge_of_victory_buff 126700) SpellInfo(surge_of_victory_buff buff_cd=55 duration=20 stat=strength) Define(sword_technique_buff 177189) SpellInfo(sword_technique_buff buff_cd=90 duration=10 stat=strength) ItemList(primal_combatants_badge_of_victory primal_combatants_badge_of_victory_alliance primal_combatants_badge_of_victory_horde) Define(primal_combatants_badge_of_victory_alliance 115159) ItemInfo(primal_combatants_badge_of_victory_alliance buff=call_of_victory_buff) Define(primal_combatants_badge_of_victory_horde 119936) ItemInfo(primal_combatants_badge_of_victory_horde buff=call_of_victory_buff) ItemList(primal_combatants_insignia_of_victory primal_combatants_insignia_of_victory_alliance primal_combatants_insignia_of_victory_horde) Define(primal_combatants_insignia_of_victory_alliance 115160) ItemInfo(primal_combatants_insignia_of_victory_alliance buff=surge_of_victory_buff) Define(primal_combatants_insignia_of_victory_horde 119937) ItemInfo(primal_combatants_insignia_of_victory_horde buff=surge_of_victory_buff) ItemList(primal_gladiators_badge_of_victory primal_gladiators_badge_of_victory_alliance primal_gladiators_badge_of_victory_horde) Define(primal_gladiators_badge_of_victory_alliance 115759) ItemInfo(primal_gladiators_badge_of_victory_alliance buff=call_of_victory_buff) Define(primal_gladiators_badge_of_victory_horde 111232) ItemInfo(primal_gladiators_badge_of_victory_horde buff=call_of_victory_buff) ItemList(primal_gladiators_insignia_of_victory primal_gladiators_insignia_of_victory_alliance primal_gladiators_insignia_of_victory_horde) Define(primal_gladiators_insignia_of_victory_alliance 115760) ItemInfo(primal_gladiators_insignia_of_victory_alliance buff=surge_of_victory_buff) Define(primal_gladiators_insignia_of_victory_horde 111233) ItemInfo(primal_gladiators_insignia_of_victory_horde buff=surge_of_victory_buff) Define(scabbard_of_kyanos 118882) ItemInfo(scabbard_of_kyanos buff=sword_technique_buff) ### ### Versatility ### Define(mote_of_the_mountain_buff 176974) SpellInfo(mote_of_the_mountain_buff buff_cd=65 duration=10 stat=versatility) Define(versatility_proc_buff 165833) SpellInfo(versatility_proc_buff buff_cd=65 duration=10 stat=versatility) Define(versatility_short_use_buff 165543) SpellInfo(versatility_short_use_buff buff_cd=90 duration=15 stat=versatility) Define(versatility_use_buff 165534) SpellInfo(versatility_use_buff buff_cd=120 duration=20 stat=versatility) Define(emberscale_talisman 110013) ItemInfo(emberscale_talisman buff=versatility_short_use_buff) Define(enforcers_stun_grenade 110017) ItemInfo(enforcers_stun_grenade buff=versatility_use_buff) Define(leaf_of_the_ancient_protectors 110009) ItemInfo(leaf_of_the_ancient_protectors buff=versatility_proc_buff) Define(mote_of_the_mountain 116292) ItemInfo(mote_of_the_mountain buff=mote_of_the_mountain_buff) Define(munificent_orb_of_ice 114428) ItemInfo(munificent_orb_of_ice buff=versatility_proc_buff) Define(munificent_soul_of_compassion 114431) ItemInfo(munificent_soul_of_compassion buff=versatility_proc_buff) Define(ragewings_firefang 110003) ItemInfo(ragewings_firefang buff=versatility_short_use_buff) ### ### Miscellaneous ### Define(empty_drinking_horn 124238) Define(soul_capacitor 124225) ItemInfo(soul_capacitor buff=spirit_shift_buff) Define(spirit_shift_buff 184293) SpellInfo(spirit_shift_buff buff_cd=60 duration=10) ]] OvaleScripts:RegisterScript(nil, nil, name, desc, code, "include") end
nilq/small-lua-stack
null
require "socket" math.randomseed(socket.gettime()*1000) math.random(); math.random(); math.random() local function recommend() local method = "GET" local path = "http://localhost:5000/recommendations?require=rate&lat=38.0235&lon=-122.095" local headers = {} -- headers["Content-Type"] = "application/x-www-form-urlencoded" return wrk.format(method, path, headers, nil) end request = function() return recommend() end
nilq/small-lua-stack
null
local MIN_X = -30000 local MAX_X = 30000 local MIN_Z = -30000 local MAX_Z = 30000 function generateRandomWalkVector(min, max, generateBreaks) local currentHeight = 0 local val = {} local mode = math.random(4); -- mode of random walking, shifts probability distribution local modeAge = 10; -- mode age, when goes to zero, mode is reset for i=0, max do val[i] = currentHeight if (mode == 1) then currentHeight = currentHeight + math.random(-1,1) elseif (mode == 2) then if (math.random(3) == 1) then currentHeight = currentHeight + math.random(-1,1) else currentHeight = currentHeight end elseif (mode == 3) then if (math.random(3) == 1) then currentHeight = currentHeight + math.random(-1,1) else currentHeight = currentHeight + 1 end elseif (mode == 4) then if (math.random(3) == 1) then currentHeight = currentHeight + math.random(-1,1) else currentHeight = currentHeight - 1 end end modeAge = modeAge - 1; if (modeAge == 0) then mode = math.random(4) modeAge = 100 end if (generateBreaks and math.random(1000) == 1) then currentHeight = currentHeight + math.random(-100,100) end end currentHeight = 0 for i=0, min,-1 do val[i] = currentHeight currentHeight = currentHeight + math.random(-1,1) end return val end minetest.register_on_mapgen_init(function(mapgen_params) math.randomseed(mapgen_params.seed) -- produce the same world for the same seed xWalk = generateRandomWalkVector(MIN_X, MAX_X, false); zWalk = generateRandomWalkVector(MIN_X, MAX_X, false); xzWalk1 = generateRandomWalkVector(MIN_X, MAX_X, false); xzWalk2 = generateRandomWalkVector(MIN_Z, MAX_Z, false); xzWalk3 = generateRandomWalkVector(MIN_Z, MAX_Z, true); xzWalk4 = generateRandomWalkVector(MIN_Z, MAX_Z, true); xzWalk5 = generateRandomWalkVector(MIN_Z, MAX_Z, true); end) minetest.set_mapgen_params({mgname="singlenode"}) minetest.register_on_generated(function(minp, maxp, seed) local c_stone = minetest.get_content_id("default:stone") local c_water = minetest.get_content_id("default:water_source") local vm, emin, emax = minetest.get_mapgen_object("voxelmanip") local data = vm:get_data() local a = VoxelArea:new({MinEdge = emin, MaxEdge = emax}) local csize = vector.add(vector.subtract(maxp, minp), 1) local write = false local index2d = 0 for z = minp.z, maxp.z do for y = minp.y, maxp.y do for x = minp.x, maxp.x do if xzWalk1[x] then index2d = (z - minp.z) * csize.x + (x - minp.x) + 1 local ivm = a:index(x, y, z) if y < (xWalk[x] + zWalk[z] + xzWalk1[x + z] + xzWalk2[z - x] + xzWalk3[math.floor((x * z * 0.1 * xWalk[math.floor(x / 100)] + x * x * 0.01 * xWalk[math.floor(z / 100)] + z * z * 0.001 * xWalk[math.floor(x / 100)] + z * 2 + x * 3) / 100)] + xzWalk4[math.floor((x * z * 0.001 * zWalk[math.floor(z / 100)] + x * x * 0.1 * zWalk[math.floor(x / 100)] + z * z * 0.01 * xWalk[math.floor(z / 100)] - z * 2 - x * 3) / 100)] + xzWalk5[math.floor((x * z * 0.0001 * xWalk[math.floor(z / 100)] + x * x * 0.01 * xWalk[math.floor(x / 100)] + z * z * 0.1 * zWalk[math.floor(x /100)] - z - x) / 100)] ) / 4 then data[ivm] = c_stone write = true elseif y < 1 then data[ivm] = c_water write = true end end end end end if write then vm:set_data(data) vm:set_lighting({day = 0, night = 0}) vm:calc_lighting() vm:update_liquids() vm:write_to_map() end end)
nilq/small-lua-stack
null