repo_name
stringlengths
6
69
path
stringlengths
6
178
copies
stringclasses
278 values
size
stringlengths
4
7
content
stringlengths
671
917k
license
stringclasses
15 values
thedraked/darkstar
scripts/globals/items/lizard_egg.lua
18
1161
----------------------------------------- -- ID: 4362 -- Item: lizard_egg -- Food Effect: 5Min, All Races ----------------------------------------- -- Health 5 -- Magic 5 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,4362); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 5); target:addMod(MOD_MP, 5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 5); target:delMod(MOD_MP, 5); end;
gpl-3.0
Ali-2h/losebot
plugins/img_google.lua
660
3196
do local mime = require("mime") local google_config = load_from_file('data/google.lua') local cache = {} --[[ local function send_request(url) local t = {} local options = { url = url, sink = ltn12.sink.table(t), method = "GET" } local a, code, headers, status = http.request(options) return table.concat(t), code, headers, status end]]-- local function get_google_data(text) local url = "http://ajax.googleapis.com/ajax/services/search/images?" url = url.."v=1.0&rsz=5" url = url.."&q="..URL.escape(text) url = url.."&imgsz=small|medium|large" if google_config.api_keys then local i = math.random(#google_config.api_keys) local api_key = google_config.api_keys[i] if api_key then url = url.."&key="..api_key end end local res, code = http.request(url) if code ~= 200 then print("HTTP Error code:", code) return nil end local google = json:decode(res) return google end -- Returns only the useful google data to save on cache local function simple_google_table(google) local new_table = {} new_table.responseData = {} new_table.responseDetails = google.responseDetails new_table.responseStatus = google.responseStatus new_table.responseData.results = {} local results = google.responseData.results for k,result in pairs(results) do new_table.responseData.results[k] = {} new_table.responseData.results[k].unescapedUrl = result.unescapedUrl new_table.responseData.results[k].url = result.url end return new_table end local function save_to_cache(query, data) -- Saves result on cache if string.len(query) <= 7 then local text_b64 = mime.b64(query) if not cache[text_b64] then local simple_google = simple_google_table(data) cache[text_b64] = simple_google end end end local function process_google_data(google, receiver, query) if google.responseStatus == 403 then local text = 'ERROR: Reached maximum searches per day' send_msg(receiver, text, ok_cb, false) elseif google.responseStatus == 200 then local data = google.responseData if not data or not data.results or #data.results == 0 then local text = 'Image not found.' send_msg(receiver, text, ok_cb, false) return false end -- Random image from table local i = math.random(#data.results) local url = data.results[i].unescapedUrl or data.results[i].url local old_timeout = http.TIMEOUT or 10 http.TIMEOUT = 5 send_photo_from_url(receiver, url) http.TIMEOUT = old_timeout save_to_cache(query, google) else local text = 'ERROR!' send_msg(receiver, text, ok_cb, false) end end function run(msg, matches) local receiver = get_receiver(msg) local text = matches[1] local text_b64 = mime.b64(text) local cached = cache[text_b64] if cached then process_google_data(cached, receiver, text) else local data = get_google_data(text) process_google_data(data, receiver, text) end end return { description = "Search image with Google API and sends it.", usage = "!img [term]: Random search an image with Google API.", patterns = { "^!img (.*)$" }, run = run } end
gpl-2.0
vatanambib/yagop
plugins/img_google.lua
660
3196
do local mime = require("mime") local google_config = load_from_file('data/google.lua') local cache = {} --[[ local function send_request(url) local t = {} local options = { url = url, sink = ltn12.sink.table(t), method = "GET" } local a, code, headers, status = http.request(options) return table.concat(t), code, headers, status end]]-- local function get_google_data(text) local url = "http://ajax.googleapis.com/ajax/services/search/images?" url = url.."v=1.0&rsz=5" url = url.."&q="..URL.escape(text) url = url.."&imgsz=small|medium|large" if google_config.api_keys then local i = math.random(#google_config.api_keys) local api_key = google_config.api_keys[i] if api_key then url = url.."&key="..api_key end end local res, code = http.request(url) if code ~= 200 then print("HTTP Error code:", code) return nil end local google = json:decode(res) return google end -- Returns only the useful google data to save on cache local function simple_google_table(google) local new_table = {} new_table.responseData = {} new_table.responseDetails = google.responseDetails new_table.responseStatus = google.responseStatus new_table.responseData.results = {} local results = google.responseData.results for k,result in pairs(results) do new_table.responseData.results[k] = {} new_table.responseData.results[k].unescapedUrl = result.unescapedUrl new_table.responseData.results[k].url = result.url end return new_table end local function save_to_cache(query, data) -- Saves result on cache if string.len(query) <= 7 then local text_b64 = mime.b64(query) if not cache[text_b64] then local simple_google = simple_google_table(data) cache[text_b64] = simple_google end end end local function process_google_data(google, receiver, query) if google.responseStatus == 403 then local text = 'ERROR: Reached maximum searches per day' send_msg(receiver, text, ok_cb, false) elseif google.responseStatus == 200 then local data = google.responseData if not data or not data.results or #data.results == 0 then local text = 'Image not found.' send_msg(receiver, text, ok_cb, false) return false end -- Random image from table local i = math.random(#data.results) local url = data.results[i].unescapedUrl or data.results[i].url local old_timeout = http.TIMEOUT or 10 http.TIMEOUT = 5 send_photo_from_url(receiver, url) http.TIMEOUT = old_timeout save_to_cache(query, google) else local text = 'ERROR!' send_msg(receiver, text, ok_cb, false) end end function run(msg, matches) local receiver = get_receiver(msg) local text = matches[1] local text_b64 = mime.b64(text) local cached = cache[text_b64] if cached then process_google_data(cached, receiver, text) else local data = get_google_data(text) process_google_data(data, receiver, text) end end return { description = "Search image with Google API and sends it.", usage = "!img [term]: Random search an image with Google API.", patterns = { "^!img (.*)$" }, run = run } end
gpl-2.0
garage11/kaupunki
build/bin/Data/LuaScripts/23_Water.lua
15
9916
-- Water example. -- This sample demonstrates: -- - Creating a large plane to represent a water body for rendering -- - Setting up a second camera to render reflections on the water surface require "LuaScripts/Utilities/Sample" local reflectionCameraNode = nil local waterNode = nil local waterPlane = Plane() local waterClipPlane = Plane() function Start() -- Execute the common startup for samples SampleStart() -- Create the scene content CreateScene() -- Create the UI content CreateInstructions() -- Setup the viewport for displaying the scene SetupViewport() -- Set the mouse mode to use in the sample SampleInitMouseMode(MM_RELATIVE) -- Hook up to the frame update event SubscribeToEvents() end function CreateScene() scene_ = Scene() -- Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000) scene_:CreateComponent("Octree") -- Create a Zone component for ambient lighting & fog control local zoneNode = scene_:CreateChild("Zone") local zone = zoneNode:CreateComponent("Zone") zone.boundingBox = BoundingBox(-1000.0, 1000.0) zone.ambientColor = Color(0.15, 0.15, 0.15) zone.fogColor = Color(1.0, 1.0, 1.0) zone.fogStart = 500.0 zone.fogEnd = 750.0 -- Create a directional light to the world. Enable cascaded shadows on it local lightNode = scene_:CreateChild("DirectionalLight") lightNode.direction = Vector3(0.6, -1.0, 0.8) local light = lightNode:CreateComponent("Light") light.lightType = LIGHT_DIRECTIONAL light.castShadows = true light.shadowBias = BiasParameters(0.00025, 0.5) light.shadowCascade = CascadeParameters(10.0, 50.0, 200.0, 0.0, 0.8) light.specularIntensity = 0.5; -- Apply slightly overbright lighting to match the skybox light.color = Color(1.2, 1.2, 1.2); -- Create skybox. The Skybox component is used like StaticModel, but it will be always located at the camera, giving the -- illusion of the box planes being far away. Use just the ordinary Box model and a suitable material, whose shader will -- generate the necessary 3D texture coordinates for cube mapping local skyNode = scene_:CreateChild("Sky") skyNode:SetScale(500.0) -- The scale actually does not matter local skybox = skyNode:CreateComponent("Skybox") skybox.model = cache:GetResource("Model", "Models/Box.mdl") skybox.material = cache:GetResource("Material", "Materials/Skybox.xml") -- Create heightmap terrain local terrainNode = scene_:CreateChild("Terrain") terrainNode.position = Vector3(0.0, 0.0, 0.0) local terrain = terrainNode:CreateComponent("Terrain") terrain.patchSize = 64 terrain.spacing = Vector3(2.0, 0.5, 2.0) -- Spacing between vertices and vertical resolution of the height map terrain.smoothing = true terrain.heightMap = cache:GetResource("Image", "Textures/HeightMap.png") terrain.material = cache:GetResource("Material", "Materials/Terrain.xml") -- The terrain consists of large triangles, which fits well for occlusion rendering, as a hill can occlude all -- terrain patches and other objects behind it terrain.occluder = true -- Create 1000 boxes in the terrain. Always face outward along the terrain normal local NUM_OBJECTS = 1000 for i = 1, NUM_OBJECTS do local objectNode = scene_:CreateChild("Box") local position = Vector3(Random(2000.0) - 1000.0, 0.0, Random(2000.0) - 1000.0) position.y = terrain:GetHeight(position) + 2.25 objectNode.position = position -- Create a rotation quaternion from up vector to terrain normal objectNode.rotation = Quaternion(Vector3(0.0, 1.0, 0.0), terrain:GetNormal(position)) objectNode:SetScale(5.0) local object = objectNode:CreateComponent("StaticModel") object.model = cache:GetResource("Model", "Models/Box.mdl") object.material = cache:GetResource("Material", "Materials/Stone.xml") object.castShadows = true end -- Create a water plane object that is as large as the terrain waterNode = scene_:CreateChild("Water") waterNode.scale = Vector3(2048.0, 1.0, 2048.0) waterNode.position = Vector3(0.0, 5.0, 0.0) local water = waterNode:CreateComponent("StaticModel") water.model = cache:GetResource("Model", "Models/Plane.mdl") water.material = cache:GetResource("Material", "Materials/Water.xml") -- Set a different viewmask on the water plane to be able to hide it from the reflection camera water.viewMask = 0x80000000 -- Create the camera. Set far clip to match the fog. Note: now we actually create the camera node outside -- the scene, because we want it to be unaffected by scene load / save cameraNode = Node() local camera = cameraNode:CreateComponent("Camera") camera.farClip = 750.0 -- Set an initial position for the camera scene node above the floor cameraNode.position = Vector3(0.0, 7.0, -20.0) end function CreateInstructions() -- Construct new Text object, set string to display and font to use local instructionText = ui.root:CreateChild("Text") instructionText:SetText("Use WASD keys and mouse to move") instructionText:SetFont(cache:GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15) instructionText.textAlignment = HA_CENTER -- Position the text relative to the screen center instructionText.horizontalAlignment = HA_CENTER instructionText.verticalAlignment = VA_CENTER instructionText:SetPosition(0, ui.root.height / 4) end function SetupViewport() -- Set up a viewport to the Renderer subsystem so that the 3D scene can be seen local viewport = Viewport:new(scene_, cameraNode:GetComponent("Camera")) renderer:SetViewport(0, viewport) -- Create a mathematical plane to represent the water in calculations waterPlane = Plane(waterNode.worldRotation * Vector3(0.0, 1.0, 0.0), waterNode.worldPosition) -- Create a downward biased plane for reflection view clipping. Biasing is necessary to avoid too aggressive clipping waterClipPlane = Plane(waterNode.worldRotation * Vector3(0.0, 1.0, 0.0), waterNode.worldPosition - Vector3(0.0, 0.1, 0.0)) -- Create camera for water reflection -- It will have the same farclip and position as the main viewport camera, but uses a reflection plane to modify -- its position when rendering reflectionCameraNode = cameraNode:CreateChild() local reflectionCamera = reflectionCameraNode:CreateComponent("Camera") reflectionCamera.farClip = 750.0 reflectionCamera.viewMask = 0x7fffffff -- Hide objects with only bit 31 in the viewmask (the water plane) reflectionCamera.autoAspectRatio = false reflectionCamera.useReflection = true reflectionCamera.reflectionPlane = waterPlane reflectionCamera.useClipping = true -- Enable clipping of geometry behind water plane reflectionCamera.clipPlane = waterClipPlane -- The water reflection texture is rectangular. Set reflection camera aspect ratio to match reflectionCamera.aspectRatio = graphics.width / graphics.height -- View override flags could be used to optimize reflection rendering. For example disable shadows --reflectionCamera.viewOverrideFlags = VO_DISABLE_SHADOWS -- Create a texture and setup viewport for water reflection. Assign the reflection texture to the diffuse -- texture unit of the water material local texSize = 1024 local renderTexture = Texture2D:new() renderTexture:SetSize(texSize, texSize, Graphics:GetRGBFormat(), TEXTURE_RENDERTARGET) renderTexture.filterMode = FILTER_BILINEAR local surface = renderTexture.renderSurface local rttViewport = Viewport:new(scene_, reflectionCamera) surface:SetViewport(0, rttViewport) local waterMat = cache:GetResource("Material", "Materials/Water.xml") waterMat:SetTexture(TU_DIFFUSE, renderTexture) end function SubscribeToEvents() -- Subscribe HandleUpdate() function for processing update events SubscribeToEvent("Update", "HandleUpdate") end function MoveCamera(timeStep) -- Do not move if the UI has a focused element (the console) if ui.focusElement ~= nil then return end -- Movement speed as world units per second local MOVE_SPEED = 20.0 -- Mouse sensitivity as degrees per pixel local MOUSE_SENSITIVITY = 0.1 -- Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees local mouseMove = input.mouseMove yaw = yaw + MOUSE_SENSITIVITY * mouseMove.x pitch = pitch + MOUSE_SENSITIVITY * mouseMove.y pitch = Clamp(pitch, -90.0, 90.0) -- Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero cameraNode.rotation = Quaternion(pitch, yaw, 0.0) -- Read WASD keys and move the camera scene node to the corresponding direction if they are pressed if input:GetKeyDown(KEY_W) then cameraNode:Translate(Vector3(0.0, 0.0, 1.0) * MOVE_SPEED * timeStep) end if input:GetKeyDown(KEY_S) then cameraNode:Translate(Vector3(0.0, 0.0, -1.0) * MOVE_SPEED * timeStep) end if input:GetKeyDown(KEY_A) then cameraNode:Translate(Vector3(-1.0, 0.0, 0.0) * MOVE_SPEED * timeStep) end if input:GetKeyDown(KEY_D) then cameraNode:Translate(Vector3(1.0, 0.0, 0.0) * MOVE_SPEED * timeStep) end -- In case resolution has changed, adjust the reflection camera aspect ratio local reflectionCamera = reflectionCameraNode:GetComponent("Camera") reflectionCamera.aspectRatio = graphics.width / graphics.height end function HandleUpdate(eventType, eventData) -- Take the frame time step, which is stored as a float local timeStep = eventData["TimeStep"]:GetFloat() -- Move the camera, scale movement with time step MoveCamera(timeStep) end
mit
ply/ReaScripts
Items Editing/Source-Destination/ply_Source-Destination configuration.lua
1
4457
--[[ @noindex Source-Destination editing configuration manager This file is a part of "Source-Destination edit" package. Check "ply_Source-Destination edit.lua" for more information. Copyright (C) 2020--2021 Paweł Łyżwa This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. ]]-- package.path = ({reaper.get_action_context()})[2]:match('^.+[\\//]')..'?.lua' local config = require("config") local gfxu = require("gfxu") local TITLE = "Source-Destination - configure" local fonts = {} -- font IDs passed to gfx.setfont(), initialized in set_fonts() local colors = {} local get_pad = function() return 3 * gfx.ext_retina end local last_mouse_cap = 0 local function set_fonts() if #fonts == 0 then for i, v in ipairs({"main", "main_b", "hint", "value", "defvalue"}) do fonts[v] = i end end local fontsize = 16 gfxu.set_font(fonts.main, "verdana", fontsize) gfxu.set_font(fonts.main_b, "verdana", fontsize, "b") gfxu.set_font(fonts.hint, "verdana", 0.8*fontsize, "i") gfxu.set_font(fonts.value, "courier", fontsize, "b") gfxu.set_font(fonts.defvalue, "courier", fontsize) end local function init() gfx.ext_retina = 1.0 -- enable high resolution support gfx.init() -- colors local color_map = { text = "col_main_text", bg = "col_main_bg", hover_bg = "col_main_editbg", } for k, v in pairs(color_map) do local r, g, b = reaper.ColorFromNative(reaper.GetThemeColor(v, 0)) colors[k] = { r = r/255, g = g/255, b = b/255, a = nil, set = function() gfx.set(r/255, g/255, b/255) end } setmetatable(colors[k], { __call = colors[k].set }) end -- window size set_fonts() local width = gfx.measurestr("x")*70 + 2*get_pad() local height = gfx.texth * (#config.params + 1.5) + 2*get_pad() gfx.quit() gfx.init(TITLE, width, height) end local function run() if gfx.getchar(-1) == -1 then return end -- window is closed, no need to draw -- update mouse event status local mouse_evt = 0 if last_mouse_cap == 0 then last_mouse_cap = gfx.mouse_cap elseif gfx.mouse_cap == 0 then mouse_evt = last_mouse_cap last_mouse_cap = 0 end local pad = get_pad() set_fonts() -- needs to be updated constantly, because gfx.ext_retina can change gfxu.fill(colors.bg) gfxu.go(pad, pad) local mouse_over_line = nil if gfx.mouse_x > 0 and gfx.mouse_x < gfx.w and gfx.mouse_y > pad and gfx.mouse_y < (gfx.h - pad) then mouse_over_line = math.ceil((gfx.mouse_y - pad) / gfx.texth) end for i, param in ipairs(config.params) do gfx.setfont(fonts.main) if mouse_over_line == i then gfxu.fill(colors.hover_bg, gfx.x, gfx.y, gfx.w-2*pad, gfx.texth) if mouse_evt == 1 then -- left click if param.boolean then param:toggle() else local function get_value_from_user() local ok, new_value = reaper.GetUserInputs(TITLE, 1, param.name, param.value or param.default) new_value = param:str2value(new_value) if ok then if new_value == nil then reaper.ShowMessageBox("Error: invalid input! Please try again", TITLE, 0) get_value_from_user() return end param:set(new_value) end end reaper.defer(get_value_from_user) end elseif mouse_evt == 2 then -- right click param:reset() end end gfxu.draw_str(param.description, colors.text) if param.value then gfx.setfont(fonts.value) else gfx.setfont(fonts.defvalue) end gfxu.go(gfx.w-pad) gfxu.rdraw_str(param:display()) gfxu.newline(pad) end gfx.setfont(fonts.hint) gfxu.go(gfx.w-pad, gfx.h-pad-gfx.texth) gfxu.rdraw_str("Left click to change, right click to reset", colors.text) gfx.update() reaper.defer(run) end init() run()
mit
master041/tele-master-asli
plugins/domaintools.lua
359
1494
local ltn12 = require "ltn12" local https = require "ssl.https" -- Edit data/mashape.lua with your Mashape API key -- http://docs.mashape.com/api-keys local mashape = load_from_file('data/mashape.lua', { api_key = '' }) local function check(name) local api = "https://domainsearch.p.mashape.com/index.php?" local param = "name="..name local url = api..param local api_key = mashape.api_key if api_key:isempty() then return 'Configure your Mashape API Key' end local headers = { ["X-Mashape-Key"] = api_key, ["Accept"] = "application/json" } local respbody = {} local body, code = https.request{ url = url, method = "GET", headers = headers, sink = ltn12.sink.table(respbody), protocol = "tlsv1" } if code ~= 200 then return code end local body = table.concat(respbody) local body = json:decode(body) --vardump(body) local domains = "List of domains for '"..name.."':\n" for k,v in pairs(body) do print(k) local status = " ❌ " if v == "Available" then status = " ✔ " end domains = domains..k..status.."\n" end return domains end local function run(msg, matches) if matches[1] == "check" then local name = matches[2] return check(name) end end return { description = "Domain tools", usage = {"!domain check [domain] : Check domain name availability.", }, patterns = { "^!domain (check) (.*)$", }, run = run }
gpl-2.0
vatanambib/yagop
plugins/webshot.lua
919
1473
local helpers = require "OAuth.helpers" local base = 'https://screenshotmachine.com/' local url = base .. 'processor.php' local function get_webshot_url(param) local response_body = {} local request_constructor = { url = url, method = "GET", sink = ltn12.sink.table(response_body), headers = { referer = base, dnt = "1", origin = base, ["User-Agent"] = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36" }, redirect = false } local arguments = { urlparam = param, size = "FULL" } request_constructor.url = url .. "?" .. helpers.url_encode_arguments(arguments) local ok, response_code, response_headers, response_status_line = https.request(request_constructor) if not ok or response_code ~= 200 then return nil end local response = table.concat(response_body) return string.match(response, "href='(.-)'") end local function run(msg, matches) local find = get_webshot_url(matches[1]) if find then local imgurl = base .. find local receiver = get_receiver(msg) send_photo_from_url(receiver, imgurl) end end return { description = "Send an screenshot of a website.", usage = { "!webshot [url]: Take an screenshot of the web and send it back to you." }, patterns = { "^!webshot (https?://[%w-_%.%?%.:/%+=&]+)$", }, run = run }
gpl-2.0
pexcn/openwrt
extra-master/packages/mwan3-luci/files/usr/lib/lua/luci/model/cbi/mwan3/mwan3_adv_hotplug.lua
9
2003
-- ------ hotplug script configuration ------ -- fs = require "nixio.fs" sys = require "luci.sys" ut = require "luci.util" script = "/etc/hotplug.d/iface/16-mwan3custom" scriptbak = "/etc/hotplug.d/iface/16-mwan3custombak" if luci.http.formvalue("cbid.luci.1._restorebak") then -- restore button has been clicked luci.http.redirect(luci.dispatcher.build_url("admin/network/mwan3/advanced/hotplug") .. "?restore=yes") elseif luci.http.formvalue("restore") == "yes" then -- restore script from backup os.execute("cp -f " .. scriptbak .. " " .. script) end m5 = SimpleForm("luci", nil) m5:append(Template("mwan3/mwan3_adv_hotplug")) -- highlight current tab f = m5:section(SimpleSection, nil, translate("This section allows you to modify the contents of /etc/hotplug.d/iface/16-mwan3custom<br />" .. "This is useful for running system commands and/or scripts based on interface ifup or ifdown hotplug events<br /><br />" .. "Notes:<br />" .. "The first line of the script must be &#34;#!/bin/sh&#34; without quotes<br />" .. "Lines beginning with # are comments and are not executed<br /><br />" .. "Available variables:<br />" .. "$ACTION is the hotplug event (ifup, ifdown)<br />" .. "$INTERFACE is the interface name (wan1, wan2, etc.)<br />" .. "$DEVICE is the device name attached to the interface (eth0.1, eth1, etc.)")) restore = f:option(Button, "_restorebak", translate("Restore default hotplug script")) restore.inputtitle = translate("Restore...") restore.inputstyle = "apply" t = f:option(TextValue, "lines") t.rmempty = true t.rows = 20 function t.cfgvalue() local hps = fs.readfile(script) if not hps or hps == "" then -- if script does not exist or is blank restore from backup sys.call("cp -f " .. scriptbak .. " " .. script) return fs.readfile(script) else return hps end end function t.write(self, section, data) -- format and write new data to script return fs.writefile(script, ut.trim(data:gsub("\r\n", "\n")) .. "\n") end return m5
gpl-2.0
thedraked/darkstar
scripts/zones/Sacrarium/Zone.lua
19
3611
----------------------------------- -- -- Zone: Sacrarium (28) -- ----------------------------------- package.loaded["scripts/zones/Sacrarium/TextIDs"] = nil; ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/zones/Sacrarium/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) -- Set random variable for determining Old Prof. Mariselle's spawn location local rand = math.random((2),(7)); SetServerVariable("Old_Prof_Spawn_Location", rand); UpdateTreasureSpawnPoint(16892179); end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then player:setPos(-219.996,-18.587,82.795,64); end -- ZONE LEVEL RESTRICTION if (ENABLE_COP_ZONE_CAP == 1) then player:addStatusEffect(EFFECT_LEVEL_RESTRICTION,50,0,0); end return cs; end; ----------------------------------- -- onConquestUpdate ----------------------------------- function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onGameDay ----------------------------------- function onGameDay() -- Labyrinth local day = VanadielDayElement() ; local tbl; local SacrariumWallOffset = 16892109; if (day == 3 or day == 7) then tbl = {9,9,8,8,9,9,8,9,8,8,9,8,8,8,9,8,9,8}; elseif (day == 1 or day == 5) then tbl = {9,9,8,9,8,8,8,8,9,9,9,8,9,8,8,8,8,9}; elseif (day == 0 or day == 4) then tbl = {8,9,8,9,8,9,9,8,9,9,8,8,9,8,8,8,8,9}; else tbl = {9,8,9,9,8,9,8,8,9,8,8,9,8,9,8,9,8,8}; end GetNPCByID(SacrariumWallOffset):setAnimation(tbl[1]); GetNPCByID(SacrariumWallOffset+6):setAnimation(tbl[2]); GetNPCByID(SacrariumWallOffset+12):setAnimation(tbl[3]); GetNPCByID(SacrariumWallOffset+13):setAnimation(tbl[4]); GetNPCByID(SacrariumWallOffset+1):setAnimation(tbl[5]); GetNPCByID(SacrariumWallOffset+7):setAnimation(tbl[6]); GetNPCByID(SacrariumWallOffset+14):setAnimation(tbl[7]); GetNPCByID(SacrariumWallOffset+2):setAnimation(tbl[8]); GetNPCByID(SacrariumWallOffset+8):setAnimation(tbl[9]); GetNPCByID(SacrariumWallOffset+9):setAnimation(tbl[10]); GetNPCByID(SacrariumWallOffset+3):setAnimation(tbl[11]); GetNPCByID(SacrariumWallOffset+15):setAnimation(tbl[12]); GetNPCByID(SacrariumWallOffset+16):setAnimation(tbl[13]); GetNPCByID(SacrariumWallOffset+10):setAnimation(tbl[14]); GetNPCByID(SacrariumWallOffset+4):setAnimation(tbl[15]); GetNPCByID(SacrariumWallOffset+17):setAnimation(tbl[16]); GetNPCByID(SacrariumWallOffset+11):setAnimation(tbl[17]); GetNPCByID(SacrariumWallOffset+5):setAnimation(tbl[18]); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
128technology/protobuf_dissector
modules/ast/scoped_identifier.lua
1
3696
---------------------------------------- -- -- Copyright (c) 2015, 128 Technology, Inc. -- -- author: Hadriel Kaplan <hadriel@128technology.com> -- -- This code is licensed under the MIT license. -- -- Version: 1.0 -- ------------------------------------------ -- prevent wireshark loading this file as a plugin if not _G['protbuf_dissector'] then return end local Settings = require "settings" local dprint = Settings.dprint local dprint2 = Settings.dprint2 local dassert = Settings.dassert local derror = Settings.derror local Identifier = require "ast.identifier" local Syntax = require "syntax" ---------------------------------------- -- The ScopedIdentifier class, may be scoped -- this is used for things like fullIdent, messageType, enumType -- grammar: ["."] {ident "."} ident local ScopedIdentifier = {} local ScopedIdentifier_mt = { __index = ScopedIdentifier } setmetatable( ScopedIdentifier, { __index = Identifier } ) -- inherit from Identifier -- go through finding [.] ident ([.] ident)* -- save their actual tokens into a table as our value function ScopedIdentifier.parse(st, idx) dassert(#st >= idx, "Identifier subtable too short") local t = {} -- could have leading period for global scope if st[idx].ttype == "PERIOD" then -- save the token and keep going t[#t+1] = st[idx] idx = idx + 1 dassert(st[idx], "Globally scoped identifier value missing identifier") end while idx <= #st do dassert(st[idx]:canBeIdentifier(), st[idx], "ScopedIdentifier value is not an identifier:", st[idx].value) -- make it an IDENTIFIER and save it st[idx].ttype = "IDENTIFIER" t[#t+1] = st[idx] idx = idx + 1 -- see if next one is a period if idx < #st and st[idx].ttype == "PERIOD" then -- save it and go around again t[#t+1] = st[idx] idx = idx + 1 else -- we're done return t, idx end end -- we're done return t, idx end function ScopedIdentifier.new(st, idx) local value, new_idx = ScopedIdentifier.parse(st, idx) local new_class = Identifier.protected_new(value) setmetatable( new_class, ScopedIdentifier_mt ) return new_class, new_idx end function ScopedIdentifier:isGlobalScope() return self.value[1].ttype == "PERIOD" end function ScopedIdentifier:isScoped() for _, token in self.value do if token.ttype == "PERIOD" then return true end end dassert(#self.value == 1, "Programming error: ScopedIdentifier has multiple values without a '.' PERIOD") return false end function ScopedIdentifier:getValue(portion_idx) local values = self.value if not portion_idx then -- behave like Identifier dassert(not self:isScoped(), "Programming error: getValue() called without index on ScopedIdentifier") return values[#values].value end -- give back requested portion local idx = (portion_idx * 2) - 1 if self:isGlobalScope() then -- offset for the global scope's period idx = idx +1 end return idx <= #values and values[idx].value or nil end function ScopedIdentifier:size() local size = #self.value if self:isGlobalScope() then size = size - 1 end return (size + 1) / 2 end function ScopedIdentifier:resolve(namespace) if self:isGlobalScope() then return namespace:findAbsoluteDeclaration(self) else return namespace:findRelativeDeclaration(self) end end function ScopedIdentifier:display() return Syntax:concatTokenValues(self.value) end return ScopedIdentifier
mit
horizonrz/DBTeam
plugins/moderation.lua
42
30441
-------------------------------------------------- -- ____ ____ _____ -- -- | \| _ )_ _|___ ____ __ __ -- -- | |_ ) _ \ | |/ ·__| _ \_| \/ | -- -- |____/|____/ |_|\____/\_____|_/\/\_| -- -- -- -------------------------------------------------- -- -- -- Developers: @Josepdal & @MaSkAoS -- -- Support: @Skneos, @iicc1 & @serx666 -- -- -- -------------------------------------------------- do local function index_gban(user_id) for k,v in pairs(_gbans.gbans_users) do if tonumber(user_id) == tonumber(v) then return k end end -- If not found return false end local function unmute_by_reply(extra, success, result) result = backward_msg_format(result) local msg = result local chat = msg.to.id local user = msg.from.id local name = msg.from.username local hash = 'muted:'..chat..':'..user redis:del(hash) if msg.to.type == 'chat' then send_msg('chat#id'..chat, 'ℹ️ '..lang_text(chat, 'userUnmuted:1')..' '..name..' ('..user..') '..lang_text(chat, 'userUnmuted:2'), ok_cb, true) elseif msg.to.type == 'channel' then send_msg('channel#id'..chat, 'ℹ️ '..lang_text(chat, 'userUnmuted:1')..' '..name..' ('..user..') '..lang_text(chat, 'userUnmuted:2'), ok_cb, true) end end local function mute_by_reply(extra, success, result) result = backward_msg_format(result) local msg = result local chat = msg.to.id local user = msg.from.id local name = msg.from.username local hash = 'muted:'..chat..':'..user redis:set(hash, true) if msg.to.type == 'chat' then send_msg('chat#id'..chat, 'ℹ️ '..lang_text(chat, 'userMuted:1')..' '..name..' ('..user..') '..lang_text(chat, 'userMuted:2'), ok_cb, true) elseif msg.to.type == 'channel' then send_msg('channel#id'..chat, 'ℹ️ '..lang_text(chat, 'userMuted:1')..' '..name..' ('..user..') '..lang_text(chat, 'userMuted:2'), ok_cb, true) end end local function mute_by_username(cb_extra, success, result) chat_type = cb_extra.chat_type chat_id = cb_extra.chat_id user_id = result.peer_id user_username = result.username local hash = 'muted:'..chat_id..':'..user_id redis:set(hash, true) if chat_type == 'chat' then send_msg('chat#id'..chat_id, 'ℹ️ '..lang_text(chat_id, 'userMuted:1')..' '..user_username..' ('..user_id..') '..lang_text(chat_id, 'userMuted:2'), ok_cb, true) elseif chat_type == 'channel' then send_msg('channel#id'..chat_id, 'ℹ️ '..lang_text(chat_id, 'userMuted:1')..' '..user_username..' ('..user_id..') '..lang_text(chat_id, 'userMuted:2'), ok_cb, true) end end local function unmute_by_username(cb_extra, success, result) chat_type = cb_extra.chat_type chat_id = cb_extra.chat_id user_id = result.peer_id user_username = result.username local hash = 'muted:'..chat_id..':'..user_id redis:del(hash) if chat_type == 'chat' then send_msg('chat#id'..chat_id, 'ℹ️ '..lang_text(chat_id, 'userMuted:1')..' '..user_username..' ('..user_id..') '..lang_text(chat_id, 'userUnmuted:2'), ok_cb, true) elseif chat_type == 'channel' then send_msg('channel#id'..chat_id, 'ℹ️ '..lang_text(chat_id, 'userMuted:1')..' '..user_username..' ('..user_id..') '..lang_text(chat_id, 'userUnmuted:2'), ok_cb, true) end end local function kick_user(user_id, chat_id) local chat = 'chat#id'..chat_id local user = 'user#id'..user_id local channel = 'channel#id'..chat_id if user_id == tostring(our_id) then print("I won't kick myself!") else chat_del_user(chat, user, ok_cb, true) channel_kick_user(channel, user, ok_cb, true) end end local function ban_user(user_id, chat_id) local chat = 'chat#id'..chat_id if user_id == tostring(our_id) then print('I won\'t kick myself!') else -- Save to redis local hash = 'banned:'..chat_id..':'..user_id redis:set(hash, true) end end local function unban_user(user_id, chat_id) local hash = 'banned:'..chat_id..':'..user_id redis:del(hash) end local function is_banned(user_id, chat_id) local hash = 'banned:'..chat_id..':'..user_id local banned = redis:get(hash) return banned or false end local function chat_kick(extra, success, result) result = backward_msg_format(result) local msg = result local chat = msg.to.id local user = msg.from.id local chat_type = msg.to.type if chat_type == 'chat' then chat_del_user('chat#id'..chat, 'user#id'..user, ok_cb, false) send_msg('chat#id'..chat, 'ℹ️ '..lang_text(chat, 'kickUser:1')..' '..user..' '..lang_text(chat, 'kickUser:2'), ok_cb, true) elseif chat_type == 'channel' then channel_kick_user('channel#id'..chat, 'user#id'..user, ok_cb, false) send_msg('channel#id'..chat, 'ℹ️ '..lang_text(chat, 'kickUser:1')..' '..user..' '..lang_text(chat, 'kickUser:2'), ok_cb, true) end end local function chat_ban(extra, success, result) result = backward_msg_format(result) local msg = result local chat = msg.to.id local user = msg.from.id local hash = 'banned:'..chat..':'..user redis:set(hash, true) chat_del_user('chat#id'..chat, 'user#id'..user, ok_cb, false) send_msg('chat#id'..chat, 'ℹ️ '..lang_text(chat, 'banUser:1')..' '..user..' '..lang_text(chat, 'banUser:2'), ok_cb, true) end local function gban_by_reply(extra, success, result) result = backward_msg_format(result) local msg = result local chat = msg.to.id local user = msg.from.id local hash = 'gban:'..user redis:set(hash, true) if not is_gbanned_table(msg.to.id) then table.insert(_gbans.gbans_users, tonumber(msg.to.id)) print(msg.to.id..' added to _gbans table') save_gbans() end if msg.to.type == 'chat' then chat_del_user('chat#id'..chat, 'user#id'..user, ok_cb, false) send_msg('chat#id'..chat, 'ℹ️ '..lang_text(chat, 'gbanUser:1')..' '..user..' '..lang_text(chat, 'gbanUser:2'), ok_cb, true) elseif msg.to.type == 'channel' then channel_kick_user('channel#id'..chat, 'user#id'..user, ok_cb, false) send_msg('channel#id'..chat, 'ℹ️ '..lang_text(chat, 'gbanUser:1')..' '..user..' '..lang_text(chat, 'gbanUser:2'), ok_cb, true) end end local function ungban_by_reply(extra, success, result) result = backward_msg_format(result) local msg = result local chat = msg.to.id local user = msg.from.id local indexid = index_gban(user) local hash = 'gban:'..user redis:del(hash) if is_gbanned_table(user_id) then table.remove(_gbans.gbans_users, indexid) print(user_id..' removed from _gbans table') save_gbans() end if msg.to.type == 'chat' then chat_add_user('chat#id'..chat, 'user#id'..user, ok_cb, false) send_msg('chat#id'..chat, 'ℹ️ '..lang_text(chat, 'ungbanUser:1')..' '..user..' '..lang_text(chat, 'ungbanUser:2'), ok_cb, true) elseif msg.to.type == 'channel' then channel_invite_user('channel#id'..chat, 'user#id'..user, ok_cb, false) send_msg('channel#id'..chat, 'ℹ️ '..lang_text(chat, 'ungbanUser:1')..' '..user..' '..lang_text(chat, 'ungbanUser:2'), ok_cb, true) end end local function add_by_reply(extra, success, result) result = backward_msg_format(result) local msg = result local chat = msg.to.id local user = msg.from.id if msg.to.type == 'chat' then chat_add_user('chat#id'..chat, 'user#id'..user, ok_cb, false) send_msg('chat#id'..chat, 'ℹ️ '..lang_text(chat, 'addUser:1')..' '..user..' '..lang_text(chat, 'addUser:2'), ok_cb, true) elseif msg.to.type == 'channel' then channel_invite_user('channel#id'..chat, 'user#id'..user, ok_cb, false) send_msg('channel#id'..chat, 'ℹ️ '..lang_text(chat, 'addUser:1')..' '..user..' '..lang_text(chat, 'addUser:3'), ok_cb, true) end end local function channel_ban(extra, success, result) local msg = result msg = backward_msg_format(msg) local chat = msg.to.id local user = msg.from.id channel_kick_user('channel#id'..chat, 'user#id'..user, ok_cb, true) send_msg('channel#id'..chat, 'ℹ️ '..lang_text(chat, 'banUser:1')..' '..user..' '..lang_text(chat, 'banUser:2'), ok_cb, true) ban_user(user, chat) end local function chat_unban(extra, success, result) result = backward_msg_format(result) local msg = result local chat = msg.to.id local user = msg.from.id unban_user(user, chat) chat_add_user('chat#id'..chat, 'user#id'..user, ok_cb, false) send_msg(chat, 'User '..user..' unbanned', ok_cb, true) end local function channel_unban(extra, success, result) local msg = result local msg = backward_msg_format(msg) local chat = msg.to.id local user = msg.from.id unban_user(user, chat) channel_invite_user('channel#id'..chat, 'user#id'..user, ok_cb, true) send_msg('channel#id'..chat, 'User '..user..' unbanned', ok_cb, true) end local function ban_by_username(cb_extra, success, result) chat_type = cb_extra.chat_type chat_id = cb_extra.chat_id user_id = result.peer_id user_username = result.username local hash = 'banned:'..chat_id..':'..user_id redis:set(hash, true) if chat_type == 'chat' then send_msg('chat#id'..chat_id, 'ℹ️ '..lang_text(chat_id, 'banUser:1')..' @'..user_username..' ('..user_id..') '..lang_text(chat_id, 'banUser:2'), ok_cb, false) chat_del_user('chat#id'..chat_id, 'user#id'..user_id, ok_cb, false) elseif chat_type == 'channel' then send_msg('channel#id'..chat_id, 'ℹ️ '..lang_text(chat_id, 'banUser:1')..' @'..user_username..' ('..user_id..') '..lang_text(chat_id, 'banUser:2'), ok_cb, false) channel_kick_user('channel#id'..chat_id, 'user#id'..user_id, ok_cb, false) end ban_user(user_id, chat_id) end local function kick_by_username(cb_extra, success, result) chat_id = cb_extra.chat_id user_id = result.peer_id chat_type = cb_extra.chat_type user_username = result.username if chat_type == 'chat' then send_msg('chat#id'..chat_id, 'ℹ️ '..lang_text(chat_id, 'kickUser:1')..' @'..user_username..' ('..user_id..') '..lang_text(chat_id, 'kickUser:2'), ok_cb, false) chat_del_user('chat#id'..chat_id, 'user#id'..user_id, ok_cb, false) elseif chat_type == 'channel' then send_msg('channel#id'..chat_id, 'ℹ️ '..lang_text(chat_id, 'kickUser:1')..' @'..user_username..' ('..user_id..') '..lang_text(chat_id, 'kickUser:2'), ok_cb, false) channel_kick_user('channel#id'..chat_id, 'user#id'..user_id, ok_cb, false) end end local function gban_by_username(cb_extra, success, result) local chat_id = cb_extra.chat_id local user_id = result.peer_id local user_username = result.username local chat_type = cb_extra.chat_type local hash = 'gban:'..user_id redis:set(hash, true) if not is_gbanned_table(user_id) then table.insert(_gbans.gbans_users, tonumber(user_id)) print(user_id..' added to _gbans table') save_gbans() end if chat_type == 'chat' then send_msg('chat#id'..chat_id, 'ℹ️ '..lang_text(chat_id, 'gbanUser:1')..' @'..user_username..' ('..user_id..') '..lang_text(chat_id, 'gbanUser:2'), ok_cb, false) chat_del_user('chat#id'..chat_id, 'user#id'..user_id, ok_cb, false) elseif chat_type == 'channel' then send_msg('channel#id'..chat_id, 'ℹ️ '..lang_text(chat_id, 'gbanUser:1')..' @'..user_username..' ('..user_id..') '..lang_text(chat_id, 'gbanUser:2'), ok_cb, false) channel_kick_user('channel#id'..chat_id, 'user#id'..user_id, ok_cb, false) end end local function ungban_by_username(cb_extra, success, result) chat_id = cb_extra.chat_id user_id = result.peer_id user_username = result.username chat_type = cb_extra.chat_type local indexid = index_gban(user_id) local hash = 'gban:'..user_id redis:del(hash) if is_gbanned_table(user_id) then table.remove(_gbans.gbans_users, indexid) print(user_id..' removed from _gbans table') save_gbans() end if chat_type == 'chat' then send_msg('chat#id'..chat_id, 'ℹ️ '..lang_text(chat_id, 'ungbanUser:1')..' @'..user_username..' ('..user_id..') '..lang_text(chat_id, 'ungbanUser:2'), ok_cb, false) chat_add_user('chat#id'..chat_id, 'user#id'..user_id, ok_cb, false) elseif chat_type == 'channel' then send_msg('channel#id'..chat_id, 'ℹ️ '..lang_text(chat_id, 'ungbanUser:1')..' @'..user_username..' ('..user_id..') '..lang_text(chat_id, 'ungbanUser:2'), ok_cb, false) channel_invite_user('channel#id'..chat_id, 'user#id'..user_id, ok_cb, false) end end local function unban_by_username(cb_extra, success, result) chat_type = cb_extra.chat_type chat_id = cb_extra.chat_id user_id = result.peer_id user_username = result.username local hash = 'banned:'..chat_id..':'..user_id redis:del(hash) if chat_type == 'chat' then send_msg('chat#id'..chat_id, 'ℹ️ '..lang_text(chat_id, 'unbanUser:1')..' @'..user_username..' ('..user_id..') '..lang_text(chat_id, 'unbanUser:2'), ok_cb, false) chat_add_user('chat#id'..chat_id, 'user#id'..user_id, callback, false) elseif chat_type == 'channel' then send_msg('channel#id'..chat_id, 'ℹ️ '..lang_text(chat_id, 'unbanUser:1')..' @'..user_username..' ('..user_id..') '..lang_text(chat_id, 'unbanUser:2'), ok_cb, false) channel_invite_user('channel#id'..chat_id, 'user#id'..user_id, callback, false) end end local function add_by_username(cb_extra, success, result) local chat_type = cb_extra.chat_type local chat_id = cb_extra.chat_id local user_id = result.peer_id local user_username = result.username print(chat_id) if chat_type == 'chat' then send_msg('chat#id'..chat_id, 'ℹ️ '..lang_text(chat_id, 'addUser:1')..' @'..user_username..' ('..user_id..') '..lang_text(chat_id, 'addUser:2'), ok_cb, false) chat_add_user('chat#id'..chat_id, 'user#id'..user_id, ok_cb, false) elseif chat_type == 'channel' then send_msg('channel#id'..chat_id, 'ℹ️ '..lang_text(chat_id, 'addUser:1')..' @'..user_username..' ('..user_id..') '..lang_text(chat_id, 'addUser:3'), ok_cb, false) channel_invite_user('channel#id'..chat_id, 'user#id'..user_id, ok_cb, false) end end local function is_gbanned(user_id) local hash = 'gban:'..user_id local banned = redis:get(hash) return banned or false end local function pre_process(msg) --Checking mute local hash = 'muted:'..msg.to.id..':'..msg.from.id if redis:get(hash) then if msg.to.type == 'chat' then delete_msg(msg.id, ok_cb, true) elseif msg.to.type == 'channel' then delete_msg(msg.id, ok_cb, true) end end -- SERVICE MESSAGE if msg.action and msg.action.type then local action = msg.action.type -- Check if banned user joins chat if action == 'chat_add_user' or action == 'chat_add_user_link' then local user_id local hash = 'lockmember:'..msg.to.id if redis:get(hash) then if msg.action.link_issuer then user_id = msg.from.id else user_id = msg.action.user.id end kick_user(user_id, msg.to.id) delete_msg(msg.id, ok_cb, true) end if msg.action.link_issuer then user_id = msg.from.id else user_id = msg.action.user.id end print('Checking invited user '..user_id) local banned = is_banned(user_id, msg.to.id) or is_gbanned(user_id) if banned then print('User is banned!') kick_user(user_id, msg.to.id) end end -- No further checks return msg end -- BANNED USER TALKING if msg.to.type == 'chat' or msg.to.type == 'channel' then local user_id = msg.from.id local chat_id = msg.to.id local banned = is_banned(user_id, chat_id) or is_gbanned(user_id, msg.to.id) if banned then print('Banned user talking!') ban_user(user_id, chat_id) kick_user(user_id, chat_id) msg.text = '' end hash = 'antibot:'..msg.to.id if redis:get(hash) then if string.sub(msg.from.username, (string.len(msg.from.username)-2), string.len(msg.from.username)) == 'bot' then kick_user(user_id, chat_id) end end end return msg end local function run(msg, matches) chat_id = msg.to.id if matches[1] == 'ban' then if permissions(msg.from.id, msg.to.id, "ban") then local chat_id = msg.to.id local chat_type = msg.to.type if msg.reply_id then if msg.to.type == 'chat' then get_message(msg.reply_id, chat_ban, false) elseif msg.to.type == 'channel' then get_message(msg.reply_id, channel_ban, {receiver=get_receiver(msg)}) end return end if not is_id(matches[2]) then local member = string.gsub(matches[2], '@', '') resolve_username(member, ban_by_username, {chat_id=chat_id, member=member, chat_type=chat_type}) return else user_id = matches[2] if chat_type == 'chat' then send_msg('chat#id'..chat_id, 'ℹ️ '..lang_text(chat_id, 'banUser:1')..' '..user_id..' '..lang_text(chat, 'banUser:2'), ok_cb, false) chat_del_user('chat#id'..chat_id, 'user#id'..user_id, ok_cb, false) elseif chat_type == 'channel' then send_msg('channel#id'..chat_id, 'ℹ️ '..lang_text(chat_id, 'banUser:1')..' '..user_id..' '..lang_text(chat, 'banUser:2'), ok_cb, false) channel_kick_user('channel#id'..chat_id, 'user#id'..user_id, ok_cb, false) end ban_user(user_id, chat_id) return end else return '🚫 '..lang_text(msg.to.id, 'require_mod') end elseif matches[1] == 'unban' then if permissions(msg.from.id, msg.to.id, "unban") then local chat_id = msg.to.id local chat_type = msg.to.type if msg.reply_id then if msg.to.type == 'chat' then get_message(msg.reply_id, chat_unban, false) elseif msg.to.type == 'channel' then get_message(msg.reply_id, channel_unban, false) end return end if not is_id(matches[2]) then local member = string.gsub(matches[2], '@', '') resolve_username(member, unban_by_username, {chat_id=chat_id, member=member, chat_type=chat_type}) return else local hash = 'banned:'..chat_id..':'..matches[2] redis:del(hash) if msg.to.type == 'chat' then chat_add_user('chat#id'..chat_id, 'user#id'..matches[2], ok_cb, false) elseif msg.to.type == 'channel' then channel_invite_user('channel#id'..chat_id, 'user#id'..matches[2], ok_cb, false) end return 'ℹ️ '..lang_text(chat_id, 'unbanUser:1')..' '..matches[2]..' '..lang_text(chat_id, 'unbanUser:2') end else return '🚫 '..lang_text(msg.to.id, 'require_mod') end elseif matches[1] == 'kick' then if permissions(msg.from.id, msg.to.id, "kick") then local chat_id = msg.to.id local chat_type = msg.to.type -- Using pattern #kick if msg.reply_id then get_message(msg.reply_id, chat_kick, false) return end if not is_id(matches[2]) then local member = string.gsub(matches[2], '@', '') resolve_username(member, kick_by_username, {chat_id=chat_id, member=member, chat_type=chat_type}) return else local user_id = matches[2] if msg.to.type == 'chat' then send_msg('chat#id'..chat_id, 'ℹ️ '..lang_text(chat_id, 'kickUser:1')..' '..user_id..' '..lang_text(chat_id, 'kickUser:2'), ok_cb, false) chat_del_user('chat#id'..msg.to.id, 'user#id'..matches[2], ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..chat_id, 'ℹ️ '..lang_text(chat_id, 'kickUser:1')..' '..user_id..' '..lang_text(chat_id, 'kickUser:2'), ok_cb, false) channel_kick_user('channel#id'..msg.to.id, 'user#id'..matches[2], ok_cb, false) end return end else return '🚫 '..lang_text(msg.to.id, 'require_mod') end elseif matches[1] == 'gban' then if permissions(msg.from.id, msg.to.id, "gban") then chat_id = msg.to.id chat_type = msg.to.type if msg.reply_id then get_message(msg.reply_id, gban_by_reply, false) return end if not is_id(matches[2]) then local member = string.gsub(matches[2], '@', '') resolve_username(member, gban_by_username, {chat_id=chat_id, member=member, chat_type=chat_type}) return else local user_id = matches[2] local hash = 'gban:'..user_id redis:set(hash, true) if not is_gbanned_table(user_id) then table.insert(_gbans.gbans_users, tonumber(user_id)) print(user_id..' added to _gbans table') save_gbans() end if chat_type == 'chat' then send_msg('chat#id'..chat_id, 'ℹ️ '..lang_text(chat_id, 'gbanUser:1')..' '..user_id..' '..lang_text(chat_id, 'gbanUser:2'), ok_cb, false) chat_del_user('chat#id'..chat_id, 'user#id'..user_id, ok_cb, false) elseif chat_type == 'channel' then send_msg('channel#id'..chat_id, 'ℹ️ '..lang_text(chat_id, 'gbanUser:1')..' '..user_id..' '..lang_text(chat_id, 'gbanUser:2'), ok_cb, false) channel_kick_user('channel#id'..chat_id, 'user#id'..user_id, ok_cb, false) end return end else return '🚫 '..lang_text(msg.to.id, 'require_admin') end elseif matches[1] == 'ungban' then if permissions(msg.from.id, msg.to.id, "ungban") then chat_id = msg.to.id chat_type = msg.to.type if msg.reply_id then get_message(msg.reply_id, ungban_by_reply, false) return end if not is_id(matches[2]) then local chat_type = msg.to.type local member = string.gsub(matches[2], '@', '') resolve_username(member, ungban_by_username, {chat_id=chat_id, member=member, chat_type=chat_type}) return else local user_id = matches[2] local hash = 'gban:'..user_id local indexid = index_gban(user_id) redis:del(hash) if is_gbanned_table(user_id) then table.remove(_gbans.gbans_users, indexid) print(user_id..' removed from _gbans table') save_gbans() end if chat_type == 'chat' then send_msg('chat#id'..chat_id, 'ℹ️ '..lang_text(chat_id, 'gbanUser:1')..' '..user_id..' '..lang_text(chat_id, 'ungbanUser:2'), ok_cb, false) chat_add_user('chat#id'..chat_id, 'user#id'..user_id, ok_cb, false) elseif chat_type == 'channel' then send_msg('channel#id'..chat_id, 'ℹ️ '..lang_text(chat_id, 'gbanUser:1')..' '..user_id..' '..lang_text(chat_id, 'ungbanUser:2'), ok_cb, false) channel_invite_user('channel#id'..chat_id, 'user#id'..user_id, ok_cb, false) end return end else return '🚫 '..lang_text(msg.to.id, 'require_mod') end elseif matches[1] == 'add' then if permissions(msg.from.id, msg.to.id, "add") then local chat_id = msg.to.id local chat_type = msg.to.type if msg.reply_id then get_message(msg.reply_id, add_by_reply, false) return end if not is_id(matches[2]) then local member = string.gsub(matches[2], '@', '') print(chat_id) resolve_username(member, add_by_username, {chat_id=chat_id, member=member, chat_type=chat_type}) return else local user_id = matches[2] if chat_type == 'chat' then send_msg('chat#id'..chat_id, 'ℹ️ '..lang_text(chat_id, 'addUser:1')..' '..user_id..' '..lang_text(chat_id, 'addUser:2'), ok_cb, false) chat_add_user('chat#id'..chat_id, 'user#id'..user_id, ok_cb, false) elseif chat_type == 'channel' then send_msg('channel#id'..chat_id, 'ℹ️ '..lang_text(chat_id, 'addUser:1')..' '..user_id..' '..lang_text(chat_id, 'addUser:3'), ok_cb, false) channel_invite_user('channel#id'..chat_id, 'user#id'..user_id, ok_cb, false) end return end else return '🚫 '..lang_text(msg.to.id, 'require_mod') end elseif matches[1] == 'mute' then if permissions(msg.from.id, msg.to.id, "mute") then if msg.reply_id then get_message(msg.reply_id, mute_by_reply, false) return end if matches[2] then if is_id(matches[2]) then local hash = 'muted:'..msg.to.id..':'..matches[2] redis:set(hash, true) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(chat_id, 'userMuted:1')..' '..matches[2]..' '..lang_text(chat_id, 'userMuted:2'), ok_cb, true) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(chat_id, 'userMuted:1')..' '..matches[2]..' '..lang_text(chat_id, 'userMuted:2'), ok_cb, true) end return else local member = string.gsub(matches[2], '@', '') local chat_id = msg.to.id local chat_type = msg.to.type resolve_username(member, mute_by_username, {chat_id=chat_id, member=member, chat_type=chat_type}) return end end else return '🚫 '..lang_text(msg.to.id, 'require_mod') end elseif matches[1] == 'unmute' then if permissions(msg.from.id, msg.to.id, "unmute") then if msg.reply_id then get_message(msg.reply_id, unmute_by_reply, false) return end if matches[2] then if is_id(matches[2]) then local hash = 'muted:'..msg.to.id..':'..matches[2] redis:del(hash) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(chat_id, 'userUnmuted:1')..' '..matches[2]..' '..lang_text(chat_id, 'userUnmuted:2'), ok_cb, true) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(chat_id, 'userUnmuted:1')..' '..matches[2]..' '..lang_text(chat_id, 'userUnmuted:2'), ok_cb, true) end return else local member = string.gsub(matches[2], '@', '') local chat_id = msg.to.id local chat_type = msg.to.type resolve_username(member, unmute_by_username, {chat_id=chat_id, member=member, chat_type=chat_type}) return end end else return '🚫 '..lang_text(msg.to.id, 'require_mod') end elseif matches[1] == 'kickme' then local hash = 'kickme:'..msg.to.id if redis:get(hash) then if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, '👋🏽 '..lang_text(chat_id, 'kickmeBye')..' @'..msg.from.username..' ('..msg.from.id..').', ok_cb, true) chat_del_user('chat#id'..msg.to.id, 'user#id'..msg.from.id, ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, '👋🏽 '..lang_text(chat_id, 'kickmeBye')..' @'..msg.from.username..' ('..msg.from.id..').', ok_cb, true) channel_kick_user('channel#id'..msg.to.id, 'user#id'..msg.from.id, ok_cb, false) end end end end return { patterns = { "^[!/#](ban) (.*)$", "^[!/#](ban)$", "^[!/#](unban) (.*)$", "^[!/#](unban)$", "^[!/#](kick) (.*)$", "^[!/#](kick)$", "^[!/#](kickme)$", "^[!/#](add) (.*)$", "^[!/#](add)$", "^[!/#](gban) (.*)$", "^[!/#](gban)$", "^[!/#](ungban) (.*)$", "^[!/#](ungban)$", '^[!/#](mute) (.*)$', '^[!/#](mute)$', '^[!/#](unmute) (.*)$', '^[!/#](unmute)$', "^!!tgservice (.*)$" }, run = run, pre_process = pre_process } end
gpl-2.0
thedraked/darkstar
scripts/globals/items/wild_pineapple.lua
18
1180
----------------------------------------- -- ID: 4598 -- Item: wild_pineapple -- Food Effect: 5Min, All Races ----------------------------------------- -- Agility -5 -- Intelligence 3 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,4598); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_AGI, -5); target:addMod(MOD_INT, 3); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_AGI, -5); target:delMod(MOD_INT, 3); end;
gpl-3.0
mtroyka/Zero-K
effects/grav.lua
17
3193
-- grav return { ["grav"] = { drag = { air = true, class = [[CSimpleParticleSystem]], ground = true, water = true, properties = { airdrag = 1, colormap = [[1 .5 1 .1 0 0 0 0]], directional = true, emitrot = 0, emitrotspread = 120, emitvector = [[0,1,0]], gravity = [[0, 0, 0]], numparticles = 3, particlelife = 8, particlelifespread = 3, particlesize = 160, particlesizespread = 80, particlespeed = .1, particlespeedspread = 0, pos = [[0, 1.0, 0]], sizegrowth = -16, sizemod = 1, texture = [[chargeparticles]], }, }, --flash = { -- air = true, -- class = [[CSimpleParticleSystem]], -- count = 1, -- ground = true, -- water = true, -- properties = { -- airdrag = 0, -- colormap = [[0 0 0 .3 0 0 0 0]], -- directional = false, -- emitrot = 0, -- emitrotspread = 180, -- emitvector = [[0, 1, 0]], -- gravity = [[0, 0, 0]], -- numparticles = 1, -- particlelife = 15, -- particlelifespread = 8, -- particlesize = 120, -- particlesizespread = 60, -- particlespeed = 0, -- particlespeedspread = 0, -- pos = [[0, 0, 0]], -- sizegrowth = 1, -- sizemod = 1, -- texture = [[burncircle]], -- }, --}, sphere = { air = true, class = [[CSpherePartSpawner]], count = 1, ground = true, underwater = 1, water = true, properties = { alpha = 1, color = [[0,0,0]], expansionspeed = 7, ttl = 14, }, }, -- flashalt = { -- air = true, -- class = [[CBitmapMuzzleFlame]], -- count = 1, -- ground = true, -- water = true, -- properties = { -- colormap = [[0 0 0 .3 0 0 0 0]], -- dir = [[0 1 0]], -- fronttexture = [[burncircle]], -- frontoffset = 0, -- length = 100, -- pos = [[0, 0, 0]], -- sidetexture = [[burncircle]], -- size = 100, -- sizegrowth = 0, -- ttl = 15, -- }, -- }, -- groundflash = { -- air = true, -- circlealpha = 0.8, -- circlegrowth = 8, -- flashalpha = 0.8, -- flashsize = 140, -- ground = true, -- ttl = 17, -- water = true, -- color = { -- [1] = 0.1, -- [2] = 0.1, -- [3] = 0.1, -- }, -- }, }, }
gpl-2.0
telergybot/1984joorge
plugins/stats.lua
1
3937
do -- Returns a table with `name` and `msgs` local function get_msgs_user_chat(user_id, chat_id) local user_info = {} local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info.msgs = tonumber(redis:get(um_hash) or 0) user_info.name = user_print_name(user)..' ['..user_id..']' return user_info end local function chat_stats(chat_id) -- Users on chat local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} -- Get user info for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end -- Sort users by msgs number table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'users in this chat \n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end local file = io.open("./groups/"..chat_id.."stats.txt", "w") file:write(text) file:flush() file:close() send_document("chat#id"..chat_id,"./groups/"..chat_id.."stats.txt", ok_cb, false) return --text end local function chat_stats2(chat_id) -- Users on chat local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} -- Get user info for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end -- Sort users by msgs number table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'users in this chat \n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end return text end -- Save stats, ban user local function bot_stats() local redis_scan = [[ local cursor = '0' local count = 0 repeat local r = redis.call("SCAN", cursor, "MATCH", KEYS[1]) cursor = r[1] count = count + #r[2] until cursor == '0' return count]] -- Users local hash = 'msgs:*:'..our_id local r = redis:eval(redis_scan, 1, hash) local text = 'Users: '..r hash = 'chat:*:users' r = redis:eval(redis_scan, 1, hash) text = text..'\nGroups: '..r return text end local function run(msg, matches) if matches[1]:lower() == 'info1984' then -- Put everything you like :) local about = _config.about_text local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /teledark ") return about end if matches[1]:lower() == "statslist" then if not is_momod(msg) then return "For mods only !" end local chat_id = msg.to.id local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ") return chat_stats2(chat_id) end if matches[1]:lower() == "stats" then if not matches[2] then if not is_momod(msg) then return "For mods only !" end if msg.to.type == 'chat' then local chat_id = msg.to.id local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ") return chat_stats(chat_id) else return end end if matches[2] == "info1984" then -- Put everything you like :) if not is_admin(msg) then return "For admins only !" else return bot_stats() end end if matches[2] == "group" then if not is_admin(msg) then return "For admins only !" else return chat_stats(matches[3]) end end end end return { patterns = { "^[!/]([Ss]tats)$", "^[!/]([Ss]tatslist)$", "^[!/]([Ss]tats) (group) (%d+)", "^[!/]([Ss]tats) (info1984)",-- Put everything you like :) }, run = run } end
gpl-2.0
yunGit/skynet
lualib/mqueue.lua
115
1798
-- This is a deprecated module, use skynet.queue instead. local skynet = require "skynet" local c = require "skynet.core" local mqueue = {} local init_once local thread_id local message_queue = {} skynet.register_protocol { name = "queue", -- please read skynet.h for magic number 8 id = 8, pack = skynet.pack, unpack = skynet.unpack, dispatch = function(session, from, ...) table.insert(message_queue, {session = session, addr = from, ... }) if thread_id then skynet.wakeup(thread_id) thread_id = nil end end } local function do_func(f, msg) return pcall(f, table.unpack(msg)) end local function message_dispatch(f) while true do if #message_queue==0 then thread_id = coroutine.running() skynet.wait() else local msg = table.remove(message_queue,1) local session = msg.session if session == 0 then local ok, msg = do_func(f, msg) if ok then if msg then skynet.fork(message_dispatch,f) error(string.format("[:%x] send a message to [:%x] return something", msg.addr, skynet.self())) end else skynet.fork(message_dispatch,f) error(string.format("[:%x] send a message to [:%x] throw an error : %s", msg.addr, skynet.self(),msg)) end else local data, size = skynet.pack(do_func(f,msg)) -- 1 means response c.send(msg.addr, 1, session, data, size) end end end end function mqueue.register(f) assert(init_once == nil) init_once = true skynet.fork(message_dispatch,f) end local function catch(succ, ...) if succ then return ... else error(...) end end function mqueue.call(addr, ...) return catch(skynet.call(addr, "queue", ...)) end function mqueue.send(addr, ...) return skynet.send(addr, "queue", ...) end function mqueue.size() return #message_queue end return mqueue
mit
fhedberg/ardupilot
libraries/AP_Scripting/examples/param_get_set_test.lua
15
2308
-- This script is a test of param set and get local count = 0 -- for fast param acess it is better to get a param object, -- this saves the code searching for the param by name every time local VM_I_Count = Parameter() if not VM_I_Count:init('SCR_VM_I_COUNT') then gcs:send_text(6, 'get SCR_VM_I_COUNT failed') end -- returns null if param cant be found local fake_param = Parameter() if not fake_param:init('FAKE_PARAM') then gcs:send_text(6, 'get FAKE_PARAM failed') end function update() -- this is the loop which periodically runs -- get and print all the scripting parameters local value = param:get('SCR_ENABLE') if value then gcs:send_text(6, string.format('LUA: SCR_ENABLE: %i',value)) else gcs:send_text(6, 'LUA: get SCR_ENABLE failed') end value = param:get('SCR_VM_I_COUNT') if value then gcs:send_text(6, string.format('LUA: SCR_VM_I_COUNT: %i',value)) else gcs:send_text(6, 'LUA: get SCR_VM_I_COUNT failed') end value = param:get('SCR_HEAP_SIZE') if value then gcs:send_text(6, string.format('LUA: SCR_HEAP_SIZE: %i',value)) else gcs:send_text(6, 'LUA: get SCR_HEAP_SIZE failed') end value = param:get('SCR_DEBUG_LVL') if value then gcs:send_text(6, string.format('LUA: SCR_DEBUG_LVL: %i',value)) else gcs:send_text(6, 'LUA: get SCR_DEBUG_LVL failed') end -- increment the script heap size by one local heap_size = param:get('SCR_HEAP_SIZE') if heap_size then if not(param:set('SCR_HEAP_SIZE',heap_size + 1)) then gcs:send_text(6, 'LUA: param set failed') end else gcs:send_text(6, 'LUA: get SCR_HEAP_SIZE failed') end -- increment the VM I count by one using direct accsess method local VM_count = VM_I_Count:get() if VM_count then gcs:send_text(6, string.format('LUA: SCR_VM_I_COUNT: %i',VM_count)) if not VM_I_Count:set( VM_count + 1) then gcs:send_text(6, string.format('LUA: failed to set SCR_VM_I_COUNT')) end else gcs:send_text(6, 'LUA: read SCR_VM_I_COUNT failed') end count = count + 1; -- self terminate after 30 loops if count > 30 then gcs:send_text(0, 'LUA: goodbye, world') param:set('SCR_ENABLE',0) end return update, 1000 -- reschedules the loop end return update() -- run immediately before starting to reschedule
gpl-3.0
moomoomoo309/FamiliarFaces
src/love-loader/love-loader.lua
1
7045
require "love.filesystem" require "love.image" require "love.audio" require "love.sound" local loader = { _VERSION = 'love-loader v2.0.2', _DESCRIPTION = 'Threaded resource loading for LÖVE', _URL = 'https://github.com/kikito/love-loader', _LICENSE = [[ MIT LICENSE Copyright (c) 2014 Enrique García Cota, Tanner Rogalsky Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]] } local resourceKinds = { image = { requestKey = "imagePath", resourceKey = "imageData", constructor = love.image.newImageData, postProcess = function(data) return love.graphics.newImage(data) end }, source = { requestKey = "sourcePath", resourceKey = "source", constructor = function(path) return love.audio.newSource(path) end }, font = { requestKey = "fontPath", resourceKey = "fontData", constructor = function(path) -- we don't use love.filesystem.newFileData directly here because there -- are actually two arguments passed to this constructor which in turn -- invokes the wrong love.filesystem.newFileData overload return love.filesystem.newFileData(path) end, postProcess = function(data, resource) local path, size = unpack(resource.requestParams) return love.graphics.newFont(data, size) end }, stream = { requestKey = "streamPath", resourceKey = "stream", constructor = function(path) return love.audio.newSource(path, "stream") end }, soundData = { requestKey = "soundDataPathOrDecoder", resourceKey = "soundData", constructor = love.sound.newSoundData }, imageData = { requestKey = "imageDataPath", resourceKey = "rawImageData", constructor = love.image.newImageData } } local CHANNEL_PREFIX = "loader_" local loaded = ... if loaded == true then local requestParams, resource local done = false local doneChannel = love.thread.getChannel(CHANNEL_PREFIX .. "is_done") while not done do for _, kind in pairs(resourceKinds) do local loader = love.thread.getChannel(CHANNEL_PREFIX .. kind.requestKey) requestParams = loader:pop() if requestParams then resource = kind.constructor(unpack(requestParams)) local producer = love.thread.getChannel(CHANNEL_PREFIX .. kind.resourceKey) producer:push(resource) end end done = doneChannel:pop() end else local pending = {} local callbacks = {} local resourceBeingLoaded local pathToThisFile = (...):gsub("%.", "/") .. ".lua" local function shift(t) return table.remove(t, 1) end local function newResource(kind, holder, key, ...) pending[#pending + 1] = { kind = kind, holder = holder, key = key, requestParams = { ... } } end local function getResourceFromThreadIfAvailable() local data, resource for name, kind in pairs(resourceKinds) do local channel = love.thread.getChannel(CHANNEL_PREFIX .. kind.resourceKey) data = channel:pop() if data then resource = kind.postProcess and kind.postProcess(data, resourceBeingLoaded) or data resourceBeingLoaded.holder[resourceBeingLoaded.key] = resource loader.loadedCount = loader.loadedCount + 1 callbacks.oneLoaded(resourceBeingLoaded.kind, resourceBeingLoaded.holder, resourceBeingLoaded.key) resourceBeingLoaded = nil end end end local function requestNewResourceToThread() resourceBeingLoaded = shift(pending) local requestKey = resourceKinds[resourceBeingLoaded.kind].requestKey local channel = love.thread.getChannel(CHANNEL_PREFIX .. requestKey) channel:push(resourceBeingLoaded.requestParams) end local function endThreadIfAllLoaded() if not resourceBeingLoaded and #pending == 0 then love.thread.getChannel(CHANNEL_PREFIX .. "is_done"):push(true) callbacks.allLoaded() end end ----------------------------------------------------- function loader.newImage(holder, key, path) newResource('image', holder, key, path) end function loader.newFont(holder, key, path, size) newResource('font', holder, key, path, size) end function loader.newSource(holder, key, path, sourceType) local kind = (sourceType == 'stream' and 'stream' or 'source') newResource(kind, holder, key, path) end function loader.newSoundData(holder, key, pathOrDecoder) newResource('soundData', holder, key, pathOrDecoder) end function loader.newImageData(holder, key, path) newResource('imageData', holder, key, path) end function loader.start(allLoadedCallback, oneLoadedCallback) callbacks.allLoaded = allLoadedCallback or function() end callbacks.oneLoaded = oneLoadedCallback or function() end local thread = love.thread.newThread(pathToThisFile) loader.loadedCount = 0 loader.resourceCount = #pending thread:start(true) loader.thread = thread end function loader.update() if loader.thread then if loader.thread:isRunning() then if resourceBeingLoaded then getResourceFromThreadIfAvailable() elseif #pending > 0 then requestNewResourceToThread() else endThreadIfAllLoaded() end else local errorMessage = loader.thread:getError() assert(not errorMessage, errorMessage) end end end return loader end
mit
thedraked/darkstar
scripts/zones/AlTaieu/npcs/_0x0.lua
14
2215
----------------------------------- -- Area: Al'Taieu -- NPC: Crystalline Field -- @pos .1 -10 -464 33 ----------------------------------- package.loaded["scripts/zones/AlTaieu/TextIDs"] = nil; ----------------------------------- require("scripts/zones/AlTaieu/TextIDs"); require("scripts/globals/missions"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) -- Set the PromathiaStatus to 3 if they did all 3 towers for GARDEN_OF_ANTIQUITY if (player:getVar("[SEA][AlTieu]SouthTowerCS") == 1 and player:getVar("[SEA][AlTieu]WestTowerCS") == 1 and player:getVar("[SEA][AlTieu]EastTowerCS") == 1 and player:getVar("PromathiaStatus") == 2) then player:setVar("[SEA][AlTieu]SouthTowerCS", 0); player:setVar("[SEA][AlTieu]WestTowerCS", 0); player:setVar("[SEA][AlTieu]EastTowerCS", 0); player:setVar("PromathiaStatus", 3); end if (player:getCurrentMission(COP) == GARDEN_OF_ANTIQUITY and player:getVar("PromathiaStatus") == 1) then player:startEvent(0x00A4); elseif (player:getCurrentMission(COP) > GARDEN_OF_ANTIQUITY or (player:getCurrentMission(COP) == GARDEN_OF_ANTIQUITY and player:getVar("PromathiaStatus") == 3)) then player:startEvent(0x0064); -- Teleport inside else player:messageSpecial(NOTHING_OUT_OF_ORDINARY); -- Access should be restricted if below requirements. Message is probably wrong, though. end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x0064 and option == 1) then player:setPos(-20,0.624,-355,191,34); -- {R} elseif (csid == 0x00A4) then player:setVar("PromathiaStatus", 2); end end;
gpl-3.0
NPLPackages/main
script/test/TestIO.lua
1
14139
--[[ Author: LiXizhi Date: 2008-12-7 Desc: testing IO ----------------------------------------------- NPL.load("(gl)script/test/TestIO.lua"); ----------------------------------------------- ]] -- convert everything in a folder to UTF8 encoding -- %TESTCASE{"Test_io_OpenFileDialog", func = "Test_io_OpenFileDialog", input = {filter="*.*"},}% function Test_io_OpenFileDialog(input) input = input or {}; if(ParaGlobal.OpenFileDialog(input)) then commonlib.echo(input); end --local input = {filter="All Files (*.*)\0*.*\0", initialdir=ParaIO.AutoFindParaEngineRootPath("")}; --if(ParaGlobal.OpenFileDialog(input)) then --commonlib.echo(input); --end end -- convert everything in a folder to UTF8 encoding -- %TESTCASE{"test_io_ConvertFileToUTF8", func = "test_io_ConvertFileToUTF8", input = {folder="script/test/", filter="*.lua"},}% function test_io_ConvertFileToUTF8(input) -- list all files in the initial directory. local search_result = ParaIO.SearchFiles(input.folder,input.filter, "", 15, 10000, 0); local nCount = search_result:GetNumOfResult(); local i; for i = 0, nCount-1 do local filename = input.folder..search_result:GetItem(i); local text; local file = ParaIO.open(filename, "r"); if(file:IsValid()) then -- get text with BOM heading local text = file:GetText(0, -1); -- check the BOM at the beginning of the file local isUTF8; if(text) then isUTF8 = (string.byte(text, 1) == tonumber("EF", 16) and string.byte(text, 2) == tonumber("BB", 16) and string.byte(text, 3) == tonumber("BF", 16)) or (string.byte(text, 1) == tonumber("FF", 16) and string.byte(text, 2) == tonumber("FE", 16)) or (string.byte(text, 1) == tonumber("FE", 16) and string.byte(text, 2) == tonumber("FF", 16)) end local puretext = file:GetText(); file:close(); if(not isUTF8) then file = ParaIO.open(filename, "w"); if(file:IsValid()) then -- write utf8 BOM file:WriteString(string.char(tonumber("EF", 16), tonumber("BB", 16), tonumber("BF", 16))) -- convert file:WriteString(ParaMisc.EncodingConvert("", "utf-8", puretext)); file:close(); end log("->"..filename.."\n") else --file = ParaIO.open(filename, "w"); --if(file:IsValid()) then ---- remove utf8 BOM header --file:WriteString(puretext) ---- convert --file:close(); --end log("->(skip)"..filename.."\n") end end end search_result:Release(); end -- convert everything in a folder to UTF8 encoding -- %TESTCASE{"test_io_CheckFileEncoding", func = "test_io_CheckFileEncoding", input = {folder="script/test/", filter="*.lua"},}% function test_io_CheckFileEncoding(input) -- list all files in the initial directory. local search_result = ParaIO.SearchFiles(input.folder,input.filter, "", 15, 10000, 0); local nCount = search_result:GetNumOfResult(); local i; for i = 0, nCount-1 do local filename = input.folder..search_result:GetItem(i); local text; local file = ParaIO.open(filename, "r"); if(file:IsValid()) then -- get text with BOM heading local text = file:GetText(0, -1); -- check the BOM at the beginning of the file local isUTF8; local isUTF16; if(text) then isUTF8 = (string.byte(text, 1) == tonumber("EF", 16) and string.byte(text, 2) == tonumber("BB", 16) and string.byte(text, 3) == tonumber("BF", 16)) isUTF16 = (string.byte(text, 1) == tonumber("FF", 16) and string.byte(text, 2) == tonumber("FE", 16)) or (string.byte(text, 1) == tonumber("FE", 16) and string.byte(text, 2) == tonumber("FF", 16)) end file:close(); if(isUTF8) then log("->(utf8)"..filename.."\n") elseif(isUTF16) then log("->(utf16)"..filename.."\n") else log("->"..filename.."\n") end end end search_result:Release(); end -- convert everything in a folder to UTF8 encoding -- %TESTCASE{"test_IO_printFile_toLOG", func = "test_IO_printFile_toLOG", input = {filename="script/kids/3DMapSystemApp/API/test/paraworld.map.test.lua", isUTF8="true"},}% function test_IO_printFile_toLOG(input) log("\r\n") local file = ParaIO.open(input.filename, "r"); if(file:IsValid()) then --local text = file:GetText(0, -1); local text = file:GetText(); if(input.isUTF8 ~= "true") then -- convert to UTF8 text = ParaMisc.EncodingConvert("", "utf-8", text) log("converting to UTF8\n") end --text = ParaMisc.EncodingConvert("utf-8", "", text) commonlib.log(text); file:close(); end end function test_file_conversion() -- convert all files under a folder NPL.load("(gl)script/ide/Files.lua"); local result = commonlib.Files.Find({}, "xmodels/character/Spells/", 0, 500, "*.m2") local i, file for i,file in pairs(result) do ParaEngine.ConvertFile("xmodels/character/Spells/"..file.filename, "character/m2/Spells/"..string.gsub(file.filename, "m2$", "x")); end local result = commonlib.Files.Find({}, "xmodels/m2/CREATURE/", 1, 500, "*.m2") local i, file for i,file in pairs(result) do ParaEngine.ConvertFile("xmodels/m2/CREATURE/"..file.filename, "character/m2/Creature/"..string.gsub(file.filename, "m2$", "x")); end --ParaEngine.ConvertFile("xmodels/character/Spells/AbolishMagic_Base.m2", "character/m2/Spells/AbolishMagic_Base.x"); --ParaEngine.ConvertFile("xmodels/m2/CREATURE/AncientOfLore/AncientOfLore.m2", "character/m2/Creature/AncientOfLore/AncientOfLore.x"); end -- test open a file in asset manifest list. function test_IO_OpenAssetFile() commonlib.echo({["model/Skybox/skybox3/snowblind_up.dds"] = ParaIO.DoesAssetFileExist("model/skybox/skybox3/snowblind_up.dds")}); local file = ParaIO.OpenAssetFile("model/Skybox/skybox3/Skybox3.x"); if(file:IsValid()) then local line; repeat line = file:readline() echo(line); until(not line) file:close(); end end function test_IO_readline() local file = ParaIO.open("temp/test_readline.txt", "w"); if(file:IsValid()) then file:WriteString("win line ending \r\n linux line ending \n last line without line ending") file:close(); end local file = ParaIO.open("temp/test_readline.txt", "r"); if(file:IsValid()) then local line; repeat line = file:readline() echo(line); until(not line) file:close(); end end function test_IO_SyncAssetFile_Async_callback() commonlib.log("asset file download is completed. msg.res = %d", msg.res) commonlib.echo(msg); -- msg.res == 1 means succeed end -- test IO file function test_IO_SyncAssetFile_Async() local filename = "model/05plants/01flower/02flower/m_vegetation_3.png"; if(ParaIO.CheckAssetFile(filename) ~= 1) then commonlib.echo({file=filename, "is not downloaded yet"}) ParaIO.SyncAssetFile_Async(filename, ";test_IO_SyncAssetFile_Async_callback();") end end -- test IO write/read binary file function test_IO_BinaryFile() local file = ParaIO.open("temp/binaryfile.bin", "w"); if(file:IsValid()) then local data = "binary\0\0\0\0file"; file:WriteString(data, #data); -- write 32 bits int file:WriteUInt(0xffffffff); file:WriteInt(-1); -- write float file:WriteFloat(-3.14); -- write double (precision is limited by lua double) file:WriteDouble(-3.1415926535897926); -- write 16bits word file:WriteWord(0xff00); -- write 16bits short integer file:WriteShort(-1); file:WriteBytes(3, {255, 0, 255}); file:close(); -- testing by reading file content back local file = ParaIO.open("temp/binaryfile.bin", "r"); if(file:IsValid()) then -- test reading binary string without increasing the file cursor assert(file:GetText(0, #data) == data); file:seekRelative(#data); assert(file:getpos() == #data); file:seek(0); -- test reading binary string assert(file:ReadString(#data) == data); assert(file:ReadUInt() == 0xffffffff); assert(file:ReadInt() == -1); assert(math.abs(file:ReadFloat() - (-3.14)) < 0.000001); assert(file:ReadDouble() == -3.1415926535897926); assert(file:ReadWord() == 0xff00); assert(file:ReadShort() == -1); local o = {}; file:ReadBytes(3, o); assert(o[1] == 255 and o[2] == 0 and o[3] == 255); file:seek(0); assert(file:ReadString(8) == "binary\0\0"); file:close(); end end end -- test IO write/read binary file in "rw" mode function test_IO_BinaryFileReadWrite() -- "rw" mode will not destroy the content of existing file. local file = ParaIO.open("temp/binaryfile.bin", "rw"); if(file:IsValid()) then local data = "binary\0\0\0\0file"; file:WriteString(data, #data); -- write 32 bits int file:WriteUInt(0xffffffff); file:WriteInt(-1); -- write float file:WriteFloat(-3.14); -- write double (precision is limited by lua double) file:WriteDouble(-3.1415926535897926); -- write 16bits word file:WriteWord(0xff00); -- write 16bits short integer file:WriteShort(-1); file:WriteBytes(3, {255, 0, 255}); file:SetEndOfFile(); ----------------------------------------- -- testing by reading file content back ----------------------------------------- file:seek(0); -- test reading binary string without increasing the file cursor assert(file:GetText(0, #data) == data); file:seekRelative(#data); assert(file:getpos() == #data); file:seek(0); -- test reading binary string assert(file:ReadString(#data) == data); assert(file:ReadUInt() == 0xffffffff); assert(file:ReadInt() == -1); assert(math.abs(file:ReadFloat() - (-3.14)) < 0.000001); assert(file:ReadDouble() == -3.1415926535897926); assert(file:ReadWord() == 0xff00); assert(file:ReadShort() == -1); local o = {}; file:ReadBytes(3, o); assert(o[1] == 255 and o[2] == 0 and o[3] == 255); file:seek(0); assert(file:ReadString(8) == "binary\0\0"); file:close(); end end -- test file system watcher function test_io_FileSystemWatcher() -- we will modify file changes under temp and model directory. local watcher = ParaIO.GetFileSystemWatcher("temp/"); -- watcher:AddDirectory("E:\\Downloads\\"); watcher:AddDirectory("temp/"); watcher:AddCallback("commonlib.echo(msg);"); end -- test file system watcher function test_io_GeneratePKG() assert(ParaAsset.GeneratePkgFile("installer/main.zip", "installer/main.test.pkg")) end function test_CreateZip() -- testing creating zip files local zipname = "temp/simple.zip"; local writer = ParaIO.CreateZip(zipname,""); --writer:ZipAdd("lua.dll", "lua.dll"); writer:ZipAdd("aaa.txt", "deletefile.list"); --writer:ZipAddFolder("temp"); -- writer:AddDirectory("worlds/", "d:/temp/*.", 4); writer:close(); -- test reading from the zip file. ParaAsset.OpenArchive(zipname); ParaIO.CopyFile("aaa.txt", "temp/aaa.txt", true); ParaAsset.CloseArchive(zipname); end --NPL.load("(gl)script/ide/UnitTest/luaunit.lua"); --SampleTestSuite = wrapFunctions( 'test_io_GeneratePKG') --ParaGlobal.Exit(LuaUnit:run('SampleTestSuite')); function test_MemoryFile() -- "<memory>" is a special name for memory file, both read/write is possible. local file = ParaIO.open("<memory>", "w"); if(file:IsValid()) then file:WriteString("hello "); local nPos = file:GetFileSize(); file:WriteString("world"); file:WriteInt(1234); file:seek(nPos); file:WriteString("World"); file:SetFilePointer(0, 2); -- 2 is relative to end of file file:WriteInt(0); file:WriteBytes(3, {100, 0, 22}); file:WriteString("End"); -- read entire binary text data back to npl string echo(#(file:GetText(0, -1))); file:close(); end end function test_process_open() -- NPL.load("script/ide/commonlib.lua"); local file = assert(io.popen('/bin/ls -la', 'r')) local output = file:read('*all') file:close() echo(output) -- exit(1) end -- OBSOLETED, use ParaIO.open(filename, "image") instead -- test passed on 2008.1.17, LiXizhi local function ParaIO_openimageTest() -- OBSOLETED, use ParaIO.open(filename, "image") instead local file = ParaIO.openimage("Texture/alphadot.png", "a8r8g8b8"); if(file:IsValid()) then local nSize = file:GetFileSize(); local nImageWidth = math.sqrt(nSize/4); -- output each pixel of the image to log local pixel = {} local x,y; for x=1, nImageWidth do for y=1, nImageWidth do -- read four bytes to pixel. file:ReadBytes(4, pixel); log(string.format("%d,%d:\tB=%d, G=%d, R=%d, A=%d\n", x,y,pixel[1],pixel[2],pixel[3],pixel[4])); end end end file:close(); end function test_reading_image_file() -- reading binary image file -- png, jpg format are supported. local filename = "Texture/alphadot.png"; local file = ParaIO.open(filename, "image"); if(file:IsValid()) then local ver = file:ReadInt(); local width = file:ReadInt(); local height = file:ReadInt(); -- how many bytes per pixel, usually 1, 3 or 4 local bytesPerPixel = file:ReadInt(); echo({ver, width=width, height = height, bytesPerPixel = bytesPerPixel}) local pixel = {}; for y=1, height do for x=1, width do pixel = file:ReadBytes(bytesPerPixel, pixel); echo({x, y, rgb=pixel}) end end file:close(); end end function test_search_zipfile() local zipPath = "temp/test.zip"; -- open with relative file path if(ParaAsset.OpenArchive(zipPath, true)) then local zip_archive = ParaEngine.GetAttributeObject():GetChild("AssetManager"):GetChild("CFileManager"):GetChild(zipPath); -- zipParentDir is usually the parent directory "temp/" of zip file. local zipParentDir = zip_archive:GetField("RootDirectory", ""); echo(zipParentDir); -- search just in a given zip archive file local filesOut = {}; -- ":.", any regular expression after : is supported. `.` match to all strings. commonlib.Files.Find(filesOut, "", 0, 10000, ":.", zipPath); -- print all files in zip file for i = 1,#filesOut do local item = filesOut[i]; echo(item.filename .. " size: "..item.filesize); if(item.filesize > 0) then local file = ParaIO.open(zipParentDir..item.filename, "r") if(file:IsValid()) then -- get binary data local binData = file:GetText(0, -1); -- dump the first few characters in the file echo(binData:sub(1, 10)); file:close(); end else -- this is a folder end end ParaAsset.CloseArchive(zipPath); end end
gpl-2.0
kaustavha/luvit
deps/utils.lua
6
2726
--[[ Copyright 2014-2015 The Luvit Authors. All Rights Reserved. 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 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. --]] exports.name = "luvit/utils" exports.version = "1.0.0-4" exports.dependencies = { "luvit/pretty-print@1.0.3", } exports.license = "Apache 2" exports.homepage = "https://github.com/luvit/luvit/blob/master/deps/utils.lua" exports.description = "Wrapper around pretty-print with extra tools for luvit" exports.tags = {"luvit", "bind", "adapter"} local Error = require('core').Error local pp = require('pretty-print') for name, value in pairs(pp) do exports[name] = value end local function bind(fn, self, ...) assert(fn, "fn is nil") local bindArgsLength = select("#", ...) -- Simple binding, just inserts self (or one arg or any kind) if bindArgsLength == 0 then return function (...) return fn(self, ...) end end -- More complex binding inserts arbitrary number of args into call. local bindArgs = {...} return function (...) local argsLength = select("#", ...) local args = {...} local arguments = {} for i = 1, bindArgsLength do arguments[i] = bindArgs[i] end for i = 1, argsLength do arguments[i + bindArgsLength] = args[i] end return fn(self, unpack(arguments, 1, bindArgsLength + argsLength)) end end local function noop(err) if err then print("Unhandled callback error", err) end end local function adapt(c, fn, ...) local nargs = select('#', ...) local args = {...} -- No continuation defaults to noop callback if not c then c = noop end local t = type(c) if t == 'function' then args[nargs + 1] = c return fn(unpack(args)) elseif t ~= 'thread' then error("Illegal continuation type " .. t) end local err, data, waiting args[nargs + 1] = function (e, ...) if waiting then if e then assert(coroutine.resume(c, nil, e)) else assert(coroutine.resume(c, ...)) end else err, data = e and Error:new(e), {...} c = nil end end fn(unpack(args)) if c then waiting = true return coroutine.yield(c) elseif err then return nil, err else return unpack(data) end end exports.bind = bind exports.noop = noop exports.adapt = adapt
apache-2.0
thedraked/darkstar
scripts/globals/mobskills/Wind_Shear.lua
36
1145
--------------------------------------------- -- Wind Shear -- -- Description: Deals damage to enemies within an area of effect. Additional effect: Knockback -- Type: Physical -- Utsusemi/Blink absorb: 2-3 shadows -- Range: 10' radial -- Notes: The knockback is rather severe. Vulpangue uses an enhanced version that inflicts Weight. --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) if(mob:getFamily() == 91) then local mobSkin = mob:getModelId(); if (mobSkin == 1746) then return 0; else return 1; end end return 0; end; function onMobWeaponSkill(target, mob, skill) local numhits = math.random(2,3); local accmod = 1; local dmgmod = .8; local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_SLASH,info.hitslanded); target:delHP(dmg); return dmg; end;
gpl-3.0
rjeli/luvit
examples/broken/app/modules/stack.lua
9
2997
--[[ Copyright 2012 The Luvit Authors. All Rights Reserved. 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 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 url = require('url') local stack = {} function stack.stack(...) local errorHandler = stack.errorHandler local handle = errorHandler local layers = {...} for i = #layers, 1, -1 do local layer = layers[i] local child = handle handle = function(req, res) local success, err = pcall(function () layer(req, res, function (err) if err then return errorHandler(req, res, err) end child(req, res) end) end) if not success and err then errorHandler(req, res, err) end end end return handle end local function core(req, res, continue) continue() end -- Build a composite stack made of several layers function stack.compose(...) local layers = {...} -- Don't bother composing singletons if #layers == 1 then return layers[1] end local stack = core for i = #layers, 1, -1 do local layer = layers[i] local child = stack stack = function (req, res, continue) local success, err = pcall(function () layer(req, res, function (err) if err then return continue(err) end child(req, res, continue) end) end) if not success and err then continue(err) end end end return stack end -- Mounts a substack app at a url subtree function stack.mount(mountpoint, ...) if mountpoint:sub(#mountpoint) == "/" then mountpoint = mountpoint:sub(1, #mountpoint - 1) end local matchpoint = mountpoint .. "/" return stack.translate(mountpoint, matchpoint, ...) end function stack.translate(mountpoint, matchpoint, ...) local stack = stack.compose(...) return function(req, res, continue) local url = req.url local uri = req.uri if not (url:sub(1, #matchpoint) == matchpoint) then return continue() end -- Modify the url if not req.real_url then req.real_url = url end req.url = url:sub(#mountpoint + 1) -- We only want to set the parsed uri if there was already one there if req.uri then req.uri = url.parse(req.url) end stack(req, res, function (err) req.url = url req.uri = uri continue(err) end) end end local Debug = require('debug') function stack.errorHandler(req, res, err) if err then res:setCode(500) res:finish(Debug.traceback(err) .. "\n") return end res:setCode(404) res:finish("Not Found\n") end return stack
apache-2.0
thedraked/darkstar
scripts/globals/spells/jubaku_ichi.lua
27
1733
----------------------------------------- -- Spell: Jubaku: Ichi -- Spell accuracy is most highly affected by Enfeebling Magic Skill, Magic Accuracy, and INT. -- taken from paralyze ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local effect = EFFECT_PARALYSIS; -- Base Stats local dINT = (caster:getStat(MOD_INT) - target:getStat(MOD_INT)); --Duration Calculation local duration = 180 * applyResistance(caster,spell,target,dINT,NINJUTSU_SKILL,0); --Paralyze base power is 20 and is not affected by resistaces. local power = 20; --Calculates resist chanve from Reist Blind if (math.random(0,100) >= target:getMod(MOD_PARALYZERES)) then if (duration >= 80) then -- Erases a weaker blind and applies the stronger one local paralysis = target:getStatusEffect(effect); if (paralysis ~= nil) then if (paralysis:getPower() < power) then target:delStatusEffect(effect); target:addStatusEffect(effect,power,0,duration); spell:setMsg(237); else -- no effect spell:setMsg(75); end else target:addStatusEffect(effect,power,0,duration); spell:setMsg(237); end else spell:setMsg(85); end else spell:setMsg(284); end return effect; end;
gpl-3.0
thedraked/darkstar
scripts/zones/Bastok-Jeuno_Airship/TextIDs.lua
22
1080
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 6379; -- You cannot obtain the item <item> come back again after sorting your inventory ITEM_OBTAINED = 6384; -- Obtained: <item> GIL_OBTAINED = 6385; -- Obtained <number> gil KEYITEM_OBTAINED = 6387; -- Obtained key item: <keyitem> -- Other WILL_REACH_JEUNO = 7204; -- The airship will reach Jeuno in Multiple Choice (Parameter 1)[less than an hour/about 1 hour/about 2 hours/about 3 hours/about 4 hours/about 5 hours/about 6 hours/about 7 hours] ( Singular/Plural Choice (Parameter 0)[minute/minutes] in Earth time). WILL_REACH_BASTOK = 7205; -- The airship will reach Bastok in Multiple Choice (Parameter 1)[less than an hour/about 1 hour/about 2 hours/about 3 hours/about 4 hours/about 5 hours/about 6 hours/about 7 hours] ( Singular/Plural Choice (Parameter 0)[minute/minutes] in Earth time). IN_JEUNO_MOMENTARILY = 7206; -- We will be arriving in Jeuno momentarily. IN_BASTOK_MOMENTARILY = 7207; -- We will be arriving in Bastok momentarily.
gpl-3.0
SnabbCo/snabbswitch
lib/ljsyscall/test/osx.lua
5
1757
-- OSX specific tests local function init(S) local helpers = require "test.helpers" local types = S.types local c = S.c local abi = S.abi local bit = require "syscall.bit" local ffi = require "ffi" local t, pt, s = types.t, types.pt, types.s local assert = helpers.assert local function fork_assert(cond, err, ...) -- if we have forked we need to fail in main thread not fork if not cond then print(tostring(err)) print(debug.traceback()) S.exit("failure") end if cond == true then return ... end return cond, ... end local function assert_equal(...) collectgarbage("collect") -- force gc, to test for bugs return assert_equals(...) end local teststring = "this is a test string" local size = 512 local buf = t.buffer(size) local tmpfile = "XXXXYYYYZZZ4521" .. S.getpid() local tmpfile2 = "./666666DDDDDFFFF" .. S.getpid() local tmpfile3 = "MMMMMTTTTGGG" .. S.getpid() local longfile = "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890" .. S.getpid() local efile = "./tmpexXXYYY" .. S.getpid() .. ".sh" local largeval = math.pow(2, 33) -- larger than 2^32 for testing local mqname = "ljsyscallXXYYZZ" .. S.getpid() local clean = function() S.rmdir(tmpfile) S.unlink(tmpfile) S.unlink(tmpfile2) S.unlink(tmpfile3) S.unlink(longfile) S.unlink(efile) end local test = {} test.time = { -- example of how to emulate clock_gettime() https://gist.github.com/jbenet/1087739 test_clock_get_time = function() local clock = assert(S.host_get_clock_service(S.mach_host_self(), "CALENDAR")) local mts = assert(S.clock_get_time(clock)) assert(S.mach_port_deallocate(nil, clock)) -- TODO this should be gc end } return test end return {init = init}
apache-2.0
Abollfazl2/Robocop
plugins/moderation.lua
336
9979
do local function check_member(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then local username = v.username data[tostring(msg.to.id)] = { moderators = {[tostring(member_id)] = username}, settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'no', lock_photo = 'no', lock_member = 'no' } } save_data(_config.moderation.data, data) return send_large_msg(receiver, 'You have been promoted as moderator for this group.') end end end local function automodadd(msg) local data = load_data(_config.moderation.data) if msg.action.type == 'chat_created' then receiver = get_receiver(msg) chat_info(receiver, check_member,{receiver=receiver, data=data, msg = msg}) else if data[tostring(msg.to.id)] then return 'Group is already added.' end if msg.from.username then username = msg.from.username else username = msg.from.print_name end -- create data array in moderation.json data[tostring(msg.to.id)] = { moderators ={[tostring(msg.from.id)] = username}, settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'no', lock_photo = 'no', lock_member = 'no' } } save_data(_config.moderation.data, data) return 'Group has been added, and @'..username..' has been promoted as moderator for this group.' end end local function modadd(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then return 'Group is already added.' end -- create data array in moderation.json data[tostring(msg.to.id)] = { moderators ={}, settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'no', lock_photo = 'no', lock_member = 'no' } } save_data(_config.moderation.data, data) return 'Group has been added.' end local function modrem(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if not data[tostring(msg.to.id)] then return 'Group is not added.' end data[tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) return 'Group has been removed' end local function promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'chat#id', '') if not data[group] then return send_large_msg(receiver, 'Group is not added.') end if data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is already a moderator.') end data[group]['moderators'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been promoted.') end local function demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'chat#id', '') if not data[group] then return send_large_msg(receiver, 'Group is not added.') end if not data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is not a moderator.') end data[group]['moderators'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been demoted.') end local function admin_promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is already as admin.') end data['admins'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been promoted as admin.') end local function admin_demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if not data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is not an admin.') end data['admins'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Admin '..member_username..' has been demoted.') end local function username_id(cb_extra, success, result) local mod_cmd = cb_extra.mod_cmd local receiver = cb_extra.receiver local member = cb_extra.member local text = 'No user @'..member..' in this group.' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.id if mod_cmd == 'promote' then return promote(receiver, member_username, member_id) elseif mod_cmd == 'demote' then return demote(receiver, member_username, member_id) elseif mod_cmd == 'adminprom' then return admin_promote(receiver, member_username, member_id) elseif mod_cmd == 'admindem' then return admin_demote(receiver, member_username, member_id) end end end send_large_msg(receiver, text) end local function modlist(msg) local data = load_data(_config.moderation.data) if not data[tostring(msg.to.id)] then return 'Group is not added.' end -- determine if table is empty if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way return 'No moderator in this group.' end local message = 'List of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do message = message .. '- '..v..' [' ..k.. '] \n' end return message end local function admin_list(msg) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if next(data['admins']) == nil then --fix way return 'No admin available.' end local message = 'List for Bot admins:\n' for k,v in pairs(data['admins']) do message = message .. '- ' .. v ..' ['..k..'] \n' end return message end function run(msg, matches) if matches[1] == 'debug' then return debugs(msg) end if not is_chat_msg(msg) then return "Only works on group" end local mod_cmd = matches[1] local receiver = get_receiver(msg) if matches[1] == 'modadd' then return modadd(msg) end if matches[1] == 'modrem' then return modrem(msg) end if matches[1] == 'promote' and matches[2] then if not is_momod(msg) then return "Only moderator can promote" end local member = string.gsub(matches[2], "@", "") chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end if matches[1] == 'demote' and matches[2] then if not is_momod(msg) then return "Only moderator can demote" end if string.gsub(matches[2], "@", "") == msg.from.username then return "You can't demote yourself" end local member = string.gsub(matches[2], "@", "") chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end if matches[1] == 'modlist' then return modlist(msg) end if matches[1] == 'adminprom' then if not is_admin(msg) then return "Only sudo can promote user as admin" end local member = string.gsub(matches[2], "@", "") chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end if matches[1] == 'admindem' then if not is_admin(msg) then return "Only sudo can promote user as admin" end local member = string.gsub(matches[2], "@", "") chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end if matches[1] == 'adminlist' then if not is_admin(msg) then return 'Admin only!' end return admin_list(msg) end if matches[1] == 'chat_add_user' and msg.action.user.id == our_id then return automodadd(msg) end if matches[1] == 'chat_created' and msg.from.id == 0 then return automodadd(msg) end end return { description = "Moderation plugin", usage = { moderator = { "!promote <username> : Promote user as moderator", "!demote <username> : Demote user from moderator", "!modlist : List of moderators", }, admin = { "!modadd : Add group to moderation list", "!modrem : Remove group from moderation list", }, sudo = { "!adminprom <username> : Promote user as admin (must be done from a group)", "!admindem <username> : Demote user from admin (must be done from a group)", }, }, patterns = { "^!(modadd)$", "^!(modrem)$", "^!(promote) (.*)$", "^!(demote) (.*)$", "^!(modlist)$", "^!(adminprom) (.*)$", -- sudoers only "^!(admindem) (.*)$", -- sudoers only "^!(adminlist)$", "^!!tgservice (chat_add_user)$", "^!!tgservice (chat_created)$", }, run = run, } end
gpl-2.0
master041/tele-master-asli
plugins/moderation.lua
336
9979
do local function check_member(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then local username = v.username data[tostring(msg.to.id)] = { moderators = {[tostring(member_id)] = username}, settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'no', lock_photo = 'no', lock_member = 'no' } } save_data(_config.moderation.data, data) return send_large_msg(receiver, 'You have been promoted as moderator for this group.') end end end local function automodadd(msg) local data = load_data(_config.moderation.data) if msg.action.type == 'chat_created' then receiver = get_receiver(msg) chat_info(receiver, check_member,{receiver=receiver, data=data, msg = msg}) else if data[tostring(msg.to.id)] then return 'Group is already added.' end if msg.from.username then username = msg.from.username else username = msg.from.print_name end -- create data array in moderation.json data[tostring(msg.to.id)] = { moderators ={[tostring(msg.from.id)] = username}, settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'no', lock_photo = 'no', lock_member = 'no' } } save_data(_config.moderation.data, data) return 'Group has been added, and @'..username..' has been promoted as moderator for this group.' end end local function modadd(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then return 'Group is already added.' end -- create data array in moderation.json data[tostring(msg.to.id)] = { moderators ={}, settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'no', lock_photo = 'no', lock_member = 'no' } } save_data(_config.moderation.data, data) return 'Group has been added.' end local function modrem(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if not data[tostring(msg.to.id)] then return 'Group is not added.' end data[tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) return 'Group has been removed' end local function promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'chat#id', '') if not data[group] then return send_large_msg(receiver, 'Group is not added.') end if data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is already a moderator.') end data[group]['moderators'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been promoted.') end local function demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'chat#id', '') if not data[group] then return send_large_msg(receiver, 'Group is not added.') end if not data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is not a moderator.') end data[group]['moderators'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been demoted.') end local function admin_promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is already as admin.') end data['admins'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been promoted as admin.') end local function admin_demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if not data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is not an admin.') end data['admins'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Admin '..member_username..' has been demoted.') end local function username_id(cb_extra, success, result) local mod_cmd = cb_extra.mod_cmd local receiver = cb_extra.receiver local member = cb_extra.member local text = 'No user @'..member..' in this group.' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.id if mod_cmd == 'promote' then return promote(receiver, member_username, member_id) elseif mod_cmd == 'demote' then return demote(receiver, member_username, member_id) elseif mod_cmd == 'adminprom' then return admin_promote(receiver, member_username, member_id) elseif mod_cmd == 'admindem' then return admin_demote(receiver, member_username, member_id) end end end send_large_msg(receiver, text) end local function modlist(msg) local data = load_data(_config.moderation.data) if not data[tostring(msg.to.id)] then return 'Group is not added.' end -- determine if table is empty if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way return 'No moderator in this group.' end local message = 'List of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do message = message .. '- '..v..' [' ..k.. '] \n' end return message end local function admin_list(msg) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if next(data['admins']) == nil then --fix way return 'No admin available.' end local message = 'List for Bot admins:\n' for k,v in pairs(data['admins']) do message = message .. '- ' .. v ..' ['..k..'] \n' end return message end function run(msg, matches) if matches[1] == 'debug' then return debugs(msg) end if not is_chat_msg(msg) then return "Only works on group" end local mod_cmd = matches[1] local receiver = get_receiver(msg) if matches[1] == 'modadd' then return modadd(msg) end if matches[1] == 'modrem' then return modrem(msg) end if matches[1] == 'promote' and matches[2] then if not is_momod(msg) then return "Only moderator can promote" end local member = string.gsub(matches[2], "@", "") chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end if matches[1] == 'demote' and matches[2] then if not is_momod(msg) then return "Only moderator can demote" end if string.gsub(matches[2], "@", "") == msg.from.username then return "You can't demote yourself" end local member = string.gsub(matches[2], "@", "") chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end if matches[1] == 'modlist' then return modlist(msg) end if matches[1] == 'adminprom' then if not is_admin(msg) then return "Only sudo can promote user as admin" end local member = string.gsub(matches[2], "@", "") chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end if matches[1] == 'admindem' then if not is_admin(msg) then return "Only sudo can promote user as admin" end local member = string.gsub(matches[2], "@", "") chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end if matches[1] == 'adminlist' then if not is_admin(msg) then return 'Admin only!' end return admin_list(msg) end if matches[1] == 'chat_add_user' and msg.action.user.id == our_id then return automodadd(msg) end if matches[1] == 'chat_created' and msg.from.id == 0 then return automodadd(msg) end end return { description = "Moderation plugin", usage = { moderator = { "!promote <username> : Promote user as moderator", "!demote <username> : Demote user from moderator", "!modlist : List of moderators", }, admin = { "!modadd : Add group to moderation list", "!modrem : Remove group from moderation list", }, sudo = { "!adminprom <username> : Promote user as admin (must be done from a group)", "!admindem <username> : Demote user from admin (must be done from a group)", }, }, patterns = { "^!(modadd)$", "^!(modrem)$", "^!(promote) (.*)$", "^!(demote) (.*)$", "^!(modlist)$", "^!(adminprom) (.*)$", -- sudoers only "^!(admindem) (.*)$", -- sudoers only "^!(adminlist)$", "^!!tgservice (chat_add_user)$", "^!!tgservice (chat_created)$", }, run = run, } end
gpl-2.0
mtroyka/Zero-K
lups/ParticleClasses/NanoLasers.lua
11
11424
-- $Id: NanoLasers.lua 3357 2008-12-05 11:08:54Z jk $ ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- local NanoLasers = {} NanoLasers.__index = NanoLasers local dlist local laserShader local knownNanoLasers = {} local lastTexture = "" ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- function NanoLasers.GetInfo() return { name = "NanoLasers", backup = "NanoLasersNoShader", --// backup class, if this class doesn't work (old cards,ati's,etc.) desc = "", layer = -16, --// extreme simply z-ordering :x --// gfx requirement fbo = false, shader = true, rtt = false, ctt = false, } end NanoLasers.Default = { layer = 0, worldspace = true, repeatEffect = false, --// shared options with all nanofx pos = {0,0,0}, --// start pos targetpos = {0,0,0}, targetradius = 0, --// terraform/unit radius color = {0, 0, 0, 0}, count = 1, inversed = false, --// reclaim? terraform = false, --// for terraform (2d target) unit = -1, nanopiece = -1, --// some unit informations targetID = -1, unitID = -1, unitpiece = -1, unitDefID = -1, teamID = -1, allyID = -1, --// custom (user) options life = 30, flare = false, streamSpeed = 10, streamThickness = -1, --//streamThickness = 4+self.count*0.34, corethickness = 1, corealpha = 1, texture = "bitmaps/largelaserfalloff.tga", } ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- --//speed ups local GL_ONE = GL.ONE local GL_SRC_ALPHA = GL.SRC_ALPHA local GL_ONE_MINUS_SRC_ALPHA = GL.ONE_MINUS_SRC_ALPHA local GL_QUADS = GL.QUADS local GL_TEXTURE = GL.TEXTURE local GL_MODELVIEW = GL.MODELVIEW local glColor = gl.Color local glTexture = gl.Texture local glBlending = gl.Blending local glMultiTexCoord = gl.MultiTexCoord local glVertex = gl.Vertex local glTranslate = gl.Translate local glMatrixMode = gl.MatrixMode local glPushMatrix = gl.PushMatrix local glPopMatrix = gl.PopMatrix local glBeginEnd = gl.BeginEnd local glUseShader = gl.UseShader local glAlphaTest = gl.AlphaTest local glCallList = gl.CallList local max = math.max local GetCameraVectors = Spring.GetCameraVectors local IsSphereInView = Spring.IsSphereInView ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- function NanoLasers:BeginDraw() glUseShader(laserShader) glBlending(GL_ONE, GL_ONE_MINUS_SRC_ALPHA) glAlphaTest(false) end function NanoLasers:EndDraw() glUseShader(0) glColor(1,1,1,1) glTexture(false) glBlending(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glAlphaTest(true) -- i hate that nv bug! glMultiTexCoord(0,0,0,0) glMultiTexCoord(1,0,0,0) glMultiTexCoord(2,0,0,0) glMultiTexCoord(3,0,0,0) lastTexture="" end function NanoLasers:Draw() if (lastTexture~=self.texture) then glTexture(self.texture) lastTexture=self.texture end local color = self.color local startPos = self.pos local endPos = self.targetpos glColor(color[1],color[2],color[3],0.0003) glMultiTexCoord(0,endPos[1] - self.normdir[3] * self.scane_mult ,endPos[2],endPos[3] + self.normdir[1] * self.scane_mult,1) glMultiTexCoord(1,startPos[1],startPos[2],startPos[3],1) if (self.inversed) then glMultiTexCoord(2, (thisGameFrame+Spring.GetFrameTimeOffset())*self.streamSpeed, self.streamThickness, self.corealpha, self.corethickness) else glMultiTexCoord(2, -(thisGameFrame+Spring.GetFrameTimeOffset())*self.streamSpeed, self.streamThickness, self.corealpha, self.corethickness) end glCallList(dlist) end ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- function NanoLasers:Update(n) UpdateNanoParticles(self) self.fpos = (self.fpos or 0) + self.count * 5 * n if (self.inversed) then self.scane_mult = 4 * math.cos(6*(self.fpos%4001)/4000*math.pi) else self.scane_mult = 8 * math.cos(2*(self.fpos%4001)/4000*math.pi) end if (self._dead) then RemoveParticles(self.id) end end -- used if repeatEffect=true; function NanoLasers:ReInitialize() self.dieGameFrame = self.dieGameFrame + self.life end function NanoLasers:Visible() if (self.allyID ~= LocalAllyTeamID) and (LocalAllyTeamID >= 0) and(self.visibility == 0) then return false end local midPos = self._midpos return IsSphereInView(midPos[1],midPos[2],midPos[3], self._radius) end ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- function NanoLasers:Initialize() laserShader = gl.CreateShader({ vertex = [[ //gl.vertex.xy := length,width //gl.vertex.zw := texcoord #define startpos gl_MultiTexCoord0 #define endpos gl_MultiTexCoord1 #define streamTranslate gl_MultiTexCoord2.x #define streamThickness gl_MultiTexCoord2.y #define coreAlpha gl_MultiTexCoord2.z #define coreThickness gl_MultiTexCoord2.w #define isCore gl_MultiTexCoord3.x varying vec3 texCoord; void main() { texCoord = vec3(gl_Vertex.z - streamTranslate, gl_Vertex.w, gl_Vertex.z); vec3 dir3; if (gl_Vertex.x>0.5) { gl_Position = (gl_ModelViewMatrix * endpos); dir3 = gl_Position.xyz - (gl_ModelViewMatrix * (startpos)).xyz; } else { gl_Position = (gl_ModelViewMatrix * startpos); dir3 = (gl_ModelViewMatrix * (endpos)).xyz - gl_Position.xyz; } vec3 v = normalize( dir3 ); vec3 w = normalize( -gl_Position.xyz ); vec3 u = normalize( cross(w,v) ); if (isCore>0.0) { gl_Position.xyz += (gl_Vertex.y * coreThickness) * u; gl_FrontColor.rgb = vec3(coreAlpha); gl_FrontColor.a = 0.003; }else{ gl_Position.xyz += (gl_Vertex.y * streamThickness) * u; gl_FrontColor = gl_Color; } gl_Position = gl_ProjectionMatrix * gl_Position; } ]], fragment = [[ uniform sampler2D tex0; varying vec3 texCoord; void main() { gl_FragColor = texture2D(tex0, texCoord.st) * gl_Color; if (texCoord.p>0.95) gl_FragColor *= vec4(1.0 - texCoord.p) * 20.0; if (texCoord.p<0.05) gl_FragColor *= vec4(texCoord.p) * 20.0; } ]], uniformInt = { tex0=0, } }) if (laserShader == nil) then print(PRIO_MAJOR,"LUPS->nanoLaserShader: shader error: "..gl.GetShaderLog()) return false end dlist = gl.CreateList(glBeginEnd,GL_QUADS,function() glMultiTexCoord(3,0) glVertex(1,-1, 1,0) glVertex(0,-1, 0,0) glVertex(0, 1, 0,1) glVertex(1, 1, 1,1) glMultiTexCoord(3,1) glVertex(1,-1, 1,0) glVertex(0,-1, 0,0) glVertex(0, 1, 0,1) glVertex(1, 1, 1,1) end) end function NanoLasers:Finalize() if (gl.DeleteShader) then gl.DeleteShader(laserShader) end gl.DeleteList(dlist) end ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- function NanoLasers:CreateParticle() self.life = self.life + 1 --// so we can reuse existing fx's self.firstGameFrame = thisGameFrame self.dieGameFrame = self.firstGameFrame + self.life if (self.flare) then --[[if you add those flares, then the laser is slower as the engine, so it needs some tweaking]]-- if (self.flare1id and particles[self.flare1id] and particles[self.flare2id]) then local flare1 = particles[self.flare1id] flare1.size = self.count*0.1 flare1:ReInitialize() local flare2 = particles[self.flare2id] flare2.size = self.count*0.75 flare2:ReInitialize() return else local r,g,b = max(self.color[1],0.13),max(self.color[2],0.13),max(self.color[3],0.13) local flare = { unit = self.unitID, piecenum = self.unitpiece, layer = self.layer, life = 31, size = self.count*0.1, sizeSpread = 1, sizeGrowth = 0.1, colormap = { {r*2,g*2,b*2,0.01},{r*2,g*2,b*2,0.01},{r*2,g*2,b*2,0.01} }, texture = 'bitmaps/GPL/groundflash.tga', count = 2, repeatEffect = false, } self.flare1id = AddParticles("StaticParticles",flare) flare.size = self.count*0.75 flare.texture = 'bitmaps/flare.tga' flare.colormap = { {r*2,g*2,b*2,0.009},{r*2,g*2,b*2,0.009},{r*2,g*2,b*2,0.009} } flare.count = 2 self.flare2id = AddParticles("StaticParticles",flare) end end self.visibility = 0 self:Update(0) --//update los if (self.streamThickness<0) then self.streamThickness = 4+self.count*0.34 end end ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- function NanoLasers.Create(Options) local unit,nanopiece=Options.unitID,Options.nanopiece if (unit and nanopiece)and(knownNanoLasers[unit])and(knownNanoLasers[unit][nanopiece]) then local reuseFx = knownNanoLasers[unit][nanopiece] CopyTable(reuseFx,Options) reuseFx:CreateParticle() return false,reuseFx.id else local newObject = MergeTable(Options, NanoLasers.Default) setmetatable(newObject,NanoLasers) -- make handle lookup newObject:CreateParticle() if (unit and nanopiece) then if (not knownNanoLasers[unit]) then knownNanoLasers[unit] = {} end knownNanoLasers[unit][nanopiece] = newObject end return newObject end end function NanoLasers:Destroy() local unit,nanopiece=self.unitID,self.nanopiece knownNanoLasers[unit][nanopiece] = nil if (not next(knownNanoLasers[unit])) then knownNanoLasers[unit] = nil end if (self.flare) then RemoveParticles(self.flare1id) RemoveParticles(self.flare2id) end end ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- return NanoLasers
gpl-2.0
master041/tele-master-asli
plugins/id.lua
355
2795
local function user_print_name(user) if user.print_name then return user.print_name end local text = '' if user.first_name then text = user.last_name..' ' end if user.lastname then text = text..user.last_name end return text end local function returnids(cb_extra, success, result) local receiver = cb_extra.receiver --local chat_id = "chat#id"..result.id local chat_id = result.id local chatname = result.print_name local text = 'IDs for chat '..chatname ..' ('..chat_id..')\n' ..'There are '..result.members_num..' members' ..'\n---------\n' i = 0 for k,v in pairs(result.members) do i = i+1 text = text .. i .. ". " .. string.gsub(v.print_name, "_", " ") .. " (" .. v.id .. ")\n" end send_large_msg(receiver, text) end local function username_id(cb_extra, success, result) local receiver = cb_extra.receiver local qusername = cb_extra.qusername local text = 'User '..qusername..' not found in this group!' for k,v in pairs(result.members) do vusername = v.username if vusername == qusername then text = 'ID for username\n'..vusername..' : '..v.id end end send_large_msg(receiver, text) end local function run(msg, matches) local receiver = get_receiver(msg) if matches[1] == "!id" then local text = 'Name : '.. string.gsub(user_print_name(msg.from),'_', ' ') .. '\nID : ' .. msg.from.id if is_chat_msg(msg) then text = text .. "\n\nYou are in group " .. string.gsub(user_print_name(msg.to), '_', ' ') .. " (ID: " .. msg.to.id .. ")" end return text elseif matches[1] == "chat" then -- !ids? (chat) (%d+) if matches[2] and is_sudo(msg) then local chat = 'chat#id'..matches[2] chat_info(chat, returnids, {receiver=receiver}) else if not is_chat_msg(msg) then return "You are not in a group." end local chat = get_receiver(msg) chat_info(chat, returnids, {receiver=receiver}) end else if not is_chat_msg(msg) then return "Only works in group" end local qusername = string.gsub(matches[1], "@", "") local chat = get_receiver(msg) chat_info(chat, username_id, {receiver=receiver, qusername=qusername}) end end return { description = "Know your id or the id of a chat members.", usage = { "!id: Return your ID and the chat id if you are in one.", "!ids chat: Return the IDs of the current chat members.", "!ids chat <chat_id>: Return the IDs of the <chat_id> members.", "!id <username> : Return the id from username given." }, patterns = { "^!id$", "^!ids? (chat) (%d+)$", "^!ids? (chat)$", "^!id (.*)$" }, run = run }
gpl-2.0
MonkeyFirst/Urho3D
bin/Data/LuaScripts/03_Sprites.lua
24
3509
-- Moving sprites example. -- This sample demonstrates: -- - Adding Sprite elements to the UI -- - Storing custom data (sprite velocity) inside UI elements -- - Handling frame update events in which the sprites are moved require "LuaScripts/Utilities/Sample" local numSprites = 100 local sprites = {} -- Custom variable identifier for storing sprite velocity within the UI element local VAR_VELOCITY = StringHash("Velocity") function Start() -- Execute the common startup for samples SampleStart() -- Create the sprites to the user interface CreateSprites() -- Set the mouse mode to use in the sample SampleInitMouseMode(MM_FREE) -- Hook up to the frame update events SubscribeToEvents() end function CreateSprites() local decalTex = cache:GetResource("Texture2D", "Textures/UrhoDecal.dds") local width = graphics.width local height = graphics.height for i = 1, numSprites do -- Create a new sprite, set it to use the texture local sprite = Sprite:new() sprite.texture = decalTex sprite:SetFullImageRect() -- The UI root element is as big as the rendering window, set random position within it sprite.position = Vector2(Random(width), Random(height)) -- Set sprite size & hotspot in its center sprite:SetSize(128, 128) sprite.hotSpot = IntVector2(64, 64) -- Set random rotation in degrees and random scale sprite.rotation = Random(360.0) sprite.scale = Vector2(1.0, 1.0) * (Random(1.0) + 0.5) -- Set random color and additive blending mode sprite:SetColor(Color(Random(0.5) + 0.5, Random(0.5) + 0.5, Random(0.5) + 0.5, 1.0)) sprite.blendMode = BLEND_ADD -- Add as a child of the root UI element ui.root:AddChild(sprite) -- Store sprite's velocity as a custom variable sprite:SetVar(VAR_VELOCITY, Variant(Vector2(Random(200.0) - 100.0, Random(200.0) - 100.0))) table.insert(sprites, sprite) end end function SubscribeToEvents() -- Subscribe HandleUpdate() function for processing update events SubscribeToEvent("Update", "HandleUpdate") end function MoveSprites(timeStep) local width = graphics.width local height = graphics.height for i = 1, numSprites do local sprite = sprites[i] sprite.rotation = sprite.rotation + timeStep * 30 local newPos = sprite.position newPos = newPos + sprite:GetVar(VAR_VELOCITY):GetVector2() * timeStep if newPos.x >= width then newPos.x = newPos.x - width elseif newPos.x < 0 then newPos.x = newPos.x + width end if newPos.y >= height then newPos.y = newPos.y - height elseif newPos.y < 0 then newPos.y = newPos.y + height end sprite.position = newPos end end function HandleUpdate(eventType, eventData) local timeStep = eventData["TimeStep"]:GetFloat() MoveSprites(timeStep) end -- Create XML patch instructions for screen joystick layout specific to this sample app function GetScreenJoystickPatchString() return "<patch>" .. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Hat0']]\">" .. " <attribute name=\"Is Visible\" value=\"false\" />" .. " </add>" .. "</patch>" end
mit
chef/chef-server
src/nginx/habitat/config/route_checks.lua
1
2633
module("route_checks", package.seeall) -- To preserve the ability to run tests locally, please comment out any -- chef templating if statements so that the un-rendered portions run in tests. -- For example: -- local response = {} response[403] = {} response[404] = {} response[503] = {} -- To add checks for a new response code, first declare it above in the form -- response[CODE] = {}, then at minimum add a new function response[CODE].default = function(route) -- To add route-specific checks, add a new function for the given -- response code in the form of response[CODE].ROUTE_ID = function(route) -- This function must return "true" if the request shoudl be terminated with "CODE". -- -- For example to implement "a 404 should occur for the users endpoint on the -- "acct" route if we are configured to force users endpoint not found": -- -- response[404].acct = function(org_config, endpoint, object_name) -- return endpoint == "users" and org_config['force_users_not_found'] == 1 -- end -- -- -- Default checks -- applied first regardless of endpoint or object-name -- are handled here. -- response[503].default = function(route) -- Habitat chef server doesn't support 503 mode yet if route.org_config["503_mode"] == 1 or config.is_route_in_maint_mode(route.route_id) then return true end return false end response[404].default = function(route) -- route-level darklaunch check: -- Habitat chef server doesn't support 404 mode yet if config.is_route_darklaunched(route.route_id) then return not (route.org_config["dl_" .. route.route_id] == 1) end return false end response[403].default = function(route) -- Habitat chef server doesn't support blocked orgs yet return route.org_config["org_blocked"] == 1 end -- -- Endpoint-specific checks from here on down. -- -- return true if client is posting to "organizations" endpoint but -- new org creation is disabled response[503].acct = function(route) -- Habitat chef server doesn't support 503 mode yet return false -- return route.org_name == nil and -- route.endpoint == "organizations" and -- ngx.req.get_method() == "POST" and -- route.org_config["disable_new_orgs"] == 1 end -- -- Our only public interface -- -- Run all available checks for the given parameters. Returns 0 -- if it's clear to proceed, otherwise it returns an http response code function route_checks.run(route) for code, check in pairs(response) do if check.default(route) or (check[route.route_id] and check[route.route_id](route)) then return code end end return 0 end
apache-2.0
thedraked/darkstar
scripts/zones/Selbina/npcs/Torapiont.lua
17
1547
----------------------------------- -- Area: Selbina -- NPC: Torapiont -- Standard Merchant NPC ----------------------------------- package.loaded["scripts/zones/Selbina/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Selbina/TextIDs"); require("scripts/globals/shop"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,TORAPIONT_SHOP_DIALOG); stock = {0x401B,11491, --Claws 0x4043,7727, --Mythril Dagger 0x4081,11588, --Tuck 0x40C8,37800, --Mythril Claymore 0x4103,11040, --Battleaxe 0x4141,4095, --Greataxe 0x429A,333, --Willow Wand 0x429B,1409, --Yew Wand 0x42C1,571, --Holly Staff 0x439B,9, --Dart 0x43B8,5, --Crossbow Bolt 0x43A6,3, --Wooden Arrow 0x43A8,7} --Iron Arrow showShop(player, STATIC, stock); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
thedraked/darkstar
scripts/globals/items/serving_of_mont_blanc.lua
18
1468
----------------------------------------- -- ID: 5557 -- Item: Serving of Mont Blanc -- Food Effect: 3 Hrs, All Races ----------------------------------------- -- TODO: Group Effect -- HP +8 -- MP +10 -- Intelligence +1 -- HP Recoverd while healing 1 -- MP Recovered while healing 1 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) result = 0 if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,10800,5557); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 8); target:addMod(MOD_MP, 10); target:addMod(MOD_INT, 1); target:addMod(MOD_HPHEAL, 1); target:addMod(MOD_MPHEAL, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 8); target:delMod(MOD_MP, 10); target:delMod(MOD_INT, 1); target:delMod(MOD_HPHEAL, 1); target:delMod(MOD_MPHEAL, 1); end;
gpl-3.0
X-Coder/wire
lua/entities/gmod_wire_egp/lib/objects/linestrip.lua
12
1267
-- Author: sk8 (& Divran) local Obj = EGP:NewObject( "LineStrip" ) Obj.w = nil Obj.h = nil Obj.x = nil Obj.y = nil Obj.vertices = {} Obj.verticesindex = "vertices" Obj.size = 1 Obj.Draw = function( self ) local n = #self.vertices if (self.a>0 and n>0 and self.size>0) then surface.SetDrawColor( self.r, self.g, self.b, self.a ) for i=1,(n-1) do local p1,p2 = self.vertices[i],self.vertices[1+i] EGP:DrawLine( p1.x, p1.y, p2.x, p2.y, self.size ) end end end Obj.Transmit = function( self, Ent, ply ) net.WriteUInt( #self.vertices, 16 ) for i=1,#self.vertices do net.WriteInt( self.vertices[i].x, 16 ) net.WriteInt( self.vertices[i].y, 16 ) end net.WriteInt(self.parent, 16) net.WriteInt(self.size, 16) EGP:SendMaterial( self ) EGP:SendColor( self ) end Obj.Receive = function( self ) local tbl = {} tbl.vertices = {} for i=1,net.ReadUInt(16) do tbl.vertices[ #tbl.vertices+1 ] = { x = net.ReadInt(16), y = net.ReadInt(16) } end tbl.parent = net.ReadInt(16) tbl.size = net.ReadInt(16) EGP:ReceiveMaterial( tbl ) EGP:ReceiveColor( tbl, self ) return tbl end Obj.DataStreamInfo = function( self ) return { vertices = self.vertices, material = self.material, r = self.r, g = self.g, b = self.b, a = self.a, parent = self.parent } end
gpl-3.0
master041/tele-master-asli
plugins/minecraft.lua
624
2605
local usage = { "!mine [ip]: Searches Minecraft server on specified ip and sends info. Default port: 25565", "!mine [ip] [port]: Searches Minecraft server on specified ip and port and sends info.", } local ltn12 = require "ltn12" local function mineSearch(ip, port, receiver) --25565 local responseText = "" local api = "https://api.syfaro.net/server/status" local parameters = "?ip="..(URL.escape(ip) or "").."&port="..(URL.escape(port) or "").."&players=true&favicon=true" local http = require("socket.http") local respbody = {} local body, code, headers, status = http.request{ url = api..parameters, method = "GET", redirect = true, sink = ltn12.sink.table(respbody) } local body = table.concat(respbody) if (status == nil) then return "ERROR: status = nil" end if code ~=200 then return "ERROR: "..code..". Status: "..status end local jsonData = json:decode(body) responseText = responseText..ip..":"..port.." ->\n" if (jsonData.motd ~= nil) then local tempMotd = "" tempMotd = jsonData.motd:gsub('%§.', '') if (jsonData.motd ~= nil) then responseText = responseText.." Motd: "..tempMotd.."\n" end end if (jsonData.online ~= nil) then responseText = responseText.." Online: "..tostring(jsonData.online).."\n" end if (jsonData.players ~= nil) then if (jsonData.players.max ~= nil) then responseText = responseText.." Max Players: "..jsonData.players.max.."\n" end if (jsonData.players.now ~= nil) then responseText = responseText.." Players online: "..jsonData.players.now.."\n" end if (jsonData.players.sample ~= nil and jsonData.players.sample ~= false) then responseText = responseText.." Players: "..table.concat(jsonData.players.sample, ", ").."\n" end end if (jsonData.favicon ~= nil and false) then --send_photo(receiver, jsonData.favicon) --(decode base64 and send) end return responseText end local function parseText(chat, text) if (text == nil or text == "!mine") then return usage end ip, port = string.match(text, "^!mine (.-) (.*)$") if (ip ~= nil and port ~= nil) then return mineSearch(ip, port, chat) end local ip = string.match(text, "^!mine (.*)$") if (ip ~= nil) then return mineSearch(ip, "25565", chat) end return "ERROR: no input ip?" end local function run(msg, matches) local chat_id = tostring(msg.to.id) local result = parseText(chat_id, msg.text) return result end return { description = "Searches Minecraft server and sends info", usage = usage, patterns = { "^!mine (.*)$" }, run = run }
gpl-2.0
thedraked/darkstar
scripts/zones/Inner_Horutoto_Ruins/npcs/_5ce.lua
14
1070
----------------------------------- -- Area: Inner Horutoto Ruins -- NPC: _5ce (Gate of Earth) -- @pos -228 0 140 192 ----------------------------------- package.loaded["scripts/zones/Inner_Horutoto_Ruins/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Inner_Horutoto_Ruins/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(DOOR_FIRMLY_CLOSED); return 1; end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
thedraked/darkstar
scripts/zones/Western_Altepa_Desert/Zone.lua
4
4527
----------------------------------- -- -- Zone: Western_Altepa_Desert (125) -- ----------------------------------- package.loaded["scripts/zones/Western_Altepa_Desert/TextIDs"] = nil; package.loaded["scripts/globals/chocobo_digging"] = nil; ----------------------------------- require("scripts/zones/Western_Altepa_Desert/TextIDs"); require("scripts/globals/icanheararainbow"); require("scripts/globals/weather"); require("scripts/globals/zone"); require("scripts/globals/chocobo_digging"); ----------------------------------- -- Chocobo Digging vars ----------------------------------- local itemMap = { -- itemid, abundance, requirement { 880, 224, DIGREQ_NONE }, { 887, 39, DIGREQ_NONE }, { 645, 14, DIGREQ_NONE }, { 893, 105, DIGREQ_NONE }, { 737, 17, DIGREQ_NONE }, { 643, 64, DIGREQ_NONE }, { 17296, 122, DIGREQ_NONE }, { 942, 6, DIGREQ_NONE }, { 642, 58, DIGREQ_NONE }, { 864, 22, DIGREQ_NONE }, { 843, 4, DIGREQ_NONE }, { 4096, 100, DIGREQ_NONE }, -- all crystals { 845, 122, DIGREQ_BURROW }, { 844, 71, DIGREQ_BURROW }, { 1845, 33, DIGREQ_BURROW }, { 838, 11, DIGREQ_BURROW }, { 902, 6, DIGREQ_BORE }, { 886, 3, DIGREQ_BORE }, { 867, 3, DIGREQ_BORE }, { 1587, 19, DIGREQ_BORE }, { 888, 25, DIGREQ_BORE }, { 1586, 8, DIGREQ_BORE }, { 885, 10, DIGREQ_BORE }, { 866, 3, DIGREQ_BORE }, { 4570, 10, DIGREQ_MODIFIER }, { 4487, 11, DIGREQ_MODIFIER }, { 4409, 12, DIGREQ_MODIFIER }, { 1188, 10, DIGREQ_MODIFIER }, { 4532, 12, DIGREQ_MODIFIER }, }; local messageArray = { DIG_THROW_AWAY, FIND_NOTHING, ITEM_OBTAINED }; ----------------------------------- -- onChocoboDig ----------------------------------- function onChocoboDig(player, precheck) return chocoboDig(player, itemMap, precheck, messageArray); end; ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) local manuals = {17289795,17289796,17289797}; SetFieldManual(manuals); local vwnpc = {17289804,17289805,17289806}; SetVoidwatchNPC(vwnpc); -- King Vinegarroon SetRespawnTime(17289575, 900, 10800); end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn( player, prevZone) local cs = -1; if ( player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then player:setPos( -19.901, 13.607, 440.058, 78); end if ( triggerLightCutscene( player)) then -- Quest: I Can Hear A Rainbow cs = 0x0002; end return cs; end; ----------------------------------- -- onConquestUpdate ----------------------------------- function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter( player, region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate( player, csid, option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if ( csid == 0x0002) then lightCutsceneUpdate(player); -- Quest: I Can Hear A Rainbow end end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish( player, csid, option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x0002) then lightCutsceneFinish(player); -- Quest: I Can Hear A Rainbow end end; function onZoneWeatherChange(weather) if (GetMobAction(17289575) == 24 and (weather == WEATHER_DUST_STORM or weather == WEATHER_SAND_STORM)) then SpawnMob(17289575); -- King Vinegarroon elseif (GetMobAction(17289575) == 16 and (weather ~= WEATHER_DUST_STORM and weather ~= WEATHER_SAND_STORM)) then DespawnMob(17289575); end end;
gpl-3.0
thedraked/darkstar
scripts/zones/Tavnazian_Safehold/npcs/qm2.lua
14
1680
----------------------------------- -- Area: Tavnazian Safehold -- NPC: ??? -- Involved in Quest: Unforgiven -- @zone 26 -- @pos 110.714 -40.856 -53.154 ----------------------------------- package.loaded["scripts/zones/Tavnazian_Safehold/TextIDs"] = nil; require("scripts/zones/Tavnazian_Safehold/TextIDs") require("scripts/globals/quests"); require("scripts/globals/keyitems"); ----------------------------------- -- For those who don't know -- at the end of if (player:getQuestStatus(REGION,QUEST_NAME) -- == 0 means QUEST_AVAILABLE -- == 1 means QUEST_ACCEPTED -- == 2 means QUEST_COMPLETED -- e.g. if (player:getQuestStatus(OTHER_AREAS,UNFORGIVEN) == 0 -- means if (player:getQuestStatus(OTHER_AREAS,UNFORGIVEN) == QUEST AVAILABLE ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local Unforgiven = player:getQuestStatus(OTHER_AREAS,UNFORGIVEN); if (Unforgiven == 1 and player:hasKeyItem(609) == false) then player:addKeyItem(609); player:messageSpecial(KEYITEM_OBTAINED,609) -- ALABASTER HAIRPIN for Unforgiven Quest end end ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end
gpl-3.0
stuta/Luajit-Tcp-Server
ffi_def_linux.lua
1
16233
-- ffi_def_osx.lua module(..., package.seeall) local ffi = require "ffi" -- Lua state - creating a new Lua state to a new thread ffi.cdef[[ // lua.h static const int LUA_GCSTOP = 0; static const int LUA_GCRESTART = 1; static const int LUA_GCCOLLECT = 2; static const int LUA_GCCOUNT = 3; static const int LUA_GCCOUNTB = 4; static const int LUA_GCSTEP = 5; static const int LUA_GCSETPAUSE = 6; static const int LUA_GCSETSTEPMUL = 7; static const int LUA_GLOBALSINDEX = -10002; typedef struct lua_State lua_State; int (lua_gc) (lua_State *L, int what, int data); lua_State *luaL_newstate(void); void luaL_openlibs(lua_State *L); void lua_close(lua_State *L); int luaL_loadstring(lua_State *L, const char *s); int lua_pcall(lua_State *L, int nargs, int nresults, int errfunc); void lua_getfield(lua_State *L, int index, const char *k); ptrdiff_t lua_tointeger(lua_State *L, int index); void lua_settop(lua_State *L, int index); ]] -- handmade basic types ffi.cdef[[ // these are/should be in sys/types.h, but is this safe universal way? // #define __char signed char typedef signed char __char; ]] ffi.cdef[[ // bad define macros, done by hand struct in6_addr { union { uint8_t __u6_addr8[16]; uint16_t __u6_addr16[8]; uint32_t __u6_addr32[4]; } __in6_u; }; // bad order of generated calls // missing generation - code these static const int PF_INET = 2; static const int PF_INET6 = 10; ]] ffi.cdef[[ // bad enums, done by hand enum { _SC_ARG_MAX, _SC_CHILD_MAX, _SC_CLK_TCK, _SC_NGROUPS_MAX, _SC_OPEN_MAX, _SC_STREAM_MAX, _SC_TZNAME_MAX, _SC_JOB_CONTROL, _SC_SAVED_IDS, _SC_REALTIME_SIGNALS, _SC_PRIORITY_SCHEDULING, _SC_TIMERS, _SC_ASYNCHRONOUS_IO, _SC_PRIORITIZED_IO, _SC_SYNCHRONIZED_IO, _SC_FSYNC, _SC_MAPPED_FILES, _SC_MEMLOCK, _SC_MEMLOCK_RANGE, _SC_MEMORY_PROTECTION, _SC_MESSAGE_PASSING, _SC_SEMAPHORES, _SC_SHARED_MEMORY_OBJECTS, _SC_AIO_LISTIO_MAX, _SC_AIO_MAX, _SC_AIO_PRIO_DELTA_MAX, _SC_DELAYTIMER_MAX, _SC_MQ_OPEN_MAX, _SC_MQ_PRIO_MAX, _SC_VERSION, _SC_PAGESIZE, _SC_RTSIG_MAX, _SC_SEM_NSEMS_MAX, _SC_SEM_VALUE_MAX, _SC_SIGQUEUE_MAX, _SC_TIMER_MAX, _SC_BC_BASE_MAX, _SC_BC_DIM_MAX, _SC_BC_SCALE_MAX, _SC_BC_STRING_MAX, _SC_COLL_WEIGHTS_MAX, _SC_EQUIV_CLASS_MAX, _SC_EXPR_NEST_MAX, _SC_LINE_MAX, _SC_RE_DUP_MAX, _SC_CHARCLASS_NAME_MAX, _SC_2_VERSION, _SC_2_C_BIND, _SC_2_C_DEV, _SC_2_FORT_DEV, _SC_2_FORT_RUN, _SC_2_SW_DEV, _SC_2_LOCALEDEF, _SC_PII, _SC_PII_XTI, _SC_PII_SOCKET, _SC_PII_INTERNET, _SC_PII_OSI, _SC_POLL, _SC_SELECT, _SC_UIO_MAXIOV, _SC_IOV_MAX = _SC_UIO_MAXIOV, _SC_PII_INTERNET_STREAM, _SC_PII_INTERNET_DGRAM, _SC_PII_OSI_COTS, _SC_PII_OSI_CLTS, _SC_PII_OSI_M, _SC_T_IOV_MAX, _SC_THREADS, _SC_THREAD_SAFE_FUNCTIONS, _SC_GETGR_R_SIZE_MAX, _SC_GETPW_R_SIZE_MAX, _SC_LOGIN_NAME_MAX, _SC_TTY_NAME_MAX, _SC_THREAD_DESTRUCTOR_ITERATIONS, _SC_THREAD_KEYS_MAX, _SC_THREAD_STACK_MIN, _SC_THREAD_THREADS_MAX, _SC_THREAD_ATTR_STACKADDR, _SC_THREAD_ATTR_STACKSIZE, _SC_THREAD_PRIORITY_SCHEDULING, _SC_THREAD_PRIO_INHERIT, _SC_THREAD_PRIO_PROTECT, _SC_THREAD_PROCESS_SHARED, _SC_NPROCESSORS_CONF, _SC_NPROCESSORS_ONLN, _SC_PHYS_PAGES, _SC_AVPHYS_PAGES, _SC_ATEXIT_MAX, _SC_PASS_MAX, _SC_XOPEN_VERSION, _SC_XOPEN_XCU_VERSION, _SC_XOPEN_UNIX, _SC_XOPEN_CRYPT, _SC_XOPEN_ENH_I18N, _SC_XOPEN_SHM, _SC_2_CHAR_TERM, _SC_2_C_VERSION, _SC_2_UPE, _SC_XOPEN_XPG2, _SC_XOPEN_XPG3, _SC_XOPEN_XPG4, _SC_CHAR_BIT, _SC_CHAR_MAX, _SC_CHAR_MIN, _SC_INT_MAX, _SC_INT_MIN, _SC_LONG_BIT, _SC_WORD_BIT, _SC_MB_LEN_MAX, _SC_NZERO, _SC_SSIZE_MAX, _SC_SCHAR_MAX, _SC_SCHAR_MIN, _SC_SHRT_MAX, _SC_SHRT_MIN, _SC_UCHAR_MAX, _SC_UINT_MAX, _SC_ULONG_MAX, _SC_USHRT_MAX, _SC_NL_ARGMAX, _SC_NL_LANGMAX, _SC_NL_MSGMAX, _SC_NL_NMAX, _SC_NL_SETMAX, _SC_NL_TEXTMAX, _SC_XBS5_ILP32_OFF32, _SC_XBS5_ILP32_OFFBIG, _SC_XBS5_LP64_OFF64, _SC_XBS5_LPBIG_OFFBIG, _SC_XOPEN_LEGACY, _SC_XOPEN_REALTIME, _SC_XOPEN_REALTIME_THREADS, _SC_ADVISORY_INFO, _SC_BARRIERS, _SC_BASE, _SC_C_LANG_SUPPORT, _SC_C_LANG_SUPPORT_R, _SC_CLOCK_SELECTION, _SC_CPUTIME, _SC_THREAD_CPUTIME, _SC_DEVICE_IO, _SC_DEVICE_SPECIFIC, _SC_DEVICE_SPECIFIC_R, _SC_FD_MGMT, _SC_FIFO, _SC_PIPE, _SC_FILE_ATTRIBUTES, _SC_FILE_LOCKING, _SC_FILE_SYSTEM, _SC_MONOTONIC_CLOCK, _SC_MULTI_PROCESS, _SC_SINGLE_PROCESS, _SC_NETWORKING, _SC_READER_WRITER_LOCKS, _SC_SPIN_LOCKS, _SC_REGEXP, _SC_REGEX_VERSION, _SC_SHELL, _SC_SIGNALS, _SC_SPAWN, _SC_SPORADIC_SERVER, _SC_THREAD_SPORADIC_SERVER, _SC_SYSTEM_DATABASE, _SC_SYSTEM_DATABASE_R, _SC_TIMEOUTS, _SC_TYPED_MEMORY_OBJECTS, _SC_USER_GROUPS, _SC_USER_GROUPS_R, _SC_2_PBS, _SC_2_PBS_ACCOUNTING, _SC_2_PBS_LOCATE, _SC_2_PBS_MESSAGE, _SC_2_PBS_TRACK, _SC_SYMLOOP_MAX, _SC_STREAMS, _SC_2_PBS_CHECKPOINT, _SC_V6_ILP32_OFF32, _SC_V6_ILP32_OFFBIG, _SC_V6_LP64_OFF64, _SC_V6_LPBIG_OFFBIG, _SC_HOST_NAME_MAX, _SC_TRACE, _SC_TRACE_EVENT_FILTER, _SC_TRACE_INHERIT, _SC_TRACE_LOG, _SC_LEVEL1_ICACHE_SIZE, _SC_LEVEL1_ICACHE_ASSOC, _SC_LEVEL1_ICACHE_LINESIZE, _SC_LEVEL1_DCACHE_SIZE, _SC_LEVEL1_DCACHE_ASSOC, _SC_LEVEL1_DCACHE_LINESIZE, _SC_LEVEL2_CACHE_SIZE, _SC_LEVEL2_CACHE_ASSOC, _SC_LEVEL2_CACHE_LINESIZE, _SC_LEVEL3_CACHE_SIZE, _SC_LEVEL3_CACHE_ASSOC, _SC_LEVEL3_CACHE_LINESIZE, _SC_LEVEL4_CACHE_SIZE, _SC_LEVEL4_CACHE_ASSOC, _SC_LEVEL4_CACHE_LINESIZE, _SC_IPV6 = _SC_LEVEL1_ICACHE_SIZE + 50, _SC_RAW_SOCKETS, _SC_V7_ILP32_OFF32, _SC_V7_ILP32_OFFBIG, _SC_V7_LP64_OFF64, _SC_V7_LPBIG_OFFBIG, _SC_SS_REPL_MAX, _SC_TRACE_EVENT_NAME_MAX, _SC_TRACE_NAME_MAX, _SC_TRACE_SYS_MAX, _SC_TRACE_USER_EVENT_MAX, _SC_XOPEN_STREAMS, _SC_THREAD_ROBUST_PRIO_INHERIT, _SC_THREAD_ROBUST_PRIO_PROTECT }; ]] -- everything above will stay, below will be generated -- -- ******************** -- -- generated code start -- --[[ lib_date_time.lua ]] ffi.cdef[[ typedef long int __time_t; typedef __time_t time_t; double difftime (time_t __time1, time_t __time0) ; time_t time (time_t *__timer); ]] --[[ lib_http.lua ]] --[[ lib_kqueue.lua ]] --[[ lib_poll.lua ]] ffi.cdef[[ static const int POLLERR = 0x008; static const int POLLHUP = 0x010; static const int POLLIN = 0x001; static const int POLLNVAL = 0x020; static const int POLLOUT = 0x004; struct pollfd { int fd; short int events; short int revents; }; void free (void *__ptr); void *realloc (void *__ptr, size_t __size) ; ]] --[[ lib_shared_memory.lua ]] ffi.cdef[[ static const int MAP_SHARED = 0x01; static const int O_CREAT = 0100; static const int O_RDONLY = 00; static const int O_RDWR = 02; static const int PROT_READ = 0x1; static const int PROT_WRITE = 0x2; typedef unsigned int __mode_t; typedef long int __off_t; typedef __mode_t mode_t; int close (int __fd); int ftruncate (int __fd, __off_t __length); void *mmap (void *__addr, size_t __len, int __prot, int __flags, int __fd, __off_t __offset); int munmap (void *__addr, size_t __len); int shm_open (const char *__name, int __oflag, mode_t __mode); int shm_unlink (const char *__name); size_t strlen (const char *__s) ; ]] --[[ lib_signal.lua ]] ffi.cdef[[ typedef struct { unsigned long int __val[(1024 / (8 * sizeof (unsigned long int)))]; } __sigset_t; typedef __sigset_t sigset_t; typedef int __pid_t; __pid_t getpid (void); int kill (__pid_t __pid, int __sig); int pthread_sigmask (int __how, const __sigset_t *__newmask, __sigset_t *__oldmask)__attribute__ ((__nothrow__ , __leaf__)); int sigaddset (sigset_t *__set, int __signo); int sigemptyset (sigset_t *__set); int sigwait (const sigset_t *__set, int *__sig) ; ]] --[[ lib_socket.lua ]] ffi.cdef[[ static const int F_GETFL = 3; static const int F_SETFL = 4; static const int O_NONBLOCK = 04000; typedef uint32_t in_addr_t; typedef unsigned short int sa_family_t; typedef unsigned long int nfds_t; typedef uint16_t in_port_t; typedef int __ssize_t; struct sockaddr { sa_family_t sa_family; char sa_data[14]; }; typedef __ssize_t ssize_t; struct in_addr { in_addr_t s_addr; }; typedef unsigned int __socklen_t; typedef __socklen_t socklen_t; struct sockaddr_in { sa_family_t sin_family; in_port_t sin_port; struct in_addr sin_addr; unsigned char sin_zero[sizeof (struct sockaddr) - (sizeof (unsigned short int)) - sizeof (in_port_t) - sizeof (struct in_addr)]; }; struct addrinfo { int ai_flags; int ai_family; int ai_socktype; int ai_protocol; socklen_t ai_addrlen; struct sockaddr *ai_addr; char *ai_canonname; struct addrinfo *ai_next; }; int accept (int __fd, struct sockaddr *__addr, socklen_t *__addr_len); int bind (int __fd, const struct sockaddr * __addr, socklen_t __len) ; int connect (int __fd, const struct sockaddr * __addr, socklen_t __len); int fcntl (int __fd, int __cmd, ...); const char *gai_strerror (int __ecode); int getaddrinfo (const char *__name, const char *__service, const struct addrinfo *__req, struct addrinfo **__pai); int getnameinfo (const struct sockaddr *__sa, socklen_t __salen, char *__host, socklen_t __hostlen, char *__serv, socklen_t __servlen, int __flags); int getpeername (int __fd, struct sockaddr *__addr, socklen_t *__len); int getsockopt (int __fd, int __level, int __optname, void *__optval, socklen_t *__optlen); uint16_t htons (uint16_t __hostshort) ; const char *inet_ntop (int __af, const void *__cp, char *__buf, socklen_t __len) ; int listen (int __fd, int __n); uint16_t ntohs (uint16_t __netshort) ; int poll (struct pollfd *__fds, nfds_t __nfds, int __timeout); ssize_t recv (int __fd, void *__buf, size_t __n, int __flags); ssize_t send (int __fd, const void *__buf, size_t __n, int __flags); int setsockopt (int __fd, int __level, int __optname, const void *__optval, socklen_t __optlen); int shutdown (int __fd, int __how); int socket (int __domain, int __type, int __protocol); ]] --[[ lib_tcp.lua ]] ffi.cdef[[ static const int AF_INET = PF_INET; static const int AF_INET6 = PF_INET6; static const int AI_PASSIVE = 0x0001; static const int INET6_ADDRSTRLEN = 46; static const int INET_ADDRSTRLEN = 16; static const int SO_RCVBUF = 8; static const int SO_REUSEADDR = 2; static const int SO_SNDBUF = 7; static const int SOL_SOCKET = 1; static const int SOMAXCONN = 128; static const int TCP_NODELAY = 1; struct sockaddr_storage { sa_family_t ss_family; unsigned long int __ss_align; char __ss_padding[(128 - (2 * sizeof (unsigned long int)))]; }; struct sockaddr_in6 { sa_family_t sin6_family; in_port_t sin6_port; uint32_t sin6_flowinfo; struct in6_addr sin6_addr; uint32_t sin6_scope_id; }; enum { IPPROTO_IP = 0, IPPROTO_HOPOPTS = 0, IPPROTO_ICMP = 1, IPPROTO_IGMP = 2, IPPROTO_IPIP = 4, IPPROTO_TCP = 6, IPPROTO_EGP = 8, IPPROTO_PUP = 12, IPPROTO_UDP = 17, IPPROTO_IDP = 22, IPPROTO_TP = 29, IPPROTO_DCCP = 33, IPPROTO_IPV6 = 41, IPPROTO_ROUTING = 43, IPPROTO_FRAGMENT = 44, IPPROTO_RSVP = 46, IPPROTO_GRE = 47, IPPROTO_ESP = 50, IPPROTO_AH = 51, IPPROTO_ICMPV6 = 58, IPPROTO_NONE = 59, IPPROTO_DSTOPTS = 60, IPPROTO_MTP = 92, IPPROTO_ENCAP = 98, IPPROTO_PIM = 103, IPPROTO_COMP = 108, IPPROTO_SCTP = 132, IPPROTO_UDPLITE = 136, IPPROTO_RAW = 255, IPPROTO_MAX }; struct in6_addr sin6_addr; in_port_t sin6_port; enum __socket_type { SOCK_STREAM = 1, SOCK_DGRAM = 2, SOCK_RAW = 3, SOCK_RDM = 4, SOCK_SEQPACKET = 5, SOCK_DCCP = 6, SOCK_PACKET = 10, SOCK_CLOEXEC = 02000000, SOCK_NONBLOCK = 04000 }; ]] --[[ lib_thread.lua ]] ffi.cdef[[ typedef union { char __size[36]; long int __align; } pthread_attr_t; typedef unsigned long int pthread_t; int pthread_create (pthread_t *__newthread, const pthread_attr_t *__attr, void *(*__start_routine) (void *), void *__arg); void pthread_exit (void *__retval); int pthread_join (pthread_t __th, void **__thread_return); pthread_t pthread_self (void); ]] --[[ lib_util.lua ]] ffi.cdef[[ struct timezone { int tz_minuteswest; int tz_dsttime; }; typedef long int __suseconds_t; typedef unsigned int __useconds_t; struct timespec { __time_t tv_sec; long int tv_nsec; }; typedef struct timezone *__timezone_ptr_t; struct timeval { __time_t tv_sec; __suseconds_t tv_usec; }; int gettimeofday (struct timeval *__tv, __timezone_ptr_t __tz); int nanosleep (const struct timespec *__requested_time, struct timespec *__remaining); int sched_yield (void); char *strerror (int __errnum); long int sysconf (int __name); int usleep (__useconds_t __useconds); ]] --[[ TestAddrinfo.lua ]] ffi.cdef[[ static const int AI_CANONNAME = 0x0002; static const int NI_MAXHOST = 1025; static const int NI_MAXSERV = 32; static const int NI_NAMEREQD = 8; static const int NI_NUMERICHOST = 1; static const int NI_NUMERICSERV = 2; ]] --[[ TestAll.lua ]] --[[ TestKqueue.lua ]] ffi.cdef[[ int open (const char *__file, int __oflag, ...); ]] --[[ TestLinux.lua ]] ffi.cdef[[ static const int O_EXCL = 0200; ]] --[[ TestSharedMemory.lua ]] --[[ TestSignal.lua ]] --[[ TestSignal_bad.lua ]] ffi.cdef[[ typedef void (*__sighandler_t) (int); int pause (void); __sighandler_t signal (int __sig, __sighandler_t __handler) ; ]] --[[ TestSocket.lua ]] --[[ TestThread.lua ]] --[[ not found calls = { [1] = "--- lib_date_time.lua ---"; [2] = "--- lib_http.lua ---"; [3] = "--- lib_kqueue.lua ---"; [4] = "--- lib_poll.lua ---"; [5] = "--- lib_shared_memory.lua ---"; [6] = "CloseHandle"; [7] = "CreateFileMappingA"; [8] = "GetLastError"; [9] = "MapViewOfFile"; [10] = "OpenFileMappingA"; [11] = "UnmapViewOfFile"; [12] = "--- lib_signal.lua ---"; [13] = "--- lib_socket.lua ---"; [14] = "closesocket"; [15] = "ioctlsocket"; [16] = "WSAAddressToStringA"; [17] = "WSACleanup"; [18] = "WSAGetLastError"; [19] = "WSAPoll"; [20] = "WSAStartup"; [21] = "--- lib_tcp.lua ---"; [22] = "SO_USELOOPBACK"; [23] = "--- lib_thread.lua ---"; [24] = "CreateThread"; [25] = "GetCurrentThreadId"; [26] = "INFINITE"; [27] = "WaitForSingleObject"; [28] = "--- lib_util.lua ---"; [29] = "ENABLE_ECHO_INPUT"; [30] = "ENABLE_LINE_INPUT"; [31] = "FORMAT_MESSAGE_FROM_SYSTEM"; [32] = "FORMAT_MESSAGE_IGNORE_INSERTS"; [33] = "GetConsoleMode"; [34] = "GetStdHandle"; [35] = "GetSystemInfo"; [36] = "QueryPerformanceCounter"; [37] = "QueryPerformanceFrequency"; [38] = "ReadConsoleA"; [39] = "SetConsoleMode"; [40] = "Sleep"; [41] = "STD_INPUT_HANDLE"; [42] = "SwitchToThread"; [43] = "--- TestAddrinfo.lua ---"; [44] = "--- TestAll.lua ---"; [45] = "--- TestKqueue.lua ---"; [46] = "EV_ADD"; [47] = "EV_ENABLE"; [48] = "EV_ONESHOT"; [49] = "EVFILT_VNODE"; [50] = "INFINITE"; [51] = "kevent"; [52] = "kqueue"; [53] = "NOTE_ATTRIB"; [54] = "NOTE_DELETE"; [55] = "NOTE_EXTEND"; [56] = "NOTE_WRITE"; [57] = "--- TestLinux.lua ---"; [58] = "--- TestSharedMemory.lua ---"; [59] = "--- TestSignal.lua ---"; [60] = "--- TestSignal_bad.lua ---"; [61] = "--- TestSocket.lua ---"; [62] = "SD_SEND"; [63] = "--- TestThread.lua ---"; }; ]]
bsd-3-clause
thedraked/darkstar
scripts/zones/Giddeus/npcs/HomePoint#1.lua
27
1248
----------------------------------- -- Area: Giddeus -- NPC: HomePoint#1 -- @pos -132 -3 -303 145 ----------------------------------- package.loaded["scripts/zones/Giddeus/TextIDs"] = nil; require("scripts/globals/settings"); require("scripts/zones/Giddeus/TextIDs"); require("scripts/globals/homepoint"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) homepointMenu( player, 0x21fc, 54); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x21fc) then if (option == 1) then player:setHomePoint(); player:messageSpecial(HOMEPOINT_SET); else hpTeleport( player, option); end end end;
gpl-3.0
thedraked/darkstar
scripts/zones/Western_Adoulin/npcs/Mastan.lua
14
2128
----------------------------------- -- Area: Western Adoulin -- NPC: Virsaint -- Type: Standard NPC and Quest NPC -- Involved with Quests: 'Order Up' -- 'The Curious Case of Melvien' -- @zone 256 -- @pos -9 0 67 ----------------------------------- package.loaded["scripts/zones/Western_Adoulin/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/keyitems"); require("scripts/zones/Western_Adoulin/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local TCCOM = player:getQuestStatus(ADOULIN, THE_CURIOUS_CASE_OF_MELVIEN); local TCCOM_Need_KI = player:hasKeyItem(MELVIENS_TURN) and (not player:hasKeyItem(MELVIENS_DEATH)) local Order_Up = player:getQuestStatus(ADOULIN, ORDER_UP); local Order_Mastan = player:getMaskBit(player:getVar("Order_Up_NPCs"), 11); if ((Order_Up == QUEST_ACCEPTED) and (not Order_Mastan)) then -- Progresses Quest: 'Order Up' player:startEvent(0x0046); elseif ((TCCOM == QUEST_ACCEPTED) and TCCOM_Need_KI) then -- Progresses Quest: 'The Curious Case of Melvien' player:startEvent(0x00B8); else -- Standard Dialogue player:startEvent(0x020D); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) if (csid == 0x0046) then -- Progresses Quest: 'Order Up' player:setMaskBit("Order_Up_NPCs", 11, true); elseif (csid == 0x00B8) then -- Progresses Quest: 'The Curious Case of Melvien' if (option == 1) then player:addKeyItem(MELVIENS_DEATH); player:messageSpecial(KEYITEM_OBTAINED, MELVIENS_DEATH); end end end;
gpl-3.0
alalazo/wesnoth
data/ai/micro_ais/cas/ca_herding_sheep_runs_enemy.lua
2
1721
local H = wesnoth.require "helper" local AH = wesnoth.require "ai/lua/ai_helper.lua" local M = wesnoth.map local function get_next_sheep_enemies(cfg) local sheep = AH.get_units_with_moves { side = wesnoth.current.side, { "and", H.get_child(cfg, "filter_second") } } if (not sheep[1]) then return end local enemies = AH.get_attackable_enemies() if (not enemies[1]) then return end local attention_distance = cfg.attention_distance or 8 -- Simply return the first sheep, order does not matter for _,single_sheep in ipairs(sheep) do local close_enemies = {} for _,enemy in ipairs(enemies) do if (M.distance_between(single_sheep.x, single_sheep.y, enemy.x, enemy.y) <= attention_distance) then table.insert(close_enemies, enemy) end end if close_enemies[1] then return single_sheep, enemies end end end local ca_herding_sheep_runs_enemy = {} function ca_herding_sheep_runs_enemy:evaluation(cfg) -- Sheep runs from any enemy within attention_distance hexes (after the dogs have moved in) if get_next_sheep_enemies(cfg) then return cfg.ca_score end return 0 end function ca_herding_sheep_runs_enemy:execution(cfg) local sheep, close_enemies = get_next_sheep_enemies(cfg) -- Maximize distance between sheep and enemies local best_hex = AH.find_best_move(sheep, function(x, y) local rating = 0 for _,enemy in ipairs(close_enemies) do rating = rating + M.distance_between(x, y, enemy.x, enemy.y) end return rating end) AH.movefull_stopunit(ai, sheep, best_hex) end return ca_herding_sheep_runs_enemy
gpl-2.0
thedraked/darkstar
scripts/zones/Port_San_dOria/npcs/Avandale.lua
14
1052
----------------------------------- -- Area: Port San d'Oria -- NPC: Avandale -- Type: Standard NPC -- @zone 232 -- @pos -105.524 -9 -125.274 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x022b); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
mtroyka/Zero-K
effects/paris.lua
12
4272
-- paris_glow -- paris -- paris_gflash -- paris_sphere return { ["paris_glow"] = { glow = { air = true, class = [[CSimpleParticleSystem]], count = 2, ground = true, water = true, properties = { airdrag = 1, colormap = [[0 0 0 0.01 0.8 0.8 0.8 0.9 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 180, emitvector = [[-0, 1, 0]], gravity = [[0, 0.00, 0]], numparticles = 1, particlelife = 10, particlelifespread = 0, particlesize = 60, particlesizespread = 10, particlespeed = 1, particlespeedspread = 0, pos = [[0, 2, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[circularthingy]], }, }, groundflash = { circlealpha = 1, circlegrowth = 0, flashalpha = 0.5, flashsize = 100, ttl = 10, color = { [1] = 0.80000001192093, [2] = 0.80000001192093, [3] = 1, }, }, }, ["paris"] = { dustring = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 0, explosiongenerator = [[custom:GEORGE]], pos = [[0, 0, 0]], }, }, gflash = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 0, explosiongenerator = [[custom:PARIS_GFLASH]], pos = [[0, 0, 0]], }, }, glow = { air = true, class = [[CExpGenSpawner]], count = 0, ground = true, water = true, properties = { delay = [[0 i0.5]], explosiongenerator = [[custom:PARIS_GLOW]], pos = [[0, 0, 0]], }, }, shere = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 0, explosiongenerator = [[custom:PARIS_SPHERE]], pos = [[0, 5, 0]], }, }, }, ["paris_gflash"] = { groundflash = { circlealpha = 0.5, circlegrowth = 60, flashalpha = 0, flashsize = 30, ttl = 20, color = { [1] = 0.80000001192093, [2] = 0.80000001192093, [3] = 1, }, }, }, ["paris_sphere"] = { groundflash = { circlealpha = 1, circlegrowth = 0, flashalpha = 0.5, flashsize = 60, ttl = 60, color = { [1] = 0.80000001192093, [2] = 0.80000001192093, [3] = 1, }, }, pikez = { air = true, class = [[explspike]], count = 15, ground = true, water = true, properties = { alpha = 0.8, alphadecay = 0.15, color = [[1.0,1.0,0.8]], dir = [[-15 r30,-15 r30,-15 r30]], length = 40, width = 15, }, }, sphere = { air = true, class = [[CSpherePartSpawner]], count = 1, ground = true, water = true, properties = { alpha = 0.3, alwaysvisible = false, color = [[0.8,0.8,1]], expansionspeed = 60, ttl = 10, }, }, }, }
gpl-2.0
NPLPackages/main
script/ide/Motion/test/autotips_test.lua
1
4658
--[[ ------------------------------------------------------------ NPL.load("(gl)script/ide/Motion/test/autotips_test.lua"); CommonCtrl.Motion.autotips_test.show(); ------------------------------------------------------------ --]] NPL.load("(gl)script/ide/Motion/AnimativeMenu/AnimativeMenu.lua"); NPL.load("(gl)script/kids/3DMapSystemUI/Desktop/autotips.lua"); local autotips_test = {index = 0,idleIndex = 0,tipIndex = 0}; commonlib.setfield("CommonCtrl.Motion.autotips_test",autotips_test); function CommonCtrl.Motion.autotips_test.show() _guihelper.ShowDialogBox("autotips_test", 0,200, 400, 400, CommonCtrl.Motion.autotips_test.CreateDlg, CommonCtrl.Motion.autotips_test.OnDlgResult); end function CommonCtrl.Motion.autotips_test.CreateDlg(_parent) local _this; _this = ParaUI.CreateUIObject("container", "autotips_test", "_fi", 0,0,0,0) --_this.background = "Texture/whitedot.png;"; _parent:AddChild(_this); _parent = _this; local left,top,width,height=10,10,200,30; --add a message btn _this = ParaUI.CreateUIObject("button", "start", "_lt", left,top,width,height) _this.text="add a message"; _this.onclick=";CommonCtrl.Motion.autotips_test.onAdd();"; _parent:AddChild(_this); --add a same message btn left,top,width,height=left,top+50,width,height _this = ParaUI.CreateUIObject("button", "stop", "_lt", left,top,width,height) _this.text="add a same message(1)"; _this.onclick=";CommonCtrl.Motion.autotips_test.onAdd(1);"; _parent:AddChild(_this); -- add a idle massage btn left,top,width,height=left,top+50,width,height _this = ParaUI.CreateUIObject("button", "resume", "_lt", left,top,width,height) _this.text="add a idle massage"; _this.onclick=";CommonCtrl.Motion.autotips_test.onAddIdle();"; _parent:AddChild(_this); -- add a tip massage btn left,top,width,height=left,top+50,width,height _this = ParaUI.CreateUIObject("button", "resume", "_lt", left,top,width,height) _this.text="add a tip massage priority = 40"; _this.onclick=";CommonCtrl.Motion.autotips_test.onAddTip(40);"; _parent:AddChild(_this); -- add a tip massage btn left,top,width,height=left,top+50,width,height _this = ParaUI.CreateUIObject("button", "resume", "_lt", left,top,width,height) _this.text="add a tip massage priority = 50"; _this.onclick=";CommonCtrl.Motion.autotips_test.onAddTip(50);"; _parent:AddChild(_this); -- add a tip massage btn left,top,width,height=left,top+50,width,height _this = ParaUI.CreateUIObject("button", "resume", "_lt", left,top,width,height) _this.text="add a tip massage priority = 30"; _this.onclick=";CommonCtrl.Motion.autotips_test.onAddTip(30);"; _parent:AddChild(_this); -- reset a tip massage btn left,top,width,height=left,top+50,width,height _this = ParaUI.CreateUIObject("button", "resume", "_lt", left,top,width,height) _this.text="reset a tip massage(1)"; _this.onclick=";CommonCtrl.Motion.autotips_test.onResetTip(1);"; _parent:AddChild(_this); -- remove a tip massage btn left,top,width,height=left,top+50,width,height _this = ParaUI.CreateUIObject("button", "resume", "_lt", left,top,width,height) _this.text="remove a tip massage(1)"; _this.onclick=";CommonCtrl.Motion.autotips_test.onRemoveTip(1);"; _parent:AddChild(_this); autotips.Show(true); end ----------------- function CommonCtrl.Motion.autotips_test.onAdd(v) local text; if(not v)then CommonCtrl.Motion.autotips_test.index = CommonCtrl.Motion.autotips_test.index + 1; text = "text"..CommonCtrl.Motion.autotips_test.index; else text = "text1"; end autotips.AddMessageTips(text) end function CommonCtrl.Motion.autotips_test.onAddIdle() local text; CommonCtrl.Motion.autotips_test.idleIndex = CommonCtrl.Motion.autotips_test.idleIndex + 1; text = "idle_text"..CommonCtrl.Motion.autotips_test.idleIndex; autotips.AddIdleTips(text) end function CommonCtrl.Motion.autotips_test.onAddTip(priority) local category,text; CommonCtrl.Motion.autotips_test.tipIndex = CommonCtrl.Motion.autotips_test.tipIndex + 1; category = "category_text"..CommonCtrl.Motion.autotips_test.tipIndex; text = "tip_text"..priority; autotips.AddTips(category,text,priority) end function CommonCtrl.Motion.autotips_test.onResetTip(v) local category,text; category = "category_text"..v; text = "tip_text"..v.."---reset"; autotips.AddTips(category,text) end function CommonCtrl.Motion.autotips_test.onRemoveTip(v) local category,text; category = "category_text"..v text = nil autotips.AddTips(category, text) end -- called when dialog returns. function CommonCtrl.Motion.autotips_test.OnDlgResult(dialogResult) if(dialogResult == _guihelper.DialogResult.OK) then return true; end end
gpl-2.0
thedraked/darkstar
scripts/zones/East_Ronfaure/npcs/Croteillard.lua
14
1043
----------------------------------- -- Area: East Ronfaure -- NPC: Croteillard -- Type: Gate Guard -- @pos 87.426 -62.999 266.709 101 ----------------------------------- package.loaded["scripts/zones/East_Ronfaure/TextIDs"] = nil; ----------------------------------- require("scripts/zones/East_Ronfaure/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc, CROTEILLARD_DIALOG); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
thedraked/darkstar
scripts/globals/abilities/ninja_roll.lua
19
2510
----------------------------------- -- Ability: Ninja Roll -- Enhances evasion for party members within area of effect -- Optimal Job: Ninja -- Lucky Number: 4 -- Unlucky Number: 8 -- Jobs: -- Corsair Level 8 -- -- Die Roll |With NIN -- -------- ---------- -- 1 |+4 -- 2 |+6 -- 3 |+8 -- 4 |+25 -- 5 |+10 -- 6 |+12 -- 7 |+14 -- 8 |+2 -- 9 |+17 -- 10 |+20 -- 11 |+30 -- Bust |-10 ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/ability"); ----------------------------------- -- onAbilityCheck ----------------------------------- function onAbilityCheck(player,target,ability) local effectID = EFFECT_NINJA_ROLL ability:setRange(ability:getRange() + player:getMod(MOD_ROLL_RANGE)); if (player:hasStatusEffect(effectID)) then return MSGBASIC_ROLL_ALREADY_ACTIVE,0; elseif atMaxCorsairBusts(player) then return MSGBASIC_CANNOT_PERFORM,0; else return 0,0; end end; ----------------------------------- -- onUseAbility ----------------------------------- function onUseAbility(caster,target,ability,action) if (caster:getID() == target:getID()) then corsairSetup(caster, ability, action, EFFECT_NINJA_ROLL, JOBS.NIN); end local total = caster:getLocalVar("corsairRollTotal") return applyRoll(caster,target,ability,action,total) end; function applyRoll(caster,target,ability,action,total) local duration = 300 + caster:getMerit(MERIT_WINNING_STREAK) local effectpowers = {4, 5, 5, 14, 6, 7, 9, 2, 10, 11, 18, 6} local effectpower = effectpowers[total]; if (caster:getLocalVar("corsairRollBonus") == 1 and total < 12) then effectpower = effectpower + 6 end if (caster:getMainJob() == JOBS.COR and caster:getMainLvl() < target:getMainLvl()) then effectpower = effectpower * (caster:getMainLvl() / target:getMainLvl()); elseif (caster:getSubJob() == JOBS.COR and caster:getSubLvl() < target:getMainLvl()) then effectpower = effectpower * (caster:getSubLvl() / target:getMainLvl()); end if (target:addCorsairRoll(caster:getMainJob(), caster:getMerit(MERIT_BUST_DURATION), EFFECT_NINJA_ROLL, effectpower, 0, duration, caster:getID(), total, MOD_EVA) == false) then ability:setMsg(422); elseif total > 11 then ability:setMsg(426); end return total; end
gpl-3.0
moomoomoo309/FamiliarFaces
src/pl/OrderedMap.lua
1
4523
--- OrderedMap, a map which preserves ordering. -- -- Derived from `pl.Map`. -- -- Dependencies: `pl.utils`, `pl.tablex`, `pl.class`, `pl.List`, `pl.Map` -- @classmod pl.OrderedMap local tablex = require 'pl.tablex' local utils = require 'pl.utils' local List = require 'pl.List' local index_by,tsort,concat = tablex.index_by,table.sort,table.concat local class = require 'pl.class' local Map = require 'pl.Map' local OrderedMap = class(Map) OrderedMap._name = 'OrderedMap' local rawset = rawset --- construct an OrderedMap. -- Will throw an error if the argument is bad. -- @param percent optional initialization table, same as for @{OrderedMap:update} function OrderedMap:_init (t) rawset(self,'_keys',List()) if t then local map,err = self:update(t) if not map then error(err,2) end end end local assert_arg,raise = utils.assert_arg,utils.raise --- update an OrderedMap using a table. -- If the table is itself an OrderedMap, then its entries will be appended. -- if it s a table of the form `{{key1=val1},{key2=val2},...}` these will be appended. -- -- Otherwise, it is assumed to be a map-like table, and order of extra entries is arbitrary. -- @tab t a table. -- @return the map, or nil in case of error -- @return the error message function OrderedMap:update (t) assert_arg(1,t,'table') if OrderedMap:class_of(t) then for k,v in t:iter() do self:set(k,v) end elseif #t > 0 then -- an array must contain {key=val} tables if type(t[1]) == 'table' then for _,pair in ipairs(t) do local key,value = next(pair) if not key then return raise 'empty pair initialization table' end self:set(key,value) end else return raise 'cannot use an array to initialize an OrderedMap' end else for k,v in pairs(t) do self:set(k,v) end end return self end --- set the key's value. This key will be appended at the end of the map. -- -- If the value is nil, then the key is removed. -- @param key the key -- @param val the value -- @return the map function OrderedMap:set (key,val) if rawget(self, key) == nil and val ~= nil then -- new key self._keys:append(key) -- we keep in order rawset(self,key,val) -- don't want to provoke __newindex! else -- existing key-value pair if val == nil then self._keys:remove_value(key) rawset(self,key,nil) else self[key] = val end end return self end OrderedMap.__newindex = OrderedMap.set --- insert a key/value pair before a given position. -- Note: if the map already contains the key, then this effectively -- moves the item to the new position by first removing at the old position. -- Has no effect if the key does not exist and val is nil -- @int pos a position starting at 1 -- @param key the key -- @param val the value; if nil use the old value function OrderedMap:insert (pos,key,val) local oldval = self[key] val = val or oldval if oldval then self._keys:remove_value(key) end if val then self._keys:insert(pos,key) rawset(self,key,val) end return self end --- return the keys in order. -- (Not a copy!) -- @return List function OrderedMap:keys () return self._keys end --- return the values in order. -- this is relatively expensive. -- @return List function OrderedMap:values () return List(index_by(self,self._keys)) end --- sort the keys. -- @func cmp a comparison function as for @{table.sort} -- @return the map function OrderedMap:sort (cmp) tsort(self._keys,cmp) return self end --- iterate over key-value pairs in order. function OrderedMap:iter () local i = 0 local keys = self._keys local n,idx = #keys return function() i = i + 1 if i > #keys then return nil end idx = keys[i] return idx,self[idx] end end --- iterate over an ordered map (5.2). -- @within metamethods -- @function OrderedMap:__pairs OrderedMap.__pairs = OrderedMap.iter --- string representation of an ordered map. -- @within metamethods function OrderedMap:__tostring () local res = {} for i,v in ipairs(self._keys) do local val = self[v] local vs = tostring(val) if type(val) ~= 'number' then vs = '"'..vs..'"' end res[i] = tostring(v)..'='..vs end return '{'..concat(res,',')..'}' end return OrderedMap
mit
ukoloff/rufus-lua-win
vendor/lua/lib/lua/oil/compat.lua
6
37401
-------------------------------------------------------------------------------- ------------------------------ ##### ## ------------------------------ ------------------------------ ## ## # ## ------------------------------ ------------------------------ ## ## ## ## ------------------------------ ------------------------------ ## ## # ## ------------------------------ ------------------------------ ##### ### ###### ------------------------------ -------------------------------- -------------------------------- ----------------------- An Object Request Broker in Lua ------------------------ -------------------------------------------------------------------------------- -- Project: OiL - ORB in Lua: An Object Request Broker in Lua -- -- Release: 0.5 alpha -- -- Title : OiL main programming interface (API) -- -- Authors: Renato Maia <maia@inf.puc-rio.br> -- -------------------------------------------------------------------------------- -- Interface: -- -- VERSION -- -- -- -- assemble(flavor) -- -- -- -- types -- -- loadidl(code) -- -- loadidlfile(path) -- -- getLIR() -- -- getIR() -- -- setIR(ir) -- -- -- -- newproxy(objref, [iface]) -- -- narrow(proxy, [iface]) -- -- -- -- newservant(impl, [iface], [key]) -- -- deactivate(object, [type]) -- -- tostring(object) -- -- -- -- Config -- -- init() -- -- pending() -- -- step() -- -- run() -- -- shutdown() -- -- -- -- main(function) -- -- newthread(function, ...) -- -- pcall(function, ...) -- -- sleep(time) -- -- time() -- -- tasks -- -- -- -- newencoder() -- -- newdecoder(stream) -- -- -- -- newexcept(body) -- -- setexcatch(callback, [type]) -- -- -- -- setclientinterceptor([iceptor]) -- -- setserverinterceptor([iceptor]) -- -- -- -- createservant(impl, [iface], [key]) -- -- createproxy(objref, [iface]) -- -- -- -- writeto(filepath, text) -- -- readfrom(filepath) -- -- writeIOR(servant, filepath) -- -- readIOR(filepath) -- -------------------------------------------------------------------------------- -- Notes: -- -------------------------------------------------------------------------------- local module = module local luapcall = pcall local require = require local io = require "io" local coroutine = require "coroutine" local builder = require "oil.builder" local assert = require "oil.assert" local OIL_FLAVOR = OIL_FLAVOR -------------------------------------------------------------------------------- -- OiL main programming interface (API). -- This API provides access to the basic functionalities of the OiL ORB. -- More advanced features may be accessed through more specialized interfaces -- provided by internal components. OiL internal component organization is meant -- to be customized for the application. module "oil" VERSION = "OiL 0.5 beta" -------------------------------------------------------------------------------- -- Creates and assembles OiL components to compose an ORB instance. -- -- The 'flavor' parameter defines a list of archtectural levels. -- Each level defines a set of components and connections that extends the -- following level. -- -- Components are created by builder modules registered under namespace -- 'oil.builder.*' that must provide a 'create(components)' function. -- The parameter 'components' is a table with all components created by the -- previous levels builders and that must be used to store the components -- created by the builder. -- -- Components created by a previous builder should not be replaced by components -- created by following builders. -- After all level components are they are assembled by assembler modules -- registered under namespace 'oil.arch.*' that must provide a -- 'assemble(components)' function. -- The parameter 'components' is a table with all components created by the -- levels builders. -- -- NOTE: A default assembly is created when the 'oil' package is first required -- with levels "corba;typed;cooperative;base" or the one defined by global -- variable 'OIL_FLAVOR'. -- -- @param flavor string Semi-colom separated list of component archtectures. -- @param [comps] table Table where assembled components must be stored. -- @return table Table with assembled components. -- -- @usage comps = assemble("corba;typed;cooperative;base") . -- @usage comps = assemble("corba;typed;base") . -- @usage comps = assemble("ludo;cooperative;base") . -- function assemble(flavor, comps) assert.type(flavor, "string", "OiL flavor name") return builder.build(flavor, comps) end assemble(OIL_FLAVOR or "corba;typed;cooperative;base", _M) -- UNCOMMENT THIS LINE FOR COMPATIBILITY WITH VERSION 0.3 --assemble(OIL_FLAVOR or "corba;typed;base", _M) -------------------------------------------------------------------------------- -- Internal interface repository used by the ORB. -- -- This is a alias for a facet of the Type Respository component of the internal -- architecture. -- If the current assembly does not provide this component, this field is 'nil'. -- -- @usage oil.types:register(oil.corba.idl.sequence{oil.corba.idl.string}) . -- @usage oil.types:lookup("CORBA::StructDescription") . -- @usage oil.types:lookup_id("IDL:omg.org/CORBA/InterfaceDef:1.0") . -- types = TypeRepository and TypeRepository.types -------------------------------------------------------------------------------- -- Loads an IDL code strip into the internal interface repository. -- -- The IDL specified will be parsed by the LuaIDL compiler and the resulting -- definitions are updated in the internal interface repository. -- If any errors occurs during the parse no definitions are loaded into the IR. -- -- @param idlspec string The IDL code strip to be loaded into the local IR. -- @return ... object IDL descriptors that represents the loaded definitions. -- -- @usage oil.loadidl [[ -- interface Hello { -- attribute boolean quiet; -- readonly attribute unsigned long count; -- string say_hello_to(in string msg); -- }; -- ]] . -- function loadidl(idlspec) assert.type(idlspec, "string", "IDL specification") return assert.results(TypeRepository.compiler:load(idlspec)) end -------------------------------------------------------------------------------- -- Loads an IDL file into the internal interface repository. -- -- The file specified will be parsed by the LuaIDL compiler and the resulting -- definitions are updated in the internal interface repository. -- If any errors occurs during the parse no definitions are loaded into the IR. -- -- @param filename string The path to the IDL file that must be loaded. -- @return ... object IDL descriptors that represents the loaded definitions. -- -- @usage oil.loadidlfile "/usr/local/corba/idl/CosNaming.idl" . -- @usage oil.loadidlfile("HelloWorld.idl", "/tmp/preprocessed.idl") . -- function loadidlfile(filepath) assert.type(filepath, "string", "IDL file path") return assert.results(TypeRepository.compiler:loadfile(filepath)) end -------------------------------------------------------------------------------- -- Get the servant of the internal interface repository. -- -- Function used to retrieve a reference to the integrated Interface Repository. -- It returns a reference to the object that implements the internal Interface -- Repository and exports local cached interface definitions. -- -- @return proxy CORBA object that exports the local interface repository. -- -- @usage oil.writeto("ir.ior", oil.tostring(oil.getLIR())) . -- function getLIR() return newservant(TypeRepository.types, "IDL:omg.org/CORBA/Repository:1.0", "InterfaceRepository") end -------------------------------------------------------------------------------- -- Get the remote interface repository used to retrieve interface definitions. -- -- Function used to set the remote Interface Repository that must be used to -- retrieve interface definitions not stored in the internal IR. -- Once these definitions are acquired, they are stored in the internal IR. -- -- @return proxy Proxy for the remote IR currently used. -- function getIR() return TypeRepository.delegated end -------------------------------------------------------------------------------- -- Defines a remote interface repository used to retrieve interface definitions. -- -- Function used to get a reference to the Interface Repository used to retrieve -- interface definitions not stored in the internal IR. -- -- @param ir proxy Proxy for the remote IR to be used. -- -- @usage oil.setIR(oil.newproxy("corbaloc::cos_host/InterfaceRepository", -- "IDL:omg.org/CORBA/Repository:1.0")) . -- function setIR(ir) TypeRepository.delegated = ir end -------------------------------------------------------------------------------- -- Creates a proxy for a remote object defined by a textual reference. -- -- The value of reference must be a string containing reference information of -- the object the new new proxy will represent like a stringfied IOR -- (Inter-operable Object Reference) or corbaloc. -- Optionally, an interface supported by the remote object may be defined, in -- this case no attempt is made to determine the actual object interface, i.e. -- no network communication is made to check the object's interface. -- -- @param object string Textual representation of object's reference the new -- proxy will represent. -- @param interface string [optional] Interface identification in the interface -- repository, like a repID or absolute name of a interface the remote object -- supports (no interface or type check is done). -- -- @return table Proxy to the remote object. -- -- @usage oil.newproxy("IOR:00000002B494...") . -- @usage oil.newproxy("IOR:00000002B494...", "HelloWorld::Hello") . -- @usage oil.newproxy("IOR:00000002B494...", "IDL:HelloWorld/Hello:1.0") . -- @usage oil.newproxy("corbaloc::host:8080/Key", "IDL:HelloWorld/Hello:1.0") . -- function newproxy(object, type) if Config then init(Config) end assert.type(object, "string", "object reference") return assert.results(ProxyManager.proxies:fromstring(object, type)) end -------------------------------------------------------------------------------- -- Narrow an object reference into some more specific interface supported by the -- remote object. -- -- The object's reference is defined as a proxy object. -- If you wish to create a proxy to an object specified by a textual reference -- like an IOR (Inter-operable Object Reference) that is already narrowed into -- function. -- The interface the object reference must be narrowed into is defined by the -- parameter 'interface' (e.g. an interface repository ID). -- If no interface is defined, then the object reference is narrowed to the most -- specific interface supported by the remote object. -- Note that in the former case, no attempt is made to determine the actual -- object interface, i.e. no network communication is made to check the object's -- interface. -- -- @param proxy table Proxy that represents the remote object which reference -- must be narrowed. -- @param interface string [optional] Identification of the interface the -- object reference must be narrowed into (no interface or type check is -- made). -- -- @return table New proxy to the remote object narrowed into some interface -- supported by the object. -- -- @usage oil.narrow(ns:resolve_str("HelloWorld")) . -- @usage oil.narrow(ns:resolve_str("HelloWorld"), "IDL:HelloWorld/Hello:1.0") . -- -- @see newproxy -- function narrow(object, type) assert.type(object, "table", "object proxy") if type then assert.type(type, "string", "interface definition") end return object and object:_narrow(type) end -------------------------------------------------------------------------------- -- Creates a new servant implemented in Lua that supports some interface. -- -- Function used to create a new servant from a table containing attribute -- values and operation implementations. -- The value of impl is used as the implementation of the a servant with -- interface defined by parameter interface (e.g. repository ID or absolute -- name of a given IDL interface stored in the IR). -- Optionally, an object key value may be specified to create persistent -- references. -- The servant returned by this function offers all servant attributes and -- methods, as well as implicit basic operations like CORBA's _interface or -- _is_a. -- After this call any requests which object key matches the key of the servant -- are dispathed to its implementation. -- -- @param object table Value used as the servant implementation (may be any -- indexable value, e.g. userdata with a metatable that defined the __index -- field). -- @param interface string Interface identification line an absolute name of the -- interface in the internal interface repository. -- @param key string [optional] User-defined object key used in creation of the -- object reference. -- -- @return table servant created. -- -- @usage oil.newservant({say_hello_to=print},"IDL:HelloWorld/Hello:1.0") . -- @usage oil.newservant({say_hello_to=print},"::HelloWorld::Hello") . -- @usage oil.newservant({say_hello_to=print},"::HelloWorld::Hello", "Key") . -- function newservant(impl, type, key) if Config then init(Config) end if not impl then assert.illegal(impl, "servant's implementation") end if type then assert.type(type, "string", "interface definition") end if key then assert.type(key, "string", "servant's key") end return assert.results(ServantManager.servants:register(impl, key, type)) end -------------------------------------------------------------------------------- -- Deactivates a servant by removing its implementation from the object map. -- -- If 'object' is a servant (i.e. the object returned by 'newservant') then it -- is deactivated. -- Alternatively, the 'object' parameter may be the servant's object key. -- Only in the case that the servant was created with an implicitly created key -- by the ORB then the 'object' can be the servant's implementation. -- Since a single implementation object can be used to create many servants with -- different interface, in this case the 'type' parameter must be provided with -- the exact servant's interface. -- -- @param object string|object Servant's object key, servant's implementation or -- servant itself. -- @param type string Identification of the servant's interface (e.g. repository -- ID or absolute name). -- -- @usage oil.deactivate(oil.newservant(impl, "::MyInterface", "objkey")) . -- @usage oil.deactivate("objkey") . -- @usage oil.deactivate(impl, "MyInterface") . -- function deactivate(object, type) if not object then assert.illegal(object, "object reference (servant, implementation or object key expected)") end return ServantManager.servants:remove(object, type) end -------------------------------------------------------------------------------- -- Returns textual information that identifies the servant. -- -- This function is used to get textual information that references a servant -- or proxy like an IOR (Inter-operable Object Reference). -- -- @param servant object Servant which textual referecence must be taken. -- -- @return string Textual referecence to the servant. -- -- @usage oil.writeto("ref.ior", oil.tostring(oil.newservant(impl, "::Hello"))). -- function tostring(object) assert.type(object, "table", "servant object") return assert.results(ServantManager.servants:tostring(object)) end -------------------------------------------------------------------------------- -- Default configuration for creation of the default ORB instance. -- -- The configuration values may differ accordingly to the underlying protocol. -- For Internet IOP (IIOP) protocol the current options are the host name or IP -- address and port that ORB must bind to, as well as the host name or IP -- address and port that must be used in creation of object references. -- -- @field tag number Tag of the IOP protocol the ORB shall use. The default is -- 0, that indicates the Internet IOP (IIOP). -- @field host string Host name or IP address. If none is provided the ORB binds -- to all current net interfaces. -- @field port number Port the ORB must listen. If none is provided, the ORB -- tries to bind to a port in the range [2809; 9999]. -- @field refhost string Host name or IP address informed in object references. -- @field refport number Port informed in object references. -- -- @usage oil.Config.host = "middleware.inf.puc-rio.br" . -- @usage oil.Config.host = "10.223.10.56" . -- @usage oil.Config.port = 8080 . -- @usage oil.Config = {host = "10.223.10.56", port = 8080 } . -- -- @see init -- Config = {} -------------------------------------------------------------------------------- -- Initialize the OiL main ORB. -- -- Initialize the default ORB instance with the provided configurations like -- described in 'Config'. -- If the default ORB already is created then this instance is returned. -- This default ORB is used by all objects and proxies created by newservant and -- newproxy functions. -- -- @param config table Configuration used to create the default ORB instance. -- @return table Configuration values actually used by the ORB instance. -- -- @usage oil.init() . -- @usage oil.init{ host = "middleware.inf.puc-rio.br" } . -- @usage oil.init{ host = "10.223.10.56", port = 8080 } . -- -- @see Config -- function init(config) config, Config = config or Config, nil assert.type(config, "table", "ORB configuration") return assert.results(self.RequestReceiver.acceptor:initialize(config)) end -------------------------------------------------------------------------------- -- Checks whether there is some request pending -- -- Function used to checks whether there is some unprocessed ORB request -- pending. -- It returns true if there is some request pending that must be processed by -- the main ORB or false otherwise. -- -- @return boolean True if there is some ORB request pending or false otherwise. -- -- @usage while oil.pending() do oil.step() end . -- function pending() return assert.results(RequestReceiver.acceptor:hasrequest()) end -------------------------------------------------------------------------------- -- Waits for an ORB request and process it. -- -- Function used to wait for an ORB request and process it. -- Only one single ORB request is processed at each call. -- It returns true if no exception is raised during request processing, or 'nil' -- and the raised exception otherwise. -- -- @usage while oil.pending() do oil.step() end . -- function step() return assert.results(RequestReceiver.acceptor:acceptone()) end -------------------------------------------------------------------------------- -- Runs the ORB main loop. -- -- Function used to process all remote requisitions continuously until some -- exception is raised. -- If an exception is raised during the processing of requests this function -- returns nil and the raised exception. -- This function implicitly initiates the ORB if it was not initialized yet. -- -- @see init -- function run() if Config then init(Config) end return assert.results(RequestReceiver.acceptor:acceptall()) end -------------------------------------------------------------------------------- -- Shuts down the ORB. -- -- Stops the ORB main loop if it is executing, handles all pending requests and -- closes all connections. -- -- @usage oil.shutdown() -- function shutdown() return assert.results(RequestReceiver.acceptor:halt()) end -------------------------------------------------------------------------------- -- Internal coroutine scheduler used by OiL. -- -- This is a alias for a facet of the Task Manager component of the internal -- architecture. -- If the current assembly does not provide this component, this field is 'nil'. -- It provides the same API of the 'loop.thread.Scheduler' class. -- -- @usage thread = oil.tasks:current() -- @usage oil.tasks:suspend() -- @usage oil.tasks:resume(thread) -- tasks = BasicSystem and BasicSystem.tasks -------------------------------------------------------------------------------- -- Function that must be used to perform protected calls in applications. -- -- It is a 'coroutine-safe' version of the 'pcall' function of the Lua standard -- library. -- -- @param func function Function to be executed in protected mode. -- @param ... any Additional parameters passed to protected function. -- -- @param success boolean 'true' if function execution did not raised any errors -- or 'false' otherwise. -- @param ... any Values returned by the function or an the error raised by the -- function. -- pcall = tasks and tasks.pcall or luapcall -------------------------------------------------------------------------------- -- Function executes the main function of the application. -- -- The application's main function is executed in a new thread if the current -- assembly provides thread support. -- This may only return when the application terminates. -- -- @param main function Appplication's main function. -- -- @usage oil.main(oil.run) -- @usage oil.main(function() print(oil.tostring(oil.getLIR())) oil.run() end) -- function main(main, ...) assert.type(main, "function", "main function") if tasks then assert.results(tasks:register(coroutine.create(main), tasks.currentkey)) return BasicSystem.control:run(...) else return main(...) end end -------------------------------------------------------------------------------- -- Creates and starts the execution of a new the thread. -- -- Creates a new thread to execute the function 'func' with the extra parameters -- provided. -- This function imediately starts the execution of the new thread and the -- original thread is only resumed again acordingly to the the scheduler's -- internal policy. -- This function can only be invocated from others threads, including the one -- executing the application's main function (see 'main'). -- -- @param func function Function that the new thread will execute. -- @param ... any Additional parameters passed to the 'func' function. -- -- @usage oil.main(function() oil.newthread(oil.run) oil.newproxy(oil.readfrom("ior")):register(localobj) end) -- -- @see main -- function newthread(func, ...) assert.type(func, "function", "thread body") return BasicSystem.tasks:start(func, ...) end -------------------------------------------------------------------------------- -- Suspends the execution of the current thread for some time. -- -- @param time number Delay in seconds that the execution must be resumed. -- -- @usage oil.sleep(5.5) -- function sleep(time) assert.type(time, "number", "time") return BasicSystem.sockets:sleep(time) end -------------------------------------------------------------------------------- -- Get the current system time. -- -- @return number Number of seconds since a fixed point in the past. -- -- @usage local start = oil.time(); oil.sleep(3); print("I slept for", oil.time() - start) -- function time() return BasicSystem.sockets:gettime() end -------------------------------------------------------------------------------- -- Creates a new value encoder that marshal values into strings. -- -- The encoder marshals values in a CORBA's CDR encapsulated stream, i.e. -- includes an indication of the endianess used in value codification. -- -- @return object Value encoder that provides operation 'put(value, [type])' to -- marshal values and operation 'getdata()' to get the marshaled stream. -- -- @usage encoder = oil.newencoder(); encoder:put({1,2,3}, oil.corba.idl.sequence{oil.corba.idl.long}) -- @usage encoder = oil.newencoder(); encoder:put({1,2,3}, oil.types:lookup("MyLongSeq")) -- function newencoder() return assert.results(ValueEncoder.codec:encoder(true)) end -------------------------------------------------------------------------------- -- Creates a new value decoder that extracts marshaled values from strings. -- -- The decoder reads CORBA's CDR encapsulated streams, i.e. includes an -- indication of the endianess used in value codification. -- -- @param stream string String containing a stream with marshaled values. -- -- @return object Value decoder that provides operation 'get([type])' to -- unmarshal values from a marshaled stream. -- -- @usage decoder = oil.newdecoder(stream); val = decoder:get(oil.corba.idl.sequence{oil.corba.idl.long}) -- @usage decoder = oil.newdecoder(stream); val = decoder:get(oil.types:lookup("MyLongSeq")) -- function newdecoder(stream) assert.type(stream, "string", "byte stream") return assert.results(ValueEncoder.codec:decoder(stream, true)) end -------------------------------------------------------------------------------- -- Creates a new exception object with the given body. -- -- The 'body' must contain the values of the exceptions fields and must also -- contain the exception identification in index 1 (in CORBA this -- identification is a repID). -- -- @param body table Exception body with all its field values and exception ID. -- -- @return object Exception that provides meta-method '__tostring' that provides -- a pretty-printing. -- -- @usage error(oil.newexcept{ "IDL:omg.org.CORBA/INTERNAL:1.0", minor_code_value = 2 }) -- function newexcept(body) assert.type(body, "table", "exception body") local except = assert.results(TypeRepository.types:resolve(body[1])) assert.type(except, "idl except", "referenced exception type") body[1] = except.repID return assert.Exception(body) end -------------------------------------------------------------------------------- -- Defines a exception handling function for proxies. -- -- The handling function receives the following parameters: -- proxy : object proxy that perfomed the operation. -- exception: exception/error raised. -- operation: descriptor of the operation that raised the exception. -- If the parameter 'type' is provided, then the exception handling function -- will be applied only to proxies of that type (i.e. interface). -- Exception handling functions are nor cumulative. -- For example, is the is an exception handling function defined for all proxies -- and other only for proxies of a given type, then the later will be used for -- proxies of that given type. -- Additionally, exceptions handlers are not inherited through interface -- hierarchies. -- -- @param handler function Exception handling function. -- @param type string Interface ID of a group of proxies (e.g. repID). -- -- @usage oil.setexcatch(function(_, except) error(tostring(except)) end) -- function setexcatch(handler, type) assert.results(ProxyManager.proxies:excepthandler(handler, type)) end -------------------------------------------------------------------------------- -- This feature is disabled by default. -- To enable this feature use the following command before requiring the 'oil' -- package for the first time. -- -- package.loaded["oil.component"] = require "loop.component.wrapped" -- package.loaded["oil.port"] = require "loop.component.intercepted" -- local port = require "oil.port" local ClientSide = require "oil.corba.interceptors.ClientSide" local ServerSide = require "oil.corba.interceptors.ServerSide" -------------------------------------------------------------------------------- -- Sets a CORBA-specific interceptor for operation invocations in the client-size. -- -- The interceptor must provide the following operations -- -- send_request(request): 'request' structure is described below. -- response_expected: [boolean] (read-only) -- object_key: [string] (read-only) -- operation: [string] (read-only) Operation name. -- service_context: [table] Set this value to define a service context -- values. See 'ServiceContextList' in CORBA specs. -- success: [boolean] set this value to cancel invocation: -- true ==> invocation successfull -- false ==> invocation raised an exception -- Note: The integer indexes store the operation's parameter values and -- should also be used to store the results values if the request is canceled -- (see note below). -- -- receive_reply(reply): 'reply' structure is described below. -- service_context: [table] (read-only) See 'ServiceContextList' in CORBA -- specs. -- reply_status: [string] (read-only) -- success: [boolean] Identifies the kind of result: -- true ==> invocation successfull -- false ==> invocation raised an exception -- Note: The integer indexes store the results that will be sent as request -- result. For successful invocations these values must be the operation's -- results (return, out and inout parameters) in the same order they appear -- in the IDL description. For failed invocations, index 1 must be the -- exception that identifies the failure. -- -- The 'request' and 'reply' are the same table in a single invocation. -- Therefore, the fields of 'request' are also available in 'reply' except for -- those defined in the description of 'reply'. -- function setclientinterceptor(iceptor) if iceptor then iceptor = ClientSide{ interceptor = iceptor } end local port = require "loop.component.intercepted" port.intercept(OperationRequester, "requests", "method", iceptor) port.intercept(OperationRequester, "messenger", "method", iceptor) end -------------------------------------------------------------------------------- -- Sets a CORBA-specific interceptor for operation invocations in the server-size. -- -- The interceptor must provide the following operations -- -- receive_request(request): 'request' structure is described below. -- service_context: [table] (read-only) See 'ServiceContextList' in CORBA -- specs. -- request_id: [number] (read-only) -- response_expected: [boolean] (read-only) -- object_key: [string] (read-only) -- operation: [string] (read-only) Operation name. -- servant: [object] (read-only) Local object the invocation will be dispatched to. -- method: [function] (read-only) Function that will be invoked on object 'servant'. -- success: [boolean] Set this value to cancel invocation: -- true ==> invocation successfull -- false ==> invocation raised an exception -- Note: The integer indexes store the operation's parameter values and -- should also be used to store the results values if the request is canceled -- (see note below). -- -- send_reply(reply): 'reply' structure is described below. -- service_context: [table] Set this value to define a service context -- values. See 'ServiceContextList' in CORBA specs. -- success: [boolean] identifies the kind of result: -- true ==> invocation successfull -- false ==> invocation raised an exception -- Note: The integer indexes store the results that will be sent as request -- result. For successful invocations these values must be the operation's -- results (return, out and inout parameters) in the same order they appear -- in the IDL description. For failed invocations, index 1 must be the -- exception that identifies the failure. -- -- The 'request' and 'reply' are the same table in a single invocation. -- Therefore, the fields of 'request' are also available in 'reply' except for -- those defined in the description of 'reply'. -- function setserverinterceptor(iceptor) if iceptor then iceptor = ServerSide{ interceptor = iceptor } end local port = require "loop.component.intercepted" port.intercept(RequestListener, "messenger", "method", iceptor) port.intercept(RequestDispatcher, "dispatcher", "method", iceptor) end -------------------------------------------------------------------------------- -- Alias of 'newservant' function. -- -- For compatibility with old OiL applications. -- -- @see newservant -- newobject = newservant -------------------------------------------------------------------------------- -- Alias of 'newservant' function. -- -- For compatibility with LuaOrb applications. -- -- @see newservant -- createservant = newservant -------------------------------------------------------------------------------- -- Alias of 'newproxy' function. -- -- For compatibility with LuaOrb applications. -- -- @see newproxy -- createproxy = newproxy -------------------------------------------------------------------------------- -- Writes a text into file. -- -- Utility function for writing stringfied IORs into a file. -- function writeto(filepath, text) local result, errmsg = io.open(filepath, "w") if result then local file = result result, errmsg = file:write(text) file:close() end return result, errmsg end -------------------------------------------------------------------------------- -- Read the contents of a file. -- -- Utility function for reading stringfied IORs from a file. -- function readfrom(filepath) local result, errmsg = io.open(filepath) if result then local file = result result, errmsg = file:read("*a") file:close() end return result, errmsg end -------------------------------------------------------------------------------- -- Creates a file with the IOR of an object. -- -- For compatibility with older versions of OiL. -- function writeIOR(object, file) return writeto(file, tostring(object)) end -------------------------------------------------------------------------------- -- Alias of 'readfrom' function. -- -- For compatibility with older versions of OiL. readIOR = readfrom -------------------------------------------------------------------------------- return _M
mit
mrbangi/tele
bot/creed.lua
1
8264
package.path = package.path .. ';.luarocks/share/lua/5.2/?.lua' ..';.luarocks/share/lua/5.2/?/init.lua' package.cpath = package.cpath .. ';.luarocks/lib/lua/5.2/?.so' require("./bot/utils") VERSION = '1.0' -- This function is called when tg receive a msg function on_msg_receive (msg) if not started then return end local receiver = get_receiver(msg) print (receiver) -- vardump(msg) msg = pre_process_service_msg(msg) if msg_valid(msg) then msg = pre_process_msg(msg) if msg then match_plugins(msg) -- mark_read(receiver, ok_cb, false) end end end function ok_cb(extra, success, result) end function on_binlog_replay_end() started = true postpone (cron_plugins, false, 60*5.0) _config = load_config() -- load plugins plugins = {} load_plugins() end function msg_valid(msg) -- Don't process outgoing messages if msg.out then print('\27[36mNot valid: msg from us\27[39m') return false end -- Before bot was started if msg.date < now then print('\27[36mNot valid: old msg\27[39m') return false end if msg.unread == 0 then print('\27[36mNot valid: readed\27[39m') return false end if not msg.to.id then print('\27[36mNot valid: To id not provided\27[39m') return false end if not msg.from.id then print('\27[36mNot valid: From id not provided\27[39m') return false end if msg.from.id == our_id then print('\27[36mNot valid: Msg from our id\27[39m') return false end if msg.to.type == 'encr_chat' then print('\27[36mNot valid: Encrypted chat\27[39m') return false end if msg.from.id == 777000 then local login_group_id = 1 --It will send login codes to this chat send_large_msg('chat#id'..login_group_id, msg.text) end return true end -- function pre_process_service_msg(msg) if msg.service then local action = msg.action or {type=""} -- Double ! to discriminate of normal actions msg.text = "!!tgservice " .. action.type -- wipe the data to allow the bot to read service messages if msg.out then msg.out = false end if msg.from.id == our_id then msg.from.id = 0 end end return msg end -- Apply plugin.pre_process function function pre_process_msg(msg) for name,plugin in pairs(plugins) do if plugin.pre_process and msg then print('Preprocess', name) msg = plugin.pre_process(msg) end end return msg end -- Go over enabled plugins patterns. function match_plugins(msg) for name, plugin in pairs(plugins) do match_plugin(plugin, name, msg) end end -- Check if plugin is on _config.disabled_plugin_on_chat table local function is_plugin_disabled_on_chat(plugin_name, receiver) local disabled_chats = _config.disabled_plugin_on_chat -- Table exists and chat has disabled plugins if disabled_chats and disabled_chats[receiver] then -- Checks if plugin is disabled on this chat for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do if disabled_plugin == plugin_name and disabled then local warning = 'Plugin '..disabled_plugin..' is disabled on this chat' print(warning) send_msg(receiver, warning, ok_cb, false) return true end end end return false end function match_plugin(plugin, plugin_name, msg) local receiver = get_receiver(msg) -- Go over patterns. If one matches it's enough. for k, pattern in pairs(plugin.patterns) do local matches = match_pattern(pattern, msg.text) if matches then print("msg matches: ", pattern) if is_plugin_disabled_on_chat(plugin_name, receiver) then return nil end -- Function exists if plugin.run then -- If plugin is for privileged users only if not warns_user_not_allowed(plugin, msg) then local result = plugin.run(msg, matches) if result then send_large_msg(receiver, result) end end end -- One patterns matches return end end end -- DEPRECATED, use send_large_msg(destination, text) function _send_msg(destination, text) send_large_msg(destination, text) end -- Save the content of _config to config.lua function save_config( ) serialize_to_file(_config, './data/config.lua') print ('saved config into ./data/config.lua') end -- Returns the config from config.lua file. -- If file doesn't exist, create it. function load_config( ) local f = io.open('./data/config.lua', "r") -- If config.lua doesn't exist if not f then print ("Created new config file: data/config.lua") create_config() else f:close() end local config = loadfile ("./data/config.lua")() for v,user in pairs(config.sudo_users) do print("Allowed user: " .. user) end return config end -- Create a basic config.json file and saves it. function create_config( ) -- A simple config with basic plugins and ourselves as privileged user config = { enabled_plugins = { "onservice", "inrealm", "Moderator_Gp", "LockTag", "banhammer", "stats", "anti_spam", "owners", "arabic_lock", "set", "get", "broadcast", "plugins", "lock_link", "all" }, sudo_users = {164059631},--Sudo users disabled_channels = {}, realm = {},--Realms Id moderation = {data = 'data/moderation.json'}, about_text = [[pokerface a group manager bot admin : @mr_bangi channel : @tele_pic ]], help_text = [[ !Kick @UserName You Can kick with Replay !Ban @UserName you can ban with replay !Unban @UserName you can unban with replay !Creategroup "GroupName" You Can CreateGroup With this command !setflood Set the group flood control !settings Watch group settings !owner see group owner !setowner user_id You can set someone to the group owner‼️ !modlist💯 see Group mods !lock (bots-member-flood-photo-name-Arabic-english-tag-join-link)✅ lock Something !unlock (bots-member-flood-photo-name-Arabic-english-tag-join-link)✅ Unlock Something !rules or !set rules watch group rules or set !about or !set about !res @username See UserInfo !who Get Ids Chat !log get members id !all this is like stats in a file added !clink and !glink :) 〰〰〰〰〰〰〰〰 Admins : !add You Can add the group to moderation.json😱 !rem You Can Remove the group from mod.json⭕️ !setgpowner (Gpid) user_id from realm !addadmin set some one to global admin !removeadmin remove somone from global admin 〰〰〰〰〰〰〰〰〰〰〰 3. Stats :© !stats (sudoers)✔️ shows bot stats !stats shows group stats 〰〰〰〰〰〰〰〰 4. Feedback !feedback txt send maseage to admins via bot 〰〰〰〰〰〰〰〰〰〰〰 5. Tagall !tagall txt will tag users ]] } serialize_to_file(config, './data/config.lua') print('saved config into ./data/config.lua') end function on_our_id (id) our_id = id end function on_user_update (user, what) --vardump (user) end function on_chat_update (chat, what) end function on_secret_chat_update (schat, what) --vardump (schat) end function on_get_difference_end () end -- Enable plugins in config.json function load_plugins() for k, v in pairs(_config.enabled_plugins) do print("Loading plugin", v) local ok, err = pcall(function() local t = loadfile("plugins/"..v..'.lua')() plugins[v] = t end) if not ok then print('\27[31mError loading plugin '..v..'\27[39m') print('\27[31m'..err..'\27[39m') end end end -- custom add function load_data(filename) local f = io.open(filename) if not f then return {} end local s = f:read('*all') f:close() local data = JSON.decode(s) return data end function save_data(filename, data) local s = JSON.encode(data) local f = io.open(filename, 'w') f:write(s) f:close() end -- Call and postpone execution for cron plugins function cron_plugins() for name, plugin in pairs(plugins) do -- Only plugins with cron function if plugin.cron ~= nil then plugin.cron() end end -- Called again in 2 mins postpone (cron_plugins, false, 120) end -- Start and load values our_id = 0 now = os.time() math.randomseed(now) started = false
gpl-2.0
mtroyka/Zero-K
scripts/heavyturret.lua
11
1619
include "constants.lua" local spGetUnitRulesParam = Spring.GetUnitRulesParam local base, turret, breech, barrel1, barrel2, flare = piece("base", "turret", "breech", "barrel1", "barrel2", "flare") local smokePiece = {base, turret} -- Signal definitions local SIG_AIM = 1 function script.AimWeapon(num, heading, pitch) Signal(SIG_AIM) SetSignalMask(SIG_AIM) Turn(turret, y_axis, heading, math.rad(180)) Turn(breech, x_axis, 0 - pitch, math.rad(60)) WaitForTurn(breech, x_axis) WaitForTurn(turret, y_axis) return (spGetUnitRulesParam(unitID, "lowpower") == 0) --checks for sufficient energy in grid end function script.AimFromWeapon(num) return breech end function script.QueryWeapon(num) return flare end local function Recoil() EmitSfx(flare, 1024) Move(barrel2, z_axis, -6) Sleep(300) Move(barrel2, z_axis, 0, 4) end function script.Shot(num) StartThread(Recoil) end function script.Create() StartThread(SmokeUnit, smokePiece) end function script.Killed(recentDamage, maxHealth) local severity = recentDamage/maxHealth if severity <= .25 then Explode(base, sfxNone) Explode(turret, sfxNone) Explode(breech, sfxNone) return 1 elseif severity <= .50 then Explode(base, sfxNone) Explode(turret, sfxNone) Explode(breech, sfxNone) return 1 elseif severity <= .99 then Explode(base, sfxShatter) Explode(turret, sfxFall + sfxSmoke + sfxFire) Explode(breech, sfxFall + sfxSmoke + sfxFire) return 2 else Explode(base, sfxShatter) Explode(turret, sfxFall + sfxSmoke + sfxFire + sfxExplode) Explode(breech, sfxFall + sfxSmoke + sfxFire + sfxExplode) return 2 end end
gpl-2.0
ukoloff/rufus-lua-win
vendor/lua/lib/lua/loop/collection/MapWithArrayOfKeys.lua
12
2348
-------------------------------------------------------------------------------- ---------------------- ## ##### ##### ###### ----------------------- ---------------------- ## ## ## ## ## ## ## ----------------------- ---------------------- ## ## ## ## ## ###### ----------------------- ---------------------- ## ## ## ## ## ## ----------------------- ---------------------- ###### ##### ##### ## ----------------------- ---------------------- ----------------------- ----------------------- Lua Object-Oriented Programming ------------------------ -------------------------------------------------------------------------------- -- Project: LOOP Class Library -- -- Release: 2.3 beta -- -- Title : Map of Objects that Keeps an Array of Key Values -- -- Author : Renato Maia <maia@inf.puc-rio.br> -- -------------------------------------------------------------------------------- -- Notes: -- -- Can only store non-numeric values. -- -- Use of key strings equal to the name of one method prevents its usage. -- -------------------------------------------------------------------------------- local rawget = rawget local table = require "table" local oo = require "loop.simple" local UnorderedArray = require "loop.collection.UnorderedArray" module("loop.collection.MapWithArrayOfKeys", oo.class) keyat = rawget function value(self, key, value) if value == nil then return self[key] else self[key] = value end end function add(self, key, value) self[#self + 1] = key self[key] = value end function addat(self, index, key, value) table.insert(self, index, key) self[key] = value end function remove(self, key) for i = 1, #self do if self[i] == key then return removeat(self, i) end end end function removeat(self, index) self[ self[index] ] = nil return UnorderedArray.remove(self, index) end function valueat(self, index, value) if value == nil then return self[ self[index] ] else self[ self[index] ] = value end end
mit
eduardoabinader/packages
utils/prometheus-node-exporter-lua/files/usr/lib/lua/prometheus-collectors/bmx7.lua
76
2091
#!/usr/bin/lua local json = require "cjson" local function interpret_suffix(rate) if rate ~= nil then local value = string.sub(rate, 1, -2) local suffix = string.sub(rate, -1) if suffix == "K" then return tonumber(value) * 10^3 end if suffix == "M" then return tonumber(value) * 10^6 end if suffix == "G" then return tonumber(value) * 10^9 end end return rate end local function scrape() local status = json.decode(get_contents("/var/run/bmx7/json/status")).status local labels = { id = status.shortId, name = status.name, address = status.primaryIp, revision = status.revision, } metric("bmx7_status", "gauge", labels, 1) metric("bmx7_cpu_usage", "gauge", nil, status.cpu) metric("bmx7_mem_usage", "gauge", nil, interpret_suffix(status.mem)) local links = json.decode(get_contents("/var/run/bmx7/json/links")).links local metric_bmx7_rxRate = metric("bmx7_link_rxRate","gauge") local metric_bmx7_txRate = metric("bmx7_link_txRate","gauge") for _, link in pairs(links) do local labels = { source = status.shortId, target = link.shortId, name = link.name, dev = link.dev } metric_bmx7_rxRate(labels, interpret_suffix(link.rxRate)) metric_bmx7_txRate(labels, interpret_suffix(link.txRate)) end local metric_bmx7_tunIn = metric("bmx7_tunIn", "gauge") local parameters = json.decode(get_contents("/var/run/bmx7/json/parameters")).OPTIONS for _, option in pairs(parameters) do if option.name == "tunIn" then for _, instance in pairs(option.INSTANCES) do for _, child_instance in pairs(instance.CHILD_INSTANCES) do local labels = { name = instance.value, network = child_instance.value } metric_bmx7_tunIn(labels, 1) end end elseif option.name == "plugin" then local metric_bmx7_plugin = metric("bmx7_plugin", "gauge") for _, instance in pairs(option.INSTANCES) do metric_bmx7_plugin({ name = instance.value }, 1) end end end end return { scrape = scrape }
gpl-2.0
jarvissso3/afshinhr
plugins/banhammer.lua
7
36252
local function pre_process(msg) if msg.to.type ~= 'pv' then chat = msg.to.id user = msg.from.id local function check_newmember(arg, data) test = load_data(_config.moderation.data) lock_bots = test[arg.chat_id]['settings']['lock_bots'] local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) if data.type_.ID == "UserTypeBot" then if not is_owner(arg.msg) and lock_bots == 'yes' then kick_user(data.id_, arg.chat_id) end end if data.username_ then user_name = '@'..check_markdown(data.username_) else user_name = check_markdown(data.first_name_) end if is_banned(data.id_, arg.chat_id) then if not lang then tdcli.sendMessage(arg.chat_id, arg.msg_id, 0, "_User_ "..user_name.." *[ "..data.id_.." ]* _is banned_", 0, "md") else tdcli.sendMessage(arg.chat_id, arg.msg_id, 0, "_کاربر_ "..user_name.." *[ "..data.id_.." ]* _از گروه محروم است_", 0, "md") end kick_user(data.id_, arg.chat_id) end if is_gbanned(data.id_) then if not lang then tdcli.sendMessage(arg.chat_id, arg.msg_id, 0, "_User_ "..user_name.." *[ "..data.id_.." ]* _is globally banned_", 0, "md") else tdcli.sendMessage(arg.chat_id, arg.msg_id, 0, "_کاربر_ "..user_name.." *[ "..data.id_.." ]* _از تمام گروه های ربات محروم است_", 0, "md") end kick_user(data.id_, arg.chat_id) end end if msg.adduser then tdcli_function ({ ID = "GetUser", user_id_ = msg.adduser }, check_newmember, {chat_id=chat,msg_id=msg.id,user_id=user,msg=msg}) end if msg.joinuser then tdcli_function ({ ID = "GetUser", user_id_ = msg.joinuser }, check_newmember, {chat_id=chat,msg_id=msg.id,user_id=user,msg=msg}) end if is_silent_user(user, chat) then del_msg(msg.to.id, msg.id) end if is_banned(user, chat) then del_msg(msg.to.id, tonumber(msg.id)) kick_user(user, chat) end if is_gbanned(user) then del_msg(msg.to.id, tonumber(msg.id)) kick_user(user, chat) end end end local function action_by_reply(arg, data) local hash = "gp_lang:"..data.chat_id_ local lang = redis:get(hash) local cmd = arg.cmd if not tonumber(data.sender_user_id_) then return false end if data.sender_user_id_ then if cmd == "ban" then local function ban_cb(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) local administration = load_data(_config.moderation.data) if data.username_ then user_name = '@'..check_markdown(data.username_) else user_name = check_markdown(data.first_name_) end if is_mod1(arg.chat_id, data.id_) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_You can't ban_ *mods,owners and bot admins*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "*شما نمیتوانید مدیران،صاحبان گروه، و ادمین های ربات رو از گروه محروم کنید*", 0, "md") end end if administration[tostring(arg.chat_id)]['banned'][tostring(data.id_)] then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already_ *banned*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* * از گروه محروم بود*", 0, "md") end end administration[tostring(arg.chat_id)]['banned'][tostring(data.id_)] = user_name save_data(_config.moderation.data, administration) kick_user(data.id_, arg.chat_id) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been_ *banned*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از گروه محروم شد*", 0, "md") end end tdcli_function ({ ID = "GetUser", user_id_ = data.sender_user_id_ }, ban_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_}) end if cmd == "unban" then local function unban_cb(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) local administration = load_data(_config.moderation.data) if data.username_ then user_name = '@'..check_markdown(data.username_) else user_name = check_markdown(data.first_name_) end if not administration[tostring(arg.chat_id)]['banned'][tostring(data.id_)] then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not_ *banned*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از گروه محروم نبود*", 0, "md") end end administration[tostring(arg.chat_id)]['banned'][tostring(data.id_)] = nil save_data(_config.moderation.data, administration) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been_ *unbanned*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از محرومیت گروه خارج شد*", 0, "md") end end tdcli_function ({ ID = "GetUser", user_id_ = data.sender_user_id_ }, unban_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_}) end if cmd == "silent" then local function silent_cb(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) local administration = load_data(_config.moderation.data) if data.username_ then user_name = '@'..check_markdown(data.username_) else user_name = check_markdown(data.first_name_) end if is_mod1(arg.chat_id, data.id_) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_You can't silent_ *mods,owners and bot admins*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "*شما نمیتوانید توانایی چت کردن رو از مدیران،صاحبان گروه، و ادمین های ربات بگیرید*", 0, "md") end end if administration[tostring(arg.chat_id)]['is_silent_users'][tostring(data.id_)] then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already_ *silent*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل توانایی چت کردن رو نداشت*", 0, "md") end end administration[tostring(arg.chat_id)]['is_silent_users'][tostring(data.id_)] = user_name save_data(_config.moderation.data, administration) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _added to_ *silent users list*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *توانایی چت کردن رو از دست داد*", 0, "md") end end tdcli_function ({ ID = "GetUser", user_id_ = data.sender_user_id_ }, silent_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_}) end if cmd == "unsilent" then local function unsilent_cb(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) local administration = load_data(_config.moderation.data) if data.username_ then user_name = '@'..check_markdown(data.username_) else user_name = check_markdown(data.first_name_) end if not administration[tostring(arg.chat_id)]['is_silent_users'][tostring(data.id_)] then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not_ *silent*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل توانایی چت کردن را داشت*", 0, "md") end end administration[tostring(arg.chat_id)]['is_silent_users'][tostring(data.id_)] = nil save_data(_config.moderation.data, administration) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _removed from_ *silent users list*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *توانایی چت کردن رو به دست آورد*", 0, "md") end end tdcli_function ({ ID = "GetUser", user_id_ = data.sender_user_id_ }, unsilent_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_}) end if cmd == "banall" then local function gban_cb(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) local administration = load_data(_config.moderation.data) if data.username_ then user_name = '@'..check_markdown(data.username_) else user_name = check_markdown(data.first_name_) end if not administration['gban_users'] then administration['gban_users'] = {} save_data(_config.moderation.data, administration) end if is_admin1(data.id_) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_You can't_ *globally ban* _other admins_", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "*شما نمیتوانید ادمین های ربات رو از تمامی گروه های ربات محروم کنید*", 0, "md") end end if is_gbanned(data.id_) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already_ *globally banned*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از گروه های ربات محروم بود*", 0, "md") end end administration['gban_users'][tostring(data.id_)] = user_name save_data(_config.moderation.data, administration) kick_user(data.id_, arg.chat_id) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been_ *globally banned*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از تمام گروه های ربات محروم شد*", 0, "md") end end tdcli_function ({ ID = "GetUser", user_id_ = data.sender_user_id_ }, gban_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_}) end if cmd == "unbanall" then local function ungban_cb(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) local administration = load_data(_config.moderation.data) if data.username_ then user_name = '@'..check_markdown(data.username_) else user_name = check_markdown(data.first_name_) end if not administration['gban_users'] then administration['gban_users'] = {} save_data(_config.moderation.data, administration) end if not is_gbanned(data.id_) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not_ *globally banned*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از گروه های ربات محروم نبود*", 0, "md") end end administration['gban_users'][tostring(data.id_)] = nil save_data(_config.moderation.data, administration) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been_ *globally unbanned*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از محرومیت گروه های ربات خارج شد*", 0, "md") end end tdcli_function ({ ID = "GetUser", user_id_ = data.sender_user_id_ }, ungban_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_}) end if cmd == "kick" then if is_mod1(data.chat_id_, data.sender_user_id_) then if not lang then return tdcli.sendMessage(data.chat_id_, "", 0, "_You can't kick_ *mods,owners and bot admins*", 0, "md") elseif lang then return tdcli.sendMessage(data.chat_id_, "", 0, "*شما نمیتوانید مدیران،صاحبان گروه و ادمین های ربات رو اخراج کنید*", 0, "md") end else kick_user(data.sender_user_id_, data.chat_id_) end end if cmd == "delall" then if is_mod1(data.chat_id_, data.sender_user_id_) then if not lang then return tdcli.sendMessage(data.chat_id_, "", 0, "_You can't delete messages_ *mods,owners and bot admins*", 0, "md") elseif lang then return tdcli.sendMessage(data.chat_id_, "", 0, "*شما نمیتوانید پیام های مدیران،صاحبان گروه و ادمین های ربات رو پاک کنید*", 0, "md") end else tdcli.deleteMessagesFromUser(data.chat_id_, data.sender_user_id_, dl_cb, nil) if not lang then return tdcli.sendMessage(data.chat_id_, "", 0, "_All_ *messages* _of_ *[ "..data.sender_user_id_.." ]* _has been_ *deleted*", 0, "md") elseif lang then return tdcli.sendMessage(data.chat_id_, "", 0, "*تمام پیام های* *[ "..data.sender_user_id_.." ]* *پاک شد*", 0, "md") end end end else if lang then return tdcli.sendMessage(data.chat_id_, "", 0, "_کاربر یافت نشد_", 0, "md") else return tdcli.sendMessage(data.chat_id_, "", 0, "*User Not Found*", 0, "md") end end end local function action_by_username(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) local cmd = arg.cmd local administration = load_data(_config.moderation.data) if not arg.username then return false end if data.id_ then if data.type_.user_.username_ then user_name = '@'..check_markdown(data.type_.user_.username_) else user_name = check_markdown(data.title_) end if cmd == "ban" then if is_mod1(arg.chat_id, data.id_) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_You can't ban_ *mods,owners and bot admins*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "*شما نمیتوانید مدیران،صاحبان گروه، و ادمین های ربات رو از گروه محروم کنید*", 0, "md") end end if administration[tostring(arg.chat_id)]['banned'][tostring(data.id_)] then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already_ *banned*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* * از گروه محروم بود*", 0, "md") end end administration[tostring(arg.chat_id)]['banned'][tostring(data.id_)] = user_name save_data(_config.moderation.data, administration) kick_user(data.id_, arg.chat_id) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been_ *banned*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از گروه محروم شد*", 0, "md") end end if cmd == "unban" then if not administration[tostring(arg.chat_id)]['banned'][tostring(data.id_)] then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not_ *banned*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از گروه محروم نبود*", 0, "md") end end administration[tostring(arg.chat_id)]['banned'][tostring(data.id_)] = nil save_data(_config.moderation.data, administration) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been_ *unbanned*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از محرومیت گروه خارج شد*", 0, "md") end end if cmd == "silent" then if is_mod1(arg.chat_id, data.id_) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_You can't silent_ *mods,owners and bot admins*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "*شما نمیتوانید توانایی چت کردن رو از مدیران،صاحبان گروه، و ادمین های ربات بگیرید*", 0, "md") end end if administration[tostring(arg.chat_id)]['is_silent_users'][tostring(data.id_)] then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already_ *silent*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل توانایی چت کردن رو نداشت*", 0, "md") end end administration[tostring(arg.chat_id)]['is_silent_users'][tostring(data.id_)] = user_name save_data(_config.moderation.data, administration) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _added to_ *silent users list*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *توانایی چت کردن رو از دست داد*", 0, "md") end end if cmd == "unsilent" then if not administration[tostring(arg.chat_id)]['is_silent_users'][tostring(data.id_)] then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not_ *silent*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل توانایی چت کردن را داشت*", 0, "md") end end administration[tostring(arg.chat_id)]['is_silent_users'][tostring(data.id_)] = nil save_data(_config.moderation.data, administration) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _removed from_ *silent users list*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *توانایی چت کردن رو به دست آورد*", 0, "md") end end if cmd == "banall" then if not administration['gban_users'] then administration['gban_users'] = {} save_data(_config.moderation.data, administration) end if is_admin1(data.id_) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_You can't_ *globally ban* _other admins_", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "*شما نمیتوانید ادمین های ربات رو از تمامی گروه های ربات محروم کنید*", 0, "md") end end if is_gbanned(data.id_) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already_ *globally banned*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از گروه های ربات محروم بود*", 0, "md") end end administration['gban_users'][tostring(data.id_)] = user_name save_data(_config.moderation.data, administration) kick_user(data.id_, arg.chat_id) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been_ *globally banned*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از تمام گروه های ربات محروم شد*", 0, "md") end end if cmd == "unbanall" then if not administration['gban_users'] then administration['gban_users'] = {} save_data(_config.moderation.data, administration) end if not is_gbanned(data.id_) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not_ *globally banned*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از گروه های ربات محروم نبود*", 0, "md") end end administration['gban_users'][tostring(data.id_)] = nil save_data(_config.moderation.data, administration) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been_ *globally unbanned*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از محرومیت گروه های ربات خارج شد*", 0, "md") end end if cmd == "kick" then if is_mod1(arg.chat_id, data.id_) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_You can't kick_ *mods,owners and bot admins*", 0, "md") elseif lang then return tdcli.sendMessage(arg.chat_id, "", 0, "*شما نمیتوانید مدیران،صاحبان گروه و ادمین های ربات رو اخراج کنید*", 0, "md") end else kick_user(data.id_, arg.chat_id) end end if cmd == "delall" then if is_mod1(arg.chat_id, data.id_) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_You can't delete messages_ *mods,owners and bot admins*", 0, "md") elseif lang then return tdcli.sendMessage(arg.chat_id, "", 0, "*شما نمیتوانید پیام های مدیران،صاحبان گروه و ادمین های ربات رو پاک کنید*", 0, "md") end else tdcli.deleteMessagesFromUser(arg.chat_id, data.id_, dl_cb, nil) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_All_ *messages* _of_ "..user_name.." *[ "..data.id_.." ]* _has been_ *deleted*", 0, "md") elseif lang then return tdcli.sendMessage(arg.chat_id, "", 0, "*تمام پیام های* "..user_name.." *[ "..data.id_.." ]* *پاک شد*", 0, "md") end end end else if lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر یافت نشد_", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "*User Not Found*", 0, "md") end end end local function run(msg, matches) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) local data = load_data(_config.moderation.data) chat = msg.to.id user = msg.from.id if msg.to.type ~= 'pv' then if matches[1] == "kick" and is_mod(msg) then if not matches[2] and msg.reply_id then tdcli_function ({ ID = "GetMessage", chat_id_ = msg.to.id, message_id_ = msg.reply_id }, action_by_reply, {chat_id=msg.to.id,cmd="kick"}) end if matches[2] and string.match(matches[2], '^%d+$') then if is_mod1(msg.to.id, matches[2]) then if not lang then tdcli.sendMessage(msg.to.id, "", 0, "_You can't kick mods,owners or bot admins_", 0, "md") elseif lang then tdcli.sendMessage(msg.to.id, "", 0, "*شما نمیتوانید مدیران،صاحبان گروه و ادمین های ربات رو اخراج کنید*", 0, "md") end else kick_user(matches[2], msg.to.id) end end if matches[2] and not string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "SearchPublicChat", username_ = matches[2] }, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="kick"}) end end if matches[1] == "delall" and is_mod(msg) then if not matches[2] and msg.reply_id then tdcli_function ({ ID = "GetMessage", chat_id_ = msg.to.id, message_id_ = msg.reply_id }, action_by_reply, {chat_id=msg.to.id,cmd="delall"}) end if matches[2] and string.match(matches[2], '^%d+$') then if is_mod1(msg.to.id, matches[2]) then if not lang then return tdcli.sendMessage(msg.to.id, "", 0, "_You can't delete messages mods,owners or bot admins_", 0, "md") elseif lang then return tdcli.sendMessage(msg.to.id, "", 0, "*شما نمیتوانید پیام های مدیران،صاحبان گروه و ادمین های ربات رو پاک کنید*", 0, "md") end else tdcli.deleteMessagesFromUser(msg.to.id, matches[2], dl_cb, nil) if not lang then return tdcli.sendMessage(msg.to.id, "", 0, "_All_ *messages* _of_ *[ "..matches[2].." ]* _has been_ *deleted*", 0, "md") elseif lang then return tdcli.sendMessage(msg.to.id, "", 0, "*تمامی پیام های* *[ "..matches[2].." ]* *پاک شد*", 0, "md") end end end if matches[2] and not string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "SearchPublicChat", username_ = matches[2] }, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="delall"}) end end end if matches[1] == "banall" and is_admin(msg) then if not matches[2] and msg.reply_id then tdcli_function ({ ID = "GetMessage", chat_id_ = msg.to.id, message_id_ = msg.reply_id }, action_by_reply, {chat_id=msg.to.id,cmd="banall"}) end if matches[2] and string.match(matches[2], '^%d+$') then if is_admin1(matches[2]) then if not lang then return tdcli.sendMessage(msg.to.id, "", 0, "_You can't globally ban other admins_", 0, "md") else return tdcli.sendMessage(msg.to.id, "", 0, "*شما نمیتوانید ادمین های ربات رو از گروه های ربات محروم کنید*", 0, "md") end end if is_gbanned(matches[2]) then if not lang then return tdcli.sendMessage(msg.to.id, "", 0, "*User "..matches[2].." is already globally banned*", 0, "md") else return tdcli.sendMessage(msg.to.id, "", 0, "*کاربر "..matches[2].." از گروه های ربات محروم بود*", 0, "md") end end data['gban_users'][tostring(matches[2])] = "" save_data(_config.moderation.data, data) kick_user(matches[2], msg.to.id) if not lang then return tdcli.sendMessage(msg.to.id, msg.id, 0, "*User "..matches[2].." has been globally banned*", 0, "md") else return tdcli.sendMessage(msg.to.id, msg.id, 0, "*کاربر "..matches[2].." از تمام گروه هار ربات محروم شد*", 0, "md") end end if matches[2] and not string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "SearchPublicChat", username_ = matches[2] }, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="banall"}) end end if matches[1] == "unbanall" and is_admin(msg) then if not matches[2] and msg.reply_id then tdcli_function ({ ID = "GetMessage", chat_id_ = msg.to.id, message_id_ = msg.reply_id }, action_by_reply, {chat_id=msg.to.id,cmd="unbanall"}) end if matches[2] and string.match(matches[2], '^%d+$') then if not is_gbanned(matches[2]) then if not lang then return tdcli.sendMessage(msg.to.id, "", 0, "*User "..matches[2].." is not globally banned*", 0, "md") else return tdcli.sendMessage(msg.to.id, "", 0, "*کاربر "..matches[2].." از گروه های ربات محروم نبود*", 0, "md") end end data['gban_users'][tostring(matches[2])] = nil save_data(_config.moderation.data, data) if not lang then return tdcli.sendMessage(msg.to.id, msg.id, 0, "*User "..matches[2].." has been globally unbanned*", 0, "md") else return tdcli.sendMessage(msg.to.id, msg.id, 0, "*کاربر "..matches[2].." از محرومیت گروه های ربات خارج شد*", 0, "md") end end if matches[2] and not string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "SearchPublicChat", username_ = matches[2] }, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="unbanall"}) end end if msg.to.type ~= 'pv' then if matches[1] == "ban" and is_mod(msg) then if not matches[2] and msg.reply_id then tdcli_function ({ ID = "GetMessage", chat_id_ = msg.to.id, message_id_ = msg.reply_id }, action_by_reply, {chat_id=msg.to.id,cmd="ban"}) end if matches[2] and string.match(matches[2], '^%d+$') then if is_mod1(msg.to.id, matches[2]) then if not lang then return tdcli.sendMessage(msg.to.id, "", 0, "_You can't ban mods,owners or bot admins_", 0, "md") else return tdcli.sendMessage(msg.to.id, "", 0, "*شما نمیتوانید مدیران،صاحبان گروه و ادمین های ربات رو از گروه محروم کنید*", 0, "md") end end if is_banned(matches[2], msg.to.id) then if not lang then return tdcli.sendMessage(msg.to.id, "", 0, "_User "..matches[2].." is already banned_", 0, "md") else return tdcli.sendMessage(msg.to.id, "", 0, "*کاربر "..matches[2].." از گروه محروم بود*", 0, "md") end end data[tostring(chat)]['banned'][tostring(matches[2])] = "" save_data(_config.moderation.data, data) kick_user(matches[2], msg.to.id) if not lang then return tdcli.sendMessage(msg.to.id, msg.id, 0, "_User "..matches[2].." has been banned_", 0, "md") else return tdcli.sendMessage(msg.to.id, msg.id, 0, "*کاربر "..matches[2].." از گروه محروم شد*", 0, "md") end end if matches[2] and not string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "SearchPublicChat", username_ = matches[2] }, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="ban"}) end end if matches[1] == "unban" and is_mod(msg) then if not matches[2] and msg.reply_id then tdcli_function ({ ID = "GetMessage", chat_id_ = msg.to.id, message_id_ = msg.reply_id }, action_by_reply, {chat_id=msg.to.id,cmd="unban"}) end if matches[2] and string.match(matches[2], '^%d+$') then if not is_banned(matches[2], msg.to.id) then if not lang then return tdcli.sendMessage(msg.to.id, "", 0, "_User "..matches[2].." is not banned_", 0, "md") else return tdcli.sendMessage(msg.to.id, "", 0, "*کاربر "..matches[2].." از گروه محروم نبود*", 0, "md") end end data[tostring(chat)]['banned'][tostring(matches[2])] = nil save_data(_config.moderation.data, data) if not lang then return tdcli.sendMessage(msg.to.id, msg.id, 0, "_User "..matches[2].." has been unbanned_", 0, "md") else return tdcli.sendMessage(msg.to.id, msg.id, 0, "*کاربر "..matches[2].." از محرومیت گروه خارج شد*", 0, "md") end end if matches[2] and not string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "SearchPublicChat", username_ = matches[2] }, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="unban"}) end end if matches[1] == "silent" and is_mod(msg) then if not matches[2] and msg.reply_id then tdcli_function ({ ID = "GetMessage", chat_id_ = msg.to.id, message_id_ = msg.reply_id }, action_by_reply, {chat_id=msg.to.id,cmd="silent"}) end if matches[2] and string.match(matches[2], '^%d+$') then if is_mod1(msg.to.id, matches[2]) then if not lang then return tdcli.sendMessage(msg.to.id, "", 0, "_You can't silent mods,leaders or bot admins_", 0, "md") else return tdcli.sendMessage(msg.to.id, "", 0, "*شما نمیتوانید توانایی چت کردن رو از مدیران،صاحبان گروه و ادمین های ربات بگیرید*", 0, "md") end end if is_silent_user(matches[2], chat) then if not lang then return tdcli.sendMessage(msg.to.id, "", 0, "_User "..matches[2].." is already silent_", 0, "md") else return tdcli.sendMessage(msg.to.id, "", 0, "*کاربر "..matches[2].." از قبل توانایی چت کردن رو نداشت*", 0, "md") end end data[tostring(chat)]['is_silent_users'][tostring(matches[2])] = "" save_data(_config.moderation.data, data) if not lang then return tdcli.sendMessage(msg.to.id, msg.id, 0, "_User "..matches[2].." added to silent users list_", 0, "md") else return tdcli.sendMessage(msg.to.id, msg.id, 0, "*کاربر "..matches[2].." توانایی چت کردن رو از دست داد*", 0, "md") end end if matches[2] and not string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "SearchPublicChat", username_ = matches[2] }, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="silent"}) end end if matches[1] == "unsilent" and is_mod(msg) then if not matches[2] and msg.reply_id then tdcli_function ({ ID = "GetMessage", chat_id_ = msg.to.id, message_id_ = msg.reply_id }, action_by_reply, {chat_id=msg.to.id,cmd="unsilent"}) end if matches[2] and string.match(matches[2], '^%d+$') then if not is_silent_user(matches[2], chat) then if not lang then return tdcli.sendMessage(msg.to.id, "", 0, "_User "..matches[2].." is not silent_", 0, "md") else return tdcli.sendMessage(msg.to.id, "", 0, "*کاربر "..matches[2].." از قبل توانایی چت کردن رو داشت*", 0, "md") end end data[tostring(chat)]['is_silent_users'][tostring(matches[2])] = nil save_data(_config.moderation.data, data) if not lang then return tdcli.sendMessage(msg.to.id, msg.id, 0, "_User "..matches[2].." removed from silent users list_", 0, "md") else return tdcli.sendMessage(msg.to.id, msg.id, 0, "*کاربر "..matches[2].." توانایی چت کردن رو به دست آورد*", 0, "md") end end if matches[2] and not string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "SearchPublicChat", username_ = matches[2] }, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="unsilent"}) end end if matches[1]:lower() == 'clean' and is_owner(msg) then if matches[2] == 'bans' then if next(data[tostring(chat)]['banned']) == nil then if not lang then return "_No_ *banned* _users in this group_" else return "*هیچ کاربری از این گروه محروم نشده*" end end for k,v in pairs(data[tostring(chat)]['banned']) do data[tostring(chat)]['banned'][tostring(k)] = nil save_data(_config.moderation.data, data) end if not lang then return "_All_ *banned* _users has been unbanned_" else return "*تمام کاربران محروم شده از گروه از محرومیت خارج شدند*" end end if matches[2] == 'silentlist' then if next(data[tostring(chat)]['is_silent_users']) == nil then if not lang then return "_No_ *silent* _users in this group_" else return "*لیست کاربران سایلنت شده خالی است*" end end for k,v in pairs(data[tostring(chat)]['is_silent_users']) do data[tostring(chat)]['is_silent_users'][tostring(k)] = nil save_data(_config.moderation.data, data) end if not lang then return "*Silent list* _has been cleaned_" else return "*لیست کاربران سایلنت شده پاک شد*" end end end end if matches[1]:lower() == 'clean' and is_sudo(msg) then if matches[2] == 'gbans' then if next(data['gban_users']) == nil then if not lang then return "_No_ *globally banned* _users available_" else return "*هیچ کاربری از گروه های ربات محروم نشده*" end end for k,v in pairs(data['gban_users']) do data['gban_users'][tostring(k)] = nil save_data(_config.moderation.data, data) end if not lang then return "_All_ *globally banned* _users has been unbanned_" else return "*تمام کاربرانی که از گروه های ربات محروم بودند از محرومیت خارج شدند*" end end end if matches[1] == "gbanlist" and is_admin(msg) then return gbanned_list(msg) end if msg.to.type ~= 'pv' then if matches[1] == "silentlist" and is_mod(msg) then return silent_users_list(chat) end if matches[1] == "banlist" and is_mod(msg) then return banned_list(chat) end end end return { patterns = { "^[!/#](banall)$", "^[!/#](banall) (.*)$", "^[!/#](unbanall)$", "^[!/#](unbanall) (.*)$", "^[!/#](gbanlist)$", "^[!/#](ban)$", "^[!/#](ban) (.*)$", "^[!/#](unban)$", "^[!/#](unban) (.*)$", "^[!/#](banlist)$", "^[!/#](silent)$", "^[!/#](silent) (.*)$", "^[!/#](unsilent)$", "^[!/#](unsilent) (.*)$", "^[!/#](silentlist)$", "^[!/#](kick)$", "^[!/#](kick) (.*)$", "^[!/#](delall)$", "^[!/#](delall) (.*)$", "^[!/#](clean) (.*)$", }, run = run, pre_process = pre_process }
gpl-3.0
thedraked/darkstar
scripts/zones/Apollyon/mobs/Barometz.lua
17
1394
----------------------------------- -- Area: Apollyon NE -- NPC: Barometz ----------------------------------- package.loaded["scripts/zones/Apollyon/TextIDs"] = nil; ----------------------------------- require("scripts/globals/limbus"); require("scripts/zones/Apollyon/TextIDs"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, player, isKiller) end; ----------------------------------- -- onMobDespawn ----------------------------------- function onMobDespawn(mob) local mobID = mob:getID(); -- print(mobID); local mobX = mob:getXPos(); local mobY = mob:getYPos(); local mobZ = mob:getZPos(); if (mobID ==16933045) then -- time T2 GetNPCByID(16932864+81):setPos(459,-1,29); GetNPCByID(16932864+81):setStatus(STATUS_NORMAL); elseif (mobID ==16933049) then -- time T3 GetNPCByID(16932864+82):setPos(480,-1,-39); GetNPCByID(16932864+82):setStatus(STATUS_NORMAL); elseif (mobID ==16933055) then -- item GetNPCByID(16932864+119):setPos(mobX,mobY,mobZ); GetNPCByID(16932864+119):setStatus(STATUS_NORMAL); end end;
gpl-3.0
z3t0/zwm
utilities.lua
1
3518
-- utilities function log(err) -- TODO: log file error(err) end -- return the number of items in a table function table_count(t) local count = 0 for _ in pairs(t) do count = count + 1 end return count end -- recursively prints table function print_r ( t ) local print_r_cache={} local function sub_print_r(t,indent) if (print_r_cache[tostring(t)]) then print(indent.."*"..tostring(t)) else print_r_cache[tostring(t)]=true if (type(t)=="table") then for pos,val in pairs(t) do if (type(val)=="table") then print(indent.."["..pos.."] => "..tostring(t).." {") sub_print_r(val,indent..string.rep(" ",string.len(pos)+8)) print(indent..string.rep(" ",string.len(pos)+6).."}") elseif (type(val)=="string") then print(indent.."["..pos..'] => "'..val..'"') else print(indent.."["..pos.."] => "..tostring(val)) end end else print(indent..tostring(t)) end end end if (type(t)=="table") then print(tostring(t).." {") sub_print_r(t," ") print("}") else sub_print_r(t," ") end print() end -- prints an error to the console -- TODO: proper error handling function error(msg) print("error: \n" .. msg) end -- Alert in center of the screen function alert_simple(msg) hs.alert(msg) end -- Alert from notifications center function alert(msg, title) if title == nil then title = "zwm" end if config["silent"] then print(msg) else hs.notify.new({title="zwm", informativeText=msg}):send() end end -- if string matches options from table function string_match(str, table) for k, v in pairs(table) do if string.match(str, v) then return true end end return false end -- if item matches a key in the table, return that pair function match_item(item, table) for k, v in pairs(table) do if string.match(item, k) then return {i = k, f = v} end end return nil end function exact_in_table(item, table) for k, v in pairs(table) do if item == k then return {i = k, f = v} end end return nil end -- hex to rgb function hex_to_rgb(hex) local hex = hex:gsub("#","") local rgb = {r =tonumber("0x"..hex:sub(1,2))/255, g = tonumber("0x"..hex:sub(3,4))/255, b = tonumber("0x"..hex:sub(5,6))/255} return rgb end -- converts text to ansi color function ansi_color(c) if c == "black" then return 30 elseif c == "red" then return 31 elseif c == "green" then return 32 elseif c == "yellow" then return 33 elseif c == "blue" then return 34 elseif c == "purple" then return 35 elseif c == "cyan" then return 36 elseif c == "white" then return 37 end end function deepcopy(orig) local orig_type = type(orig) local copy if orig_type == 'table' then copy = {} for orig_key, orig_value in next, orig, nil do copy[deepcopy(orig_key)] = deepcopy(orig_value) end setmetatable(copy, deepcopy(getmetatable(orig))) else -- number, string, boolean, etc copy = orig end return copy end
mit
mtroyka/Zero-K
effects/heatray.lua
17
2758
-- heatray_ceg -- heatray_hit return { ["heatray_hit"] = { usedefaultexplosions = false, cinder = { air = true, class = [[heatcloud]], count = 1, ground = true, water = true, properties = { alwaysvisible = false, heat = [[d1 5]], heatfalloff = 1, maxheat = 15, pos = 0, size = [[5]], sizegrowth = -0.05, speed = [[0, 0, 0]], texture = [[redexplo]], }, }, airflash = { air = true, class = [[heatcloud]], count = 1, ground = true, water = true, properties = { alwaysvisible = false, heat = [[d1 5]], heatfalloff = 2, maxheat = 15, pos = 0, size = [[3]], sizegrowth = 1, speed = [[0, 0, 0]], texture = [[redexplo]], }, }, groundflash = { circlealpha = 1, circlegrowth = 0.125, flashalpha = 0.5, flashsize = 8, ttl = 64, color = { [1] = 1, [2] = 0.25, [3] = 0, }, }, sparks = { class = [[CSimpleParticleSystem]], count = 1, ground = true, unit = 1, properties = { airdrag = 0.999, alwaysvisible = false, colormap = [[1 0.75 0.25 0.01 0.01 0.01 0.005 0.01]], directional = true, emitrot = 180, emitrotspread = 80, emitvector = [[dir]], gravity = [[0, -1, 0]], numparticles = [[d1 5]], particlelife = [[d5 10]], particlelifespread = 2, particlesize = [[d0.1 0.5]], particlesizespread = 0.5, particlespeed = [[0.5 d0.1]], particlespeedspread = 2, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 0.9, texture = [[plasma]], }, }, steam = { class = [[CExpGenSpawner]], count = 2, nounit = 1, properties = { delay = [[i1]], dir = [[dir]], explosiongenerator = [[custom:BEAMWEAPON_HIT_YELLOW_STEAM]], pos = [[0, 0, 0]], }, }, }, }
gpl-2.0
thedraked/darkstar
scripts/zones/The_Garden_of_RuHmet/bcnms/when_angels_fall.lua
30
2268
----------------------------------- -- Area: The_Garden_of_RuHmet -- Name: when_angels_fall ----------------------------------- package.loaded["scripts/zones/The_Garden_of_RuHmet/TextIDs"] = nil; ----------------------------------- require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/globals/missions"); require("scripts/zones/The_Garden_of_RuHmet/TextIDs"); ----------------------------------- -- EXAMPLE SCRIPT -- -- What should go here: -- giving key items, playing ENDING cutscenes -- -- What should NOT go here: -- Handling of "battlefield" status, spawning of monsters, -- putting loot into treasure pool, -- enforcing ANY rules (SJ/number of people/etc), moving -- chars around, playing entrance CSes (entrance CSes go in bcnm.lua) -- After registering the BCNM via bcnmRegister(bcnmid) function onBcnmRegister(player,instance) end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBcnmEnter(player,instance) end; -- Leaving the BCNM by every mean possible, given by the LeaveCode -- 1=Select Exit on circle -- 2=Winning the BC -- 3=Disconnected or warped out -- 4=Losing the BC -- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called -- from the core when a player disconnects or the time limit is up, etc function onBcnmLeave(player,instance,leavecode) if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage if (player:getCurrentMission(COP) == WHEN_ANGELS_FALL and player:getVar("PromathiaStatus")==4) then player:startEvent(0x7d01,0,0,0,instance:getTimeInside(),0,0,0); player:setVar("PromathiaStatus",5); else player:startEvent(0x7d01,0,0,0,instance:getTimeInside(),0,0,1); -- end elseif (leavecode == 4) then player:startEvent(0x7d02); end --printf("leavecode: %u",leavecode); end; function onEventUpdate(player,csid,option) -- print("bc update csid "..csid.." and option "..option); end; function onEventFinish(player,csid,option) -- print("bc finish csid "..csid.." and option "..option); if (csid== 0x7d01) then player:setPos(420,0,445,192); end end;
gpl-3.0
thedraked/darkstar
scripts/zones/Dynamis-Xarcabard/mobs/Animated_Spear.lua
17
1486
----------------------------------- -- Area: Dynamis Xarcabard -- MOB: Animated Spear ----------------------------------- require("scripts/globals/status"); require("scripts/zones/Dynamis-Xarcabard/TextIDs"); ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) if (mob:AnimationSub() == 3) then SetDropRate(114,1578,1000); else SetDropRate(114,1578,0); end target:showText(mob,ANIMATED_SPEAR_DIALOG); SpawnMob(17330423):updateEnmity(target); SpawnMob(17330424):updateEnmity(target); SpawnMob(17330425):updateEnmity(target); SpawnMob(17330435):updateEnmity(target); SpawnMob(17330436):updateEnmity(target); SpawnMob(17330437):updateEnmity(target); end; ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob,target) -- TODO: add battle dialog end; ----------------------------------- -- onMobDisengage ----------------------------------- function onMobDisengage(mob) mob:showText(mob,ANIMATED_SPEAR_DIALOG+2); end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, player, isKiller) player:showText(mob,ANIMATED_SPEAR_DIALOG+1); DespawnMob(17330423); DespawnMob(17330424); DespawnMob(17330425); DespawnMob(17330435); DespawnMob(17330436); DespawnMob(17330437); end;
gpl-3.0
mtroyka/Zero-K
units/armcybr.lua
2
4675
unitDef = { unitname = [[armcybr]], name = [[Wyvern]], description = [[Singularity Bomber]], --autoheal = 25, brakerate = 0.4, buildCostEnergy = 2000, buildCostMetal = 2000, builder = false, buildPic = [[ARMCYBR.png]], buildTime = 2000, canAttack = true, canFly = true, canGuard = true, canMove = true, canPatrol = true, canSubmerge = false, category = [[FIXEDWING]], collide = false, collisionVolumeOffsets = [[-2 0 0]], collisionVolumeScales = [[32 12 40]], collisionVolumeType = [[box]], corpse = [[DEAD]], crashDrag = 0.02, cruiseAlt = 250, customParams = { helptext = [[The Wyvern drops a single powerful bomb that can send units flying. It is sturdy enough to penetrate moderate AA and escape to repair, but should not be used recklessly - it's too expensive for that.]], description_de = [[Implosion Bomber]], description_fr = [[Bombardier r Implosion]], helptext_de = [[Wyvern ist ein mächtiger Bomber, der alles in Schutt und Asche legt. Seine Schlagkraft und Ausdauer ist riesig, doch muss er nach jedem Angriff Munition nachladen, was ihn eher für Angriffe auf einzelne Ziele prädestiniert.]], helptext_fr = [[Le Wyvern est tout simplement la mort venue du ciel. Ce bombardier lourdement blindé et relativement lent transporte une tete nucléaire tactique r implosion. Capable de faire des ravages dans les lignes ennemies, ou de détruire des structures lourdement blindées. Tout simplement mortel utilisé en petites escadres.]], modelradius = [[10]], }, explodeAs = [[GUNSHIPEX]], floater = true, footprintX = 3, footprintZ = 3, iconType = [[bombernuke]], idleAutoHeal = 5, idleTime = 1800, maneuverleashlength = [[1280]], maxAcc = 0.75, maxDamage = 2360, maxFuel = 1000000, maxVelocity = 9, minCloakDistance = 75, mygravity = 1, noAutoFire = false, noChaseCategory = [[TERRAFORM FIXEDWING SATELLITE GUNSHIP SUB]], objectName = [[ARMCYBR]], refuelTime = 20, script = [[armcybr.lua]], seismicSignature = 0, selfDestructAs = [[GUNSHIPEX]], sightDistance = 660, turnRadius = 20, workerTime = 0, weapons = { { def = [[ARM_PIDR]], badTargetCategory = [[GUNSHIP FIXEDWING]], onlyTargetCategory = [[SWIM LAND SINK TURRET FLOAT SHIP HOVER GUNSHIP FIXEDWING]], }, }, weaponDefs = { ARM_PIDR = { name = [[Implosion Bomb]], areaOfEffect = 192, avoidFeature = false, avoidFriendly = false, burnblow = true, cegTag = [[raventrail]], collideFriendly = false, craterBoost = 1, craterMult = 2, customParams = { light_color = [[1.6 0.85 0.38]], light_radius = 750, }, damage = { default = 2000.1, planes = 2000.1, subs = 100, }, edgeEffectiveness = 0.5, explosionGenerator = [[custom:NUKE_150]], fireStarter = 100, flightTime = 3, impulseBoost = 0, impulseFactor = -0.8, interceptedByShieldType = 2, model = [[wep_m_deathblow.s3o]], range = 500, reloadtime = 8, smokeTrail = false, soundHit = [[weapon/missile/liche_hit]], soundStart = [[weapon/missile/liche_fire]], startVelocity = 300, tolerance = 16000, tracks = true, turnRate = 30000, weaponAcceleration = 200, weaponType = [[MissileLauncher]], weaponVelocity = 400, }, }, featureDefs = { DEAD = { blocking = true, featureDead = [[HEAP]], footprintX = 2, footprintZ = 2, object = [[licho_d.s3o]], }, HEAP = { blocking = false, footprintX = 2, footprintZ = 2, object = [[debris3x3b.s3o]], }, }, } return lowerkeys({ armcybr = unitDef })
gpl-2.0
thedraked/darkstar
scripts/zones/The_Eldieme_Necropolis/npcs/qm9.lua
57
2181
----------------------------------- -- Area: The Eldieme Necropolis -- NPC: qm9 (??? - Ancient Papyrus Shreds) -- Involved in Quest: In Defiant Challenge -- @pos 92.272 -32 -64.676 195 ----------------------------------- package.loaded["scripts/zones/The_Eldieme_Necropolis/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/keyitems"); require("scripts/globals/settings"); require("scripts/zones/The_Eldieme_Necropolis/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (OldSchoolG1 == false) then if (player:hasItem(1088) == false and player:hasKeyItem(ANCIENT_PAPYRUS_SHRED3) == false and player:getQuestStatus(JEUNO,IN_DEFIANT_CHALLENGE) == QUEST_ACCEPTED) then player:addKeyItem(ANCIENT_PAPYRUS_SHRED3); player:messageSpecial(KEYITEM_OBTAINED,ANCIENT_PAPYRUS_SHRED3); end if (player:hasKeyItem(ANCIENT_PAPYRUS_SHRED1) and player:hasKeyItem(ANCIENT_PAPYRUS_SHRED2) and player:hasKeyItem(ANCIENT_PAPYRUS_SHRED3)) then if (player:getFreeSlotsCount() >= 1) then player:addItem(1088, 1); player:messageSpecial(ITEM_OBTAINED, 1088); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, 1088); end end if (player:hasItem(1088)) then player:delKeyItem(ANCIENT_PAPYRUS_SHRED1); player:delKeyItem(ANCIENT_PAPYRUS_SHRED2); player:delKeyItem(ANCIENT_PAPYRUS_SHRED3); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID2: %u",csid); -- printf("RESULT2: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
thedraked/darkstar
scripts/zones/Gustav_Tunnel/MobIDs.lua
28
1592
----------------------------------- -- Area: Gustav Tunnel (212) -- Comments: -- posX, posY, posZ -- (Taken from 'mob_spawn_points' table) ----------------------------------- Goblinsavior_Heronox = 17645609; Goblinsavior_Heronox_PH = { [17645592] = '1', -- 153.000, -10.000, -53.000 [17645605] = '1', -- 152.325, -10.702, -77.007 [17645604] = '1', -- 165.558, -10.647, -68.537 }; -- Wyvernpoacher Drachlox Wyvernpoacher_Drachlox = 17645640; Wyvernpoacher_Drachlox_PH = { [17645633] = '1', -- -100.000, 1.000, -44.000 [17645634] = '1', -- -101.000, 1.000, -29.000 [17645644] = '1', -- -165.598, 0.218, -21.966 [17645643] = '1', -- -150.673, -0.067, -20.914 }; -- Baobhan Sith Baobhan_Sith = 17645719; Baobhan_Sith_PH = { [17645717] = '1', -- 171.000, 9.194, 55.000 [17645718] = '1', -- 187.000, 9.000, 105.000 }; -- Taxim Taxim = 17645742; Taxim_PH = { [17645731] = '1', -- -172.941, -1.220, 55.577 [17645738] = '1', -- -137.334, -0.108, 48.105 [17645744] = '1', -- -125.000, 0.635, 59.000 [17645739] = '1', -- -118.000, -0.515, 79.000 }; -- Ungur Ungur = 17645755; Ungur_PH = { [17645764] = '1', -- -242.000, -0.577, 120.000 [17645792] = '1', -- -88.000, 0.735, 190.000 [17645784] = '1', -- -123.856, 0.239, 223.303 [17645758] = '1', -- -277.000, -10.000, -34.000 [17645754] = '1', -- -316.000, -9.000, 3.000 }; -- Amikiri Amikiri = 17645774; Amikiri_PH = { [17645763] = '1', -- -245.000, -0.045, 146.000 [17645768] = '1', -- -228.872, -0.264, 144.689 [17645772] = '1', -- -209.552, -0.257, 161.728 };
gpl-3.0
thedraked/darkstar
scripts/zones/Port_Windurst/npcs/Sheia_Pohrichamaha.lua
17
1503
----------------------------------- -- Area: Port Windurst -- NPC: Sheia Pohrichamaha -- Only sells when Windurst controlls Fauregandi Region -- Confirmed shop stock, August 2013 ----------------------------------- require("scripts/globals/shop"); require("scripts/globals/conquest"); package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil; require("scripts/zones/Port_Windurst/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) RegionOwner = GetRegionOwner(FAUREGANDI); if (RegionOwner ~= NATION_WINDURST) then player:showText(npc,SHEIAPOHRICHAMAHA_CLOSED_DIALOG); else player:showText(npc,SHEIAPOHRICHAMAHA_OPEN_DIALOG); stock = { 0x11DB, 90, --Beaugreens 0x110B, 39, --Faerie Apple 0x02B3, 54 --Maple Log } showShop(player,WINDURST,stock); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
grafi-tt/luabind
examples/glut/glut_bindings.lua
38
1543
quit = false function resize_func(w, h) local ratio = w / h print('====== resize') glMatrixMode(gl.PROJECTION) glLoadIdentity() glViewport(0,0,w,h) gluPerspective(45,ratio,1,1000) glMatrixMode(gl.MODELVIEW) glLoadIdentity() end angle = 0 angle2 = 0 previous_time = 0 function display_func() if quit then return end local cur_time = glutGet(glut.ELAPSED_TIME) local delta = (cur_time - previous_time) / 1000 previous_time = cur_time glClear(gl.COLOR_BUFFER_BIT + gl.DEPTH_BUFFER_BIT) glPushMatrix() glTranslate(0,0,-5) glRotate(angle, 0, 1, 0) glRotate(angle2, 0, 0, 1) glColor3(1,0,0) -- glutWireSphere(0.75, 10, 10) glutSolidTeapot(0.75) -- glColor3(1,1,1) -- glutWireTeapot(0.75) glPopMatrix() angle = angle + 200 * delta angle2 = angle2 + 170 * delta frames = frames + 1 if math.mod(frames, 100) == 0 then local fps = frames * 1000 / (glutGet(glut.ELAPSED_TIME) - start_time); print('fps: ' .. fps .. ' time: ' .. glutGet(glut.ELAPSED_TIME) .. ' frames: ' .. frames) end glutSwapBuffers() end function keyboard_func(key,x,y) print('keyboard' .. key) if key == 27 then glutDestroyWindow(window) quit = true end end glutInitWindowSize(600,600) glutInitWindowPosition(0,0) glutInitDisplayMode(glut.RGB + glut.DOUBLE + glut.DEPTH) window = glutCreateWindow("luabind, glut-bindings") glutDisplayFunc(display_func) glutIdleFunc(display_func) glutKeyboardFunc(keyboard_func) glutReshapeFunc(resize_func) resize_func(600,600) start_time = glutGet(glut.ELAPSED_TIME) frames = 0 glutMainLoop()
mit
X-Coder/wire
lua/effects/thruster_ring_grow1.lua
10
1652
EFFECT.Mat = Material( "effects/select_ring" ) /*--------------------------------------------------------- Initializes the effect. The data is a table of data which was passed from the server. ---------------------------------------------------------*/ function EFFECT:Init( data ) local size = 16 self:SetCollisionBounds( Vector( -size,-size,-size ), Vector( size,size,size ) ) local Pos = data:GetOrigin() + data:GetNormal() * 2 self:SetPos( Pos ) self:SetAngles( data:GetNormal():Angle() + Angle( 0.01, 0.01, 0.01 ) ) self.Pos = data:GetOrigin() self.Normal = data:GetNormal() self.Speed = 2 self.Size = 16 self.Alpha = 255 end /*--------------------------------------------------------- THINK ---------------------------------------------------------*/ function EFFECT:Think( ) local speed = FrameTime() * self.Speed //if (self.Speed > 100) then self.Speed = self.Speed - 1000 * speed end //self.Size = self.Size + speed * self.Speed self.Size = self.Size + (255 - self.Alpha)*0.06 self.Alpha = self.Alpha - 250.0 * speed self:SetPos( self:GetPos() + self.Normal * speed * 128 ) if (self.Alpha < 0 ) then return false end if (self.Size < 0) then return false end return true end /*--------------------------------------------------------- Draw the effect ---------------------------------------------------------*/ function EFFECT:Render( ) if (self.Alpha < 1 ) then return end render.SetMaterial( self.Mat ) render.DrawQuadEasy( self:GetPos(), self:GetAngles():Forward(), self.Size, self.Size, Color( math.Rand( 10, 100), math.Rand( 100, 220), math.Rand( 240, 255), self.Alpha ) ) end
gpl-3.0
SnabbCo/snabbswitch
src/apps/pcap/tap.lua
7
2543
-- Use of this source code is governed by the Apache 2.0 license; see COPYING. module(...,package.seeall) local ffi = require("ffi") local app = require("core.app") local lib = require("core.lib") local link = require("core.link") local pcap = require("lib.pcap.pcap") local pf = require("pf") Tap = {} local tap_config_params = { -- Name of file to which to write packets. filename = { required=true }, -- "truncate" to truncate the file, or "append" to add to the file. mode = { default = "truncate" }, -- Only packets that match this pflang filter will be captured. filter = { }, -- Only write every Nth packet that matches the filter. sample = { default=1 }, } function Tap:new(conf) local o = lib.parse(conf, tap_config_params) local mode = assert(({truncate='w+b', append='a+b'})[o.mode]) o.file = assert(io.open(o.filename, mode)) if o.file:seek() == 0 then pcap.write_file_header(o.file) end if o.filter then o.filter = pf.compile_filter(o.filter) end o.n = o.sample - 1 return setmetatable(o, {__index = Tap}) end function Tap:push () local n = self.n while not link.empty(self.input.input) do local p = link.receive(self.input.input) if not self.filter or self.filter(p.data, p.length) then n = n + 1 if n == self.sample then n = 0 pcap.write_record(self.file, p.data, p.length) end end link.transmit(self.output.output, p) end self.n = n end function selftest () print('selftest: apps.pcap.tap') local config = require("core.config") local Sink = require("apps.basic.basic_apps").Sink local PcapReader = require("apps.pcap.pcap").PcapReader local function run(filter, sample) local tmp = os.tmpname() local c = config.new() -- Re-use example from packet filter test. config.app(c, "source", PcapReader, "apps/packet_filter/samples/v6.pcap") config.app(c, "tap", Tap, {filename=tmp, filter=filter, sample=sample}) config.app(c, "sink", Sink ) config.link(c, "source.output -> tap.input") config.link(c, "tap.output -> sink.input") app.configure(c) while not app.app_table.source.done do app.breathe() end local n = 0 for packet, record in pcap.records(tmp) do n = n + 1 end os.remove(tmp) app.configure(config.new()) return n end assert(run() == 161) assert(run("icmp6") == 49) assert(run(nil, 2) == 81) assert(run("icmp6", 2) == 25) print('selftest: ok') end
apache-2.0
thedraked/darkstar
scripts/zones/Castle_Oztroja/npcs/_47d.lua
14
1071
----------------------------------- -- Area: Castle Oztroja -- NPC: _47d -- @pos 20.000 24.168 -25.000 151 ----------------------------------- package.loaded["scripts/zones/Castle_Oztroja/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Castle_Oztroja/TextIDs"); ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(player:hasKeyItem(OLD_RING) == false) then player:addKeyItem(OLD_RING); player:messageSpecial(KEYITEM_OBTAINED,OLD_RING); end if (npc:getAnimation() == 9) then npc:openDoor(); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
mtroyka/Zero-K
LuaUI/Widgets/unit_auto_group.lua
6
11333
local versionNum = '3.031' function widget:GetInfo() return { name = "Auto Group", desc = "v".. (versionNum) .." Alt+0-9 sets autogroup# for selected unit type(s). Newly built units get added to group# equal to their autogroup#. Alt BACKQUOTE (~) remove units. Type '/luaui autogroup help' for help or view settings at: Settings/Interface/AutoGroup'.", author = "Licho", date = "Mar 23, 2007", license = "GNU GPL, v2 or later", layer = 0, enabled = true --loaded by default? } end include("keysym.h.lua") ---- CHANGELOG ----- -- versus666, v3.03 (17dec2011) : Back to alt BACKQUOTE to remove selected units from group -- to please licho, changed help accordingly. -- versus666, v3.02 (16dec2011) : Fixed for 84, removed unused features, now alt backspace to remove -- selected units from group, changed help accordingly. -- versus666, v3.01 (07jan2011) : Added check to comply with F5. -- wagonrepairer v3.00 (07dec2010) : 'Chilified' autogroup. -- versus666, v2.25 (04nov2010) : Added switch to show or not group number, by licho's request. -- versus666, v2.24 (27oct2010) : Added switch to auto add units when built from factories. -- Add group label numbers to units in group. -- Sped up some routines & cleaned code. -- ?, v2,23 : Unknown. -- very_bad_solider,v2.22 : Ignores buildings and factories. -- Does not react when META (+ALT) is pressed. -- CarRepairer, v2.00 : Autogroups key is alt instead of alt+ctrl. -- Added commands: help, loadgroups, cleargroups, verboseMode, addall. -- Licho, v1.0 : Creation. --REMINDER : -- none -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local debug = false --of true generates debug messages local unit2group = {} -- list of unit types to group local groupableBuildingTypes = { 'tacnuke', 'empmissile', 'napalmmissile', 'seismic' } local groupableBuildings = {} for _, v in ipairs( groupableBuildingTypes ) do if UnitDefNames[v] then groupableBuildings[ UnitDefNames[v].id ] = true end end local helpText = 'Alt+0-9 sets autogroup# for selected unit type(s).\nNewly built units get added to group# equal to their autogroup#.'.. '\nAlt+BACKQUOTE (~) deletes autogrouping for selected unit type(s).' --'Ctrl+~ removes nearest selected unit from its group and selects it. ' --'Extra function: Ctrl+q picks single nearest unit from current selection.', options_order = { 'mainlabel', 'help', 'cleargroups', 'loadgroups', 'addall', 'verbose', 'immediate', 'groupnumbers', } options_path = 'Settings/Interface/Control Groups' options = { mainlabel = {name='Auto Group', type='label'}, loadgroups = { name = 'Preserve Auto Groups', desc = 'Preserve auto groupings for next game. Unchecking this clears the groups!', type = 'bool', value = true, noHotkey = true, OnChange = function(self) if not self.value then unit2group = {} Spring.Echo('game_message: Cleared Autogroups.') end end }, addall = { name = 'Add All', desc = 'Existing units will be added to group# when setting autogroup#.', type = 'bool', value = false, noHotkey = true, }, verbose = { name = 'Verbose Mode', type = 'bool', value = true, noHotkey = true, }, immediate = { name = 'Immediate Mode', desc = 'Units built/resurrected/received are added to autogroups immediately instead of waiting them to be idle.', type = 'bool', value = false, noHotkey = true, }, groupnumbers = { name = 'Display Group Numbers', type = 'bool', value = true, noHotkey = true, }, help = { name = 'Help', type = 'text', value = helpText, }, cleargroups = { name = 'Clear Auto Groups', type = 'button', OnChange = function() unit2group = {} Spring.Echo('game_message: Cleared Autogroups.') end, }, } local finiGroup = {} local myTeam local selUnitDefs = {} local loadGroups = true local createdFrame = {} local textColor = {0.7, 1.0, 0.7, 1.0} -- r g b alpha local textSize = 13.0 -- gr = groupe selected/wanted -- speedups local SetUnitGroup = Spring.SetUnitGroup local GetSelectedUnits = Spring.GetSelectedUnits local GetUnitDefID = Spring.GetUnitDefID local GetAllUnits = Spring.GetAllUnits local GetUnitHealth = Spring.GetUnitHealth local GetMouseState = Spring.GetMouseState local SelectUnitArray = Spring.SelectUnitArray local TraceScreenRay = Spring.TraceScreenRay local GetUnitPosition = Spring.GetUnitPosition local UDefTab = UnitDefs local GetGroupList = Spring.GetGroupList local GetGroupUnits = Spring.GetGroupUnits local GetGameFrame = Spring.GetGameFrame local IsGuiHidden = Spring.IsGUIHidden local Echo = Spring.Echo function printDebug( value ) if ( debug ) then Echo( value ) end end function widget:Initialize() local _, _, spec, team = Spring.GetPlayerInfo(Spring.GetMyPlayerID()) if spec then widgetHandler:RemoveWidget() return false end myTeam = team end function widget:DrawWorld() if not IsGuiHidden() then local existingGroups = GetGroupList() if options.groupnumbers.value then for inGroup, _ in pairs(existingGroups) do units = GetGroupUnits(inGroup) for _, unit in ipairs(units) do if Spring.IsUnitInView(unit) then local ux, uy, uz = Spring.GetUnitViewPosition(unit) gl.PushMatrix() gl.Translate(ux, uy, uz) gl.Billboard() gl.Color(textColor)--unused anyway when gl.Text have option 's' (and b & w) gl.Text("" .. inGroup, 30.0, -10.0, textSize, "cns") gl.PopMatrix() end end end else end end end function widget:UnitFinished(unitID, unitDefID, unitTeam) if (unitTeam == myTeam and unitID ~= nil) then if (createdFrame[unitID] == GetGameFrame()) then local gr = unit2group[unitDefID] --printDebug("<AUTOGROUP>: Unit finished " .. unitID) -- if gr ~= nil then SetUnitGroup(unitID, gr) end else finiGroup[unitID] = 1 end end end function widget:UnitCreated(unitID, unitDefID, unitTeam, builderID) if (unitTeam == myTeam) then createdFrame[unitID] = GetGameFrame() end end function widget:UnitFromFactory(unitID, unitDefID, unitTeam) if options.immediate.value or groupableBuildings[unitDefID] then if (unitTeam == myTeam) then createdFrame[unitID] = GetGameFrame() local gr = unit2group[unitDefID] if gr ~= nil then SetUnitGroup(unitID, gr) end --printDebug("<AUTOGROUP>: Unit from factory " .. unitID) end end end function widget:UnitDestroyed(unitID, unitDefID, teamID) finiGroup[unitID] = nil createdFrame[unitID] = nil --printDebug("<AUTOGROUP> : Unit destroyed ".. unitID) end function widget:UnitGiven(unitID, unitDefID, newTeamID, teamID) if (newTeamID == myTeam) then local gr = unit2group[unitDefID] --printDebug("<AUTOGROUP> : Unit given ".. unit2group[unitDefID]) if gr ~= nil then SetUnitGroup(unitID, gr) end end createdFrame[unitID] = nil finiGroup[unitID] = nil end function widget:UnitTaken(unitID, unitDefID, oldTeamID, teamID) if (teamID == myTeam) then local gr = unit2group[unitDefID] --printDebug("<AUTOGROUP> : Unit taken ".. unit2group[unitDefID]) if gr ~= nil then SetUnitGroup(unitID, gr) end end createdFrame[unitID] = nil finiGroup[unitID] = nil end function widget:UnitIdle(unitID, unitDefID, unitTeam) if (unitTeam == myTeam and finiGroup[unitID]~=nil) then local gr = unit2group[unitDefID] if gr ~= nil then SetUnitGroup(unitID, gr) --printDebug("<AUTOGROUP> : Unit idle " .. gr) end finiGroup[unitID] = nil end end function widget:KeyPress(key, modifier, isRepeat) if ( modifier.alt and not modifier.meta ) then local gr if (key == KEYSYMS.N_0) then gr = 0 end if (key == KEYSYMS.N_1) then gr = 1 end if (key == KEYSYMS.N_2) then gr = 2 end if (key == KEYSYMS.N_3) then gr = 3 end if (key == KEYSYMS.N_4) then gr = 4 end if (key == KEYSYMS.N_5) then gr = 5 end if (key == KEYSYMS.N_6) then gr = 6 end if (key == KEYSYMS.N_7) then gr = 7 end if (key == KEYSYMS.N_8) then gr = 8 end if (key == KEYSYMS.N_9) then gr = 9 end if (key == KEYSYMS.BACKQUOTE) then gr = -1 end if (gr ~= nil) then if (gr == -1) then gr = nil end selUnitDefIDs = {} local exec = false --set to true when there is at least one unit to process for _, unitID in ipairs(GetSelectedUnits()) do local udid = GetUnitDefID(unitID) if ( not UDefTab[udid]["isFactory"] and (groupableBuildings[udid] or not UDefTab[udid]["isBuilding"] )) then selUnitDefIDs[udid] = true unit2group[udid] = gr --local x, y, z = Spring.GetUnitPosition(unitID) --Spring.MarkerAddPoint( x, y, z ) exec = true --Echo('<AUTOGROUP> : Add unit ' .. unitID .. 'to group ' .. gr) if (gr==nil) then SetUnitGroup(unitID, -1) else SetUnitGroup(unitID, gr) end end end if ( exec == false ) then return false --nothing to do end for udid,_ in pairs(selUnitDefIDs) do if options.verbose.value then if gr then Echo('game_message: Added '.. Spring.Utilities.GetHumanName(UnitDefs[udid]) ..' to autogroup #'.. gr ..'.') else Echo('game_message: Removed '.. Spring.Utilities.GetHumanName(UnitDefs[udid]) ..' from autogroups.') end end end if options.addall.value then local myUnits = Spring.GetTeamUnits(myTeam) for _, unitID in pairs(myUnits) do local curUnitDefID = GetUnitDefID(unitID) if selUnitDefIDs[curUnitDefID] then if gr then local _, _, _, _, buildProgress = GetUnitHealth(unitID) if buildProgress == 1 then SetUnitGroup(unitID, gr) SelectUnitArray({unitID}, true) end else SetUnitGroup(unitID, -1) end end end end return true --key was processed by widget end elseif (modifier.ctrl and not modifier.meta) then if (key == KEYSYMS.BACKQUOTE) then local mx,my = GetMouseState() local _,pos = TraceScreenRay(mx,my,true) local mindist = math.huge local muid = nil if (pos == nil) then return end for _, uid in ipairs(GetSelectedUnits()) do local x,_,z = GetUnitPosition(uid) dist = (pos[1]-x)*(pos[1]-x) + (pos[3]-z)*(pos[3]-z) if (dist < mindist) then mindist = dist muid = uid end end if (muid ~= nil) then SetUnitGroup(muid,-1) SelectUnitArray({muid}) end end --[[ if (key == KEYSYMS.Q) then for _, uid in ipairs(GetSelectedUnits()) do SetUnitGroup(uid,-1) end end --]] end return false end function widget:GetConfigData() local groups = {} for id, gr in pairs(unit2group) do table.insert(groups, {UnitDefs[id].name, gr}) end local ret = { version = versionNum, groups = groups, } return ret end function widget:SetConfigData(data) if (data and type(data) == 'table' and data.version and (data.version+0) > 2.1) then local groupData = data.groups if groupData and type(groupData) == 'table' then for _, nam in ipairs(groupData) do if type(nam) == 'table' then local gr = UnitDefNames[nam[1]] if (gr ~= nil) then unit2group[gr.id] = nam[2] end end end end end end --------------------------------------------------------------------------------
gpl-2.0
thedraked/darkstar
scripts/globals/mobskills/Miasma.lua
33
1139
--------------------------------------------- -- Miasma -- -- Description: Releases a toxic cloud on nearby targets. Additional effects: Slow + Poison + Plague -- Type: Magical -- Utsusemi/Blink absorb: Wipes shadows? -- Range: Less than or equal to 10.0 -- Notes: Only used by Gulool Ja Ja. --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) return 0; end; function onMobWeaponSkill(target, mob, skill) local duration = 180; MobStatusEffectMove(mob, target, EFFECT_POISON, mob:getMainLvl()/3, 3, 60); MobStatusEffectMove(mob, target, EFFECT_SLOW, 128, 3, 120); MobStatusEffectMove(mob, target, EFFECT_PLAGUE, 5, 3, 60); local dmgmod = 1; local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*4,ELE_EARTH,dmgmod,TP_NO_EFFECT); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_EARTH,MOBPARAM_WIPE_SHADOWS); target:delHP(dmg); return dmg; end;
gpl-3.0
jhasse/wxFormBuilder
build/premake/4.3/tests/base/test_table.lua
14
1035
-- -- tests/base/test_table.lua -- Automated test suite for the new table functions. -- Copyright (c) 2008-2010 Jason Perkins and the Premake project -- T.table = { } local suite = T.table -- -- table.contains() tests -- function suite.contains_OnContained() t = { "one", "two", "three" } test.istrue( table.contains(t, "two") ) end function suite.contains_OnNotContained() t = { "one", "two", "three" } test.isfalse( table.contains(t, "four") ) end -- -- table.flatten() tests -- function suite.flatten_OnMixedValues() t = { "a", { "b", "c" }, "d" } test.isequal({ "a", "b", "c", "d" }, table.flatten(t)) end -- -- table.implode() tests -- function suite.implode() t = { "one", "two", "three", "four" } test.isequal("[one], [two], [three], [four]", table.implode(t, "[", "]", ", ")) end -- -- table.isempty() tests -- function suite.isempty_ReturnsTrueOnEmpty() test.istrue(table.isempty({})) end function suite.isempty_ReturnsFalseOnNotEmpty() test.isfalse(table.isempty({ 1 })) end
gpl-2.0
ukoloff/rufus-lua-win
vendor/lua/lib/lua/pl/class.lua
12
5169
--- Provides a reuseable and convenient framework for creating classes in Lua. -- Two possible notations: -- -- B = class(A) -- class.B(A) -- -- The latter form creates a named class. -- -- See the Guide for further @{01-introduction.md.Simplifying_Object_Oriented_Programming_in_Lua|discussion} -- @module pl.class local error, getmetatable, io, pairs, rawget, rawset, setmetatable, tostring, type = _G.error, _G.getmetatable, _G.io, _G.pairs, _G.rawget, _G.rawset, _G.setmetatable, _G.tostring, _G.type -- this trickery is necessary to prevent the inheritance of 'super' and -- the resulting recursive call problems. local function call_ctor (c,obj,...) -- nice alias for the base class ctor local base = rawget(c,'_base') if base then local parent_ctor = rawget(base,'_init') if parent_ctor then obj.super = function(obj,...) call_ctor(base,obj,...) end end end local res = c._init(obj,...) obj.super = nil return res end local function is_a(self,klass) local m = getmetatable(self) if not m then return false end --*can't be an object! while m do if m == klass then return true end m = rawget(m,'_base') end return false end local function class_of(klass,obj) if type(klass) ~= 'table' or not rawget(klass,'is_a') then return false end return klass.is_a(obj,klass) end local function _class_tostring (obj) local mt = obj._class local name = rawget(mt,'_name') setmetatable(obj,nil) local str = tostring(obj) setmetatable(obj,mt) if name then str = name ..str:gsub('table','') end return str end local function tupdate(td,ts) for k,v in pairs(ts) do td[k] = v end end local function _class(base,c_arg,c) c = c or {} -- a new class instance, which is the metatable for all objects of this type -- the class will be the metatable for all its objects, -- and they will look up their methods in it. local mt = {} -- a metatable for the class instance if type(base) == 'table' then -- our new class is a shallow copy of the base class! tupdate(c,base) c._base = base -- inherit the 'not found' handler, if present if rawget(c,'_handler') then mt.__index = c._handler end elseif base ~= nil then error("must derive from a table type",3) end c.__index = c setmetatable(c,mt) c._init = nil if base and rawget(base,'_class_init') then base._class_init(c,c_arg) end -- expose a ctor which can be called by <classname>(<args>) mt.__call = function(class_tbl,...) local obj = {} setmetatable(obj,c) if rawget(c,'_init') then -- explicit constructor local res = call_ctor(c,obj,...) if res then -- _if_ a ctor returns a value, it becomes the object... obj = res setmetatable(obj,c) end elseif base and rawget(base,'_init') then -- default constructor -- make sure that any stuff from the base class is initialized! call_ctor(base,obj,...) end if base and rawget(base,'_post_init') then base._post_init(obj) end if not rawget(c,'__tostring') then c.__tostring = _class_tostring end return obj end -- Call Class.catch to set a handler for methods/properties not found in the class! c.catch = function(handler) c._handler = handler mt.__index = handler end c.is_a = is_a c.class_of = class_of c._class = c return c end --- create a new class, derived from a given base class. -- Supporting two class creation syntaxes: -- either `Name = class(base)` or `class.Name(base)` -- @function class -- @param base optional base class -- @param c_arg optional parameter to class ctor -- @param c optional table to be used as class local class class = setmetatable({},{ __call = function(fun,...) return _class(...) end, __index = function(tbl,key) if key == 'class' then io.stderr:write('require("pl.class").class is deprecated. Use require("pl.class")\n') return class end local env = _G return function(...) local c = _class(...) c._name = key rawset(env,key,c) return c end end }) class.properties = class() function class.properties._class_init(klass) klass.__index = function(t,key) -- normal class lookup! local v = klass[key] if v then return v end -- is it a getter? v = rawget(klass,'get_'..key) if v then return v(t) end -- is it a field? return rawget(t,'_'..key) end klass.__newindex = function (t,key,value) -- if there's a setter, use that, otherwise directly set table local p = 'set_'..key local setter = klass[p] if setter then setter(t,value) else rawset(t,key,value) end end end return class
mit
thedraked/darkstar
scripts/zones/Metalworks/npcs/Grohm.lua
14
3042
----------------------------------- -- Area: Metalworks -- NPC: Grohm -- Involved In Mission: Journey Abroad -- @pos -18 -11 -27 237 ----------------------------------- package.loaded["scripts/zones/Metalworks/TextIDs"] = nil; ----------------------------------- require("scripts/globals/missions"); require("scripts/zones/Metalworks/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getCurrentMission(SANDORIA) == JOURNEY_TO_BASTOK) then if (player:getVar("notReceivePickaxe") == 1) then player:startEvent(0x01a9); elseif (player:getVar("MissionStatus") == 4) then player:startEvent(0x01a7); elseif (player:getVar("MissionStatus") == 5 and player:hasItem(599) == false) then player:startEvent(0x01a8); else player:startEvent(0x01a6); end elseif (player:getCurrentMission(SANDORIA) == JOURNEY_TO_BASTOK2) then if (player:getVar("MissionStatus") == 9) then player:startEvent(0x01aa); else player:startEvent(0x01ab); end elseif (player:getCurrentMission(WINDURST) == THE_THREE_KINGDOMS_BASTOK) then if (player:getVar("notReceivePickaxe") == 1) then player:startEvent(0x01a9,1); elseif (player:getVar("MissionStatus") == 4) then player:startEvent(0x01a7,1); elseif (player:getVar("MissionStatus") == 5 and player:hasItem(599) == false) then player:startEvent(0x01a8,1); else player:startEvent(0x01a6); end elseif (player:getCurrentMission(WINDURST) == THE_THREE_KINGDOMS_BASTOK2) then if (player:getVar("MissionStatus") == 9) then player:startEvent(0x01aa,1); else player:startEvent(0x01ab,1); end else player:startEvent(0x01ab);--0x01a6 end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x01a7 or csid == 0x01a9) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,605); -- Pickaxes player:setVar("notReceivePickaxe",1); else player:addItem(605,5); player:messageSpecial(ITEM_OBTAINED,605); -- Pickaxes player:setVar("MissionStatus",5); player:setVar("notReceivePickaxe",0); end elseif (csid == 0x01aa) then player:setVar("MissionStatus",10); end end;
gpl-3.0
rjeli/luvit
tests/test-fs-stat.lua
14
1933
--[[ Copyright 2012 The Luvit Authors. All Rights Reserved. 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 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 FS = require('fs') local JSON = require('json') require('tap')(function(test) test('fs.stat', function() FS.stat('.', function(err, stats) assert(not err) p(JSON.stringify(stats)) assert(type(stats.mtime.sec) == 'number') end) end) test('fs.lstat', function() FS.lstat('.', function(err, stats) assert(not err) p(JSON.stringify(stats)) assert(type(stats.mtime.sec) == 'number') end) end) -- fstat test('fs.open', function() FS.open('.', 'r', function(err, fd) assert(not err) assert(fd) FS.fstat(fd, function(err, stats) assert(not err) p(JSON.stringify(stats)) assert(type(stats.mtime.sec) == 'number') FS.close(fd) end) end) end) -- fstatSync test('fstatSync', function() FS.open('.', 'r', function(err, fd) local ok, stats ok, stats = pcall(FS.fstatSync, fd) assert(ok) if stats then p(JSON.stringify(stats)) assert(type(stats.mtime.sec) == 'number') end FS.close(fd) end) end) test('stat', function() p('stating: ' .. module.path) FS.stat(module.path, function(err, s) assert(not err) p(JSON.stringify(s)) assert(s.type == 'file') assert(type(s.mtime.sec) == 'number') end) end) end)
apache-2.0
Shayan123456/ahvaz
bot/utils.lua
646
23489
URL = require "socket.url" http = require "socket.http" https = require "ssl.https" ltn12 = require "ltn12" serpent = require "serpent" feedparser = require "feedparser" json = (loadfile "./libs/JSON.lua")() mimetype = (loadfile "./libs/mimetype.lua")() redis = (loadfile "./libs/redis.lua")() JSON = (loadfile "./libs/dkjson.lua")() http.TIMEOUT = 10 function get_receiver(msg) if msg.to.type == 'user' then return 'user#id'..msg.from.id end if msg.to.type == 'chat' then return 'chat#id'..msg.to.id end if msg.to.type == 'encr_chat' then return msg.to.print_name end end function is_chat_msg( msg ) if msg.to.type == 'chat' then return true end return false end function string.random(length) local str = ""; for i = 1, length do math.random(97, 122) str = str..string.char(math.random(97, 122)); end return str; end function string:split(sep) local sep, fields = sep or ":", {} local pattern = string.format("([^%s]+)", sep) self:gsub(pattern, function(c) fields[#fields+1] = c end) return fields end -- DEPRECATED function string.trim(s) print("string.trim(s) is DEPRECATED use string:trim() instead") return s:gsub("^%s*(.-)%s*$", "%1") end -- Removes spaces function string:trim() return self:gsub("^%s*(.-)%s*$", "%1") end function get_http_file_name(url, headers) -- Eg: foo.var local file_name = url:match("[^%w]+([%.%w]+)$") -- Any delimited alphanumeric on the url file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$") -- Random name, hope content-type works file_name = file_name or str:random(5) local content_type = headers["content-type"] local extension = nil if content_type then extension = mimetype.get_mime_extension(content_type) end if extension then file_name = file_name.."."..extension end local disposition = headers["content-disposition"] if disposition then -- attachment; filename=CodeCogsEqn.png file_name = disposition:match('filename=([^;]+)') or file_name end return file_name end -- Saves file to /tmp/. If file_name isn't provided, -- will get the text after the last "/" for filename -- and content-type for extension function download_to_file(url, file_name) print("url to download: "..url) local respbody = {} local options = { url = url, sink = ltn12.sink.table(respbody), redirect = true } -- nil, code, headers, status local response = nil if url:starts('https') then options.redirect = false response = {https.request(options)} else response = {http.request(options)} end local code = response[2] local headers = response[3] local status = response[4] if code ~= 200 then return nil end file_name = file_name or get_http_file_name(url, headers) local file_path = "/tmp/"..file_name print("Saved to: "..file_path) file = io.open(file_path, "w+") file:write(table.concat(respbody)) file:close() return file_path end function vardump(value) print(serpent.block(value, {comment=false})) end -- taken from http://stackoverflow.com/a/11130774/3163199 function scandir(directory) local i, t, popen = 0, {}, io.popen for filename in popen('ls -a "'..directory..'"'):lines() do i = i + 1 t[i] = filename end return t end -- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen function run_command(str) local cmd = io.popen(str) local result = cmd:read('*all') cmd:close() return result end -- User has privileges function is_sudo(msg) local var = false -- Check users id in config for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end -- Returns the name of the sender function get_name(msg) local name = msg.from.first_name if name == nil then name = msg.from.id end return name end -- Returns at table of lua files inside plugins function plugins_names( ) local files = {} for k, v in pairs(scandir("plugins")) do -- Ends with .lua if (v:match(".lua$")) then table.insert(files, v) end end return files end -- Function name explains what it does. function file_exists(name) local f = io.open(name,"r") if f ~= nil then io.close(f) return true else return false end end -- Save into file the data serialized for lua. -- Set uglify true to minify the file. function serialize_to_file(data, file, uglify) file = io.open(file, 'w+') local serialized if not uglify then serialized = serpent.block(data, { comment = false, name = '_' }) else serialized = serpent.dump(data) end file:write(serialized) file:close() end -- Returns true if the string is empty function string:isempty() return self == nil or self == '' end -- Returns true if the string is blank function string:isblank() self = self:trim() return self:isempty() end -- DEPRECATED!!!!! function string.starts(String, Start) print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead") return Start == string.sub(String,1,string.len(Start)) end -- Returns true if String starts with Start function string:starts(text) return text == string.sub(self,1,string.len(text)) end -- Send image to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_photo(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function, cb_extra = cb_extra } -- Call to remove with optional callback send_photo(receiver, file_path, cb_function, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_photo_from_url(receiver, url, cb_function, cb_extra) -- If callback not provided cb_function = cb_function or ok_cb cb_extra = cb_extra or false local file_path = download_to_file(url, false) if not file_path then -- Error local text = 'Error downloading the image' send_msg(receiver, text, cb_function, cb_extra) else print("File path: "..file_path) _send_photo(receiver, file_path, cb_function, cb_extra) end end -- Same as send_photo_from_url but as callback function function send_photo_from_url_callback(cb_extra, success, result) local receiver = cb_extra.receiver local url = cb_extra.url local file_path = download_to_file(url, false) if not file_path then -- Error local text = 'Error downloading the image' send_msg(receiver, text, ok_cb, false) else print("File path: "..file_path) _send_photo(receiver, file_path, ok_cb, false) end end -- Send multiple images asynchronous. -- param urls must be a table. function send_photos_from_url(receiver, urls) local cb_extra = { receiver = receiver, urls = urls, remove_path = nil } send_photos_from_url_callback(cb_extra) end -- Use send_photos_from_url. -- This function might be difficult to understand. function send_photos_from_url_callback(cb_extra, success, result) -- cb_extra is a table containing receiver, urls and remove_path local receiver = cb_extra.receiver local urls = cb_extra.urls local remove_path = cb_extra.remove_path -- The previously image to remove if remove_path ~= nil then os.remove(remove_path) print("Deleted: "..remove_path) end -- Nil or empty, exit case (no more urls) if urls == nil or #urls == 0 then return false end -- Take the head and remove from urls table local head = table.remove(urls, 1) local file_path = download_to_file(head, false) local cb_extra = { receiver = receiver, urls = urls, remove_path = file_path } -- Send first and postpone the others as callback send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra) end -- Callback to remove a file function rmtmp_cb(cb_extra, success, result) local file_path = cb_extra.file_path local cb_function = cb_extra.cb_function or ok_cb local cb_extra = cb_extra.cb_extra if file_path ~= nil then os.remove(file_path) print("Deleted: "..file_path) end -- Finally call the callback cb_function(cb_extra, success, result) end -- Send document to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_document(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function or ok_cb, cb_extra = cb_extra or false } -- Call to remove with optional callback send_document(receiver, file_path, rmtmp_cb, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_document_from_url(receiver, url, cb_function, cb_extra) local file_path = download_to_file(url, false) print("File path: "..file_path) _send_document(receiver, file_path, cb_function, cb_extra) end -- Parameters in ?a=1&b=2 style function format_http_params(params, is_get) local str = '' -- If is get add ? to the beginning if is_get then str = '?' end local first = true -- Frist param for k,v in pairs (params) do if v then -- nil value if first then first = false str = str..k.. "="..v else str = str.."&"..k.. "="..v end end end return str end -- Check if user can use the plugin and warns user -- Returns true if user was warned and false if not warned (is allowed) function warns_user_not_allowed(plugin, msg) if not user_allowed(plugin, msg) then local text = 'This plugin requires privileged user' local receiver = get_receiver(msg) send_msg(receiver, text, ok_cb, false) return true else return false end end -- Check if user can use the plugin function user_allowed(plugin, msg) if plugin.privileged and not is_sudo(msg) then return false end return true end function send_order_msg(destination, msgs) local cb_extra = { destination = destination, msgs = msgs } send_order_msg_callback(cb_extra, true) end function send_order_msg_callback(cb_extra, success, result) local destination = cb_extra.destination local msgs = cb_extra.msgs local file_path = cb_extra.file_path if file_path ~= nil then os.remove(file_path) print("Deleted: " .. file_path) end if type(msgs) == 'string' then send_large_msg(destination, msgs) elseif type(msgs) ~= 'table' then return end if #msgs < 1 then return end local msg = table.remove(msgs, 1) local new_cb_extra = { destination = destination, msgs = msgs } if type(msg) == 'string' then send_msg(destination, msg, send_order_msg_callback, new_cb_extra) elseif type(msg) == 'table' then local typ = msg[1] local nmsg = msg[2] new_cb_extra.file_path = nmsg if typ == 'document' then send_document(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'image' or typ == 'photo' then send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'audio' then send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'video' then send_video(destination, nmsg, send_order_msg_callback, new_cb_extra) else send_file(destination, nmsg, send_order_msg_callback, new_cb_extra) end end end -- Same as send_large_msg_callback but friendly params function send_large_msg(destination, text) local cb_extra = { destination = destination, text = text } send_large_msg_callback(cb_extra, true) end -- If text is longer than 4096 chars, send multiple msg. -- https://core.telegram.org/method/messages.sendMessage function send_large_msg_callback(cb_extra, success, result) local text_max = 4096 local destination = cb_extra.destination local text = cb_extra.text local text_len = string.len(text) local num_msg = math.ceil(text_len / text_max) if num_msg <= 1 then send_msg(destination, text, ok_cb, false) else local my_text = string.sub(text, 1, 4096) local rest = string.sub(text, 4096, text_len) local cb_extra = { destination = destination, text = rest } send_msg(destination, my_text, send_large_msg_callback, cb_extra) end end -- Returns a table with matches or nil function match_pattern(pattern, text, lower_case) if text then local matches = {} if lower_case then matches = { string.match(text:lower(), pattern) } else matches = { string.match(text, pattern) } end if next(matches) then return matches end end -- nil end -- Function to read data from files function load_from_file(file, default_data) local f = io.open(file, "r+") -- If file doesn't exists if f == nil then -- Create a new empty table default_data = default_data or {} serialize_to_file(default_data, file) print ('Created file', file) else print ('Data loaded from file', file) f:close() end return loadfile (file)() end -- See http://stackoverflow.com/a/14899740 function unescape_html(str) local map = { ["lt"] = "<", ["gt"] = ">", ["amp"] = "&", ["quot"] = '"', ["apos"] = "'" } new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s) var = map[s] or n == "#" and string.char(s) var = var or n == "#x" and string.char(tonumber(s,16)) var = var or orig return var end) return new end --Check if this chat is realm or not function is_realm(msg) local var = false local realms = 'realms' local data = load_data(_config.moderation.data) local chat = msg.to.id if data[tostring(realms)] then if data[tostring(realms)][tostring(msg.to.id)] then var = true end return var end end --Check if this chat is a group or not function is_group(msg) local var = false local groups = 'groups' local data = load_data(_config.moderation.data) local chat = msg.to.id if data[tostring(groups)] then if data[tostring(groups)][tostring(msg.to.id)] then var = true end return var end end function savelog(group, logtxt) local text = (os.date("[ %c ]=> "..logtxt.."\n \n")) local file = io.open("./groups/logs/"..group.."log.txt", "a") file:write(text) file:close() end function user_print_name(user) if user.print_name then return user.print_name end local text = '' if user.first_name then text = user.last_name..' ' end if user.lastname then text = text..user.last_name end return text end --Check if user is the owner of that group or not function is_owner(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['set_owner'] then if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then var = true end end end if data['admins'] then if data['admins'][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_owner2(user_id, group_id) local var = false local data = load_data(_config.moderation.data) if data[tostring(group_id)] then if data[tostring(group_id)]['set_owner'] then if data[tostring(group_id)]['set_owner'] == tostring(user_id) then var = true end end end if data['admins'] then if data['admins'][tostring(user_id)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == user_id then var = true end end return var end --Check if user is admin or not function is_admin(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id local admins = 'admins' if data[tostring(admins)] then if data[tostring(admins)][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_admin2(user_id) local var = false local data = load_data(_config.moderation.data) local user = user_id local admins = 'admins' if data[tostring(admins)] then if data[tostring(admins)][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == user_id then var = true end end return var end --Check if user is the mod of that group or not function is_momod(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['moderators'] then if data[tostring(msg.to.id)]['moderators'][tostring(user)] then var = true end end end if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['set_owner'] then if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then var = true end end end if data['admins'] then if data['admins'][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_momod2(user_id, group_id) local var = false local data = load_data(_config.moderation.data) local usert = user_id if data[tostring(group_id)] then if data[tostring(group_id)]['moderators'] then if data[tostring(group_id)]['moderators'][tostring(usert)] then var = true end end end if data[tostring(group_id)] then if data[tostring(group_id)]['set_owner'] then if data[tostring(group_id)]['set_owner'] == tostring(user_id) then var = true end end end if data['admins'] then if data['admins'][tostring(user_id)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == usert then var = true end end return var end -- Returns the name of the sender function kick_user(user_id, chat_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_owner2(user_id, chat_id) then -- Ignore admins return end local chat = 'chat#id'..chat_id local user = 'user#id'..user_id chat_del_user(chat, user, ok_cb, true) end -- Ban function ban_user(user_id, chat_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_admin2(user_id) then -- Ignore admins return end -- Save to redis local hash = 'banned:'..chat_id redis:sadd(hash, user_id) -- Kick from chat kick_user(user_id, chat_id) end -- Global ban function banall_user(user_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_admin2(user_id) then -- Ignore admins return end -- Save to redis local hash = 'gbanned' redis:sadd(hash, user_id) end -- Global unban function unbanall_user(user_id) --Save on redis local hash = 'gbanned' redis:srem(hash, user_id) end -- Check if user_id is banned in chat_id or not function is_banned(user_id, chat_id) --Save on redis local hash = 'banned:'..chat_id local banned = redis:sismember(hash, user_id) return banned or false end -- Check if user_id is globally banned or not function is_gbanned(user_id) --Save on redis local hash = 'gbanned' local banned = redis:sismember(hash, user_id) return banned or false end -- Returns chat_id ban list function ban_list(chat_id) local hash = 'banned:'..chat_id local list = redis:smembers(hash) local text = "Ban list !\n\n" for k,v in pairs(list) do text = text..k.." - "..v.." \n" end return text end -- Returns globally ban list function banall_list() local hash = 'gbanned' local list = redis:smembers(hash) local text = "global bans !\n\n" for k,v in pairs(list) do text = text..k.." - "..v.." \n" end return text end -- /id by reply function get_message_callback_id(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id send_large_msg(chat, result.from.id) else return 'Use This in Your Groups' end end -- kick by reply for mods and owner function Kick_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't kick myself" end if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin return "you can't kick mods,owner and admins" end chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) else return 'Use This in Your Groups' end end -- Kick by reply for admins function Kick_by_reply_admins(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't kick myself" end if is_admin2(result.from.id) then -- Ignore admins return end chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) else return 'Use This in Your Groups' end end --Ban by reply for admins function ban_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't ban myself" end if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin return "you can't kick mods,owner and admins" end ban_user(result.from.id, result.to.id) send_large_msg(chat, "User "..result.from.id.." Banned") else return 'Use This in Your Groups' end end -- Ban by reply for admins function ban_by_reply_admins(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't ban myself" end if is_admin2(result.from.id) then -- Ignore admins return end ban_user(result.from.id, result.to.id) send_large_msg(chat, "User "..result.from.id.." Banned") else return 'Use This in Your Groups' end end -- Unban by reply function unban_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't unban myself" end send_large_msg(chat, "User "..result.from.id.." Unbanned") -- Save on redis local hash = 'banned:'..result.to.id redis:srem(hash, result.from.id) else return 'Use This in Your Groups' end end function banall_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't banall myself" end if is_admin2(result.from.id) then -- Ignore admins return end local name = user_print_name(result.from) banall_user(result.from.id) chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) send_large_msg(chat, "User "..name.."["..result.from.id.."] hammered") else return 'Use This in Your Groups' end end
gpl-2.0
thedraked/darkstar
scripts/zones/Abyssea-Attohwa/npcs/qm10.lua
9
1346
----------------------------------- -- Zone: Abyssea-Attohwa -- NPC: qm10 (???) -- Spawns Nightshade -- @pos ? ? ? 215 ----------------------------------- require("scripts/globals/status"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) --[[ if (trade:hasItemQty(3082,1) and trade:getItemCount() == 1) then -- Player has all the required items. if (GetMobAction(17658271) == ACTION_NONE) then -- Mob not already spawned from this SpawnMob(17658271):updateClaim(player); -- Spawn NM, Despawn after inactive for 5 minutes (pt has to reclaim within 5 of a wipe) player:tradeComplete(); end end ]] end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(1010, 3082); -- Inform player what items they need. end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
kaustavha/luvit
deps/childprocess.lua
5
4471
--[[ Copyright 2014 The Luvit Authors. All Rights Reserved. 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 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. --]] exports.name = "luvit/childprocess" exports.version = "1.0.8-1" exports.dependencies = { "luvit/core@1.0.5", "luvit/net@1.2.0", "luvit/timer@1.0.0", } exports.license = "Apache 2" exports.homepage = "https://github.com/luvit/luvit/blob/master/deps/childprocess.lua" exports.description = "A port of node.js's childprocess module for luvit." exports.tags = {"luvit", "spawn", "process"} local core = require('core') local net = require('net') local timer = require('timer') local uv = require('uv') local Error = core.Error local Process = core.Emitter:extend() function Process:initialize(stdin, stdout, stderr) self.stdout = stdout self.stdin = stdin self.stderr = stderr end function Process:setHandle(handle) self.handle = handle end function Process:setPid(pid) self.pid = pid end function Process:kill(signal) if self.handle and not uv.is_closing(self.handle) then uv.process_kill(self.handle, signal or 'sigterm') end end function Process:close(err) if self.handle and not uv.is_closing(self.handle) then uv.close(self.handle) end self:destroy(err) end function Process:destroy(err) self:_cleanup(err) if err then timer.setImmediate(function() self:emit('error', err) end) end end function Process:_cleanup(err) timer.setImmediate(function() if self.stdout then self.stdout:_end(err) -- flush self.stdout:destroy(err) -- flush end if self.stderr then self.stderr:destroy(err) end if self.stdin then self.stdin:destroy(err) end end) end local function spawn(command, args, options) local envPairs = {} local em, onExit, handle, pid local stdout, stdin, stderr, stdio, closesGot args = args or {} options = options or {} options.detached = options.detached or false if options.env then for k, v in pairs(options.env) do table.insert(envPairs, k .. '=' .. v) end end local function maybeClose() closesGot = closesGot - 1 if closesGot == 0 then em:emit('close', em.exitCode, em.signal) end end local function countStdio(stdio) local count = 0 if stdio[1] then count = count + 1 end if stdio[2] then count = count + 1 end if stdio[3] then count = count + 1 end return count + 1 -- for exit call end if options.stdio then stdio = {} stdin = options.stdio[1] stdout = options.stdio[2] stderr = options.stdio[3] stdio[1] = options.stdio[1] and options.stdio[1]._handle stdio[2] = options.stdio[2] and options.stdio[2]._handle stdio[3] = options.stdio[3] and options.stdio[3]._handle if stdio[1] then options.stdio[1]:once('close', maybeClose) end if stdio[2] then options.stdio[2]:once('close', maybeClose) end if stdio[3] then options.stdio[3]:once('close', maybeClose) end closesGot = countStdio(stdio) else stdin = net.Socket:new({ handle = uv.new_pipe(false) }) stdout = net.Socket:new({ handle = uv.new_pipe(false) }) stderr = net.Socket:new({ handle = uv.new_pipe(false) }) stdio = { stdin._handle, stdout._handle, stderr._handle} stdin:once('close', maybeClose) stdout:once('close', maybeClose) stderr:once('close', maybeClose) closesGot = countStdio(stdio) end function onExit(code, signal) em.exitCode = code em.signal = signal em:emit('exit', code, signal) maybeClose() em:close() end handle, pid = uv.spawn(command, { cwd = options.cwd or nil, stdio = stdio, args = args, env = envPairs, detached = options.detached, uid = options.uid, gid = options.gid }, onExit) em = Process:new(stdin, stdout, stderr) em:setHandle(handle) em:setPid(pid) if not em.handle then timer.setImmediate(function() em.exitCode = -127 em:emit('exit', em.exitCode) em:destroy(Error:new(pid)) maybeClose() end) end return em end exports.spawn = spawn
apache-2.0
thedraked/darkstar
scripts/zones/Gusgen_Mines/npcs/Clay.lua
14
1229
----------------------------------- -- Area: Gusgen Mines -- NPC: Clay -- Involved in Quest: A Potter's Preference -- @pos 117 -21 432 196 ----------------------------------- package.loaded["scripts/zones/Gusgen_Mines/TextIDs"] = nil; ----------------------------------- require("scripts/globals/titles"); require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/zones/Gusgen_Mines/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:addItem(569,1); --569 - dish_of_gusgen_clay player:messageSpecial(ITEM_OBTAINED,569); -- dish_of_gusgen_clay end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID2: %u",csid); -- printf("RESULT2: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
thedraked/darkstar
scripts/zones/Ordelles_Caves/npcs/Grounds_Tome.lua
30
1098
----------------------------------- -- Area: Ordelle's Caves -- NPC: Grounds Tome ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/groundsofvalor"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) startGov(GOV_EVENT_ORDELLES_CAVES,player); end; ----------------------------------- -- onEventSelection ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); updateGov(player,csid,option,655,656,657,658,659,660,661,662,0,0); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); finishGov(player,csid,option,655,656,657,658,659,660,661,662,0,0,GOV_MSG_ORDELLES_CAVES); end;
gpl-3.0
thedraked/darkstar
scripts/globals/weaponskills/circle_blade.lua
25
1358
----------------------------------- -- Circle Blade -- Sword weapon skill -- Skill Level: 150 -- Delivers an area of effect attack. Attack radius varies with TP. -- Aligned with the Aqua Gorget & Thunder Gorget. -- Aligned with the Aqua Belt & Thunder Belt. -- Element: None -- Modifiers: STR:35% -- 100%TP 200%TP 300%TP -- 1.00 1.00 1.00 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar) local params = {}; params.numHits = 1; params.ftp100 = 1; params.ftp200 = 1; params.ftp300 = 1; params.str_wsc = 0.35; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0; params.canCrit = false; params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0; params.atkmulti = 1; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.str_wsc = 1.0; end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, tp, primary, action, taChar, params); return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
thedraked/darkstar
scripts/globals/spells/bluemagic/feather_tickle.lua
25
1164
----------------------------------------- -- Spell: Feather Tickle -- Reduces an enemy's TP -- Spell cost: 48 MP -- Monster Type: Birds -- Spell Type: Magical (Wind) -- Blue Magic Points: 3 -- Stat Bonus: AGI+1 -- Level: 64 -- Casting Time: 4 seconds -- Recast Time: 26 seconds -- Magic Bursts on: Detonation, Fragmentation, and Light -- Combos: Clear Mind ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); require("scripts/globals/bluemagic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local dINT = caster:getStat(MOD_MND) - target:getStat(MOD_MND); local resist = applyResistance(caster,spell,target,dINT,BLUE_SKILL); local power = 300 * resist; if (target:getTP() == 0) then spell:setMsg(75); else target:delTP(power); spell:setMsg(431); end return tp; end;
gpl-3.0
garage11/kaupunki
build/bin/Data/LuaScripts/01_HelloWorld.lua
24
1882
-- This first example, maintaining tradition, prints a "Hello World" message. -- Furthermore it shows: -- - Using the Sample utility functions as a base for the application -- - Adding a Text element to the graphical user interface -- - Subscribing to and handling of update events require "LuaScripts/Utilities/Sample" function Start() -- Execute the common startup for samples SampleStart() -- Create "Hello World" Text CreateText() -- Set the mouse mode to use in the sample SampleInitMouseMode(MM_FREE) -- Finally, hook-up this HelloWorld instance to handle update events SubscribeToEvents() end function CreateText() -- Construct new Text object local helloText = Text:new() -- Set String to display helloText.text = "Hello World from Urho3D!" -- Set font and text color helloText:SetFont(cache:GetResource("Font", "Fonts/Anonymous Pro.ttf"), 30) helloText.color = Color(0.0, 1.0, 0.0) -- Align Text center-screen helloText.horizontalAlignment = HA_CENTER helloText.verticalAlignment = VA_CENTER -- Add Text instance to the UI root element ui.root:AddChild(helloText) end function SubscribeToEvents() -- Subscribe HandleUpdate() function for processing update events SubscribeToEvent("Update", "HandleUpdate") end function HandleUpdate(eventType, eventData) -- Do nothing for now, could be extended to eg. animate the display end -- Create XML patch instructions for screen joystick layout specific to this sample app function GetScreenJoystickPatchString() return "<patch>" .. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Hat0']]\">" .. " <attribute name=\"Is Visible\" value=\"false\" />" .. " </add>" .. "</patch>" end
mit
thedraked/darkstar
scripts/zones/Northern_San_dOria/npcs/Guilerme.lua
14
2093
----------------------------------- -- Area: Northern San d'Oria -- NPC: Guillerme -- Involved in Quest: Rosel the Armorer -- @zone 231 -- @pos -4.500 0.000 99.000 ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Northern_San_dOria/TextIDs"); require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script local FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE); if (FlyerForRegine == 1) then local count = trade:getItemCount(); local MagicFlyer = trade:hasItemQty(532,1); if (MagicFlyer == true and count == 1) then player:messageSpecial(FLYER_REFUSED); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) -- "Rosel the Armorer" quest status var RoselTheArmorer = player:getQuestStatus(SANDORIA,ROSEL_THE_ARMORER); -- "Rosel the Armorer" - turn in reciept to prince if (RoselTheArmorer == QUEST_ACCEPTED and player:hasKeyItem(RECEIPT_FOR_THE_PRINCE)) then player:startEvent(0x01fb); else player:showText(npc,GUILERME_DIALOG); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); -- "Rosel the Armorer", give receipt to NPC:Guilerme if (csid == 0x01fb) then player:delKeyItem(RECEIPT_FOR_THE_PRINCE); end; end;
gpl-3.0
thedraked/darkstar
scripts/zones/Windurst_Walls/npcs/Naih_Arihmepp.lua
14
1471
----------------------------------- -- Area: Windurst Walls -- NPC: Naih Arihmepp -- Type: Standard NPC -- @pos -64.578 -13.465 202.147 239 ----------------------------------- package.loaded["scripts/zones/Windurst_Walls/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/zones/Windurst_Walls/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local WildcatWindurst = player:getVar("WildcatWindurst"); if (player:getQuestStatus(WINDURST,LURE_OF_THE_WILDCAT_WINDURST) == QUEST_ACCEPTED and player:getMaskBit(WildcatWindurst,9) == false) then player:startEvent(0x01f4); else player:startEvent(0x0146); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x01f4) then player:setMaskBit(player:getVar("WildcatWindurst"),"WildcatWindurst",9,true); end end;
gpl-3.0
garage11/kaupunki
build/bin/Data/LuaScripts/09_MultipleViewports.lua
24
13081
-- Multiple viewports example. -- This sample demonstrates: -- - Setting up two viewports with two separate cameras -- - Adding post processing effects to a viewport's render path and toggling them require "LuaScripts/Utilities/Sample" local rearCameraNode = nil function Start() -- Execute the common startup for samples SampleStart() -- Create the scene content CreateScene() -- Create the UI content CreateInstructions() -- Setup the viewports for displaying the scene SetupViewports() -- Set the mouse mode to use in the sample SampleInitMouseMode(MM_RELATIVE) -- Hook up to the frame update and render post-update events SubscribeToEvents() end function CreateScene() scene_ = Scene() -- Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000) -- Also create a DebugRenderer component so that we can draw debug geometry scene_:CreateComponent("Octree") scene_:CreateComponent("DebugRenderer") -- Create scene node & StaticModel component for showing a static plane local planeNode = scene_:CreateChild("Plane") planeNode.scale = Vector3(100.0, 1.0, 100.0) local planeObject = planeNode:CreateComponent("StaticModel") planeObject.model = cache:GetResource("Model", "Models/Plane.mdl") planeObject.material = cache:GetResource("Material", "Materials/StoneTiled.xml") -- Create a Zone component for ambient lighting & fog control local zoneNode = scene_:CreateChild("Zone") local zone = zoneNode:CreateComponent("Zone") zone.boundingBox = BoundingBox(-1000.0, 1000.0) zone.ambientColor = Color(0.15, 0.15, 0.15) zone.fogColor = Color(0.5, 0.5, 0.7) zone.fogStart = 100.0 zone.fogEnd = 300.0 -- Create a directional light to the world. Enable cascaded shadows on it local lightNode = scene_:CreateChild("DirectionalLight") lightNode.direction = Vector3(0.6, -1.0, 0.8) local light = lightNode:CreateComponent("Light") light.lightType = LIGHT_DIRECTIONAL light.castShadows = true light.shadowBias = BiasParameters(0.00025, 0.5) -- Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance light.shadowCascade = CascadeParameters(10.0, 50.0, 200.0, 0.0, 0.8) -- Create some mushrooms local NUM_MUSHROOMS = 240 for i = 1, NUM_MUSHROOMS do local mushroomNode = scene_:CreateChild("Mushroom") mushroomNode.position = Vector3(Random(90.0) - 45.0, 0.0, Random(90.0) - 45.0) mushroomNode.rotation = Quaternion(0.0, Random(360.0), 0.0) mushroomNode:SetScale(0.5 + Random(2.0)) local mushroomObject = mushroomNode:CreateComponent("StaticModel") mushroomObject.model = cache:GetResource("Model", "Models/Mushroom.mdl") mushroomObject.material = cache:GetResource("Material", "Materials/Mushroom.xml") mushroomObject.castShadows = true end -- Create randomly sized boxes. If boxes are big enough, make them occluders. Occluders will be software rasterized before -- rendering to a low-resolution depth-only buffer to test the objects in the view frustum for visibility local NUM_BOXES = 20 for i = 1, NUM_BOXES do local boxNode = scene_:CreateChild("Box") local size = 1.0 + Random(10.0) boxNode.position = Vector3(Random(80.0) - 40.0, size * 0.5, Random(80.0) - 40.0) boxNode:SetScale(size) local boxObject = boxNode:CreateComponent("StaticModel") boxObject.model = cache:GetResource("Model", "Models/Box.mdl") boxObject.material = cache:GetResource("Material", "Materials/Stone.xml") boxObject.castShadows = true if size >= 3.0 then boxObject.occluder = true end end -- Create the camera. Limit far clip distance to match the fog cameraNode = scene_:CreateChild("Camera") local camera = cameraNode:CreateComponent("Camera") camera.farClip = 300.0 -- Parent the rear camera node to the front camera node and turn it 180 degrees to face backward -- Here, we use the angle-axis constructor for Quaternion instead of the usual Euler angles rearCameraNode = cameraNode:CreateChild("RearCamera") rearCameraNode:Rotate(Quaternion(180.0, Vector3(0.0, 1.0, 0.0))) local rearCamera = rearCameraNode:CreateComponent("Camera") rearCamera.farClip = 300.0 -- Because the rear viewport is rather small, disable occlusion culling from it. Use the camera's -- "view override flags" for this. We could also disable eg. shadows or force low material quality -- if we wanted rearCamera.viewOverrideFlags = VO_DISABLE_OCCLUSION -- Set an initial position for the front camera scene node above the plane cameraNode.position = Vector3(0.0, 5.0, 0.0) end function CreateInstructions() -- Construct new Text object, set string to display and font to use local instructionText = ui.root:CreateChild("Text") instructionText.text = "Use WASD keys and mouse to move\n".. "B to toggle bloom, F to toggle FXAA\n".. "Space to toggle debug geometry\n" instructionText:SetFont(cache:GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15) -- The text has multiple rows. Center them in relation to each other instructionText.textAlignment = HA_CENTER -- Position the text relative to the screen center instructionText.horizontalAlignment = HA_CENTER instructionText.verticalAlignment = VA_CENTER instructionText:SetPosition(0, ui.root.height / 4) end function SetupViewports() renderer.numViewports = 2 -- Set up the front camera viewport local viewport = Viewport:new(scene_, cameraNode:GetComponent("Camera")) renderer:SetViewport(0, viewport) -- Clone the default render path so that we do not interfere with the other viewport, then add -- bloom and FXAA post process effects to the front viewport. Render path commands can be tagged -- for example with the effect name to allow easy toggling on and off. We start with the effects -- disabled. local effectRenderPath = viewport:GetRenderPath():Clone() effectRenderPath:Append(cache:GetResource("XMLFile", "PostProcess/Bloom.xml")) effectRenderPath:Append(cache:GetResource("XMLFile", "PostProcess/FXAA2.xml")) -- Make the bloom mixing parameter more pronounced effectRenderPath:SetShaderParameter("BloomMix", Variant(Vector2(0.9, 0.6))) effectRenderPath:SetEnabled("Bloom", false) effectRenderPath:SetEnabled("FXAA2", false) viewport:SetRenderPath(effectRenderPath) -- Set up the rear camera viewport on top of the front view ("rear view mirror") -- The viewport index must be greater in that case, otherwise the view would be left behind local rearViewport = Viewport:new(scene_, rearCameraNode:GetComponent("Camera"), IntRect(graphics.width * 2 / 3, 32, graphics.width - 32, graphics.height / 3)) renderer:SetViewport(1, rearViewport) end function SubscribeToEvents() -- Subscribe HandleUpdate() function for processing update events SubscribeToEvent("Update", "HandleUpdate") -- Subscribe HandlePostRenderUpdate() function for processing the post-render update event, during which we request -- debug geometry SubscribeToEvent("PostRenderUpdate", "HandlePostRenderUpdate") end function MoveCamera(timeStep) -- Do not move if the UI has a focused element (the console) if ui.focusElement ~= nil then return end -- Movement speed as world units per second local MOVE_SPEED = 20.0 -- Mouse sensitivity as degrees per pixel local MOUSE_SENSITIVITY = 0.1 -- Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees local mouseMove = input.mouseMove yaw = yaw + MOUSE_SENSITIVITY * mouseMove.x pitch = pitch + MOUSE_SENSITIVITY * mouseMove.y pitch = Clamp(pitch, -90.0, 90.0) -- Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero cameraNode.rotation = Quaternion(pitch, yaw, 0.0) -- Read WASD keys and move the camera scene node to the corresponding direction if they are pressed if input:GetKeyDown(KEY_W) then cameraNode:Translate(Vector3(0.0, 0.0, 1.0) * MOVE_SPEED * timeStep) end if input:GetKeyDown(KEY_S) then cameraNode:Translate(Vector3(0.0, 0.0, -1.0) * MOVE_SPEED * timeStep) end if input:GetKeyDown(KEY_A) then cameraNode:Translate(Vector3(-1.0, 0.0, 0.0) * MOVE_SPEED * timeStep) end if input:GetKeyDown(KEY_D) then cameraNode:Translate(Vector3(1.0, 0.0, 0.0) * MOVE_SPEED * timeStep) end -- Toggle post processing effects on the front viewport. Note that the rear viewport is unaffected local effectRenderPath = renderer:GetViewport(0).renderPath if input:GetKeyPress(KEY_B) then effectRenderPath:ToggleEnabled("Bloom") end if input:GetKeyPress(KEY_F) then effectRenderPath:ToggleEnabled("FXAA2") end -- Toggle debug geometry with space if input:GetKeyPress(KEY_SPACE) then drawDebug = not drawDebug end end function HandleUpdate(eventType, eventData) -- Take the frame time step, which is stored as a float local timeStep = eventData["TimeStep"]:GetFloat() -- Move the camera, scale movement with time step MoveCamera(timeStep) end function HandlePostRenderUpdate(eventType, eventData) -- If draw debug mode is enabled, draw viewport debug geometry. Disable depth test so that we can see the effect of occlusion if drawDebug then renderer:DrawDebugGeometry(false) end end -- Create XML patch instructions for screen joystick layout specific to this sample app function GetScreenJoystickPatchString() return "<patch>" .. " <add sel=\"/element\">" .. " <element type=\"Button\">" .. " <attribute name=\"Name\" value=\"Button3\" />" .. " <attribute name=\"Position\" value=\"-120 -120\" />" .. " <attribute name=\"Size\" value=\"96 96\" />" .. " <attribute name=\"Horiz Alignment\" value=\"Right\" />" .. " <attribute name=\"Vert Alignment\" value=\"Bottom\" />" .. " <attribute name=\"Texture\" value=\"Texture2D;Textures/TouchInput.png\" />" .. " <attribute name=\"Image Rect\" value=\"96 0 192 96\" />" .. " <attribute name=\"Hover Image Offset\" value=\"0 0\" />" .. " <attribute name=\"Pressed Image Offset\" value=\"0 0\" />" .. " <element type=\"Text\">" .. " <attribute name=\"Name\" value=\"Label\" />" .. " <attribute name=\"Horiz Alignment\" value=\"Center\" />" .. " <attribute name=\"Vert Alignment\" value=\"Center\" />" .. " <attribute name=\"Color\" value=\"0 0 0 1\" />" .. " <attribute name=\"Text\" value=\"FXAA\" />" .. " </element>" .. " <element type=\"Text\">" .. " <attribute name=\"Name\" value=\"KeyBinding\" />" .. " <attribute name=\"Text\" value=\"F\" />" .. " </element>" .. " </element>" .. " </add>" .. " <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/attribute[@name='Is Visible']\" />" .. " <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Bloom</replace>" .. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]\">" .. " <element type=\"Text\">" .. " <attribute name=\"Name\" value=\"KeyBinding\" />" .. " <attribute name=\"Text\" value=\"B\" />" .. " </element>" .. " </add>" .. " <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/attribute[@name='Is Visible']\" />" .. " <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Debug</replace>" .. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]\">" .. " <element type=\"Text\">" .. " <attribute name=\"Name\" value=\"KeyBinding\" />" .. " <attribute name=\"Text\" value=\"SPACE\" />" .. " </element>" .. " </add>" .. "</patch>" end
mit
thedraked/darkstar
scripts/zones/Port_Bastok/npcs/Oggbi.lua
26
3415
----------------------------------- -- Area: Port Bastok -- NPC: Oggbi -- Starts and Finishes: Ghosts of the Past, The First Meeting -- @zone 236 -- @pos -159 -7 5 ----------------------------------- package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/Port_Bastok/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(BASTOK,GHOSTS_OF_THE_PAST) == QUEST_ACCEPTED) then if (trade:hasItemQty(13122,1) and trade:getItemCount() == 1) then -- Trade Miner's Pendant player:startEvent(0x00e8); -- Finish Quest "Ghosts of the Past" end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) ghostsOfThePast = player:getQuestStatus(BASTOK,GHOSTS_OF_THE_PAST); theFirstMeeting = player:getQuestStatus(BASTOK,THE_FIRST_MEETING); mLvl = player:getMainLvl(); mJob = player:getMainJob(); if (ghostsOfThePast == QUEST_AVAILABLE and mJob == 2 and mLvl >= 40) then player:startEvent(0x00e7); -- Start Quest "Ghosts of the Past" elseif (ghostsOfThePast == QUEST_COMPLETED and player:needToZone() == false and theFirstMeeting == QUEST_AVAILABLE and mJob == 2 and mLvl >= 50) then player:startEvent(0x00e9); -- Start Quest "The First Meeting" elseif (player:hasKeyItem(LETTER_FROM_DALZAKK) and player:hasKeyItem(SANDORIAN_MARTIAL_ARTS_SCROLL)) then player:startEvent(0x00ea); -- Finish Quest "The First Meeting" else player:startEvent(0x00e6); -- Standard Dialog end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x00e7) then player:addQuest(BASTOK,GHOSTS_OF_THE_PAST); elseif (csid == 0x00e8) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,17478); -- Beat Cesti else player:tradeComplete(); player:addItem(17478); player:messageSpecial(ITEM_OBTAINED,17478); -- Beat Cesti player:needToZone(true); player:addFame(BASTOK,AF1_FAME); player:completeQuest(BASTOK,GHOSTS_OF_THE_PAST); end elseif (csid == 0x00e9) then player:addQuest(BASTOK,THE_FIRST_MEETING); elseif (csid == 0x00ea) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,14090); -- Temple Gaiters else player:delKeyItem(LETTER_FROM_DALZAKK); player:delKeyItem(SANDORIAN_MARTIAL_ARTS_SCROLL); player:addItem(14090); player:messageSpecial(ITEM_OBTAINED,14090); -- Temple Gaiters player:addFame(BASTOK,AF2_FAME); player:completeQuest(BASTOK,THE_FIRST_MEETING); end end end;
gpl-3.0
brimworks/zile
src/redisplay.lua
1
2999
-- Terminal independent redisplay routines -- -- Copyright (c) 2010 Free Software Foundation, Inc. -- -- This file is part of GNU Zile. -- -- GNU Zile is free software; you can redistribute it and/or modify it -- under the terms of the GNU General Public License as published by -- the Free Software Foundation; either version 3, or (at your option) -- any later version. -- -- GNU Zile is distributed in the hope that it will be useful, but -- WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -- General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with GNU Zile; see the file COPYING. If not, write to the -- Free Software Foundation, Fifth Floor, 51 Franklin Street, Boston, -- MA 02111-1301, USA. function recenter (wp) local pt = window_pt (wp) if pt.n > wp.eheight / 2 then wp.topdelta = wp.eheight / 2 else wp.topdelta = pt.n end end Defun ("recenter", {}, [[ Center point in window and redisplay screen. The desired position of point is always relative to the current window. ]], true, function () recenter (cur_wp) term_full_redisplay () return leT end ) function resize_windows () local wp -- Resize windows horizontally. for _, wp in ipairs (windows) do wp.fwidth = term_width () wp.ewidth = wp.fwidth end -- Work out difference in window height; windows may be taller than -- terminal if the terminal was very short. local hdelta = term_height () - 1 for _, wp in ipairs (windows) do hdelta = hdelta - wp.fheight end -- Resize windows vertically. if hdelta > 0 then -- Increase windows height. local w = #windows while hdelta > 0 do windows[w].fheight = windows[w].fheight + 1 windows[w].eheight = windows[w].eheight + 1 hdelta = hdelta - 1 w = w - 1 if w == 0 then w = #windows end end else -- Decrease windows' height, and close windows if necessary. local decreased repeat local w = #windows decreased = false while w > 0 and hdelta < 0 do local wp = windows[w] if wp.fheight > 2 then wp.fheight = wp.fheight - 1 wp.eheight = wp.eheight - 1 hdelta = hdelta + 1 decreased = true elseif #windows > 1 then delete_window (wp) w = w - 1 decreased = true end end until decreased == false end execute_function ("recenter") end function resync_redisplay (wp) local delta = wp.bp.pt.n - wp.lastpointn if delta ~= 0 then if (delta > 0 and wp.topdelta + delta < wp.eheight) or (delta < 0 and wp.topdelta >= -delta) then wp.topdelta = wp.topdelta + delta elseif wp.bp.pt.n > wp.eheight / 2 then wp.topdelta = math.floor (wp.eheight / 2) else wp.topdelta = wp.bp.pt.n end end wp.lastpointn = wp.bp.pt.n end
gpl-3.0
moomoomoo309/FamiliarFaces
src/pl/url.lua
4
1028
--- Python-style URL quoting library. -- -- @module pl.url local url = {} local function quote_char(c) return string.format("%%%02X", string.byte(c)) end --- Quote the url, replacing special characters using the '%xx' escape. -- @string s the string -- @bool quote_plus Also escape slashes and replace spaces by plus signs. function url.quote(s, quote_plus) if type(s) ~= "string" then return s end s = s:gsub("\n", "\r\n") s = s:gsub("([^A-Za-z0-9 %-_%./])", quote_char) if quote_plus then s = s:gsub(" ", "+") s = s:gsub("/", quote_char) else s = s:gsub(" ", "%%20") end return s end local function unquote_char(h) return string.char(tonumber(h, 16)) end --- Unquote the url, replacing '%xx' escapes and plus signs. -- @string s the string function url.unquote(s) if type(s) ~= "string" then return s end s = s:gsub("+", " ") s = s:gsub("%%(%x%x)", unquote_char) s = s:gsub("\r\n", "\n") return s end return url
mit
thedraked/darkstar
scripts/zones/Southern_San_dOria_[S]/npcs/Nembet.lua
14
1024
----------------------------------- -- Area: Southern SandOria [S] -- NPC: Nembet -- @zone 80 -- @pos 147 -3 110 ----------------------------------- package.loaded["scripts/zones/Southern_San_dOria_[S]/TextIDs"] = nil; require("scripts/zones/Southern_San_dOria_[S]/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc, ITEM_DELIVERY_DIALOG); player:openSendBox(); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
alalazo/wesnoth
data/campaigns/tutorial/lua/character_selection.lua
2
2233
-- #textdomain wesnoth-tutorial -- Allows the player to choose whether they want to play Konrad or Li’sar -- for the tutorial local helper = wesnoth.require "helper" local T = helper.set_wml_tag_metatable {} local wml_actions = wesnoth.wml_actions local _ = wesnoth.textdomain "wesnoth-tutorial" function wml_actions.select_character() local character_selection_dialog = { maximum_height = 250, maximum_width = 400, T.helptip { id="tooltip_large" }, -- mandatory field T.tooltip { id="tooltip_large" }, -- mandatory field T.grid { T.row { T.column { grow_factor = 1, border = "all", border_size = 5, horizontal_alignment = "left", T.label { definition = "title", label = _"Select Character" } } }, T.row { T.column { grow_factor = 1, border = "all", border_size = 5, horizontal_alignment = "left", T.label { label = _"Who do you want to play?" } } }, T.row { T.column { T.grid { T.row { T.column { grow_factor = 1, border = "all", border_size = 5, T.image { label = "units/konrad-fighter.png" } }, T.column { grow_factor = 1, border = "all", border_size = 5, T.image { label = "units/human-princess.png~TC(1,magenta)" } } }, T.row { T.column { grow_factor = 1, border = "all", border_size = 5, T.button { label = _"Konrad", return_value = 1 } }, T.column { grow_factor = 1, border = "all", border_size = 5, T.button { label = _"Li’sar", return_value = 2 } } } } } } } } local character = wesnoth.show_dialog(character_selection_dialog) local unit = wesnoth.get_variable("student_store") if character == 2 then wesnoth.put_unit({ type = "Fighteress", id = unit.id, name = _"Li’sar", unrenamable = true, profile = "portraits/lisar.png", canrecruit = true, facing = unit.facing, }, unit.x, unit.y ) else wesnoth.put_unit(unit) end wesnoth.redraw {} end
gpl-2.0
Devul/DarkRP
gamemode/modules/f1menu/cl_htmlcontrols.lua
12
3854
surface.CreateFont("F1AddressBar", { size = 14, weight = 400, antialias = true, shadow = false, font = "Coolvetica"}) local PANEL = {} -- Remove any Javascript warnings function PANEL:ConsoleMessage() end function PANEL:Init() self.BaseClass.Init(self) self.history = {} self.currentIndex = 0 self:AddFunction("darkrp", "urlLoaded", function(url) self:urlLoaded(url) end) end function PANEL:Think() self.BaseClass.Think(self) if self.loaded and self:IsLoading() then self.loaded = false elseif not self.loaded and not self:IsLoading() then self.loaded = true self:QueueJavascript([[darkrp.urlLoaded(document.location.href)]]) end end function PANEL:OpenURL(url, noHistory) self.noHistory = noHistory == nil and false or noHistory self.BaseClass.OpenURL(self, url) end function PANEL:urlLoaded(url) if not self.noHistory and self.history[self.currentIndex] ~= url then if #self.history > self.currentIndex then for i = self.currentIndex + 1, #self.history, 1 do self.history[i] = nil end end self.currentIndex = self.currentIndex + 1 self.history[self.currentIndex] = url end self.noHistory = false self.URL = url end function PANEL:HTMLBack() if self.currentIndex <= 1 then return end self.currentIndex = self.currentIndex - 1 self:OpenURL(self.history[self.currentIndex], true) end function PANEL:HTMLForward() if self.currentIndex >= #self.history then return end self.currentIndex = self.currentIndex + 1 self:OpenURL(self.history[self.currentIndex], true) end function PANEL:Refresh() if not self.URL then return end -- refreshed before the URL is set self:OpenURL(self.URL, true) end derma.DefineControl("F1HTML", "HTML Derma is fucking broken. Let's fix that.", PANEL, "DHTML") PANEL = {} function PANEL:Init() self.BackButton:SetDisabled(true) self.ForwardButton:SetDisabled(true) self.RefreshButton:SetDisabled(true) self.HomeButton:SetDisabled(true) self.StopButton:Remove() self.AddressBar:DockMargin(0, 6, 6, 6) self.AddressBar:SetFont("F1AddressBar") self.AddressBar:SetTextColor(Color(255, 255, 255, 255)) self.AddressBar:SetDisabled(true) self.AddressBar:SetEditable(false) end function PANEL:Think() if self.HTML and self.htmlLoaded and self.HTML:IsLoading() then self.htmlLoaded = false self:StartedLoading() elseif self.HTML and not self.htmlLoaded and not self.HTML:IsLoading() then self.htmlLoaded = true end end function PANEL:SetHTML(html) local oldOpeningURL = html.OpeningURL local oldFinishedURL = html.FinishedURL self.BaseClass.SetHTML(self, html) self.HTML.OpeningURL = oldOpeningURL self.HTML.FinishedURL = oldFinishedURL local oldUrlLoaded = self.HTML.urlLoaded self.HTML.urlLoaded = function(panel, url) if oldUrlLoaded then oldUrlLoaded(panel, url) end self.AddressBar:SetText(DarkRP.deLocalise(url)) self:FinishedLoading() end end function PANEL:StartedLoading() self.BackButton:SetDisabled(true) self.ForwardButton:SetDisabled(true) self.RefreshButton:SetDisabled(true) self.HomeButton:SetDisabled(true) end function PANEL:FinishedLoading() self.RefreshButton:SetDisabled(false) self.HomeButton:SetDisabled(false) self:UpdateNavButtonStatus() end function PANEL:UpdateHistory(url) -- Do nothing. end function PANEL:UpdateNavButtonStatus() self.BackButton:SetDisabled(self.HTML.currentIndex <= 1) self.ForwardButton:SetDisabled(self.HTML.currentIndex >= #self.HTML.history) end derma.DefineControl("F1HTMLControls", "HTML Derma is fucking broken. Let's fix that.", PANEL, "DHTMLControls")
mit
NPLPackages/main
script/ide/Display/Util/ObjectsCreator.lua
1
3704
--[[ Title: ObjectsCreator Author(s): Leio Date: 2009/1/22 Desc: use the lib: ------------------------------------------------------------ NPL.load("(gl)script/ide/Display/Util/ObjectsCreator.lua"); ------------------------------------------------------------ ]] NPL.load("(gl)script/ide/Display/InteractiveObject.lua"); local ObjectsCreator = { } commonlib.setfield("CommonCtrl.Display.Util.ObjectsCreator",ObjectsCreator); function ObjectsCreator.CreateObjectByParams(classType,params) local obj; if(classType == "ZoneNode" or classType == "PortalNode")then local name = params.name; local w,h,d,facing = params.width,params.height,params.depth,params.facing; if(classType == "ZoneNode")then local zoneplanes = params.zoneplanes; obj = ParaScene.CreateZone(name,zoneplanes,w,h,d,facing); else local homezone = params.homezone; local targetzone = params.targetzone; local portalpoints = params.portalpoints; obj = ParaScene.CreatePortal(name,homezone,targetzone,portalpoints,w,h,d,facing); end else obj = ObjEditor.CreateObjectByParams(params) end --if(classType == "Actor3D" or classType == "Building3D" or classType == "Flower")then --obj = ObjEditor.CreateObjectByParams(params) --elseif(classType == "ZoneNode" or classType == "PortalNode")then --local name = params.name; --local w,h,d,facing = params.width,params.height,params.depth,params.facing; --if(classType == "ZoneNode")then --local zoneplanes = params.zoneplanes; --obj = ParaScene.CreateZone(name,zoneplanes,w,h,d,facing); --else --local homezone = params.homezone; --local targetzone = params.targetzone; --local portalpoints = params.portalpoints; --obj = ParaScene.CreatePortal(name,homezone,targetzone,portalpoints,w,h,d,facing); --end --end return obj; end -- pos_x, pos_y,pos_z: is the point at the bottom center of the box. -- obb_x,obb_y,obb_z: is the size of the box. -- column:true ¼ì²âÈýά false ¼ì²â¶þά£¬Ä¬ÈÏΪfalse function ObjectsCreator.Contains(point,box,column) if(not point or not box)then return end local dx = box.obb_x/2; local dy = box.obb_y; local dz = box.obb_z/2; local min_x = box.pos_x - dx; local min_y = box.pos_y - dy; local min_z = box.pos_z - dz; local max_x = box.pos_x + dx; local max_y = box.pos_y + dy; local max_z = box.pos_z + dz; if(column)then if(point.x >= min_x and point.y >= min_y and point.z >= min_z and point.x <= max_x and point.y <= max_y and point.z <= max_z)then return true; end else if(point.x >= min_x and point.z >= min_z and point.x <= max_x and point.z <= max_z)then return true; end end end function ObjectsCreator.HitTest(box1,box2,column) if(not box1 or not box2)then return end box1 = ObjectsCreator.GetRect(box1); box2 = ObjectsCreator.GetRect(box2); if(math.abs(box1.min_x + box1.max_x - box2.min_x - box2.max_x) < (box1.max_x - box1.min_x + box2.max_x - box2.min_x))then if(math.abs(box1.min_z + box1.max_z - box2.min_z - box2.max_z) < (box1.max_z - box1.min_z + box2.max_z - box2.min_z))then if(column)then if(math.abs(box1.min_y + box1.max_y - box2.min_y - box2.max_y) < (box1.max_y - box1.min_y + box2.max_y - box2.min_y))then return true; end else return true; end end end end function ObjectsCreator.GetRect(box) if(not box)then return end local dx = box.obb_x/2; local dy = box.obb_y; local dz = box.obb_z/2; local min_x = box.pos_x - dx; local min_y = box.pos_y; local min_z = box.pos_z - dz; local max_x = box.pos_x + dx; local max_y = box.pos_y + dy; local max_z = box.pos_z + dz; return { min_x = min_x, min_y = min_y, min_z = min_z, max_x = max_x, max_y = max_y, max_z = max_z, } end
gpl-2.0
pexcn/openwrt
extra-master/packages/mwan3-luci/files/usr/lib/lua/luci/model/cbi/mwan3/mwan3_interface.lua
9
9177
-- ------ extra functions ------ -- function iface_check() -- find issues with too many interfaces, reliability and metric uci.cursor():foreach("mwan3", "interface", function (section) local ifname = section[".name"] ifnum = ifnum+1 -- count number of mwan3 interfaces configured -- create list of metrics for none and duplicate checking local metlkp = ut.trim(sys.exec("uci get -p /var/state network." .. ifname .. ".metric")) if metlkp == "" then err_found = 1 err_nomet_list = err_nomet_list .. ifname .. " " else metric_list = metric_list .. ifname .. " " .. metlkp .. "\n" end -- check if any interfaces have a higher reliability requirement than tracking IPs configured local tipnum = tonumber(ut.trim(sys.exec("echo $(uci get -p /var/state mwan3." .. ifname .. ".track_ip) | wc -w"))) if tipnum > 0 then local relnum = tonumber(ut.trim(sys.exec("uci get -p /var/state mwan3." .. ifname .. ".reliability"))) if relnum and relnum > tipnum then err_found = 1 err_rel_list = err_rel_list .. ifname .. " " end end -- check if any interfaces are not properly configured in /etc/config/network or have no default route in main routing table if ut.trim(sys.exec("uci get -p /var/state network." .. ifname)) == "interface" then local ifdev = ut.trim(sys.exec("uci get -p /var/state network." .. ifname .. ".ifname")) if ifdev == "uci: Entry not found" or ifdev == "" then err_found = 1 err_netcfg_list = err_netcfg_list .. ifname .. " " err_route_list = err_route_list .. ifname .. " " else local rtcheck = ut.trim(sys.exec("route -n | awk -F' ' '{ if ($8 == \"" .. ifdev .. "\" && $1 == \"0.0.0.0\") print $1 }'")) if rtcheck == "" then err_found = 1 err_route_list = err_route_list .. ifname .. " " end end else err_found = 1 err_netcfg_list = err_netcfg_list .. ifname .. " " err_route_list = err_route_list .. ifname .. " " end end ) -- check if any interfaces have duplicate metrics local metric_dupnums = sys.exec("echo '" .. metric_list .. "' | awk -F' ' '{ print $2 }' | uniq -d") if metric_dupnums ~= "" then err_found = 1 local metric_dupes = "" for line in metric_dupnums:gmatch("[^\r\n]+") do metric_dupes = sys.exec("echo '" .. metric_list .. "' | grep '" .. line .. "' | awk -F' ' '{ print $1 }'") err_dupmet_list = err_dupmet_list .. metric_dupes end err_dupmet_list = sys.exec("echo '" .. err_dupmet_list .. "' | tr '\n' ' '") end end function iface_warn() -- display status and warning messages at the top of the page local warns = "" if ifnum <= 250 then warns = "<strong>There are currently " .. ifnum .. " of 250 supported interfaces configured</strong>" else warns = "<font color=\"ff0000\"><strong>WARNING: " .. ifnum .. " interfaces are configured exceeding the maximum of 250!</strong></font>" end if err_rel_list ~= " " then warns = warns .. "<br /><br /><font color=\"ff0000\"><strong>WARNING: some interfaces have a higher reliability requirement than there are tracking IP addresses!</strong></font>" end if err_route_list ~= " " then warns = warns .. "<br /><br /><font color=\"ff0000\"><strong>WARNING: some interfaces have no default route in the main routing table!</strong></font>" end if err_netcfg_list ~= " " then warns = warns .. "<br /><br /><font color=\"ff0000\"><strong>WARNING: some interfaces are configured incorrectly or not at all in /etc/config/network!</strong></font>" end if err_nomet_list ~= " " then warns = warns .. "<br /><br /><font color=\"ff0000\"><strong>WARNING: some interfaces have no metric configured in /etc/config/network!</strong></font>" end if err_dupmet_list ~= " " then warns = warns .. "<br /><br /><font color=\"ff0000\"><strong>WARNING: some interfaces have duplicate metrics configured in /etc/config/network!</strong></font>" end return warns end -- ------ interface configuration ------ -- dsp = require "luci.dispatcher" sys = require "luci.sys" ut = require "luci.util" ifnum = 0 metric_list = "" err_found = 0 err_dupmet_list = " " err_netcfg_list = " " err_nomet_list = " " err_rel_list = " " err_route_list = " " iface_check() m5 = Map("mwan3", translate("MWAN3 Multi-WAN Interface Configuration"), translate(iface_warn())) m5:append(Template("mwan3/mwan3_config_css")) mwan_interface = m5:section(TypedSection, "interface", translate("Interfaces"), translate("MWAN3 supports up to 250 physical and/or logical interfaces<br />" .. "MWAN3 requires that all interfaces have a unique metric configured in /etc/config/network<br />" .. "Names must match the interface name found in /etc/config/network (see advanced tab)<br />" .. "Names may contain characters A-Z, a-z, 0-9, _ and no spaces<br />" .. "Interfaces may not share the same name as configured members, policies or rules")) mwan_interface.addremove = true mwan_interface.dynamic = false mwan_interface.sectionhead = "Interface" mwan_interface.sortable = true mwan_interface.template = "cbi/tblsection" mwan_interface.extedit = dsp.build_url("admin", "network", "mwan3", "configuration", "interface", "%s") function mwan_interface.create(self, section) TypedSection.create(self, section) m5.uci:save("mwan3") luci.http.redirect(dsp.build_url("admin", "network", "mwan3", "configuration", "interface", section)) end enabled = mwan_interface:option(DummyValue, "enabled", translate("Enabled")) enabled.rawhtml = true function enabled.cfgvalue(self, s) if self.map:get(s, "enabled") == "1" then return "Yes" else return "No" end end track_ip = mwan_interface:option(DummyValue, "track_ip", translate("Tracking IP")) track_ip.rawhtml = true function track_ip.cfgvalue(self, s) local str = "" tracked = self.map:get(s, "track_ip") if tracked then for k,v in pairs(tracked) do str = str .. v .. "<br />" end return str else return "&#8212;" end end reliability = mwan_interface:option(DummyValue, "reliability", translate("Tracking reliability")) reliability.rawhtml = true function reliability.cfgvalue(self, s) if tracked then return self.map:get(s, "reliability") or "&#8212;" else return "&#8212;" end end count = mwan_interface:option(DummyValue, "count", translate("Ping count")) count.rawhtml = true function count.cfgvalue(self, s) if tracked then return self.map:get(s, "count") or "&#8212;" else return "&#8212;" end end timeout = mwan_interface:option(DummyValue, "timeout", translate("Ping timeout")) timeout.rawhtml = true function timeout.cfgvalue(self, s) if tracked then local tcheck = self.map:get(s, "timeout") if tcheck then return tcheck .. "s" else return "&#8212;" end else return "&#8212;" end end interval = mwan_interface:option(DummyValue, "interval", translate("Ping interval")) interval.rawhtml = true function interval.cfgvalue(self, s) if tracked then local icheck = self.map:get(s, "interval") if icheck then return icheck .. "s" else return "&#8212;" end else return "&#8212;" end end down = mwan_interface:option(DummyValue, "down", translate("Interface down")) down.rawhtml = true function down.cfgvalue(self, s) if tracked then return self.map:get(s, "down") or "&#8212;" else return "&#8212;" end end up = mwan_interface:option(DummyValue, "up", translate("Interface up")) up.rawhtml = true function up.cfgvalue(self, s) if tracked then return self.map:get(s, "up") or "&#8212;" else return "&#8212;" end end metric = mwan_interface:option(DummyValue, "metric", translate("Metric")) metric.rawhtml = true function metric.cfgvalue(self, s) local metcheck = sys.exec("uci get -p /var/state network." .. s .. ".metric") if metcheck ~= "" then return metcheck else return "&#8212;" end end errors = mwan_interface:option(DummyValue, "errors", translate("Errors")) errors.rawhtml = true function errors.cfgvalue(self, s) if err_found == 1 then local mouseover, linebrk = "", "" if string.find(err_rel_list, " " .. s .. " ") then mouseover = "Higher reliability requirement than there are tracking IP addresses" linebrk = "&#10;&#10;" end if string.find(err_route_list, " " .. s .. " ") then mouseover = mouseover .. linebrk .. "No default route in the main routing table" linebrk = "&#10;&#10;" end if string.find(err_netcfg_list, " " .. s .. " ") then mouseover = mouseover .. linebrk .. "Configured incorrectly or not at all in /etc/config/network" linebrk = "&#10;&#10;" end if string.find(err_nomet_list, " " .. s .. " ") then mouseover = mouseover .. linebrk .. "No metric configured in /etc/config/network" linebrk = "&#10;&#10;" end if string.find(err_dupmet_list, " " .. s .. " ") then mouseover = mouseover .. linebrk .. "Duplicate metric configured in /etc/config/network" end if mouseover == "" then return "" else return "<span title=\"" .. mouseover .. "\"><img src=\"/luci-static/resources/cbi/reset.gif\" alt=\"error\"></img></span>" end else return "" end end return m5
gpl-2.0
thedraked/darkstar
scripts/zones/Northern_San_dOria/npcs/Macuillie.lua
11
2571
----------------------------------- -- Area: Northern San d'Oria -- NPC: Macuillie -- Type: Guildworker's Union Representative -- @zone 231 -- @pos -191.738 11.001 138.656 ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; require("scripts/globals/keyitems"); require("scripts/globals/crafting"); require("scripts/zones/Northern_San_dOria/TextIDs"); local keyitems = { [0] = { id = METAL_PURIFICATION, rank = 3, cost = 40000 }, [1] = { id = METAL_ENSORCELLMENT, rank = 3, cost = 40000 }, [2] = { id = CHAINWORK, rank = 3, cost = 10000 }, [3] = { id = SHEETING, rank = 3, cost = 10000 }, [4] = { id = WAY_OF_THE_BLACKSMITH, rank = 9, cost = 20000 } }; local items = { [2] = { id = 15445, rank = 3, cost = 10000 }, [3] = { id = 14831, rank = 5, cost = 70000 }, [4] = { id = 14393, rank = 7, cost = 100000 }, [5] = { id = 153, rank = 9, cost = 150000 }, [6] = { id = 334, rank = 9, cost = 200000 }, [7] = { id = 15820, rank = 6, cost = 80000 }, [8] = { id = 3661, rank = 7, cost = 50000 }, [9] = { id = 3324, rank = 9, cost = 15000 } }; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) unionRepresentativeTrade(player, npc, trade, 0x02da, 2); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) unionRepresentativeTrigger(player, 2, 0x02d9, "guild_smithing", keyitems); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option,target) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x02d9) then unionRepresentativeTriggerFinish(player, option, target, 2, "guild_smithing", keyitems, items); elseif (csid == 0x02da) then player:messageSpecial(GP_OBTAINED, option); end end;
gpl-3.0
mtroyka/Zero-K
LuaRules/Gadgets/CAI/astar.lua
9
7268
--------------------------------------------------------------------- --[[ author: quantum GPL v2 or later http://www.policyalmanac.org/games/aStarTutorial.htm http://en.wikipedia.org/wiki/A*_search_algorithm use: override IsBlocked, GetDistance, etc and run aStar.GetPath -- example -------------------------------- local aStar = dofile"astar.lua" aStar.gridHeight = 250 aStar.gridWidth = 250 aStar.IsBlocked = local function(id) return false end function aStar.GetDistanceEstimate(a, b) -- heuristic estimate of distance to goal local x1, y1 = aStar.ToCoords(a) local x2, y2 = aStar.ToCoords(b) return math.max(math.abs(x2-x1), math.abs(y2-y1)) + math.min(math.abs(x2-x1), math.abs(y2-y1))/2*1.001 end function aStar.GetDistance(a, b) -- distance between two directly connected nodes (squares if in a grid) local x1, y1 = aStar.ToCoords(a) local x2, y2 = aStar.ToCoords(b) if x1 == x2 or y1 == y2 then return 1 else return 2^0.5 end end local startID = aStar.ToID{1, 1} local goalID = aStar.ToID{80, 90} local path = aStar.GetPath(startID, goalID) ]] --------------------------------------------------------------------- --------------------------------------------------------------------- local function GetSetCount(set) local count = 0 for _ in pairs(set) do count = count + 1 end return count end local function ReconstructPath(parents, node) local path = {} repeat path[#path + 1] = node node = parents[node] until not node -- reverse it local x, y, temp = 1, #path while x < y do temp = path[x] path[x] = path[y] path[y] = temp x, y = x + 1, y - 1 end return path end local aStar = { -- set grid size gridWidth = 250, gridHeight = 250, } function aStar.NewPriorityQueue() local heap = {} -- binary heap local priorities = {} local heapCount = 0 function heap.Insert(currentKey, currentPriority, currentPosition) if not currentPosition then -- we are inserting a new item, as opposed to changing the f value of an item already in the heap currentPosition = heapCount + 1 heapCount = heapCount + 1 end priorities[currentKey] = currentPriority heap[currentPosition] = currentKey while true do local parentPosition = math.floor(currentPosition/2) if parentPosition == 1 then break end local parentKey = heap[parentPosition] if parentKey and priorities[parentKey] > currentPriority then -- swap parent and current node heap[parentPosition] = currentKey heap[currentPosition] = parentKey currentPosition = parentPosition else break end end end function heap.UpdateNode(currentKey, currentPriority) for position=1, heapCount do local id = heap[position] if id == currentKey then heap.Insert(currentKey, currentPriority, position) break end end end function heap.Pop() local ret = heap[1] if not ret then error "queue is empty" end heap[1] = heap[heapCount] heap[heapCount] = nil heapCount = heapCount - 1 local currentPosition = 1 while true do local currentKey = heap[currentPosition] local currentPriority = priorities[currentKey] local child1Position = currentPosition*2 local child1Key = heap[child1Position] if not child1Key then break end local child2Position = currentPosition*2 + 1 local child2Key = heap[child2Position] if not child2Key then break end local child1F = priorities[child1Key] local child2F = priorities[child2Key] if currentPriority < child1F and currentPriority < child2F then break elseif child1F < child2F then heap[child1Position] = currentKey heap[currentPosition] = child1Key currentPosition = child1Position else heap[child2Position] = currentKey heap[currentPosition] = child2Key currentPosition = child2Position end end return ret, priorities[ret] end return heap end function aStar.ToID(coords) -- override this local function if necessary, converts grid coords to node id local x, y = coords[1], coords[2] return y * aStar.gridWidth + x end function aStar.ToCoords(id) -- override this local function if necessary, converts node id to grid coords return id % aStar.gridWidth, math.floor(id/aStar.gridWidth) end function aStar.GetDistance(a, b) -- override this local function, exact distance beween adjacent nodes a and b error"override this local function" end function aStar.IsBlocked(id) error"override this local function" end function aStar.GetNeighbors(id, goal) -- override this if the nodes are not arranged in a grid local x, y = aStar.ToCoords(id) local nodes = { aStar.ToID{x-1, y}, aStar.ToID{x, y-1}, aStar.ToID{x+1, y}, aStar.ToID{x, y+1}, aStar.ToID{x-1, y-1}, aStar.ToID{x-1, y+1}, aStar.ToID{x+1, y+1}, aStar.ToID{x+1, y-1} } local passable = {} local passableCount = 0 for nodeIndex=1, 8 do local node = nodes[nodeIndex] if not aStar.IsBlocked(node) then passableCount = passableCount + 1 passable[passableCount] = node end end return passable end function aStar.GetDistanceEstimate(a, b) -- heuristic estimate of distance to goal error"override this local function" end function aStar.GetPathsThreaded(startID, goalID, cyclesBeforeYield) cyclesBeforeYield = cyclesBeforeYield or 1000 return coroutine.create(aStar.GetPath) end function aStar.GetPath(startID, goalID, cyclesBeforeYield) local parents = {} local gScores = {} -- distance from start along optimal path local closedSet = {} -- nodes already evaluated local openHeap = aStar.NewPriorityQueue() -- binary heap of nodes by f score gScores[startID] = 0 openHeap.Insert(startID, aStar.GetDistanceEstimate(startID, goalID)) local cyclesFromLastYield = 0 local cycleCounter = 0 while openHeap[1] do -- threading cycleCounter = cycleCounter + 1 if cyclesBeforeYield then cyclesFromLastYield = cyclesFromLastYield + 1 if cyclesFromLastYield > cyclesBeforeYield then cyclesFromLastYield= 0 coroutine.yield(cycleCounter) end end local currentNode = openHeap.Pop() if currentNode == goalID then -- goal reached return ReconstructPath(parents, currentNode), closedSet end closedSet[currentNode] = true for _, neighbor in ipairs(aStar.GetNeighbors(currentNode)) do if not closedSet[neighbor] then local tentativeGScore = gScores[currentNode] + aStar.GetDistance(currentNode, neighbor) if not gScores[neighbor] then parents[neighbor] = currentNode gScores[neighbor] = tentativeGScore openHeap.Insert(neighbor, gScores[neighbor] + aStar.GetDistanceEstimate(neighbor, goalID)) elseif tentativeGScore < gScores[neighbor] then parents[neighbor] = currentNode gScores[neighbor] = tentativeGScore openHeap.UpdateNode(neighbor, gScores[neighbor] + aStar.GetDistanceEstimate(neighbor, goalID)) end end end end return false end return aStar
gpl-2.0
thedraked/darkstar
scripts/zones/Port_Windurst/npcs/Ada.lua
14
1043
----------------------------------- -- Area: Port Windurst -- NPC: Ada -- Type: Standard NPC -- @zone 240 -- @pos -79.803 -6.75 168.652 -- -- Auto-Script: Requires Verification (Verfied by Brawndo) ----------------------------------- package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x002c); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
thedraked/darkstar
scripts/zones/Dynamis-Buburimu/mobs/Serjeant_Tombstone.lua
22
1228
----------------------------------- -- Area: Dynamis Buburimu -- MOB: Serjeant_Tombstone ----------------------------------- package.loaded["scripts/zones/Dynamis-Buburimu/TextIDs"] = nil; ----------------------------------- require("scripts/globals/dynamis"); require("scripts/zones/Dynamis-Buburimu/TextIDs"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) mob:setMobMod(MOBMOD_SUPERLINK, mob:getShortID()); end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) dynamis.spawnGroup(mob, BuburimuOrcishList); end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, player, isKiller) local mobID = mob:getID(); if ( mobID == 16941135 or mobID == 16941411) then --hp player:messageBasic(024,(player:getMaxHP()-player:getHP())); player:restoreHP(3000); elseif (mobID == 16941137 or mobID == 16941412) then --mp player:messageBasic(025,(player:getMaxMP()-player:getMP())); player:restoreMP(3000); end end;
gpl-3.0
lipp/zbus
zbus/socket.lua
1
7564
local ev = require'ev' local socket = require'socket' require'pack' local print = print local pairs = pairs local tinsert = table.insert local tconcat = table.concat local ipairs = ipairs local assert = assert local spack = string.pack local error = error local log = print module('zbus.socket') local wrap_sync = function(sock) if not sock then error('can not wrap nil socket') end return { receive_message = function(_) local parts = {} while true do local header,err = sock:receive(4) if err then error('could not read header:'..err) end local _,bytes = header:unpack('>I') if bytes == 0 then break end local part = sock:receive(bytes) assert(part) tinsert(parts,part) end -- print('RECV',#parts,tconcat(parts)) return parts end, send_message = function(_,parts) local message = '' for i,part in ipairs(parts) do local len = #part assert(len>0) message = message..spack('>I',len)..part end message = message..spack('>I',0) sock:send(message) end, getfd = function() return sock:getfd() end, close = function() sock:shutdown() sock:close() end } end local wrap_async = function(sock) if not sock then error('can not wrap nil socket') end sock:settimeout(0) sock:setoption('tcp-nodelay',true) local on_message = function() end local on_close = function() end local wrapped = {} wrapped.send_message = function(_,parts) -- assert(#parts>0) -- print('SND',#parts,tconcat(parts)) local message = '' for i,part in ipairs(parts) do message = message..spack('>I',#part)..part end message = message..spack('>I',0) local len = #message assert(len>0) local pos = 1 local fd = sock:getfd() assert(fd > -1) ev.IO.new( function(loop,write_io) while pos < len do local err pos,err = sock:send(message,pos) if not pos then if err == 'timeout' then return elseif err == 'closed' then write_io:stop(loop) sock:shutdown() sock:close() return end end end write_io:stop(loop) end, fd, ev.WRITE ):start(ev.Loop.default) end wrapped.on_close = function(_,f) on_close = f end wrapped.on_message = function(_,f) on_message = f end wrapped.close = function() sock:shutdown() sock:close() -- sock = nil end wrapped.read_io = function() local parts = {} local part local left local length local header local _ local fd = sock:getfd() assert(fd > -1) return ev.IO.new( function(loop,read_io) while true do if not header or #header < 4 then local err,sub header,err,sub = sock:receive(4,header) if err then if err == 'timeout' then header = sub return else if err ~= 'closed' then log('ERROR','unknown socket error',err) end read_io:stop(loop) sock:shutdown() sock:close() on_close(wrapped) return end end if #header == 4 then _,left = header:unpack('>I') if left == 0 then -- print('on message',#parts,tconcat(parts)) on_message(parts,wrapped) parts = {} part = nil left = nil length = nil header = nil else length = left end end end if length then if not part or #part ~= length then local err,sub part,err,sub = sock:receive(length,part) if err then if err == 'timeout' then part = sub left = length - #part return else if err ~= 'closed' then log('ERROR','unknown socket error',err) end read_io:stop(loop) sock:shutdown() sock:close() on_close(wrapped) return end end if #part == length then tinsert(parts,part) part = nil left = nil length = nil header = nil end end end -- if length end -- while end, fd, ev.READ) end return wrapped end local listener = function(port,on_connect) local sock = assert(socket.bind('*',port)) sock:settimeout(0) local fd = sock:getfd() assert(fd > -1) local listen_io = ev.IO.new( function(loop,accept_io) local client = assert(sock:accept()) local wrapped = wrap_async(client) wrapped:read_io():start(loop) on_connect(wrapped) end, fd, ev.READ) return { io = listen_io } end return { listener = listener, wrap_async = wrap_async, wrap_sync = wrap_sync }
mit
thedraked/darkstar
scripts/zones/The_Eldieme_Necropolis/npcs/_5f9.lua
12
1097
----------------------------------- -- Area: The Eldieme Necropolis -- NPC: Shiva's Gate -- @pos 270 -34 -60 195 ----------------------------------- package.loaded["scripts/zones/The_Eldieme_Necropolis/TextIDs"] = nil; ----------------------------------- require("scripts/zones/The_Eldieme_Necropolis/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (npc:getAnimation() == 9) then player:messageSpecial(SOLID_STONE); end return 0; end; -- ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
X-Coder/wire
lua/entities/gmod_wire_user.lua
9
1183
AddCSLuaFile() DEFINE_BASECLASS( "base_wire_entity" ) ENT.PrintName = "Wire User" ENT.RenderGroup = RENDERGROUP_BOTH ENT.WireDebugName = "User" function ENT:SetupDataTables() self:NetworkVar( "Float", 0, "BeamLength" ) end if CLIENT then return end -- No more client function ENT:Initialize() self:PhysicsInit( SOLID_VPHYSICS ) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid( SOLID_VPHYSICS ) self.Inputs = Wire_CreateInputs(self, { "Fire"}) self:Setup(2048) end function ENT:Setup(Range) if Range then self:SetBeamLength(Range) end end function ENT:TriggerInput(iname, value) if (iname == "Fire") then if (value ~= 0) then local vStart = self:GetPos() local trace = util.TraceLine( { start = vStart, endpos = vStart + (self:GetUp() * self:GetBeamLength()), filter = { self }, }) if not IsValid(trace.Entity) then return false end local ply = self:GetPlayer() if not IsValid(ply) then ply = self end if trace.Entity.Use then trace.Entity:Use(ply,ply,USE_ON,0) else trace.Entity:Fire("use","1",0) end end end end duplicator.RegisterEntityClass("gmod_wire_user", WireLib.MakeWireEnt, "Data", "Range")
gpl-3.0
stuta/Luajit-Tcp-Server
WTypes.lua
1
13256
local ffi = require"ffi" local bit = require"bit" local bnot = bit.bnot local band = bit.band local bor = bit.bor local lshift = bit.lshift local rshift = bit.rshift ffi.cdef[[ // Basic Data types typedef unsigned char BYTE; typedef long BOOL; typedef BYTE BOOLEAN; typedef char CHAR; typedef wchar_t WCHAR; typedef uint16_t WORD; typedef unsigned long DWORD; typedef uint32_t DWORD32; typedef int INT; typedef int32_t INT32; typedef int64_t INT64; typedef float FLOAT; typedef long LONG; typedef signed int LONG32; typedef int64_t LONGLONG; typedef size_t SIZE_T; typedef uint8_t BCHAR; typedef unsigned char UCHAR; typedef unsigned int UINT; typedef unsigned int UINT32; typedef unsigned long ULONG; typedef unsigned int ULONG32; typedef unsigned short USHORT; typedef uint64_t ULONGLONG; // Some pointer types typedef int * LPINT; typedef unsigned char *PBYTE; typedef char * PCHAR; typedef uint16_t * PWCHAR; typedef unsigned char *PBOOLEAN; typedef unsigned char *PUCHAR; typedef const unsigned char *PCUCHAR; typedef char * PSTR; typedef unsigned int *PUINT; typedef unsigned int *PUINT32; typedef unsigned long *PULONG; typedef unsigned int *PULONG32; typedef unsigned short *PUSHORT; typedef LONGLONG *PLONGLONG; typedef ULONGLONG *PULONGLONG; typedef void * PVOID; typedef DWORD * DWORD_PTR; typedef intptr_t LONG_PTR; typedef uintptr_t UINT_PTR; typedef uintptr_t ULONG_PTR; typedef ULONG_PTR * PULONG_PTR; typedef DWORD * LPCOLORREF; typedef BOOL * LPBOOL; typedef char * LPSTR; typedef short * LPWSTR; typedef short * PWSTR; typedef const short * LPCWSTR; typedef const short * PCWSTR; typedef LPSTR LPTSTR; typedef DWORD * LPDWORD; typedef void * LPVOID; typedef WORD * LPWORD; typedef const char * LPCSTR; typedef const char * PCSTR; typedef LPCSTR LPCTSTR; typedef const void * LPCVOID; typedef LONG_PTR LRESULT; typedef LONG_PTR LPARAM; typedef UINT_PTR WPARAM; typedef unsigned char TBYTE; typedef char TCHAR; typedef USHORT COLOR16; typedef DWORD COLORREF; // Special types typedef WORD ATOM; typedef DWORD LCID; typedef USHORT LANGID; // Various Handles typedef void * HANDLE; typedef HANDLE *PHANDLE; typedef HANDLE LPHANDLE; typedef void * HBITMAP; typedef void * HBRUSH; typedef void * HICON; typedef HICON HCURSOR; typedef HANDLE HDC; typedef void * HDESK; typedef HANDLE HDROP; typedef HANDLE HDWP; typedef HANDLE HENHMETAFILE; typedef INT HFILE; typedef HANDLE HFONT; typedef void * HGDIOBJ; typedef HANDLE HGLOBAL; typedef HANDLE HGLRC; typedef HANDLE HHOOK; typedef void * HINSTANCE; typedef void * HKEY; typedef void * HKL; typedef HANDLE HLOCAL; typedef void * HMEMF; typedef HANDLE HMENU; typedef HANDLE HMETAFILE; typedef void HMF; typedef HINSTANCE HMODULE; typedef HANDLE HMONITOR; typedef HANDLE HPALETTE; typedef void * HPEN; typedef LONG HRESULT; typedef HANDLE HRGN; typedef void * HRSRC; typedef void * HSTR; typedef HANDLE HSZ; typedef void * HTASK; typedef void * HWINSTA; typedef HANDLE HWND; // Ole Automation typedef WCHAR OLECHAR; typedef OLECHAR *LPOLESTR; typedef const OLECHAR *LPCOLESTR; //typedef char OLECHAR; //typedef LPSTR LPOLESTR; //typedef LPCSTR LPCOLESTR; typedef OLECHAR *BSTR; typedef BSTR *LPBSTR; typedef DWORD ACCESS_MASK; typedef ACCESS_MASK* PACCESS_MASK; typedef LONG FXPT16DOT16, *LPFXPT16DOT16; typedef LONG FXPT2DOT30, *LPFXPT2DOT30; ]] require "guiddef" ffi.cdef[[ typedef union _LARGE_INTEGER { struct { DWORD LowPart; LONG HighPart; }; struct { DWORD LowPart; LONG HighPart; } u; LONGLONG QuadPart; } LARGE_INTEGER, *PLARGE_INTEGER; typedef struct _ULARGE_INTEGER { ULONGLONG QuadPart; } ULARGE_INTEGER; typedef struct _FILETIME { DWORD dwLowDateTime; DWORD dwHighDateTime; } FILETIME; typedef struct _FILETIME *PFILETIME; typedef struct _FILETIME *LPFILETIME; typedef struct _SYSTEMTIME { WORD wYear; WORD wMonth; WORD wDayOfWeek; WORD wDay; WORD wHour; WORD wMinute; WORD wSecond; WORD wMilliseconds; } SYSTEMTIME, *PSYSTEMTIME, *LPSYSTEMTIME; typedef struct _SECURITY_ATTRIBUTES { DWORD nLength; LPVOID lpSecurityDescriptor; BOOL bInheritHandle; } SECURITY_ATTRIBUTES, *PSECURITY_ATTRIBUTES, *LPSECURITY_ATTRIBUTES; typedef USHORT SECURITY_DESCRIPTOR_CONTROL; typedef USHORT *PSECURITY_DESCRIPTOR_CONTROL; typedef PVOID PSID; typedef struct _ACL { UCHAR AclRevision; UCHAR Sbz1; USHORT AclSize; USHORT AceCount; USHORT Sbz2; } ACL, *PACL; typedef struct _SECURITY_DESCRIPTOR { UCHAR Revision; UCHAR Sbz1; SECURITY_DESCRIPTOR_CONTROL Control; PSID Owner; PSID Group; PACL Sacl; PACL Dacl; } SECURITY_DESCRIPTOR, *PSECURITY_DESCRIPTOR; typedef struct _COAUTHIDENTITY { USHORT *User; ULONG UserLength; USHORT *Domain; ULONG DomainLength; USHORT *Password; ULONG PasswordLength; ULONG Flags; } COAUTHIDENTITY; typedef struct _COAUTHINFO { DWORD dwAuthnSvc; DWORD dwAuthzSvc; LPWSTR pwszServerPrincName; DWORD dwAuthnLevel; DWORD dwImpersonationLevel; COAUTHIDENTITY *pAuthIdentityData; DWORD dwCapabilities; } COAUTHINFO; typedef LONG SCODE; typedef SCODE *PSCODE; typedef enum tagMEMCTX { MEMCTX_TASK = 1, MEMCTX_SHARED = 2, MEMCTX_MACSYSTEM = 3, MEMCTX_UNKNOWN = -1, MEMCTX_SAME = -2 } MEMCTX; typedef enum tagMSHLFLAGS { MSHLFLAGS_NORMAL = 0, MSHLFLAGS_TABLESTRONG = 1, MSHLFLAGS_TABLEWEAK = 2, MSHLFLAGS_NOPING = 4, MSHLFLAGS_RESERVED1 = 8, MSHLFLAGS_RESERVED2 = 16, MSHLFLAGS_RESERVED3 = 32, MSHLFLAGS_RESERVED4 = 64 } MSHLFLAGS; typedef enum tagMSHCTX { MSHCTX_LOCAL = 0, MSHCTX_NOSHAREDMEM = 1, MSHCTX_DIFFERENTMACHINE = 2, MSHCTX_INPROC = 3, MSHCTX_CROSSCTX = 4 } MSHCTX; typedef enum tagDVASPECT { DVASPECT_CONTENT = 1, DVASPECT_THUMBNAIL = 2, DVASPECT_ICON = 4, DVASPECT_DOCPRINT = 8 } DVASPECT; typedef enum tagSTGC { STGC_DEFAULT = 0, STGC_OVERWRITE = 1, STGC_ONLYIFCURRENT = 2, STGC_DANGEROUSLYCOMMITMERELYTODISKCACHE = 4, STGC_CONSOLIDATE = 8 } STGC; typedef enum tagSTGMOVE { STGMOVE_MOVE = 0, STGMOVE_COPY = 1, STGMOVE_SHALLOWCOPY = 2 } STGMOVE; typedef enum tagSTATFLAG { STATFLAG_DEFAULT = 0, STATFLAG_NONAME = 1, STATFLAG_NOOPEN = 2 } STATFLAG; typedef void *HCONTEXT; typedef struct _BYTE_BLOB { unsigned long clSize; uint8_t abData[ 1 ]; } BYTE_BLOB; typedef struct _WORD_BLOB { unsigned long clSize; unsigned short asData[ 1 ]; } WORD_BLOB; typedef struct _DWORD_BLOB { unsigned long clSize; unsigned long alData[ 1 ]; } DWORD_BLOB; typedef struct _FLAGGED_BYTE_BLOB { unsigned long fFlags; unsigned long clSize; uint8_t abData[ 1 ]; } FLAGGED_BYTE_BLOB; typedef struct _FLAGGED_WORD_BLOB { unsigned long fFlags; unsigned long clSize; unsigned short asData[ 1 ]; } FLAGGED_WORD_BLOB; typedef struct _BYTE_SIZEDARR { unsigned long clSize; uint8_t *pData; } BYTE_SIZEDARR; typedef struct _SHORT_SIZEDARR { unsigned long clSize; unsigned short *pData; } WORD_SIZEDARR; typedef struct _LONG_SIZEDARR { unsigned long clSize; unsigned long *pData; } DWORD_SIZEDARR; ]] --typedef enum tagCLSCTX { CLSCTX_INPROC_SERVER = 0x1 CLSCTX_INPROC_HANDLER = 0x2 CLSCTX_LOCAL_SERVER = 0x4 CLSCTX_INPROC_SERVER16 = 0x8 CLSCTX_REMOTE_SERVER = 0x10 CLSCTX_INPROC_HANDLER16 = 0x20 CLSCTX_RESERVED1 = 0x40 CLSCTX_RESERVED2 = 0x80 CLSCTX_RESERVED3 = 0x100 CLSCTX_RESERVED4 = 0x200 CLSCTX_NO_CODE_DOWNLOAD = 0x400 CLSCTX_RESERVED5 = 0x800 CLSCTX_NO_CUSTOM_MARSHAL = 0x1000 CLSCTX_ENABLE_CODE_DOWNLOAD = 0x2000 CLSCTX_NO_FAILURE_LOG = 0x4000 CLSCTX_DISABLE_AAA = 0x8000 CLSCTX_ENABLE_AAA = 0x10000 CLSCTX_FROM_DEFAULT_CONTEXT = 0x20000 CLSCTX_ACTIVATE_32_BIT_SERVER = 0x40000 CLSCTX_ACTIVATE_64_BIT_SERVER = 0x80000 CLSCTX_ENABLE_CLOAKING = 0x100000 CLSCTX_PS_DLL = 0x80000000 --} CLSCTX; CLSCTX_VALID_MASK = bor( CLSCTX_INPROC_SERVER , CLSCTX_INPROC_HANDLER , CLSCTX_LOCAL_SERVER , CLSCTX_INPROC_SERVER16 , CLSCTX_REMOTE_SERVER , CLSCTX_NO_CODE_DOWNLOAD , CLSCTX_NO_CUSTOM_MARSHAL , CLSCTX_ENABLE_CODE_DOWNLOAD , CLSCTX_NO_FAILURE_LOG , CLSCTX_DISABLE_AAA , CLSCTX_ENABLE_AAA , CLSCTX_FROM_DEFAULT_CONTEXT , CLSCTX_ACTIVATE_32_BIT_SERVER , CLSCTX_ACTIVATE_64_BIT_SERVER , CLSCTX_ENABLE_CLOAKING , CLSCTX_PS_DLL) WDT_INPROC_CALL =( 0x48746457 ) WDT_REMOTE_CALL =( 0x52746457 ) WDT_INPROC64_CALL = ( 0x50746457 ) ffi.cdef[[ enum { MAXSHORT = 32767, MINSHORT = -32768, MAXINT = 2147483647, MININT = -2147483648, // MAXLONGLONG = 9223372036854775807, // MINLONGLONG = -9223372036854775807, }; ]] ffi.cdef[[ typedef struct tagSIZE { LONG cx; LONG cy; } SIZE, *PSIZE; typedef struct tagPOINT { int32_t x; int32_t y; } POINT, *PPOINT; typedef struct _POINTL { LONG x; LONG y; } POINTL, *PPOINTL; typedef struct tagRECT { int32_t left; int32_t top; int32_t right; int32_t bottom; } RECT, *PRECT; ]] RECT = nil RECT_mt = { __tostring = function(self) local str = string.format("%d %d %d %d", self.left, self.top, self.right, self.bottom) return str end, __index = { } } RECT = ffi.metatype("RECT", RECT_mt) ffi.cdef[[ typedef struct _TRIVERTEX { LONG x; LONG y; COLOR16 Red; COLOR16 Green; COLOR16 Blue; COLOR16 Alpha; }TRIVERTEX, *PTRIVERTEX; typedef struct _GRADIENT_TRIANGLE { ULONG Vertex1; ULONG Vertex2; ULONG Vertex3; }GRADIENT_TRIANGLE, *PGRADIENT_TRIANGLE; typedef struct _GRADIENT_RECT { ULONG UpperLeft; ULONG LowerRight; }GRADIENT_RECT, *PGRADIENT_RECT; typedef struct tagRGBQUAD { BYTE rgbBlue; BYTE rgbGreen; BYTE rgbRed; BYTE rgbReserved; } RGBQUAD; typedef struct tagRGBTRIPLE { BYTE rgbtBlue; BYTE rgbtGreen; BYTE rgbtRed; } RGBTRIPLE; typedef struct tagBITMAP { LONG bmType; LONG bmWidth; LONG bmHeight; LONG bmWidthBytes; WORD bmPlanes; WORD bmBitsPixel; LPVOID bmBits; } BITMAP, *PBITMAP; typedef struct tagBITMAPCOREHEADER { DWORD bcSize; WORD bcWidth; WORD bcHeight; WORD bcPlanes; WORD bcBitCount; } BITMAPCOREHEADER, *PBITMAPCOREHEADER; typedef struct tagBITMAPINFOHEADER{ DWORD biSize; LONG biWidth; LONG biHeight; WORD biPlanes; WORD biBitCount; DWORD biCompression; DWORD biSizeImage; LONG biXPelsPerMeter; LONG biYPelsPerMeter; DWORD biClrUsed; DWORD biClrImportant; } BITMAPINFOHEADER, *PBITMAPINFOHEADER; typedef struct tagBITMAPINFO { BITMAPINFOHEADER bmiHeader; RGBQUAD bmiColors[1]; } BITMAPINFO, *PBITMAPINFO; typedef struct tagCIEXYZ { FXPT2DOT30 ciexyzX; FXPT2DOT30 ciexyzY; FXPT2DOT30 ciexyzZ; } CIEXYZ, * PCIEXYZ; typedef struct tagCIEXYZTRIPLE { CIEXYZ ciexyzRed; CIEXYZ ciexyzGreen; CIEXYZ ciexyzBlue; } CIEXYZTRIPLE, *PCIEXYZTRIPLE; typedef struct { DWORD bV4Size; LONG bV4Width; LONG bV4Height; WORD bV4Planes; WORD bV4BitCount; DWORD bV4V4Compression; DWORD bV4SizeImage; LONG bV4XPelsPerMeter; LONG bV4YPelsPerMeter; DWORD bV4ClrUsed; DWORD bV4ClrImportant; DWORD bV4RedMask; DWORD bV4GreenMask; DWORD bV4BlueMask; DWORD bV4AlphaMask; DWORD bV4CSType; CIEXYZTRIPLE bV4Endpoints; DWORD bV4GammaRed; DWORD bV4GammaGreen; DWORD bV4GammaBlue; } BITMAPV4HEADER, *PBITMAPV4HEADER; typedef struct { DWORD bV5Size; LONG bV5Width; LONG bV5Height; WORD bV5Planes; WORD bV5BitCount; DWORD bV5Compression; DWORD bV5SizeImage; LONG bV5XPelsPerMeter; LONG bV5YPelsPerMeter; DWORD bV5ClrUsed; DWORD bV5ClrImportant; DWORD bV5RedMask; DWORD bV5GreenMask; DWORD bV5BlueMask; DWORD bV5AlphaMask; DWORD bV5CSType; CIEXYZTRIPLE bV5Endpoints; DWORD bV5GammaRed; DWORD bV5GammaGreen; DWORD bV5GammaBlue; DWORD bV5Intent; DWORD bV5ProfileData; DWORD bV5ProfileSize; DWORD bV5Reserved; } BITMAPV5HEADER, *PBITMAPV5HEADER; ]] BITMAPINFOHEADER = nil BITMAPINFOHEADER_mt = { __index = { __new = function(ct) print("BITMAPINFOHEADER_ct") local obj = ffi.new(ct); obj.biSize = ffi.sizeof("BITMAPINFOHEADER") return obj; end, Init = function(self) self.biSize = ffi.sizeof("BITMAPINFOHEADER") end, } } BITMAPINFOHEADER = ffi.metatype("BITMAPINFOHEADER", BITMAPINFOHEADER_mt) BITMAPINFO = ffi.typeof("BITMAPINFO") BITMAPINFO_mt = { __new = function(ct) print("BITMAPINFO_ct") local obj = ffi.new(ct); obj.bmiHeader:Init(); return obj; end, __index = { Init = function(self) self.bmiHeader:Init(); end, }, } BITMAPINFO = ffi.metatype("BITMAPINFO", BITMAPINFO_mt)
bsd-3-clause