repo_name
stringlengths
6
78
path
stringlengths
4
206
copies
stringclasses
281 values
size
stringlengths
4
7
content
stringlengths
625
1.05M
license
stringclasses
15 values
yylangchen/Sample_Lua
frameworks/cocos2d-x/cocos/scripting/lua-bindings/auto/api/PhysicsJointSpring.lua
10
2061
-------------------------------- -- @module PhysicsJointSpring -- @extend PhysicsJoint -- @parent_module cc -------------------------------- -- -- @function [parent=#PhysicsJointSpring] setAnchr2 -- @param self -- @param #vec2_table anchr2 -------------------------------- -- -- @function [parent=#PhysicsJointSpring] setAnchr1 -- @param self -- @param #vec2_table anchr1 -------------------------------- -- -- @function [parent=#PhysicsJointSpring] getDamping -- @param self -- @return float#float ret (return value: float) -------------------------------- -- -- @function [parent=#PhysicsJointSpring] setStiffness -- @param self -- @param #float stiffness -------------------------------- -- -- @function [parent=#PhysicsJointSpring] getRestLength -- @param self -- @return float#float ret (return value: float) -------------------------------- -- -- @function [parent=#PhysicsJointSpring] getAnchr2 -- @param self -- @return vec2_table#vec2_table ret (return value: vec2_table) -------------------------------- -- -- @function [parent=#PhysicsJointSpring] getAnchr1 -- @param self -- @return vec2_table#vec2_table ret (return value: vec2_table) -------------------------------- -- -- @function [parent=#PhysicsJointSpring] getStiffness -- @param self -- @return float#float ret (return value: float) -------------------------------- -- -- @function [parent=#PhysicsJointSpring] setRestLength -- @param self -- @param #float restLength -------------------------------- -- -- @function [parent=#PhysicsJointSpring] setDamping -- @param self -- @param #float damping -------------------------------- -- -- @function [parent=#PhysicsJointSpring] construct -- @param self -- @param #cc.PhysicsBody a -- @param #cc.PhysicsBody b -- @param #vec2_table anchr1 -- @param #vec2_table anchr2 -- @param #float stiffness -- @param #float damping -- @return PhysicsJointSpring#PhysicsJointSpring ret (return value: cc.PhysicsJointSpring) return nil
mit
xdemolish/darkstar
scripts/globals/weaponskills/tachi_rana.lua
1
4535
----------------------------------- -- Tachi Rana -- Great Katana weapon skill -- Skill Level: N/A -- Delivers a three-fold attack. params.accuracy varies with TP. Aftermath effect varies with TP. See Kogarasumaru. -- In order to obtain Tachi: Rana, the Unlocking a Myth (Samurai) quest must be completed. -- Will stack with Sneak Attack (first hit only). -- Aligned with the Shadow Gorget, Soil Gorget & Snow Gorget. -- Aligned with the Shadow Belt, Soil Belt & Snow 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) local params = {}; params.numHits = 3; 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.8; params.acc200= 0.9; params.acc300= 1; params.atkmulti = 1; local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params); if((player:getEquipID(SLOT_MAIN) == 19002) and (player:getMainJob() == JOB_SAM)) then if(damage > 0) then -- AFTERMATH LV1 if ((player:getTP() >= 100) and (player:getTP() <= 110)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 10, 0, 180, 0, 1); elseif ((player:getTP() >= 111) and (player:getTP() <= 120)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 11, 0, 180, 0, 1); elseif ((player:getTP() >= 121) and (player:getTP() <= 130)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 12, 0, 180, 0, 1); elseif ((player:getTP() >= 131) and (player:getTP() <= 140)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 13, 0, 180, 0, 1); elseif ((player:getTP() >= 141) and (player:getTP() <= 150)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 14, 0, 180, 0, 1); elseif ((player:getTP() >= 151) and (player:getTP() <= 160)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 15, 0, 180, 0, 1); elseif ((player:getTP() >= 161) and (player:getTP() <= 170)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 16, 0, 180, 0, 1); elseif ((player:getTP() >= 171) and (player:getTP() <= 180)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 17, 0, 180, 0, 1); elseif ((player:getTP() >= 181) and (player:getTP() <= 190)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 18, 0, 180, 0, 1); elseif ((player:getTP() >= 191) and (player:getTP() <= 199)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 19, 0, 180, 0, 1); -- AFTERMATH LV2 elseif ((player:getTP() >= 200) and (player:getTP() <= 210)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 24, 0, 180, 0, 1); elseif ((player:getTP() >= 211) and (player:getTP() <= 219)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 28, 0, 180, 0, 1); elseif ((player:getTP() >= 221) and (player:getTP() <= 229)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 32, 0, 180, 0, 1); elseif ((player:getTP() >= 231) and (player:getTP() <= 239)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 36, 0, 180, 0, 1); elseif ((player:getTP() >= 241) and (player:getTP() <= 249)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 40, 0, 180, 0, 1); elseif ((player:getTP() >= 251) and (player:getTP() <= 259)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 44, 0, 180, 0, 1); elseif ((player:getTP() >= 261) and (player:getTP() <= 269)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 48, 0, 180, 0, 1); elseif ((player:getTP() >= 271) and (player:getTP() <= 279)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 52, 0, 180, 0, 1); elseif ((player:getTP() >= 281) and (player:getTP() <= 289)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 56, 0, 180, 0, 1); elseif ((player:getTP() >= 291) and (player:getTP() <= 299)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 59, 0, 180, 0, 1); -- AFTERMATH LV3 elseif ((player:getTP() == 300)) then player:addStatusEffect(EFFECT_AFTERMATH_LV3, 45, 0, 120, 0, 1); end end end return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
hsiaoyi/Melo
cocos2d/tests/lua-tests/src/testResource.lua
7
2060
s_pPathGrossini = "Images/grossini.png" s_pPathSister1 = "Images/grossinis_sister1.png" s_pPathSister2 = "Images/grossinis_sister2.png" s_pPathB1 = "Images/b1.png" s_pPathB2 = "Images/b2.png" s_pPathR1 = "Images/r1.png" s_pPathR2 = "Images/r2.png" s_pPathF1 = "Images/f1.png" s_pPathF2 = "Images/f2.png" s_pPathBlock = "Images/blocks.png" s_back = "Images/background.png" s_back1 = "Images/background1.png" s_back2 = "Images/background2.png" s_back3 = "Images/background3.png" s_stars1 = "Images/stars.png" s_stars2 = "Images/stars2.png" s_fire = "Images/fire.png" s_snow = "Images/snow.png" s_streak = "Images/streak.png" s_PlayNormal = "Images/btn-play-normal.png" s_PlaySelect = "Images/btn-play-selected.png" s_AboutNormal = "Images/btn-about-normal.png" s_AboutSelect = "Images/btn-about-selected.png" s_HighNormal = "Images/btn-highscores-normal.png" s_HighSelect = "Images/btn-highscores-selected.png" s_Ball = "Images/ball.png" s_Paddle = "Images/paddle.png" s_pPathClose = "Images/close.png" s_MenuItem = "Images/menuitemsprite.png" s_SendScore = "Images/SendScoreButton.png" s_PressSendScore = "Images/SendScoreButtonPressed.png" s_Power = "Images/powered.png" s_AtlasTest = "Images/atlastest.png" -- tilemaps resource s_TilesPng = "TileMaps/tiles.png" s_LevelMapTga = "TileMaps/levelmap.tga" -- spine test resource s_pPathSpineBoyJson = "spine/spineboy.json" s_pPathSpineBoyAtlas = "spine/spineboy.atlas" -- fonts resource s_markerFeltFontPath = "fonts/Marker Felt.ttf" s_arialPath = "fonts/arial.ttf" s_thonburiPath = "fonts/Thonburi.ttf" s_tahomaPath = "fonts/tahoma.ttf" s_s9s_ui_plist = "Images/ui.plist"
apache-2.0
chris5560/openwrt-luci
applications/luci-app-olsr/luasrc/model/cbi/olsr/olsrdiface6.lua
68
5949
-- Copyright 2010 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. local util = require "luci.util" local ip = require "luci.ip" function write_float(self, section, value) local n = tonumber(value) if n ~= nil then return Value.write(self, section, "%.1f" % n) end end m = Map("olsrd6", translate("OLSR Daemon - Interface"), translate("The OLSR daemon is an implementation of the Optimized Link State Routing protocol. ".. "As such it allows mesh routing for any network equipment. ".. "It runs on any wifi card that supports ad-hoc mode and of course on any ethernet device. ".. "Visit <a href='http://www.olsr.org'>olsrd.org</a> for help and documentation.")) m.redirect = luci.dispatcher.build_url("admin/services/olsrd6") if not arg[1] or m.uci:get("olsrd6", arg[1]) ~= "Interface" then luci.http.redirect(m.redirect) return end i = m:section(NamedSection, arg[1], "Interface", translate("Interface")) i.anonymous = true i.addremove = false i:tab("general", translate("General Settings")) i:tab("addrs", translate("IP Addresses")) i:tab("timing", translate("Timing and Validity")) ign = i:taboption("general", Flag, "ignore", translate("Enable"), translate("Enable this interface.")) ign.enabled = "0" ign.disabled = "1" ign.rmempty = false function ign.cfgvalue(self, section) return Flag.cfgvalue(self, section) or "0" end network = i:taboption("general", Value, "interface", translate("Network"), translate("The interface OLSRd should serve.")) network.template = "cbi/network_netlist" network.widget = "radio" network.nocreate = true mode = i:taboption("general", ListValue, "Mode", translate("Mode"), translate("Interface Mode is used to prevent unnecessary packet forwarding on switched ethernet interfaces. ".. "valid Modes are \"mesh\" and \"ether\". Default is \"mesh\".")) mode:value("mesh") mode:value("ether") mode.optional = true mode.rmempty = true weight = i:taboption("general", Value, "Weight", translate("Weight"), translate("When multiple links exist between hosts the weight of interface is used to determine the link to use. ".. "Normally the weight is automatically calculated by olsrd based on the characteristics of the interface, ".. "but here you can specify a fixed value. Olsrd will choose links with the lowest value.<br />".. "<b>Note:</b> Interface weight is used only when LinkQualityLevel is set to 0. ".. "For any other value of LinkQualityLevel, the interface ETX value is used instead.")) weight.optional = true weight.datatype = "uinteger" weight.placeholder = "0" lqmult = i:taboption("general", DynamicList, "LinkQualityMult", translate("LinkQuality Multiplicator"), translate("Multiply routes with the factor given here. Allowed values are between 0.01 and 1.0. ".. "It is only used when LQ-Level is greater than 0. Examples:<br />".. "reduce LQ to fd91:662e:3c58::1 by half: fd91:662e:3c58::1 0.5<br />".. "reduce LQ to all nodes on this interface by 20%: default 0.8")) lqmult.optional = true lqmult.rmempty = true lqmult.cast = "table" lqmult.placeholder = "default 1.0" function lqmult.validate(self, value) for _, v in pairs(value) do if v ~= "" then local val = util.split(v, " ") local host = val[1] local mult = val[2] if not host or not mult then return nil, translate("LQMult requires two values (IP address or 'default' and multiplicator) seperated by space.") end if not (host == "default" or ip.IPv6(host)) then return nil, translate("Can only be a valid IPv6 address or 'default'") end if not tonumber(mult) or tonumber(mult) > 1 or tonumber(mult) < 0.01 then return nil, translate("Invalid Value for LQMult-Value. Must be between 0.01 and 1.0.") end if not mult:match("[0-1]%.[0-9]+") then return nil, translate("Invalid Value for LQMult-Value. You must use a decimal number between 0.01 and 1.0 here.") end end end return value end ip6m = i:taboption("addrs", Value, "IPv6Multicast", translate("IPv6 multicast"), translate("IPv6 multicast address. Default is \"FF02::6D\", the manet-router linklocal multicast.")) ip6m.optional = true ip6m.datatype = "ip6addr" ip6m.placeholder = "FF02::6D" ip6s = i:taboption("addrs", Value, "IPv6Src", translate("IPv6 source"), translate("IPv6 src prefix. OLSRd will choose one of the interface IPs which matches the prefix of this parameter. ".. "Default is \"0::/0\", which triggers the usage of a not-linklocal interface IP.")) ip6s.optional = true ip6s.datatype = "ip6addr" ip6s.placeholder = "0::/0" hi = i:taboption("timing", Value, "HelloInterval", translate("Hello interval")) hi.optional = true hi.datatype = "ufloat" hi.placeholder = "5.0" hi.write = write_float hv = i:taboption("timing", Value, "HelloValidityTime", translate("Hello validity time")) hv.optional = true hv.datatype = "ufloat" hv.placeholder = "40.0" hv.write = write_float ti = i:taboption("timing", Value, "TcInterval", translate("TC interval")) ti.optional = true ti.datatype = "ufloat" ti.placeholder = "2.0" ti.write = write_float tv = i:taboption("timing", Value, "TcValidityTime", translate("TC validity time")) tv.optional = true tv.datatype = "ufloat" tv.placeholder = "256.0" tv.write = write_float mi = i:taboption("timing", Value, "MidInterval", translate("MID interval")) mi.optional = true mi.datatype = "ufloat" mi.placeholder = "18.0" mi.write = write_float mv = i:taboption("timing", Value, "MidValidityTime", translate("MID validity time")) mv.optional = true mv.datatype = "ufloat" mv.placeholder = "324.0" mv.write = write_float ai = i:taboption("timing", Value, "HnaInterval", translate("HNA interval")) ai.optional = true ai.datatype = "ufloat" ai.placeholder = "18.0" ai.write = write_float av = i:taboption("timing", Value, "HnaValidityTime", translate("HNA validity time")) av.optional = true av.datatype = "ufloat" av.placeholder = "108.0" av.write = write_float return m
apache-2.0
xdemolish/darkstar
scripts/globals/abilities/maguss_roll.lua
1
1407
----------------------------------- -- Ability: Magus's Roll ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); ----------------------------------- -- onUseAbility ----------------------------------- function onAbilityCheck(player,target,ability) local effectID = getCorsairRollEffect(ability:getID()); if (player:hasStatusEffect(effectID) or player:hasBustEffect(effectID)) then return MSGBASIC_ROLL_ALREADY_ACTIVE,0; else return 0,0; end end; function onUseAbilityRoll(caster, target, ability, total) local duration = 300 + caster:getMerit(MERIT_WINNING_STREAK) local effectpowers = {5, 20, 6, 8, 9, 3, 10, 13, 14, 15, 25} local effectpower = effectpowers[total] if (total < 12 and caster:hasPartyJob(JOB_BLU) ) then effectpower = effectpower + 8; end if (caster:getMainJob() == JOB_COR and caster:getMainLvl() < target:getMainLvl()) then effectpower = effectpower * (caster:getMainLvl() / target:getMainLvl()); elseif (caster:getSubJob() == JOB_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_MAGUSS_ROLL, effectpower, 0, duration, target:getID(), total, MOD_MDEF) == false) then ability:setMsg(423); end end;
gpl-3.0
xdemolish/darkstar
scripts/zones/Aht_Urhgan_Whitegate/npcs/Kuhmden.lua
34
1032
----------------------------------- -- Area: Aht Urhgan Whitegate -- NPC: Kuhmden -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x00FC); 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
ld-test/dromozoa-unix
test/unix_server.lua
1
1559
-- Copyright (C) 2016 Tomoyuki Fujimori <moyu@dromozoa.com> -- -- This file is part of dromozoa-unix. -- -- dromozoa-unix 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. -- -- dromozoa-unix 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 dromozoa-unix. If not, see <http://www.gnu.org/licenses/>. local unix = require "dromozoa.unix" local abstract = 1 local server = assert(unix.socket(unix.AF_UNIX, unix.SOCK_STREAM)) local result, message, code = server:bind(unix.sockaddr_un("\0dromozoa-unix/test.sock")) if not result then if code == unix.ENOENT then abstract = 0 assert(server:bind(unix.sockaddr_un("test.sock"))) else assert(result, message, code) end end assert(server:listen()) io.stdout:write(abstract, "\n") io.stdout:flush() io.stdout:close() local fd, sa = server:accept(unix.O_CLOEXEC) while true do local result, message, code = fd:read(256) if result and #result > 0 then assert(result == "foo\n") -- io.stderr:write(result) assert(fd:write("bar\n") == 4) else break end end assert(fd:close()) assert(server:close()) os.remove("test.sock")
gpl-3.0
xdemolish/darkstar
scripts/zones/Jugner_Forest_[S]/npcs/Cavernous_Maw.lua
5
1382
----------------------------------- -- Cavernous Maw -- Teleports Players to Jugner Forest -- @pos -118 -8 -520 82 ----------------------------------- package.loaded["scripts/zones/Jugner_Forest_[S]/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/teleports"); require("scripts/globals/campaign"); require("scripts/zones/Jugner_Forest_[S]/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(hasMawActivated(player,3) == false) then player:startEvent(0x0065); else player:startEvent(0x0066); 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); if(option == 1) then if(csid == 0x0065) then player:addNationTeleport(MAW,8); end toMaw(player,14); end end;
gpl-3.0
Andreas-Kreuz/ak-lua-skripte-fuer-eep
lua/LUA/ak/modellpacker/AkModellPaket.lua
1
2685
local AkModellPacker = require("ak.modellpacker.AkModellPacker") local AkModellPaket = {} function AkModellPaket:new(eepVersion, deutscherName, deutscheBeschreibung) local o = {} setmetatable(o, self) self.__index = self o.eepVersion = eepVersion o.deutscherName = deutscherName o.deutscheBeschreibung = deutscheBeschreibung o:setzeName() o:setzeBeschreibung() o.modellPfade = {} o.installationsPfade = {} return o end function AkModellPaket:setzeName(englischerName, franzoesischerName, polnischerName) self.englischerName = englischerName or self.deutscherName self.franzoesischerName = franzoesischerName or self.englischerName self.polnischerName = polnischerName or self.englischerName end function AkModellPaket:setzeBeschreibung(englisch, franzoesisch, polnisch) self.englischeBeschreibung = englisch or self.deutscheBeschreibung self.franzoesischeBeschreibung = franzoesisch or self.englischeBeschreibung self.polnischeBeschreibung = polnisch or self.englischeBeschreibung end --- Sucht im Unterordner des Basisordners nach Modellen -- Alle erkannten Dateien werden als "praefix\unterOrdner\...\Datei" erkannt und installiert -- @param basisOrdner -- @param praefix -- @param unterOrdner -- @param excludePattern -- function AkModellPaket:fuegeDateienHinzu(basisOrdner, praefix, unterOrdner, pfadAusschlussMuster) assert(type(basisOrdner) == "string", "Need 'basisOrdner' as string") assert(type(praefix) == "string", "Need 'praefix' as string") assert(type(unterOrdner) == "string", "Need 'unterOrdner' as string") local neuePfade = {} print(string.format("[#ModellPaket] Durchsuche \"%s\" in Unterordner \"%s\"", basisOrdner, unterOrdner)) local _, dateiGefunden = AkModellPacker.dateienSuchen(neuePfade, basisOrdner, unterOrdner) assert(dateiGefunden, string.format("Keine Datei gefunden: \"%s\" in Unterordner \"%s\"", basisOrdner, unterOrdner)) for pfad, datei in pairs(neuePfade) do if pfadAusschlussMuster and AkModellPaket.pfadAusschliessen(pfad, pfadAusschlussMuster) then print("[#ModellPaket] Ueberspringe: " .. pfad) else print("[#ModellPaket] Fuege Datei hinzu: " .. pfad) self.installationsPfade[praefix .. pfad] = datei self.modellPfade[basisOrdner .. "\\" .. pfad] = datei end end end function AkModellPaket.pfadAusschliessen(pfad, pfadAusschlussMuster) if not pfadAusschlussMuster then return false end for _, muster in ipairs(pfadAusschlussMuster) do if string.find(pfad, muster, 1, true) then return true end end return false end return AkModellPaket
mit
mohammad24/unixx
libs/JSON.lua
3765
34843
-- -*- coding: utf-8 -*- -- -- Simple JSON encoding and decoding in pure Lua. -- -- Copyright 2010-2014 Jeffrey Friedl -- http://regex.info/blog/ -- -- Latest version: http://regex.info/blog/lua/json -- -- This code is released under a Creative Commons CC-BY "Attribution" License: -- http://creativecommons.org/licenses/by/3.0/deed.en_US -- -- It can be used for any purpose so long as the copyright notice above, -- the web-page links above, and the 'AUTHOR_NOTE' string below are -- maintained. Enjoy. -- local VERSION = 20141223.14 -- version history at end of file local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-" -- -- The 'AUTHOR_NOTE' variable exists so that information about the source -- of the package is maintained even in compiled versions. It's also -- included in OBJDEF below mostly to quiet warnings about unused variables. -- local OBJDEF = { VERSION = VERSION, AUTHOR_NOTE = AUTHOR_NOTE, } -- -- Simple JSON encoding and decoding in pure Lua. -- http://www.json.org/ -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- -- -- -- DECODING (from a JSON string to a Lua table) -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- If the JSON text is for an object or an array, e.g. -- { "what": "books", "count": 3 } -- or -- [ "Larry", "Curly", "Moe" ] -- -- the result is a Lua table, e.g. -- { what = "books", count = 3 } -- or -- { "Larry", "Curly", "Moe" } -- -- -- The encode and decode routines accept an optional second argument, -- "etc", which is not used during encoding or decoding, but upon error -- is passed along to error handlers. It can be of any type (including nil). -- -- -- -- ERROR HANDLING -- -- With most errors during decoding, this code calls -- -- JSON:onDecodeError(message, text, location, etc) -- -- with a message about the error, and if known, the JSON text being -- parsed and the byte count where the problem was discovered. You can -- replace the default JSON:onDecodeError() with your own function. -- -- The default onDecodeError() merely augments the message with data -- about the text and the location if known (and if a second 'etc' -- argument had been provided to decode(), its value is tacked onto the -- message as well), and then calls JSON.assert(), which itself defaults -- to Lua's built-in assert(), and can also be overridden. -- -- For example, in an Adobe Lightroom plugin, you might use something like -- -- function JSON:onDecodeError(message, text, location, etc) -- LrErrors.throwUserError("Internal Error: invalid JSON data") -- end -- -- or even just -- -- function JSON.assert(message) -- LrErrors.throwUserError("Internal Error: " .. message) -- end -- -- If JSON:decode() is passed a nil, this is called instead: -- -- JSON:onDecodeOfNilError(message, nil, nil, etc) -- -- and if JSON:decode() is passed HTML instead of JSON, this is called: -- -- JSON:onDecodeOfHTMLError(message, text, nil, etc) -- -- The use of the fourth 'etc' argument allows stronger coordination -- between decoding and error reporting, especially when you provide your -- own error-handling routines. Continuing with the the Adobe Lightroom -- plugin example: -- -- function JSON:onDecodeError(message, text, location, etc) -- local note = "Internal Error: invalid JSON data" -- if type(etc) = 'table' and etc.photo then -- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName') -- end -- LrErrors.throwUserError(note) -- end -- -- : -- : -- -- for i, photo in ipairs(photosToProcess) do -- : -- : -- local data = JSON:decode(someJsonText, { photo = photo }) -- : -- : -- end -- -- -- -- -- -- DECODING AND STRICT TYPES -- -- Because both JSON objects and JSON arrays are converted to Lua tables, -- it's not normally possible to tell which original JSON type a -- particular Lua table was derived from, or guarantee decode-encode -- round-trip equivalency. -- -- However, if you enable strictTypes, e.g. -- -- JSON = assert(loadfile "JSON.lua")() --load the routines -- JSON.strictTypes = true -- -- then the Lua table resulting from the decoding of a JSON object or -- JSON array is marked via Lua metatable, so that when re-encoded with -- JSON:encode() it ends up as the appropriate JSON type. -- -- (This is not the default because other routines may not work well with -- tables that have a metatable set, for example, Lightroom API calls.) -- -- -- ENCODING (from a lua table to a JSON string) -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false }) -- -- On error during encoding, this code calls: -- -- JSON:onEncodeError(message, etc) -- -- which you can override in your local JSON object. -- -- The 'etc' in the error call is the second argument to encode() -- and encode_pretty(), or nil if it wasn't provided. -- -- -- PRETTY-PRINTING -- -- An optional third argument, a table of options, allows a bit of -- configuration about how the encoding takes place: -- -- pretty = JSON:encode(val, etc, { -- pretty = true, -- if false, no other options matter -- indent = " ", -- this provides for a three-space indent per nesting level -- align_keys = false, -- see below -- }) -- -- encode() and encode_pretty() are identical except that encode_pretty() -- provides a default options table if none given in the call: -- -- { pretty = true, align_keys = false, indent = " " } -- -- For example, if -- -- JSON:encode(data) -- -- produces: -- -- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11} -- -- then -- -- JSON:encode_pretty(data) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- The following three lines return identical results: -- JSON:encode_pretty(data) -- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " }) -- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " }) -- -- An example of setting your own indent string: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " }) -- -- produces: -- -- { -- | "city": "Kyoto", -- | "climate": { -- | | "avg_temp": 16, -- | | "humidity": "high", -- | | "snowfall": "minimal" -- | }, -- | "country": "Japan", -- | "wards": 11 -- } -- -- An example of setting align_keys to true: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true }) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- which I must admit is kinda ugly, sorry. This was the default for -- encode_pretty() prior to version 20141223.14. -- -- -- AMBIGUOUS SITUATIONS DURING THE ENCODING -- -- During the encode, if a Lua table being encoded contains both string -- and numeric keys, it fits neither JSON's idea of an object, nor its -- idea of an array. To get around this, when any string key exists (or -- when non-positive numeric keys exist), numeric keys are converted to -- strings. -- -- For example, -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- produces the JSON object -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To prohibit this conversion and instead make it an error condition, set -- JSON.noKeyConversion = true -- -- -- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT -- -- assert -- onDecodeError -- onDecodeOfNilError -- onDecodeOfHTMLError -- onEncodeError -- -- If you want to create a separate Lua JSON object with its own error handlers, -- you can reload JSON.lua or use the :new() method. -- --------------------------------------------------------------------------- local default_pretty_indent = " " local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent } local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject function OBJDEF:newArray(tbl) return setmetatable(tbl or {}, isArray) end function OBJDEF:newObject(tbl) return setmetatable(tbl or {}, isObject) end local function unicode_codepoint_as_utf8(codepoint) -- -- codepoint is a number -- if codepoint <= 127 then return string.char(codepoint) elseif codepoint <= 2047 then -- -- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8 -- local highpart = math.floor(codepoint / 0x40) local lowpart = codepoint - (0x40 * highpart) return string.char(0xC0 + highpart, 0x80 + lowpart) elseif codepoint <= 65535 then -- -- 1110yyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x1000) local remainder = codepoint - 0x1000 * highpart local midpart = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midpart highpart = 0xE0 + highpart midpart = 0x80 + midpart lowpart = 0x80 + lowpart -- -- Check for an invalid character (thanks Andy R. at Adobe). -- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070 -- if ( highpart == 0xE0 and midpart < 0xA0 ) or ( highpart == 0xED and midpart > 0x9F ) or ( highpart == 0xF0 and midpart < 0x90 ) or ( highpart == 0xF4 and midpart > 0x8F ) then return "?" else return string.char(highpart, midpart, lowpart) end else -- -- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x40000) local remainder = codepoint - 0x40000 * highpart local midA = math.floor(remainder / 0x1000) remainder = remainder - 0x1000 * midA local midB = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midB return string.char(0xF0 + highpart, 0x80 + midA, 0x80 + midB, 0x80 + lowpart) end end function OBJDEF:onDecodeError(message, text, location, etc) if text then if location then message = string.format("%s at char %d of: %s", message, location, text) else message = string.format("%s: %s", message, text) end end if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError function OBJDEF:onEncodeError(message, etc) if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end local function grok_number(self, text, start, etc) -- -- Grab the integer part -- local integer_part = text:match('^-?[1-9]%d*', start) or text:match("^-?0", start) if not integer_part then self:onDecodeError("expected number", text, start, etc) end local i = start + integer_part:len() -- -- Grab an optional decimal part -- local decimal_part = text:match('^%.%d+', i) or "" i = i + decimal_part:len() -- -- Grab an optional exponential part -- local exponent_part = text:match('^[eE][-+]?%d+', i) or "" i = i + exponent_part:len() local full_number_text = integer_part .. decimal_part .. exponent_part local as_number = tonumber(full_number_text) if not as_number then self:onDecodeError("bad number", text, start, etc) end return as_number, i end local function grok_string(self, text, start, etc) if text:sub(start,start) ~= '"' then self:onDecodeError("expected string's opening quote", text, start, etc) end local i = start + 1 -- +1 to bypass the initial quote local text_len = text:len() local VALUE = "" while i <= text_len do local c = text:sub(i,i) if c == '"' then return VALUE, i + 1 end if c ~= '\\' then VALUE = VALUE .. c i = i + 1 elseif text:match('^\\b', i) then VALUE = VALUE .. "\b" i = i + 2 elseif text:match('^\\f', i) then VALUE = VALUE .. "\f" i = i + 2 elseif text:match('^\\n', i) then VALUE = VALUE .. "\n" i = i + 2 elseif text:match('^\\r', i) then VALUE = VALUE .. "\r" i = i + 2 elseif text:match('^\\t', i) then VALUE = VALUE .. "\t" i = i + 2 else local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if hex then i = i + 6 -- bypass what we just read -- We have a Unicode codepoint. It could be standalone, or if in the proper range and -- followed by another in a specific range, it'll be a two-code surrogate pair. local codepoint = tonumber(hex, 16) if codepoint >= 0xD800 and codepoint <= 0xDBFF then -- it's a hi surrogate... see whether we have a following low local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if lo_surrogate then i = i + 6 -- bypass the low surrogate we just read codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16) else -- not a proper low, so we'll just leave the first codepoint as is and spit it out. end end VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint) else -- just pass through what's escaped VALUE = VALUE .. text:match('^\\(.)', i) i = i + 2 end end end self:onDecodeError("unclosed string", text, start, etc) end local function skip_whitespace(text, start) local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2 if match_end then return match_end + 1 else return start end end local grok_one -- assigned later local function grok_object(self, text, start, etc) if text:sub(start,start) ~= '{' then self:onDecodeError("expected '{'", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '{' local VALUE = self.strictTypes and self:newObject { } or { } if text:sub(i,i) == '}' then return VALUE, i + 1 end local text_len = text:len() while i <= text_len do local key, new_i = grok_string(self, text, i, etc) i = skip_whitespace(text, new_i) if text:sub(i, i) ~= ':' then self:onDecodeError("expected colon", text, i, etc) end i = skip_whitespace(text, i + 1) local new_val, new_i = grok_one(self, text, i) VALUE[key] = new_val -- -- Expect now either '}' to end things, or a ',' to allow us to continue. -- i = skip_whitespace(text, new_i) local c = text:sub(i,i) if c == '}' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '}'", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '{'", text, start, etc) end local function grok_array(self, text, start, etc) if text:sub(start,start) ~= '[' then self:onDecodeError("expected '['", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '[' local VALUE = self.strictTypes and self:newArray { } or { } if text:sub(i,i) == ']' then return VALUE, i + 1 end local VALUE_INDEX = 1 local text_len = text:len() while i <= text_len do local val, new_i = grok_one(self, text, i) -- can't table.insert(VALUE, val) here because it's a no-op if val is nil VALUE[VALUE_INDEX] = val VALUE_INDEX = VALUE_INDEX + 1 i = skip_whitespace(text, new_i) -- -- Expect now either ']' to end things, or a ',' to allow us to continue. -- local c = text:sub(i,i) if c == ']' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '['", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '['", text, start, etc) end grok_one = function(self, text, start, etc) -- Skip any whitespace start = skip_whitespace(text, start) if start > text:len() then self:onDecodeError("unexpected end of string", text, nil, etc) end if text:find('^"', start) then return grok_string(self, text, start, etc) elseif text:find('^[-0123456789 ]', start) then return grok_number(self, text, start, etc) elseif text:find('^%{', start) then return grok_object(self, text, start, etc) elseif text:find('^%[', start) then return grok_array(self, text, start, etc) elseif text:find('^true', start) then return true, start + 4 elseif text:find('^false', start) then return false, start + 5 elseif text:find('^null', start) then return nil, start + 4 else self:onDecodeError("can't parse JSON", text, start, etc) end end function OBJDEF:decode(text, etc) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc) end if text == nil then self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc) elseif type(text) ~= 'string' then self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc) end if text:match('^%s*$') then return nil end if text:match('^%s*<') then -- Can't be JSON... we'll assume it's HTML self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc) end -- -- Ensure that it's not UTF-32 or UTF-16. -- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3), -- but this package can't handle them. -- if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc) end local success, value = pcall(grok_one, self, text, 1, etc) if success then return value else -- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert. if self.assert then self.assert(false, value) else assert(false, value) end -- and if we're still here, return a nil and throw the error message on as a second arg return nil, value end end local function backslash_replacement_function(c) if c == "\n" then return "\\n" elseif c == "\r" then return "\\r" elseif c == "\t" then return "\\t" elseif c == "\b" then return "\\b" elseif c == "\f" then return "\\f" elseif c == '"' then return '\\"' elseif c == '\\' then return '\\\\' else return string.format("\\u%04x", c:byte()) end end local chars_to_be_escaped_in_JSON_string = '[' .. '"' -- class sub-pattern to match a double quote .. '%\\' -- class sub-pattern to match a backslash .. '%z' -- class sub-pattern to match a null .. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters .. ']' local function json_string_literal(value) local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function) return '"' .. newval .. '"' end local function object_or_array(self, T, etc) -- -- We need to inspect all the keys... if there are any strings, we'll convert to a JSON -- object. If there are only numbers, it's a JSON array. -- -- If we'll be converting to a JSON object, we'll want to sort the keys so that the -- end result is deterministic. -- local string_keys = { } local number_keys = { } local number_keys_must_be_strings = false local maximum_number_key for key in pairs(T) do if type(key) == 'string' then table.insert(string_keys, key) elseif type(key) == 'number' then table.insert(number_keys, key) if key <= 0 or key >= math.huge then number_keys_must_be_strings = true elseif not maximum_number_key or key > maximum_number_key then maximum_number_key = key end else self:onEncodeError("can't encode table with a key of type " .. type(key), etc) end end if #string_keys == 0 and not number_keys_must_be_strings then -- -- An empty table, or a numeric-only array -- if #number_keys > 0 then return nil, maximum_number_key -- an array elseif tostring(T) == "JSON array" then return nil elseif tostring(T) == "JSON object" then return { } else -- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects return nil end end table.sort(string_keys) local map if #number_keys > 0 then -- -- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array -- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object. -- if self.noKeyConversion then self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc) end -- -- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings -- map = { } for key, val in pairs(T) do map[key] = val end table.sort(number_keys) -- -- Throw numeric keys in there as strings -- for _, number_key in ipairs(number_keys) do local string_key = tostring(number_key) if map[string_key] == nil then table.insert(string_keys , string_key) map[string_key] = T[number_key] else self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc) end end end return string_keys, nil, map end -- -- Encode -- -- 'options' is nil, or a table with possible keys: -- pretty -- if true, return a pretty-printed version -- indent -- a string (usually of spaces) used to indent each nested level -- align_keys -- if true, align all the keys when formatting a table -- local encode_value -- must predeclare because it calls itself function encode_value(self, value, parents, etc, options, indent) if value == nil then return 'null' elseif type(value) == 'string' then return json_string_literal(value) elseif type(value) == 'number' then if value ~= value then -- -- NaN (Not a Number). -- JSON has no NaN, so we have to fudge the best we can. This should really be a package option. -- return "null" elseif value >= math.huge then -- -- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should -- really be a package option. Note: at least with some implementations, positive infinity -- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is. -- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">=" -- case first. -- return "1e+9999" elseif value <= -math.huge then -- -- Negative infinity. -- JSON has no INF, so we have to fudge the best we can. This should really be a package option. -- return "-1e+9999" else return tostring(value) end elseif type(value) == 'boolean' then return tostring(value) elseif type(value) ~= 'table' then self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc) else -- -- A table to be converted to either a JSON object or array. -- local T = value if type(options) ~= 'table' then options = {} end if type(indent) ~= 'string' then indent = "" end if parents[T] then self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc) else parents[T] = true end local result_value local object_keys, maximum_number_key, map = object_or_array(self, T, etc) if maximum_number_key then -- -- An array... -- local ITEMS = { } for i = 1, maximum_number_key do table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent)) end if options.pretty then result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]" else result_value = "[" .. table.concat(ITEMS, ",") .. "]" end elseif object_keys then -- -- An object -- local TT = map or T if options.pretty then local KEYS = { } local max_key_length = 0 for _, key in ipairs(object_keys) do local encoded = encode_value(self, tostring(key), parents, etc, options, indent) if options.align_keys then max_key_length = math.max(max_key_length, #encoded) end table.insert(KEYS, encoded) end local key_indent = indent .. tostring(options.indent or "") local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "") local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s" local COMBINED_PARTS = { } for i, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent) table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val)) end result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}" else local PARTS = { } for _, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, indent) local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent) table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val)) end result_value = "{" .. table.concat(PARTS, ",") .. "}" end else -- -- An empty array/object... we'll treat it as an array, though it should really be an option -- result_value = "[]" end parents[T] = false return result_value end end function OBJDEF:encode(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode must be called in method format", etc) end return encode_value(self, value, {}, etc, options or nil) end function OBJDEF:encode_pretty(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc) end return encode_value(self, value, {}, etc, options or default_pretty_options) end function OBJDEF.__tostring() return "JSON encode/decode package" end OBJDEF.__index = OBJDEF function OBJDEF:new(args) local new = { } if args then for key, val in pairs(args) do new[key] = val end end return setmetatable(new, OBJDEF) end return OBJDEF:new() -- -- Version history: -- -- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really -- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines -- more flexible, and changed the default encode_pretty() to be more generally useful. -- -- Added a third 'options' argument to the encode() and encode_pretty() routines, to control -- how the encoding takes place. -- -- Updated docs to add assert() call to the loadfile() line, just as good practice so that -- if there is a problem loading JSON.lua, the appropriate error message will percolate up. -- -- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string, -- so that the source of the package, and its version number, are visible in compiled copies. -- -- 20140911.12 Minor lua cleanup. -- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'. -- (Thanks to SmugMug's David Parry for these.) -- -- 20140418.11 JSON nulls embedded within an array were being ignored, such that -- ["1",null,null,null,null,null,"seven"], -- would return -- {1,"seven"} -- It's now fixed to properly return -- {1, nil, nil, nil, nil, nil, "seven"} -- Thanks to "haddock" for catching the error. -- -- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up. -- -- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2", -- and this caused some problems. -- -- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate, -- and had of course diverged (encode_pretty didn't get the fixes that encode got, so -- sometimes produced incorrect results; thanks to Mattie for the heads up). -- -- Handle encoding tables with non-positive numeric keys (unlikely, but possible). -- -- If a table has both numeric and string keys, or its numeric keys are inappropriate -- (such as being non-positive or infinite), the numeric keys are turned into -- string keys appropriate for a JSON object. So, as before, -- JSON:encode({ "one", "two", "three" }) -- produces the array -- ["one","two","three"] -- but now something with mixed key types like -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- instead of throwing an error produces an object: -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To maintain the prior throw-an-error semantics, set -- JSON.noKeyConversion = true -- -- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry. -- -- 20130120.6 Comment update: added a link to the specific page on my blog where this code can -- be found, so that folks who come across the code outside of my blog can find updates -- more easily. -- -- 20111207.5 Added support for the 'etc' arguments, for better error reporting. -- -- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent. -- -- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules: -- -- * When encoding lua for JSON, Sparse numeric arrays are now handled by -- spitting out full arrays, such that -- JSON:encode({"one", "two", [10] = "ten"}) -- returns -- ["one","two",null,null,null,null,null,null,null,"ten"] -- -- In 20100810.2 and earlier, only up to the first non-null value would have been retained. -- -- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999". -- Version 20100810.2 and earlier created invalid JSON in both cases. -- -- * Unicode surrogate pairs are now detected when decoding JSON. -- -- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding -- -- 20100731.1 initial public release --
gpl-2.0
peymankhanas84877/Horror_Avatar_bot
libs/JSON.lua
3765
34843
-- -*- coding: utf-8 -*- -- -- Simple JSON encoding and decoding in pure Lua. -- -- Copyright 2010-2014 Jeffrey Friedl -- http://regex.info/blog/ -- -- Latest version: http://regex.info/blog/lua/json -- -- This code is released under a Creative Commons CC-BY "Attribution" License: -- http://creativecommons.org/licenses/by/3.0/deed.en_US -- -- It can be used for any purpose so long as the copyright notice above, -- the web-page links above, and the 'AUTHOR_NOTE' string below are -- maintained. Enjoy. -- local VERSION = 20141223.14 -- version history at end of file local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-" -- -- The 'AUTHOR_NOTE' variable exists so that information about the source -- of the package is maintained even in compiled versions. It's also -- included in OBJDEF below mostly to quiet warnings about unused variables. -- local OBJDEF = { VERSION = VERSION, AUTHOR_NOTE = AUTHOR_NOTE, } -- -- Simple JSON encoding and decoding in pure Lua. -- http://www.json.org/ -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- -- -- -- DECODING (from a JSON string to a Lua table) -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- If the JSON text is for an object or an array, e.g. -- { "what": "books", "count": 3 } -- or -- [ "Larry", "Curly", "Moe" ] -- -- the result is a Lua table, e.g. -- { what = "books", count = 3 } -- or -- { "Larry", "Curly", "Moe" } -- -- -- The encode and decode routines accept an optional second argument, -- "etc", which is not used during encoding or decoding, but upon error -- is passed along to error handlers. It can be of any type (including nil). -- -- -- -- ERROR HANDLING -- -- With most errors during decoding, this code calls -- -- JSON:onDecodeError(message, text, location, etc) -- -- with a message about the error, and if known, the JSON text being -- parsed and the byte count where the problem was discovered. You can -- replace the default JSON:onDecodeError() with your own function. -- -- The default onDecodeError() merely augments the message with data -- about the text and the location if known (and if a second 'etc' -- argument had been provided to decode(), its value is tacked onto the -- message as well), and then calls JSON.assert(), which itself defaults -- to Lua's built-in assert(), and can also be overridden. -- -- For example, in an Adobe Lightroom plugin, you might use something like -- -- function JSON:onDecodeError(message, text, location, etc) -- LrErrors.throwUserError("Internal Error: invalid JSON data") -- end -- -- or even just -- -- function JSON.assert(message) -- LrErrors.throwUserError("Internal Error: " .. message) -- end -- -- If JSON:decode() is passed a nil, this is called instead: -- -- JSON:onDecodeOfNilError(message, nil, nil, etc) -- -- and if JSON:decode() is passed HTML instead of JSON, this is called: -- -- JSON:onDecodeOfHTMLError(message, text, nil, etc) -- -- The use of the fourth 'etc' argument allows stronger coordination -- between decoding and error reporting, especially when you provide your -- own error-handling routines. Continuing with the the Adobe Lightroom -- plugin example: -- -- function JSON:onDecodeError(message, text, location, etc) -- local note = "Internal Error: invalid JSON data" -- if type(etc) = 'table' and etc.photo then -- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName') -- end -- LrErrors.throwUserError(note) -- end -- -- : -- : -- -- for i, photo in ipairs(photosToProcess) do -- : -- : -- local data = JSON:decode(someJsonText, { photo = photo }) -- : -- : -- end -- -- -- -- -- -- DECODING AND STRICT TYPES -- -- Because both JSON objects and JSON arrays are converted to Lua tables, -- it's not normally possible to tell which original JSON type a -- particular Lua table was derived from, or guarantee decode-encode -- round-trip equivalency. -- -- However, if you enable strictTypes, e.g. -- -- JSON = assert(loadfile "JSON.lua")() --load the routines -- JSON.strictTypes = true -- -- then the Lua table resulting from the decoding of a JSON object or -- JSON array is marked via Lua metatable, so that when re-encoded with -- JSON:encode() it ends up as the appropriate JSON type. -- -- (This is not the default because other routines may not work well with -- tables that have a metatable set, for example, Lightroom API calls.) -- -- -- ENCODING (from a lua table to a JSON string) -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false }) -- -- On error during encoding, this code calls: -- -- JSON:onEncodeError(message, etc) -- -- which you can override in your local JSON object. -- -- The 'etc' in the error call is the second argument to encode() -- and encode_pretty(), or nil if it wasn't provided. -- -- -- PRETTY-PRINTING -- -- An optional third argument, a table of options, allows a bit of -- configuration about how the encoding takes place: -- -- pretty = JSON:encode(val, etc, { -- pretty = true, -- if false, no other options matter -- indent = " ", -- this provides for a three-space indent per nesting level -- align_keys = false, -- see below -- }) -- -- encode() and encode_pretty() are identical except that encode_pretty() -- provides a default options table if none given in the call: -- -- { pretty = true, align_keys = false, indent = " " } -- -- For example, if -- -- JSON:encode(data) -- -- produces: -- -- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11} -- -- then -- -- JSON:encode_pretty(data) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- The following three lines return identical results: -- JSON:encode_pretty(data) -- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " }) -- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " }) -- -- An example of setting your own indent string: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " }) -- -- produces: -- -- { -- | "city": "Kyoto", -- | "climate": { -- | | "avg_temp": 16, -- | | "humidity": "high", -- | | "snowfall": "minimal" -- | }, -- | "country": "Japan", -- | "wards": 11 -- } -- -- An example of setting align_keys to true: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true }) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- which I must admit is kinda ugly, sorry. This was the default for -- encode_pretty() prior to version 20141223.14. -- -- -- AMBIGUOUS SITUATIONS DURING THE ENCODING -- -- During the encode, if a Lua table being encoded contains both string -- and numeric keys, it fits neither JSON's idea of an object, nor its -- idea of an array. To get around this, when any string key exists (or -- when non-positive numeric keys exist), numeric keys are converted to -- strings. -- -- For example, -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- produces the JSON object -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To prohibit this conversion and instead make it an error condition, set -- JSON.noKeyConversion = true -- -- -- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT -- -- assert -- onDecodeError -- onDecodeOfNilError -- onDecodeOfHTMLError -- onEncodeError -- -- If you want to create a separate Lua JSON object with its own error handlers, -- you can reload JSON.lua or use the :new() method. -- --------------------------------------------------------------------------- local default_pretty_indent = " " local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent } local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject function OBJDEF:newArray(tbl) return setmetatable(tbl or {}, isArray) end function OBJDEF:newObject(tbl) return setmetatable(tbl or {}, isObject) end local function unicode_codepoint_as_utf8(codepoint) -- -- codepoint is a number -- if codepoint <= 127 then return string.char(codepoint) elseif codepoint <= 2047 then -- -- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8 -- local highpart = math.floor(codepoint / 0x40) local lowpart = codepoint - (0x40 * highpart) return string.char(0xC0 + highpart, 0x80 + lowpart) elseif codepoint <= 65535 then -- -- 1110yyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x1000) local remainder = codepoint - 0x1000 * highpart local midpart = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midpart highpart = 0xE0 + highpart midpart = 0x80 + midpart lowpart = 0x80 + lowpart -- -- Check for an invalid character (thanks Andy R. at Adobe). -- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070 -- if ( highpart == 0xE0 and midpart < 0xA0 ) or ( highpart == 0xED and midpart > 0x9F ) or ( highpart == 0xF0 and midpart < 0x90 ) or ( highpart == 0xF4 and midpart > 0x8F ) then return "?" else return string.char(highpart, midpart, lowpart) end else -- -- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x40000) local remainder = codepoint - 0x40000 * highpart local midA = math.floor(remainder / 0x1000) remainder = remainder - 0x1000 * midA local midB = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midB return string.char(0xF0 + highpart, 0x80 + midA, 0x80 + midB, 0x80 + lowpart) end end function OBJDEF:onDecodeError(message, text, location, etc) if text then if location then message = string.format("%s at char %d of: %s", message, location, text) else message = string.format("%s: %s", message, text) end end if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError function OBJDEF:onEncodeError(message, etc) if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end local function grok_number(self, text, start, etc) -- -- Grab the integer part -- local integer_part = text:match('^-?[1-9]%d*', start) or text:match("^-?0", start) if not integer_part then self:onDecodeError("expected number", text, start, etc) end local i = start + integer_part:len() -- -- Grab an optional decimal part -- local decimal_part = text:match('^%.%d+', i) or "" i = i + decimal_part:len() -- -- Grab an optional exponential part -- local exponent_part = text:match('^[eE][-+]?%d+', i) or "" i = i + exponent_part:len() local full_number_text = integer_part .. decimal_part .. exponent_part local as_number = tonumber(full_number_text) if not as_number then self:onDecodeError("bad number", text, start, etc) end return as_number, i end local function grok_string(self, text, start, etc) if text:sub(start,start) ~= '"' then self:onDecodeError("expected string's opening quote", text, start, etc) end local i = start + 1 -- +1 to bypass the initial quote local text_len = text:len() local VALUE = "" while i <= text_len do local c = text:sub(i,i) if c == '"' then return VALUE, i + 1 end if c ~= '\\' then VALUE = VALUE .. c i = i + 1 elseif text:match('^\\b', i) then VALUE = VALUE .. "\b" i = i + 2 elseif text:match('^\\f', i) then VALUE = VALUE .. "\f" i = i + 2 elseif text:match('^\\n', i) then VALUE = VALUE .. "\n" i = i + 2 elseif text:match('^\\r', i) then VALUE = VALUE .. "\r" i = i + 2 elseif text:match('^\\t', i) then VALUE = VALUE .. "\t" i = i + 2 else local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if hex then i = i + 6 -- bypass what we just read -- We have a Unicode codepoint. It could be standalone, or if in the proper range and -- followed by another in a specific range, it'll be a two-code surrogate pair. local codepoint = tonumber(hex, 16) if codepoint >= 0xD800 and codepoint <= 0xDBFF then -- it's a hi surrogate... see whether we have a following low local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if lo_surrogate then i = i + 6 -- bypass the low surrogate we just read codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16) else -- not a proper low, so we'll just leave the first codepoint as is and spit it out. end end VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint) else -- just pass through what's escaped VALUE = VALUE .. text:match('^\\(.)', i) i = i + 2 end end end self:onDecodeError("unclosed string", text, start, etc) end local function skip_whitespace(text, start) local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2 if match_end then return match_end + 1 else return start end end local grok_one -- assigned later local function grok_object(self, text, start, etc) if text:sub(start,start) ~= '{' then self:onDecodeError("expected '{'", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '{' local VALUE = self.strictTypes and self:newObject { } or { } if text:sub(i,i) == '}' then return VALUE, i + 1 end local text_len = text:len() while i <= text_len do local key, new_i = grok_string(self, text, i, etc) i = skip_whitespace(text, new_i) if text:sub(i, i) ~= ':' then self:onDecodeError("expected colon", text, i, etc) end i = skip_whitespace(text, i + 1) local new_val, new_i = grok_one(self, text, i) VALUE[key] = new_val -- -- Expect now either '}' to end things, or a ',' to allow us to continue. -- i = skip_whitespace(text, new_i) local c = text:sub(i,i) if c == '}' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '}'", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '{'", text, start, etc) end local function grok_array(self, text, start, etc) if text:sub(start,start) ~= '[' then self:onDecodeError("expected '['", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '[' local VALUE = self.strictTypes and self:newArray { } or { } if text:sub(i,i) == ']' then return VALUE, i + 1 end local VALUE_INDEX = 1 local text_len = text:len() while i <= text_len do local val, new_i = grok_one(self, text, i) -- can't table.insert(VALUE, val) here because it's a no-op if val is nil VALUE[VALUE_INDEX] = val VALUE_INDEX = VALUE_INDEX + 1 i = skip_whitespace(text, new_i) -- -- Expect now either ']' to end things, or a ',' to allow us to continue. -- local c = text:sub(i,i) if c == ']' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '['", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '['", text, start, etc) end grok_one = function(self, text, start, etc) -- Skip any whitespace start = skip_whitespace(text, start) if start > text:len() then self:onDecodeError("unexpected end of string", text, nil, etc) end if text:find('^"', start) then return grok_string(self, text, start, etc) elseif text:find('^[-0123456789 ]', start) then return grok_number(self, text, start, etc) elseif text:find('^%{', start) then return grok_object(self, text, start, etc) elseif text:find('^%[', start) then return grok_array(self, text, start, etc) elseif text:find('^true', start) then return true, start + 4 elseif text:find('^false', start) then return false, start + 5 elseif text:find('^null', start) then return nil, start + 4 else self:onDecodeError("can't parse JSON", text, start, etc) end end function OBJDEF:decode(text, etc) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc) end if text == nil then self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc) elseif type(text) ~= 'string' then self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc) end if text:match('^%s*$') then return nil end if text:match('^%s*<') then -- Can't be JSON... we'll assume it's HTML self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc) end -- -- Ensure that it's not UTF-32 or UTF-16. -- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3), -- but this package can't handle them. -- if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc) end local success, value = pcall(grok_one, self, text, 1, etc) if success then return value else -- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert. if self.assert then self.assert(false, value) else assert(false, value) end -- and if we're still here, return a nil and throw the error message on as a second arg return nil, value end end local function backslash_replacement_function(c) if c == "\n" then return "\\n" elseif c == "\r" then return "\\r" elseif c == "\t" then return "\\t" elseif c == "\b" then return "\\b" elseif c == "\f" then return "\\f" elseif c == '"' then return '\\"' elseif c == '\\' then return '\\\\' else return string.format("\\u%04x", c:byte()) end end local chars_to_be_escaped_in_JSON_string = '[' .. '"' -- class sub-pattern to match a double quote .. '%\\' -- class sub-pattern to match a backslash .. '%z' -- class sub-pattern to match a null .. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters .. ']' local function json_string_literal(value) local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function) return '"' .. newval .. '"' end local function object_or_array(self, T, etc) -- -- We need to inspect all the keys... if there are any strings, we'll convert to a JSON -- object. If there are only numbers, it's a JSON array. -- -- If we'll be converting to a JSON object, we'll want to sort the keys so that the -- end result is deterministic. -- local string_keys = { } local number_keys = { } local number_keys_must_be_strings = false local maximum_number_key for key in pairs(T) do if type(key) == 'string' then table.insert(string_keys, key) elseif type(key) == 'number' then table.insert(number_keys, key) if key <= 0 or key >= math.huge then number_keys_must_be_strings = true elseif not maximum_number_key or key > maximum_number_key then maximum_number_key = key end else self:onEncodeError("can't encode table with a key of type " .. type(key), etc) end end if #string_keys == 0 and not number_keys_must_be_strings then -- -- An empty table, or a numeric-only array -- if #number_keys > 0 then return nil, maximum_number_key -- an array elseif tostring(T) == "JSON array" then return nil elseif tostring(T) == "JSON object" then return { } else -- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects return nil end end table.sort(string_keys) local map if #number_keys > 0 then -- -- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array -- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object. -- if self.noKeyConversion then self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc) end -- -- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings -- map = { } for key, val in pairs(T) do map[key] = val end table.sort(number_keys) -- -- Throw numeric keys in there as strings -- for _, number_key in ipairs(number_keys) do local string_key = tostring(number_key) if map[string_key] == nil then table.insert(string_keys , string_key) map[string_key] = T[number_key] else self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc) end end end return string_keys, nil, map end -- -- Encode -- -- 'options' is nil, or a table with possible keys: -- pretty -- if true, return a pretty-printed version -- indent -- a string (usually of spaces) used to indent each nested level -- align_keys -- if true, align all the keys when formatting a table -- local encode_value -- must predeclare because it calls itself function encode_value(self, value, parents, etc, options, indent) if value == nil then return 'null' elseif type(value) == 'string' then return json_string_literal(value) elseif type(value) == 'number' then if value ~= value then -- -- NaN (Not a Number). -- JSON has no NaN, so we have to fudge the best we can. This should really be a package option. -- return "null" elseif value >= math.huge then -- -- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should -- really be a package option. Note: at least with some implementations, positive infinity -- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is. -- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">=" -- case first. -- return "1e+9999" elseif value <= -math.huge then -- -- Negative infinity. -- JSON has no INF, so we have to fudge the best we can. This should really be a package option. -- return "-1e+9999" else return tostring(value) end elseif type(value) == 'boolean' then return tostring(value) elseif type(value) ~= 'table' then self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc) else -- -- A table to be converted to either a JSON object or array. -- local T = value if type(options) ~= 'table' then options = {} end if type(indent) ~= 'string' then indent = "" end if parents[T] then self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc) else parents[T] = true end local result_value local object_keys, maximum_number_key, map = object_or_array(self, T, etc) if maximum_number_key then -- -- An array... -- local ITEMS = { } for i = 1, maximum_number_key do table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent)) end if options.pretty then result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]" else result_value = "[" .. table.concat(ITEMS, ",") .. "]" end elseif object_keys then -- -- An object -- local TT = map or T if options.pretty then local KEYS = { } local max_key_length = 0 for _, key in ipairs(object_keys) do local encoded = encode_value(self, tostring(key), parents, etc, options, indent) if options.align_keys then max_key_length = math.max(max_key_length, #encoded) end table.insert(KEYS, encoded) end local key_indent = indent .. tostring(options.indent or "") local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "") local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s" local COMBINED_PARTS = { } for i, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent) table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val)) end result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}" else local PARTS = { } for _, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, indent) local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent) table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val)) end result_value = "{" .. table.concat(PARTS, ",") .. "}" end else -- -- An empty array/object... we'll treat it as an array, though it should really be an option -- result_value = "[]" end parents[T] = false return result_value end end function OBJDEF:encode(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode must be called in method format", etc) end return encode_value(self, value, {}, etc, options or nil) end function OBJDEF:encode_pretty(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc) end return encode_value(self, value, {}, etc, options or default_pretty_options) end function OBJDEF.__tostring() return "JSON encode/decode package" end OBJDEF.__index = OBJDEF function OBJDEF:new(args) local new = { } if args then for key, val in pairs(args) do new[key] = val end end return setmetatable(new, OBJDEF) end return OBJDEF:new() -- -- Version history: -- -- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really -- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines -- more flexible, and changed the default encode_pretty() to be more generally useful. -- -- Added a third 'options' argument to the encode() and encode_pretty() routines, to control -- how the encoding takes place. -- -- Updated docs to add assert() call to the loadfile() line, just as good practice so that -- if there is a problem loading JSON.lua, the appropriate error message will percolate up. -- -- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string, -- so that the source of the package, and its version number, are visible in compiled copies. -- -- 20140911.12 Minor lua cleanup. -- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'. -- (Thanks to SmugMug's David Parry for these.) -- -- 20140418.11 JSON nulls embedded within an array were being ignored, such that -- ["1",null,null,null,null,null,"seven"], -- would return -- {1,"seven"} -- It's now fixed to properly return -- {1, nil, nil, nil, nil, nil, "seven"} -- Thanks to "haddock" for catching the error. -- -- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up. -- -- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2", -- and this caused some problems. -- -- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate, -- and had of course diverged (encode_pretty didn't get the fixes that encode got, so -- sometimes produced incorrect results; thanks to Mattie for the heads up). -- -- Handle encoding tables with non-positive numeric keys (unlikely, but possible). -- -- If a table has both numeric and string keys, or its numeric keys are inappropriate -- (such as being non-positive or infinite), the numeric keys are turned into -- string keys appropriate for a JSON object. So, as before, -- JSON:encode({ "one", "two", "three" }) -- produces the array -- ["one","two","three"] -- but now something with mixed key types like -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- instead of throwing an error produces an object: -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To maintain the prior throw-an-error semantics, set -- JSON.noKeyConversion = true -- -- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry. -- -- 20130120.6 Comment update: added a link to the specific page on my blog where this code can -- be found, so that folks who come across the code outside of my blog can find updates -- more easily. -- -- 20111207.5 Added support for the 'etc' arguments, for better error reporting. -- -- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent. -- -- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules: -- -- * When encoding lua for JSON, Sparse numeric arrays are now handled by -- spitting out full arrays, such that -- JSON:encode({"one", "two", [10] = "ten"}) -- returns -- ["one","two",null,null,null,null,null,null,null,"ten"] -- -- In 20100810.2 and earlier, only up to the first non-null value would have been retained. -- -- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999". -- Version 20100810.2 and earlier created invalid JSON in both cases. -- -- * Unicode surrogate pairs are now detected when decoding JSON. -- -- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding -- -- 20100731.1 initial public release --
gpl-2.0
hfjgjfg/mohammad
libs/JSON.lua
3765
34843
-- -*- coding: utf-8 -*- -- -- Simple JSON encoding and decoding in pure Lua. -- -- Copyright 2010-2014 Jeffrey Friedl -- http://regex.info/blog/ -- -- Latest version: http://regex.info/blog/lua/json -- -- This code is released under a Creative Commons CC-BY "Attribution" License: -- http://creativecommons.org/licenses/by/3.0/deed.en_US -- -- It can be used for any purpose so long as the copyright notice above, -- the web-page links above, and the 'AUTHOR_NOTE' string below are -- maintained. Enjoy. -- local VERSION = 20141223.14 -- version history at end of file local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-" -- -- The 'AUTHOR_NOTE' variable exists so that information about the source -- of the package is maintained even in compiled versions. It's also -- included in OBJDEF below mostly to quiet warnings about unused variables. -- local OBJDEF = { VERSION = VERSION, AUTHOR_NOTE = AUTHOR_NOTE, } -- -- Simple JSON encoding and decoding in pure Lua. -- http://www.json.org/ -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- -- -- -- DECODING (from a JSON string to a Lua table) -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- If the JSON text is for an object or an array, e.g. -- { "what": "books", "count": 3 } -- or -- [ "Larry", "Curly", "Moe" ] -- -- the result is a Lua table, e.g. -- { what = "books", count = 3 } -- or -- { "Larry", "Curly", "Moe" } -- -- -- The encode and decode routines accept an optional second argument, -- "etc", which is not used during encoding or decoding, but upon error -- is passed along to error handlers. It can be of any type (including nil). -- -- -- -- ERROR HANDLING -- -- With most errors during decoding, this code calls -- -- JSON:onDecodeError(message, text, location, etc) -- -- with a message about the error, and if known, the JSON text being -- parsed and the byte count where the problem was discovered. You can -- replace the default JSON:onDecodeError() with your own function. -- -- The default onDecodeError() merely augments the message with data -- about the text and the location if known (and if a second 'etc' -- argument had been provided to decode(), its value is tacked onto the -- message as well), and then calls JSON.assert(), which itself defaults -- to Lua's built-in assert(), and can also be overridden. -- -- For example, in an Adobe Lightroom plugin, you might use something like -- -- function JSON:onDecodeError(message, text, location, etc) -- LrErrors.throwUserError("Internal Error: invalid JSON data") -- end -- -- or even just -- -- function JSON.assert(message) -- LrErrors.throwUserError("Internal Error: " .. message) -- end -- -- If JSON:decode() is passed a nil, this is called instead: -- -- JSON:onDecodeOfNilError(message, nil, nil, etc) -- -- and if JSON:decode() is passed HTML instead of JSON, this is called: -- -- JSON:onDecodeOfHTMLError(message, text, nil, etc) -- -- The use of the fourth 'etc' argument allows stronger coordination -- between decoding and error reporting, especially when you provide your -- own error-handling routines. Continuing with the the Adobe Lightroom -- plugin example: -- -- function JSON:onDecodeError(message, text, location, etc) -- local note = "Internal Error: invalid JSON data" -- if type(etc) = 'table' and etc.photo then -- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName') -- end -- LrErrors.throwUserError(note) -- end -- -- : -- : -- -- for i, photo in ipairs(photosToProcess) do -- : -- : -- local data = JSON:decode(someJsonText, { photo = photo }) -- : -- : -- end -- -- -- -- -- -- DECODING AND STRICT TYPES -- -- Because both JSON objects and JSON arrays are converted to Lua tables, -- it's not normally possible to tell which original JSON type a -- particular Lua table was derived from, or guarantee decode-encode -- round-trip equivalency. -- -- However, if you enable strictTypes, e.g. -- -- JSON = assert(loadfile "JSON.lua")() --load the routines -- JSON.strictTypes = true -- -- then the Lua table resulting from the decoding of a JSON object or -- JSON array is marked via Lua metatable, so that when re-encoded with -- JSON:encode() it ends up as the appropriate JSON type. -- -- (This is not the default because other routines may not work well with -- tables that have a metatable set, for example, Lightroom API calls.) -- -- -- ENCODING (from a lua table to a JSON string) -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false }) -- -- On error during encoding, this code calls: -- -- JSON:onEncodeError(message, etc) -- -- which you can override in your local JSON object. -- -- The 'etc' in the error call is the second argument to encode() -- and encode_pretty(), or nil if it wasn't provided. -- -- -- PRETTY-PRINTING -- -- An optional third argument, a table of options, allows a bit of -- configuration about how the encoding takes place: -- -- pretty = JSON:encode(val, etc, { -- pretty = true, -- if false, no other options matter -- indent = " ", -- this provides for a three-space indent per nesting level -- align_keys = false, -- see below -- }) -- -- encode() and encode_pretty() are identical except that encode_pretty() -- provides a default options table if none given in the call: -- -- { pretty = true, align_keys = false, indent = " " } -- -- For example, if -- -- JSON:encode(data) -- -- produces: -- -- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11} -- -- then -- -- JSON:encode_pretty(data) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- The following three lines return identical results: -- JSON:encode_pretty(data) -- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " }) -- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " }) -- -- An example of setting your own indent string: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " }) -- -- produces: -- -- { -- | "city": "Kyoto", -- | "climate": { -- | | "avg_temp": 16, -- | | "humidity": "high", -- | | "snowfall": "minimal" -- | }, -- | "country": "Japan", -- | "wards": 11 -- } -- -- An example of setting align_keys to true: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true }) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- which I must admit is kinda ugly, sorry. This was the default for -- encode_pretty() prior to version 20141223.14. -- -- -- AMBIGUOUS SITUATIONS DURING THE ENCODING -- -- During the encode, if a Lua table being encoded contains both string -- and numeric keys, it fits neither JSON's idea of an object, nor its -- idea of an array. To get around this, when any string key exists (or -- when non-positive numeric keys exist), numeric keys are converted to -- strings. -- -- For example, -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- produces the JSON object -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To prohibit this conversion and instead make it an error condition, set -- JSON.noKeyConversion = true -- -- -- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT -- -- assert -- onDecodeError -- onDecodeOfNilError -- onDecodeOfHTMLError -- onEncodeError -- -- If you want to create a separate Lua JSON object with its own error handlers, -- you can reload JSON.lua or use the :new() method. -- --------------------------------------------------------------------------- local default_pretty_indent = " " local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent } local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject function OBJDEF:newArray(tbl) return setmetatable(tbl or {}, isArray) end function OBJDEF:newObject(tbl) return setmetatable(tbl or {}, isObject) end local function unicode_codepoint_as_utf8(codepoint) -- -- codepoint is a number -- if codepoint <= 127 then return string.char(codepoint) elseif codepoint <= 2047 then -- -- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8 -- local highpart = math.floor(codepoint / 0x40) local lowpart = codepoint - (0x40 * highpart) return string.char(0xC0 + highpart, 0x80 + lowpart) elseif codepoint <= 65535 then -- -- 1110yyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x1000) local remainder = codepoint - 0x1000 * highpart local midpart = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midpart highpart = 0xE0 + highpart midpart = 0x80 + midpart lowpart = 0x80 + lowpart -- -- Check for an invalid character (thanks Andy R. at Adobe). -- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070 -- if ( highpart == 0xE0 and midpart < 0xA0 ) or ( highpart == 0xED and midpart > 0x9F ) or ( highpart == 0xF0 and midpart < 0x90 ) or ( highpart == 0xF4 and midpart > 0x8F ) then return "?" else return string.char(highpart, midpart, lowpart) end else -- -- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x40000) local remainder = codepoint - 0x40000 * highpart local midA = math.floor(remainder / 0x1000) remainder = remainder - 0x1000 * midA local midB = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midB return string.char(0xF0 + highpart, 0x80 + midA, 0x80 + midB, 0x80 + lowpart) end end function OBJDEF:onDecodeError(message, text, location, etc) if text then if location then message = string.format("%s at char %d of: %s", message, location, text) else message = string.format("%s: %s", message, text) end end if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError function OBJDEF:onEncodeError(message, etc) if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end local function grok_number(self, text, start, etc) -- -- Grab the integer part -- local integer_part = text:match('^-?[1-9]%d*', start) or text:match("^-?0", start) if not integer_part then self:onDecodeError("expected number", text, start, etc) end local i = start + integer_part:len() -- -- Grab an optional decimal part -- local decimal_part = text:match('^%.%d+', i) or "" i = i + decimal_part:len() -- -- Grab an optional exponential part -- local exponent_part = text:match('^[eE][-+]?%d+', i) or "" i = i + exponent_part:len() local full_number_text = integer_part .. decimal_part .. exponent_part local as_number = tonumber(full_number_text) if not as_number then self:onDecodeError("bad number", text, start, etc) end return as_number, i end local function grok_string(self, text, start, etc) if text:sub(start,start) ~= '"' then self:onDecodeError("expected string's opening quote", text, start, etc) end local i = start + 1 -- +1 to bypass the initial quote local text_len = text:len() local VALUE = "" while i <= text_len do local c = text:sub(i,i) if c == '"' then return VALUE, i + 1 end if c ~= '\\' then VALUE = VALUE .. c i = i + 1 elseif text:match('^\\b', i) then VALUE = VALUE .. "\b" i = i + 2 elseif text:match('^\\f', i) then VALUE = VALUE .. "\f" i = i + 2 elseif text:match('^\\n', i) then VALUE = VALUE .. "\n" i = i + 2 elseif text:match('^\\r', i) then VALUE = VALUE .. "\r" i = i + 2 elseif text:match('^\\t', i) then VALUE = VALUE .. "\t" i = i + 2 else local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if hex then i = i + 6 -- bypass what we just read -- We have a Unicode codepoint. It could be standalone, or if in the proper range and -- followed by another in a specific range, it'll be a two-code surrogate pair. local codepoint = tonumber(hex, 16) if codepoint >= 0xD800 and codepoint <= 0xDBFF then -- it's a hi surrogate... see whether we have a following low local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if lo_surrogate then i = i + 6 -- bypass the low surrogate we just read codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16) else -- not a proper low, so we'll just leave the first codepoint as is and spit it out. end end VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint) else -- just pass through what's escaped VALUE = VALUE .. text:match('^\\(.)', i) i = i + 2 end end end self:onDecodeError("unclosed string", text, start, etc) end local function skip_whitespace(text, start) local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2 if match_end then return match_end + 1 else return start end end local grok_one -- assigned later local function grok_object(self, text, start, etc) if text:sub(start,start) ~= '{' then self:onDecodeError("expected '{'", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '{' local VALUE = self.strictTypes and self:newObject { } or { } if text:sub(i,i) == '}' then return VALUE, i + 1 end local text_len = text:len() while i <= text_len do local key, new_i = grok_string(self, text, i, etc) i = skip_whitespace(text, new_i) if text:sub(i, i) ~= ':' then self:onDecodeError("expected colon", text, i, etc) end i = skip_whitespace(text, i + 1) local new_val, new_i = grok_one(self, text, i) VALUE[key] = new_val -- -- Expect now either '}' to end things, or a ',' to allow us to continue. -- i = skip_whitespace(text, new_i) local c = text:sub(i,i) if c == '}' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '}'", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '{'", text, start, etc) end local function grok_array(self, text, start, etc) if text:sub(start,start) ~= '[' then self:onDecodeError("expected '['", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '[' local VALUE = self.strictTypes and self:newArray { } or { } if text:sub(i,i) == ']' then return VALUE, i + 1 end local VALUE_INDEX = 1 local text_len = text:len() while i <= text_len do local val, new_i = grok_one(self, text, i) -- can't table.insert(VALUE, val) here because it's a no-op if val is nil VALUE[VALUE_INDEX] = val VALUE_INDEX = VALUE_INDEX + 1 i = skip_whitespace(text, new_i) -- -- Expect now either ']' to end things, or a ',' to allow us to continue. -- local c = text:sub(i,i) if c == ']' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '['", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '['", text, start, etc) end grok_one = function(self, text, start, etc) -- Skip any whitespace start = skip_whitespace(text, start) if start > text:len() then self:onDecodeError("unexpected end of string", text, nil, etc) end if text:find('^"', start) then return grok_string(self, text, start, etc) elseif text:find('^[-0123456789 ]', start) then return grok_number(self, text, start, etc) elseif text:find('^%{', start) then return grok_object(self, text, start, etc) elseif text:find('^%[', start) then return grok_array(self, text, start, etc) elseif text:find('^true', start) then return true, start + 4 elseif text:find('^false', start) then return false, start + 5 elseif text:find('^null', start) then return nil, start + 4 else self:onDecodeError("can't parse JSON", text, start, etc) end end function OBJDEF:decode(text, etc) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc) end if text == nil then self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc) elseif type(text) ~= 'string' then self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc) end if text:match('^%s*$') then return nil end if text:match('^%s*<') then -- Can't be JSON... we'll assume it's HTML self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc) end -- -- Ensure that it's not UTF-32 or UTF-16. -- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3), -- but this package can't handle them. -- if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc) end local success, value = pcall(grok_one, self, text, 1, etc) if success then return value else -- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert. if self.assert then self.assert(false, value) else assert(false, value) end -- and if we're still here, return a nil and throw the error message on as a second arg return nil, value end end local function backslash_replacement_function(c) if c == "\n" then return "\\n" elseif c == "\r" then return "\\r" elseif c == "\t" then return "\\t" elseif c == "\b" then return "\\b" elseif c == "\f" then return "\\f" elseif c == '"' then return '\\"' elseif c == '\\' then return '\\\\' else return string.format("\\u%04x", c:byte()) end end local chars_to_be_escaped_in_JSON_string = '[' .. '"' -- class sub-pattern to match a double quote .. '%\\' -- class sub-pattern to match a backslash .. '%z' -- class sub-pattern to match a null .. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters .. ']' local function json_string_literal(value) local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function) return '"' .. newval .. '"' end local function object_or_array(self, T, etc) -- -- We need to inspect all the keys... if there are any strings, we'll convert to a JSON -- object. If there are only numbers, it's a JSON array. -- -- If we'll be converting to a JSON object, we'll want to sort the keys so that the -- end result is deterministic. -- local string_keys = { } local number_keys = { } local number_keys_must_be_strings = false local maximum_number_key for key in pairs(T) do if type(key) == 'string' then table.insert(string_keys, key) elseif type(key) == 'number' then table.insert(number_keys, key) if key <= 0 or key >= math.huge then number_keys_must_be_strings = true elseif not maximum_number_key or key > maximum_number_key then maximum_number_key = key end else self:onEncodeError("can't encode table with a key of type " .. type(key), etc) end end if #string_keys == 0 and not number_keys_must_be_strings then -- -- An empty table, or a numeric-only array -- if #number_keys > 0 then return nil, maximum_number_key -- an array elseif tostring(T) == "JSON array" then return nil elseif tostring(T) == "JSON object" then return { } else -- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects return nil end end table.sort(string_keys) local map if #number_keys > 0 then -- -- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array -- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object. -- if self.noKeyConversion then self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc) end -- -- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings -- map = { } for key, val in pairs(T) do map[key] = val end table.sort(number_keys) -- -- Throw numeric keys in there as strings -- for _, number_key in ipairs(number_keys) do local string_key = tostring(number_key) if map[string_key] == nil then table.insert(string_keys , string_key) map[string_key] = T[number_key] else self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc) end end end return string_keys, nil, map end -- -- Encode -- -- 'options' is nil, or a table with possible keys: -- pretty -- if true, return a pretty-printed version -- indent -- a string (usually of spaces) used to indent each nested level -- align_keys -- if true, align all the keys when formatting a table -- local encode_value -- must predeclare because it calls itself function encode_value(self, value, parents, etc, options, indent) if value == nil then return 'null' elseif type(value) == 'string' then return json_string_literal(value) elseif type(value) == 'number' then if value ~= value then -- -- NaN (Not a Number). -- JSON has no NaN, so we have to fudge the best we can. This should really be a package option. -- return "null" elseif value >= math.huge then -- -- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should -- really be a package option. Note: at least with some implementations, positive infinity -- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is. -- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">=" -- case first. -- return "1e+9999" elseif value <= -math.huge then -- -- Negative infinity. -- JSON has no INF, so we have to fudge the best we can. This should really be a package option. -- return "-1e+9999" else return tostring(value) end elseif type(value) == 'boolean' then return tostring(value) elseif type(value) ~= 'table' then self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc) else -- -- A table to be converted to either a JSON object or array. -- local T = value if type(options) ~= 'table' then options = {} end if type(indent) ~= 'string' then indent = "" end if parents[T] then self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc) else parents[T] = true end local result_value local object_keys, maximum_number_key, map = object_or_array(self, T, etc) if maximum_number_key then -- -- An array... -- local ITEMS = { } for i = 1, maximum_number_key do table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent)) end if options.pretty then result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]" else result_value = "[" .. table.concat(ITEMS, ",") .. "]" end elseif object_keys then -- -- An object -- local TT = map or T if options.pretty then local KEYS = { } local max_key_length = 0 for _, key in ipairs(object_keys) do local encoded = encode_value(self, tostring(key), parents, etc, options, indent) if options.align_keys then max_key_length = math.max(max_key_length, #encoded) end table.insert(KEYS, encoded) end local key_indent = indent .. tostring(options.indent or "") local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "") local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s" local COMBINED_PARTS = { } for i, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent) table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val)) end result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}" else local PARTS = { } for _, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, indent) local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent) table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val)) end result_value = "{" .. table.concat(PARTS, ",") .. "}" end else -- -- An empty array/object... we'll treat it as an array, though it should really be an option -- result_value = "[]" end parents[T] = false return result_value end end function OBJDEF:encode(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode must be called in method format", etc) end return encode_value(self, value, {}, etc, options or nil) end function OBJDEF:encode_pretty(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc) end return encode_value(self, value, {}, etc, options or default_pretty_options) end function OBJDEF.__tostring() return "JSON encode/decode package" end OBJDEF.__index = OBJDEF function OBJDEF:new(args) local new = { } if args then for key, val in pairs(args) do new[key] = val end end return setmetatable(new, OBJDEF) end return OBJDEF:new() -- -- Version history: -- -- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really -- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines -- more flexible, and changed the default encode_pretty() to be more generally useful. -- -- Added a third 'options' argument to the encode() and encode_pretty() routines, to control -- how the encoding takes place. -- -- Updated docs to add assert() call to the loadfile() line, just as good practice so that -- if there is a problem loading JSON.lua, the appropriate error message will percolate up. -- -- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string, -- so that the source of the package, and its version number, are visible in compiled copies. -- -- 20140911.12 Minor lua cleanup. -- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'. -- (Thanks to SmugMug's David Parry for these.) -- -- 20140418.11 JSON nulls embedded within an array were being ignored, such that -- ["1",null,null,null,null,null,"seven"], -- would return -- {1,"seven"} -- It's now fixed to properly return -- {1, nil, nil, nil, nil, nil, "seven"} -- Thanks to "haddock" for catching the error. -- -- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up. -- -- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2", -- and this caused some problems. -- -- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate, -- and had of course diverged (encode_pretty didn't get the fixes that encode got, so -- sometimes produced incorrect results; thanks to Mattie for the heads up). -- -- Handle encoding tables with non-positive numeric keys (unlikely, but possible). -- -- If a table has both numeric and string keys, or its numeric keys are inappropriate -- (such as being non-positive or infinite), the numeric keys are turned into -- string keys appropriate for a JSON object. So, as before, -- JSON:encode({ "one", "two", "three" }) -- produces the array -- ["one","two","three"] -- but now something with mixed key types like -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- instead of throwing an error produces an object: -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To maintain the prior throw-an-error semantics, set -- JSON.noKeyConversion = true -- -- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry. -- -- 20130120.6 Comment update: added a link to the specific page on my blog where this code can -- be found, so that folks who come across the code outside of my blog can find updates -- more easily. -- -- 20111207.5 Added support for the 'etc' arguments, for better error reporting. -- -- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent. -- -- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules: -- -- * When encoding lua for JSON, Sparse numeric arrays are now handled by -- spitting out full arrays, such that -- JSON:encode({"one", "two", [10] = "ten"}) -- returns -- ["one","two",null,null,null,null,null,null,null,"ten"] -- -- In 20100810.2 and earlier, only up to the first non-null value would have been retained. -- -- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999". -- Version 20100810.2 and earlier created invalid JSON in both cases. -- -- * Unicode surrogate pairs are now detected when decoding JSON. -- -- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding -- -- 20100731.1 initial public release --
gpl-2.0
xdemolish/darkstar
scripts/zones/Port_Jeuno/npcs/Shami.lua
17
18277
----------------------------------- -- Area: Port Jeuno -- NPC: Shami -- Orb Seller (BCNM) -- @pos -14 8 44 246 ----------------------------------- package.loaded["scripts/zones/Port_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Port_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local NumberItem = trade:getItemCount(); local BeastmensSeal = player:getSeals(0); local KindredsSeal = player:getSeals(1); local KindredsCrest = player:getSeals(2); local HighKindredsCrest = player:getSeals(3); local SacredKindredsCrest = player:getSeals(4); ---------------------------------------------------------------------------------------------------------------------------- -------- Trading Seals/Crests to Shami ------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------------- if(trade:hasItemQty(1126,NumberItem) and trade:getItemCount() == NumberItem) then player:startEvent(0x0141,0,BeastmensSeal + NumberItem); -- Giving Shami Beastmen's Seal player:addSeals(NumberItem,0); player:tradeComplete(trade); elseif(trade:hasItemQty(1127,NumberItem) and trade:getItemCount() == NumberItem) then player:startEvent(0x0141,1,KindredsSeal + NumberItem); -- Giving Shami Kindred's Seal player:addSeals(NumberItem,1); player:tradeComplete(trade); elseif(trade:hasItemQty(2955,NumberItem) and trade:getItemCount() == NumberItem) then player:startEvent(0x0141,2,KindredsCrest + NumberItem); -- Giving Shami Kindred's Crest player:addSeals(NumberItem,2); player:tradeComplete(trade); elseif(trade:hasItemQty(2956,NumberItem) and trade:getItemCount() == NumberItem) then player:startEvent(0x0141,3,HighKindredsCrest + NumberItem); -- Giving Shami High Kindred's Crest player:addSeals(NumberItem,3); player:tradeComplete(trade); elseif(trade:hasItemQty(2957,NumberItem) and trade:getItemCount() == NumberItem) then player:startEvent(0x0141,3,SacredKindredsCrest + NumberItem); -- Giving Shami High Kindred's Crest player:addSeals(NumberItem,4); player:tradeComplete(trade); ---------------------------------------------------------------------------------------------------------------------------- -------- Trading Cracked BCNM Orbs or checking where you can bring the Orb ------------------------------------------------ ---------------------------------------------------------------------------------------------------------------------------- elseif(trade:hasItemQty(1551,1) and NumberItem == 1) then if (player:getVar("CloudyOrbIsCracked") == 1) then player:startEvent(0x0016); -- Cloudy Orb is Cracked player:setVar("CloudyOrbIsCracked",0); else player:startEvent(0x0005); -- Cloudy Orb is ok, List where you can take the orb. end elseif(trade:hasItemQty(1552,1) and NumberItem == 1) then if(player:getVar("SkyOrbIsCracked") == 1) then player:startEvent(0x0016); -- Sky Orb is Cracked player:setVar("SkyOrbIsCracked",0); else player:startEvent(0x0009); -- Sky Orb is ok, List where you can take the orb. end elseif(trade:hasItemQty(1131,1) and NumberItem == 1) then if(player:getVar("StarOrbIsCracked") == 1) then player:startEvent(0x0016); -- Star Orb is Cracked player:setVar("StarOrbIsCracked",0); else player:startEvent(0x0009); -- Star Orb is ok, List where you can take the orb. end elseif(trade:hasItemQty(1177,1) and NumberItem == 1) then if(player:getVar("CometOrbIsCracked") == 1) then player:startEvent(0x0016); -- Comet Orb is Cracked player:setVar("CometOrbIsCracked",0); else player:startEvent(0x0009); -- Comet Orb is ok, List where you can take the orb. end elseif(trade:hasItemQty(1130,1) and NumberItem == 1) then if(player:getVar("MoonOrbIsCracked") == 1) then player:startEvent(0x0016); -- Moon Orb is Cracked player:setVar("MoonOrbIsCracked",0); else player:startEvent(0x0009); -- Moon Orb is ok, List where you can take the orb. end ---------------------------------------------------------------------------------------------------------------------------- -------- Trading Cracked KSNM Orbs or checking where you can bring the Orb ------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------------- elseif(trade:hasItemQty(1180,1) and NumberItem == 1) then if(player:getVar("AtroposOrbIsCracked") == 1) then player:startEvent(0x0016); -- Atropos Orb is Cracked player:setVar("AtroposOrbIsCracked",0); else player:startEvent(0x0009); -- Atropos Orb is ok, List where you can take the orb. end elseif(trade:hasItemQty(1175,1) and NumberItem == 1) then if(player:getVar("ClothoOrbIsCracked") == 1) then player:startEvent(0x0016); -- Clotho Orb is Cracked player:setVar("ClothoOrbIsCracked",0); else player:startEvent(0x0009); -- Clotho Orb is ok, List where you can take the orb. end elseif(trade:hasItemQty(1178,1) and NumberItem == 1) then if(player:getVar("LachesisOrbIsCracked") == 1) then player:startEvent(0x0016) -- Lachesis Orb is Cracked player:setVar("LachesisOrbIsCracked",0); else player:startEvent(0x0009); -- Lachesis Orb is ok, List where you can take the orb. end elseif(trade:hasItemQty(1553,1) and NumberItem == 1) then if(player:getVar("ThemisOrbIsCracked") == 1) then player:startEvent(0x0016); -- Themis Orb is Cracked player:setVar("ThemisOrbIsCracked",0); else player:startEvent(0x000b); -- Themis Orb is ok, List where you can take the orb. end -- TODO : Add in trade-in for cracked Kindred Crest orbs (and High Kindred Crest) and find cutscene that tells you where you can bring it end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local oldBeastmensSeal = player:getVar("ShamiBeastmensSeal"); local oldKindredsSeal = player:getVar("ShamiKindredsSeal"); local oldKindredsCrest = player:getVar("ShamiKindredsCrest"); local oldHighKindredsCrest = player:getVar("ShamiHighKindredsCrest"); local BeastmensSeal = player:getSeals(0); local KindredsSeal = player:getSeals(1); local KindredsCrest = player:getSeals(2); local HighKindredsCrest = player:getSeals(3); local SacredKindredsCrest = player:getSeals(4); local WildcatJeuno = player:getVar("WildcatJeuno"); if (oldBeastmensSeal > 0) then player:addSeals(oldBeastmensSeal,0); player:setVar("ShamiBeastmensSeal",0); end if (oldKindredsSeal > 0) then player:addSeals(oldKindredsSeal,1); player:setVar("ShamiKindredsSeal",0); end if (oldKindredsCrest > 0) then player:addSeals(oldKindredsCrest,2); player:setVar("ShamiKindredsCrest",0); end if (oldHighKindredsCrest > 0) then player:addSeals(oldHighKindredsCrest,3); player:setVar("ShamiHighKindredsCrest",0); end -- TODO: player:startEvent(0x0142,0,0,0,0,1,0,1) -- First time talking to him WITH beastmen seal in inventory if (player:getQuestStatus(JEUNO,LURE_OF_THE_WILDCAT_JEUNO) == QUEST_ACCEPTED and player:getMaskBit(WildcatJeuno,17) == false) then player:startEvent(317); elseif(BeastmensSeal + KindredsSeal + KindredsCrest + HighKindredsCrest == 0) then player:startEvent(0x0017); -- Standard dialog ? else player:startEvent(0x0142,(KindredsSeal * 65536) + BeastmensSeal,(HighKindredsCrest * 65536) + KindredsCrest,SacredKindredsCrest,0,1,0,0); -- Standard dialog with menu end end; -- 0x0032 : 30 sceau conférie : choix entre clotho et lachésis -- 0x0018 : Après achat d'un orb (qu'bia, yughott, palborough, giddeus) -- 0x0008 : Après achat d'un orb (yughott, palborough, giddeus, qu'bia, ghelsba) -- 0x0004 : Après achat d'un orb (yughott, palborough, giddeus, ghelsba) -- 0x000a : Après achat d'un orb (yughott, palborough, giddeus) -- 0x0009 : Trade d'un orb ? (yughott, palborough, giddeus, ghelsba) -- 0x0005 : Trade d'un orb ? (yughott, palborough, giddeus, ghelsba) -- 0x000b : Trade d'un orb ? (yughott, palborough, giddeus) -- 0x001a : Trade d'un orb ? (qu'bia, yughott, palborough, giddeus) -- 0x001b : Trade d'un orb ? (qu'bia, chambre des oracles) -- 0x0016 : Trade d'un orb utilisé (il le recup) -- 0x0019 : Un seul échange autorisé par semaine -- 0x0141 : trade sceau + nombre player:startEvent(0x0141,0,15); -- 0 shbete, 1 s-confrerie, 2 s-demons, 3 s-seigneurdes hombre ----------------------------------- -- 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); local BeastmensSeal = player:getSeals(0); local KindredsSeal = player:getSeals(1); local KindredsCrest = player:getSeals(2); local HighKindredsCrest = player:getSeals(3); local SacredKindredsCrest = player:getSeals(4); if (csid == 0x0016) then -- Player gave Shami a cracked orb player:tradeComplete(); elseif (option >= 508 and option ~= 1073741824) then -- Player has asked to retrieve seals (1073741824 means someone hit escape during cutscene, don't remove this or people will get free seals) local takingSealCount = 0; if ((option + 2)% 256 == 0) then if (player:getFreeSlotsCount() >=1) then takingSealCount = (option + 2)/256 - 1; -- Every seal requested adds 256 to the option value. The lowest is one seal which sets the option to 510, two seals would be 510 + 256. etc player:delSeals(takingSealCount,0); player:addItem(1126,takingSealCount); player:messageSpecial(ITEM_OBTAINED,1126); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,1126); end elseif((option + 1)% 256 == 0) then if (player:getFreeSlotsCount() >=1) then takingSealCount = (option + 1)/256 - 1; -- Every seal requested adds 256 to the option value. The lowest is one seal which sets the option to 511, two seals would be 511 + 256. etc player:delSeals(takingSealCount,1); player:addItem(1127,takingSealCount); player:messageSpecial(ITEM_OBTAINED,1127); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,1127); end elseif((option + 3)% 256 == 0) then if (player:getFreeSlotsCount() >=1) then takingSealCount = (option + 3)/256 - 1; -- Every seal requested adds 256 to the option value. The lowest is one seal which sets the option to 509, two seals would be 509 + 256. etc player:delSeals(takingSealCount,2); player:addItem(2955,takingSealCount); player:messageSpecial(ITEM_OBTAINED,2955); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,2955); end elseif((option + 4)% 256 == 0) then if (player:getFreeSlotsCount() >=1) then takingSealCount = (option + 4)/256 - 1; -- Every seal requested adds 256 to the option value. The lowest is one seal which sets the option to 508, two seals would be 508 + 256. etc player:delSeals(takingSealCount,3); player:addItem(2956,takingSealCount); player:messageSpecial(ITEM_OBTAINED,2956); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,2956); end elseif((option + 5)% 256 == 0) then if (player:getFreeSlotsCount() >=1) then takingSealCount = (option + 5)/256 - 1; -- Every seal requested adds 256 to the option value. The lowest is one seal which sets the option to 508, two seals would be 508 + 256. etc player:delSeals(takingSealCount,4); player:addItem(2957,takingSealCount); player:messageSpecial(ITEM_OBTAINED,2957); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,2957); end end ---------------------------------------------------------------------------------------------------------------------------- -------- Begin BCNM orb Handout -------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------------- elseif (csid == 0x0142) then if (option == 1 and BeastmensSeal >= 20) then -- Player asked for Cloudy orb if(player:getFreeSlotsCount() >= 1 and player:hasItem(1551) == false) then player:delSeals(20,0); player:addItem(1551); player:messageSpecial(ITEM_OBTAINED,1551); player:setVar("CloudyOrbIsCracked",0); elseif(player:hasItem(1551))then player:addItem(1551); -- does not add the item but forces it to send the "you cannot carry anymore of these" message. else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,1551); end elseif (option == 2 and BeastmensSeal >= 30) then -- Player asked for Sky orb if(player:getFreeSlotsCount() >= 1 and player:hasItem(1552) == false) then player:delSeals(30,0); player:addItem(1552); player:messageSpecial(ITEM_OBTAINED,1552); player:setVar("SkyOrbIsCracked",0); elseif(player:hasItem(1552))then player:addItem(1552); -- does not add the item but forces it to send the "you cannot carry anymore of these" message. else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,1552); end elseif (option == 3 and BeastmensSeal >= 40) then -- Player asked for Star orb if(player:getFreeSlotsCount() >= 1 and player:hasItem(1131) == false) then player:delSeals(40,0); player:addItem(1131); player:messageSpecial(ITEM_OBTAINED,1131); player:setVar("StarOrbIsCracked",0); elseif(player:hasItem(1131) == true)then player:addItem(1131); -- does not add the item but forces it to send the "you cannot carry anymore of these" message. else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,1131); end elseif (option == 4 and BeastmensSeal >= 50) then -- Player asked for Comet orb if(player:getFreeSlotsCount() >= 1 and player:hasItem(1177) == false) then player:delSeals(50,0); player:addItem(1177); player:messageSpecial(ITEM_OBTAINED,1177); player:setVar("CometOrbIsCracked",0); elseif(player:hasItem(1177))then player:addItem(1177); -- does not add the item but forces it to send the "you cannot carry anymore of these" message. else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,1177); end elseif (option == 5 and BeastmensSeal >= 60) then -- Player asked for Moon orb if(player:getFreeSlotsCount() >= 1 and player:hasItem(1130) == false) then player:delSeals(60,0); player:addItem(1130); player:messageSpecial(ITEM_OBTAINED,1130); player:setVar("MoonOrbIsCracked",0); elseif(player:hasItem(1130)) then player:addItem(1130); -- does not add the item but forces it to send the "you cannot carry anymore of these" message. else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,1130); end ---------------------------------------------------------------------------------------------------------------------------- -------- Begin KSNM orb Handout -------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------------- elseif (option == 6 and KindredsSeal >= 30) then -- Player asked for Clotho Orb if(player:getFreeSlotsCount() >= 1 and player:hasItem(1175) == false) then player:delSeals(30,1); player:addItem(1175); player:messageSpecial(ITEM_OBTAINED,1175); player:setVar("ClothoOrbIsCracked",0); elseif(player:hasItem(1175))then player:addItem(1175); -- does not add the item but forces it to send the "you cannot carry anymore of these" message. else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,1175); end elseif (option == 7 and KindredsSeal >= 30) then -- Player asked for Lachesis Orb if(player:getFreeSlotsCount() >= 1 and player:hasItem(1178) == false) then player:delSeals(30,1); player:addItem(1178); player:messageSpecial(ITEM_OBTAINED,1178); player:setVar("LachesisOrbIsCracked",0); elseif(player:hasItem(1178) == true)then player:addItem(1178); -- does not add the item but forces it to send the "you cannot carry anymore of these" message. else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,1178); end elseif (option == 8 and KindredsSeal >= 30) then -- Player asked for Atropos Orb if(player:getFreeSlotsCount() >= 1 and player:hasItem(1180) == false) then player:delSeals(30,1); player:addItem(1180); player:messageSpecial(ITEM_OBTAINED,1180); player:setVar("AtroposOrbIsCracked",0); elseif(player:hasItem(1180))then player:addItem(1180); -- does not add the item but forces it to send the "you cannot carry anymore of these" message. else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,1180); end elseif (option == 9 and KindredsSeal >= 99) then -- Player asked for Themis Orb if(player:getFreeSlotsCount() >= 1 and player:hasItem(1553) == false) then player:delSeals(99,1); player:addItem(1553); player:messageSpecial(ITEM_OBTAINED,1553); player:setVar("ThemisOrbIsCracked",0); elseif(player:hasItem(1553))then player:addItem(1553); -- does not add the item but forces it to send the "you cannot carry anymore of these" message. else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,1553); end end -- TODO : Add in orbs for Kindred Crest exhcange (and High Kindred Crest) and find cutscene that tells you where you can bring it. elseif (csid == 317) then player:setMaskBit(player:getVar("WildcatJeuno"),"WildcatJeuno",17,true); end end;
gpl-3.0
jono659/enko
scripts/globals/mobskills/freezebite.lua
5
1288
----------------------------------- -- Freezebite -- Great Sword weapon skill -- Skill Level: 100 -- Delivers an ice elemental attack. Damage varies with TP. -- Aligned with the Snow Gorget & Breeze Gorget. -- Aligned with the Snow Belt & Breeze Belt. -- Element: Ice -- Modifiers: STR:30% ; INT:20% -- 100%TP 200%TP 300%TP -- 1.00 1.50 3.00 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); require("/scripts/globals/monstertpmoves"); ----------------------------------- function onMobSkillCheck(target,mob,skill) return 0; end; function onMobWeaponSkill(target, mob, skill) local params = {}; params.numHits = 1; params.ftp100 = 1; params.ftp200 = 1.5; params.ftp300 = 3; params.str_wsc = 0.3; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.2; 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; local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(mob, target, params); target:delHP(dmg); return dmg; end;
gpl-3.0
Arcscion/Shadowlyre
scripts/zones/Windurst_Waters_[S]/npcs/Pahpe_Rauulih.lua
3
1065
----------------------------------- -- Area: Windurst Waters (S) -- NPC: Pahpe Rauulih -- Type: Standard NPC -- @zone 94 -- !pos -39.740 -4.499 53.223 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Windurst_Waters_[S]/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x01ab); 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
zacscott/lovi
console.lua
1
5019
-- console.lua - virtual console control interface -- -- Copyright (C) 2015, Zachary Scott -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. local _ = require 'lib/moses' local config = require 'config' -- console state local x, y = 0, 0 -- current position local w, h = 0, 0 -- current screen size local screen = {} -- the current screen buffer -- console font local font = nil local fontWidth, fontHeight = 0, 0 -- console colour state local curfg, curbg = {}, {} -- current foreground & background colour local globalfb, globalbg = {}, {} -- default colours, important for perf -- returns the padding for the window local function padding() return config.get( 'padding' ) * 2 -- on both sides (up/down, left/right) end -- resizes the console to fit the screen size local function resize() w = math.floor( ( love.window.getWidth() - padding() ) / fontWidth ) - 1 h = math.floor( ( love.window.getHeight() - padding() ) / fontHeight ) - 1 end -- clears the screen, including cursor position, colours local function clear() screen = {} x, y = 0, 0 curfg, curbg = globalfg, globalbg end -- initialises the console view on screen local function init( foreground, background, fontName ) globalfg, globalbg = foreground, background -- load the default font local font = love.graphics.newFont( fontName, config.get( 'fontSize' ) ) -- set the default font love.graphics.setFont( font ) fontHeight = font:getHeight() fontWidth = font:getWidth( 'M' ) -- prime resize() clear() end -- returns the size of the screen in characters local function size() return w, h end -- returns the width of the console in characters local function width() return w end -- returns the height of the console in characters local function height() return h end -- return the dimensions in pixels for a screen of the given size (in cahracters) local function screenSize( w, h ) return w * fontWidth + padding(), h * fontHeight + padding() end -- sets the foreground colour function fg( colour ) curfg = colour end -- sets the background colour function bg( colour ) curbg = colour end -- move to the given position on the screen local function gotoxy( new_x, new_y ) x, y = new_x, new_y end -- starts a new line in the console local function newline() gotoxy( 0, y+1 ) end -- puts the given character at the current position on the screen local function put( str ) str = tostring( str ) for i = 1, #str do local ch = str:sub( i, i ) -- create row if not exist already if screen[ y ] == nil then screen[ y ] = {} end -- handle newlines if ch == '\n' then newline() return end -- put character on screen buffer screen[ y ][ x ] = { ch = ch, fg = curfg, bg = curbg, } x = x + 1 -- move to next character end end -- returns the character at the current location local function get() local row = screen[ y ] if row == nil then return '' else local cell = row[ x ] if cell == nil then return '' else return cell.ch end end end -- puts the given line at the given position local function putline( line ) put( line ) newline() end -- renders the console to the screen local function draw() love.graphics.clear() love.graphics.setBackgroundColor( globalbg ) _.each( screen, function( y, row ) local actualx = 0 _.each( row, function( x, value ) -- skip if past screen if x > width() then return end local screenx, screeny = actualx * fontWidth, y * fontHeight -- add padding around the window screenx = screenx + config.get( 'padding' ) screeny = screeny + config.get( 'padding' ) -- draw background if different from the global if value.bg ~= globalbg then love.graphics.setColor( value.bg ) love.graphics.rectangle( 'fill', screenx, screeny, fontWidth, fontHeight ) end -- draw the character love.graphics.setColor( value.fg ) love.graphics.print( tostring( value.ch ), screenx, screeny ) -- handle tab character rendering if value.ch == '\t' then actualx = actualx + config.get( 'tabSize' ) else actualx = actualx + 1 end end ) end ) end return { init = init, resize = resize, size = size, width = width, height = height, screenSize = screenSize, draw = draw, fg = fg, bg = bg, clear = clear, gotoxy = gotoxy, put = put, get = get, putline = putline, newline = newline }
gpl-3.0
jono659/enko
scripts/zones/Castle_Zvahl_Keep/npcs/Treasure_Chest.lua
12
3193
----------------------------------- -- Area: Castle Zvahl Keep -- NPC: Treasure Chest -- @zone 162 ----------------------------------- package.loaded["scripts/zones/Castle_Zvahl_Keep/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/treasure"); require("scripts/globals/quests"); require("scripts/zones/Castle_Zvahl_Keep/TextIDs"); local TreasureType = "Chest"; local TreasureLvL = 53; local TreasureMinLvL = 43; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- trade:hasItemQty(1048,1); -- Treasure Key -- trade:hasItemQty(1115,1); -- Skeleton Key -- trade:hasItemQty(1023,1); -- Living Key -- trade:hasItemQty(1022,1); -- Thief's Tools local questItemNeeded = 0; -- Player traded a key. if((trade:hasItemQty(1048,1) or trade:hasItemQty(1115,1) or trade:hasItemQty(1023,1) or trade:hasItemQty(1022,1)) and trade:getItemCount() == 1) then local zone = player:getZoneID(); -- IMPORTANT ITEM: keyitem ----------- if(player:getQuestStatus(BASTOK,A_TEST_OF_TRUE_LOVE) == QUEST_ACCEPTED and player:hasKeyItem(UN_MOMENT) == false) then questItemNeeded = 1; end -------------------------------------- local pack = openChance(player,npc,trade,TreasureType,TreasureLvL,TreasureMinLvL,questItemNeeded); local success = 0; if(pack[2] ~= nil) then player:messageSpecial(pack[2]); success = pack[1]; else success = pack[1]; end if(success ~= -2) then player:tradeComplete(); if(math.random() <= success) then -- 0 or 1 -- Succeded to open the coffer player:messageSpecial(CHEST_UNLOCKED); if(questItemNeeded == 1) then player:setVar("ATestOfTrueLoveProgress",player:getVar("ATestOfTrueLoveProgress")+1); player:addKeyItem(UN_MOMENT); player:messageSpecial(KEYITEM_OBTAINED,UN_MOMENT); -- Un moment for A Test Of True Love quest else player:setVar("["..zone.."]".."Treasure_"..TreasureType,os.time() + math.random(CHEST_MIN_ILLUSION_TIME,CHEST_MAX_ILLUSION_TIME)); local loot = chestLoot(zone,npc); -- print("loot array: "); -- debug -- print("[1]", loot[1]); -- debug -- print("[2]", loot[2]); -- debug if(loot[1]=="gil") then player:addGil(loot[2]*GIL_RATE); player:messageSpecial(GIL_OBTAINED,loot[2]*GIL_RATE); else -- Item player:addItem(loot[2]); player:messageSpecial(ITEM_OBTAINED,loot[2]); end end UpdateTreasureSpawnPoint(npc:getID()); end end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(CHEST_LOCKED,1048); 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
jono659/enko
scripts/zones/Ilrusi_Atoll/Zone.lua
36
1453
----------------------------------- -- -- Zone: Ilrusi_Atoll -- zone 55 ----------------------------------- require("scripts/globals/settings"); package.loaded["scripts/zones/Ilrusi_Atoll/TextIDs"] = nil; require("scripts/zones/Ilrusi_Atoll/TextIDs"); require("scripts/globals/settings"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) cs = -1; --------------RANDOMIZE COFFER------------------------ local correctcoffer = math.random(17002505,17002516); SetServerVariable("correctcoffer",correctcoffer); printf("corect_golden_salvage_coffer: %u",correctcoffer); --------------------------------------------------- return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) 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
jono659/enko
scripts/zones/Temenos/mobs/Telchines_White_Mage.lua
17
1139
----------------------------------- -- Area: Temenos N T -- NPC: Telchines_White_Mage ----------------------------------- package.loaded["scripts/zones/Temenos/TextIDs"] = nil; ----------------------------------- require("scripts/globals/limbus"); require("scripts/zones/Temenos/TextIDs"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) if(IsMobDead(16928788)==true and IsMobDead(16928789)==true and IsMobDead(16928792)==true and IsMobDead(16928793)==true )then GetNPCByID(16928768+26):setPos(19,80,430); GetNPCByID(16928768+26):setStatus(STATUS_NORMAL); GetNPCByID(16928768+160):setPos(16,80,430); GetNPCByID(16928768+160):setStatus(STATUS_NORMAL); GetNPCByID(16928768+211):setPos(22,80,430); GetNPCByID(16928768+211):setStatus(STATUS_NORMAL); end end;
gpl-3.0
Arcscion/Shadowlyre
scripts/globals/mobskills/fuscous_ooze.lua
34
1073
--------------------------------------------------- -- Fuscous Ooze -- Family: Slugs -- Description: A dusky slime inflicts encumberance and weight. -- Type: Magical -- Utsusemi/Blink absorb: Ignores shadows -- Range: Cone -- Notes: --------------------------------------------------- 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) -- TODO: Encumberance seems to do nothing? local typeEffect = EFFECT_WEIGHT; local duration = 45; MobStatusEffectMove(mob, target, typeEffect, 50, 0, duration); local dmgmod = 1; local baseDamage = mob:getWeaponDmg()*3.7; local info = MobMagicalMove(mob,target,skill,baseDamage,ELE_WATER,dmgmod,TP_NO_EFFECT); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_WATER,MOBPARAM_IGNORE_SHADOWS); target:delHP(dmg); return dmg; end;
gpl-3.0
spawnazzo/luci
modules/admin-mini/luasrc/model/cbi/mini/wifi.lua
73
11663
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- -- Data init -- local fs = require "nixio.fs" local sys = require "luci.sys" local uci = require "luci.model.uci".cursor() if not uci:get("network", "wan") then uci:section("network", "interface", "wan", {proto="none", ifname=" "}) uci:save("network") uci:commit("network") end local wlcursor = luci.model.uci.cursor_state() local wireless = wlcursor:get_all("wireless") local wifidevs = {} local ifaces = {} for k, v in pairs(wireless) do if v[".type"] == "wifi-iface" then table.insert(ifaces, v) end end wlcursor:foreach("wireless", "wifi-device", function(section) table.insert(wifidevs, section[".name"]) end) -- Main Map -- m = Map("wireless", translate("Wifi"), translate("Here you can configure installed wifi devices.")) m:chain("network") -- Status Table -- s = m:section(Table, ifaces, translate("Networks")) link = s:option(DummyValue, "_link", translate("Link")) function link.cfgvalue(self, section) local ifname = self.map:get(section, "ifname") local iwinfo = sys.wifi.getiwinfo(ifname) return iwinfo and "%d/%d" %{ iwinfo.quality, iwinfo.quality_max } or "-" end essid = s:option(DummyValue, "ssid", "ESSID") bssid = s:option(DummyValue, "_bsiid", "BSSID") function bssid.cfgvalue(self, section) local ifname = self.map:get(section, "ifname") local iwinfo = sys.wifi.getiwinfo(ifname) return iwinfo and iwinfo.bssid or "-" end channel = s:option(DummyValue, "channel", translate("Channel")) function channel.cfgvalue(self, section) return wireless[self.map:get(section, "device")].channel end protocol = s:option(DummyValue, "_mode", translate("Protocol")) function protocol.cfgvalue(self, section) local mode = wireless[self.map:get(section, "device")].mode return mode and "802." .. mode end mode = s:option(DummyValue, "mode", translate("Mode")) encryption = s:option(DummyValue, "encryption", translate("<abbr title=\"Encrypted\">Encr.</abbr>")) power = s:option(DummyValue, "_power", translate("Power")) function power.cfgvalue(self, section) local ifname = self.map:get(section, "ifname") local iwinfo = sys.wifi.getiwinfo(ifname) return iwinfo and "%d dBm" % iwinfo.txpower or "-" end scan = s:option(Button, "_scan", translate("Scan")) scan.inputstyle = "find" function scan.cfgvalue(self, section) return self.map:get(section, "ifname") or false end -- WLAN-Scan-Table -- t2 = m:section(Table, {}, translate("<abbr title=\"Wireless Local Area Network\">WLAN</abbr>-Scan"), translate("Wifi networks in your local environment")) function scan.write(self, section) m.autoapply = false t2.render = t2._render local ifname = self.map:get(section, "ifname") local iwinfo = sys.wifi.getiwinfo(ifname) if iwinfo then local _, cell for _, cell in ipairs(iwinfo.scanlist) do t2.data[#t2.data+1] = { Quality = "%d/%d" %{ cell.quality, cell.quality_max }, ESSID = cell.ssid, Address = cell.bssid, Mode = cell.mode, ["Encryption key"] = cell.encryption.enabled and "On" or "Off", ["Signal level"] = "%d dBm" % cell.signal, ["Noise level"] = "%d dBm" % iwinfo.noise } end end end t2._render = t2.render t2.render = function() end t2:option(DummyValue, "Quality", translate("Link")) essid = t2:option(DummyValue, "ESSID", "ESSID") function essid.cfgvalue(self, section) return self.map:get(section, "ESSID") end t2:option(DummyValue, "Address", "BSSID") t2:option(DummyValue, "Mode", translate("Mode")) chan = t2:option(DummyValue, "channel", translate("Channel")) function chan.cfgvalue(self, section) return self.map:get(section, "Channel") or self.map:get(section, "Frequency") or "-" end t2:option(DummyValue, "Encryption key", translate("<abbr title=\"Encrypted\">Encr.</abbr>")) t2:option(DummyValue, "Signal level", translate("Signal")) t2:option(DummyValue, "Noise level", translate("Noise")) if #wifidevs < 1 then return m end -- Config Section -- s = m:section(NamedSection, wifidevs[1], "wifi-device", translate("Devices")) s.addremove = false en = s:option(Flag, "disabled", translate("enable")) en.rmempty = false en.enabled = "0" en.disabled = "1" function en.cfgvalue(self, section) return Flag.cfgvalue(self, section) or "0" end local hwtype = m:get(wifidevs[1], "type") if hwtype == "atheros" then mode = s:option(ListValue, "hwmode", translate("Mode")) mode.override_values = true mode:value("", "auto") mode:value("11b", "802.11b") mode:value("11g", "802.11g") mode:value("11a", "802.11a") mode:value("11bg", "802.11b+g") mode.rmempty = true end ch = s:option(Value, "channel", translate("Channel")) for i=1, 14 do ch:value(i, i .. " (2.4 GHz)") end s = m:section(TypedSection, "wifi-iface", translate("Local Network")) s.anonymous = true s.addremove = false s:option(Value, "ssid", translate("Network Name (<abbr title=\"Extended Service Set Identifier\">ESSID</abbr>)")) bssid = s:option(Value, "bssid", translate("<abbr title=\"Basic Service Set Identifier\">BSSID</abbr>")) local devs = {} luci.model.uci.cursor():foreach("wireless", "wifi-device", function (section) table.insert(devs, section[".name"]) end) if #devs > 1 then device = s:option(DummyValue, "device", translate("Device")) else s.defaults.device = devs[1] end mode = s:option(ListValue, "mode", translate("Mode")) mode.override_values = true mode:value("ap", translate("Provide (Access Point)")) mode:value("adhoc", translate("Independent (Ad-Hoc)")) mode:value("sta", translate("Join (Client)")) function mode.write(self, section, value) if value == "sta" then local oldif = m.uci:get("network", "wan", "ifname") if oldif and oldif ~= " " then m.uci:set("network", "wan", "_ifname", oldif) end m.uci:set("network", "wan", "ifname", " ") self.map:set(section, "network", "wan") else if m.uci:get("network", "wan", "_ifname") then m.uci:set("network", "wan", "ifname", m.uci:get("network", "wan", "_ifname")) end self.map:set(section, "network", "lan") end return ListValue.write(self, section, value) end encr = s:option(ListValue, "encryption", translate("Encryption")) encr.override_values = true encr:value("none", "No Encryption") encr:value("wep", "WEP") if hwtype == "atheros" or hwtype == "mac80211" then local supplicant = fs.access("/usr/sbin/wpa_supplicant") local hostapd = fs.access("/usr/sbin/hostapd") if hostapd and supplicant then encr:value("psk", "WPA-PSK") encr:value("psk2", "WPA2-PSK") encr:value("psk-mixed", "WPA-PSK/WPA2-PSK Mixed Mode") encr:value("wpa", "WPA-Radius", {mode="ap"}, {mode="sta"}) encr:value("wpa2", "WPA2-Radius", {mode="ap"}, {mode="sta"}) elseif hostapd and not supplicant then encr:value("psk", "WPA-PSK", {mode="ap"}, {mode="adhoc"}) encr:value("psk2", "WPA2-PSK", {mode="ap"}, {mode="adhoc"}) encr:value("psk-mixed", "WPA-PSK/WPA2-PSK Mixed Mode", {mode="ap"}, {mode="adhoc"}) encr:value("wpa", "WPA-Radius", {mode="ap"}) encr:value("wpa2", "WPA2-Radius", {mode="ap"}) encr.description = translate( "WPA-Encryption requires wpa_supplicant (for client mode) or hostapd (for AP " .. "and ad-hoc mode) to be installed." ) elseif not hostapd and supplicant then encr:value("psk", "WPA-PSK", {mode="sta"}) encr:value("psk2", "WPA2-PSK", {mode="sta"}) encr:value("psk-mixed", "WPA-PSK/WPA2-PSK Mixed Mode", {mode="sta"}) encr:value("wpa", "WPA-EAP", {mode="sta"}) encr:value("wpa2", "WPA2-EAP", {mode="sta"}) encr.description = translate( "WPA-Encryption requires wpa_supplicant (for client mode) or hostapd (for AP " .. "and ad-hoc mode) to be installed." ) else encr.description = translate( "WPA-Encryption requires wpa_supplicant (for client mode) or hostapd (for AP " .. "and ad-hoc mode) to be installed." ) end elseif hwtype == "broadcom" then encr:value("psk", "WPA-PSK") encr:value("psk2", "WPA2-PSK") encr:value("psk+psk2", "WPA-PSK/WPA2-PSK Mixed Mode") end key = s:option(Value, "key", translate("Key")) key:depends("encryption", "wep") key:depends("encryption", "psk") key:depends("encryption", "psk2") key:depends("encryption", "psk+psk2") key:depends("encryption", "psk-mixed") key:depends({mode="ap", encryption="wpa"}) key:depends({mode="ap", encryption="wpa2"}) key.rmempty = true key.password = true server = s:option(Value, "server", translate("Radius-Server")) server:depends({mode="ap", encryption="wpa"}) server:depends({mode="ap", encryption="wpa2"}) server.rmempty = true port = s:option(Value, "port", translate("Radius-Port")) port:depends({mode="ap", encryption="wpa"}) port:depends({mode="ap", encryption="wpa2"}) port.rmempty = true if hwtype == "atheros" or hwtype == "mac80211" then nasid = s:option(Value, "nasid", translate("NAS ID")) nasid:depends({mode="ap", encryption="wpa"}) nasid:depends({mode="ap", encryption="wpa2"}) nasid.rmempty = true eaptype = s:option(ListValue, "eap_type", translate("EAP-Method")) eaptype:value("TLS") eaptype:value("TTLS") eaptype:value("PEAP") eaptype:depends({mode="sta", encryption="wpa"}) eaptype:depends({mode="sta", encryption="wpa2"}) cacert = s:option(FileUpload, "ca_cert", translate("Path to CA-Certificate")) cacert:depends({mode="sta", encryption="wpa"}) cacert:depends({mode="sta", encryption="wpa2"}) privkey = s:option(FileUpload, "priv_key", translate("Path to Private Key")) privkey:depends({mode="sta", eap_type="TLS", encryption="wpa2"}) privkey:depends({mode="sta", eap_type="TLS", encryption="wpa"}) privkeypwd = s:option(Value, "priv_key_pwd", translate("Password of Private Key")) privkeypwd:depends({mode="sta", eap_type="TLS", encryption="wpa2"}) privkeypwd:depends({mode="sta", eap_type="TLS", encryption="wpa"}) auth = s:option(Value, "auth", translate("Authentication")) auth:value("PAP") auth:value("CHAP") auth:value("MSCHAP") auth:value("MSCHAPV2") auth:depends({mode="sta", eap_type="PEAP", encryption="wpa2"}) auth:depends({mode="sta", eap_type="PEAP", encryption="wpa"}) auth:depends({mode="sta", eap_type="TTLS", encryption="wpa2"}) auth:depends({mode="sta", eap_type="TTLS", encryption="wpa"}) identity = s:option(Value, "identity", translate("Identity")) identity:depends({mode="sta", eap_type="PEAP", encryption="wpa2"}) identity:depends({mode="sta", eap_type="PEAP", encryption="wpa"}) identity:depends({mode="sta", eap_type="TTLS", encryption="wpa2"}) identity:depends({mode="sta", eap_type="TTLS", encryption="wpa"}) password = s:option(Value, "password", translate("Password")) password:depends({mode="sta", eap_type="PEAP", encryption="wpa2"}) password:depends({mode="sta", eap_type="PEAP", encryption="wpa"}) password:depends({mode="sta", eap_type="TTLS", encryption="wpa2"}) password:depends({mode="sta", eap_type="TTLS", encryption="wpa"}) end if hwtype == "atheros" or hwtype == "broadcom" then iso = s:option(Flag, "isolate", translate("AP-Isolation"), translate("Prevents Client to Client communication")) iso.rmempty = true iso:depends("mode", "ap") hide = s:option(Flag, "hidden", translate("Hide <abbr title=\"Extended Service Set Identifier\">ESSID</abbr>")) hide.rmempty = true hide:depends("mode", "ap") end if hwtype == "mac80211" or hwtype == "atheros" then bssid:depends({mode="adhoc"}) end if hwtype == "broadcom" then bssid:depends({mode="wds"}) bssid:depends({mode="adhoc"}) end return m
apache-2.0
Arcscion/Shadowlyre
scripts/zones/Bastok_Markets_[S]/npcs/Silke.lua
17
1235
----------------------------------- -- Area: Bastok Markets (S) -- NPC: Silke -- Standard Merchant NPC ----------------------------------- package.loaded["scripts/zones/Bastok_Markets_[S]/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Bastok_Markets_[S]/TextIDs"); require("scripts/globals/shop"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,SILKE_SHOP_DIALOG); stock = {0x17ab,29925, -- Animus Augeo Schema 0x17ac,29925, -- Animus Minuo Schema 0x17ad,36300} -- Adloquim Schema 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
Tikiwinkie/overthebox-feeds
luci-mod-admin-full/luasrc/model/cbi/admin_network/routes.lua
58
2299
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Licensed to the public under the Apache License 2.0. local wa = require "luci.tools.webadmin" local fs = require "nixio.fs" m = Map("network", translate("Routes"), translate("Routes specify over which interface and gateway a certain host or network " .. "can be reached.")) s = m:section(TypedSection, "route", translate("Static IPv4 Routes")) s.addremove = true s.anonymous = true s.template = "cbi/tblsection" iface = s:option(ListValue, "interface", translate("Interface")) wa.cbi_add_networks(iface) t = s:option(Value, "target", translate("Target"), translate("Host-<abbr title=\"Internet Protocol Address\">IP</abbr> or Network")) t.datatype = "ip4addr" t.rmempty = false n = s:option(Value, "netmask", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Netmask"), translate("if target is a network")) n.placeholder = "255.255.255.255" n.datatype = "ip4addr" n.rmempty = true g = s:option(Value, "gateway", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Gateway")) g.datatype = "ip4addr" g.rmempty = true metric = s:option(Value, "metric", translate("Metric")) metric.placeholder = 0 metric.datatype = "range(0,255)" metric.rmempty = true mtu = s:option(Value, "mtu", translate("MTU")) mtu.placeholder = 1500 mtu.datatype = "range(64,9000)" mtu.rmempty = true if fs.access("/proc/net/ipv6_route") then s = m:section(TypedSection, "route6", translate("Static IPv6 Routes")) s.addremove = true s.anonymous = true s.template = "cbi/tblsection" iface = s:option(ListValue, "interface", translate("Interface")) wa.cbi_add_networks(iface) t = s:option(Value, "target", translate("Target"), translate("<abbr title=\"Internet Protocol Version 6\">IPv6</abbr>-Address or Network (CIDR)")) t.datatype = "ip6addr" t.rmempty = false g = s:option(Value, "gateway", translate("<abbr title=\"Internet Protocol Version 6\">IPv6</abbr>-Gateway")) g.datatype = "ip6addr" g.rmempty = true metric = s:option(Value, "metric", translate("Metric")) metric.placeholder = 0 metric.datatype = "range(0,65535)" -- XXX: not sure metric.rmempty = true mtu = s:option(Value, "mtu", translate("MTU")) mtu.placeholder = 1500 mtu.datatype = "range(64,9000)" mtu.rmempty = true end return m
gpl-3.0
N0U/Zero-K
units/amphimpulse.lua
4
5937
unitDef = { unitname = [[amphimpulse]], name = [[Archer]], description = [[Amphibious Raider/Riot Bot]], acceleration = 0.2, activateWhenBuilt = true, brakeRate = 0.4, buildCostMetal = 200, buildPic = [[amphimpulse.png]], canGuard = true, canMove = true, canPatrol = true, category = [[SINK]], corpse = [[DEAD]], customParams = { amph_regen = 40, amph_submerged_at = 40, sink_on_emp = 1, maxwatertank = [[180]], floattoggle = [[1]], }, explodeAs = [[BIG_UNITEX]], footprintX = 2, footprintZ = 2, iconType = [[amphraider]], idleAutoHeal = 5, idleTime = 1800, leaveTracks = true, maxDamage = 820, maxSlope = 36, maxVelocity = 2.5, minCloakDistance = 75, movementClass = [[AKBOT2]], noChaseCategory = [[TERRAFORM FIXEDWING GUNSHIP HOVER SHIP SWIM SUB LAND FLOAT SINK TURRET]], objectName = [[amphraider2.s3o]], script = [[amphimpulse.lua]], selfDestructAs = [[BIG_UNITEX]], sfxtypes = { explosiongenerators = { [[custom:watercannon_muzzle]], }, }, sightDistance = 500, sonarDistance = 500, trackOffset = 0, trackStrength = 8, trackStretch = 1, trackType = [[ComTrack]], trackWidth = 22, turnRate = 1200, upright = true, weapons = { { def = [[WATERCANNON]], badTargetCategory = [[FIXEDWING]], onlyTargetCategory = [[FIXEDWING LAND SINK TURRET SHIP SWIM FLOAT GUNSHIP HOVER]], }, { def = [[FAKE_WATERCANNON]], badTargetCategory = [[FIXEDWING]], onlyTargetCategory = [[FIXEDWING LAND SINK TURRET SHIP SWIM FLOAT GUNSHIP HOVER]], }, }, weaponDefs = { WATERCANNON = { name = [[Water Cutter]], areaOfEffect = 128, beamTime = 1/30, beamTtl = 10, beamDecay = 0.80, coreThickness = 0, craterBoost = 0, craterMult = 0, customParams = { impulse = [[30]], impulsemaxdepth = [[20]], impulsedepthmult = [[0.5]], normaldamage = [[1]], stats_damage = 10.4, stats_hide_damage = 1, -- continuous laser stats_hide_reload = 1, light_camera_height = 1500, light_color = [[0 0.03 0.07]], light_radius = 100, }, damage = { default = 1.3, subs = 1, }, explosionGenerator = [[custom:watercannon_impact]], impactOnly = false, interceptedByShieldType = 1, largeBeamLaser = true, laserFlareSize = 0, minIntensity = 1, noSelfDamage = true, range = 300, reloadtime = 0.1, rgbColor = [[0.2 0.2 0.3]], scrollSpeed = 10, -- soundStart = [[weapon/laser/laser_burn8]], soundTrigger = true, sweepfire = false, texture1 = [[corelaser]], texture2 = [[wake]], texture3 = [[wake]], texture4 = [[wake]], thickness = 7, tileLength = 100, tolerance = 5000, turret = true, weaponType = [[BeamLaser]], weaponVelocity = 500, }, FAKE_WATERCANNON = { name = [[Fake Water Cutter]], areaOfEffect = 128, beamTime = 1/30, beamTtl = 10, beamDecay = 0.80, coreThickness = 0, craterBoost = 0, craterMult = 0, customParams = { impulse = [[30]], normaldamage = [[1]], }, damage = { default = 1.3, subs = 1, }, explosionGenerator = [[custom:watercannon_impact]], impactOnly = false, interceptedByShieldType = 1, largeBeamLaser = true, laserFlareSize = 0, minIntensity = 1, noSelfDamage = true, range = 300, reloadtime = 0.1, rgbColor = [[0.2 0.2 0.3]], scrollSpeed = 10, -- soundStart = [[weapon/laser/laser_burn8]], soundTrigger = true, sweepfire = false, texture1 = [[corelaser]], texture2 = [[wake]], texture3 = [[wake]], texture4 = [[wake]], thickness = 7, tileLength = 100, tolerance = 5000, turret = true, waterWeapon = true, weaponType = [[BeamLaser]], weaponVelocity = 500, }, }, featureDefs = { DEAD = { blocking = true, featureDead = [[HEAP]], footprintX = 2, footprintZ = 2, object = [[amphraider2_dead.s3o]], }, HEAP = { blocking = false, footprintX = 2, footprintZ = 2, object = [[debris2x2c.s3o]], }, }, } return lowerkeys({ amphimpulse = unitDef })
gpl-2.0
jono659/enko
scripts/zones/Windurst_Waters_[S]/npcs/Ransnana.lua
38
1050
----------------------------------- -- Area: Windurst Waters (S) -- NPC: Ransnana -- Type: Standard NPC -- @zone: 94 -- @pos -22.008 -13.339 122.819 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Windurst_Waters_[S]/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0198); 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
jono659/enko
scripts/zones/Northern_San_dOria/npcs/HomePoint#4.lua
12
1210
----------------------------------- -- Area: Northern San dOria -- NPC: HomePoint#4 -- @pos: -132 12 195 231 ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; require("scripts/globals/settings"); require("scripts/zones/Northern_San_dOria/TextIDs"); require("scripts/globals/homepoint"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) homepointMenu( player, 0x21ff, 98); 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 == 0x21ff) then if (option == 1) then player:setHomePoint(); player:messageSpecial(HOMEPOINT_SET); else hpTeleport( player, option); end end end;
gpl-3.0
jono659/enko
scripts/zones/Metalworks/npcs/Pius.lua
23
1832
----------------------------------- -- Area: Metalworks -- NPC: Pius -- Involved In Mission: Journey Abroad -- @pos 99 -21 -12 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) Mission = player:getCurrentMission(player:getNation()); MissionStatus = player:getVar("MissionStatus"); if(Mission == JOURNEY_TO_BASTOK and MissionStatus == 3 or Mission == JOURNEY_TO_BASTOK2 and MissionStatus == 8) then player:startEvent(0x0163); elseif(Mission == THE_THREE_KINGDOMS_BASTOK and MissionStatus == 3 or Mission == THE_THREE_KINGDOMS_BASTOK2 and MissionStatus == 8) then player:startEvent(0x0163,1); elseif(Mission == JOURNEY_TO_BASTOK or Mission == JOURNEY_TO_BASTOK2 or Mission == THE_THREE_KINGDOMS_BASTOK2 and MissionStatus < 11) then player:startEvent(0x0164); else player:startEvent(0x015e); 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 == 0x0163) then if(player:getVar("MissionStatus") == 3) then player:setVar("MissionStatus",4); else player:setVar("MissionStatus",9); end end end;
gpl-3.0
Arcscion/Shadowlyre
scripts/globals/items/balik_sandvici_+1.lua
12
1433
----------------------------------------- -- ID: 5591 -- Item: Balik Sandvic +1 -- Food Effect: 60Min, All Races ----------------------------------------- -- Dexterity 3 -- Agility 1 -- Intelligence 3 -- Mind -2 -- Ranged ACC 6 ----------------------------------------- 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,3600,5591); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, 3); target:addMod(MOD_AGI, 1); target:addMod(MOD_INT, 3); target:addMod(MOD_MND, -2); target:addMod(MOD_RACC, 6); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, 3); target:delMod(MOD_AGI, 1); target:delMod(MOD_INT, 3); target:delMod(MOD_MND, -2); target:delMod(MOD_RACC, 6); end;
gpl-3.0
Arcscion/Shadowlyre
scripts/globals/mobskills/mow.lua
32
1069
--------------------------------------------- -- Mow -- -- Description: Deals damage in an area of effect. Additional effect: Poison -- Type: Physical -- Utsusemi/Blink absorb: 2-3 shadows -- Range: Unknown radial -- Notes: Poison can take around 10HP/tick --------------------------------------------- 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 numhits = math.random(2,3); local accmod = 1; local dmgmod = 1; 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); local typeEffect = EFFECT_POISON; local power = mob:getMainLvl()/4 + 3; MobPhysicalStatusEffectMove(mob, target, skill, typeEffect, power, 3, 60); target:delHP(dmg); return dmg; end;
gpl-3.0
N0U/Zero-K
units/grebe.lua
5
4806
unitDef = { unitname = [[grebe]], name = [[Grebe]], description = [[Amphibious Raider Bot]], acceleration = 0.2, activateWhenBuilt = true, brakeRate = 0.4, buildCostMetal = 300, buildPic = [[grebe.png]], canGuard = true, canMove = true, canPatrol = true, category = [[LAND SINK]], corpse = [[DEAD]], customParams = { }, explodeAs = [[BIG_UNITEX]], footprintX = 2, footprintZ = 2, iconType = [[walkerraider]], idleAutoHeal = 5, idleTime = 1800, leaveTracks = true, maxDamage = 900, maxSlope = 36, maxVelocity = 2.4, maxWaterDepth = 5000, minCloakDistance = 75, movementClass = [[AKBOT2]], noChaseCategory = [[TERRAFORM SATELLITE FIXEDWING GUNSHIP HOVER SHIP SWIM SUB LAND FLOAT SINK TURRET]], objectName = [[amphraider.s3o]], script = [[grebe.lua]], selfDestructAs = [[BIG_UNITEX]], sfxtypes = { explosiongenerators = { }, }, sightDistance = 500, sonarDistance = 300, trackOffset = 0, trackStrength = 8, trackStretch = 1, trackType = [[ComTrack]], trackWidth = 22, turnRate = 1200, upright = true, weapons = { { def = [[GRENADE]], badTargetCategory = [[FIXEDWING]], onlyTargetCategory = [[FIXEDWING LAND SINK TURRET SHIP SWIM FLOAT GUNSHIP HOVER]], }, --{ -- def = [[TORPEDO]], -- badTargetCategory = [[FIXEDWING]], -- onlyTargetCategory = [[FIXEDWING LAND SINK TURRET SHIP SWIM FLOAT GUNSHIP HOVER]], --}, }, weaponDefs = { GRENADE = { name = [[Grenade Launcher]], accuracy = 200, areaOfEffect = 96, craterBoost = 1, craterMult = 2, damage = { default = 240, planes = 240, subs = 12, }, explosionGenerator = [[custom:PLASMA_HIT_96]], fireStarter = 180, impulseBoost = 0, impulseFactor = 0.2, interceptedByShieldType = 2, model = [[diskball.s3o]], projectiles = 2, range = 360, reloadtime = 3, smokeTrail = true, soundHit = [[explosion/ex_med6]], soundHitVolume = 8, soundStart = [[weapon/cannon/cannon_fire3]], soundStartVolume = 2, soundTrigger = true, sprayangle = 512, turret = true, weaponType = [[Cannon]], weaponVelocity = 400, }, TORPEDO = { name = [[Torpedo]], areaOfEffect = 16, avoidFriendly = false, burnblow = true, collideFriendly = false, craterBoost = 0, craterMult = 0, damage = { default = 200, subs = 200, }, explosionGenerator = [[custom:TORPEDO_HIT]], flightTime = 6, impactOnly = true, impulseBoost = 0, impulseFactor = 0.4, interceptedByShieldType = 1, model = [[wep_t_longbolt.s3o]], noSelfDamage = true, range = 400, reloadtime = 3, soundHit = [[explosion/wet/ex_underwater]], soundStart = [[weapon/torpedo]], startVelocity = 90, tolerance = 1000, tracks = true, turnRate = 10000, turret = true, waterWeapon = true, weaponAcceleration = 25, weaponType = [[TorpedoLauncher]], weaponVelocity = 140, }, }, featureDefs = { DEAD = { blocking = true, featureDead = [[HEAP]], footprintX = 3, footprintZ = 3, object = [[wreck2x2b.s3o]], }, HEAP = { blocking = false, footprintX = 2, footprintZ = 2, object = [[debris2x2c.s3o]], }, }, } return lowerkeys({ grebe = unitDef })
gpl-2.0
Arcscion/Shadowlyre
scripts/zones/Southern_San_dOria/npcs/Faulpie.lua
3
2889
----------------------------------- -- Area: Southern San d'Oria -- NPC: Faulpie -- Type: Leathercraft Guild Master -- !pos -178.882 -2 9.891 230 ----------------------------------- package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Southern_San_dOria/TextIDs"); require("scripts/globals/crafting"); require("scripts/globals/missions"); require("scripts/globals/status"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local newRank = tradeTestItem(player,npc,trade,SKILL_LEATHERCRAFT); if (newRank ~= 0) then player:setSkillRank(SKILL_LEATHERCRAFT,newRank); player:startEvent(0x0289,0,0,0,0,newRank); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local getNewRank = 0; local craftSkill = player:getSkillLevel(SKILL_LEATHERCRAFT); local testItem = getTestItem(player,npc,SKILL_LEATHERCRAFT); local guildMember = isGuildMember(player,7); if (guildMember == 1) then guildMember = 150995375; end if (canGetNewRank(player,craftSkill,SKILL_LEATHERCRAFT) == 1) then getNewRank = 100; end if (player:getCurrentMission(ASA) == THAT_WHICH_CURDLES_BLOOD and guildMember == 150995375 and getNewRank ~= 100) then local item = 0; local asaStatus = player:getVar("ASA_Status"); -- TODO: Other Enfeebling Kits if (asaStatus == 0) then item = 2779; else printf("Error: Unknown ASA Status Encountered <%u>", asaStatus); end -- The Parameters are Item IDs for the Recipe player:startEvent(0x03b0, item, 2773, 917, 917, 2776, 4103); else player:startEvent(0x0288,testItem,getNewRank,30,guildMember,44,0,0,0); end end; -- 0x0288 0x0289 0x02f8 0x02f9 0x02fa 0x02fb 0x02fc 0x02fd 0x0302 0x0303 0x0304 0x0305 0x0306 0x0307 0x03b0 0x0392 ----------------------------------- -- 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 == 0x0288 and option == 1) then local crystal = 4103; -- dark crystal if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,crystal); else player:addItem(crystal); player:messageSpecial(ITEM_OBTAINED,crystal); signupGuild(player, guild.leathercraft); end end end;
gpl-3.0
jono659/enko
scripts/zones/Riverne-Site_B01/npcs/_0t1.lua
19
1338
----------------------------------- -- Area: Riverne Site #B01 -- NPC: Unstable Displacement ----------------------------------- package.loaded["scripts/zones/Riverne-Site_B01/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Riverne-Site_B01/TextIDs"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) if(trade:hasItemQty(1691,1) and trade:getItemCount() == 1) then -- Trade Giant Scale player:tradeComplete(); npc:openDoor(RIVERNE_PORTERS); player:messageSpecial(SD_HAS_GROWN); end end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) if(npc:getAnimation() == 8) then player:startEvent(0x7); else player:messageSpecial(SD_VERY_SMALL); end; 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
jono659/enko
scripts/globals/spells/foe_requiem_ii.lua
11
1622
----------------------------------------- -- Spell: Foe Requiem II ----------------------------------------- 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_REQUIEM; local duration = 79; local power = 2; local pCHR = caster:getStat(MOD_CHR); local mCHR = target:getStat(MOD_CHR); local dCHR = (pCHR - mCHR); local resm = applyResistance(caster,spell,target,dCHR,SINGING_SKILL,0); if(resm < 0.5) then spell:setMsg(85);--resist message return 1; end local iBoost = caster:getMod(MOD_REQUIEM_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT); power = power + iBoost; if (caster:hasStatusEffect(EFFECT_SOUL_VOICE)) then power = power * 2; elseif (caster:hasStatusEffect(EFFECT_MARCATO)) then power = power * 1.5; end caster:delStatusEffect(EFFECT_MARCATO); duration = duration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1); if (caster:hasStatusEffect(EFFECT_TROUBADOUR)) then duration = duration * 2; end -- Try to overwrite weaker slow / haste if(canOverwrite(target, effect, power)) then -- overwrite them target:delStatusEffect(effect); target:addStatusEffect(effect,power,3,duration); spell:setMsg(237); else spell:setMsg(75); -- no effect end return effect; end;
gpl-3.0
sevenbot/antispamsevenn
plugins/inpm.lua
1114
3008
do local function pairsByKeys (t, f) local a = {} for n in pairs(t) do table.insert(a, n) end table.sort(a, f) local i = 0 -- iterator variable local iter = function () -- iterator function i = i + 1 if a[i] == nil then return nil else return a[i], t[a[i]] end end return iter end local function chat_list(msg) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] then return 'No groups at the moment' end local message = 'List of Groups:\n*Use /join (ID) to join*\n\n ' for k,v in pairs(data[tostring(groups)]) do local settings = data[tostring(v)]['settings'] for m,n in pairsByKeys(settings) do if m == 'set_name' then name = n end end message = message .. '👥 '.. name .. ' (ID: ' .. v .. ')\n\n ' end local file = io.open("./groups/lists/listed_groups.txt", "w") file:write(message) file:flush() file:close() return message end local function run(msg, matches) if msg.to.type ~= 'chat' or is_sudo(msg) or is_admin(msg) and is_realm(msg) then local data = load_data(_config.moderation.data) if matches[1] == 'join' and data[tostring(matches[2])] then if is_banned(msg.from.id, matches[2]) then return 'You are banned.' end if is_gbanned(msg.from.id) then return 'You are globally banned.' end if data[tostring(matches[2])]['settings']['lock_member'] == 'yes' and not is_owner2(msg.from.id, matches[2]) then return 'Group is private.' end local chat_id = "chat#id"..matches[2] local user_id = "user#id"..msg.from.id chat_add_user(chat_id, user_id, ok_cb, false) local group_name = data[tostring(matches[2])]['settings']['set_name'] return "Added you to chat:\n\n👥"..group_name.." (ID:"..matches[2]..")" elseif matches[1] == 'join' and not data[tostring(matches[2])] then return "Chat not found." end if matches[1] == 'chats'then if is_admin(msg) and msg.to.type == 'chat' then return chat_list(msg) elseif msg.to.type ~= 'chat' then return chat_list(msg) end end if matches[1] == 'chatlist'then if is_admin(msg) and msg.to.type == 'chat' then send_document("chat#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false) elseif msg.to.type ~= 'chat' then send_document("user#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false) end end end end return { patterns = { "^[/!](chats)$", "^[/!](chatlist)$", "^[/!](join) (.*)$", "^[/!](kickme) (.*)$", "^!!tgservice (chat_add_user)$" }, run = run, } end
gpl-2.0
abferm/network-manager
examples/lua/lgi/show-wifi-networks.lua
6
3967
#!/usr/bin/env lua -- -*- Mode: Lua; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- -- vim: ft=lua ts=2 sts=2 sw=2 et ai -- -- 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 2 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, write to the Free Software Foundation, Inc., -- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -- -- Copyright 2015 Red Hat, Inc. -- -- -- This example lists Wi-Fi access points NetworkManager scanned on Wi-Fi devices. -- The example uses libnm library using GObject introspection via Lua lgi module. -- Most distribution ship the module as lua-lgi package. -- libnm guide: https://developer.gnome.org/libnm/1.0/ -- Lua-lgi guide: https://github.com/pavouk/lgi/blob/master/docs/guide.md -- local lgi = require 'lgi' local NM = lgi.NM function is_empty(t) local next = next if next(t) then return false else return true end end function ssid_to_utf8(ap) local ssid = ap:get_ssid() if not ssid then return "" end return NM.utils_ssid_to_utf8(ssid:get_data()) end function print_device_info(device) local active_ap = device:get_active_access_point() if active_ap then ssid = ssid_to_utf8(active_ap) end local info = string.format("Device: %s | Driver: %s | Active AP: %s", device:get_iface(), device:get_driver(), ssid) print(info) print(string.rep("=", info:len())) end function flags_to_string(flags) local str = "" for flag, _ in pairs(flags) do str = str .. " " .. flag end if str == "" then str = "NONE" end return (str:gsub( "^%s", "")) end function flags_to_security(flags, wpa_flags, rsn_flags) local str = "" if flags["PRIVACY"] and is_empty(wpa_flags) and is_empty(rsn_flags) then str = str .. " WEP" end if not is_empty(wpa_flags) then str = str .. " WPA1" end if not is_empty(rsn_flags) then str = str .. " WPA2" end if wpa_flags["KEY_MGMT_802_1X"] or rsn_flags["KEY_MGMT_802_1X"] then str = str .. " 802.1X" end return (str:gsub( "^%s", "")) end function print_ap_info(ap) local strength = ap:get_strength() local frequency = ap:get_frequency() local flags = ap:get_flags() local wpa_flags = ap:get_wpa_flags() local rsn_flags = ap:get_rsn_flags() -- remove extra NONE from the flags tables flags["NONE"] = nil wpa_flags["NONE"] = nil rsn_flags["NONE"] = nil print("SSID: ", ssid_to_utf8(ap)) print("BSSID: ", ap:get_bssid()) print("Frequency: ", frequency) print("Channel: ", NM.utils_wifi_freq_to_channel(frequency)) print("Mode: ", ap:get_mode()) print("Flags: ", flags_to_string(flags)) print("WPA flags: ", flags_to_string(wpa_flags)) print("RSN flags: ", flags_to_string(rsn_flags)) print("Security: ", flags_to_security(flags, wpa_flags, rsn_flags)) print(string.format("Strength: %s %s%%", NM.utils_wifi_strength_bars(strength), strength)) print("") end --------------------------- -- Main code starts here -- --------------------------- -- Call setlocale() else NM.utils_wifi_strength_bars() will think the locale -- is ASCII-only, and return the fallback characters rather than the unicode bars os.setlocale('') -- get all devices client = NM.Client.new() devs = client:get_devices() -- print APs for all Wi-Fi devices for _, dev in ipairs(devs) do if dev:get_device_type() == "WIFI" then print_device_info(dev) for _, ap in ipairs(dev:get_access_points()) do print_ap_info(ap) end end end
gpl-2.0
jono659/enko
scripts/zones/Southern_San_dOria_[S]/npcs/Achtelle.lua
72
1069
----------------------------------- -- Area: Southern SandOria [S] -- NPC: Achtelle -- @zone 80 -- @pos 108 2 -11 ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) --player:startEvent(0x01FE); Event doesnt work but this is her default dialogue, threw in something below til it gets fixed player:showText(npc, 13454); -- (Couldn't find default dialogue) How very good to see you again! 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
spawnazzo/luci
modules/admin-full/luasrc/controller/admin/uci.lua
85
1975
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2010 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- module("luci.controller.admin.uci", package.seeall) function index() local redir = luci.http.formvalue("redir", true) or luci.dispatcher.build_url(unpack(luci.dispatcher.context.request)) entry({"admin", "uci"}, nil, _("Configuration")) entry({"admin", "uci", "changes"}, call("action_changes"), _("Changes"), 40).query = {redir=redir} entry({"admin", "uci", "revert"}, call("action_revert"), _("Revert"), 30).query = {redir=redir} entry({"admin", "uci", "apply"}, call("action_apply"), _("Apply"), 20).query = {redir=redir} entry({"admin", "uci", "saveapply"}, call("action_apply"), _("Save &#38; Apply"), 10).query = {redir=redir} end function action_changes() local uci = luci.model.uci.cursor() local changes = uci:changes() luci.template.render("admin_uci/changes", { changes = next(changes) and changes }) end function action_apply() local path = luci.dispatcher.context.path local uci = luci.model.uci.cursor() local changes = uci:changes() local reload = {} -- Collect files to be applied and commit changes for r, tbl in pairs(changes) do table.insert(reload, r) if path[#path] ~= "apply" then uci:load(r) uci:commit(r) uci:unload(r) end end luci.template.render("admin_uci/apply", { changes = next(changes) and changes, configs = reload }) end function action_revert() local uci = luci.model.uci.cursor() local changes = uci:changes() -- Collect files to be reverted for r, tbl in pairs(changes) do uci:load(r) uci:revert(r) uci:unload(r) end luci.template.render("admin_uci/revert", { changes = next(changes) and changes }) end
apache-2.0
Arcscion/Shadowlyre
scripts/globals/items/poultry_pitaru.lua
12
1347
----------------------------------------- -- ID: 5890 -- Item: poultry_pitaru -- Food Effect: 30 Min, All Races ----------------------------------------- -- MP +7% (cap 110) -- Increases rate of magic skill gains by 40% ----------------------------------------- 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,1800,5890); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_FOOD_MPP, 7); target:addMod(MOD_FOOD_MP_CAP, 110); target:addMod(MOD_MAGIC_SKILLUP_RATE, 40); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_FOOD_MPP, 7); target:delMod(MOD_FOOD_MP_CAP, 110); target:delMod(MOD_MAGIC_SKILLUP_RATE, 40); end;
gpl-3.0
jono659/enko
scripts/globals/mobskills/Tidal_Dive.lua
6
1157
--------------------------------------------- -- Tidal Dive -- -- Description: Dives at nearby targets. Additional effect: Weight and/or Bind (Status Effect) -- Type: Physical -- Utsusemi/Blink absorb: 2-3 shadows -- Range: Unknown radial -- Notes: Only used over deep water. --------------------------------------------- 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 typeEffect = EFFECT_BIND; 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_NONE,info.hitslanded); MobPhysicalStatusEffectMove(mob, target, skill, typeEffect, 1, 0, 30); typeEffect = EFFECT_WEIGHT; MobPhysicalStatusEffectMove(mob, target, skill, typeEffect, 50, 0, 60); target:delHP(dmg); return dmg; end;
gpl-3.0
jono659/enko
scripts/zones/Bastok_Mines/npcs/Abd-al-Raziq.lua
9
2433
----------------------------------- -- Area: Bastok Mines -- NPC: Abd-al-Raziq -- Type: Alchemy Guild Master -- @pos 126.768 1.017 -0.234 234 ----------------------------------- package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil; ----------------------------------- require("scripts/globals/crafting"); require("scripts/zones/Bastok_Mines/TextIDs"); local SKILLID = 55; -- Alchemy ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local newRank = tradeTestItem(player,npc,trade,SKILLID); if(newRank ~= 0) then player:setSkillRank(SKILLID,newRank); player:startEvent(0x0079,0,0,0,0,newRank); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local getNewRank = 0; local craftSkill = player:getSkillLevel(SKILLID); local testItem = getTestItem(player,npc,SKILLID); local guildMember = isGuildMember(player,1); if(guildMember == 1) then guildMember = 150995375; end if(canGetNewRank(player,craftSkill,SKILLID) == 1) then getNewRank = 100; end if (player:getCurrentMission(ASA) == THAT_WHICH_CURDLES_BLOOD and guildMember == 150995375 and getNewRank ~= 100) then local item = 0; local asaStatus = player:getVar("ASA_Status"); -- TODO: Other Enfeebling Kits if(asaStatus == 0) then item = 2779; else printf("Error: Unknown ASA Status Encountered <%u>", asaStatus); end -- The Parameters are Item IDs for the Recipe player:startEvent(0x024e, item, 2774, 929, 4103, 2777, 4103); else player:startEvent(0x0078,testItem,getNewRank,30,guildMember,44,0,0,0); 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 == 0x0078 and option == 1) then local crystal = math.random(4096,4101); if(player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,crystal); else player:addItem(crystal); player:messageSpecial(ITEM_OBTAINED,crystal); signupGuild(player,2); end end end;
gpl-3.0
Arcscion/Shadowlyre
scripts/zones/Cloister_of_Tremors/bcnms/trial_by_earth.lua
3
1849
----------------------------------- -- Area: Cloister of Tremors -- BCNM: Trial by Earth -- !pos -539 1 -493 209 ----------------------------------- package.loaded["scripts/zones/Cloister_of_Tremors/TextIDs"] = nil; ------------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/Cloister_of_Tremors/TextIDs"); ----------------------------------- -- 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) -- print("leave code "..leavecode); if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage if (player:hasCompleteQuest(BASTOK,TRIAL_BY_EARTH)) then player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,0,1); else player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,0,0); end elseif (leavecode == 4) then player:startEvent(0x7d02); end 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:delKeyItem(TUNING_FORK_OF_EARTH); player:addKeyItem(WHISPER_OF_TREMORS); player:messageSpecial(KEYITEM_OBTAINED,WHISPER_OF_TREMORS); end end;
gpl-3.0
Arcscion/Shadowlyre
scripts/globals/spells/cryohelix.lua
3
1975
-------------------------------------- -- Spell: Cryohelix -- Deals ice damage that gradually reduces -- a target's HP. Damage dealt is greatly affected by the weather. -------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) -- get helix acc/att merits local merit = caster:getMerit(MERIT_HELIX_MAGIC_ACC_ATT); -- calculate raw damage local params = {}; params.dmg = 35; params.multiplier = 1; params.skillType = ELEMENTAL_MAGIC_SKILL; params.attribute = MOD_INT; params.hasMultipleTargetReduction = false; local dmg = calculateMagicDamage(caster, target, spell, params); dmg = dmg + caster:getMod(MOD_HELIX_EFFECT); -- get resist multiplier (1x if no resist) local params = {}; params.diff = caster:getStat(MOD_INT)-target:getStat(MOD_INT); params.attribute = MOD_INT; params.skillType = ELEMENTAL_MAGIC_SKILL; params.bonus = merit*3; resist = applyResistance(caster, target, spell, params); -- get the resisted damage dmg = dmg*resist; -- add on bonuses (staff/day/weather/jas/mab/etc all go in this function) dmg = addBonuses(caster,spell,target,dmg,merit*2); -- add in target adjustment dmg = adjustForTarget(target,dmg,spell:getElement()); local dot = dmg; -- add in final adjustments dmg = finalMagicAdjustments(caster,target,spell,dmg); -- calculate Damage over time dot = target:magicDmgTaken(dot); local duration = getHelixDuration(caster) + caster:getMod(MOD_HELIX_DURATION); duration = duration * (resist/2); if (dot > 0) then target:addStatusEffect(EFFECT_HELIX,dot,3,duration); end; return dmg; end;
gpl-3.0
jono659/enko
scripts/zones/Selbina/npcs/Lucia.lua
17
1180
----------------------------------- -- Area: Selbina -- NPC: Lucia -- @zone -- @pos ----------------------------------- package.loaded["scripts/zones/Selbina/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Selbina/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(player:getZPos() > -28.750) then player:startEvent(0x00dd,player:getGil(),100); else player:startEvent(0x00eb); 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 == 0x00dd and player:getZPos() < -28.750) then player:delGil(100); end end;
gpl-3.0
Cyumus/GarryWare13
entities/weapons/sware_velocitygun/shared.lua
2
2503
if ( SERVER ) then AddCSLuaFile( "shared.lua" ) end SWEP.Base = "gmdm_base" SWEP.PrintName = "SWARE Velocity Gun" SWEP.Slot = 1 SWEP.SlotPos = 0 SWEP.DrawAmmo = true SWEP.DrawCrosshair = true SWEP.ViewModel = "models/weapons/v_357.mdl" SWEP.WorldModel = "models/weapons/w_357.mdl" SWEP.HoldType = "pistol" SWEP.Primary.ClipSize = -1 -- Size of a clip SWEP.Primary.DefaultClip = -1 -- Default number of bullets in a clip SWEP.Primary.Automatic = false -- Automatic/Semi Auto SWEP.Primary.Ammo = "none" SWEP.ShootSound = Sound( "Weapon_AR2.Single" ) function SWEP:PrimaryAttack() self.Weapon:SetNextPrimaryFire( CurTime() + 1.3 ) self.Weapon:SetNextSecondaryFire( CurTime() + 0.1 ) if ( not self:CanShootWeapon() ) then return end --if ( not self:CanPrimaryAttack() ) then return end self.Weapon:EmitSound(self.ShootSound) self:ShootBullet( 0, 1, 0.0 ) -- Punches the player's view. self.Owner:ViewPunch( Angle( -5, 0, 0 ) ) if ( SERVER ) then -- Make the player fly upwards. self.Owner:SetGroundEntity( NULL ) self.Owner:SetVelocity( self.Owner:GetVelocity()*-1 + self.Owner:GetAimVector() * -250 ) local trace = self.Owner:GetEyeTrace() if trace.Entity:IsPlayer() then trace.Entity:SetGroundEntity( NULL ) trace.Entity:SetVelocity(trace.Entity:GetVelocity()*-1 + Vector(0,0,375)) end end end SWEP.Secondary.ClipSize = -1 -- Size of a clip SWEP.Secondary.DefaultClip = -1 -- Default number of bullets in a clip SWEP.Secondary.Automatic = false -- Automatic/Semi Auto SWEP.Secondary.Ammo = "none" function SWEP:SecondaryAttack() self:SetNextSecondaryFire( CurTime() + 3 ) end function SWEP:ShootEffects() self.Weapon:SendWeaponAnim( ACT_VM_PRIMARYATTACK ) -- View model animation self.Owner:MuzzleFlash() -- Crappy muzzle light self.Owner:SetAnimation( PLAYER_ATTACK1 ) -- 3rd Person Animation end function SWEP:ShootBullet( damage, num_bullets, aimcone ) local bullet = {} bullet.Num = num_bullets bullet.Src = self.Owner:GetShootPos() -- Source bullet.Dir = self.Owner:GetAimVector() -- Dir of bullet bullet.Spread = Vector( aimcone, aimcone, 0 ) -- Aim Cone bullet.Tracer = 1 -- Show a tracer on every x bullets bullet.Force = 5 -- Amount of force to give to phys objects bullet.Damage = damage bullet.AmmoType = "Pistol" bullet.HullSize = 2 bullet.TracerName = "SWARE_FlashTrace" self.Owner:FireBullets( bullet ) self:ShootEffects() end
gpl-2.0
jono659/enko
scripts/zones/Mhaura/npcs/Albin.lua
17
1072
----------------------------------- -- Area: Mhaura -- NPC: Albin -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Mhaura/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Mhaura/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(player:getZPos() <= 39) then player:startEvent(0x00dc); else player:startEvent(0x00e5); 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
Arcscion/Shadowlyre
scripts/globals/spells/bluemagic/mandibular_bite.lua
33
1716
----------------------------------------- -- Spell: Mandibular Bite -- Damage varies with TP -- Spell cost: 38 MP -- Monster Type: Vermin -- Spell Type: Physical (Slashing) -- Blue Magic Points: 2 -- Stat Bonus: INT+1 -- Level: 44 -- Casting Time: 0.5 seconds -- Recast Time: 19.25 seconds -- Skillchain property(ies): Induration (can open Impaction, Compression, or Fragmentation) -- Combos: Plantoid Killer ----------------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/bluemagic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local params = {}; -- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage params.tpmod = TPMOD_ATTACK; params.dmgtype = DMGTYPE_SLASH; params.scattr = SC_INDURATION; params.numhits = 1; params.multiplier = 2.0; params.tp150 = 1.2; params.tp300 = 1.4; params.azuretp = 1.5; params.duppercap = 45; --guesstimated attack % bonuses params.str_wsc = 0.2; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.2; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; damage = BluePhysicalSpell(caster, target, spell, params); damage = BlueFinalAdjustments(caster, target, spell, damage, params); return damage; end;
gpl-3.0
Arcscion/Shadowlyre
scripts/zones/Lufaise_Meadows/npcs/Jersey.lua
3
1898
----------------------------------- -- Area: Lufaise Meadows -- NPC: Jersey -- Type: Outpost Vendor -- !pos -548.706 -7.197 -53.897 24 ----------------------------------- package.loaded["scripts/zones/Lufaise_Meadows/TextIDs"] = nil; ----------------------------------- require("scripts/globals/shop"); require("scripts/globals/conquest"); require("scripts/zones/Lufaise_Meadows/TextIDs"); local region = TAVNAZIANARCH; local csid = 0x7ff4; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local owner = GetRegionOwner(region); local arg1 = getArg1(owner,player); if (owner == player:getNation()) then nation = 1; elseif (arg1 < 1792) then nation = 2; else nation = 0; end player:startEvent(csid,nation,OP_TeleFee(player,region),0,OP_TeleFee(player,region),player:getCP(),0,0,0); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); player:updateEvent(player:getGil(),OP_TeleFee(player,region),0,OP_TeleFee(player,region),player:getCP()); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); if (option == 1) then ShowOPVendorShop(player); elseif (option == 2) then if (player:delGil(OP_TeleFee(player,region))) then toHomeNation(player); end elseif (option == 6) then player:delCP(OP_TeleFee(player,region)); toHomeNation(player); end end;
gpl-3.0
Arcscion/Shadowlyre
scripts/globals/abilities/role_reversal.lua
4
1201
----------------------------------- -- Ability: Role Reversal -- Swaps Master's current HP with Automaton's current HP. -- Obtained: Puppetmaster Level 75 -- Recast Time: 2:00 -- Duration: Instant ----------------------------------- require("scripts/globals/settings") require("scripts/globals/status") require("scripts/globals/pets") require("scripts/globals/msg"); ----------------------------------- -- onAbilityCheck ----------------------------------- function onAbilityCheck(player,target,ability) if not player:getPet() then return msgBasic.REQUIRES_A_PET, 0 elseif not player:getPetID() or not (player:getPetID() >= 69 and player:getPetID() <= 72) then return msgBasic.NO_EFFECT_ON_PET, 0 else return 0, 0 end end ----------------------------------- -- onUseAbility ----------------------------------- function onUseAbility(player,target,ability) local pet = player:getPet() if pet then local bonus = 1 + (player:getMerit(MERIT_ROLE_REVERSAL)-5)/100 local playerHP = player:getHP() local petHP = pet:getHP() pet:setHP(math.max(playerHP * bonus, 1)) player:setHP(math.max(petHP * bonus, 1)) end end
gpl-3.0
jono659/enko
scripts/zones/Bastok-Jeuno_Airship/npcs/Dereck.lua
12
1993
----------------------------------- -- Area: Bastok-Jeuno Airship -- NPC: Dereck -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Bastok-Jeuno_Airship/TextIDs"] = nil; require("scripts/zones/Bastok-Jeuno_Airship/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local vHour = VanadielHour(); local vMin = VanadielMinute(); while vHour >= 6 do vHour = vHour - 6; end local message = WILL_REACH_BASTOK; if (vHour == 0) then if (vMin >= 13) then vHour = 3; message = WILL_REACH_JEUNO; end elseif (vHour == 1) then vHour = 2; message = WILL_REACH_JEUNO; elseif (vHour == 2) then vHour = 1; message = WILL_REACH_JEUNO; elseif (vHour == 3) then if (vMin <= 11) then vHour = 0; message = WILL_REACH_JEUNO; end elseif (vHour == 4) then vHour = 2; elseif (vHour == 5) then vHour = 1; end local vMinutes = 0; if (message == WILL_REACH_JEUNO) then vMinutes = (vHour * 60) + 11 - vMin; else -- WILL_REACH_BASTOK vMinutes = (vHour * 60) + 13 - vMin; end if (vMinutes <= 30) then if( message == WILL_REACH_BASTOK) then message = IN_BASTOK_MOMENTARILY; else -- WILL_REACH_JEUNO message = IN_JEUNO_MOMENTARILY; end elseif (vMinutes < 60) then vHour = 0; end player:messageSpecial( message, math.floor((2.4 * vMinutes) / 60), math.floor( vMinutes / 60 + 0.5)); 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
jono659/enko
scripts/zones/Windurst_Waters_[S]/npcs/Adjutant.lua
38
1048
----------------------------------- -- Area: Windurst Waters (S) -- NPC: Adjutant -- Type: Standard NPC -- @zone: 94 -- @pos -67.819 -4.499 58.997 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Windurst_Waters_[S]/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0131); 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
Arcscion/Shadowlyre
scripts/zones/Valkurm_Dunes/npcs/Tsunashige_IM.lua
3
3324
----------------------------------- -- Area: Valkurm Dunes -- NPC: Tsunashige, I.M. -- Outpost Conquest Guards -- !pos 139.394 -7.885 100.384 103 ----------------------------------- package.loaded["scripts/zones/Valkurm_Dunes/TextIDs"] = nil; ----------------------------------- require("scripts/globals/conquest"); require("scripts/zones/Valkurm_Dunes/TextIDs"); local guardnation = NATION_BASTOK; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno local guardtype = 3; -- 1: city, 2: foreign, 3: outpost, 4: border local region = ZULKHEIM; local csid = 0x7ff9; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then if (supplyRunFresh(player) == 1) then player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies ! else player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use." player:delKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region)); player:setVar("supplyQuest_region",0); end else local arg1 = getArg1(guardnation, player) - 1; if (arg1 >= 1792) then -- foreign, non-allied player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0); else -- citizen or allied player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); if (option == 1) then local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600; player:delStatusEffect(EFFECT_SIGIL); player:delStatusEffect(EFFECT_SANCTION); player:delStatusEffect(EFFECT_SIGNET); player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet elseif (option == 2) then player:delKeyItem(getSupplyKey(region)); player:addCP(supplyReward[region + 1]) player:messageSpecial(CONQUEST); -- "You've earned conquest points!" if (hasOutpost(player, region+5) == 0) then local supply_quests = 2^(region+5); player:addNationTeleport(guardnation,supply_quests); player:setVar("supplyQuest_region",0); end elseif (option == 4) then if (player:delGil(giltosetHP(guardnation,player))) then player:setHomePoint(); player:messageSpecial(CONQUEST + 94); -- "Your home point has been set." else player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here." end end end;
gpl-3.0
Arcscion/Shadowlyre
scripts/zones/Southern_San_dOria/npcs/Clainomille.lua
3
1301
----------------------------------- -- Area: Southern San d'Oria -- NPC: Clainomille -- Type: Standard NPC -- @zone 230 -- !pos -72.771 0.999 -6.112 -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (FlyerForRegine == 1) then count = trade:getItemCount(); 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) player:startEvent(0x0265); 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
hypnoscope/let-s-code-an-indie-game
episode_38/src/logic/rooms/floorplans/dungeon_room.lua
10
1312
local tilemap = require("src.logic.rooms.tilemap") local dungeonRoomFloorplan = [[ ^^^^^^^^^^^^^^^^^^^^^XXX^^^^^^^^^^^^^^^^^^^^^^^^^^ xxxxxxxxxxxxxxxxxxxxxXXXxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxXXXxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxXXXxxxxxxxxxxxxxxxxxxxxxxxxxx =====================XXXxxxxxxxxxxxxxxxxxxxxxxxxxx .....................sXXxxxxxxxxxxxxxxxxxxxxxxxxxx ......................sXxxxxxxxxxxxxxxxxxxxxxxxxxx .......................s========================== ......,........................................... .................................................. .................................................. .....................,............................ .................................................. .................................................. .................................................. ...................................,.............. vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ]] return tilemap.create( dungeonRoomFloorplan, 50, nil, {x=2, y=0, z=90}, {x=386, y=0, z=90})
mit
jono659/enko
scripts/globals/spells/bluemagic/cannonball.lua
10
1737
----------------------------------------- -- Spell: Cannonball -- Damage varies with TP -- Spell cost: 66 MP -- Monster Type: Vermin -- Spell Type: Physical (Blunt) -- Blue Magic Points: 3 -- Stat Bonus: STR+1, DEX+1 -- Level: 70 -- Casting Time: 0.5 seconds -- Recast Time: 28.5 seconds -- Skillchain Element(s): Fusion (can open/close Light with Fragmentation WSs and spells) -- Combos: None ----------------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/bluemagic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local params = {}; -- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage params.tpmod = TPMOD_DAMAGE; params.dmgtype = DMGTYPE_H2H; params.scattr = SC_FUSION; params.numhits = 1; params.multiplier = 1.75; params.tp150 = 2.125; params.tp300 = 2.75; params.azuretp = 2.875; params.duppercap = 75; params.str_wsc = 0.5; params.dex_wsc = 0.0; params.vit_wsc = 0.5; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; damage = BluePhysicalSpell(caster, target, spell, params); damage = BlueFinalAdjustments(caster, target, spell, damage, params); -- Missing Bonus damage from defense? return damage; end;
gpl-3.0
zhangxiangxiao/nn
VolumetricConvolution.lua
39
1702
local VolumetricConvolution, parent = torch.class('nn.VolumetricConvolution', 'nn.Module') function VolumetricConvolution:__init(nInputPlane, nOutputPlane, kT, kW, kH, dT, dW, dH) parent.__init(self) dT = dT or 1 dW = dW or 1 dH = dH or 1 self.nInputPlane = nInputPlane self.nOutputPlane = nOutputPlane self.kT = kT self.kW = kW self.kH = kH self.dT = dT self.dW = dW self.dH = dH self.weight = torch.Tensor(nOutputPlane, nInputPlane, kT, kH, kW) self.bias = torch.Tensor(nOutputPlane) self.gradWeight = torch.Tensor(nOutputPlane, nInputPlane, kT, kH, kW) self.gradBias = torch.Tensor(nOutputPlane) -- temporary buffers for unfolding (CUDA) self.finput = torch.Tensor() self.fgradInput = torch.Tensor() self:reset() end function VolumetricConvolution:reset(stdv) if stdv then stdv = stdv * math.sqrt(3) else stdv = 1/math.sqrt(self.kT*self.kW*self.kH*self.nInputPlane) end if nn.oldSeed then self.weight:apply(function() return torch.uniform(-stdv, stdv) end) self.bias:apply(function() return torch.uniform(-stdv, stdv) end) else self.weight:uniform(-stdv, stdv) self.bias:uniform(-stdv, stdv) end end function VolumetricConvolution:updateOutput(input) return input.nn.VolumetricConvolution_updateOutput(self, input) end function VolumetricConvolution:updateGradInput(input, gradOutput) return input.nn.VolumetricConvolution_updateGradInput(self, input, gradOutput) end function VolumetricConvolution:accGradParameters(input, gradOutput, scale) return input.nn.VolumetricConvolution_accGradParameters(self, input, gradOutput, scale) end
bsd-3-clause
Arcscion/Shadowlyre
scripts/globals/mobskills/tebbad_wing.lua
33
1231
--------------------------------------------- -- Tebbad Wing -- -- Description: A hot wind deals Fire damage to enemies within a very wide area of effect. Additional effect: Plague -- Type: Magical -- Utsusemi/Blink absorb: Wipes shadows -- Range: 30' radial. -- Notes: Used only by Tiamat, Smok and Ildebrann --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) if (mob:hasStatusEffect(EFFECT_MIGHTY_STRIKES)) then return 1; elseif (mob:AnimationSub() == 1) then return 1; elseif (target:isBehind(mob, 48) == true) then return 1; end return 0; end; function onMobWeaponSkill(target, mob, skill) local typeEffect = EFFECT_PLAGUE; MobStatusEffectMove(mob, target, typeEffect, 10, 0, 120); local dmgmod = 1; local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*5,ELE_FIRE,dmgmod,TP_NO_EFFECT); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_FIRE,MOBPARAM_WIPE_SHADOWS); target:delHP(dmg); return dmg; end;
gpl-3.0
jono659/enko
scripts/zones/Talacca_Cove/npcs/qm1.lua
42
1267
----------------------------------- -- Area: Talacca_Cove -- NPC: ??? (corsair job flag quest) -- ----------------------------------- package.loaded["scripts/zones/Talacca_Cove/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Talacca_Cove/TextIDs"); require("scripts/globals/keyitems"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) LuckOfTheDraw = player:getVar("LuckOfTheDraw"); if (LuckOfTheDraw ==3) then player:startEvent(0x0002); 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 == 0x0002) then player:setVar("LuckOfTheDraw",4); player:addKeyItem(FORGOTTEN_HEXAGUN); player:messageSpecial(KEYITEM_OBTAINED,FORGOTTEN_HEXAGUN); end end;
gpl-3.0
jono659/enko
scripts/zones/Port_Jeuno/npcs/Jaipal.lua
12
1269
----------------------------------- -- Area: Port Jeuno -- NPC: Jaipal -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Port_Jeuno/TextIDs"] = nil; require("scripts/zones/Port_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local vHour = VanadielHour(); local vMin = VanadielMinute(); while vHour >= 4 do vHour = vHour - 6; end if( vHour == -2) then vHour = 4; elseif( vHour == -1) then vHour = 5; end local seconds = math.floor(2.4 * ((vHour * 60) + vMin)); player:startEvent( 0x272B, seconds, 0, 0, 0, 0, 0, 0, 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
jono659/enko
scripts/zones/VeLugannon_Palace/mobs/Zipacna.lua
11
1794
----------------------------------- -- Area: VeLugannon Palace -- NPC: Zipacna ----------------------------------- local path = { -202, 0, 391, -209, 0, 387, -214, 0, 381, -238, 0, 380, -256, 4, 381, -261, 8, 400, -257, 12, 417, -240, 16, 420, -257, 12, 417, -261, 8, 400, -256, 4, 381, -238, 0, 380, -214, 0, 381, -209, 0, 387, -194, 0, 388, -179, 0, 379, -134, 0, 379, -115, 0, 417, -112, 0, 454, -105, 0, 460, -80, 0, 460, -65, 0, 459, -60, 0, 452, -59, 0, 420, 59, 0, 420, 60, 0, 429, 60, 0, 445, 62, 0, 456, 78, 0, 460, 108, 0, 458, 132, 0, 381, 185, 0, 380, 199, 0, 391, 218, 0, 380, 259, 4, 383, 258, 12, 418, 248, 14, 420, 219, 16, 420, 248, 14, 420, 258, 12, 418, 259, 4, 383, 218, 0, 380, 199, 0, 391, 185, 0, 380, 132, 0, 381, 108, 0, 458, 78, 0, 460, 62, 0, 456, 60, 0, 445, 60, 0, 429, 59, 0, 420, -59, 0, 420, -60, 0, 452, -65, 0, 459, -80, 0, 460, -105, 0, 460, -112, 0, 454, -115, 0, 417, -134, 0, 379, -179, 0, 379, -191, 0, 385, -195, 0, 396, -202, 0, 391, -209, 0, 387, -214, 0, 381, -238, 0, 380, -256, 4, 381, -261, 8, 400, -257, 12, 417, -240, 16, 420, -257, 12, 417, -261, 8, 400, -256, 4, 381, -238, 0, 380, -214, 0, 381, -209, 0, 387, -202, 0, 391, }; ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; function onMobSpawn(mob) onMobRoam(mob); end; function onPath(mob) pathfind.patrol(mob, path, PATHFLAG_RUN); end; function onMobRoam(mob) -- move to start position if not moving if(mob:isFollowingPath() == false) then mob:pathThrough(pathfind.first(path), PATHFLAG_RUN); end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, killer) mob:setRespawnTime(math.random((10800),(14400))); -- respawn 3-4 hrs end;
gpl-3.0
jono659/enko
scripts/zones/Bastok_Markets/npcs/Yafafa.lua
36
1619
----------------------------------- -- Area: Bastok Markets -- NPC: Yafafa -- Only sells when Bastok controls Kolshushu -- -- Updated Aug-09-2013 by Zerahn, based on bgwiki and gamerescape ----------------------------------- require("scripts/globals/shop"); require("scripts/globals/conquest"); package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil; require("scripts/zones/Bastok_Markets/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) RegionOwner = GetRegionOwner(KOLSHUSHU); if (RegionOwner ~= BASTOK) then player:showText(npc,YAFAFA_CLOSED_DIALOG); else player:showText(npc,YAFAFA_OPEN_DIALOG); stock = { 0x1197, 184, --Buburimu Grape 0x0460,1620, --Casablanca 0x1107, 220, --Dhalmel Meat 0x0266, 72, --Mhaura Garlic 0x115d, 40 --Yagudo Cherry } showShop(player,BASTOK,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
Arcscion/Shadowlyre
scripts/zones/Metalworks/npcs/HomePoint#1.lua
3
1248
----------------------------------- -- Area: Metalworks -- NPC: HomePoint#1 -- !pos 46 -14 -19 237 ----------------------------------- package.loaded["scripts/zones/Metalworks/TextIDs"] = nil; require("scripts/globals/settings"); require("scripts/zones/Metalworks/TextIDs"); require("scripts/globals/homepoint"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) homepointMenu( player, 0x21fc, 16); 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
Arcscion/Shadowlyre
scripts/zones/Upper_Jeuno/npcs/Monberaux.lua
1
5954
----------------------------------- -- Area: Upper Jeuno -- NPC: Monberaux -- Starts and Finishes Quest: The Lost Cardian (finish), The kind cardian (start) -- Involved in Quests: Save the Clock Tower -- !pos -43 0 -1 244 ----------------------------------- package.loaded["scripts/zones/Upper_Jeuno/TextIDs"] = nil; package.loaded["scripts/globals/settings"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/shop"); require("scripts/globals/missions"); require("scripts/globals/quests"); require("scripts/zones/Upper_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (trade:hasItemQty(555,1) == true and trade:getItemCount() == 1) then a = player:getVar("saveTheClockTowerNPCz1"); -- NPC Part1 if (a == 0 or (a ~= 4 and a ~= 5 and a ~= 6 and a ~= 12 and a ~= 20 and a ~= 7 and a ~= 28 and a ~= 13 and a ~= 22 and a ~= 14 and a ~= 21 and a ~= 15 and a ~= 23 and a ~= 29 and a ~= 30 and a ~= 31)) then player:startEvent(0x005b,10 - player:getVar("saveTheClockTowerVar")); -- "Save the Clock Tower" Quest end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local TheLostCardien = player:getQuestStatus(JEUNO,THE_LOST_CARDIAN); local CooksPride = player:getQuestStatus(JEUNO,COOK_S_PRIDE); -- COP mission 1-1 if (player:getCurrentMission(COP) == THE_RITES_OF_LIFE and player:getVar("PromathiaStatus") == 1) then player:startEvent(0x000a);--10 -- COP mission 1-2 elseif (player:getCurrentMission(COP) == BELOW_THE_ARKS and player:getVar("PromathiaStatus") == 0) then player:startEvent(0x0009);--9 -- COP mission 3-5 elseif (player:getCurrentMission(COP) == DARKNESS_NAMED and player:getVar("PromathiaStatus") == 0) then player:startEvent(0x0052);-- 82 elseif (player:getCurrentMission(COP) == DARKNESS_NAMED and player:getVar("PromathiaStatus") == 3) then player:startEvent(0x004B); --75 elseif (player:getCurrentMission(COP) == THREE_PATHS and player:getVar("COP_Tenzen_s_Path") == 2) then player:startEvent(0x004A); --74 elseif (player:getCurrentMission(COP) == THREE_PATHS and player:getVar("COP_Tenzen_s_Path") == 4) then player:startEvent(0x0006); elseif (CooksPride == QUEST_COMPLETED and TheLostCardien == QUEST_AVAILABLE and player:getVar("theLostCardianVar") == 2) then player:startEvent(0x0021); -- Long CS & Finish Quest "The Lost Cardian" 33 elseif (CooksPride == QUEST_COMPLETED and TheLostCardien == QUEST_AVAILABLE and player:getVar("theLostCardianVar") == 3) then player:startEvent(0x0022); -- Shot CS & Finish Quest "The Lost Cardian" 34 elseif (TheLostCardien == QUEST_COMPLETED and player:getQuestStatus(JEUNO,THE_KIND_CARDIAN) == QUEST_ACCEPTED) then player:startEvent(0x0020); -- 32 else player:startEvent(0x001c); -- Standard dialog 28 end end; --Door:Infirmary 2 ++ --Door:Infirmary 10 ++ --Door:Infirmary 207 ++ --Door:Infirmary 82 ++ --Door:Infirmary 10059 nonCOP --Door:Infirmary 10060 nonCOP --Door:Infirmary 10205 nonCOP --Door:Infirmary 10061 nonCOP --Door:Infirmary 10062 nonCOP --Door:Infirmary 10207 nonCOP --Door:Infirmary 33 ++ --Door:Infirmary 34 ++ --Door:Infirmary 2 ++ --Door:Infirmary 82 ++ --Door:Infirmary 75 ++ --Door:Infirmary 10060 nonCOP --Door:Infirmary 10205 nonCOP --Tenzen 10011 --Tenzen 10012 ----------------------------------- -- 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 == 0x0006) then player:setVar("COP_Tenzen_s_Path",5); elseif (csid == 0x004a) then player:setVar("COP_Tenzen_s_Path",3); player:addKeyItem(ENVELOPE_FROM_MONBERAUX); player:messageSpecial(KEYITEM_OBTAINED,ENVELOPE_FROM_MONBERAUX); elseif (csid == 0x000a) then player:setVar("PromathiaStatus",0); player:addKeyItem(MYSTERIOUS_AMULET_DRAINED); player:completeMission(COP,THE_RITES_OF_LIFE); player:addMission(COP,BELOW_THE_ARKS); -- start the mission 1-2 player:startEvent(0x00ce); -- 206 elseif (csid == 0x00ce) then player:startEvent(0x00cf); --207 elseif (csid == 0x0052) then player:setVar("PromathiaStatus",1); elseif (csid == 0x004B) then player:setVar("PromathiaStatus",0); player:completeMission(COP,DARKNESS_NAMED); player:addMission(COP,SHELTERING_DOUBT); elseif (csid == 0x005b) then player:setVar("saveTheClockTowerVar",player:getVar("saveTheClockTowerVar") + 1); player:setVar("saveTheClockTowerNPCz1",player:getVar("saveTheClockTowerNPCz1") + 4); elseif (csid == 0x0021 and option == 0 or csid == 0x0022 and option == 0) then player:addTitle(TWOS_COMPANY); player:setVar("theLostCardianVar",0); player:addGil(GIL_RATE*2100); player:messageSpecial(GIL_OBTAINED,GIL_RATE*2100); player:addKeyItem(TWO_OF_SWORDS); player:messageSpecial(KEYITEM_OBTAINED,TWO_OF_SWORDS); -- Two of Swords (Key Item) player:addFame(JEUNO,30); player:completeQuest(JEUNO,THE_LOST_CARDIAN); player:addQuest(JEUNO,THE_KIND_CARDIAN); -- Start next quest "THE_KING_CARDIAN" elseif (csid == 0x0021 and option == 1) then player:setVar("theLostCardianVar",3); end end;
gpl-3.0
Configi/configi
vendor/lua/lfs.lua
1
31578
local bit = require "bit" local ffi = require "ffi" local band = bit.band local rshift = bit.rshift local lib = ffi.C local ffi_str = ffi.string local concat = table.concat local has_table_new, new_tab = pcall(require, "table.new") if not has_table_new or type(new_tab) ~= "function" then new_tab = function () return {} end end local _M = { _VERSION = "0.1", } -- common utils/constants local IS_64_BIT = ffi.abi('64bit') local ERANGE = 'Result too large' ffi.cdef([[ char* strerror(int errnum); ]]) local function errno() return ffi_str(lib.strerror(ffi.errno())) end local OS = ffi.os -- sys/syslimits.h local MAXPATH local wchar_t if OS == 'Windows' then MAXPATH = 260 ffi.cdef([[ typedef int mbstate_t; /* In VC2015, M$ change the definition of mbstate_t to this and breaks the ABI. */ typedef struct _Mbstatet { // state of a multibyte translation unsigned long _Wchar; unsigned short _Byte, _State; } _Mbstatet; typedef _Mbstatet mbstate_t; size_t mbrtowc(wchar_t* pwc, const char* s, size_t n, mbstate_t* ps); ]]) function wchar_t(s) local mbstate = ffi.new('mbstate_t[1]') local wcs = ffi.new('wchar_t[?]', #s + 1) local i = 0 local offset = 0 local len = #s while true do local processed = lib.mbrtowc( wcs + i, ffi.cast('const char *', s) + offset, len, mbstate) if processed <= 0 then break end i = i + 1 offset = offset + processed len = len - processed end return wcs end elseif OS == 'Linux' then MAXPATH = 4096 else MAXPATH = 1024 end -- misc if OS == "Windows" then local utime_def if IS_64_BIT then utime_def = [[ typedef __int64 time_t; struct __utimebuf64 { time_t actime; time_t modtime; }; typedef struct __utimebuf64 utimebuf; int _utime64(unsigned char *file, utimebuf *times); ]] else utime_def = [[ typedef __int32 time_t; struct __utimebuf32 { time_t actime; time_t modtime; }; typedef struct __utimebuf32 utimebuf; int _utime632(unsigned char *file, utimebuf *times); ]] end ffi.cdef([[ char *_getcwd(char *buf, size_t size); int _chdir(const char *path); int _rmdir(const char *pathname); int _mkdir(const char *pathname); ]] .. utime_def .. [[ typedef wchar_t* LPTSTR; typedef unsigned char BOOLEAN; typedef unsigned long DWORD; BOOLEAN CreateSymbolicLinkW( LPTSTR lpSymlinkFileName, LPTSTR lpTargetFileName, DWORD dwFlags ); int _fileno(struct FILE *stream); int _setmode(int fd, int mode); ]]) function _M.chdir(path) if type(path) ~= 'string' then error('path should be a string') end if lib._chdir(path) == 0 then return true end return nil, errno() end function _M.currentdir() local size = MAXPATH while true do local buf = ffi.new("char[?]", size) if lib._getcwd(buf, size) ~= nil then return ffi_str(buf) end local err = errno() if err ~= ERANGE then return nil, err end size = size * 2 end end function _M.mkdir(path) if type(path) ~= 'string' then error('path should be a string') end if lib._mkdir(path) == 0 then return true end return nil, errno() end function _M.rmdir(path) if type(path) ~= 'string' then error('path should be a string') end if lib._rmdir(path) == 0 then return true end return nil, errno() end function _M.touch(path, actime, modtime) local buf if type(actime) == "number" then modtime = modtime or actime buf = ffi.new("utimebuf") buf.actime = actime buf.modtime = modtime end local p = ffi.new("unsigned char[?]", #path + 1) ffi.copy(p, path) local utime = IS_64_BIT and lib._utime64 or lib._utime32 if utime(p, buf) == 0 then return true end return nil, errno() end function _M.setmode(file, mode) if io.type(file) ~= 'file' then error("setmode: invalid file") end if mode ~= nil and (mode ~= 'text' and mode ~= 'binary') then error('setmode: invalid mode') end mode = (mode == 'text') and 0x4000 or 0x8000 local prev_mode = lib._setmode(lib._fileno(file), mode) if prev_mode == -1 then return nil, errno() end return true, (prev_mode == 0x4000) and 'text' or 'binary' end local function check_is_dir(path) return _M.attributes(path, 'mode') == 'directory' and 1 or 0 end function _M.link(old, new) local is_dir = check_is_dir(old) if lib.CreateSymbolicLinkW( wchar_t(new), wchar_t(old), is_dir) ~= 0 then return true end return nil, errno() end local findfirst local findnext if IS_64_BIT then ffi.cdef([[ typedef struct _finddata64_t { uint64_t attrib; uint64_t time_create; uint64_t time_access; uint64_t time_write; uint64_t size; char name[]] .. MAXPATH ..[[]; } _finddata_t; int _findfirst64(const char *filespec, _finddata_t *fileinfo); int _findnext64(int handle, _finddata_t *fileinfo); int _findclose(int handle); ]]) findfirst = lib._findfirst64 findnext = lib._findnext64 else ffi.cdef([[ typedef struct _finddata32_t { uint32_t attrib; uint32_t time_create; uint32_t time_access; uint32_t time_write; uint32_t size; char name[]] .. MAXPATH ..[[]; } _finddata_t; int _findfirst32(const char* filespec, _finddata_t* fileinfo); int _findnext32(int handle, _finddata_t *fileinfo); int _findclose(int handle); ]]) findfirst = lib._findfirst32 findnext = lib._findnext32 end local function findclose(dentry) if dentry and dentry.handle ~= -1 then lib._findclose(dentry.handle) dentry.handle = -1 end end local dir_type = ffi.metatype("struct {int handle;}", { __gc = findclose }) local function close(dir) findclose(dir._dentry) dir.closed = true end local function iterator(dir) if dir.closed ~= false then error("closed directory") end local entry = ffi.new("_finddata_t") if not dir._dentry then dir._dentry = ffi.new(dir_type) dir._dentry.handle = findfirst(dir._pattern, entry) if dir._dentry.handle == -1 then dir.closed = true return nil, errno() end return ffi_str(entry.name) end if findnext(dir._dentry.handle, entry) == 0 then return ffi_str(entry.name) end close(dir) return nil end local dirmeta = {__index = { next = iterator, close = close, }} function _M.dir(path) if #path > MAXPATH - 2 then error('path too long: ' .. path) end local dir_obj = setmetatable({ _pattern = path..'/*', closed = false, }, dirmeta) return iterator, dir_obj end ffi.cdef([[ int _fileno(struct FILE *stream); int fseek(struct FILE *stream, long offset, int origin); long ftell(struct FILE *stream); int _locking(int fd, int mode, long nbytes); ]]) local mode_ltype_map = { r = 2, -- LK_NBLCK w = 2, -- LK_NBLCK u = 0, -- LK_UNLCK } local SEEK_SET = 0 local SEEK_END = 2 local function lock(fh, mode, start, len) local lkmode = mode_ltype_map[mode] if not len or len <= 0 then if lib.fseek(fh, 0, SEEK_END) ~= 0 then return nil, errno() end len = lib.ftell(fh) end if not start or start <= 0 then start = 0 end if lib.fseek(fh, start, SEEK_SET) ~= 0 then return nil, errno() end local fd = lib._fileno(fh) if lib._locking(fd, lkmode, len) == -1 then return nil, errno() end return true end function _M.lock(filehandle, mode, start, length) if mode ~= 'r' and mode ~= 'w' then error("lock: invalid mode") end if io.type(filehandle) ~= 'file' then error("lock: invalid file") end local ok, err = lock(filehandle, mode, start, length) if not ok then return nil, err end return true end function _M.unlock(filehandle, start, length) if io.type(filehandle) ~= 'file' then error("unlock: invalid file") end local ok, err = lock(filehandle, 'u', start, length) if not ok then return nil, err end return true end else ffi.cdef([[ char *getcwd(char *buf, size_t size); int chdir(const char *path); int rmdir(const char *pathname); typedef unsigned int mode_t; int mkdir(const char *pathname, mode_t mode); typedef size_t time_t; struct utimebuf { time_t actime; time_t modtime; }; int utime(const char *file, const struct utimebuf *times); int link(const char *oldpath, const char *newpath); int symlink(const char *oldpath, const char *newpath); ]]) function _M.chdir(path) if lib.chdir(path) == 0 then return true end return nil, errno() end function _M.currentdir() local size = MAXPATH while true do local buf = ffi.new("char[?]", size) if lib.getcwd(buf, size) ~= nil then return ffi_str(buf) end local err = errno() if err ~= ERANGE then return nil, err end size = size * 2 end end function _M.mkdir(path, mode) if lib.mkdir(path, mode or 509) == 0 then return true end return nil, errno() end function _M.rmdir(path) if lib.rmdir(path) == 0 then return true end return nil, errno() end function _M.touch(path, actime, modtime) local buf if type(actime) == "number" then modtime = modtime or actime buf = ffi.new("struct utimebuf") buf.actime = actime buf.modtime = modtime end local p = ffi.new("unsigned char[?]", #path + 1) ffi.copy(p, path) if lib.utime(p, buf) == 0 then return true end return nil, errno() end function _M.setmode() return true, "binary" end function _M.link(old, new, symlink) local f = symlink and lib.symlink or lib.link if f(old, new) == 0 then return true end return nil, errno() end local dirent_def if OS == 'OSX' or OS == 'BSD' then dirent_def = [[ /* _DARWIN_FEATURE_64_BIT_INODE is NOT defined here? */ struct dirent { uint32_t d_ino; uint16_t d_reclen; uint8_t d_type; uint8_t d_namlen; char d_name[256]; }; ]] else dirent_def = [[ struct dirent { int64_t d_ino; size_t d_off; unsigned short d_reclen; unsigned char d_type; char d_name[256]; }; ]] end ffi.cdef(dirent_def .. [[ typedef struct __dirstream DIR; DIR *opendir(const char *name); struct dirent *readdir(DIR *dirp); int closedir(DIR *dirp); ]]) local function close(dir) if dir._dentry ~= nil then lib.closedir(dir._dentry) dir._dentry = nil dir.closed = true end end local function iterator(dir) if dir.closed ~= false then error("closed directory") end local entry = lib.readdir(dir._dentry) if entry ~= nil then return ffi_str(entry.d_name) else close(dir) return nil end end local dir_obj_type = ffi.metatype([[ struct { DIR *_dentry; bool closed; } ]], {__index = { next = iterator, close = close, }, __gc = close }) function _M.dir(path) local dentry = lib.opendir(path) if dentry == nil then error("cannot open "..path.." : "..errno()) end local dir_obj = ffi.new(dir_obj_type) dir_obj._dentry = dentry dir_obj.closed = false; return iterator, dir_obj end local SEEK_SET = 0 local F_SETLK = (OS == 'Linux') and 6 or 8 local mode_ltype_map local flock_def if OS == 'Linux' then flock_def = [[ struct flock { short int l_type; short int l_whence; int64_t l_start; int64_t l_len; int l_pid; }; ]] mode_ltype_map = { r = 0, -- F_RDLCK w = 1, -- F_WRLCK u = 2, -- F_UNLCK } else flock_def = [[ struct flock { int64_t l_start; int64_t l_len; int32_t l_pid; short l_type; short l_whence; }; ]] mode_ltype_map = { r = 1, -- F_RDLCK u = 2, -- F_UNLCK w = 3, -- F_WRLCK } end ffi.cdef(flock_def..[[ int fileno(struct FILE *stream); int fcntl(int fd, int cmd, ... /* arg */ ); int unlink(const char *path); ]]) local function lock(fd, mode, start, len) local flock = ffi.new('struct flock') flock.l_type = mode_ltype_map[mode] flock.l_whence = SEEK_SET flock.l_start = start or 0 flock.l_len = len or 0 if lib.fcntl(fd, F_SETLK, flock) == -1 then return nil, errno() end return true end function _M.lock(filehandle, mode, start, length) if mode ~= 'r' and mode ~= 'w' then error("lock: invalid mode") end if io.type(filehandle) ~= 'file' then error("lock: invalid file") end local fd = lib.fileno(filehandle) local ok, err = lock(fd, mode, start, length) if not ok then return nil, err end return true end function _M.unlock(filehandle, start, length) if io.type(filehandle) ~= 'file' then error("unlock: invalid file") end local fd = lib.fileno(filehandle) local ok, err = lock(fd, 'u', start, length) if not ok then return nil, err end return true end end -- lock related local dir_lock_struct local create_lockfile local delete_lockfile if OS == 'Windows' then ffi.cdef([[ typedef const wchar_t* LPCWSTR; typedef struct _SECURITY_ATTRIBUTES { DWORD nLength; void *lpSecurityDescriptor; int bInheritHandle; } SECURITY_ATTRIBUTES; typedef SECURITY_ATTRIBUTES *LPSECURITY_ATTRIBUTES; void *CreateFileW( LPCWSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, void *hTemplateFile ); int CloseHandle(void *hObject); ]]) local GENERIC_WRITE = 0x40000000 local CREATE_NEW = 1 local FILE_NORMAL_DELETE_ON_CLOSE = 0x04000080 dir_lock_struct = 'struct {void *lockname;}' function create_lockfile(dir_lock, _, lockname) lockname = wchar_t(lockname) dir_lock.lockname = lib.CreateFileW(lockname, GENERIC_WRITE, 0, nil, CREATE_NEW, FILE_NORMAL_DELETE_ON_CLOSE, nil) return dir_lock.lockname ~= ffi.cast('void*', -1) end function delete_lockfile(dir_lock) return lib.CloseHandle(dir_lock.lockname) end else dir_lock_struct = 'struct {char *lockname;}' function create_lockfile(dir_lock, path, lockname) dir_lock.lockname = ffi.new('char[?]', #lockname + 1) ffi.copy(dir_lock.lockname, lockname) return lib.symlink(path, lockname) == 0 end function delete_lockfile(dir_lock) return lib.unlink(dir_lock.lockname) end end local function unlock_dir(dir_lock) if dir_lock.lockname ~= nil then dir_lock:delete_lockfile() dir_lock.lockname = nil end return true end local dir_lock_type = ffi.metatype(dir_lock_struct, {__gc = unlock_dir, __index = { free = unlock_dir, create_lockfile = create_lockfile, delete_lockfile = delete_lockfile, }} ) function _M.lock_dir(path, _) -- It's interesting that the lock_dir from vanilla lfs just ignores second paramter. -- So, I follow this behavior too :) local dir_lock = ffi.new(dir_lock_type) local lockname = path .. '/lockfile.lfs' if not dir_lock:create_lockfile(path, lockname) then return nil, errno() end return dir_lock end -- stat related local stat_func local lstat_func if OS == 'Linux' then ffi.cdef([[ long syscall(int number, ...); ]]) local ARCH = ffi.arch -- Taken from justincormack/ljsyscall local stat_syscall_num local lstat_syscall_num if ARCH == 'x64' then ffi.cdef([[ typedef struct { unsigned long st_dev; unsigned long st_ino; unsigned long st_nlink; unsigned int st_mode; unsigned int st_uid; unsigned int st_gid; unsigned int __pad0; unsigned long st_rdev; long st_size; long st_blksize; long st_blocks; unsigned long st_atime; unsigned long st_atime_nsec; unsigned long st_mtime; unsigned long st_mtime_nsec; unsigned long st_ctime; unsigned long st_ctime_nsec; long __unused[3]; } stat; ]]) stat_syscall_num = 4 lstat_syscall_num = 6 elseif ARCH == 'x86' then ffi.cdef([[ typedef struct { unsigned long long st_dev; unsigned char __pad0[4]; unsigned long __st_ino; unsigned int st_mode; unsigned int st_nlink; unsigned long st_uid; unsigned long st_gid; unsigned long long st_rdev; unsigned char __pad3[4]; long long st_size; unsigned long st_blksize; unsigned long long st_blocks; unsigned long st_atime; unsigned long st_atime_nsec; unsigned long st_mtime; unsigned int st_mtime_nsec; unsigned long st_ctime; unsigned long st_ctime_nsec; unsigned long long st_ino; } stat; ]]) stat_syscall_num = IS_64_BIT and 106 or 195 lstat_syscall_num = IS_64_BIT and 107 or 196 elseif ARCH == 'arm' then if IS_64_BIT then ffi.cdef([[ typedef struct { unsigned long st_dev; unsigned long st_ino; unsigned int st_mode; unsigned int st_nlink; unsigned int st_uid; unsigned int st_gid; unsigned long st_rdev; unsigned long __pad1; long st_size; int st_blksize; int __pad2; long st_blocks; long st_atime; unsigned long st_atime_nsec; long st_mtime; unsigned long st_mtime_nsec; long st_ctime; unsigned long st_ctime_nsec; unsigned int __unused4; unsigned int __unused5; } stat; ]]) stat_syscall_num = 106 lstat_syscall_num = 107 else ffi.cdef([[ typedef struct { unsigned long long st_dev; unsigned char __pad0[4]; unsigned long __st_ino; unsigned int st_mode; unsigned int st_nlink; unsigned long st_uid; unsigned long st_gid; unsigned long long st_rdev; unsigned char __pad3[4]; long long st_size; unsigned long st_blksize; unsigned long long st_blocks; unsigned long st_atime; unsigned long st_atime_nsec; unsigned long st_mtime; unsigned int st_mtime_nsec; unsigned long st_ctime; unsigned long st_ctime_nsec; unsigned long long st_ino; } stat; ]]) stat_syscall_num = 195 lstat_syscall_num = 196 end elseif ARCH == 'ppc' or ARCH == 'ppcspe' then ffi.cdef([[ typedef struct { unsigned long long st_dev; unsigned long long st_ino; unsigned int st_mode; unsigned int st_nlink; unsigned int st_uid; unsigned int st_gid; unsigned long long st_rdev; unsigned long long __pad1; long long st_size; int st_blksize; int __pad2; long long st_blocks; int st_atime; unsigned int st_atime_nsec; int st_mtime; unsigned int st_mtime_nsec; int st_ctime; unsigned int st_ctime_nsec; unsigned int __unused4; unsigned int __unused5; } stat; ]]) stat_syscall_num = IS_64_BIT and 106 or 195 lstat_syscall_num = IS_64_BIT and 107 or 196 elseif ARCH == 'mips' or ARCH == 'mipsel' then ffi.cdef([[ typedef struct { unsigned long st_dev; unsigned long __st_pad0[3]; unsigned long long st_ino; mode_t st_mode; nlink_t st_nlink; uid_t st_uid; gid_t st_gid; unsigned long st_rdev; unsigned long __st_pad1[3]; long long st_size; time_t st_atime; unsigned long st_atime_nsec; time_t st_mtime; unsigned long st_mtime_nsec; time_t st_ctime; unsigned long st_ctime_nsec; unsigned long st_blksize; unsigned long __st_pad2; long long st_blocks; long __st_padding4[14]; } stat; ]]) stat_syscall_num = IS_64_BIT and 4106 or 4213 lstat_syscall_num = IS_64_BIT and 4107 or 4214 end if stat_syscall_num then stat_func = function(filepath, buf) return lib.syscall(stat_syscall_num, filepath, buf) end lstat_func = function(filepath, buf) return lib.syscall(lstat_syscall_num, filepath, buf) end else ffi.cdef('typedef struct {} stat;') stat_func = function() error("TODO support other Linux architectures") end lstat_func = stat_func end elseif OS == 'Windows' then ffi.cdef([[ typedef struct { unsigned int st_dev; unsigned short st_ino; unsigned short st_mode; short st_nlink; short st_uid; short st_gid; unsigned int st_rdev; int64_t st_size; long long st_atime; long long st_mtime; long long st_ctime; } stat; int _stat64(const char *path, stat *buffer); ]]) stat_func = lib._stat64 lstat_func = stat_func elseif OS == 'OSX' then ffi.cdef([[ struct timespec { time_t tv_sec; long tv_nsec; }; typedef struct { uint32_t st_dev; uint16_t st_mode; uint16_t st_nlink; uint64_t st_ino; uint32_t st_uid; uint32_t st_gid; uint32_t st_rdev; struct timespec st_atimespec; struct timespec st_mtimespec; struct timespec st_ctimespec; struct timespec st_birthtimespec; int64_t st_size; int64_t st_blocks; int32_t st_blksize; uint32_t st_flags; uint32_t st_gen; int32_t st_lspare; int64_t st_qspare[2]; } stat; int stat64(const char *path, stat *buf); int lstat64(const char *path, stat *buf); ]]) stat_func = lib.stat64 lstat_func = lib.lstat64 else ffi.cdef('typedef struct {} stat;') stat_func = function() error('TODO: support other posix system') end lstat_func = stat_func end local STAT = { FMT = 0xF000, FSOCK = 0xC000, FLNK = 0xA000, FREG = 0x8000, FBLK = 0x6000, FDIR = 0x4000, FCHR = 0x2000, FIFO = 0x1000, } local ftype_name_map = { [STAT.FREG] = 'file', [STAT.FDIR] = 'directory', [STAT.FLNK] = 'link', [STAT.FSOCK] = 'socket', [STAT.FCHR] = 'char device', [STAT.FBLK] = "block device", [STAT.FIFO] = "named pipe", } local function mode_to_ftype(mode) local ftype = band(mode, STAT.FMT) return ftype_name_map[ftype] or 'other' end local function mode_to_perm(mode) local perm_bits = band(mode, tonumber(777, 8)) local perm = new_tab(9, 0) local i = 9 while i > 0 do local perm_bit = band(perm_bits, 7) perm[i] = (band(perm_bit, 1) > 0 and 'x' or '-') perm[i-1] = (band(perm_bit, 2) > 0 and 'w' or '-') perm[i-2] = (band(perm_bit, 4) > 0 and 'r' or '-') i = i - 3 perm_bits = rshift(perm_bits, 3) end return concat(perm) end local function time_or_timespec(time, timespec) local t = tonumber(time) if not t and timespec then t = tonumber(timespec.tv_sec) end return t end local attr_handlers = { access = function(st) return time_or_timespec(st.st_atime, st.st_atimespec) end, blksize = function(st) return tonumber(st.st_blksize) end, blocks = function(st) return tonumber(st.st_blocks) end, change = function(st) return time_or_timespec(st.st_ctime, st.st_ctimespec) end, dev = function(st) return tonumber(st.st_dev) end, gid = function(st) return tonumber(st.st_gid) end, ino = function(st) return tonumber(st.st_ino) end, mode = function(st) return mode_to_ftype(st.st_mode) end, modification = function(st) return time_or_timespec(st.st_mtime, st.st_mtimespec) end, nlink = function(st) return tonumber(st.st_nlink) end, permissions = function(st) return mode_to_perm(st.st_mode) end, rdev = function(st) return tonumber(st.st_rdev) end, size = function(st) return tonumber(st.st_size) end, uid = function(st) return tonumber(st.st_uid) end, } -- Add target field for symlinkattributes, which is the absolute path of linked target local get_link_target_path if OS == 'Windows' then function get_link_target_path() return nil end else ffi.cdef('unsigned long readlink(const char *path, char *buf, size_t bufsize);') function get_link_target_path(link_path) local size = MAXPATH while true do local buf = ffi.new('char[?]', size) local read = lib.readlink(link_path, buf, size) if read == -1 then return nil, errno() end if read < size then return ffi_str(buf) end size = size * 2 end end end local mt = { __index = function(self, attr_name) local func = attr_handlers[attr_name] return func and func(self) end } local stat_type = ffi.metatype('stat', mt) local function attributes(filepath, attr, follow_symlink) local buf = ffi.new(stat_type) local func = follow_symlink and stat_func or lstat_func if func(filepath, buf) == -1 then return nil, errno() end local atype = type(attr) if atype == 'string' then local value if attr == 'target' and not follow_symlink then value = get_link_target_path(filepath) else value = buf[attr] end if value == nil then error("invalid attribute name '" .. attr .. "'") end return value else local tab = (atype == 'table') and attr or {} for k, _ in pairs(attr_handlers) do tab[k] = buf[k] end if not follow_symlink then tab.target = get_link_target_path(filepath) end return tab end end function _M.attributes(filepath, attr) return attributes(filepath, attr, true) end function _M.symlinkattributes(filepath, attr) return attributes(filepath, attr, false) end return _M
mit
Kikkers/Factorio-Smarter-Circuitry
actuator_0.4.9/control.lua
1
10305
require "defines" function prt(value) game.players[1].print(tostring(value)) end script.on_init(function() init() end) script.on_load(function() init() for _,actuator in ipairs(global.actuators) do if actuator.target ~= nil and actuator.target.valid then findFunction(actuator, actuator.target) end end end) function init() if global.actuators == nil then global.actuators = {} else for _,actuator in ipairs(global.actuators) do insertAt(actuator.base.position, actuator) end end if global.gateforce == nil then global.gateforce = game.create_force("gate") end end positions = {} function insertAt(pos, reference) if positions[pos.x] == nil then positions[pos.x] = {} end if positions[pos.x][pos.y] == nil then positions[pos.x][pos.y] = {} end positions[pos.x][pos.y] = reference end function getAt(pos) if positions[pos.x] == nil then return nil end return positions[pos.x][pos.y] end function table_nil_cleanup(targetTable) local j=0 local n = #targetTable for i=1,n do if targetTable[i]~=nil then j=j+1 targetTable[j]=targetTable[i] end end for i=j+1,n do targetTable[i]=nil end end script.on_event(defines.events.on_tick, function(event) for i,actuator in ipairs(global.actuators) do if actuator.base.valid then if actuator.target ~= nil and actuator.target.valid then if not actuator.checkForMovement or checkStationary(actuator) then local newState if actuator.base.energy > 0 then newState = testConditionFulfilled(actuator.base) else newState = false end if newState ~= actuator.state then actuator.state = newState setIndicator(actuator) actuator.tickFunction(actuator) elseif not actuator.behavesAsToggle and actuator.base.energy > 0 then actuator.tickFunction(actuator) end end else resetActuator(actuator) end else global.actuators[i] = nil end end if game.tick % 60 == 0 then table_nil_cleanup(global.actuators) end end) function testConditionFulfilled(wireConnectedObject) local wCondition = wireConnectedObject.get_circuit_condition(1) local lCondition = wireConnectedObject.get_circuit_condition(2) return lCondition.fulfilled or wCondition.fulfilled end function checkStationary(actuator) if actuator.vehiclepos == nil then actuator.vehiclepos = {x = actuator.target.position.x, y = actuator.target.position.y} else if actuator.vehiclepos.x == actuator.target.position.x and actuator.vehiclepos.y == actuator.target.position.y then return true else actuator.target = nil actuator.vehiclepos = nil end end return false end function tickactuator_train(actuator) if actuator.target.train.speed ~= 0 then return end if actuator.target.train.manual_mode ~= actuator.state then actuator.target.train.manual_mode = actuator.state end end function tickactuator_car(actuator) tickactuator_activation(actuator) end function tickactuator_gate(actuator) if actuator.state then actuator.target.request_to_open(global.gateforce) else actuator.target.request_to_close(global.gateforce) end end function resetActuator(actuator) actuator.target = nil actuator.tickFunction = nil actuator.state = testConditionFulfilled(actuator.base) actuator.checkForMovement = false actuator.behavesAsToggle = true actuator.wait = nil restoreGateSegments(actuator) if actuator.base.energy > 0 then setIndicator(actuator) end if findTarget(actuator) then actuator.state = not actuator.state -- force a change, but only in the next tick end end function restoreGateSegments(actuator) if actuator.gateSegments ~= nil then for _,segment in ipairs(actuator.gateSegments) do if segment.valid then segment.force = actuator.base.force end end end actuator.gateSegments = nil end function findGateSegments(actuator) local surface = actuator.base.surface local x = actuator.targetX local y = actuator.targetY local name = actuator.target.name local dir = actuator.target.direction local segments = {actuator.target} if dir == 2 then -- horizontal for i = 1, 1000 do local adj = surface.find_entities_filtered{area = {{x - 0.1 + i, y - 0.1}, {x + 0.1 + i, y + 0.1}}, name = name} if #adj == 0 or not adj[1].valid or adj[1].direction ~= dir then break else table.insert(segments, adj[1]) end end for i = 1, 1000 do local adj = surface.find_entities_filtered{area = {{x - 0.1 - i, y - 0.1}, {x + 0.1 - i, y + 0.1}}, name = name} if #adj == 0 or not adj[1].valid or adj[1].direction ~= dir then break else table.insert(segments, adj[1]) end end else -- vertical for i = 1, 1000 do local adj = surface.find_entities_filtered{area = {{x - 0.1, y - 0.1 + i}, {x + 0.1, y + 0.1 + i}}, name = name} if #adj == 0 or not adj[1].valid or adj[1].direction ~= dir then break else table.insert(segments, adj[1]) end end for i = 1, 1000 do local adj = surface.find_entities_filtered{area = {{x - 0.1, y - 0.1 - i}, {x + 0.1, y + 0.1 - i}}, name = name} if #adj == 0 or not adj[1].valid or adj[1].direction ~= dir then break else table.insert(segments, adj[1]) end end end for _,segment in ipairs(segments) do segment.force = global.gateforce end actuator.gateSegments = segments end function tickactuator_flip(actuator) actuator.target.direction = (actuator.target.direction + 4) % 8 end function tickactuator_activation(actuator) actuator.target.active = not actuator.state end searchHandler = { ["locomotive"] = tickactuator_train, ["transport-belt"] = tickactuator_flip, ["splitter"] = tickactuator_flip, ["car"] = tickactuator_car, ["gate"] = tickactuator_gate, } ignoredHandler = { ["car"] = true, ["player"] = true, } function findFunction(actuator, entity) local func = searchHandler[entity.type] if func ~= nil then actuator.tickFunction = func return true elseif ignoredHandler[entity.type] == nil and entity.energy ~= nil then actuator.tickFunction = tickactuator_activation return true end return false end function findTarget(actuator) local adj = actuator.base.surface.find_entities_filtered{area = {{actuator.targetX - 0.1, actuator.targetY - 0.1}, {actuator.targetX + 0.1, actuator.targetY + 0.1}}, force = actuator.base.force} for _,entity in ipairs(adj) do if findFunction(actuator, entity) then actuator.target = entity if actuator.tickFunction == tickactuator_train or actuator.tickFunction == tickactuator_car then actuator.checkForMovement = true actuator.behavesAsToggle = false elseif actuator.tickFunction == tickactuator_gate then actuator.behavesAsToggle = false findGateSegments(actuator) end return true end end return false end function getAdjPos(entity) local dir = entity.direction local posX = entity.position.x local posY = entity.position.y if dir == 6 then posX = posX + 1 elseif dir == 2 then posX = posX - 1 elseif dir == 0 then posY = posY + 1 elseif dir == 4 then posY = posY - 1 end return posX, posY end function createActuator(entity) if entity.name == "directional-actuator" then local targetX, targetY = getAdjPos(entity) local indicator = entity.surface.create_entity{name = "indicator-green", position = entity.position} local actuator = {base = entity, indicator = indicator, targetX = targetX, targetY = targetY, state = false, checkForMovement = false, behavesAsToggle = true} setIndicator(actuator) table.insert(global.actuators, actuator) insertAt(entity.position, actuator) end end script.on_event(defines.events.on_player_rotated_entity, function(event) if event.entity.name == "directional-actuator" then local targetX, targetY = getAdjPos(event.entity) local actuator = getAt(event.entity.position) tryDeactivate(actuator) actuator.targetX = targetX actuator.targetY = targetY resetActuator(actuator) end end) function tryDeactivate(actuator) if actuator.target ~= nil and actuator.target.valid and actuator.tickFunction ~= nil then actuator.state = false setIndicator(actuator) actuator.tickFunction(actuator) end end function setIndicator(actuator) if actuator.indicator ~= nil and actuator.indicator.valid then actuator.indicator.destroy() end if actuator.state then if actuator.target ~= nil and actuator.target.valid then actuator.indicator = actuator.base.surface.create_entity{name = "indicator-red", position = {x = actuator.base.position.x, y = actuator.base.position.y - 0.3}} else actuator.indicator = actuator.base.surface.create_entity{name = "indicator-orange", position = {x = actuator.base.position.x, y = actuator.base.position.y - 0.3}} end else actuator.indicator = actuator.base.surface.create_entity{name = "indicator-green", position = {x = actuator.base.position.x, y = actuator.base.position.y - 0.3}} end end function loopDestroy(list) for _, v in pairs(list) do if v ~= nil and v.valid then v.destroy() end end end function removeIndicators(entity) local x = entity.position.x local y = entity.position.y loopDestroy(entity.surface.find_entities_filtered{area = {{x - 0.5, y - 0.5}, {x + 0.5, y + 0.5}}, name = "indicator-green"}) loopDestroy(entity.surface.find_entities_filtered{area = {{x - 0.5, y - 0.5}, {x + 0.5, y + 0.5}}, name = "indicator-orange"}) loopDestroy(entity.surface.find_entities_filtered{area = {{x - 0.5, y - 0.5}, {x + 0.5, y + 0.5}}, name = "indicator-red"}) end function removeActuator(entity) if entity.name == "directional-actuator" then local actuator = getAt(entity.position) if actuator == nil then removeIndicators(entity) else tryDeactivate(actuator) restoreGateSegments(actuator) if actuator.indicator ~= nil and actuator.indicator.valid then actuator.indicator.destroy() end end end end script.on_event(defines.events.on_built_entity, function(event) createActuator(event.created_entity) end) script.on_event(defines.events.on_robot_built_entity, function(event) createActuator(event.created_entity) end) script.on_event(defines.events.on_preplayer_mined_item, function(event) removeActuator(event.entity) end) script.on_event(defines.events.on_robot_pre_mined, function(event) removeActuator(event.entity) end)
unlicense
MetroGirl/Src_LUNA
Luna/data/script/cameracontroller.lua
1
1618
ID = "Script" local g_init_pos = { 2.0, 2.0, -2.0 } local g_init_at = { 0.0, 1.0, 0.0 } local g_time = 0.0 local function greets_camera(scene_time_second) local elapsed = scene_time_second - 75 return { posx = g_init_pos[1] - 0.5 + 0.3 * elapsed, posy = g_init_pos[2] + 1.5 + math.sin(scene_time_second), posz = g_init_pos[3] + math.cos(scene_time_second), atx = g_init_at[1] - 0.5 + 0.3 * elapsed, aty = g_init_at[2], atz = g_init_at[3], } end local function ending_camera(scene_time_second) local y = math.min(scene_time_second, 204) if 169 < scene_time_second then return { posx = g_init_pos[1], posy = g_init_pos[2] + 0.3 * (y-169), posz = g_init_pos[3], atx = g_init_at[1], aty = g_init_at[2] + 0.36 * (y-169), atz = g_init_at[3], } end return { posx = g_init_pos[1], posy = g_init_pos[2], posz = g_init_pos[3], atx = g_init_at[1], aty = g_init_at[2], atz = g_init_at[3], } end function get_position(scene_time_second, scene_time_ratio) local time = g_time g_time = g_time + 0.1 if scene_time_second < 75 then return { posx = g_init_pos[1],-- + 0.3 * time, posy = g_init_pos[2], posz = g_init_pos[3], atx = g_init_at[1],-- + 0.3 * time, aty = g_init_at[2], atz = g_init_at[3], } elseif scene_time_second < 104 then return greets_camera(scene_time_second) elseif 155 < scene_time_second then return ending_camera(scene_time_second) end return { posx = g_init_pos[1],-- + 0.3 * time, posy = g_init_pos[2], posz = g_init_pos[3], atx = g_init_at[1],-- + 0.3 * time, aty = g_init_at[2], atz = g_init_at[3], } end
artistic-2.0
jono659/enko
scripts/zones/Windurst_Waters_[S]/npcs/Emhi_Tchaoryo.lua
38
1061
----------------------------------- -- Area: Windurst Waters (S) -- NPC: Emhi Tchaoryo -- Type: Campaign Ops Overseer -- @zone: 94 -- @pos 10.577 -2.478 32.680 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Windurst_Waters_[S]/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0133); 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
Arcscion/Shadowlyre
scripts/zones/Aht_Urhgan_Whitegate/npcs/Sharin-Garin.lua
3
1976
----------------------------------- -- Area: Aht Urhgan Whitegate -- NPC: Sharin-Garin -- Type: Adventurer's Assistant -- !pos 122.658 -1.315 33.001 50 ----------------------------------- package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil; ----------------------------------- require("scripts/globals/besieged"); require("scripts/globals/keyitems"); require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local runicpass = 0; if (player:hasKeyItem(RUNIC_PORTAL_USE_PERMIT)) then runicpass = 1; end local cost = 200 -- 200 IS to get a permit if (getMercenaryRank(player) == 11) then captain = 1; else captain = 0; end; local merc = 2 -- Probably could be done, but not really important atm player:startEvent(0x008C,0,merc,runicpass,player:getCurrency("imperial_standing"),getAstralCandescence(),cost,captain); 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 == 0x008C and option == 1) then player:addKeyItem(RUNIC_PORTAL_USE_PERMIT); player:messageSpecial(KEYITEM_OBTAINED,RUNIC_PORTAL_USE_PERMIT); player:delCurrency("imperial_standing", 200); elseif (csid == 0x008C and option == 2) then player:addKeyItem(RUNIC_PORTAL_USE_PERMIT); player:messageSpecial(KEYITEM_OBTAINED,RUNIC_PORTAL_USE_PERMIT); end end;
gpl-3.0
michelePap/tg
test.lua
210
2571
started = 0 our_id = 0 function vardump(value, depth, key) local linePrefix = "" local spaces = "" if key ~= nil then linePrefix = "["..key.."] = " end if depth == nil then depth = 0 else depth = depth + 1 for i=1, depth do spaces = spaces .. " " end end if type(value) == 'table' then mTable = getmetatable(value) if mTable == nil then print(spaces ..linePrefix.."(table) ") else print(spaces .."(metatable) ") value = mTable end for tableKey, tableValue in pairs(value) do vardump(tableValue, depth, tableKey) end elseif type(value) == 'function' or type(value) == 'thread' or type(value) == 'userdata' or value == nil then print(spaces..tostring(value)) else print(spaces..linePrefix.."("..type(value)..") "..tostring(value)) end end print ("HI, this is lua script") function ok_cb(extra, success, result) end -- Notification code {{{ function get_title (P, Q) if (Q.type == 'user') then return P.first_name .. " " .. P.last_name elseif (Q.type == 'chat') then return Q.title elseif (Q.type == 'encr_chat') then return 'Secret chat with ' .. P.first_name .. ' ' .. P.last_name else return '' end end local lgi = require ('lgi') local notify = lgi.require('Notify') notify.init ("Telegram updates") local icon = os.getenv("HOME") .. "/.telegram-cli/telegram-pics/telegram_64.png" function do_notify (user, msg) local n = notify.Notification.new(user, msg, icon) n:show () end -- }}} function on_msg_receive (msg) if started == 0 then return end if msg.out then return end do_notify (get_title (msg.from, msg.to), msg.text) if (msg.text == 'ping') then if (msg.to.id == our_id) then send_msg (msg.from.print_name, 'pong', ok_cb, false) else send_msg (msg.to.print_name, 'pong', ok_cb, false) end return end if (msg.text == 'PING') then if (msg.to.id == our_id) then fwd_msg (msg.from.print_name, msg.id, ok_cb, false) else fwd_msg (msg.to.print_name, msg.id, ok_cb, false) end return end 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) --vardump (chat) end function on_secret_chat_update (schat, what) --vardump (schat) end function on_get_difference_end () end function cron() -- do something postpone (cron, false, 1.0) end function on_binlog_replay_end () started = 1 postpone (cron, false, 1.0) end
gpl-2.0
N0U/Zero-K
LuaUI/Configs/nubtron_config.lua
5
8962
--[[ INSTRUCTIONS Choose names for the unitClass table and use those names in conditions. For example if you use "Con" then you must use "ConSelected" not "conSelected": local unitClasses = { Con = { 'cloakcon' }, } local steps = { selectCon = { image = unitClasses.Con[1] ..'.png', passIfAny = { 'ConSelected' }, }, } Use the mClasses table to indicate mobile units, as opposed to structures. local mClasses = { Con=1, } ** Tasks and Steps ** Tasks and steps can either pass (move to next task/step) or fail (go to previous task/step). A task contains a set of steps. Define the steps in a task using the "states" table (sorry, steps = states). A task will pass when its own conditions pass and it's on its final step (state). You can set conditions for a tasks/steps using the following tables. ** Condition tables ** errIfAny - task/step fails if any conditions are true errIfAnyNot - task/step fails if any conditions are false passIfAny - task/step completes if any conditions are true passIfAnyNot - task/step completes if any conditions are false ** Generic conditions ** have<unitClass> - unit exists and is completed <unitClass>Selected - unit is selected ** Special Built-in conditions ** clickedNubtron - user clicks Next button commSelected - user selects commander (based on customparam in ZK) gameStarted guardFac - constructor (Con) guards factory (BotLab) lowMetalIncome lowEnergryIncome metalMapView ** Generic Steps (autogenerated for you) ** selectBuild<unitClass> - Tells user to select a structure from the build menu start<unitClass> - Triggers if user selected the structure to be built. Tells user to place the structure build<unitClass> - Unit (mobile or structure) is being built finish<unitClass> - Triggers if structure partly completed structure is no longer being built, tells user that structure needs finishing ]] --- unit classes --- local unitClasses = { Mex = { 'staticmex' }, Solar = { 'energysolar' }, LLT = { 'turretlaser' }, BotLab = { 'factorycloak' }, Radar = { 'staticradar' }, Con = { 'cloakcon' }, Raider = { 'cloakraid' }, } local unitClassNames = { Mex = 'Mex', Solar = 'Solar Collector', LLT = 'LLT', BotLab = 'Bot Lab', Radar = 'Radar', Con = 'Constructor', Raider = 'Raider', } --mobile units local mClasses = { Con=1, Raider=1, } -- generic sub states local steps = { intro = { --message = 'Hello! I am Nubtron, the friendly robot. I will teach you how to play Complete Annihilation. <(Click here to continue)>', passIfAny = { 'clickedNubtron', }, }, intro2 = { --message = 'Just follow my instructions. You can drag this window around by my face. <(Click here to continue)>', passIfAny = { 'clickedNubtron'}, }, intro3 = { --message = 'Practice zooming the camera in and out with your mouse\'s scroll wheel <(Click here to continue)>', passIfAny = { 'clickedNubtron' }, }, intro4 = { --message = 'Practice panning the camera up, down, left and right with your arrow keys. <(Click here to continue)>', passIfAny = { 'clickedNubtron' }, }, intro5 = { --message = 'Place your starting position by clicking on a nice flat spot on the map, then click on the <Ready> button', passIfAny = { 'gameStarted' }, }, selectComm = { --message = 'Select only your commander by clicking on it or pressing <ctrl+c>.', passIfAny = {'commSelected'} }, showMetalMap = { --message = 'View the metal map by pressing <F4>.', passIfAny = { 'metalMapView' } }, hideMetalMap = { --message = 'Hide the metal map by pressing <F4>.', passIfAnyNot = { 'metalMapView' } }, selectBotLab = { --message = 'Select only your Bot Lab by clicking on it (the blue circles will help you find it).', passIfAny = { 'BotLabSelected' } }, selectCon = { --message = 'Select one constructor by clicking on it (the blue circles will help you find it).', --image = { arm='unitpics/'.. unitClasses.Con[1] ..'.png', core='unitpics/'.. unitClasses.Con[2] ..'.png' }, image = unitClasses.Con[1] ..'.png', passIfAny = { 'ConSelected' }, }, guardFac = { --message = 'Have the constructor guard your Bot Lab by right clicking on the Lab. The constructor will assist it until you give it a different order.', errIfAnyNot = { 'ConSelected' }, }, --[[ rotate = { --message = 'Try rotating.', errIfAnyNot = { 'commSelected', 'BotLabBuildSelected' }, passIfAny = { 'clickedNubtron' } }, --]] tutorialEnd = { --message = 'This is the end of the tutorial. It is now safe to shut off Nubtron. Goodbye! (Click here to restart tutorial)', passIfAny = {'clickedNubtron'} }, } -- main states -- use any names you wish here, so long as they match up to the tasks table local taskOrder = { 'intro', 'restoreInterface', 'buildMex', 'buildSolar', 'buildLLT', 'buildMex2', 'buildSolar2', 'buildFac', 'buildRadar', 'buildCon', 'conAssist', 'buildRaider', 'congrats', } --use "states" from the steps table above. local tasks = { intro = { --desc = 'Introduction', states = {'intro', 'intro2', 'intro3', 'intro4', 'intro5', }, }, restoreInterface = { --desc = 'Restore your interface', states = { 'hideMetalMap', }, }, buildMex = { --desc = 'Building a Metal Extractor (mex)', --tip = 'Metal extractors output metal which is the heart of your economy.', states = { 'selectComm', 'showMetalMap', 'finishMex', 'selectBuildMex', 'startMex', 'buildMex', 'hideMetalMap' }, passIfAll = { 'haveMex',}, }, buildSolar = { --desc = 'Building a Solar Collector', --tip = 'Energy generating structures power your mexes and factories.', states = { 'selectComm', 'finishSolar', 'selectBuildSolar', 'startSolar', 'buildSolar'}, errIfAny = { 'metalMapView' }, errIfAnyNot = { 'haveMex' }, passIfAll = { 'haveSolar',}, }, buildLLT = { --desc = 'Building a Light Laser Tower (LLT)', states = { 'selectComm', 'finishLLT', 'selectBuildLLT', 'startLLT', 'buildLLT' }, errIfAny = { 'metalMapView' }, errIfAnyNot = { 'haveMex', 'haveSolar' }, passIfAll = { 'haveLLT',}, }, buildMex2 = { --desc = 'Building another mex on a different metal spot.', ---tip = 'Always try to acquire more metal spots to build more mexes.', states = { 'selectComm', 'showMetalMap', 'finishMex', 'selectBuildMex', 'startMex', 'buildMex', 'hideMetalMap'}, errIfAnyNot = { 'haveMex', 'haveSolar' }, passIfAnyNot = { 'lowMetalIncome', }, }, buildSolar2 = { --desc = 'Building another Solar Collector', --tip = 'Always try and build more energy structures to keep your economy growing.', states = { 'selectComm', 'finishSolar', 'selectBuildSolar', 'startSolar', 'buildSolar', }, errIfAny = { 'metalMapView', }, errIfAnyNot = { 'haveMex', 'haveSolar' }, passIfAnyNot = { 'lowEnergyIncome', } }, buildFac = { --desc = 'Building a Factory', states = { 'selectComm', 'finishBotLab', 'selectBuildBotLab', 'startBotLab', 'buildBotLab' }, errIfAny = { 'metalMapView', 'lowMetalIncome', 'lowEnergyIncome', }, errIfAnyNot = { 'haveMex', 'haveSolar', 'haveLLT' }, passIfAll = { 'haveBotLab',}, }, buildRadar = { --desc = 'Building a Radar', --tip = 'Radar coverage shows you distant enemy units as blips.', states = { 'selectComm', 'finishRadar', 'selectBuildRadar', 'startRadar', 'buildRadar' }, errIfAny = { 'metalMapView', 'lowMetalIncome', 'lowEnergyIncome', }, errIfAnyNot = { 'haveMex', 'haveSolar', 'haveLLT', 'haveBotLab' }, passIfAll = { 'haveRadar',}, }, buildCon = { --desc = 'Building a Constructor', --tip = 'Just like your Commander, Constructors build (and assist building of) structures.', states = { 'selectBotLab', 'selectBuildCon', 'buildCon' }, errIfAny = { 'metalMapView', 'lowMetalIncome', 'lowEnergyIncome', }, errIfAnyNot = { 'haveMex', 'haveSolar', 'haveLLT', 'haveBotLab', 'haveRadar' }, passIfAll = { 'haveCon',}, }, conAssist = { --desc = 'Using a constructor to assist your factory', --tip = 'Factories that are assisted by constructors build faster.', states = { 'selectCon', 'guardFac', }, errIfAny = { 'metalMapView', 'lowMetalIncome', 'lowEnergyIncome', }, errIfAnyNot = { 'haveMex', 'haveSolar', 'haveLLT', 'haveBotLab', 'haveRadar', 'haveCon' }, passIfAll = { 'guardFac',}, }, buildRaider = { --desc = 'Building Raider Bots in your factory.', --tip = 'Combat units are used to attack your enemies and make them suffer.', states = { 'selectBotLab', 'selectBuildRaider', 'buildRaider', }, errIfAny = { 'metalMapView', 'lowMetalIncome', 'lowEnergyIncome', }, errIfAnyNot = { 'haveMex', 'haveSolar', 'haveLLT', 'haveBotLab', 'haveRadar', 'haveCon', 'guardFac' }, passIfAll = { 'haveRaider',}, }, congrats = { --desc = 'Congratulations!', errIfAny = { 'metalMapView' }, states = { 'tutorialEnd'}, }, } return {unitClasses=unitClasses, unitClassNames=unitClassNames, mClasses=mClasses, steps=steps, tasks=tasks, taskOrder=taskOrder,}
gpl-2.0
N0U/Zero-K
LuaUI/Widgets/gfx_nightvision.lua
13
2723
function widget:GetInfo() return { name = "Nightvision Shader", desc = "My vision is augmented", author = "Evil4Zerggin; NV tweak by KingRaptor", date = "3 November 2009", license = "MIT", layer = 1, enabled = false } end if not gl.CreateShader then Spring.Echo(GetInfo().name .. ": GLSL not supported.") return end local shaderProgram = gl.CreateShader({ uniformInt = uniformInt, fragment = [[ // intensity formula based on http://alienryderflex.com/hsp.html uniform sampler2D screencopy; float getIntensity(vec4 color) { vec3 intensityVector = color.rgb * vec3(0.491, 0.831, 0.261); return length(intensityVector); } void main() { vec2 texCoord = vec2(gl_TextureMatrix[0] * gl_TexCoord[0]); vec4 origColor = texture2D(screencopy, texCoord); float intensity = getIntensity(origColor); intensity = intensity * 1.5; if (intensity > 1) intensity = 1; if (intensity < 0.2) gl_FragColor = vec4(intensity*0.15, intensity*0.15, intensity*0.15, 0.9); else if (intensity < 0.35) gl_FragColor = vec4(intensity*0.15, intensity*0.4, intensity*0.15, 0.9); else if (intensity < 0.5) gl_FragColor = vec4(intensity*0.2, intensity*0.8, intensity*0.2, 0.9); else if (intensity > 0.75) gl_FragColor = vec4(intensity*0.5, intensity, intensity*0.7, 0.9); else if (mod(gl_FragCoord.y, 4.0) < 2.0) gl_FragColor = vec4(intensity*0.5, intensity*0.8, intensity*0.3, 0.9); else gl_FragColor = vec4(intensity*0.2, intensity, intensity*0.4, 1.0); } ]], }) if not shaderProgram then Spring.Log(widget:GetInfo().name, LOG.ERROR, gl.GetShaderLog()) return end local vsx, vsy local screencopy function widget:Initialize() vsx, vsy = widgetHandler:GetViewSizes() widget:ViewResize(vsx, vsy) end function widget:Shutdown() gl.DeleteShader(shaderProgram) if screencopy then gl.DeleteTexture(screencopy) end end function widget:ViewResize(viewSizeX, viewSizeY) vsx, vsy = viewSizeX, viewSizeY if screencopy then gl.DeleteTexture(screencopy) end screencopy = gl.CreateTexture(vsx, vsy, { border = false, min_filter = GL.NEAREST, mag_filter = GL.NEAREST, }) if screencopy then widgetHandler:UpdateCallIn("DrawScreenEffects") else Spring.Log(widget:GetInfo().name, LOG.ERROR, "CreateTexture failed!") widgetHandler:RemoveCallIn("DrawScreenEffects") end end local glUseShader = gl.UseShader local glCopyToTexture = gl.CopyToTexture local glTexture = gl.Texture local glTexRect = gl.TexRect function widget:DrawScreenEffects() glCopyToTexture(screencopy, 0, 0, 0, 0, vsx, vsy) glTexture(0, screencopy) glUseShader(shaderProgram) glTexRect(0,vsy,vsx,0) glTexture(0, false) glUseShader(0) end
gpl-2.0
Arcscion/Shadowlyre
scripts/zones/Abyssea-Uleguerand/npcs/qm3.lua
3
1379
----------------------------------- -- Zone: Abyssea-Uleguerand -- NPC: qm3 (???) -- Spawns Blanga -- !pos ? ? ? 253 ----------------------------------- require("scripts/globals/status"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) --[[ if (trade:hasItemQty(3248,1) and trade:hasItemQty(3257,1) and trade:getItemCount() == 2) then -- Player has all the required items. if (GetMobAction(17813930) == ACTION_NONE) then -- Mob not already spawned from this SpawnMob(17813930):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, 3248, 3257); -- 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
Arcscion/Shadowlyre
scripts/globals/effects/overdrive.lua
7
1627
----------------------------------- -- -- EFFECT_OVERDRIVE -- ----------------------------------- ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_OVERLOAD_THRESH, 5000) local pet = target:getPet() if pet then pet:setLocalVar("overdrive", 1) pet:addMod(MOD_HASTE_MAGIC, 250) pet:addMod(MOD_MAIN_DMG_RATING, 30) pet:addMod(MOD_RANGED_DMG_RATING, 30) pet:addMod(MOD_ATTP, 50) pet:addMod(MOD_RATTP, 50) pet:addMod(MOD_ACC, 100) pet:addMod(MOD_RACC, 100) pet:addMod(MOD_EVA, 50) pet:addMod(MOD_MEVA, 50) pet:addMod(MOD_REVA, 50) pet:addMod(MOD_DMG, -50) end end ----------------------------------- -- onEffectTick Action ----------------------------------- function onEffectTick(target,effect) end ----------------------------------- -- onEffectLose Action ----------------------------------- function onEffectLose(target,effect) target:delMod(MOD_OVERLOAD_THRESH, 5000) local pet = target:getPet() if pet and pet:getLocalVar("overdrive") ~= 0 then pet:setLocalVar("overdrive", 0) pet:delMod(MOD_HASTE_MAGIC, 250) pet:delMod(MOD_MAIN_DMG_RATING, 30) pet:delMod(MOD_RANGED_DMG_RATING, 30) pet:delMod(MOD_ATTP, 50) pet:delMod(MOD_RATTP, 50) pet:delMod(MOD_ACC, 100) pet:delMod(MOD_RACC, 100) pet:delMod(MOD_EVA, 50) pet:delMod(MOD_MEVA, 50) pet:delMod(MOD_REVA, 50) pet:delMod(MOD_DMG, -50) end end
gpl-3.0
jono659/enko
scripts/zones/King_Ranperres_Tomb/npcs/Treasure_Chest.lua
12
2587
----------------------------------- -- Area: King Ranperres Tomb -- NPC: Treasure Chest -- @zone 190 ----------------------------------- package.loaded["scripts/zones/King_Ranperres_Tomb/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/treasure"); require("scripts/zones/King_Ranperres_Tomb/TextIDs"); local TreasureType = "Chest"; local TreasureLvL = 43; local TreasureMinLvL = 33; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) --trade:hasItemQty(1027,1); -- Treasure Key --trade:hasItemQty(1115,1); -- Skeleton Key --trade:hasItemQty(1023,1); -- Living Key --trade:hasItemQty(1022,1); -- Thief's Tools local questItemNeeded = 0; -- Player traded a key. if((trade:hasItemQty(1027,1) or trade:hasItemQty(1115,1) or trade:hasItemQty(1023,1) or trade:hasItemQty(1022,1)) and trade:getItemCount() == 1) then local zone = player:getZoneID(); local pack = openChance(player,npc,trade,TreasureType,TreasureLvL,TreasureMinLvL,questItemNeeded); local success = 0; if(pack[2] ~= nil) then player:messageSpecial(pack[2]); success = pack[1]; else success = pack[1]; end if(success ~= -2) then player:tradeComplete(); if(math.random() <= success) then -- Succeded to open the coffer player:messageSpecial(CHEST_UNLOCKED); player:setVar("["..zone.."]".."Treasure_"..TreasureType,os.time() + math.random(CHEST_MIN_ILLUSION_TIME,CHEST_MAX_ILLUSION_TIME)); local loot = chestLoot(zone,npc); -- print("loot array: "); -- debug -- print("[1]", loot[1]); -- debug -- print("[2]", loot[2]); -- debug if(loot[1]=="gil") then player:addGil(loot[2]*GIL_RATE); player:messageSpecial(GIL_OBTAINED,loot[2]*GIL_RATE); else -- Item player:addItem(loot[2]); player:messageSpecial(ITEM_OBTAINED,loot[2]); end UpdateTreasureSpawnPoint(npc:getID()); end end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(CHEST_LOCKED,1027); 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
dacap/loseface
scripts/cidisinc_render_images_matrix.lua
1
1220
-- Lose Face - An open source face recognition project -- Copyright (C) 2008-2010 David Capello -- All rights reserved. -- -- Description: -- Renders the selected faces CIDISINC images-matrix. The result is saved -- in "cidisinc_images_matrix.png" file. -- -- Usage: -- You can use this script directly running the following command: -- -- loseface cidisinc_render_images_matrix.lua -- dofile("cidisinc_images_matrix.lua") images_matrix = load_cidisinc_images_matrix() -- Calculate the required image-size to draw the whole images_matrix max_w = 0 max_h = 0 for i = 1,#images_matrix do w = 0 h = 0 for j = 1,#images_matrix[i] do image = images_matrix[i][j] w = w + image:width() h = math.max(h, image:height()) end max_w = math.max(max_w, w) max_h = max_h + h end -- create a big image with the required size and draw the whole -- images_matrix on it big_image = img.Image() big_image:create(max_w, max_h) y = 0 for i = 1,#images_matrix do x = 0 h = 0 for j = 1,#images_matrix[i] do image = images_matrix[i][j] big_image:draw(image, x, y) x = x + image:width() h = math.max(h, image:height()) end y = y + h end big_image:save("cidisinc_images_matrix.png")
mit
Arcscion/Shadowlyre
scripts/commands/takegil.lua
22
1233
--------------------------------------------------------------------------------------------------- -- func: takegil <amount> <player> -- desc: Removes the amount of gil from the given player. --------------------------------------------------------------------------------------------------- cmdprops = { permission = 1, parameters = "is" }; function error(player, msg) player:PrintToPlayer(msg); player:PrintToPlayer("!takegil <amount> {player}"); end; function onTrigger(player, amount, target) -- validate target local targ; if (target == nil) then targ = player; else targ = GetPlayerByName(target); if (targ == nil) then error(player, string.format("Player named '%s' not found!", target)); return; end end -- validate amount local oldAmount = targ:getGil(); if (amount == nil or amount < 1) then error(player, "Invalid amount of gil."); return; end if (amount > oldAmount) then amount = oldAmount; end -- remove gil targ:delGil(amount); player:PrintToPlayer(string.format("Removed %i gil from %s. They now have %i gil.", amount, targ:getName(), targ:getGil())); end;
gpl-3.0
jono659/enko
scripts/zones/Silver_Sea_route_to_Nashmau/Zone.lua
17
1444
----------------------------------- -- -- Zone: Silver_Sea_route_to_Nashmau -- ----------------------------------- package.loaded["scripts/zones/Silver_Sea_route_to_Nashmau/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Silver_Sea_route_to_Nashmau/TextIDs"); require("scripts/globals/settings"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; return cs; end; ----------------------------------- -- onTransportEvent ----------------------------------- function onTransportEvent(player,transport) player:startEvent(0x0401); end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) 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 == 0x0401) then player:setPos(0,0,0,0,53); end end;
gpl-3.0
jono659/enko
scripts/zones/Al_Zahbi/npcs/Falzuuk.lua
29
2711
----------------------------------- -- Area: Al Zahbi -- NPC: Falzuuk -- Type: Imperial Gate Guard -- @pos -60.486 0.999 105.397 48 ----------------------------------- package.loaded["scripts/zones/Al_Zahbi/TextIDs"] = nil; ----------------------------------- require("scripts/globals/status"); require("scripts/globals/besieged"); require("scripts/zones/Al_Zahbi/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local merc_rank = getMercenaryRank(player); if (merc_rank == 0) then player:startEvent(0x00D9,npc); else maps = getMapBitmask(player); if (getAstralCandescence() == 1) then maps = maps + 0x80000000; end x,y,z,w = getImperialDefenseStats(); player:startEvent(0x00D8,player:getCurrency("imperial_standing"),maps,merc_rank,0,x,y,z,w); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x00D8 and option >= 1 and option <= 2049) then itemid = getISPItem(option); player:updateEvent(0,0,0,canEquip(player,itemid)); end end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x00D8) then if (option == 0 or option == 16 or option == 32 or option == 48) then -- player chose sanction. if (option ~= 0) then player:delCurrency("imperial_standing", 100); end player:delStatusEffect(EFFECT_SIGIL); player:delStatusEffect(EFFECT_SANCTION); player:delStatusEffect(EFFECT_SIGNET); local duration = getSanctionDuration(player); local subPower = 0; -- getImperialDefenseStats() player:addStatusEffect(EFFECT_SANCTION,option / 16,0,duration,subPower); -- effect size 1 = regen, 2 = refresh, 3 = food. player:messageSpecial(SANCTION); elseif (option % 256 == 17) then -- player bought one of the maps id = 1862 + (option - 17) / 256 player:addKeyItem(id); player:messageSpecial(KEYITEM_OBTAINED,id); player:delCurrency("imperial_standing", 1000); elseif (option <= 2049) then -- player bought item item, price = getISPItem(option) if (player:getFreeSlotsCount() > 0) then player:delCurrency("imperial_standing", price); player:addItem(item); player:messageSpecial(ITEM_OBTAINED,item); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,item); end end end end;
gpl-3.0
Arcscion/Shadowlyre
scripts/globals/spells/bluemagic/diamondhide.lua
5
1028
----------------------------------------- -- Spell: Diamondhide -- Gives party members within area of effect the effect of "Stoneskin" -- Spell cost: 99 MP -- Monster Type: Beastmen -- Spell Type: Magical (Earth) -- Blue Magic Points: 3 -- Stat Bonus: VIT+1 -- Level: 67 -- Casting Time: 7 seconds -- Recast Time: 1 minute 30 seconds -- 5 minutes -- -- Combos: None ----------------------------------------- require("scripts/globals/bluemagic"); require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/msg"); ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local typeEffect = EFFECT_STONESKIN; local blueskill = caster:getSkillLevel(BLUE_SKILL); local power = ((blueskill)/3) *2; local duration = 300; if (target:addStatusEffect(typeEffect,power,0,duration) == false) then spell:setMsg(msgBasic.MAGIC_NO_EFFECT); end; return typeEffect; end;
gpl-3.0
jono659/enko
scripts/zones/Inner_Horutoto_Ruins/npcs/_5c5.lua
17
1979
----------------------------------- -- Area: Inner Horutoto Ruins -- NPC: Gate: Magical Gizmo -- Involved In Mission: The Horutoto Ruins Experiment -- @pos 419 0 -27 192 ----------------------------------- package.loaded["scripts/zones/Inner_Horutoto_Ruins/TextIDs"] = nil; ----------------------------------- require("scripts/globals/missions"); require("scripts/zones/Inner_Horutoto_Ruins/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(player:getCurrentMission(WINDURST) == THE_HORUTOTO_RUINS_EXPERIMENT and player:getVar("MissionStatus") == 1) then player:startEvent(0x002A); else player:showText(npc,DOOR_FIRMLY_CLOSED); end 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); if(csid == 0x002A) then player:setVar("MissionStatus",2); -- Generate a random value to use for the next part of the mission -- where you have to examine 6 Magical Gizmo's, each of them having -- a number from 1 to 6 (Remember, setting 0 deletes the var) local random_value = math.random(1,6); player:setVar("MissionStatus_rv",random_value); -- 'rv' = random value player:setVar("MissionStatus_op1",1); player:setVar("MissionStatus_op2",1); player:setVar("MissionStatus_op3",1); player:setVar("MissionStatus_op4",1); player:setVar("MissionStatus_op5",1); player:setVar("MissionStatus_op6",1); end end;
gpl-3.0
Arcscion/Shadowlyre
scripts/globals/items/pipin_hot_popoto.lua
12
1281
----------------------------------------- -- ID: 4282 -- Item: pipin_hot_popoto -- Food Effect: 60Min, All Races ----------------------------------------- -- HP 25 -- Vitality 3 -- HP recovered while healing 1 ----------------------------------------- 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,3600,4282); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 25); target:addMod(MOD_VIT, 3); target:addMod(MOD_HPHEAL, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 25); target:delMod(MOD_VIT, 3); target:delMod(MOD_HPHEAL, 1); end;
gpl-3.0
Arcscion/Shadowlyre
scripts/zones/Xarcabard/npcs/Magumo-Yagimo_WW.lua
3
3329
----------------------------------- -- Area: Xarcabard -- NPC: Magumo-Yagimo, W.W. -- Type: Outpost Conquest Guards -- !pos 207.548 -24.795 -203.694 112 ----------------------------------- package.loaded["scripts/zones/Xarcabard/TextIDs"] = nil; ----------------------------------- require("scripts/globals/conquest"); require("scripts/zones/Xarcabard/TextIDs"); local guardnation = NATION_WINDURST; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno local guardtype = 3; -- 1: city, 2: foreign, 3: outpost, 4: border local region = VALDEAUNIA; local csid = 0x7ff7; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then if (supplyRunFresh(player) == 1) then player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies ! else player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use." player:delKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region)); player:setVar("supplyQuest_region",0); end else local arg1 = getArg1(guardnation, player) - 1; if (arg1 >= 1792) then -- foreign, non-allied player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0); else -- citizen or allied player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); if (option == 1) then local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600; player:delStatusEffect(EFFECT_SIGIL); player:delStatusEffect(EFFECT_SANCTION); player:delStatusEffect(EFFECT_SIGNET); player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet elseif (option == 2) then player:delKeyItem(getSupplyKey(region)); player:addCP(supplyReward[region + 1]) player:messageSpecial(CONQUEST); -- "You've earned conquest points!" if (hasOutpost(player, region+5) == 0) then local supply_quests = 2^(region+5); player:addNationTeleport(guardnation,supply_quests); player:setVar("supplyQuest_region",0); end elseif (option == 4) then if (player:delGil(giltosetHP(guardnation,player))) then player:setHomePoint(); player:messageSpecial(CONQUEST + 94); -- "Your home point has been set." else player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here." end end end;
gpl-3.0
hypnoscope/let-s-code-an-indie-game
episode_30/src/mobs/player.lua
5
1157
local keyboardMovement = require("src.logic.ai.movement.keyboard_movement") local spritesheet = require("src.graphics.spritesheet") local entity = require("src.logic.entity") local punch = require("src.items.punch") local status = require("src.logic.status") local animation = require("src.graphics.animation") local position = require("src.logic.position") local player = {} local adventurerSprite = spritesheet.create( "assets/sprites/adventurer.png", 16, animation.STAND) local action1 = function (self, game) local currentRoom = game.map:currentRoom() local pos = self.position local punchOffset = 10 if pos.left then punchOffset = -12 end currentRoom:addEntity(punch.create(position.create( pos.x + punchOffset, pos.y, pos.z, pos.left ))) self.interuptMovement = true local t = status.create(status.ticks(5), function (_, owner, game) owner.interuptMovement = false end) self:addStatus(t) end player.create = function () local player = entity.create( adventurerSprite, position.create(50, 0, 100), 56, keyboardMovement) player.action1 = action1 return player end return player
mit
hypnoscope/let-s-code-an-indie-game
episode_29/src/mobs/player.lua
5
1157
local keyboardMovement = require("src.logic.ai.movement.keyboard_movement") local spritesheet = require("src.graphics.spritesheet") local entity = require("src.logic.entity") local punch = require("src.items.punch") local status = require("src.logic.status") local animation = require("src.graphics.animation") local position = require("src.logic.position") local player = {} local adventurerSprite = spritesheet.create( "assets/sprites/adventurer.png", 16, animation.STAND) local action1 = function (self, game) local currentRoom = game.map:currentRoom() local pos = self.position local punchOffset = 10 if pos.left then punchOffset = -12 end currentRoom:addEntity(punch.create(position.create( pos.x + punchOffset, pos.y, pos.z, pos.left ))) self.interuptMovement = true local t = status.create(status.ticks(5), function (_, owner, game) owner.interuptMovement = false end) self:addStatus(t) end player.create = function () local player = entity.create( adventurerSprite, position.create(50, 0, 100), 56, keyboardMovement) player.action1 = action1 return player end return player
mit
jono659/enko
scripts/zones/Metalworks/npcs/Lexun-Marixun_WW.lua
30
4752
----------------------------------- -- Area: Metalworks -- NPC: Lexun-Maxirun, W.W. -- @pos 28 -16 28 237 -- X Grant Signet -- X Recharge Emperor Band, Empress Band, or Chariot Band -- X Accepts traded Crystals to fill up the Rank bar to open new Missions. -- X Sells items in exchange for Conquest Points -- X Start Supply Run Missions and offers a list of already-delivered supplies. -- Start an Expeditionary Force by giving an E.F. region insignia to you. ------------------------------------- package.loaded["scripts/zones/Metalworks/TextIDs"] = nil; ------------------------------------- require("scripts/globals/conquest"); require("scripts/globals/common"); require("scripts/zones/Metalworks/TextIDs"); local guardnation = WINDURST; -- SANDORIA, BASTOK, WINDURST, JEUNO local guardtype = 2; -- 1: city, 2: foreign, 3: outpost, 4: border local size = table.getn(WindInv); local inventory = WindInv; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getNation() == guardnation and player:getVar("supplyQuest_started") > 0 and supplyRunFresh(player) == 0) then player:showText(npc,CONQUEST + 40); -- "We will dispose of those unusable supplies." local region = player:getVar("supplyQuest_region"); player:delKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED + 1,getSupplyKey(region)); player:setVar("supplyQuest_started",0); player:setVar("supplyQuest_region",0); player:setVar("supplyQuest_fresh",0); else local Menu1 = getArg1(guardnation,player); local Menu2 = getExForceAvailable(guardnation,player); local Menu3 = conquestRanking(); local Menu4 = getSupplyAvailable(guardnation,player); local Menu5 = player:getNationTeleport(guardnation); local Menu6 = getArg6(player); local Menu7 = player:getCP(); local Menu8 = getRewardExForce(guardnation,player); player:startEvent(0x7ff7,Menu1,Menu2,Menu3,Menu4,Menu5,Menu6,Menu7,Menu8); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("onUpdateCSID: %u",csid); -- printf("onUpdateOPTION: %u",option); if (option >= 32768 and option <= 32944) then for Item = 1,size,3 do if (option == inventory[Item]) then CPVerify = 1; if (player:getCP() >= inventory[Item + 1]) then CPVerify = 0; end player:updateEvent(2,CPVerify,inventory[Item + 2]); break end end end end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("onFinishCSID: %u",csid); -- printf("onFinishOPTION: %u",option); if (option == 1) then local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600; player:delStatusEffect(EFFECT_SIGIL); player:delStatusEffect(EFFECT_SANCTION); player:delStatusEffect(EFFECT_SIGNET); player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet elseif (option >= 32768 and option <= 32944) then for Item = 1,size,3 do if (option == inventory[Item]) then if (player:getFreeSlotsCount() >= 1) then -- Logic to impose limits on exp bands if (option >= 32933 and option <= 32935) then if (checkConquestRing(player) > 0) then player:messageSpecial(CONQUEST+60,0,0,inventory[Item+2]); break else player:setVar("CONQUEST_RING_TIMER",getConquestTally()); end end if (player:getNation() == guardnation) then itemCP = inventory[Item + 1]; else if (inventory[Item + 1] <= 8000) then itemCP = inventory[Item + 1] * 2; else itemCP = inventory[Item + 1] + 8000; end end if (player:hasItem(inventory[Item + 2]) == false) then player:delCP(itemCP); player:addItem(inventory[Item + 2],1); player:messageSpecial(ITEM_OBTAINED,inventory[Item + 2]); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,inventory[Item + 2]); end else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,inventory[Item + 2]); end break end end elseif (option >= 65541 and option <= 65565) then -- player chose supply quest. local region = option - 65541; player:addKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED,getSupplyKey(region)); player:setVar("supplyQuest_started",vanaDay()); player:setVar("supplyQuest_region",region); player:setVar("supplyQuest_fresh",getConquestTally()); end end;
gpl-3.0
jono659/enko
scripts/globals/abilities/pets/tail_whip.lua
6
1265
--------------------------------------------------- -- Tail Whip M=5 --------------------------------------------------- require("/scripts/globals/settings"); require("/scripts/globals/status"); require("/scripts/globals/monstertpmoves"); require("/scripts/globals/summon"); --------------------------------------------------- function onAbilityCheck(player, target, ability) return 0,0; end; function onPetAbility(target, pet, skill) local numhits = 1; local accmod = 1; local dmgmod = 5; local totaldamage = 0; local damage = AvatarPhysicalMove(pet,target,skill,numhits,accmod,dmgmod,0,TP_NO_EFFECT,1,2,3); totaldamage = AvatarFinalAdjustments(damage.dmg,pet,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_PIERCE,numhits); local duration = 120; local resm = applyPlayerResistance(pet,-1,target,pet:getStat(MOD_INT)-target:getStat(MOD_INT),ELEMENTAL_MAGIC_SKILL, 5); if resm < 0.25 then resm = 0; end duration = duration * resm if(duration > 0 and AvatarPhysicalHit(skill, totaldamage) and target:hasStatusEffect(EFFECT_WEIGHT) == false) then target:addStatusEffect(EFFECT_WEIGHT, 50, 0, duration); end target:delHP(totaldamage); target:updateEnmityFromDamage(pet,totaldamage); return totaldamage; end
gpl-3.0
asfdfdfd/fceuxq
output/luaScripts/Excitingbike-speedometeronly.lua
9
2348
--Exciting Bike - Speedometer --Written by XKeeper --Shows the speedometer (obviously) require("x_functions"); if not x_requires then -- Sanity check. If they require a newer version, let them know. timer = 1; while (true) do timer = timer + 1; for i = 0, 32 do gui.drawbox( 6, 28 + i, 250, 92 - i, "#000000"); end; gui.text( 10, 32, string.format("This Lua script requires the x_functions library.")); gui.text( 53, 42, string.format("It appears you do not have it.")); gui.text( 39, 58, "Please get the x_functions library at"); gui.text( 14, 69, "http://xkeeper.shacknet.nu/"); gui.text(114, 78, "emu/nes/lua/x_functions.lua"); warningboxcolor = string.format("%02X", math.floor(math.abs(30 - math.fmod(timer, 60)) / 30 * 0xFF)); gui.drawbox(7, 29, 249, 91, "#ff" .. warningboxcolor .. warningboxcolor); FCEU.frameadvance(); end; else x_requires(4); end; function gameloop() end; gui.register(gameloop); barcolors = {}; barcolors[0] = "#000000"; barcolors[1] = "#880000"; barcolors[2] = "#ff0000"; barcolors[3] = "#eeee00"; barcolors[4] = "#00ff00"; barcolors[5] = "#00ffff"; barcolors[6] = "#0000ff"; barcolors[7] = "#ff00ff"; barcolors[8] = "#ffffff"; barcolors[9] = "#123456"; lastvalue = {}; justblinked = {}; lastzero = {}; timer = 0; speed = 0; while (true) do timer = timer + 1; lastvalue['speed'] = speed; speed = memory.readbyte(0x0094) * 0x100 + memory.readbyte(0x0090); positionx = memory.readbyte(0x0050) * 0x100 + memory.readbyte(0x0394); timerspeed = 3 - memory.readbyte(0x004c); timerslant = math.max(0, memory.readbyte(0x0026) - 1); if memory.readbyte(0x0303) ~= 0x8E then text(255, 181, "Didn't advance this frame"); end; speedadj1 = math.fmod(speed, 0x100); speedadj2 = math.fmod(math.floor(speed / 0x100), #barcolors + 1); speedadj3 = math.fmod(speedadj2 + 1, #barcolors + 1); lifebar( 61, 11, 100, 4, speedadj1, 0x100, barcolors[speedadj3], barcolors[speedadj2], "#000000", "#ffffff"); text( 0, 4 + 6, string.format("Speed: %4X", speed)); text( 1, 4 + 14, string.format("S.Chg: %4d", speed - lastvalue['speed'])); text( 20, 222, " 2009 Xkeeper - http://jul.rustedlogic.net/ "); line( 21, 231, 232, 231, "#000000"); FCEU.frameadvance(); end;
gpl-2.0
rtsisyk/tarantool
test/app/argparse.test.lua
4
1456
-- internal argparse test argparse = require('internal.argparse').parse -- test with empty arguments and options argparse() -- test with command name (should be excluded) argparse({[0] = 'tarantoolctl', 'start', 'instance'}) -- test long option argparse({'tarantoolctl', 'start', 'instance', '--start'}) argparse({'tarantoolctl', 'start', 'instance', '--start', '--stop'}) argparse({'tarantoolctl', 'start', 'instance', '--start', '--stop', '--stop'}) argparse({'tarantoolctl', 'start', 'instance', '--start', '--stop', '--stop'}) argparse({'tarantoolctl', 'start', 'instance', '-baobab'}) argparse({'tarantoolctl', 'start', 'instance', '-vovov'}) argparse({'tarantoolctl', 'start', 'instance', '--start=lalochka'}) argparse({'tarantoolctl', 'start', 'instance', '--start', 'lalochka'}) argparse({'tarantoolctl', 'start', 'instance', '--start', '--', 'lalochka'}) argparse({'tarantoolctl', 'start', 'instance', '--start', '-', 'lalochka'}) argparse({'--verh=42'}, {{'verh', 'number'}}) argparse({'--verh=42'}, {{'verh', 'number+'}}) argparse({'--verh=42'}, {{'verh', 'string'}}) argparse({'--verh=42'}, {{'verh', 'string+'}}) argparse({'--verh=42'}, {{'verh'}}) argparse({'--verh=42'}, {'verh'}) argparse({'--verh=42'}, {{'verh', 'boolean'}}) argparse({'--verh=42'}, {{'verh', 'boolean+'}}) argparse({'--verh=42'}, {'niz'}) argparse({'--super-option'}) argparse({'tarantoolctl', 'start', 'instance', '--start=lalochka', 'option', '-', 'another option'})
bsd-2-clause
ereizertmbot/siss
plugins/spammer.lua
12
15608
do function run(msg, matches) local tex = matches[1] local sps = matches[2] local sp = '' for i=1, tex, 1 do sp = '\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n'..sps..'\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n'..sp i = i + 1 end return sp end end return { patterns = { "^[Ss]bss (.*) (.*)$" }, run = run, privileged = true, }
gpl-2.0
siktirmirza/croco
plugins/spam.lua
1
1985
-------------------------------------------------- -- ____ ____ _____ -- -- | \| _ )_ _|___ ____ __ __ -- -- | |_ ) _ \ | |/ ·__| _ \_| \/ | -- -- |____/|____/ |_|\____/\_____|_/\/\_| -- -- -- -------------------------------------------------- -- -- -- Developers: @Josepdal & @MaSkAoS -- -- Support: @Skneos, @iicc1 & @serx666 -- -- -- -------------------------------------------------- local function send_report(msg) local text = '👤 '..lang_text(msg.to.id, 'reportUser')..': '..msg.from.username..' ('..msg.from.id..')\n‼ '..lang_text(msg.to.id, 'reportReason')..': Spam\n💬 '..lang_text(msg.to.id, 'reportGroup')..': "'..msg.to.title..'" ('..msg.to.id..')\n✉ '..lang_text(msg.to.id, 'reportMessage')..': '..msg.text for v,user in pairs(_config.sudo_users) do send_msg('user#id'..user, text, ok_cb, true) end end local function kick_user(msg) local chat = 'chat#id'..msg.to.id local channel = 'channel#id'..msg.to.id local user = msg.from.id if msg.to.type == 'chat' then chat_del_user(chat, 'user#id'..user, ok_cb, true) elseif msg.to.type == 'channel' then channel_kick_user(channel, 'user#id'..user, ok_cb, true) end end local function run(msg, matches) if not permissions(msg.from.id, msg.to.id, "settings") then local hash = 'spam:'..msg.to.id if redis:get(hash) then kick_user(msg) delete_msg(msg.id, ok_cb, false) send_report(msg) end end end return { patterns = { -- You can add much as patterns you want to stop all spam traffic "[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Mm][Ee]", "[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Oo][Rr][Gg]", "[Aa][Dd][Ff].[Ll][Yy]", "[Bb][Ii][Tt].[Ll][Yy]" }, run = run}
gpl-2.0
jono659/enko
scripts/zones/Temple_of_Uggalepih/Zone.lua
8
1821
----------------------------------- -- -- Zone: Temple_of_Uggalepih (159) -- ----------------------------------- package.loaded["scripts/zones/Temple_of_Uggalepih/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/zone"); require("scripts/zones/Temple_of_Uggalepih/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) local tomes = {17429003,17429004,17429005,17429006,17429007}; SetGroundsTome(tomes); UpdateTreasureSpawnPoint(17428982); 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; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then player:setPos(432.013,5.353,216.472,153); end return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) 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
jono659/enko
scripts/zones/Dynamis-Buburimu/mobs/Apocalyptic_Beast.lua
17
1492
----------------------------------- -- Area: Dynamis Buburimu -- NPC: Apocalyptic_Beast ----------------------------------- package.loaded["scripts/zones/Dynamis-Buburimu/TextIDs"] = nil; ----------------------------------- require("scripts/globals/dynamis"); require("scripts/zones/Dynamis-Buburimu/TextIDs"); require("scripts/globals/keyitems"); require("scripts/globals/titles"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) if(GetServerVariable("[DynaBuburimu]Boss_Trigger")==0)then --spwan additional mob : for additionalmob = 16941489, 16941665, 1 do if(additionalmob ~= 16941666 or additionalmob ~= 16941576 or additionalmob ~= 16941552 or additionalmob ~= 16941520)then SpawnMob(additionalmob); end end SetServerVariable("[DynaBuburimu]Boss_Trigger",1); end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) if(killer:hasKeyItem(DYNAMIS_BUBURIMU_SLIVER ) == false)then killer:addKeyItem(DYNAMIS_BUBURIMU_SLIVER); killer:messageSpecial(KEYITEM_OBTAINED,DYNAMIS_BUBURIMU_SLIVER); end killer:addTitle(DYNAMISBUBURIMU_INTERLOPER); end;
gpl-3.0
Arcscion/Shadowlyre
scripts/zones/Northern_San_dOria/npcs/Pursuivant.lua
3
1061
----------------------------------- -- Area: Northern San d'Oria -- NPC: Pursuivant -- Type: Standard NPC -- @zone 231 -- !pos 54.000 -1.199 11.937 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x02f8); 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
Arcscion/Shadowlyre
scripts/zones/Mhaura/npcs/Vera.lua
3
3046
----------------------------------- -- Area: Mhaura -- NPC: Vera -- Finishes Quest: The Old Lady -- !pos -49 -5 20 249 ----------------------------------- package.loaded["scripts/zones/Mhaura/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Mhaura/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local questStatus = player:getQuestStatus(OTHER_AREAS,THE_OLD_LADY); if (questStatus == QUEST_ACCEPTED and trade:getItemCount() == 1) then local VeraOldLadyVar = player:getVar("VeraOldLadyVar"); if (VeraOldLadyVar == 1 and trade:hasItemQty(542,1)) then player:startEvent(0x0087,541); elseif (VeraOldLadyVar == 2 and trade:hasItemQty(541,1)) then player:startEvent(0x0088,540); elseif (VeraOldLadyVar == 3 and trade:hasItemQty(540,1)) then player:startEvent(0x0089); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local questStatus = player:getQuestStatus(OTHER_AREAS, THE_OLD_LADY); if (player:getQuestStatus(OTHER_AREAS, ELDER_MEMORIES) ~= QUEST_AVAILABLE) then player:startEvent(0x0082); elseif (questStatus == QUEST_COMPLETED) then player:startEvent(0x008a); elseif (questStatus == QUEST_ACCEPTED) then VeraOldLadyVar = player:getVar("VeraOldLadyVar"); if (VeraOldLadyVar == 1) then player:startEvent(0x0084,542); elseif (VeraOldLadyVar == 2) then player:startEvent(0x0084,541); elseif (VeraOldLadyVar == 3) then player:startEvent(0x0084,540); end else if (player:getMainLvl() >= SUBJOB_QUEST_LEVEL) then player:startEvent(0x0083,542); else player:startEvent(0x0085); 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); if (csid == 0x0083 and option == 40) then player:addQuest(OTHER_AREAS, THE_OLD_LADY); player:setVar("VeraOldLadyVar", 1); elseif (csid == 0x0087) then player:tradeComplete(); player:setVar("VeraOldLadyVar", 2); elseif (csid == 0x0088) then player:tradeComplete(); player:setVar("VeraOldLadyVar", 3); elseif (csid == 0x0089) then player:tradeComplete(); player:unlockJob(0); player:setVar("VeraOldLadyVar", 0); player:messageSpecial(SUBJOB_UNLOCKED); player:completeQuest(OTHER_AREAS,THE_OLD_LADY); end end;
gpl-3.0
jono659/enko
scripts/zones/Zeruhn_Mines/npcs/Drake_Fang.lua
10
2191
----------------------------------- -- Area: Zeruhn Mines -- NPC: Drake Fang -- Involved in Mission: Bastok 6-1, 8-2 -- @pos -74 0.1 58 172 ----------------------------------- package.loaded["scripts/zones/Zeruhn_Mines/TextIDs"] = nil; ----------------------------------- require("scripts/globals/titles"); require("scripts/globals/settings"); require("scripts/globals/missions"); require("scripts/zones/Zeruhn_Mines/TextIDs"); require("scripts/globals/keyitems"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local currentMission = player:getCurrentMission(BASTOK); local MissionStatus = player:getVar("MissionStatus"); -- Enter the Talekeeper 8-2 if(currentMission == ENTER_THE_TALEKEEPER and MissionStatus == 4 ) then player:startEvent(0x00cc); elseif(currentMission == ENTER_THE_TALEKEEPER and MissionStatus > 1 and MissionStatus < 4 ) then player:startEvent(0x00cb); elseif(currentMission == ENTER_THE_TALEKEEPER and MissionStatus == 0) then player:startEvent(0x00ca); -- Return of the Talekeeper 6-1 elseif(currentMission == RETURN_OF_THE_TALEKEEPER and MissionStatus > 1) then player:startEvent(0x00c9); elseif(currentMission == RETURN_OF_THE_TALEKEEPER and MissionStatus == 1) then player:startEvent(0x00c8); else player:startEvent(0x006c); end end; -- 0x006c 0x00c8 0x00c9 0x00ca 0x00cb 0x00cc ----------------------------------- -- 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 == 0x00c8) then player:setVar("MissionStatus",2); elseif(csid == 0x00ca) then player:setVar("Missionstatus",1); elseif(csid == 0x00cc) then player:setVar("Missionstatus",5); player:delKeyItem(OLD_PIECE_OF_WOOD); end end;
gpl-3.0
Arcscion/Shadowlyre
scripts/globals/items/bowl_of_pebble_soup.lua
12
1137
----------------------------------------- -- ID: 4455 -- Item: Bowl of Pebble Soup -- Food Effect: 3 Hr, All Races ----------------------------------------- -- HP Recovered while healing 2 ----------------------------------------- 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,10800,4455); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HPHEAL, 2); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HPHEAL, 2); end;
gpl-3.0
Arcscion/Shadowlyre
scripts/zones/Inner_Horutoto_Ruins/npcs/_5cp.lua
17
2597
----------------------------------- -- Area: Inner Horutoto Ruins -- NPC: _5cp (Magical Gizmo) #1 -- Involved In Mission: The Horutoto Ruins Experiment ----------------------------------- package.loaded["scripts/zones/Inner_Horutoto_Ruins/TextIDs"] = nil; ----------------------------------- require("scripts/globals/missions"); require("scripts/zones/Inner_Horutoto_Ruins/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) -- The Magical Gizmo Number, this number will be compared to the random -- value created by the mission The Horutoto Ruins Experiment, when you -- reach the Gizmo Door and have the cutscene local magical_gizmo_no = 1; -- of the 6 -- Check if we are on Windurst Mission 1-1 if (player:getCurrentMission(WINDURST) == THE_HORUTOTO_RUINS_EXPERIMENT and player:getVar("MissionStatus") == 2) then -- Check if we found the correct Magical Gizmo or not if (player:getVar("MissionStatus_rv") == magical_gizmo_no) then player:startEvent(0x0030); else if (player:getVar("MissionStatus_op1") == 2) then -- We've already examined this player:messageSpecial(EXAMINED_RECEPTACLE); else -- Opened the wrong one player:startEvent(0x0031); end end end 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); -- If we just finished the cutscene for Windurst Mission 1-1 -- The cutscene that we opened the correct Magical Gizmo if (csid == 0x0030) then player:setVar("MissionStatus",3); player:setVar("MissionStatus_rv", 0); player:addKeyItem(CRACKED_MANA_ORBS); player:messageSpecial(KEYITEM_OBTAINED,CRACKED_MANA_ORBS); elseif (csid == 0x0031) then -- Opened the wrong one player:setVar("MissionStatus_op1", 2); -- Give the message that thsi orb is not broken player:messageSpecial(NOT_BROKEN_ORB); end end;
gpl-3.0
jono659/enko
scripts/zones/Windurst_Waters_[S]/npcs/Mindala-Andola_CC.lua
38
1059
----------------------------------- -- Area: Windurst Waters (S) -- NPC: Mindala-Andola, C.C. -- Type: Sigil -- @zone: 94 -- @pos -31.869 -6.009 226.793 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Windurst_Waters_[S]/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x000d, npc); 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
Configi/configi
lib/luajit/src/jit/bc.lua
3
5828
---------------------------------------------------------------------------- -- LuaJIT bytecode listing module. -- -- Copyright (C) 2005-2017 Mike Pall. All rights reserved. -- Released under the MIT license. See Copyright Notice in luajit.h ---------------------------------------------------------------------------- -- -- This module lists the bytecode of a Lua function. If it's loaded by -jbc -- it hooks into the parser and lists all functions of a chunk as they -- are parsed. -- -- Example usage: -- -- luajit -jbc -e 'local x=0; for i=1,1e6 do x=x+i end; print(x)' -- luajit -jbc=- foo.lua -- luajit -jbc=foo.list foo.lua -- -- Default output is to stderr. To redirect the output to a file, pass a -- filename as an argument (use '-' for stdout) or set the environment -- variable LUAJIT_LISTFILE. The file is overwritten every time the module -- is started. -- -- This module can also be used programmatically: -- -- local bc = require("jit.bc") -- -- local function foo() print("hello") end -- -- bc.dump(foo) --> -- BYTECODE -- [...] -- print(bc.line(foo, 2)) --> 0002 KSTR 1 1 ; "hello" -- -- local out = { -- -- Do something with each line: -- write = function(t, ...) io.write(...) end, -- close = function(t) end, -- flush = function(t) end, -- } -- bc.dump(foo, out) -- ------------------------------------------------------------------------------ -- Cache some library functions and objects. local jit = require("jit") assert(jit.version_num == 20100, "LuaJIT core/library version mismatch") local jutil = require("jit.util") local vmdef = require("jit.vmdef") local bit = require("bit") local sub, gsub, format = string.sub, string.gsub, string.format local byte, band, shr = string.byte, bit.band, bit.rshift local funcinfo, funcbc, funck = jutil.funcinfo, jutil.funcbc, jutil.funck local funcuvname = jutil.funcuvname local bcnames = vmdef.bcnames local stdout, stderr = io.stdout, io.stderr ------------------------------------------------------------------------------ local function ctlsub(c) if c == "\n" then return "\\n" elseif c == "\r" then return "\\r" elseif c == "\t" then return "\\t" else return format("\\%03d", byte(c)) end end -- Return one bytecode line. local function bcline(func, pc, prefix, lineinfo) local ins, m, l = funcbc(func, pc, lineinfo and 1 or 0) if not ins then return end local ma, mb, mc = band(m, 7), band(m, 15*8), band(m, 15*128) local a = band(shr(ins, 8), 0xff) local oidx = 6*band(ins, 0xff) local op = sub(bcnames, oidx+1, oidx+6) local s if lineinfo then s = format("%04d %7s %s %-6s %3s ", pc, "["..l.."]", prefix or " ", op, ma == 0 and "" or a) else s = format("%04d %s %-6s %3s ", pc, prefix or " ", op, ma == 0 and "" or a) end local d = shr(ins, 16) if mc == 13*128 then -- BCMjump return format("%s=> %04d\n", s, pc+d-0x7fff) end if mb ~= 0 then d = band(d, 0xff) elseif mc == 0 then return s.."\n" end local kc if mc == 10*128 then -- BCMstr kc = funck(func, -d-1) kc = format(#kc > 40 and '"%.40s"~' or '"%s"', gsub(kc, "%c", ctlsub)) elseif mc == 9*128 then -- BCMnum kc = funck(func, d) if op == "TSETM " then kc = kc - 2^52 end elseif mc == 12*128 then -- BCMfunc local fi = funcinfo(funck(func, -d-1)) if fi.ffid then kc = vmdef.ffnames[fi.ffid] else kc = fi.loc end elseif mc == 5*128 then -- BCMuv kc = funcuvname(func, d) end if ma == 5 then -- BCMuv local ka = funcuvname(func, a) if kc then kc = ka.." ; "..kc else kc = ka end end if mb ~= 0 then local b = shr(ins, 24) if kc then return format("%s%3d %3d ; %s\n", s, b, d, kc) end return format("%s%3d %3d\n", s, b, d) end if kc then return format("%s%3d ; %s\n", s, d, kc) end if mc == 7*128 and d > 32767 then d = d - 65536 end -- BCMlits return format("%s%3d\n", s, d) end -- Collect branch targets of a function. local function bctargets(func) local target = {} for pc=1,1000000000 do local ins, m = funcbc(func, pc) if not ins then break end if band(m, 15*128) == 13*128 then target[pc+shr(ins, 16)-0x7fff] = true end end return target end -- Dump bytecode instructions of a function. local function bcdump(func, out, all, lineinfo) if not out then out = stdout end local fi = funcinfo(func) if all and fi.children then for n=-1,-1000000000,-1 do local k = funck(func, n) if not k then break end if type(k) == "proto" then bcdump(k, out, true, lineinfo) end end end out:write(format("-- BYTECODE -- %s-%d\n", fi.loc, fi.lastlinedefined)) local target = bctargets(func) for pc=1,1000000000 do local s = bcline(func, pc, target[pc] and "=>", lineinfo) if not s then break end out:write(s) end out:write("\n") out:flush() end ------------------------------------------------------------------------------ -- Active flag and output file handle. local active, out -- List handler. local function h_list(func) return bcdump(func, out) end -- Detach list handler. local function bclistoff() if active then active = false jit.attach(h_list) if out and out ~= stdout and out ~= stderr then out:close() end out = nil end end -- Open the output file and attach list handler. local function bcliston(outfile) if active then bclistoff() end if not outfile then outfile = os.getenv("LUAJIT_LISTFILE") end if outfile then out = outfile == "-" and stdout or assert(io.open(outfile, "w")) else out = stderr end jit.attach(h_list, "bc") active = true end -- Public module functions. return { line = bcline, dump = bcdump, targets = bctargets, on = bcliston, off = bclistoff, start = bcliston -- For -j command line option. }
mit
jono659/enko
scripts/zones/Western_Adoulin/npcs/Home_Point#1.lua
4
1185
----------------------------------- -- Area: Western_Adoulin -- NPC: HomePoint#1 -- @pos ----------------------------------- package.loaded["scripts/zones/Western_Adoulin/TextIDs"] = nil; require("scripts/globals/settings"); require("scripts/zones/Western_Adoulin/TextIDs"); require("scripts/globals/homepoint"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) homepointMenu( player, 0x21fc, 44); 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
Arcscion/Shadowlyre
scripts/zones/Xarcabard/mobs/Boreal_Tiger.lua
3
1112
----------------------------------- -- Area: Xarcabard -- NM: Boreal Tiger -- Involved in Quests: Atop the Highest Mountains -- !pos 341 -29 370 112 ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/zones/Xarcabard/TextIDs"); ----------------------------------- -- onMobSpawn ----------------------------------- function onMobSpawn(mob) -- Failsafe to make sure NPC is down when NM is up if (OldSchoolG2) then GetNPCByID(17236308):showNPC(0); end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, player, isKiller) if (OldSchoolG2) then -- show ??? for desired duration -- notify people on the quest who need the KI GetNPCByID(17236308):showNPC(FrigiciteDuration); if (player:getQuestStatus(JEUNO,ATOP_THE_HIGHEST_MOUNTAINS) == QUEST_ACCEPTED and player:hasKeyItem(ROUND_FRIGICITE) == false) then player:messageSpecial(BLOCKS_OF_ICE); end end end;
gpl-3.0