repo_name
stringlengths
6
69
path
stringlengths
6
178
copies
stringclasses
278 values
size
stringlengths
4
7
content
stringlengths
671
917k
license
stringclasses
15 values
SalvationDevelopment/Salvation-Scripts-TCG
c85718645.lua
5
1761
--闇帝ディルグ function c85718645.initial_effect(c) --remove local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(85718645,0)) e1:SetCategory(CATEGORY_REMOVE+CATEGORY_DECKDES) e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetCode(EVENT_SUMMON_SUCCESS) e1:SetTarget(c85718645.target) e1:SetOperation(c85718645.operation) c:RegisterEffect(e1) local e2=e1:Clone() e2:SetCode(EVENT_SPSUMMON_SUCCESS) c:RegisterEffect(e2) --cannot attack local e3=Effect.CreateEffect(c) e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS) e3:SetCode(EVENT_SUMMON_SUCCESS) e3:SetOperation(c85718645.disatt) c:RegisterEffect(e3) local e4=e3:Clone() e4:SetCode(EVENT_SPSUMMON_SUCCESS) c:RegisterEffect(e4) end function c85718645.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(1-tp) and chkc:IsAbleToRemove() end if chk==0 then return Duel.IsExistingTarget(Card.IsAbleToRemove,tp,0,LOCATION_GRAVE,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE) local g=Duel.SelectTarget(tp,Card.IsAbleToRemove,tp,0,LOCATION_GRAVE,1,2,nil) Duel.SetOperationInfo(0,CATEGORY_REMOVE,g,g:GetCount(),0,0) end function c85718645.operation(e,tp,eg,ep,ev,re,r,rp) local tg=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS) local sg=tg:Filter(Card.IsRelateToEffect,nil,e) local count=Duel.Remove(sg,POS_FACEUP,REASON_EFFECT) if count>0 then Duel.DiscardDeck(1-tp,count,REASON_EFFECT) end end function c85718645.disatt(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_CANNOT_ATTACK) e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END) c:RegisterEffect(e1) end
gpl-2.0
Riverlance/kingdom-age-game-windows
modules/game_viplist/viplist.lua
1
12322
_G.GameVipList = { } vipWindow = nil vipTopMenuButton = nil addVipWindow = nil editVipWindow = nil contentsPanel = nil vipInfo = {} function GameVipList.init() -- Alias GameVipList.m = modules.game_viplist connect(g_game, { onGameStart = GameVipList.online, onGameEnd = GameVipList.offline, onAddVip = GameVipList.onAddVip, onVipStateChange = GameVipList.onVipStateChange }) g_keyboard.bindKeyDown('Ctrl+F', GameVipList.toggle) vipWindow = g_ui.loadUI('viplist') vipTopMenuButton = ClientTopMenu.addRightGameToggleButton('vipTopMenuButton', tr('VIP List') .. ' (Ctrl+F)', '/images/ui/top_menu/viplist', GameVipList.toggle) contentsPanel = vipWindow:getChildById('contentsPanel') vipWindow.topMenuButton = vipTopMenuButton contentsPanel.onMousePress = GameVipList.onVipListMousePress if not g_game.getFeature(GameAdditionalVipInfo) then GameVipList.loadVipInfo() end GameInterface.setupMiniWindow(vipWindow, vipTopMenuButton) if g_game.isOnline() then GameVipList.online() end end function GameVipList.terminate() g_keyboard.unbindKeyDown('Ctrl+F') disconnect(g_game, { onGameStart = GameVipList.online, onGameEnd = GameVipList.offline, onAddVip = GameVipList.onAddVip, onVipStateChange = GameVipList.onVipStateChange }) if not g_game.getFeature(GameAdditionalVipInfo) then GameVipList.saveVipInfo() end if addVipWindow then addVipWindow:destroy() end if editVipWindow then editVipWindow:destroy() end vipWindow:destroy() vipTopMenuButton:destroy() _G.GameVipList = nil end function GameVipList.loadVipInfo() local settings = g_settings.getNode('VipList') if not settings then vipInfo = {} return end vipInfo = settings['VipInfo'] or {} end function GameVipList.saveVipInfo() settings = {} settings['VipInfo'] = vipInfo g_settings.mergeNode('VipList', settings) end function GameVipList.clear() contentsPanel:destroyChildren() end function GameVipList.online() GameInterface.setupMiniWindow(vipWindow, vipTopMenuButton) GameVipList.clear() for id,vip in pairs(g_game.getVips()) do GameVipList.onAddVip(id, unpack(vip)) end end function GameVipList.offline() GameVipList.clear() end function GameVipList.toggle() GameInterface.toggleMiniWindow(vipWindow) end function GameVipList.createAddWindow() if not addVipWindow then addVipWindow = g_ui.displayUI('addvip') end end function GameVipList.createEditWindow(widget) if editVipWindow then return end editVipWindow = g_ui.displayUI('editvip') local name = widget:getText() local id = widget:getId():sub(4) local okButton = editVipWindow:getChildById('buttonOK') local cancelButton = editVipWindow:getChildById('buttonCancel') local nameLabel = editVipWindow:getChildById('nameLabel') nameLabel:setText(name) local descriptionText = editVipWindow:getChildById('descriptionText') descriptionText:appendText(widget:getTooltip()) local notifyCheckBox = editVipWindow:getChildById('checkBoxNotify') notifyCheckBox:setChecked(widget.notifyLogin) local iconRadioGroup = UIRadioGroup.create() for i = VipIconFirst, VipIconLast do iconRadioGroup:addWidget(editVipWindow:recursiveGetChildById('icon' .. i)) end iconRadioGroup:selectWidget(editVipWindow:recursiveGetChildById('icon' .. widget.iconId)) local cancelFunction = function() editVipWindow:destroy() iconRadioGroup:destroy() editVipWindow = nil end local saveFunction = function() if not widget or not contentsPanel:hasChild(widget) then cancelFunction() return end local name = widget:getText() local state = widget.vipState local description = descriptionText:getText() local iconId = tonumber(iconRadioGroup:getSelectedWidget():getId():sub(5)) local notify = notifyCheckBox:isChecked() if g_game.getFeature(GameAdditionalVipInfo) then g_game.editVip(id, description, iconId, notify) else if notify ~= false or #description > 0 or iconId > 0 then vipInfo[id] = {description = description, iconId = iconId, notifyLogin = notify} else vipInfo[id] = nil end end widget:destroy() GameVipList.onAddVip(id, name, state, description, iconId, notify) editVipWindow:destroy() iconRadioGroup:destroy() editVipWindow = nil end cancelButton.onClick = cancelFunction okButton.onClick = saveFunction editVipWindow.onEscape = cancelFunction editVipWindow.onEnter = saveFunction end function GameVipList.destroyAddWindow() addVipWindow:destroy() addVipWindow = nil end function GameVipList.addVip() g_game.addVip(addVipWindow:getChildById('name'):getText()) GameVipList.destroyAddWindow() end function GameVipList.removeVip(widgetOrName) if not widgetOrName then return end local widget if type(widgetOrName) == 'string' then local entries = contentsPanel:getChildren() for i = 1, #entries do if entries[i]:getText():lower() == widgetOrName:lower() then widget = entries[i] break end end if not widget then return end else widget = widgetOrName end if widget then local id = widget:getId():sub(4) g_game.removeVip(id) contentsPanel:removeChild(widget) if vipInfo[id] and g_game.getFeature(GameAdditionalVipInfo) then vipInfo[id] = nil end end end function GameVipList.hideOffline(state) settings = {} settings['hideOffline'] = state g_settings.mergeNode('VipList', settings) GameVipList.online() end function GameVipList.isHiddingOffline() local settings = g_settings.getNode('VipList') if not settings then return false end return settings['hideOffline'] end function GameVipList.getSortedBy() local settings = g_settings.getNode('VipList') if not settings or not settings['sortedBy'] then return 'status' end return settings['sortedBy'] end function GameVipList.sortBy(state) settings = {} settings['sortedBy'] = state g_settings.mergeNode('VipList', settings) GameVipList.online() end function GameVipList.onAddVip(id, name, state, description, iconId, notify) local label = contentsPanel:getChildById('vip' .. id) if not label then label = g_ui.createWidget('VipListLabel') label.onMousePress = GameVipList.onVipListLabelMousePress label:setId('vip' .. id) label:setText(name) else return end if not g_game.getFeature(GameAdditionalVipInfo) then local tmpVipInfo = vipInfo[tostring(id)] label.iconId = 0 label.notifyLogin = false if tmpVipInfo then if tmpVipInfo.iconId then label:setImageClip(torect((tmpVipInfo.iconId * 12) .. ' 0 12 12')) label.iconId = tmpVipInfo.iconId end if tmpVipInfo.description then label:setTooltip(tmpVipInfo.description) end label.notifyLogin = tmpVipInfo.notifyLogin or false end else label:setTooltip(description) label:setImageClip(torect((iconId * 12) .. ' 0 12 12')) label.iconId = iconId label.notifyLogin = notify end if state == VipState.Online then label:setColor('#00ff00') elseif state == VipState.Pending then label:setColor('#ffca38') else label:setColor('#ff0000') end label.vipState = state label:setPhantom(false) connect(label, { onDoubleClick = function() g_game.openPrivateChannel(label:getText()) return true end }) if state == VipState.Offline and GameVipList.isHiddingOffline() then label:setVisible(false) end local nameLower = name:lower() local childrenCount = contentsPanel:getChildCount() for i=1,childrenCount do local child = contentsPanel:getChildByIndex(i) if (state == VipState.Online and child.vipState ~= VipState.Online and GameVipList.getSortedBy() == 'status') or (label.iconId > child.iconId and GameVipList.getSortedBy() == 'type') then contentsPanel:insertChild(i, label) return end if (((state ~= VipState.Online and child.vipState ~= VipState.Online) or (state == VipState.Online and child.vipState == VipState.Online)) and GameVipList.getSortedBy() == 'status') or (label.iconId == child.iconId and GameVipList.getSortedBy() == 'type') or GameVipList.getSortedBy() == 'name' then local childText = child:getText():lower() local length = math.min(childText:len(), nameLower:len()) for j=1,length do if nameLower:byte(j) < childText:byte(j) then contentsPanel:insertChild(i, label) return elseif nameLower:byte(j) > childText:byte(j) then break elseif j == nameLower:len() then -- We are at the end of nameLower, and its shorter than childText, thus insert before contentsPanel:insertChild(i, label) return end end end end contentsPanel:insertChild(childrenCount+1, label) end function GameVipList.onVipStateChange(id, state) local label = contentsPanel:getChildById('vip' .. id) local name = label:getText() local description = label:getTooltip() local iconId = label.iconId local notify = label.notifyLogin label:destroy() GameVipList.onAddVip(id, name, state, description, iconId, notify) if notify and state ~= VipState.Pending then if modules.game_textmessage then GameTextMessage.displayFailureMessage(state == VipState.Online and tr('%s has logged in.', name) or tr('%s has logged out.', name)) end end end function GameVipList.onVipListMousePress(widget, mousePos, mouseButton) if mouseButton ~= MouseRightButton then return end local menu = g_ui.createWidget('PopupMenu') menu:setGameMenu(true) menu:addOption(tr('Add new VIP'), function() GameVipList.createAddWindow() end) menu:addSeparator() if not GameVipList.isHiddingOffline() then menu:addOption(tr('Hide offline'), function() GameVipList.hideOffline(true) end) else menu:addOption(tr('Show offline'), function() GameVipList.hideOffline(false) end) end if not(GameVipList.getSortedBy() == 'name') then menu:addOption(tr('Sort by name'), function() GameVipList.sortBy('name') end) end if not(GameVipList.getSortedBy() == 'status') then menu:addOption(tr('Sort by status'), function() GameVipList.sortBy('status') end) end if not(GameVipList.getSortedBy() == 'type') then menu:addOption(tr('Sort by type'), function() GameVipList.sortBy('type') end) end menu:display(mousePos) return true end function GameVipList.onVipListLabelMousePress(widget, mousePos, mouseButton) if mouseButton ~= MouseRightButton then return end local menu = g_ui.createWidget('PopupMenu') menu:setGameMenu(true) menu:addOption(tr('Send message'), function() g_game.openPrivateChannel(widget:getText()) end) menu:addOption(tr('Add new VIP'), function() GameVipList.createAddWindow() end) menu:addOption(tr('Edit') .. ' ' .. widget:getText(), function() if widget then GameVipList.createEditWindow(widget) end end) menu:addOption(tr('Remove') .. ' ' .. widget:getText(), function() if widget then GameVipList.removeVip(widget) end end) menu:addSeparator() menu:addOption(tr('Copy name'), function() g_window.setClipboardText(widget:getText()) end) if GameConsole and GameConsole.getOwnPrivateTab() then menu:addSeparator() menu:addOption(tr('Invite to private chat'), function() g_game.inviteToOwnChannel(widget:getText()) end) menu:addOption(tr('Exclude from private chat'), function() g_game.excludeFromOwnChannel(widget:getText()) end) end if not GameVipList.isHiddingOffline() then menu:addOption(tr('Hide offline'), function() GameVipList.hideOffline(true) end) else menu:addOption(tr('Show offline'), function() GameVipList.hideOffline(false) end) end if not(GameVipList.getSortedBy() == 'name') then menu:addOption(tr('Sort by name'), function() GameVipList.sortBy('name') end) end if not(GameVipList.getSortedBy() == 'status') then menu:addOption(tr('Sort by status'), function() GameVipList.sortBy('status') end) end if not(GameVipList.getSortedBy() == 'type') then menu:addOption(tr('Sort by type'), function() GameVipList.sortBy('type') end) end menu:display(mousePos) return true end
mit
nagyistoce/OpenBird
cocos2d/cocos/scripting/lua/script/CocoStudio.lua
19
8831
require "json" require "extern" ccs = ccs or {} function ccs.sendTriggerEvent(event) local triggerObjArr = ccs.TriggerMng.getInstance():get(event) if nil == triggerObjArr then return end for i = 1, table.getn(triggerObjArr) do local triObj = triggerObjArr[i] if nil ~= triObj and triObj.detect then triObj:done() end end end function ccs.registerTriggerClass(className, createFunc) ccs.TInfo.new(className,createFunc) end ccs.TInfo = class("TInfo") ccs.TInfo._className = "" ccs.TInfo._fun = nil function ccs.TInfo:ctor(c,f) -- @param {String|ccs.TInfo}c -- @param {Function}f if nil ~= f then self._className = c self._fun = f else self._className = c._className self._fun = c._fun end ccs.ObjectFactory.getInstance():registerType(self) end ccs.ObjectFactory = class("ObjectFactory") ccs.ObjectFactory._typeMap = nil ccs.ObjectFactory._instance = nil function ccs.ObjectFactory:ctor() self._typeMap = {} end function ccs.ObjectFactory.getInstance() if nil == ccs.ObjectFactory._instance then ccs.ObjectFactory._instance = ccs.ObjectFactory.new() end return ccs.ObjectFactory._instance end function ccs.ObjectFactory.destroyInstance() ccs.ObjectFactory._instance = nil end function ccs.ObjectFactory:createObject(classname) local obj = nil local t = self._typeMap[classname] if nil ~= t then obj = t._fun() end return obj end function ccs.ObjectFactory:registerType(t) self._typeMap[t._className] = t end ccs.TriggerObj = class("TriggerObj") ccs.TriggerObj._cons = {} ccs.TriggerObj._acts = {} ccs.TriggerObj._enable = false ccs.TriggerObj._id = 0 ccs.TriggerObj._vInt = {} function ccs.TriggerObj.extend(target) local t = tolua.getpeer(target) if not t then t = {} tolua.setpeer(target, t) end setmetatable(t, TriggerObj) return target end function ccs.TriggerObj:ctor() self:init() end function ccs.TriggerObj:init() self._id = 0 self._enable = true self._cons = {} self._acts = {} self._vInt = {} end function ccs.TriggerObj:detect() if (not self._enable) or (table.getn(self._cons) == 0) then return true end local ret = true local obj = nil for i = 1 , table.getn(self._cons) do obj = self._cons[i] if nil ~= obj and obj.detect then ret = ret and obj:detect() end end return ret end function ccs.TriggerObj:done() if (not self._enable) or (table.getn(self._acts) == 0) then return end local obj = nil for i = 1, table.getn(self._acts) do obj = self._acts[i] if nil ~= obj and obj.done then obj:done() end end end function ccs.TriggerObj:removeAll() local obj = nil for i=1, table.getn(self._cons) do obj = self._cons[i] if nil ~= obj then obj:removeAll() end end self._cons = {} for i=1, table.getn(self._acts) do obj = self._acts[i] if nil ~= obj then obj:removeAll() end end self._acts = {} end function ccs.TriggerObj:serialize(jsonValue) self._id = jsonValue["id"] local count = 0 --condition local cons = jsonValue["conditions"] if nil ~= cons then count = table.getn(cons) for i = 1, count do local subDict = cons[i] local className = subDict["classname"] if nil ~= className then local obj = ObjectFactory.getInstance():createObject(className) assert(nil ~= obj, string.format("class named %s can not implement!",className)) obj:serialize(subDict) obj:init() table.insert(self._cons, obj) end end end local actions = jsonValue["actions"] if nil ~= actions then count = table.getn(actions) for i = 1,count do local subAction = actions[i] local className = subAction["classname"] if nil ~= className then local act = ccs.ObjectFactory.getInstance():createObject(className) assert(nil ~= act ,string.format("class named %s can not implement!",className)) act:serialize(subAction) act:init() table.insert(self._acts,act) end end end local events = jsonValue["events"] if nil ~= events then count = table.getn(events) for i = 1, count do local subEveent = events[i] local eventID = subEveent["id"] if eventID >= 0 then table.insert(self._vInt,eventID) end end end end function ccs.TriggerObj:getId() return self._id end function ccs.TriggerObj:setEnable(enable) self._enable = enable end function ccs.TriggerObj:getEvents() return self._vInt end ccs.TriggerMng = class("TriggerMng") ccs.TriggerMng._eventTriggers = nil ccs.TriggerMng._triggerObjs = nil ccs.TriggerMng._movementDispatches = nil ccs.TriggerMng._instance = nil function ccs.TriggerMng:ctor() self._triggerObjs = {} self._movementDispatches = {} self._eventTriggers = {} end function ccs.TriggerMng.getInstance() if ccs.TriggerMng._instance == nil then ccs.TriggerMng._instance = ccs.TriggerMng.new() end return ccs.TriggerMng._instance end function ccs.TriggerMng.destroyInstance() if ccs.TriggerMng._instance ~= nil then ccs.TriggerMng._instance:removeAll() ccs.TriggerMng._instance = nil end end function ccs.TriggerMng:triggerMngVersion() return "1.0.0.0" end function ccs.TriggerMng:parse(jsonStr) local parseTable = json.decode(jsonStr,1) if nil == parseTable then return end local count = table.getn(parseTable) for i = 1, count do local subDict = parseTable[i] local triggerObj = ccs.TriggerObj.new() triggerObj:serialize(subDict) local events = triggerObj:getEvents() for j = 1, table.getn(events) do local event = events[j] self:add(event, triggerObj) end self._triggerObjs[triggerObj:getId()] = triggerObj end end function ccs.TriggerMng:get(event) return self._eventTriggers[event] end function ccs.TriggerMng:getTriggerObj(id) return self._triggerObjs[id] end function ccs.TriggerMng:add(event,triggerObj) local eventTriggers = self._eventTriggers[event] if nil == eventTriggers then eventTriggers = {} end local exist = false for i = 1, table.getn(eventTriggers) do if eventTriggers[i] == triggers then exist = true break end end if not exist then table.insert(eventTriggers,triggerObj) self._eventTriggers[event] = eventTriggers end end function ccs.TriggerMng:removeAll( ) for k in pairs(self._eventTriggers) do local triObjArr = self._eventTriggers[k] for j = 1, table.getn(triObjArr) do local obj = triObjArr[j] obj:removeAll() end end self._eventTriggers = {} end function ccs.TriggerMng:remove(event, obj) if nil ~= obj then return self:removeObjByEvent(event, obj) end assert(event >= 0,"event must be larger than 0") if nil == self._eventTriggers then return false end local triObjects = self._eventTriggers[event] if nil == triObjects then return false end for i = 1, table.getn(triObjects) do local triObject = triggers[i] if nil ~= triObject then triObject:remvoeAll() end end self._eventTriggers[event] = nil return true end function ccs.TriggerMng:removeObjByEvent(event, obj) assert(event >= 0,"event must be larger than 0") if nil == self._eventTriggers then return false end local triObjects = self._eventTriggers[event] if nil == triObjects then return false end for i = 1,table.getn(triObjects) do local triObject = triObjects[i] if nil ~= triObject and triObject == obj then triObject:remvoeAll() table.remove(triObjects, i) return true end end end function ccs.TriggerMng:removeTriggerObj(id) local obj = self.getTriggerObj(id) if nil == obj then return false end local events = obj:getEvents() for i = 1, table.getn(events) do self:remove(events[i],obj) end return true end function ccs.TriggerMng:isEmpty() return (not (nil == self._eventTriggers)) or table.getn(self._eventTriggers) <= 0 end
mit
Turttle/darkstar
scripts/zones/Windurst_Walls/npcs/Zayhi-Bauhi.lua
17
5268
----------------------------------- -- Area: Windurst Walls -- Location: X:-91 Y:-9 Z:109 -- NPC: Zayhi-Bauhi -- Working 100% -- Starts and Finishes Quest: To Bee or Not to Bee? ----------------------------------- package.loaded["scripts/zones/Windurst_Walls/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Windurst_Walls/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(WINDURST,TO_BEE_OR_NOT_TO_BEE) == QUEST_ACCEPTED) then if (trade:hasItemQty(4370,1) and trade:getItemCount() == 1) then local ToBeeOrNotStatus = player:getVar("ToBeeOrNot_var"); if (ToBeeOrNotStatus == 10) then player:startEvent(0x0045); -- After Honey#1: Clearing throat elseif (ToBeeOrNotStatus == 1) then player:startEvent(0x0046); -- After Honey#2: Tries to speak again... coughs elseif (ToBeeOrNotStatus == 2) then player:startEvent(0x0049); -- After Honey#3: Tries to speak again... coughs..asked for more Honey elseif (ToBeeOrNotStatus == 3) then player:startEvent(0x004A); -- After Honey#4: Feels like its getting a lot better but there is still iritaion elseif (ToBeeOrNotStatus == 4) then player:startEvent(0x004B); -- After Honey#5: ToBee quest Finish (tooth hurts from all the Honey end end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local ToBee = player:getQuestStatus(WINDURST,TO_BEE_OR_NOT_TO_BEE); local PostmanKOsTwice = player:getQuestStatus(WINDURST,THE_POSTMAN_ALWAYS_KO_S_TWICE); local ToBeeOrNotStatus = player:getVar("ToBeeOrNot_var"); if ((player:getFameLevel(WINDURST) >= 2 and PostmanKOsTwice == QUEST_COMPLETED and ToBee == QUEST_AVAILABLE) or (ToBee == QUEST_ACCEPTED and ToBeeOrNotStatus == 10)) then player:startEvent(0x0040); -- Just Before Quest Start "Too Bee or Not Too Be" (Speech given with lots of coughing) elseif (ToBee == QUEST_ACCEPTED) then if (ToBeeOrNotStatus == 1) then player:startEvent(0x0045); -- After Honey#1: Clearing throat elseif (ToBeeOrNotStatus == 2) then player:startEvent(0x0046); -- After Honey#2: Tries to speak again... coughs elseif (ToBeeOrNotStatus == 3) then player:startEvent(0x0049); -- After Honey#3: Tries to speak again... coughs..asked for more Honey elseif (ToBeeOrNotStatus == 4) then player:startEvent(0x004A); -- After Honey#4: Feels like its getting a lot better but there is still iritaion end elseif (ToBee == QUEST_COMPLETED and player:needToZone()) then player:startEvent(0x004E); -- ToBee After Quest Finish but before zone (tooth still hurts) else player:startEvent(0x012B); -- Normal speech end end; -- Event ID List for NPC -- player:startEvent(0x012B); -- Normal speach -- player:startEvent(0x003D); -- Normal speach -- player:startEvent(0x0040); -- Start quest "Too Bee or Not Too Be" (Speech given with lots of coughing) -- player:startEvent(0x0045); -- After Honey#1: Clearing throat -- player:startEvent(0x0046); -- After Honey#2: Tries to speak again... coughs -- player:startEvent(0x0049); -- After Honey#3: Tries to speak again... coughs..asked for more Honey -- player:startEvent(0x004A); -- After Honey#4: Feels like its getting a lot better but there is still iritaion -- player:startEvent(0x004B); -- After Honey#5: ToBee quest Finish (tooth hurts from all the Honey) -- player:startEvent(0x004E); -- ToBee After Quest Finish but before zone (tooth still hurts) ----------------------------------- -- 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 == 0x0040) then player:setVar("ToBeeOrNot_var",10); elseif (csid == 0x0045) then -- After Honey#1: Clearing throat player:tradeComplete(); player:setVar("ToBeeOrNot_var",1); elseif (csid == 0x0046) then -- After Honey#2: Tries to speak again... coughs player:tradeComplete(); player:setVar("ToBeeOrNot_var",2); elseif (csid == 0x0049) then -- After Honey#3: Tries to speak again... coughs..asked for more Honey player:tradeComplete(); player:setVar("ToBeeOrNot_var",3); elseif (csid == 0x004A) then -- After Honey#4: Feels like its getting a lot better but there is still iritaion player:tradeComplete(); player:setVar("ToBeeOrNot_var",4); elseif (csid == 0x004B) then -- After Honey#5: ToBee quest Finish (tooth hurts from all the Honey) player:tradeComplete(); player:setVar("ToBeeOrNot_var",5); player:addFame(WINDURST,WIN_FAME*30); player:completeQuest(WINDURST,TO_BEE_OR_NOT_TO_BEE); player:needToZone(true); end end;
gpl-3.0
eugeneia/snabb
src/lib/hardware/pci.lua
2
10651
-- Use of this source code is governed by the Apache 2.0 license; see COPYING. module(...,package.seeall) local ffi = require("ffi") local C = ffi.C local S = require("syscall") local shm = require("core.shm") local lib = require("core.lib") --- ### Hardware device information devices = {} --- Array of all supported hardware devices. --- --- Each entry is a "device info" table with these attributes: --- --- * `pciaddress` e.g. `"0000:83:00.1"` --- * `vendor` id hex string e.g. `"0x8086"` for Intel. --- * `device` id hex string e.g. `"0x10fb"` for 82599 chip. --- * `interface` name of Linux interface using this device e.g. `"eth0"`. --- * `status` string Linux operational status, or `nil` if not known. --- * `driver` Lua module that supports this hardware e.g. `"intel_mp"`. --- * `usable` device was suitable to use when scanned? `yes` or `no` --- Initialize (or re-initialize) the `devices` table. function scan_devices () for device in assert(S.util.ls("/sys/bus/pci/devices")) do if device ~= '.' and device ~= '..' then local info = device_info(device) if info.driver then table.insert(devices, info) end end end end function device_info (pciaddress) local info = {} local p = path(pciaddress) assert(S.stat(p), ("No such device: %s"):format(pciaddress)) info.pciaddress = canonical(pciaddress) info.vendor = lib.firstline(p.."/vendor") info.device = lib.firstline(p.."/device") info.model = which_model(info.vendor, info.device) info.driver = which_driver(info.vendor, info.device) if info.driver then info.rx, info.tx = which_link_names(info.driver) info.interface = lib.firstfile(p.."/net") if info.interface then info.status = lib.firstline(p.."/net/"..info.interface.."/operstate") end end info.usable = lib.yesno(is_usable(info)) return info end --- Return the path to the sysfs directory for `pcidev`. function path(pcidev) return "/sys/bus/pci/devices/"..qualified(pcidev) end model = { ["82599_SFP"] = 'Intel 82599 SFP', ["82574L"] = 'Intel 82574L', ["82571"] = 'Intel 82571', ["82599_T3"] = 'Intel 82599 T3', ["X540"] = 'Intel X540', ["X520"] = 'Intel X520', ["i350"] = 'Intel 350', ["i210"] = 'Intel 210', ["X710"] = 'Intel X710', ["XL710_VF"] = 'Intel XL710/X710 Virtual Function', ["AVF"] = 'Intel AVF' } -- Supported cards indexed by vendor and device id. local cards = { ["0x8086"] = { ["0x10fb"] = {model = model["82599_SFP"], driver = 'apps.intel_mp.intel_mp'}, ["0x10d3"] = {model = model["82574L"], driver = 'apps.intel_mp.intel_mp'}, ["0x105e"] = {model = model["82571"], driver = 'apps.intel_mp.intel_mp'}, ["0x151c"] = {model = model["82599_T3"], driver = 'apps.intel_mp.intel_mp'}, ["0x1528"] = {model = model["X540"], driver = 'apps.intel_mp.intel_mp'}, ["0x154d"] = {model = model["X520"], driver = 'apps.intel_mp.intel_mp'}, ["0x1521"] = {model = model["i350"], driver = 'apps.intel_mp.intel_mp'}, ["0x1533"] = {model = model["i210"], driver = 'apps.intel_mp.intel_mp'}, ["0x157b"] = {model = model["i210"], driver = 'apps.intel_mp.intel_mp'}, ["0x154c"] = {model = model["XL710_VF"], driver = 'apps.intel_avf.intel_avf'}, ["0x1889"] = {model = model["AVF"], driver = 'apps.intel_avf.intel_avf'}, ["0x1572"] = {model = model["X710"], driver = nil}, }, ["0x1924"] = { ["0x0903"] = {model = 'SFN7122F', driver = 'apps.solarflare.solarflare'} }, ["0x15b3"] = { ["0x1013" ] = {model = 'MT27700', driver = 'apps.mellanox.connectx'}, ["0x1017" ] = {model = 'MT27800', driver = 'apps.mellanox.connectx'}, ["0x1019" ] = {model = 'MT28800', driver = 'apps.mellanox.connectx'}, ["0x101d" ] = {model = 'MT2892', driver = 'apps.mellanox.connectx'}, }, } local link_names = { ['apps.solarflare.solarflare'] = { "rx", "tx" }, ['apps.intel_mp.intel_mp'] = { "input", "output" }, ['apps.intel_avf.intel_avf'] = { "input", "output" }, ['apps.mellanox.connectx'] = { "input", "output" }, } -- Return the name of the Lua module that implements support for this device. function which_driver (vendor, device) local card = cards[vendor] and cards[vendor][device] return card and card.driver end function which_model (vendor, device) local card = cards[vendor] and cards[vendor][device] return card and card.model end function which_link_names (driver) return unpack(assert(link_names[driver])) end --- ### Device manipulation. --- Return true if `device` is safely available for use, or false if --- the operating systems to be using it. function is_usable (info) return info.driver and (info.interface == nil or info.status == 'down') end -- Reset a PCI function. -- See https://www.kernel.org/doc/Documentation/ABI/testing/sysfs-bus-pci function reset_device (pciaddress) root_check() local p = path(pciaddress).."/reset" if lib.can_write(p) then lib.writefile(p, "1") else error("Cannot write: "..p) end end --- Force Linux to release the device with `pciaddress`. --- The corresponding network interface (e.g. `eth0`) will disappear. function unbind_device_from_linux (pciaddress) root_check() local p = path(pciaddress).."/driver/unbind" if lib.can_write(p) then lib.writefile(path(pciaddress).."/driver/unbind", qualified(pciaddress)) end end -- ### Access PCI devices using Linux sysfs (`/sys`) filesystem -- sysfs is an interface towards the Linux kernel based on special -- files that are implemented as callbacks into the kernel. Here are -- some background links about sysfs: -- - High-level: <http://en.wikipedia.org/wiki/Sysfs> -- - Low-level: <https://www.kernel.org/doc/Documentation/filesystems/sysfs.txt> -- PCI hardware device registers can be memory-mapped via sysfs for -- "Memory-Mapped I/O" by device drivers. The trick is to `mmap()` a file -- such as: -- /sys/bus/pci/devices/0000:00:04.0/resource0 -- and then read and write that memory to access the device. -- Memory map PCI device configuration space. -- Return two values: -- Pointer for memory-mapped access. -- File descriptor for the open sysfs resource file. function open_pci_resource_locked(device,n) return open_pci_resource(device, n, true) end function open_pci_resource_unlocked(device,n) return open_pci_resource(device, n, false) end function open_pci_resource (device, n, lock) assert(lock == true or lock == false, "Explicit lock status required") root_check() local filepath = path(device).."/resource"..n local f,err = S.open(filepath, "rdwr, sync") assert(f, "failed to open resource " .. filepath .. ": " .. tostring(err)) if lock then assert(f:flock("ex, nb"), "failed to lock " .. filepath) end return f end function map_pci_memory (f) local st = assert(f:stat()) local mem, err = f:mmap(nil, st.size, "read, write", "shared", 0) -- mmap() returns EINVAL on Linux >= 4.5 if the device is still -- claimed by the kernel driver. We assume that -- unbind_device_from_linux() has already been called but it may take -- some time for the driver to release the device. if not mem and err.INVAL then local filepath = S.readlink("/proc/self/fd/"..f:getfd()) lib.waitfor2("mmap of "..filepath, function () mem, err = f:mmap(nil, st.size, "read, write", "shared", 0) return mem ~= nil or not err.INVAL end, 10, 1000000) end assert(mem, err) return ffi.cast("uint32_t *", mem) end function close_pci_resource (fd, base) local st = assert(fd:stat()) S.munmap(base, st.size) fd:close() end --- Enable or disable PCI bus mastering. DMA only works when bus --- mastering is enabled. function set_bus_master (device, enable) root_check() local f = assert(S.open(path(device).."/config", "rdwr")) local fd = f:getfd() local value = ffi.new("uint16_t[1]") assert(C.pread(fd, value, 2, 0x4) == 2) if enable then shm.create('group/dma/pci/'..canonical(device), 'uint64_t') value[0] = bit.bor(value[0], lib.bits({Master=2})) else shm.unlink('group/dma/pci/'..canonical(device)) value[0] = bit.band(value[0], bit.bnot(lib.bits({Master=2}))) end assert(C.pwrite(fd, value, 2, 0x4) == 2) f:close() end -- Shutdown DMA to prevent "dangling" requests for PCI devices opened -- by pid (or other processes in its process group). -- -- This is an internal API function provided for cleanup during -- process termination. function shutdown (pid) local dma = shm.children("/"..pid.."/group/dma/pci") for _, device in ipairs(dma) do -- Only disable bus mastering if we are able to get an exclusive lock on -- resource 0 (i.e., no process left using the device.) if pcall(open_pci_resource_locked(device, 0)) then set_bus_master(device, false) end end end function root_check () lib.root_check("error: must run as root to access PCI devices") end -- Return the canonical (abbreviated) representation of the PCI address. -- -- example: canonical("0000:01:00.0") -> "01:00.0" function canonical (address) return address:gsub("^0000:", "") end -- Return the fully-qualified representation of a PCI address. -- -- example: qualified("01:00.0") -> "0000:01:00.0" function qualified (address) return address:gsub("^%x%x:%x%x[.]%x+$", "0000:%1") end --- ### Selftest --- --- PCI selftest scans for available devices and performs our driver's --- self-test on each of them. function selftest () print("selftest: pci") assert(qualified("0000:01:00.0") == "0000:01:00.0", "qualified 1") assert(qualified( "01:00.0") == "0000:01:00.0", "qualified 2") assert(qualified( "0a:00.0") == "0000:0a:00.0", "qualified 3") assert(qualified( "0A:00.0") == "0000:0A:00.0", "qualified 4") assert(canonical("0000:01:00.0") == "01:00.0", "canonical 1") assert(canonical( "01:00.0") == "01:00.0", "canonical 2") scan_devices() print_device_summary() end function print_device_summary () local attrs = {"pciaddress", "model", "interface", "status", "driver", "usable"} local fmt = "%-11s %-18s %-10s %-7s %-20s %s" print(fmt:format(unpack(attrs))) for _,info in ipairs(devices) do local values = {} for _,attr in ipairs(attrs) do table.insert(values, info[attr] or "-") end print(fmt:format(unpack(values))) end end
apache-2.0
Riverlance/kingdom-age-game-windows
modules/gamelib/const.lua
1
9262
-- @docconsts @{ ACCOUNT_TYPE_NORMAL = 1 ACCOUNT_TYPE_TUTOR = 2 ACCOUNT_TYPE_SENIORTUTOR = 3 ACCOUNT_TYPE_GAMEMASTER = 4 ACCOUNT_TYPE_GOD = 5 FloorHigher = 0 FloorLower = 15 CreatureTypePlayer = 0 CreatureTypeMonster = 1 CreatureTypeNpc = 2 CreatureTypeSummonOwn = 3 CreatureTypeSummonOther = 4 SkullNone = 0 SkullYellow = 1 SkullGreen = 2 SkullWhite = 3 SkullRed = 4 SkullBlack = 5 SkullOrange = 6 SkullProtected = 7 ShieldNone = 0 ShieldWhiteYellow = 1 ShieldWhiteBlue = 2 ShieldBlue = 3 ShieldYellow = 4 ShieldBlueSharedExp = 5 ShieldYellowSharedExp = 6 ShieldBlueNoSharedExpBlink = 7 ShieldYellowNoSharedExpBlink = 8 ShieldBlueNoSharedExp = 9 ShieldYellowNoSharedExp = 10 ShieldGray = 11 ShieldStr = { [ShieldNone] = 'None', [ShieldWhiteYellow] = 'Inviter', [ShieldWhiteBlue] = 'Invitee', [ShieldBlue] = 'Partner', [ShieldYellow] = 'Leader', [ShieldGray] = 'Other member', } ShieldStr[ShieldBlueSharedExp] = ShieldStr[ShieldBlue] ShieldStr[ShieldYellowSharedExp] = ShieldStr[ShieldYellow] ShieldStr[ShieldBlueNoSharedExpBlink] = ShieldStr[ShieldBlue] ShieldStr[ShieldYellowNoSharedExpBlink] = ShieldStr[ShieldYellow] ShieldStr[ShieldBlueNoSharedExp] = ShieldStr[ShieldBlue] ShieldStr[ShieldYellowNoSharedExp] = ShieldStr[ShieldYellow] ShieldHierarchy = -- From most to less important { [ShieldYellow] = 1, [ShieldYellowSharedExp] = 2, [ShieldYellowNoSharedExpBlink] = 3, [ShieldYellowNoSharedExp] = 4, [ShieldWhiteYellow] = 5, [ShieldBlue] = 6, [ShieldBlueSharedExp] = 7, [ShieldBlueNoSharedExpBlink] = 8, [ShieldBlueNoSharedExp] = 9, [ShieldWhiteBlue] = 10, [ShieldGray] = 11, [ShieldNone] = 12, } EmblemNone = 0 EmblemGreen = 1 EmblemRed = 2 EmblemBlue = 3 EmblemMember = 4 EmblemOther = 5 VocationLearner = 0 VocationKnight = 1 VocationPaladin = 2 VocationArcher = 3 VocationAssassin = 4 VocationWizard = 5 VocationBard = 6 VocationStr = { [VocationLearner] = 'Learner', [VocationKnight] = 'Knight', [VocationPaladin] = 'Paladin', [VocationArcher] = 'Archer', [VocationAssassin] = 'Assassin', [VocationWizard] = 'Wizard', [VocationBard] = 'Bard', } NpcIconNone = 0 NpcIconChat = 1 NpcIconTrade = 2 NpcIconQuest = 3 NpcIconTradeQuest = 4 SpecialIconNone = 0 SpecialIconWanted = 1 VipIconFirst = 0 VipIconLast = 10 Directions = { North = 0, East = 1, South = 2, West = 3, NorthEast = 4, SouthEast = 5, SouthWest = 6, NorthWest = 7 } Skill = { Fist = 0, Club = 1, Sword = 2, Axe = 3, Distance = 4, Shielding = 5, Fishing = 6, CriticalChance = 7, CriticalDamage = 8, LifeLeechChance = 9, LifeLeechAmount = 10, ManaLeechChance = 11, ManaLeechAmount = 12 } North = Directions.North East = Directions.East South = Directions.South West = Directions.West NorthEast = Directions.NorthEast SouthEast = Directions.SouthEast SouthWest = Directions.SouthWest NorthWest = Directions.NorthWest FightOffensive = 1 FightBalanced = 2 FightDefensive = 3 DontChase = 0 ChaseOpponent = 1 PVPWhiteDove = 0 PVPWhiteHand = 1 PVPYellowHand = 2 PVPRedFist = 3 GameProtocolChecksum = 1 GameAccountNames = 2 GameChallengeOnLogin = 3 GamePenalityOnDeath = 4 GameNameOnNpcTrade = 5 GameDoubleFreeCapacity = 6 GameDoubleExperience = 7 GameTotalCapacity = 8 GameSkillsBase = 9 GamePlayerRegenerationTime = 10 GameChannelPlayerList = 11 GamePlayerMounts = 12 GameEnvironmentEffect = 13 GameCreatureEmblems = 14 GameItemAnimationPhase = 15 GameMagicEffectU16 = 16 GamePlayerMarket = 17 GameSpritesU32 = 18 GameChargeableItems = 19 GameOfflineTrainingTime = 20 GamePurseSlot = 21 GameFormatCreatureName = 22 GameSpellList = 23 GameClientPing = 24 -- 25 free GameDoubleHealth = 26 GameDoubleSkills = 27 GameChangeMapAwareRange = 28 GameMapMovePosition = 29 GameAttackSeq = 30 GameDiagonalAnimatedText = 31 GameLoginPending = 32 GameNewSpeedLaw = 33 GameForceFirstAutoWalkStep = 34 GameMinimapRemove = 35 GameDoubleShopSellAmount = 36 GameContainerPagination = 37 GameThingMarks = 38 GameLooktypeU16 = 39 GamePlayerStamina = 40 GamePlayerAddons = 41 GameMessageStatements = 42 GameMessageLevel = 43 GameNewFluids = 44 GamePlayerStateU16 = 45 GameNewOutfitProtocol = 46 GamePVPMode = 47 GameWritableDate = 48 GameAdditionalVipInfo = 49 GameSpritesAlphaChannel = 50 GamePremiumExpiration = 51 GameBrowseField = 52 GameEnhancedAnimations = 53 GameOGLInformation = 54 GameMessageSizeCheck = 55 GamePreviewState = 56 GameLoginPacketEncryption = 57 GameClientVersion = 58 GameContentRevision = 59 GameExperienceBonus = 60 GameAuthenticator = 61 GameUnjustifiedPointsPacket = 62 GameSessionKey = 63 GameDeathType = 64 GameIdleAnimations = 65 GameKeepUnawareTiles = 66 GameIngameStore = 67 GameIngameStoreHighlights = 68 GameIngameStoreServiceType = 69 GameAdditionalSkills = 70 GameBaseSkillU16 = 71 GameCreatureIcons = 72 GameHideNpcNames = 73 TextColors = { red = '#f55e5e', --'#c83200' orange = '#f36500', --'#c87832' lightYellow = '#e6db74', yellow = '#ffff00', --'#e6c832' green = '#00eb00', --'#3fbe32' lightblue = '#5ff7f7', blue = '#9f9dfd', --blue1 = '#6e50dc', --blue2 = '#3264c8', --blue3 = '#0096c8', white = '#ffffff', --'#bebebe' } MessageModes = { None = 0, Say = 1, Whisper = 2, Yell = 3, PrivateFrom = 4, PrivateTo = 5, ChannelManagement = 6, Channel = 7, ChannelHighlight = 8, Spell = 9, NpcFrom = 10, NpcTo = 11, GamemasterBroadcast = 12, GamemasterChannel = 13, GamemasterPrivateFrom = 14, GamemasterPrivateTo = 15, Login = 16, Warning = 17, Game = 18, Failure = 19, Look = 20, DamageDealed = 21, DamageReceived = 22, Heal = 23, Exp = 24, DamageOthers = 25, HealOthers = 26, ExpOthers = 27, Status = 28, Loot = 29, TradeNpc = 30, Guild = 31, PartyManagement = 32, Party = 33, BarkLow = 34, BarkLoud = 35, Report = 36, HotkeyUse = 37, TutorialHint = 38, Thankyou = 39, Market = 40, Mana = 41, BeyondLast = 42, MonsterYell = 43, MonsterSay = 44, Red = 45, Blue = 46, --RVRChannel = 47, -- Deprecated --RVRAnswer = 48, -- Deprecated --RVRContinue = 49, -- Deprecated GameHighlight = 50, NpcFromStartBlock = 51, Last = 52, MessageGameBigTop = 53, MessageGameBigCenter = 54, MessageGameBigBottom = 55, Invalid = 255, } OTSERV_RSA = "1091201329673994292788609605089955415282375029027981291234687579" .. "3726629149257644633073969600111060390723088861007265581882535850" .. "3429057592827629436413108566029093628212635953836686562675849720" .. "6207862794310902180176810615217550567108238764764442605581471797" .. "07119674283982419152118103759076030616683978566631413" CIPSOFT_RSA = "1321277432058722840622950990822933849527763264961655079678763618" .. "4334395343554449668205332383339435179772895415509701210392836078" .. "6959821132214473291575712138800495033169914814069637740318278150" .. "2907336840325241747827401343576296990629870233111328210165697754" .. "88792221429527047321331896351555606801473202394175817" -- set to the latest Tibia.pic signature to make otclient compatible with official tibia PIC_SIGNATURE = 0x56C5DDE7 OsTypes = { Linux = 1, Windows = 2, Flash = 3, OtclientLinux = 10, OtclientWindows = 11, OtclientMac = 12, } PathFindResults = { Ok = 0, Position = 1, Impossible = 2, TooFar = 3, NoWay = 4, } PathFindFlags = { AllowNullTiles = 1, AllowCreatures = 2, AllowNonPathable = 4, AllowNonWalkable = 8, } VipState = { Offline = 0, Online = 1, Pending = 2, } ExtendedIds = { Activate = 0, Locale = 1, Ping = 2, Sound = 3, Game = 4, Particles = 5, MapShader = 6, NeedsUpdate = 7 } PreviewState = { Default = 0, Inactive = 1, Active = 2 } Blessings = { None = 0, Adventurer = 1, SpiritualShielding = 2, EmbraceOfTibia = 4, FireOfSuns = 8, WisdomOfSolitude = 16, SparkOfPhoenix = 32 } DeathType = { Regular = 0, Blessed = 1 } ProductType = { Other = 0, NameChange = 1 } StoreErrorType = { NoError = -1, PurchaseError = 0, NetworkError = 1, HistoryError = 2, TransferError = 3, Information = 4 } StoreState = { None = 0, New = 1, Sale = 2, Timed = 3 } ChannelEvent = { Join = 0, Leave = 1, Invite = 2, Exclude = 3, } -- @}
mit
Turttle/darkstar
scripts/globals/items/imperial_omelette.lua
35
2869
----------------------------------------- -- ID: 4331 -- Item: imperial_omelette -- Food Effect: 240Min, All Races ----------------------------------------- -- Non Elvaan Stats -- Strength 5 -- Dexterity 2 -- Intelligence -3 -- Mind 4 -- Attack % 22 -- Attack Cap 70 -- Ranged ATT % 22 -- Ranged ATT Cap 70 ----------------------------------------- -- Elvaan Stats -- Strength 6 -- Health 20 -- Elvaan Stats -- Strength 6 -- Health 20 -- Magic 20 -- Intelligence -2 -- Mind 5 -- Charisma 4 -- Attack % 22 -- Attack Cap 85 -- Ranged ATT % 22 -- Ranged ATT Cap 85 ----------------------------------------- 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,14400,4331); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) if (target:getRace() ~= 4) then target:addMod(MOD_STR, 5); target:addMod(MOD_DEX, 2); target:addMod(MOD_INT, -3); target:addMod(MOD_MND, 4); target:addMod(MOD_FOOD_ATTP, 22); target:addMod(MOD_FOOD_ATT_CAP, 70); target:addMod(MOD_FOOD_RATTP, 22); target:addMod(MOD_FOOD_RATT_CAP, 70); else target:addMod(MOD_HP, 20); target:addMod(MOD_MP, 20); target:addMod(MOD_STR, 6); target:addMod(MOD_DEX, 2); target:addMod(MOD_INT, -2); target:addMod(MOD_MND, 5); target:addMod(MOD_CHR, 4); target:addMod(MOD_FOOD_ATTP, 22); target:addMod(MOD_FOOD_ATT_CAP, 85); target:addMod(MOD_FOOD_RATTP, 22); target:addMod(MOD_FOOD_RATT_CAP, 85); end end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) if (target:getRace() ~= 4) then target:delMod(MOD_STR, 5); target:delMod(MOD_DEX, 2); target:delMod(MOD_INT, -3); target:delMod(MOD_MND, 4); target:delMod(MOD_FOOD_ATTP, 22); target:delMod(MOD_FOOD_ATT_CAP, 70); target:delMod(MOD_FOOD_RATTP, 22); target:delMod(MOD_FOOD_RATT_CAP, 70); else target:delMod(MOD_HP, 20); target:delMod(MOD_MP, 20); target:delMod(MOD_STR, 6); target:delMod(MOD_DEX, 2); target:delMod(MOD_INT, -2); target:delMod(MOD_MND, 5); target:delMod(MOD_CHR, 4); target:delMod(MOD_FOOD_ATTP, 22); target:delMod(MOD_FOOD_ATT_CAP, 85); target:delMod(MOD_FOOD_RATTP, 22); target:delMod(MOD_FOOD_RATT_CAP, 85); end end;
gpl-3.0
fgenesis/Aquaria_experimental
game_scripts/scripts/maps/map_mithalas02.lua
6
2008
-- Copyright (C) 2007, 2010 - Bit-Blot -- -- This file is part of Aquaria. -- -- Aquaria 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. if not v then v = {} end if not AQUARIA_VERSION then dofile("scripts/entities/entityinclude.lua") end v.leave = true function init() if isFlag(FLAG_ENDING, ENDING_NAIJACAVE) then local e1 = getNode("end1") local e2 = getNode("end2") local e3 = getNode("end3") local e4 = getNode("end4") local e5 = getNode("end5") local sn = getNode("spirit") overrideZoom(0.8) fade2(1, 0) local spirit = createEntity("drask", "", node_x(sn), node_y(sn)) entity_animate(spirit, "sit", -1) local cam = createEntity("empty", "", node_x(e1), node_y(e1)) cam_toEntity(cam) watch(0.5) entity_setPosition(cam, node_x(e2), node_y(e2), 8, 0, 0, 1) fade2(0, 3) fadeIn(0) watch(5) fade2(1, 3) watch(3) overrideZoom(0.65, 20) entity_warpToNode(cam, e3) watch(0.5) entity_setPosition(cam, node_x(e4), node_y(e4), 5, 0, 0, 1) fade2(0, 3) watch(5) entity_setPosition(cam, node_x(e5), node_y(e5), 5, 0, 0, 1) watch(5) fade2(1, 3) watch(3) overrideZoom(0) if v.leave then loadMap("forest04") else watch(1) fade2(0, 0) cam_toEntity(getNaija()) end --fade2(0,4) --loadMap("energytemple") end end
gpl-2.0
SalvationDevelopment/Salvation-Scripts-TCG
c100000100.lua
2
1431
--Power Wall function c100000100.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_PRE_BATTLE_DAMAGE) e1:SetCondition(c100000100.condition) e1:SetOperation(c100000100.activate) c:RegisterEffect(e1) end function c100000100.condition(e,tp,eg,ep,ev,re,r,rp) return tp~=Duel.GetTurnPlayer() and Duel.GetAttackTarget()==nil and Duel.IsPlayerCanDiscardDeck(tp,1) end function c100000100.activate(e,tp,eg,ep,ev,re,r,rp) local lp=Duel.GetLP(tp) local atk=e:GetLabelObject():GetAttack() local maxc=lp>atk and atk or lp maxc=math.floor(maxc/100)*100 local t={} local l=1 for i=1,maxc/100 do t[i]=i*100 end Duel.Hint(HINT_SELECTMSG,tp,aux.Stringid(100000100,0)) local announce=Duel.AnnounceNumber(tp,table.unpack(t)) local g1=Duel.GetDecktopGroup(tp,announce) Duel.DisableShuffleCheck() Duel.Remove(g1,POS_FACEUP,REASON_EFFECT) if Duel.GetBattleDamage(tp)>=announce*100 then Duel.ChangeBattleDamage(tp,Duel.GetBattleDamage(tp)-announce*100) else Duel.ChangeBattleDamage(tp,0) end e:GetHandler():SetHint(CHINT_NUMBER,announce) e:GetHandler():RegisterFlagEffect(100000100,RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END,0,1) end
gpl-2.0
SalvationDevelopment/Salvation-Scripts-TCG
c85520851.lua
2
1318
--超伝導恐獣 function c85520851.initial_effect(c) --damage local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(85520851,0)) e1:SetCategory(CATEGORY_DAMAGE) e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET) e1:SetType(EFFECT_TYPE_IGNITION) e1:SetCountLimit(1) e1:SetRange(LOCATION_MZONE) e1:SetCost(c85520851.cost) e1:SetTarget(c85520851.target) e1:SetOperation(c85520851.operation) c:RegisterEffect(e1) end function c85520851.cost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():GetAttackAnnouncedCount()==0 and Duel.CheckReleaseGroup(tp,nil,1,nil) end local sg=Duel.SelectReleaseGroup(tp,nil,1,1,nil) Duel.Release(sg,REASON_COST) local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_OATH) e1:SetCode(EFFECT_CANNOT_ATTACK_ANNOUNCE) e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END) e:GetHandler():RegisterEffect(e1) end function c85520851.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end Duel.SetTargetPlayer(1-tp) Duel.SetTargetParam(1000) Duel.SetOperationInfo(0,CATEGORY_DAMAGE,nil,0,1-tp,1000) end function c85520851.operation(e,tp,eg,ep,ev,re,r,rp) local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM) Duel.Damage(p,d,REASON_EFFECT) end
gpl-2.0
dickeyf/darkstar
scripts/globals/effects/saber_dance.lua
32
1693
----------------------------------- -- -- EFFECT_SABER_DANCE -- ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) local saberDanceMerits = target:getMerit(MERIT_SABER_DANCE); if (saberDanceMerits>5) then target:addMod(MOD_SAMBA_PDURATION, (saberDanceMerits -5)); end -- Does not stack with warrior Double Attack trait, so disable it if (target:hasTrait(15)) then --TRAIT_DOUBLE_ATTACK target:delMod(MOD_DOUBLE_ATTACK, 10); end target:addMod(MOD_DOUBLE_ATTACK,effect:getPower()); target:delStatusEffect(EFFECT_FAN_DANCE); end; ----------------------------------- -- onEffectTick Action ----------------------------------- function onEffectTick(target,effect) local power = effect:getPower(); local decayby = 0; -- Double attack rate decays until 20% then stays there if (power > 20) then decayby = 3; effect:setPower(power-decayby); target:delMod(MOD_DOUBLE_ATTACK,decayby); end end; ----------------------------------- -- onEffectLose Action ----------------------------------- function onEffectLose(target,effect) local saberDanceMerits = target:getMerit(MERIT_SABER_DANCE); if (saberDanceMerits>1) then target:delMod(MOD_SAMBA_PDURATION, (saberDanceMerits -5)); end if (target:hasTrait(15)) then --TRAIT_DOUBLE_ATTACK -- put Double Attack trait back on. target:addMod(MOD_DOUBLE_ATTACK, 10); end target:delMod(MOD_DOUBLE_ATTACK,effect:getPower()); end;
gpl-3.0
SalvationDevelopment/Salvation-Scripts-TCG
c42940404.lua
4
3841
--マシンナーズ・ギアフレーム function c42940404.initial_effect(c) --equip local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(42940404,0)) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetCategory(CATEGORY_EQUIP) e1:SetType(EFFECT_TYPE_IGNITION) e1:SetRange(LOCATION_MZONE) e1:SetTarget(c42940404.eqtg) e1:SetOperation(c42940404.eqop) c:RegisterEffect(e1) --unequip local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(42940404,1)) e2:SetCategory(CATEGORY_SPECIAL_SUMMON) e2:SetType(EFFECT_TYPE_IGNITION) e2:SetRange(LOCATION_SZONE) e2:SetCondition(aux.IsUnionState) e2:SetTarget(c42940404.sptg) e2:SetOperation(c42940404.spop) c:RegisterEffect(e2) --destroy sub local e3=Effect.CreateEffect(c) e3:SetType(EFFECT_TYPE_EQUIP) e3:SetProperty(EFFECT_FLAG_IGNORE_IMMUNE) e3:SetCode(EFFECT_DESTROY_SUBSTITUTE) e3:SetCondition(aux.IsUnionState) e3:SetValue(1) c:RegisterEffect(e3) --eqlimit local e4=Effect.CreateEffect(c) e4:SetType(EFFECT_TYPE_SINGLE) e4:SetCode(EFFECT_EQUIP_LIMIT) e4:SetProperty(EFFECT_FLAG_CANNOT_DISABLE) e4:SetValue(aux.TargetBoolFunction(Card.IsRace,RACE_MACHINE)) c:RegisterEffect(e4) --search local e5=Effect.CreateEffect(c) e5:SetDescription(aux.Stringid(42940404,2)) e5:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH) e5:SetType(EFFECT_TYPE_TRIGGER_O+EFFECT_TYPE_SINGLE) e5:SetCode(EVENT_SUMMON_SUCCESS) e5:SetTarget(c42940404.stg) e5:SetOperation(c42940404.sop) c:RegisterEffect(e5) end c42940404.old_union=true function c42940404.filter(c) return c:IsFaceup() and c:IsRace(RACE_MACHINE) and c:GetUnionCount()==0 end function c42940404.eqtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(tp) and c42940404.filter(chkc) and chkc~=e:GetHandler() end if chk==0 then return e:GetHandler():GetFlagEffect(42940404)==0 and Duel.GetLocationCount(tp,LOCATION_SZONE)>0 and Duel.IsExistingTarget(c42940404.filter,tp,LOCATION_MZONE,0,1,e:GetHandler()) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_EQUIP) local g=Duel.SelectTarget(tp,c42940404.filter,tp,LOCATION_MZONE,0,1,1,e:GetHandler()) Duel.SetOperationInfo(0,CATEGORY_EQUIP,g,1,0,0) e:GetHandler():RegisterFlagEffect(42940404,RESET_EVENT+0x7e0000+RESET_PHASE+PHASE_END,0,1) end function c42940404.eqop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local tc=Duel.GetFirstTarget() if not c:IsRelateToEffect(e) or c:IsFacedown() then return end if not tc:IsRelateToEffect(e) or not c42940404.filter(tc) then Duel.SendtoGrave(c,REASON_EFFECT) return end if not Duel.Equip(tp,c,tc,false) then return end aux.SetUnionState(c) end function c42940404.sptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():GetFlagEffect(42940404)==0 and Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,false,false) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0) e:GetHandler():RegisterFlagEffect(42940404,RESET_EVENT+0x7e0000+RESET_PHASE+PHASE_END,0,1) end function c42940404.spop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if not c:IsRelateToEffect(e) then return end Duel.SpecialSummon(c,0,tp,tp,true,false,POS_FACEUP_ATTACK) end function c42940404.sfilter(c) return c:IsSetCard(0x36) and c:GetCode()~=42940404 and c:IsType(TYPE_MONSTER) and c:IsAbleToHand() end function c42940404.stg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c42940404.sfilter,tp,LOCATION_DECK,0,1,nil) end Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK) end function c42940404.sop(e,tp,eg,ep,ev,re,r,rp) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND) local g=Duel.SelectMatchingCard(tp,c42940404.sfilter,tp,LOCATION_DECK,0,1,1,nil) if g:GetCount()>0 then Duel.SendtoHand(g,nil,REASON_EFFECT) Duel.ConfirmCards(1-tp,g) end end
gpl-2.0
alfred-bot/zacbot
plugins/Moderation.lua
2
9650
do local function check_member(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then local username = v.username data[tostring(msg.to.id)] = { moderators = {[tostring(member_id)] = username}, settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'no', lock_photo = 'no', lock_member = 'no' } } save_data(_config.moderation.data, data) return send_large_msg(receiver, 'You Are Seted For Moderation') end end end local function automodadd(msg) local data = load_data(_config.moderation.data) if msg.action.type == 'chat_created' then receiver = get_receiver(msg) chat_info(receiver, check_member,{receiver=receiver, data=data, msg = msg}) else if data[tostring(msg.to.id)] then return 'Group Have Already Moderator List' end if msg.from.username then username = msg.from.username else username = msg.from.print_name end data[tostring(msg.to.id)] = { moderators ={[tostring(msg.from.id)] = username}, settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'no', lock_photo = 'no', lock_member = 'no' } } save_data(_config.moderation.data, data) return 'Moderator List Added and @'..username..' Are Seted For Moderation' end end local function modadd(msg) if not is_admin(msg) then return "You Are Not Global Admin" end local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then return 'Group Have Already Moderator List' end data[tostring(msg.to.id)] = { moderators ={}, settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'no', lock_photo = 'no', lock_member = 'no' } } save_data(_config.moderation.data, data) return 'Moderator List Added' end local function modrem(msg) if not is_admin(msg) then return "You Are Not Global Admin" end local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if not data[tostring(msg.to.id)] then return 'Group Have Not Moderator List' end data[tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) return 'Moderator List Removed' end local function promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'chat#id', '') if not data[group] then return send_large_msg(receiver, 'Group Have Not Moderator List') end if data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is Already Moderator') end data[group]['moderators'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' Seted For Moderation') end local function demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'chat#id', '') if not data[group] then return send_large_msg(receiver, 'Group Have Not Moderator List') end if not data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is Not Moderator') end data[group]['moderators'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' Demoted') end local function admin_promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is Already Global Admin') end data['admins'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' Seted in Global Admins List') end local function admin_demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if not data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is Not Global Admin') end data['admins'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, member_username..' Demoted of Global Admins List') end local function username_id(cb_extra, success, result) local mod_cmd = cb_extra.mod_cmd local receiver = cb_extra.receiver local member = cb_extra.member local text = 'No @'..member..' in Group.' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.id if mod_cmd == 'modset' then return promote(receiver, member_username, member_id) elseif mod_cmd == 'moddem' then return demote(receiver, member_username, member_id) elseif mod_cmd == 'adminset' then return admin_promote(receiver, member_username, member_id) elseif mod_cmd == 'admindem' then return admin_demote(receiver, member_username, member_id) end end end send_large_msg(receiver, text) end local function modlist(msg) local data = load_data(_config.moderation.data) if not data[tostring(msg.to.id)] then return 'Group Have Not Moderator List' end if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way return 'Group Have Not Moderator' end local message = 'Moderators List For ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do message = message .. '> @'..v..' (' ..k.. ') \n' end return message end local function admin_list(msg) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if next(data['admins']) == nil then return 'Global Admins List Not Available' end local message = 'Robot Global Admins List:\n' for k,v in pairs(data['admins']) do message = message .. '> @'.. v ..' ('..k..') \n' end return message end function run(msg, matches) if matches[1] == 'debug' then return debugs(msg) end if not is_chat_msg(msg) then return "Works in Group" end local mod_cmd = matches[1] local receiver = get_receiver(msg) if matches[1] == 'modadd' then return modadd(msg) end if matches[1] == 'modrem' then return modrem(msg) end if matches[1] == 'modset' and matches[2] then if not is_momod(msg) then return "You Are Not Moderator or Global Admin" end local member = string.gsub(matches[2], "@", "") chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end if matches[1] == 'moddem' and matches[2] then if not is_momod(msg) then return "You Are Not Moderator or Global Admin" end if string.gsub(matches[2], "@", "") == msg.from.username then return "Can Not Demote Yourself" end local member = string.gsub(matches[2], "@", "") chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end if matches[1] == 'modlist' then return modlist(msg) end if matches[1] == 'adminset' then if not is_admin(msg) then return "You Are Not Sudo or Global Admin" end local member = string.gsub(matches[2], "@", "") chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end if matches[1] == 'admindem' then if not is_admin(msg) then return "You Are Not Sudo or Global Admin" end local member = string.gsub(matches[2], "@", "") chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end if matches[1] == 'adminlist' then if not is_admin(msg) then return 'You Are Not Sudo or Global Admin' end return admin_list(msg) end if matches[1] == 'chat_add_user' and msg.action.user.id == our_id then return automodadd(msg) end if matches[1] == 'chat_created' and msg.from.id == 0 then return automodadd(msg) end end return { description = "Global Admin and Moderation Options", usage = { moderator = { "!modset <@User> : Set Moderator", "!moddem <@user> : Demote Moderator", "!modlist : Moderators List", }, admin = { "!modadd : Add Moderator List", "!modrem : Remove Moderator List", }, sudo = { "!adminset <@User> : Set Global Admin", "!admindem <@User> : Demote Global Admin", "!adminlist : Global Admins List", }, }, patterns = { "^!(modset) (.*)$", "^!(moddem) (.*)$", "^!(modlist)$", "^!(modadd)$", "^!(modrem)$", "^!(adminset) (.*)$", "^!(admindem) (.*)$", "^!(adminlist)$", "^!!tgservice (chat_add_user)$", "^!!tgservice (chat_created)$", }, run = run, } end
gpl-2.0
Turttle/darkstar
scripts/zones/Port_Bastok/npcs/Ravorara.lua
38
1028
----------------------------------- -- Area: Port Bastok -- NPC: Ravorara -- Type: Quest Giver -- @zone: 236 -- @pos -151.062 -7 -7.243 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0136); 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
SalvationDevelopment/Salvation-Scripts-TCG
c91078716.lua
6
2124
--ポリノシス function c91078716.initial_effect(c) --Activate(summon) local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_DISABLE_SUMMON+CATEGORY_DESTROY) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_SUMMON) e1:SetCondition(c91078716.condition1) e1:SetCost(c91078716.cost) e1:SetTarget(c91078716.target1) e1:SetOperation(c91078716.activate1) c:RegisterEffect(e1) local e2=e1:Clone() e2:SetCode(EVENT_SPSUMMON) c:RegisterEffect(e2) --Activate(effect) local e3=Effect.CreateEffect(c) e3:SetCategory(CATEGORY_NEGATE+CATEGORY_DESTROY) e3:SetType(EFFECT_TYPE_ACTIVATE) e3:SetCode(EVENT_CHAINING) e3:SetCondition(c91078716.condition2) e3:SetCost(c91078716.cost) e3:SetTarget(c91078716.target2) e3:SetOperation(c91078716.activate2) c:RegisterEffect(e3) end function c91078716.condition1(e,tp,eg,ep,ev,re,r,rp) return Duel.GetCurrentChain()==0 end function c91078716.filter(c) return c:IsRace(RACE_PLANT) and not c:IsStatus(STATUS_BATTLE_DESTROYED) end function c91078716.cost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.CheckReleaseGroup(tp,c91078716.filter,1,nil) end local g=Duel.SelectReleaseGroup(tp,c91078716.filter,1,1,nil) Duel.Release(g,REASON_COST) end function c91078716.target1(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end Duel.SetOperationInfo(0,CATEGORY_DISABLE_SUMMON,eg,eg:GetCount(),0,0) Duel.SetOperationInfo(0,CATEGORY_DESTROY,eg,eg:GetCount(),0,0) end function c91078716.activate1(e,tp,eg,ep,ev,re,r,rp) Duel.NegateSummon(eg) Duel.Destroy(eg,REASON_EFFECT) end function c91078716.condition2(e,tp,eg,ep,ev,re,r,rp) return re:IsHasType(EFFECT_TYPE_ACTIVATE) and Duel.IsChainNegatable(ev) end function c91078716.target2(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end Duel.SetOperationInfo(0,CATEGORY_NEGATE,eg,1,0,0) if re:GetHandler():IsDestructable() and re:GetHandler():IsRelateToEffect(re) then Duel.SetOperationInfo(0,CATEGORY_DESTROY,eg,1,0,0) end end function c91078716.activate2(e,tp,eg,ep,ev,re,r,rp) if Duel.NegateActivation(ev) and re:GetHandler():IsRelateToEffect(re) then Duel.Destroy(eg,REASON_EFFECT) end end
gpl-2.0
Turttle/darkstar
scripts/globals/abilities/pets/geocrush.lua
18
1404
--------------------------------------------------- -- Geocrush --------------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); require("scripts/globals/magic"); --------------------------------------------------- function onAbilityCheck(player, target, ability) return 0,0; end; function onPetAbility(target, pet, skill) local dINT = math.floor(pet:getStat(MOD_INT) - target:getStat(MOD_INT)); local tp = skill:getTP(); local master = pet:getMaster(); local merits = 0; if (master ~= nil and master:isPC()) then merits = master:getMerit(MERIT_GEOCRUSH); end tp = tp + (merits - 40); if (tp > 300) then tp = 300; end --note: this formula is only accurate for level 75 - 76+ may have a different intercept and/or slope local damage = math.floor(512 + 1.72*(tp+1)); damage = damage + (dINT * 1.5); damage = MobMagicalMove(pet,target,skill,damage,ELE_EARTH,1,TP_NO_EFFECT,0); damage = mobAddBonuses(pet, nil, target, damage.dmg, ELE_EARTH); damage = AvatarFinalAdjustments(damage,pet,skill,target,MOBSKILL_MAGICAL,MOBPARAM_NONE,1); target:delHP(damage); target:updateEnmityFromDamage(pet,damage); if (target:hasStatusEffect(EFFECT_STUN) == false) then target:addStatusEffect(EFFECT_STUN,3,3,3); end return damage; end
gpl-3.0
Riverlance/kingdom-age-game-windows
data/locales/pt.lua
1
29617
locale = { name = "pt", charset = "cp1252", languageName = "Português", formatNumbers = true, decimalSeperator = ',', thousandsSeperator = '.', -- As traduções devem vir sempre em ordem alfabética. translation = { ['%d of experience per hour'] = '%d de experiência por hora', ['%i kill%s left'] = '%i morte%s restantes', ['%s has finished the request.'] = '%s finalizou a solicitação.', ['%s has logged in.'] = '%s logou.', ['%s has logged out.'] = '%s deslogou.', ['%s: (use object on target)'] = '%s: (usar objeto no alvo)', ['%s: (use object on yourself)'] = '%s: (usar objeto em si)', ['%s: (use object with crosshair)'] = '%s: (usar objeto com mira)', ['%s: (use object)'] = '%s: (usar objeto)', ['1a) Offensive name'] = '1a) Nome ofensivo', ['1b) Invalid name format'] = '1b) Nome com formato inválido', ['1c) Unsuitable name'] = '1c) Nome não adequado', ['1d) Name inciting rule violation'] = '1d) Nome estimulando violação de regra', ['2a) Offensive statement'] = '2a) Afirmação ofensiva', ['2b) Spamming'] = '2b) Spamming', ['2c) Illegal advertising'] = '2c) Anúncio ilegal', ['2d) Off-topic public statement'] = '2d) Afirmação pública fora de contexto', ['2e) Non-english public statement'] = '2e) Afirmação pública em língua não inglesa', ['2f) Inciting rule violation'] = '2f) Estimulando violação de regra', ['3a) Bug abuse'] = '3a) Abuso de erros', ['3b) Game weakness abuse'] = '3b) Abuso de fragilidades do jogo', ['3c) Using unofficial software to play'] = '3c) Uso de programas ilegais para jogar', ['3d) Hacking'] = '3d) Hacking', ['3e) Multi-clienting'] = '3e) Uso de mais de um client para jogar', ['3f) Account trading or sharing'] = '3f) Troca de contas ou compartilhamento', ['4a) Threatening gamemaster'] = '4a) Ameaça ao gamemaster', ['4b) Pretending to have influence on rule enforcement'] = '4b) Fingir ter influência sobre a execução de regras', ['4c) False report to gamemaster'] = '4c) Relatório falso para gamemaster', ['A new authentication token is required.\nLogin again.'] = 'É necessário um novo token de autenticação.\nLogue novamente.', ['Accept'] = 'Aceitar', ['Account Status'] = 'Estado da Conta', ['Account'] = 'Conta', ['Action'] = 'Ação', ['Activate allowed list'] = 'Ativar lista de permitidos', ['Activate ignore list'] = 'Ativar lista de ignorados', ['Add new server'] = 'Adicionar novo servidor', ['Add new VIP'] = 'Adicionar novo VIP', ['Add to VIP list'] = 'Adicionar à lista VIP', ['Add'] = 'Adicionar', ['Addon'] = 'Addon', ['Adjust volume'] = 'Ajustar volume', ['All modules and scripts were reloaded.'] = 'Todos módulos e scripts foram recarregados.', ['All'] = 'Tod.', -- Recommended size: 3 ['Allow auto chase override'] = 'Permitir sobrescrever o modo de perseguição', ['Allow VIPs to message you'] = 'Permitir VIPs lhe enviar mensagem', ['Allowed players'] = 'Jogadores permitidos', ['Ambient light'] = 'Luz ambiente', ['Amount is too high.'] = 'Quantidade muito alta.', ['Amount is too low.'] = 'Quantidade muito baixa.', ['Amount'] = 'Quant.', -- Recommended size: 6 ['Anonymous'] = 'Anônimo', ['Any'] = 'Qualquer', ['Are you sure you want to logout?'] = 'Você tem certeza de que quer deslogar?', ['Asc.'] = 'Cres.', -- Recommended size: 4 ['Attack'] = 'Atacar', ['Attr'] = 'Atri', -- Recommended size: 4 ['Attributes'] = 'Atributos', ['Auction End'] = 'Final do Leilão', ['Audio'] = 'Áudio', ['Authenticator Token'] = 'Token de Autenticação', ['Author'] = 'Autor', ['Auto login selected character on next charlist load'] = 'Auto logar com o char selecionado ao abrir a próxima lista de chars', ['Auto Login'] = 'Entrar Automaticamente', ['Autoload priority'] = 'Prioridade de carregamento', ['Autoload'] = 'Carregar automaticamente', ['Average Price'] = 'Média de Preço', ['Axe Fighting'] = 'Combate com Machado', ['Balance'] = 'Saldo', ['Banishment + Final Warning'] = 'Banimento + Aviso final', ['Banishment'] = 'Banimento', ['Battle'] = 'Batalha', ['Browse field'] = 'Explorar campo', ['Browse'] = 'Explorar', ['Button Assign'] = 'Atribuir Botão', ['Buy Offers'] = 'Ofertas de Compra', ['Buy with backpack'] = 'Incluir mochila', ['Buy'] = 'Comprar', ['Buyer Name'] = 'Comprador', ['Cancel'] = 'Cancelar', ['Cannot login while already in game.'] = 'Não é possivel logar enquanto já estiver no jogo.', ['Cap'] = 'Cap', ['Capacity'] = 'Capacidade', ['Center'] = 'Centro', ['Change language'] = 'Alterar língua', ['Channel appended to %s'] = 'Canal anexado a %s', ['Channel saved at'] = 'Canal salvo em', ['Channels'] = 'Canais', ['Character List'] = 'Lista de Chars', ['Character name'] = 'Nome do char', ['Character'] = 'Char', ['Choose an option.'] = 'Escolha uma opção.', ['Classic control'] = 'Controle clássico', ['Clear current message window'] = 'Limpar a janela de mensagens atual', ['Clear messages'] = 'Apagar mensagens', ['Clear object'] = 'Remover objeto', ['Client needs update.'] = 'O aplicativo precisa de atualização.', ['Client Version'] = 'Versão do Client', ['Close this channel'] = 'Fechar esse canal', ['Close'] = 'Fechar', ['Club Fighting'] = 'Combate com Maça', ['Combat Controls'] = 'Controles de Combate', ['Comment'] = 'Comentário', ['Connecting to game server...'] = 'Conectando ao servidor do jogo...', ['Connecting to login server...'] = 'Conectando ao servidor de login...', ['Connection Error'] = 'Erro de Conexão', ['Connection failed, the server address does not exist.'] = 'A conexão falhou, o endereço do servidor não existe.', ['Connection failed.'] = 'A conexão falhou.', ['Connection refused, the server might be offline or restarting.\nTry again later.'] = 'Conexão recusada, o servidor pode estar offline ou reiniciando.\nTente novamente mais tarde.', ['Connection timed out. Either your network is failing or the server is offline.'] = 'A conexão expirou. A sua rede está falhando ou o servidor está desconectado.', ['Console'] = 'Console', ['Cooldown'] = 'Cooldown', ['Cooldowns'] = 'Cooldowns', ['Copy message'] = 'Copiar mensagem', ['Copy name'] = 'Copiar nome', ['Copy'] = 'Copiar', ['Create Map Mark'] = 'Criar Marca no Mapa', ['Create mark'] = 'Criar marca', ['Create New Offer'] = 'Criar Nova Oferta', ['Create Offer'] = 'Criar Oferta', ['Critical Hit Chance'] = 'Chance de Ataque Crítico', ['Critical Hit Damage'] = 'Dano de Ataque Critico', ['Current hotkey to add'] = 'Atalho atual para adicionar', ['Current hotkeys'] = 'Atalhos atuais', ['Current Offers'] = 'Ofertas Atuais', ['days'] = 'dias', ['Default'] = 'Padrão', ['Delete mark'] = 'Deletar marca', ['Desc.'] = 'Dec.', -- Recommended size: 4 ['Description'] = 'Descrição', ['Destructive behaviour'] = 'Comportamento destrutivo', ['Detail'] = 'Detalhe', ['Details'] = 'Detalhes', ['DEV Mode'] = false, ['Disable chat mode, allow to walk using WASD'] = 'Desativar o modo de conversa, permitir\ncaminhar usando WASD', ['Disable shared XP'] = 'Desativar XP compartilhada', ['Dismount'] = 'Desmontar', ['Display a dialog window to choose an option\nwithout typing any message, just by clicking. You\ncan also choose the recommended option by pressing\n\'Enter\' or cancel by pressing \'Esc\'.\nNote: It wont appear on all messages, only basic.'] = 'Exibir janela de diálogo para escolher uma opção\nsem digitar qualquer mensagem, apenas clicando.\nVocê também porque escolher a opção recomendada\nao pressionar \'Enter\' ou cancelar ao pressionar\n\'Esc\'.\nNota: Isso não irá aparecer para\ntodas as mensagens, apenas básicas.', ['Display connection speed to the server\n(milliseconds).'] = 'Exibir a velocidade de conexão com o servidor\n(milissegundos).', ['Display creature health bars'] = 'Exibir barras de vida das criaturas', ['Display creature names'] = 'Exibir nomes das criaturas', ['Display text messages'] = 'Exibir mensagens de texto', ['Distance Fighting'] = 'Combate à Distância', ['Distance'] = 'Distância', ['Don\'t stretch or shrink Game Window'] = 'Não esticar ou encolher a janela do game', ['Draw Boxes'] = false, ['Draw debug boxes'] = false, ['Druid'] = false, ['Edit hotkey text'] = 'Editar texto do atalho', ['Edit List'] = 'Editar Lista', ['Edit Text'] = 'Editar Texto', ['Edit VIP list'] = 'Editar lista VIP', ['Edit'] = 'Editar', ['Enable audio'] = 'Ativar áudio', ['Enable chat mode'] = 'Ativar o modo de conversa', ['Enable dash walking'] = 'Ativar caminhada veloz', ['Enable lights'] = 'Ativar luzes', ['Enable music'] = 'Ativar música', ['Enable shared XP'] = 'Ativar XP compartilhada', ['Enable smart walking'] = 'Ativar caminhada inteligente', ['Enable vertical synchronization'] = 'Ativar sincronização vertical', ['Enter one name per line.'] = 'Insira um nome por linha.', ['Enter with your account again to update your client.'] = 'Insira sua conta novamente para atualizar o client.', ['Enter'] = 'Entrar', ['ERROR'] = 'ERRO', ['Error'] = 'Erro', ['Excessive unjustified player killing'] = 'Assassinato de jogadores em excesso sem justificativa', ['Exclude from private chat'] = 'Excluir do canal privado', ['Exit'] = 'Sair', ['Fee'] = 'Taxa', ['Feed Time'] = 'Tempo de Alimentação', ['Filter list to match your level'] = 'Filtrar a lista para seu level', ['Filter list to match your vocation'] = 'Filtrar a lista para sua vocação', ['Filters'] = 'Filtros', ['Find'] = 'Pesq', -- Recommended size: 4 ['Fishing'] = 'Pesca', ['Fist Fighting'] = 'Combate de Luta', ['Follow'] = 'Seguir', ['For Your Information'] = 'Para Sua Informação', ['Force Exit'] = 'Forçar Saída', ['Formula'] = 'Fórmula', ['Free Account'] = 'Conta Gratuita', ['Fullscreen'] = 'Tela cheia', ['Game framerate limit'] = 'Limite da taxa de quadros do jogo', ['Game screen size'] = 'Tamanho da tela do jogo', ['Game'] = 'Jogo', ['gold'] = false, ['Graphics card driver not detected'] = 'Driver da placa de vídeo não detectado', ['Graphics'] = 'Gráficos', ['Group'] = 'Grupo', ['Head'] = 'Cabeça', ['Healing'] = 'Curando', ['Health Info'] = 'Info de Vida', ['Health Information'] = 'Informação de Vida', ['Health'] = 'Vida', ['Hide Map'] = false, ['Hide monsters'] = 'Esconder montros', ['Hide NPCs'] = 'Esconder NPCs', ['Hide offline'] = 'Esconder offline', ['Hide party members'] = 'Esconder membros do grupo', ['Hide players'] = 'Esconder jogadores', ['Hide safe players'] = 'Esconder jogadores seguros', ['Hide spells for higher exp. levels'] = 'Esconder feitiços de nível avançado', ['Hide spells for other vocations'] = 'Esconder feitiços de outras vocações', ['Hide the map panel'] = 'Esconder o painel do mapa', ['Highest Price'] = 'Maior Preço', ['Hold the left mouse button (or press \'%s\')\nfor navigate. Scroll the mouse middle button for\nzoom. Press the right mouse button to create map\nmarks. Press \'%s\' for view the entire\ngame map.'] = 'Segure o botão esquerdo do mouse (ou pressione \'%s\')\npara navegar. Gire o botão do central do mouse\npara ampliar. Clique com o botão direito do mouse\npara criar marcas de mapa. Pressione \'%s\' para\nvisualizar o mapa inteiro do jogo.', ['Host'] = false, ['Hotkeys'] = 'Atalhos', ['HP'] = false, ['If you shut down the program, your character might stay in the game.\nClick on \'Logout\' to ensure that you character leaves the game properly.\nClick on \'Exit\' if you want to exit the program without logging out your character.'] = 'Se você desligar o programa, o seu char pode continuar no jogo.\nClique em \'Deslogar\' para assegurar que seu char desconecte do jogo adequadamente.\nClique em \'Forçar Saída\' para fechar o programa sem desconectar seu char.', ['Ignore capacity'] = 'Ignorar capacidade', ['Ignore equipped'] = 'Ignorar equipado', ['Ignore List'] = 'Lista de Ignorados', ['Ignore players'] = 'Ignorar jogadores', ['Ignore Private Messages'] = 'Ignorar Mensagens Privadas', ['Ignore Yelling'] = 'Ignorar Gritos', ['Ignore'] = 'Ignorar', ['Ignored players'] = 'Jogadores ignorados', ['Interface framerate limit'] = 'Limite da taxa de quadros da interface', ['Invalid authentication token.'] = 'Token de autenticação inválido.', ['Inventory'] = 'Inventário', ['Invite to party'] = 'Convidar para o grupo', ['Invite to private chat'] = 'Convidar para o canal privado', ['IP Address Banishment'] = 'Banimento de endereço IP', ['It is empty.'] = 'Está vazio.', ['Item Name'] = 'Nome do Item', ['Item Offers'] = 'Ofertas de Itens', ['Items'] = 'Itens', ['Join %s\'s party'] = 'Entrar no grupo de %s', ['Knight'] = false, ['Leave party'] = 'Sair do grupo', ['Left Sticker'] = 'Adesivo Esquerdo', ['Level'] = 'Nível', ['Life Leech Amount'] = 'Qtd Dreno de Vida', ['Life Leech Chance'] = 'Chc Dreno de Vida', ['Lifetime Premium Account'] = 'Conta Premium Eterna', ['Limits FPS to 60'] = 'Limita o FPS em 60', ['List of items that you\'re able to buy'] = 'Lista de itens que você pode comprar', ['List of items that you\'re able to sell'] = 'Lista de itens que você pode vender', ['Load'] = 'Carregar', ['Loading'] = 'Carregando', ['Local Server'] = false, ['Login Error'] = 'Erro de Login', ['Login'] = 'Logar', ['Logout'] = 'Deslogar', ['Look'] = 'Ver', ['Lowest Price'] = 'Menor Preço', ['LV'] = false, ['Magic Level'] = 'Nível de Mágica', ['Make sure that your client uses\nthe correct game client version'] = 'Tenha certeza de que o seu client use\na correta versão do client do jogo', ['Mana'] = 'Mana', ['Market Error'] = 'Erro de Mercado', ['Market Offers'] = 'Ofertas de Mercado', ['Market'] = 'Mercado', ['Message of the Day'] = 'Mensagem do Dia', ['Message to'] = 'Mensagem para', ['Minimap'] = 'Minimapa', ['Module Manager'] = 'Gerenciador de Módulos', ['Module name'] = 'Nome do módulo', ['Mount'] = 'Montar', ['Move stackable item'] = 'Mover item contável', ['Move up'] = 'Mover acima', ['MP'] = false, ['Music volume'] = 'Volume da música', ['My Offers'] = 'Minhas Ofertas', ['Name Report + Banishment + Final Warning'] = 'Report de Nome + Banimento + Aviso Final', ['Name Report + Banishment'] = 'Report de Nome + Banimento', ['Name Report'] = 'Report de Nome', ['Name'] = 'Nome', ['New Server'] = 'Novo Servidor', ['Next level in %d hours and %d minutes'] = 'Próximo nível em %d horas e %d minutos', ['No graphics card detected. Everything will be drawn using the CPU,\nthus the performance will be really bad.\nUpdate your graphics driver to have a better performance.'] = 'Nenhuma placa gráfica foi detectada. Tudo será desenhado usando a CPU,\nportanto o desempenho será realmente ruim.\nAtualize seu driver de gráficos para ter um melhor desempenho.', ['No information'] = 'Nenhuma informação', ['No item selected.'] = 'Nenhum item selecionado.', ['No mount'] = 'Sem montaria', ['No outfit'] = 'Sem outfit', ['No skull'] = 'Sem skull', ['No statement has been selected.'] = 'Nenhuma afirmação foi selecionada.', ['no'] = 'não', ['No'] = 'Não', ['None'] = 'Nenhum', ['Not enough balance to create this offer.'] = 'Saldo insuficiente para criar essa oferta.', ['Not enough items in your depot to create this offer.'] = 'Itens insuficientes no seu depot para criar essa oferta.', ['Notation'] = 'Notação', ['Notify login'] = 'Notificar login', ['NPC Trade'] = 'Troca com NPC', ['Offer History'] = 'Histórico de Ofertas', ['Offer Type'] = 'Tipo de Oferta', ['Offers'] = 'Ofertas', ['Offline Training'] = 'Treino Offline', ['Ok'] = 'Ok', ['on %s.\n'] = 'em %s.\n', ['Opacity'] = 'Opacidade', ['Open a private message channel'] = 'Abrir um canal privado', ['Open charlist automatically when starting client'] = 'Abrir lista de chars ao iniciar o client', ['Open in new window'] = 'Abrir em nova janela', ['Open new channel'] = 'Abrir novo canal', ['Open purse'] = 'Abrir bolsa', ['Open PvP Situations'] = 'Situações de PvP Livre', ['Open PvP'] = 'PvP Livre', ['Open'] = 'Abrir', ['Options'] = 'Opções', ['Ouch! Brave adventurer, you have met a sad fate.\nBut do not despair, for the gods will bring you back into this world.\n\nThis death penalty has been reduced by 100%%.\n\nSimply click on Ok to resume your journeys!'] = 'Ai! Bravo aventureiro, você se deparou com um triste destino.\nMas não se desespere, pois os deuses o trará de volta para esse mundo.\n\nA pena de morte foi reduzida em 100%%.\n\nSimplesmente clique em Ok para continuar suas jornadas!', ['Ouch! Brave adventurer, you have met a sad fate.\nBut do not despair, for the gods will bring you back\ninto this world in exchange for a small sacrifice.\n\nSimply click on Ok to resume your journeys!'] = 'Ai! Bravo aventureiro, você se deparou com um triste destino.\nMas não se desespere, pois os deuses o tratá de volta\npara esse mundo em troca de um pequeno sacrifício.\n\nSimplesmente clique em Ok para continuar suas jornadas!', ['Ouch! Brave adventurer, you have met a sad fate.\nBut do not despair, for the gods will bring you back\ninto this world in exchange for a small sacrifice.\n\nThis death penalty has been reduced by %i%%.\n\nSimply click on Ok to resume your journeys!'] = 'Ai! Bravo aventureiro, você se deparou com um triste destino.\nMas não se desespere, pois os deuses o tratá de volta\npara esse mundo em troca de um pequeno sacrifício.\n\nA pena de morte foi reduzida em %i%%.\n\nSimplesmente clique em Ok para continuar suas jornadas!', ['Overview'] = 'Visão geral', ['Page %d of %d'] = 'Página %d de %d', ['Paladin'] = false, ['Pass leadership to %s'] = 'Passar liderança para %s', ['Password'] = 'Senha', ['Piece Price'] = 'Preço/Peça', -- Recommended size: 12 ['Port'] = false, ['Position'] = 'Posição', ['Premium Account - Days left'] = 'Conta Premium - Dias restantes', ['Premium'] = 'Premium', ['Press \'Enter\' for default.\nPress \'Esc\' for cancel.'] = 'Pressione \'Enter\' para o padrão.\nPressione \'Esc\' para cancelar.', ['Press the key you wish to add onto your hotkeys manager'] = 'Pressione a tecla que você deseja\nadicionar no gerenciador de atalhos', ['Price is too high.'] = 'Preço muito alto.', ['Price is too low.'] = 'Preço muito baixo.', ['Price'] = 'Preço', ['Primary'] = 'Primário', ['Process'] = 'Processar', ['Protocol'] = 'Protocolo', ['Quest Log'] = 'Registro de Quest', ['Randomize characters outfit'] = 'Gerar outfit aleatório', ['Randomize'] = 'Randomizar', ['Reason'] = 'Razão', ['Refresh Offers'] = 'Atualizar Ofertas', ['Refresh'] = 'Atualizar', ['Reject'] = 'Rejeitar', ['Reload All'] = 'Recarregar Todos', ['Reload'] = 'Recarregar', ['Remaining skull time'] = 'Tempo de skull restante', ['Remember account and password when starts client'] = 'Lembrar conta e senha ao abrir o jogo', ['Remember'] = 'Lembrar', ['Remove'] = 'Remover', ['Report Bug'] = 'Reportar Erro', ['Report Rule Violation'] = 'Reportar Violação de Regra', ['Report Rule'] = 'Reportar Regra', ['Reserved for more functionality later.'] = 'Reservado para mais funcionalidade posterior.', ['Reset All'] = 'Resetar Todos', ['Reset Market'] = 'Resetar Mercado', ['Reset selection, filters and search'] = 'Resetar seleção, filtros e pesquisa', ['Revoke %s\'s invitation'] = 'Recusar o convite de %s', ['Rewards'] = 'Recompensas', ['Right Sticker'] = 'Adesivo Direito', ['Rotate'] = 'Girar', ['Rule violation'] = 'Violação de regra', ['Rule Violations'] = 'Violações de Regra', ['Save messages'] = 'Salvar mensagens', ['Save'] = 'Salvar', ['Search all items'] = 'Procurar todos os itens', ['Search'] = 'Pesquisar', ['Secondary'] = 'Secundário', ['See it on loot window.'] = 'Veja-os na janela de loot.', ['Select all'] = 'Selecionar tudo', ['Select object'] = 'Selecionar objeto', ['Select Outfit'] = 'Selecionar Outfit', ['Select your language'] = 'Selecione sua língua', ['Select'] = 'Selecione', ['Sell All'] = 'Vender Todos', ['Sell Offers'] = 'Ofertas de Venda', ['Sell'] = 'Vender', ['Seller Name'] = 'Vendedor', ['Send automatically'] = 'Enviar automaticamente', ['Send message'] = 'Enviar mensagem', ['Send'] = 'Enviar', ['Server List'] = 'Lista de Servidores', ['Server running from 127.0.0.1'] = false, ['Server'] = 'Servidor', ['Set outfit'] = 'Alterar outfit', ['Settings of allowed'] = 'Configurações de permitidos', ['Settings of ignore'] = 'Configurações de ignorados', ['Shielding'] = 'Defensiva', ['Show all items'] = 'Exibir todos os itens', ['Show connection ping'] = 'Exibir latência de conexão', ['Show Depot Only'] = 'Exibir Somente Depot', ['Show event messages in console'] = 'Exibir mensagens de eventos no console', ['Show frame rate'] = 'Exibir taxa de quadros', ['Show info messages in console'] = 'Exibir mensagens informativas no console', ['Show left panel'] = 'Exibir barra lateral esquerda', ['Show levels in console'] = 'Exibir níveis no console', ['Show NPCs dialog windows'] = 'Exibir janelas de diálogo nos NPCs', ['Show offline'] = 'Exibir offline', ['Show private messages in console'] = 'Exibir mensagens privadas no console', ['Show private messages on screen'] = 'Exibir mensagens na tela', ['Show Server Messages'] = 'Exibir Mensagens do Servidor', ['Show status messages in console'] = 'Exibir mensagens de estado no console', ['Show Text'] = 'Exibir Texto', ['Show timestamps in console'] = 'Exibir o horário no console', ['Show your depot items only'] = 'Exibir os itens somente do depot', ['Skull Time'] = 'Tempo de Skull', ['Sorcerer'] = false, ['Sort by name'] = 'Ordenar por nome', ['Sort by status'] = 'Ordenar por status', ['Sort by type'] = 'Ordenar por tipo', ['Soul'] = 'Alma', ['Special'] = 'Especial', ['Speed'] = 'Velocidade', ['Spell Cooldowns'] = 'Cooldowns de Magia', ['Spell List'] = 'Lista de Magias', ['Stamina'] = 'Vigor', ['State the rule violation in one clear sentence and wait for a reply from a gamemaster. Note that your message will disappear if you close the channel.'] = 'Indique a violação de regra em uma frase limpa e espere uma resposta de um gamemaster. Observe que sua mensagem desaparecerá se você fechar o canal.', ['Statement Report'] = 'Afirmar Relato', ['Statement'] = 'Afirmação', ['Statistics'] = 'Estatísticas', ['Stay logged during session'] = 'Manter-se logado durante a sessão', ['Sticker'] = 'Adesivo', ['Stop attack'] = 'Parar de atacar', ['Stop follow'] = 'Parar de seguir', ['Support'] = 'Suporte', ['Sword Fighting'] = 'Combate com Espada', ['Teleport'] = 'Teleportar', ['Terminal'] = 'Terminal', ['There is no way.'] = false, -- Systems messages wont be translated yet ['This offer is 25%% above the average market price'] = 'Essa oferta está 25%% acima da média de preço do mercado', ['This offer is 25%% below the average market price'] = 'Essa oferta está 25%% abaixo da média de preço do mercado', ['Time'] = 'Tempo', ['Total price is too high.'] = 'Valor total é muito alto.', ['Total Price'] = 'Preço Total', ['Total Transations'] = 'Total de Transações', ['Trade with'] = 'Trocar com', ['Trade'] = 'Trocar', ['Trying to reconnect in %s seconds.'] = 'Tentando reconectar em %s segundos.', ['Two-Factor Authentication'] = 'Autenticação de Dois Fatores', ['Type'] = 'Tipo', ['Unable to load dat file, place a valid dat in \'%s\''] = 'Não foi possível carregar o arquivo DAT, insira um DAT válido em \'%s\'', ['Unable to load spr file, place a valid spr in \'%s\''] = 'Não foi possível carregar o arquivo SPR, insira um SPR válido em \'%s\'', ['Unignore'] = 'Designorar', ['Unjustified points gained during the last 24 hours.\n%i kill%s left.'] = 'Pontos injustificados obtidos nas últimas 24 horas.\n%i morte%s restantes.', ['Unjustified points gained during the last 30 days.\n%i kill%s left.'] = 'Pontos injustificados obtidos nos últimos 30 dias.\n%i morte%s restantes.', ['Unjustified points gained during the last 7 days.\n%i kill%s left.'] = 'Pontos injustificados obtidos nos últimos 7 dias.\n%i morte%s restantes.', ['Unjustified Points'] = 'Pontos Injustificados', ['Unload'] = 'Descarregar', ['Update needed'] = 'Atualização necessária', ['Use on target'] = 'Usar no alvo', ['Use on yourself'] = 'Usar em si', ['Use this dialog to only report bugs or player rule violations!\nONLY IN ENGLISH!\n\n[Bad Example] :(\nFound a fucking bug! msg me! fast!!!\n\n[Nice Example] :)\nGood morning!\nI found a map bug on my actual position.\nHere is the details: ...'] = false, ['Use with'] = 'Usar com', ['Use'] = 'Usar', ['Version'] = 'Versão', ['VIP List'] = 'Lista VIP', ['Voc.'] = 'Voc.', ['Vocation'] = 'Vocação', ['Wait patiently for a gamemaster to reply.'] = 'Aguarde pacientemente um gamemaster responder.', ['Waiting List'] = 'Lista de Espera', ['Website'] = 'Website', ['Weight'] = 'Peso', ['Will boost your walk on high speed characters.'] = 'Melhorará a caminhada dos chars velozes.', ['Will detect when to use diagonal step based on the\nkeys you are pressing.'] = 'Detectará quando usar um passo diagonal baseado nas\nteclas que você está pressionando.', ['With crosshair'] = 'Com mira', ['X: %d | Y: %d | Z: %d'] = false, ['XP'] = false, ['yes'] = 'sim', ['Yes'] = 'Sim', ['You are bleeding'] = 'Você está sangrando', ['You are burning'] = 'Você está queimando', ['You are cursed'] = 'Você está amaldiçoado', ['You are dazzled'] = 'Você está deslumbrado', ['You are dead'] = 'Você está morto', ['You are drowning'] = 'Você está se afogando', ['You are drunk'] = 'Você está bêbado', ['You are electrified'] = 'Você está eletrificado', ['You are freezing'] = 'Você está congelando', ['You are hasted'] = 'Você está veloz', ['You are hungry'] = 'Você está faminto', ['You are paralysed'] = 'Você está paralizado', ['You are poisoned'] = 'Você está envenenado', ['You are protected by a magic shield'] = 'Você está protegido com um escudo mágico', ['You are strengthened'] = 'Você está forte', ['You are within a protection zone'] = 'Você está dentro de uma zona de proteção', ['You can enter new text.'] = 'Você pode inserir um novo texto.', ['You cannot create a private chat channel with yourself.'] = 'Você não pode criar um canal de chat privado consigo mesmo.', ['You cannot create more offers.'] = 'Você não pode criar mais ofertas.', ['You have %d in your depot.'] = 'Você tem %d em seu depot.', ['You have %d%% to advance to level %d.'] = 'Resta %d%% para avançar para o nível %d.', ['You have %d%% to go\n%d of experience left'] = 'Resta %d%% para avançar\n%d de experiência restante', ['You have %s percent to go'] = 'Resta %s porcento para avançar', ['You have %s percent'] = 'Você tem %s porcento', ['You have no skull'] = 'Você não tem skull', ['You may not logout during a fight'] = 'Você não pode deslogar durante um combate', ['You may not logout or enter a protection zone'] = 'Você não pode deslogar ou logar em uma zona de proteção', ['You must enter a comment.'] = 'Você deve inserir um comentário', ['You must enter a valid server address and port.'] = 'Você deve colocar um endereço e um port do servidor válidos.', ['You must select a character to login.'] = 'Você deve selecionar um char para logar.', ['You must select a reason.'] = 'Você deve inserir uma razão.', ['You must select an action.'] = 'Você deve inserir uma ação.', ['You must wait %d seconds before creating a new offer.'] = 'Você deve esperar %d segundos antes de criar uma nova oferta.', ['You read the following, written by \n%s\n'] = 'Você lê o seguinte, escrito por \n%s\n', ['You read the following, written on \n%s.\n'] = 'Você lê o seguinte, escrito em \n%s.\n', ['Your Capacity'] = 'Sua Capacidade', ['Your character health is %d out of %d.'] = 'A vida do seu char é %d de %d.', ['Your character mana is %d out of %d.'] = 'A mana do seu char é %d de %d.', ['Your client needs updating, try redownloading it.'] = 'Seu client precisa de atualização, tente baixá-lo novamente.', ['Your connection is failing. If you logout now, your\ncharacter will be still online. Do you want to\nforce logout?'] = 'Sua conexão está falhando. Se você deslogar agora, seu\nchar ainda estará online. Deseja forçar o logout?', ['Your Money'] = 'Seu Dinheiro', ['Your request has been closed.'] = 'Sua solicitação foi encerrada.', } } ClientLocales.installLocale(locale)
mit
SalvationDevelopment/Salvation-Scripts-TCG
c15978426.lua
5
1584
--EMセカンドンキー function c15978426.initial_effect(c) --tograve local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(15978426,0)) e1:SetCategory(CATEGORY_TOGRAVE+CATEGORY_SEARCH+CATEGORY_TOHAND) e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e1:SetProperty(EFFECT_FLAG_DAMAGE_STEP) e1:SetCode(EVENT_SUMMON_SUCCESS) e1:SetTarget(c15978426.tgtg) e1:SetOperation(c15978426.tgop) c:RegisterEffect(e1) local e2=e1:Clone() e2:SetCode(EVENT_SPSUMMON_SUCCESS) c:RegisterEffect(e2) end function c15978426.filter(c,tohand) return c:IsSetCard(0x9f) and not c:IsCode(15978426) and c:IsType(TYPE_MONSTER) and (c:IsAbleToGrave() or (tohand and c:IsAbleToHand())) end function c15978426.tgtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then local tohand=Duel.GetFieldCard(tp,LOCATION_SZONE,6) and Duel.GetFieldCard(tp,LOCATION_SZONE,7) return Duel.IsExistingMatchingCard(c15978426.filter,tp,LOCATION_DECK,0,1,nil,tohand) end Duel.SetOperationInfo(0,CATEGORY_TOGRAVE,nil,1,tp,LOCATION_DECK) end function c15978426.tgop(e,tp,eg,ep,ev,re,r,rp) local tohand=Duel.GetFieldCard(tp,LOCATION_SZONE,6) and Duel.GetFieldCard(tp,LOCATION_SZONE,7) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE) local g=Duel.SelectMatchingCard(tp,c15978426.filter,tp,LOCATION_DECK,0,1,1,nil,tohand) local tc=g:GetFirst() if not tc then return end if tohand and tc:IsAbleToHand() and (not tc:IsAbleToGrave() or Duel.SelectYesNo(tp,aux.Stringid(15978426,1))) then Duel.SendtoHand(tc,nil,REASON_EFFECT) Duel.ConfirmCards(1-tp,tc) else Duel.SendtoGrave(tc,REASON_EFFECT) end end
gpl-2.0
Turttle/darkstar
scripts/globals/abilities/addendum_white.lua
28
1647
----------------------------------- -- Ability: Addendum: White -- Allows access to additional White Magic spells while using Light Arts. -- Obtained: Scholar Level 10 -- Recast Time: Stratagem Charge -- Duration: 2 hours -- -- Level |Charges |Recharge Time per Charge -- ----- -------- --------------- -- 10 |1 |4:00 minutes -- 30 |2 |2:00 minutes -- 50 |3 |1:20 minutes -- 70 |4 |1:00 minute -- 90 |5 |48 seconds ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); ----------------------------------- -- onAbilityCheck ----------------------------------- function onAbilityCheck(player,target,ability) if player:hasStatusEffect(EFFECT_ADDENDUM_WHITE) then return MSGBASIC_EFFECT_ALREADY_ACTIVE, 0; end return 0,0; end; ----------------------------------- -- onUseAbility ----------------------------------- function onUseAbility(player,target,ability) player:delStatusEffectSilent(EFFECT_DARK_ARTS); player:delStatusEffectSilent(EFFECT_ADDENDUM_BLACK); player:delStatusEffectSilent(EFFECT_LIGHT_ARTS); local skillbonus = player:getMod(MOD_LIGHT_ARTS_SKILL); local effectbonus = player:getMod(MOD_LIGHT_ARTS_EFFECT); local regenbonus = 0; if (player:getMainJob() == JOB_SCH and player:getMainLvl() >= 20) then regenbonus = 3 * math.floor((player:getMainLvl() - 10) / 10); end player:addStatusEffectEx(EFFECT_ADDENDUM_WHITE,EFFECT_ADDENDUM_WHITE,effectbonus,0,7200,0,regenbonus,true); return EFFECT_ADDENDUM_WHITE; end;
gpl-3.0
birdbrainswagtrain/GmodPillPack-TeamFortress
lua/weapons/pktfw_flamethrower.lua
1
3001
AddCSLuaFile() SWEP.ViewModel = "models/weapons/c_arms_citizen.mdl" SWEP.WorldModel = "models/weapons/c_models/c_flamethrower/c_flamethrower.mdl" SWEP.Primary.ClipSize = 200 SWEP.Primary.DefaultClip = 200 SWEP.Primary.Automatic = true SWEP.Primary.Ammo = "AR2" SWEP.Secondary.ClipSize = -1 SWEP.Secondary.DefaultClip = -1 SWEP.Secondary.Automatic = false SWEP.Secondary.Ammo = "none" SWEP.Spawnable=true SWEP.AdminSpawnable=true SWEP.PrintName="Flame Thrower" SWEP.Category = "Pill Pack Weapons - TF2" SWEP.Slot=2 function SWEP:SetupDataTables() self:NetworkVar("Entity",0,"Emitter") end function SWEP:Initialize() self:SetHoldType("crossbow") self.sound_flame = CreateSound(self,"weapons/flame_thrower_loop.wav") if SERVER then local emitter = ents.Create("pill_target") self:SetEmitter(emitter) emitter:Spawn() end end function SWEP:PrimaryAttack() if ( !self:CanPrimaryAttack() ) then return end self.sound_flame:Play() if self.Owner:WaterLevel()>=2 then if CLIENT and IsValid(self:GetEmitter()) and self.particles!="bubbles" then self:GetEmitter():StopParticles() ParticleEffectAttach("flamethrower_underwater",PATTACH_ABSORIGIN_FOLLOW,self:GetEmitter(),0) self.particles="bubbles" end else if CLIENT and IsValid(self:GetEmitter()) and self.particles!="flame" then self:GetEmitter():StopParticles() ParticleEffectAttach("_flamethrower_real",PATTACH_ABSORIGIN_FOLLOW,self:GetEmitter(),0) self.particles="flame" end if SERVER then local target = self.Owner:TraceHullAttack( self.Owner:GetPos()+Vector(0,0,60), self.Owner:GetPos()+Vector(0,0,60)+self.Owner:EyeAngles():Forward()*200, Vector(-30,-30,-30), Vector(30,30,30), 5,DMG_BURN,0,true ) if IsValid(target) then target:Ignite(10) end end end if SERVER then if self.takeammo then self:TakePrimaryAmmo(1) end self.takeammo= !self.takeammo end self:SetNextPrimaryFire(CurTime() + .04) end function SWEP:Think() if self:GetNextPrimaryFire()+.05<CurTime() then self.sound_flame:Stop() if CLIENT and self.particles then self:GetEmitter():StopParticles() self.particles=nil end end if IsValid(self:GetEmitter()) then self:GetEmitter():SetNetworkOrigin(self.Owner:GetPos()+Vector(0,0,60)+self.Owner:EyeAngles():Forward()*50) self:GetEmitter():SetAngles(self.Owner:EyeAngles()) end end function SWEP:SecondaryAttack() end function SWEP:Reload() /*if self.ReloadingTime and CurTime() <= self.ReloadingTime then return end local pill_ent = pk_pills.getMappedEnt(self.Owner) if IsValid(pill_ent) and pill_ent.iscloaked then return end if (self:Clip1() < self.Primary.ClipSize and self.Owner:GetAmmoCount(self.Primary.Ammo) > 0) then self:EmitSound(self.sound_reload) self:DefaultReload(ACT_INVALID) self.ReloadingTime = CurTime() + self.time_reload self:SetNextPrimaryFire(CurTime() + self.time_reload) end*/ end function SWEP:CanPrimaryAttack() if self:Clip1() <= 0 then return false end return true end
mit
SalvationDevelopment/Salvation-Scripts-TCG
c38411870.lua
2
1045
--つり天井 function c38411870.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_DESTROY) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetHintTiming(0,0x1c0+TIMING_END_PHASE) e1:SetCondition(c38411870.condition) e1:SetTarget(c38411870.target) e1:SetOperation(c38411870.activate) c:RegisterEffect(e1) end function c38411870.condition(e,tp,eg,ep,ev,re,r,rp) return Duel.GetFieldGroupCount(tp,LOCATION_MZONE,LOCATION_MZONE)>=4 end function c38411870.filter(c) return c:IsFaceup() end function c38411870.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c38411870.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil) end local sg=Duel.GetMatchingGroup(c38411870.filter,tp,LOCATION_MZONE,LOCATION_MZONE,nil) Duel.SetOperationInfo(0,CATEGORY_DESTROY,sg,sg:GetCount(),0,0) end function c38411870.activate(e,tp,eg,ep,ev,re,r,rp) local sg=Duel.GetMatchingGroup(c38411870.filter,tp,LOCATION_MZONE,LOCATION_MZONE,nil) Duel.Destroy(sg,REASON_EFFECT) end
gpl-2.0
darcy0511/Dato-Core
src/unity/python/graphlab/lua/pl/lexer.lua
14
14051
--- Lexical scanner for creating a sequence of tokens from text. -- `lexer.scan(s)` returns an iterator over all tokens found in the -- string `s`. This iterator returns two values, a token type string -- (such as 'string' for quoted string, 'iden' for identifier) and the value of the -- token. -- -- Versions specialized for Lua and C are available; these also handle block comments -- and classify keywords as 'keyword' tokens. For example: -- -- > s = 'for i=1,n do' -- > for t,v in lexer.lua(s) do print(t,v) end -- keyword for -- iden i -- = = -- number 1 -- , , -- iden n -- keyword do -- -- See the Guide for further @{06-data.md.Lexical_Scanning|discussion} -- @module pl.lexer local yield,wrap = coroutine.yield,coroutine.wrap local strfind = string.find local strsub = string.sub local append = table.insert local function assert_arg(idx,val,tp) if type(val) ~= tp then error("argument "..idx.." must be "..tp, 2) end end local lexer = {} local NUMBER1 = '^[%+%-]?%d+%.?%d*[eE][%+%-]?%d+' local NUMBER2 = '^[%+%-]?%d+%.?%d*' local NUMBER3 = '^0x[%da-fA-F]+' local NUMBER4 = '^%d+%.?%d*[eE][%+%-]?%d+' local NUMBER5 = '^%d+%.?%d*' local IDEN = '^[%a_][%w_]*' local WSPACE = '^%s+' local STRING0 = [[^(['\"]).-\\%1]] local STRING1 = [[^(['\"]).-[^\]%1]] local STRING3 = "^((['\"])%2)" -- empty string local PREPRO = '^#.-[^\\]\n' local plain_matches,lua_matches,cpp_matches,lua_keyword,cpp_keyword local function tdump(tok) return yield(tok,tok) end local function ndump(tok,options) if options and options.number then tok = tonumber(tok) end return yield("number",tok) end -- regular strings, single or double quotes; usually we want them -- without the quotes local function sdump(tok,options) if options and options.string then tok = tok:sub(2,-2) end return yield("string",tok) end -- long Lua strings need extra work to get rid of the quotes local function sdump_l(tok,options) if options and options.string then tok = tok:sub(3,-3) end return yield("string",tok) end local function chdump(tok,options) if options and options.string then tok = tok:sub(2,-2) end return yield("char",tok) end local function cdump(tok) return yield('comment',tok) end local function wsdump (tok) return yield("space",tok) end local function pdump (tok) return yield('prepro',tok) end local function plain_vdump(tok) return yield("iden",tok) end local function lua_vdump(tok) if lua_keyword[tok] then return yield("keyword",tok) else return yield("iden",tok) end end local function cpp_vdump(tok) if cpp_keyword[tok] then return yield("keyword",tok) else return yield("iden",tok) end end --- create a plain token iterator from a string or file-like object. -- @string s the string -- @tab matches an optional match table (set of pattern-action pairs) -- @tab[opt] filter a table of token types to exclude, by default `{space=true}` -- @tab[opt] options a table of options; by default, `{number=true,string=true}`, -- which means convert numbers and strip string quotes. function lexer.scan (s,matches,filter,options) --assert_arg(1,s,'string') local file = type(s) ~= 'string' and s filter = filter or {space=true} options = options or {number=true,string=true} if filter then if filter.space then filter[wsdump] = true end if filter.comments then filter[cdump] = true end end if not matches then if not plain_matches then plain_matches = { {WSPACE,wsdump}, {NUMBER3,ndump}, {IDEN,plain_vdump}, {NUMBER1,ndump}, {NUMBER2,ndump}, {STRING3,sdump}, {STRING0,sdump}, {STRING1,sdump}, {'^.',tdump} } end matches = plain_matches end local function lex () local i1,i2,idx,res1,res2,tok,pat,fun,capt local line = 1 if file then s = file:read()..'\n' end local sz = #s local idx = 1 --print('sz',sz) while true do for _,m in ipairs(matches) do pat = m[1] fun = m[2] i1,i2 = strfind(s,pat,idx) if i1 then tok = strsub(s,i1,i2) idx = i2 + 1 if not (filter and filter[fun]) then lexer.finished = idx > sz res1,res2 = fun(tok,options) end if res1 then local tp = type(res1) -- insert a token list if tp=='table' then yield('','') for _,t in ipairs(res1) do yield(t[1],t[2]) end elseif tp == 'string' then -- or search up to some special pattern i1,i2 = strfind(s,res1,idx) if i1 then tok = strsub(s,i1,i2) idx = i2 + 1 yield('',tok) else yield('','') idx = sz + 1 end --if idx > sz then return end else yield(line,idx) end end if idx > sz then if file then --repeat -- next non-empty line line = line + 1 s = file:read() if not s then return end --until not s:match '^%s*$' s = s .. '\n' idx ,sz = 1,#s break else return end else break end end end end end return wrap(lex) end local function isstring (s) return type(s) == 'string' end --- insert tokens into a stream. -- @param tok a token stream -- @param a1 a string is the type, a table is a token list and -- a function is assumed to be a token-like iterator (returns type & value) -- @string a2 a string is the value function lexer.insert (tok,a1,a2) if not a1 then return end local ts if isstring(a1) and isstring(a2) then ts = {{a1,a2}} elseif type(a1) == 'function' then ts = {} for t,v in a1() do append(ts,{t,v}) end else ts = a1 end tok(ts) end --- get everything in a stream upto a newline. -- @param tok a token stream -- @return a string function lexer.getline (tok) local t,v = tok('.-\n') return v end --- get current line number. -- Only available if the input source is a file-like object. -- @param tok a token stream -- @return the line number and current column function lexer.lineno (tok) return tok(0) end --- get the rest of the stream. -- @param tok a token stream -- @return a string function lexer.getrest (tok) local t,v = tok('.+') return v end --- get the Lua keywords as a set-like table. -- So `res["and"]` etc would be `true`. -- @return a table function lexer.get_keywords () if not lua_keyword then lua_keyword = { ["and"] = true, ["break"] = true, ["do"] = true, ["else"] = true, ["elseif"] = true, ["end"] = true, ["false"] = true, ["for"] = true, ["function"] = true, ["if"] = true, ["in"] = true, ["local"] = true, ["nil"] = true, ["not"] = true, ["or"] = true, ["repeat"] = true, ["return"] = true, ["then"] = true, ["true"] = true, ["until"] = true, ["while"] = true } end return lua_keyword end --- create a Lua token iterator from a string or file-like object. -- Will return the token type and value. -- @string s the string -- @tab[opt] filter a table of token types to exclude, by default `{space=true,comments=true}` -- @tab[opt] options a table of options; by default, `{number=true,string=true}`, -- which means convert numbers and strip string quotes. function lexer.lua(s,filter,options) filter = filter or {space=true,comments=true} lexer.get_keywords() if not lua_matches then lua_matches = { {WSPACE,wsdump}, {NUMBER3,ndump}, {IDEN,lua_vdump}, {NUMBER4,ndump}, {NUMBER5,ndump}, {STRING3,sdump}, {STRING0,sdump}, {STRING1,sdump}, {'^%-%-%[%[.-%]%]',cdump}, {'^%-%-.-\n',cdump}, {'^%[%[.-%]%]',sdump_l}, {'^==',tdump}, {'^~=',tdump}, {'^<=',tdump}, {'^>=',tdump}, {'^%.%.%.',tdump}, {'^%.%.',tdump}, {'^.',tdump} } end return lexer.scan(s,lua_matches,filter,options) end --- create a C/C++ token iterator from a string or file-like object. -- Will return the token type type and value. -- @string s the string -- @tab[opt] filter a table of token types to exclude, by default `{space=true,comments=true}` -- @tab[opt] options a table of options; by default, `{number=true,string=true}`, -- which means convert numbers and strip string quotes. function lexer.cpp(s,filter,options) filter = filter or {comments=true} if not cpp_keyword then cpp_keyword = { ["class"] = true, ["break"] = true, ["do"] = true, ["sizeof"] = true, ["else"] = true, ["continue"] = true, ["struct"] = true, ["false"] = true, ["for"] = true, ["public"] = true, ["void"] = true, ["private"] = true, ["protected"] = true, ["goto"] = true, ["if"] = true, ["static"] = true, ["const"] = true, ["typedef"] = true, ["enum"] = true, ["char"] = true, ["int"] = true, ["bool"] = true, ["long"] = true, ["float"] = true, ["true"] = true, ["delete"] = true, ["double"] = true, ["while"] = true, ["new"] = true, ["namespace"] = true, ["try"] = true, ["catch"] = true, ["switch"] = true, ["case"] = true, ["extern"] = true, ["return"] = true,["default"] = true,['unsigned'] = true,['signed'] = true, ["union"] = true, ["volatile"] = true, ["register"] = true,["short"] = true, } end if not cpp_matches then cpp_matches = { {WSPACE,wsdump}, {PREPRO,pdump}, {NUMBER3,ndump}, {IDEN,cpp_vdump}, {NUMBER4,ndump}, {NUMBER5,ndump}, {STRING3,sdump}, {STRING1,chdump}, {'^//.-\n',cdump}, {'^/%*.-%*/',cdump}, {'^==',tdump}, {'^!=',tdump}, {'^<=',tdump}, {'^>=',tdump}, {'^->',tdump}, {'^&&',tdump}, {'^||',tdump}, {'^%+%+',tdump}, {'^%-%-',tdump}, {'^%+=',tdump}, {'^%-=',tdump}, {'^%*=',tdump}, {'^/=',tdump}, {'^|=',tdump}, {'^%^=',tdump}, {'^::',tdump}, {'^.',tdump} } end return lexer.scan(s,cpp_matches,filter,options) end --- get a list of parameters separated by a delimiter from a stream. -- @param tok the token stream -- @string[opt=')'] endtoken end of list. Can be '\n' -- @string[opt=','] delim separator -- @return a list of token lists. function lexer.get_separated_list(tok,endtoken,delim) endtoken = endtoken or ')' delim = delim or ',' local parm_values = {} local level = 1 -- used to count ( and ) local tl = {} local function tappend (tl,t,val) val = val or t append(tl,{t,val}) end local is_end if endtoken == '\n' then is_end = function(t,val) return t == 'space' and val:find '\n' end else is_end = function (t) return t == endtoken end end local token,value while true do token,value=tok() if not token then return nil,'EOS' end -- end of stream is an error! if is_end(token,value) and level == 1 then append(parm_values,tl) break elseif token == '(' then level = level + 1 tappend(tl,'(') elseif token == ')' then level = level - 1 if level == 0 then -- finished with parm list append(parm_values,tl) break else tappend(tl,')') end elseif token == delim and level == 1 then append(parm_values,tl) -- a new parm tl = {} else tappend(tl,token,value) end end return parm_values,{token,value} end --- get the next non-space token from the stream. -- @param tok the token stream. function lexer.skipws (tok) local t,v = tok() while t == 'space' do t,v = tok() end return t,v end local skipws = lexer.skipws --- get the next token, which must be of the expected type. -- Throws an error if this type does not match! -- @param tok the token stream -- @string expected_type the token type -- @bool no_skip_ws whether we should skip whitespace function lexer.expecting (tok,expected_type,no_skip_ws) assert_arg(1,tok,'function') assert_arg(2,expected_type,'string') local t,v if no_skip_ws then t,v = tok() else t,v = skipws(tok) end if t ~= expected_type then error ("expecting "..expected_type,2) end return v end return lexer
agpl-3.0
SalvationDevelopment/Salvation-Scripts-TCG
c41113025.lua
5
1119
--ディスクライダー function c41113025.initial_effect(c) --atkup local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(41113025,0)) e1:SetCategory(CATEGORY_ATKCHANGE) e1:SetType(EFFECT_TYPE_IGNITION) e1:SetRange(LOCATION_MZONE) e1:SetCountLimit(1) e1:SetCost(c41113025.cost) e1:SetOperation(c41113025.operation) c:RegisterEffect(e1) end function c41113025.cfilter(c) return c:GetType()==TYPE_TRAP and c:IsAbleToRemoveAsCost() end function c41113025.cost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c41113025.cfilter,tp,LOCATION_GRAVE,0,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE) local cg=Duel.SelectMatchingCard(tp,c41113025.cfilter,tp,LOCATION_GRAVE,0,1,1,nil) Duel.Remove(cg,POS_FACEUP,REASON_COST) end function c41113025.operation(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if c:IsFaceup() and c:IsRelateToEffect(e) then local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_UPDATE_ATTACK) e1:SetValue(500) e1:SetReset(RESET_EVENT+0x1ff0000+RESET_PHASE+PHASE_END,2) c:RegisterEffect(e1) end end
gpl-2.0
SalvationDevelopment/Salvation-Scripts-TCG
c31247589.lua
2
1854
--剣闘獣ディカエリィ function c31247589.initial_effect(c) --double attack local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_EXTRA_ATTACK) e1:SetCondition(c31247589.dacon) e1:SetValue(1) c:RegisterEffect(e1) --special summon local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(31247589,0)) e2:SetCategory(CATEGORY_SPECIAL_SUMMON) e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O) e2:SetCode(EVENT_PHASE+PHASE_BATTLE) e2:SetRange(LOCATION_MZONE) e2:SetCondition(c31247589.spcon) e2:SetCost(c31247589.spcost) e2:SetTarget(c31247589.sptg) e2:SetOperation(c31247589.spop) c:RegisterEffect(e2) end function c31247589.dacon(e) return e:GetHandler():GetFlagEffect(31247589)>0 end function c31247589.spcon(e,tp,eg,ep,ev,re,r,rp) return e:GetHandler():GetBattledGroupCount()>0 end function c31247589.spcost(e,tp,eg,ep,ev,re,r,rp,chk) local c=e:GetHandler() if chk==0 then return c:IsAbleToDeckAsCost() end Duel.SendtoDeck(c,nil,2,REASON_COST) end function c31247589.filter(c,e,tp) return not c:IsCode(31247589) and c:IsSetCard(0x19) and c:IsCanBeSpecialSummoned(e,107,tp,false,false) end function c31247589.sptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>-1 and Duel.IsExistingMatchingCard(c31247589.filter,tp,LOCATION_DECK,0,1,nil,e,tp) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,0,LOCATION_DECK) end function c31247589.spop(e,tp,eg,ep,ev,re,r,rp) if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectMatchingCard(tp,c31247589.filter,tp,LOCATION_DECK,0,1,1,nil,e,tp) local tc=g:GetFirst() if tc then Duel.SpecialSummon(tc,107,tp,tp,false,false,POS_FACEUP) tc:RegisterFlagEffect(tc:GetOriginalCode(),RESET_EVENT+0x1ff0000,0,0) end end
gpl-2.0
dickeyf/darkstar
scripts/zones/Xarcabard_[S]/mobs/Fusty_Gnole.lua
13
1699
----------------------------------- -- Area: Xarcabard (S) -- NPC: Fusty Gnole ----------------------------------- ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) mob:setLocalVar("transformTime", os.time()) end; ----------------------------------- -- onMobRoam Action ----------------------------------- function onMobRoam(mob) local transformTime = mob:getLocalVar("transformTime"); local roamChance = math.random(1,100); local roamMoonPhase = VanadielMoonPhase(); if (roamChance > 100-roamMoonPhase) then if (mob:AnimationSub() == 0 and os.time() - transformTime > 300) then mob:AnimationSub(1); mob:setLocalVar("transformTime", os.time()); elseif (mob:AnimationSub() == 1 and os.time() - transformTime > 300) then mob:AnimationSub(0); mob:setLocalVar("transformTime", os.time()); end end end; ----------------------------------- -- onMobEngaged -- Change forms every 60 seconds ----------------------------------- function onMobEngaged(mob,target) local changeTime = mob:getLocalVar("changeTime"); local chance = math.random(1,100); local moonPhase = VanadielMoonPhase(); if (chance > 100-moonPhase) then if (mob:AnimationSub() == 0 and mob:getBattleTime() - changeTime > 45) then mob:AnimationSub(1); mob:setLocalVar("changeTime", mob:getBattleTime()); elseif (mob:AnimationSub() == 1 and mob:getBattleTime() - changeTime > 45) then mob:AnimationSub(0); mob:setLocalVar("changeTime", mob:getBattleTime()); end end end;
gpl-3.0
SalvationDevelopment/Salvation-Scripts-TCG
c78355370.lua
2
3560
--クリボーン function c78355370.initial_effect(c) --special summon local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(78355370,0)) e1:SetCategory(CATEGORY_SPECIAL_SUMMON) e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetCode(EVENT_PHASE+PHASE_BATTLE) e1:SetRange(LOCATION_HAND) e1:SetCost(c78355370.spcost1) e1:SetTarget(c78355370.sptg1) e1:SetOperation(c78355370.spop1) c:RegisterEffect(e1) --special summon local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(78355370,1)) e2:SetCategory(CATEGORY_SPECIAL_SUMMON) e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O) e2:SetProperty(EFFECT_FLAG_CARD_TARGET) e2:SetCode(EVENT_ATTACK_ANNOUNCE) e2:SetRange(LOCATION_GRAVE) e2:SetCondition(c78355370.spcon2) e2:SetCost(c78355370.spcost2) e2:SetTarget(c78355370.sptg2) e2:SetOperation(c78355370.spop2) c:RegisterEffect(e2) end function c78355370.spcost1(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():IsDiscardable() end Duel.SendtoGrave(e:GetHandler(),REASON_COST+REASON_DISCARD) end function c78355370.spfilter1(c,e,tp,tid) return c:GetTurnID()==tid and bit.band(c:GetReason(),REASON_BATTLE)~=0 and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function c78355370.sptg1(e,tp,eg,ep,ev,re,r,rp,chk,chkc) local tid=Duel.GetTurnCount() if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c78355370.spfilter1(chkc,e,tp,tid) end if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingTarget(c78355370.spfilter1,tp,LOCATION_GRAVE,0,1,nil,e,tp,tid) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectTarget(tp,c78355370.spfilter1,tp,LOCATION_GRAVE,0,1,1,nil,e,tp,tid) Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0) end function c78355370.spop1(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) then Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP) end end function c78355370.spcon2(e,tp,eg,ep,ev,re,r,rp) return Duel.GetAttacker():GetControler()~=tp end function c78355370.spcost2(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():IsAbleToRemoveAsCost() end Duel.Remove(e:GetHandler(),POS_FACEUP,REASON_COST) end function c78355370.spfilter2(c,e,tp) return c:IsSetCard(0xa4) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) and c:IsType(TYPE_MONSTER) end function c78355370.sptg2(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c78355370.spfilter2(chkc,e,tp) end if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingTarget(c78355370.spfilter2,tp,LOCATION_GRAVE,0,1,e:GetHandler(),e,tp) end local ft=Duel.GetLocationCount(tp,LOCATION_MZONE) if Duel.IsPlayerAffectedByEffect(tp,59822133) then ft=1 end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectTarget(tp,c78355370.spfilter2,tp,LOCATION_GRAVE,0,1,ft,nil,e,tp) Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,g:GetCount(),0,0) end function c78355370.spop2(e,tp,eg,ep,ev,re,r,rp) local ft=Duel.GetLocationCount(tp,LOCATION_MZONE) if ft<=0 then return end local g=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS):Filter(Card.IsRelateToEffect,nil,e) if g:GetCount()>1 and Duel.IsPlayerAffectedByEffect(tp,59822133) then return end if g:GetCount()>ft then Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) g=g:Select(tp,ft,ft,nil) end if g:GetCount()>0 then Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP) end end
gpl-2.0
Turttle/darkstar
scripts/zones/Lower_Jeuno/npcs/Panta-Putta.lua
17
4082
----------------------------------- -- Area: Lower Jeuno -- NPC: Panta-Putta -- Starts and Finishes Quest: The Wonder Magic Set, The kind cardian -- Involved in Quests: The Lost Cardian -- @zone 245 -- @pos -61 0 -140 ----------------------------------- package.loaded["scripts/zones/Lower_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/quests"); require("scripts/zones/Lower_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) TheWonderMagicSet = player:getQuestStatus(JEUNO,THE_WONDER_MAGIC_SET); WonderMagicSetKI = player:hasKeyItem(WONDER_MAGIC_SET); TheLostCardianCS = player:getVar("theLostCardianVar"); TheKindCardian = player:getQuestStatus(JEUNO,THE_KIND_CARDIAN); if (player:getFameLevel(JEUNO) >= 4 and TheWonderMagicSet == QUEST_AVAILABLE) then player:startEvent(0x004D); -- Start quest "The wonder magic set" elseif (TheWonderMagicSet == QUEST_ACCEPTED and WonderMagicSetKI == false) then player:startEvent(0x0037); -- During quest "The wonder magic set" elseif (WonderMagicSetKI == true) then player:startEvent(0x0021); -- Finish quest "The wonder magic set" elseif (TheWonderMagicSet == QUEST_COMPLETED and player:getQuestStatus(JEUNO,COOK_S_PRIDE) ~= QUEST_COMPLETED) then player:startEvent(0x0028); -- Standard dialog elseif (TheWonderMagicSet == QUEST_COMPLETED and player:getQuestStatus(JEUNO,THE_LOST_CARDIAN) == QUEST_AVAILABLE) then if (TheLostCardianCS >= 1) then player:startEvent(0x001E); -- Second dialog for "The lost cardien" quest else player:startEvent(0x0028); -- Standard dialog end elseif (TheKindCardian == QUEST_ACCEPTED and player:getVar("theKindCardianVar") == 2) then player:startEvent(0x0023); -- Finish quest "The kind cardien" elseif (TheKindCardian == QUEST_COMPLETED) then player:startEvent(0x004C); -- New standard dialog after "The kind cardien" else player:startEvent(0x004E); -- Base standard dialog end end; -- 0x004E oh zut j'ai besoin de cette marmite -- 0x001E j'ai été trop dur avec two... et percé la marmite -- 0x0028 du moment que j'ai cette boite et la marmite je vais enfin battre ce gars ----------------------------------- -- 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 == 0x004D and option == 1) then player:addQuest(JEUNO,THE_WONDER_MAGIC_SET); elseif (csid == 0x0021) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,13328); else player:addTitle(FOOLS_ERRAND_RUNNER); player:delKeyItem(WONDER_MAGIC_SET); player:addItem(13328); player:messageSpecial(ITEM_OBTAINED,13328); player:addFame(JEUNO, JEUNO_FAME*30); player:needToZone(true); player:completeQuest(JEUNO,THE_WONDER_MAGIC_SET); end elseif (csid == 0x001E) then player:setVar("theLostCardianVar",2); elseif (csid == 0x0023) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,13596); else player:addTitle(BRINGER_OF_BLISS); player:delKeyItem(TWO_OF_SWORDS); player:setVar("theKindCardianVar",0); player:addItem(13596); player:messageSpecial(ITEM_OBTAINED,13596); -- Green Cape player:addFame(JEUNO, JEUNO_FAME*30); player:completeQuest(JEUNO,THE_KIND_CARDIAN); end end end;
gpl-3.0
Andrey2470T/Advanced-Trains-Optinal-Additional-
advtrains/helpers.lua
2
8687
--advtrains by orwell96, see readme.txt advtrains.dir_trans_tbl={ [0]={x=0, z=1}, [1]={x=1, z=2}, [2]={x=1, z=1}, [3]={x=2, z=1}, [4]={x=1, z=0}, [5]={x=2, z=-1}, [6]={x=1, z=-1}, [7]={x=1, z=-2}, [8]={x=0, z=-1}, [9]={x=-1, z=-2}, [10]={x=-1, z=-1}, [11]={x=-2, z=-1}, [12]={x=-1, z=0}, [13]={x=-2, z=1}, [14]={x=-1, z=1}, [15]={x=-1, z=2}, } function advtrains.dirCoordSet(coord, dir) local x,z if advtrains.dir_trans_tbl[dir] then x,z=advtrains.dir_trans_tbl[dir].x, advtrains.dir_trans_tbl[dir].z else error("advtrains: in helpers.lua/dirCoordSet() given dir="..(dir or "nil")) end return {x=coord.x+x, y=coord.y, z=coord.z+z} end function advtrains.dirToCoord(dir) return advtrains.dirCoordSet({x=0, y=0, z=0}, dir) end function advtrains.maxN(list, expectstart) local n=expectstart or 0 while list[n] do n=n+1 end return n-1 end function advtrains.minN(list, expectstart) local n=expectstart or 0 while list[n] do n=n-1 end return n+1 end --vertical_transmit: --[[ rely1, rely2 tell to which height the connections are pointed to. 1 means it will go up the next node ]] function advtrains.conway(midreal, prev, drives_on)--in order prev,mid,return local mid=advtrains.round_vector_floor_y(midreal) local midnode_ok, middir1, middir2, midrely1, midrely2=advtrains.get_rail_info_at(mid, drives_on) if not midnode_ok then return nil end local next, chkdir, chkrely, y_offset y_offset=0 --atprint(" in order mid1,mid2",middir1,middir2) --try if it is dir1 local cor1=advtrains.dirCoordSet(mid, middir2)--<<<< if cor1.x==prev.x and cor1.z==prev.z then--this was previous next=advtrains.dirCoordSet(mid, middir1) if midrely1>=1 then next.y=next.y+1 --atprint("found midrely1 to be >=1: next is now "..(next and minetest.pos_to_string(next) or "nil")) y_offset=1 end chkdir=middir1 chkrely=midrely1 --atprint("dir2 applied next pos:",minetest.pos_to_string(next),"(chkdir is ",chkdir,")") end --dir2??? local cor2=advtrains.dirCoordSet(mid, middir1)--<<<< if math.floor(cor2.x+0.5)==math.floor(prev.x+0.5) and math.floor(cor2.z+0.5)==math.floor(prev.z+0.5) then next=advtrains.dirCoordSet(mid, middir2)--dir2 wird überprüft, alles gut. if midrely2>=1 then next.y=next.y+1 --atprint("found midrely2 to be >=1: next is now "..(next and minetest.pos_to_string(next) or "nil")) y_offset=1 end chkdir=middir2 chkrely=midrely2 --atprint(" dir2 applied next pos:",minetest.pos_to_string(next),"(chkdir is ",chkdir,")") end --atprint("dir applied next pos: "..(next and minetest.pos_to_string(next) or "nil").."(chkdir is "..(chkdir or "nil")..", y-offset "..y_offset..")") --is there a next if not next then --atprint("in conway: no next rail(nil), returning!") return nil end local nextnode_ok, nextdir1, nextdir2, nextrely1, nextrely2, nextrailheight=advtrains.get_rail_info_at(advtrains.round_vector_floor_y(next), drives_on) --is it a rail? if(not nextnode_ok) then --atprint("in conway: next "..minetest.pos_to_string(next).." not a rail, trying one node below!") next.y=next.y-1 y_offset=y_offset-1 nextnode_ok, nextdir1, nextdir2, nextrely1, nextrely2, nextrailheight=advtrains.get_rail_info_at(advtrains.round_vector_floor_y(next), drives_on) if(not nextnode_ok) then --atprint("in conway: one below "..minetest.pos_to_string(next).." is not a rail either, returning!") return nil end end --is this next rail connecting to the mid? if not ( (((nextdir1+8)%16)==chkdir and nextrely1==chkrely-y_offset) or (((nextdir2+8)%16)==chkdir and nextrely2==chkrely-y_offset) ) then --atprint("in conway: next "..minetest.pos_to_string(next).." not connecting, trying one node below!") next.y=next.y-1 y_offset=y_offset-1 nextnode_ok, nextdir1, nextdir2, nextrely1, nextrely2, nextrailheight=advtrains.get_rail_info_at(advtrains.round_vector_floor_y(next), drives_on) if(not nextnode_ok) then --atprint("in conway: (at connecting if check again) one below "..minetest.pos_to_string(next).." is not a rail either, returning!") return nil end if not ( (((nextdir1+8)%16)==chkdir and nextrely1==chkrely) or (((nextdir2+8)%16)==chkdir and nextrely2==chkrely) ) then --atprint("in conway: one below "..minetest.pos_to_string(next).." rail not connecting, returning!") --atprint(" in order mid1,2,next1,2,chkdir "..middir1.." "..middir2.." "..nextdir1.." "..nextdir2.." "..chkdir) return nil end end --atprint("conway found rail.") return vector.add(advtrains.round_vector_floor_y(next), {x=0, y=nextrailheight, z=0}), chkdir end --TODO use this function advtrains.oppd(dir) return ((dir+8)%16) end function advtrains.round_vector_floor_y(vec) return {x=math.floor(vec.x+0.5), y=math.floor(vec.y), z=math.floor(vec.z+0.5)} end function advtrains.yawToDirection(yaw, conn1, conn2) if not conn1 or not conn2 then error("given nil to yawToDirection: conn1="..(conn1 or "nil").." conn2="..(conn1 or "nil")) end local yaw1=math.pi*(conn1/4) local yaw2=math.pi*(conn2/4) if advtrains.minAngleDiffRad(yaw, yaw1)<advtrains.minAngleDiffRad(yaw, yaw2) then--change to > if weird behavior return conn2 else return conn1 end end function advtrains.minAngleDiffRad(r1, r2) local try1=r2-r1 local try2=(r2+2*math.pi)-r1 local try3=r2-(r1+2*math.pi) if math.min(math.abs(try1), math.abs(try2), math.abs(try3))==math.abs(try1) then return try1 end if math.min(math.abs(try1), math.abs(try2), math.abs(try3))==math.abs(try2) then return try2 end if math.min(math.abs(try1), math.abs(try2), math.abs(try3))==math.abs(try3) then return try3 end end function advtrains.dumppath(path) if not path then atprint("dumppath: no path(nil)") return end local min=advtrains.minN(path) local max=advtrains.maxN(path) for i=min, max do atprint("["..i.."] "..(path[i] and minetest.pos_to_string(path[i]) or "nil")) end end function advtrains.merge_tables(a, ...) local new={} for _,t in ipairs({a,...}) do for k,v in pairs(t) do new[k]=v end end return new end function advtrains.yaw_from_3_positions(prev, curr, next) local pts=minetest.pos_to_string --atprint("p3 "..pts(prev)..pts(curr)..pts(next)) local prev2curr=math.atan2((curr.x-prev.x), (prev.z-curr.z)) local curr2next=math.atan2((next.x-curr.x), (curr.z-next.z)) --atprint("y3 "..(prev2curr*360/(2*math.pi)).." "..(curr2next*360/(2*math.pi))) return prev2curr+(advtrains.minAngleDiffRad(prev2curr, curr2next)/2) end function advtrains.get_wagon_yaw(front, first, second, back, pct) local pts=minetest.pos_to_string --atprint("p "..pts(front)..pts(first)..pts(second)..pts(back)) local y2=advtrains.yaw_from_3_positions(second, first, front) local y1=advtrains.yaw_from_3_positions(back, second, first) --atprint("y "..(y1*360/(2*math.pi)).." "..(y2*360/(2*math.pi))) return y1+advtrains.minAngleDiffRad(y1, y2)*pct end function advtrains.get_real_index_position(path, index) if not path or not index then return end local first_pos=path[math.floor(index)] local second_pos=path[math.floor(index)+1] if not first_pos or not second_pos then return nil end local factor=index-math.floor(index) local actual_pos={x=first_pos.x-(first_pos.x-second_pos.x)*factor, y=first_pos.y-(first_pos.y-second_pos.y)*factor, z=first_pos.z-(first_pos.z-second_pos.z)*factor,} return actual_pos end function advtrains.pos_median(pos1, pos2) return {x=pos1.x-(pos1.x-pos2.x)*0.5, y=pos1.y-(pos1.y-pos2.y)*0.5, z=pos1.z-(pos1.z-pos2.z)*0.5} end function advtrains.abs_ceil(i) return math.ceil(math.abs(i))*math.sign(i) end function advtrains.serialize_inventory(inv) local ser={} local liszts=inv:get_lists() for lisztname, liszt in pairs(liszts) do ser[lisztname]={} for idx, item in ipairs(liszt) do local istring=item:to_string() if istring~="" then ser[lisztname][idx]=istring end end end return minetest.serialize(ser) end function advtrains.deserialize_inventory(sers, inv) local ser=minetest.deserialize(sers) if ser then inv:set_lists(ser) return true end return false end --is_protected wrapper that checks for protection_bypass privilege function advtrains.is_protected(pos, name) if not name then error("advtrains.is_protected() called without name parameter!") end if minetest.check_player_privs(name, {protection_bypass=true}) then --player can bypass protection return false end return minetest.is_protected(pos, name) end
lgpl-2.1
Turttle/darkstar
scripts/zones/West_Ronfaure/mobs/Scarab_Beetle.lua
23
1074
----------------------------------- -- Area: West Ronfaure(100) -- MOB: Scarab Beetle -- Note: Place holder for Fungus Beetle ----------------------------------- require("scripts/globals/fieldsofvalor"); require("scripts/zones/West_Ronfaure/MobIDs"); ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) checkRegime(killer,mob,3,1); checkRegime(killer,mob,4,2); mob = mob:getID(); if (Fungus_Beetle_PH[mob] ~= nil) then printf("Action:%u:%u",Fungus_Beetle,GetMobAction(Fungus_Beetle)); ToD = GetServerVariable("[POP]Fungus_Beetle"); if (ToD <= os.time(t) and GetMobAction(Fungus_Beetle) == 0) then if (math.random((1),(10)) == 5) then UpdateNMSpawnPoint(Fungus_Beetle); GetMobByID(Fungus_Beetle):setRespawnTime(GetMobRespawnTime(mob)); SetServerVariable("[PH]Fungus_Beetle", mob); DeterMob(mob, true); end end end end;
gpl-3.0
dickeyf/darkstar
scripts/zones/Port_Windurst/npcs/Odilia.lua
13
1044
----------------------------------- -- Area: Port Windurst -- NPC: Odilia -- Type: Standard NPC -- @zone: 240 -- @pos 78.801 -6 118.653 -- -- Auto-Script: Requires Verification (Verfied By Brawndo) ----------------------------------- package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0121); 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
SalvationDevelopment/Salvation-Scripts-TCG
c76263644.lua
3
3110
--Dragoon D-END function c76263644.initial_effect(c) --fusion material c:EnableReviveLimit() aux.AddFusionProcCode2(c,83965310,17132130,false,false) --destroy local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_IGNITION) e2:SetProperty(EFFECT_FLAG_CARD_TARGET) e2:SetCategory(CATEGORY_DAMAGE+CATEGORY_DESTROY) e2:SetDescription(aux.Stringid(76263644,0)) e2:SetCountLimit(1) e2:SetRange(LOCATION_MZONE) e2:SetCost(c76263644.descost) e2:SetTarget(c76263644.destg) e2:SetOperation(c76263644.desop) c:RegisterEffect(e2) --Special Summon local e3=Effect.CreateEffect(c) e3:SetDescription(aux.Stringid(76263644,1)) e3:SetType(EFFECT_TYPE_TRIGGER_O+EFFECT_TYPE_FIELD) e3:SetCategory(CATEGORY_SPECIAL_SUMMON) e3:SetCode(EVENT_PHASE+PHASE_STANDBY) e3:SetRange(LOCATION_GRAVE) e3:SetCountLimit(1) e3:SetCondition(c76263644.spcon) e3:SetCost(c76263644.spcost) e3:SetTarget(c76263644.sptg) e3:SetOperation(c76263644.spop) c:RegisterEffect(e3) end c76263644.material_setcode=0x8 function c76263644.descost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetActivityCount(tp,ACTIVITY_BATTLE_PHASE)==0 end local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_FIELD) e1:SetCode(EFFECT_CANNOT_BP) e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET) e1:SetTargetRange(1,0) e1:SetReset(RESET_PHASE+PHASE_END) Duel.RegisterEffect(e1,tp) end function c76263644.destg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(1-tp) end if chk==0 then return Duel.IsExistingTarget(aux.TRUE,tp,0,LOCATION_MZONE,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY) local g=Duel.SelectTarget(tp,aux.TRUE,tp,0,LOCATION_MZONE,1,1,nil) local d=g:GetFirst() local atk=0 if d:IsFaceup() then atk=d:GetAttack() end Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,1,0,0) Duel.SetOperationInfo(0,CATEGORY_DAMAGE,nil,0,1-tp,atk) end function c76263644.desop(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) then local atk=0 if tc:IsFaceup() then atk=tc:GetAttack() end if Duel.Destroy(tc,REASON_EFFECT)==0 then return end Duel.Damage(1-tp,atk,REASON_EFFECT) end end function c76263644.spcon(e,tp,eg,ep,ev,re,r,rp) return Duel.GetTurnPlayer()==tp end function c76263644.spcost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c76263644.spfilter,tp,LOCATION_GRAVE,0,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE) local g=Duel.SelectMatchingCard(tp,c76263644.spfilter,tp,LOCATION_GRAVE,0,1,1,nil) Duel.Remove(g,POS_FACEUP,REASON_COST) end function c76263644.spfilter(c) return c:IsSetCard(0xc008) and c:IsAbleToRemoveAsCost() end function c76263644.sptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,false,false) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0) end function c76263644.spop(e,tp,eg,ep,ev,re,r,rp) if e:GetHandler():IsRelateToEffect(e) then Duel.SpecialSummon(e:GetHandler(),0,tp,tp,false,false,POS_FACEUP) end end
gpl-2.0
puug/kong
kong/plugins/cors/access.lua
1
1784
local responses = require "kong.tools.responses" local _M = {} local function configure_origin(ngx, conf) if conf.origin == nil then ngx.header["Access-Control-Allow-Origin"] = "*" else ngx.header["Access-Control-Allow-Origin"] = conf.origin ngx.header["Vary"] = "Origin" end end local function configure_credentials(ngx, conf) if (conf.credentials) then ngx.header["Access-Control-Allow-Credentials"] = "true" end end local function configure_headers(ngx, conf, headers) if conf.headers == nil then ngx.header["Access-Control-Allow-Headers"] = headers['access-control-request-headers'] or "" else ngx.header["Access-Control-Allow-Headers"] = conf.headers end end local function configure_exposed_headers(ngx, conf) if conf.exposed_headers ~= nil then ngx.header["Access-Control-Expose-Headers"] = conf.exposed_headers end end local function configure_methods(ngx, conf) if conf.methods ~= nil then ngx.header["Access-Control-Allow-Methods"] = conf.methods else ngx.header["Access-Control-Allow-Methods"] = "GET,HEAD,PUT,PATCH,POST,DELETE" end end local function configure_max_age(ngx, conf) if conf.max_age ~= nil then ngx.header["Access-Control-Max-Age"] = tostring(conf.max_age) end end function _M.execute(conf) local request = ngx.req local method = request.get_method() local headers = request.get_headers() configure_origin(ngx, conf) configure_credentials(ngx, conf) if method == "OPTIONS" then -- Preflight configure_headers(ngx, conf, headers) configure_methods(ngx, conf) configure_max_age(ngx, conf) if not conf.preflight_continue then return responses.send_HTTP_NO_CONTENT() end else configure_exposed_headers(ngx, conf) end end return _M
mit
erictheredsu/eric_git
MGCN/wow/WTF/Account/ERIC/Mangoscn/Erica/SavedVariables/BaudBag.lua
1
23844
BaudBag_Cfg = { { { ["AutoOpen"] = false, ["Name"] = "Erica 的背包", ["Columns"] = 8, ["BlankTop"] = false, ["RarityColor"] = true, ["Coords"] = { 797.1558227539063, -- [1] 364.0889587402344, -- [2] }, ["Background"] = 1, ["Scale"] = 100, }, -- [1] { ["AutoOpen"] = false, ["Scale"] = 100, ["Name"] = "Erica 的背包", ["Background"] = 1, ["RarityColor"] = true, ["Coords"] = { 797.1558227539063, -- [1] 364.0889587402344, -- [2] }, ["BlankTop"] = false, ["Columns"] = 8, }, -- [2] { ["BlankTop"] = false, ["Name"] = "Erica 的背包", ["Columns"] = 8, ["AutoOpen"] = false, ["Scale"] = 100, ["Background"] = 1, ["Coords"] = { 797.1558227539063, -- [1] 364.0889587402344, -- [2] }, ["RarityColor"] = true, }, -- [3] { ["BlankTop"] = false, ["RarityColor"] = true, ["Name"] = "Erica 的背包", ["Coords"] = { 797.1558227539063, -- [1] 364.0889587402344, -- [2] }, ["Scale"] = 100, ["Background"] = 1, ["AutoOpen"] = false, ["Columns"] = 8, }, -- [4] { ["AutoOpen"] = false, ["Scale"] = 100, ["Name"] = "Erica 的背包", ["Background"] = 1, ["RarityColor"] = true, ["Coords"] = { 578.8447265625, -- [1] 259.5556945800781, -- [2] }, ["BlankTop"] = false, ["Columns"] = 8, }, -- [5] { ["AutoOpen"] = false, ["Scale"] = 100, ["Name"] = "Erica 的背包", ["Background"] = 1, ["RarityColor"] = true, ["Coords"] = { 442.3112487792969, -- [1] 401.7777099609375, -- [2] }, ["BlankTop"] = false, ["Columns"] = 8, }, -- [6] ["Enabled"] = false, ["Joined"] = { nil, -- [1] false, -- [2] false, -- [3] false, -- [4] false, -- [5] false, -- [6] }, ["ShowBags"] = false, }, -- [1] { { ["AutoOpen"] = true, ["Name"] = "Erica 的银行", ["Columns"] = 12, ["BlankTop"] = false, ["RarityColor"] = true, ["Coords"] = { 312.8889465332031, -- [1] 275.9111022949219, -- [2] }, ["Background"] = 1, ["Scale"] = 100, }, -- [1] ["Enabled"] = true, ["Joined"] = { [8] = true, }, ["ShowBags"] = true, }, -- [2] } BaudBag_Cache = { [5] = { { ["Count"] = 15, ["Link"] = "|cff1eff00|Hitem:7909:0:0:0:0:0:0:0|h[青绿石]|h|r", }, -- [1] { ["Count"] = 6, ["Link"] = "|cff1eff00|Hitem:7971:0:0:0:0:0:0:0|h[黑珍珠]|h|r", }, -- [2] { ["Count"] = 16, ["Link"] = "|cff1eff00|Hitem:3864:0:0:0:0:0:0:0|h[黄水晶]|h|r", }, -- [3] { ["Count"] = 20, ["Link"] = "|cff1eff00|Hitem:3864:0:0:0:0:0:0:0|h[黄水晶]|h|r", }, -- [4] { ["Count"] = 20, ["Link"] = "|cff1eff00|Hitem:3864:0:0:0:0:0:0:0|h[黄水晶]|h|r", }, -- [5] { ["Count"] = 4, ["Link"] = "|cff1eff00|Hitem:13926:0:0:0:0:0:0:0|h[金珍珠]|h|r", }, -- [6] { ["Count"] = 18, ["Link"] = "|cff1eff00|Hitem:24478:0:0:0:0:0:0:0|h[裂纹的珍珠]|h|r", }, -- [7] { ["Count"] = 2, ["Link"] = "|cff1eff00|Hitem:24479:0:0:0:0:0:0:0|h[暗影珍珠]|h|r", }, -- [8] { ["Count"] = 8, ["Link"] = "|cff1eff00|Hitem:1529:0:0:0:0:0:0:0|h[翡翠]|h|r", }, -- [9] { ["Count"] = 12, ["Link"] = "|cff1eff00|Hitem:1705:0:0:0:0:0:0:0|h[次级月亮石]|h|r", }, -- [10] { ["Count"] = 4, ["Link"] = "|cff1eff00|Hitem:1206:0:0:0:0:0:0:0|h[绿玛瑙]|h|r", }, -- [11] { ["Count"] = 1, ["Link"] = "|cff1eff00|Hitem:5500:0:0:0:0:0:0:0|h[彩色珍珠]|h|r", }, -- [12] { ["Count"] = 11, ["Link"] = "|cff1eff00|Hitem:1210:0:0:0:0:0:0:0|h[暗影石]|h|r", }, -- [13] { ["Count"] = 5, ["Link"] = "|cff1eff00|Hitem:818:0:0:0:0:0:0:0|h[虎眼石]|h|r", }, -- [14] { ["Count"] = 2, ["Link"] = "|cff1eff00|Hitem:5498:0:0:0:0:0:0:0|h[有光泽的小珍珠]|h|r", }, -- [15] { ["Count"] = 7, ["Link"] = "|cff1eff00|Hitem:774:0:0:0:0:0:0:0|h[孔雀石]|h|r", }, -- [16] { ["Count"] = 10, ["Link"] = "|cff1eff00|Hitem:21929:0:0:0:0:0:0:0|h[火榴石]|h|r", }, -- [17] { ["Count"] = 2, ["Link"] = "|cff1eff00|Hitem:23427:0:0:0:0:0:0:0|h[恒金矿石]|h|r", }, -- [18] { ["Count"] = 16, ["Link"] = "|cff1eff00|Hitem:23447:0:0:0:0:0:0:0|h[恒金锭]|h|r", }, -- [19] { ["Count"] = 20, ["Link"] = "|cff1eff00|Hitem:23449:0:0:0:0:0:0:0|h[氪金锭]|h|r", }, -- [20] { ["Count"] = 16, ["Link"] = "|cff1eff00|Hitem:6037:0:0:0:0:0:0:0|h[真银锭]|h|r", }, -- [21] { ["Count"] = 20, ["Link"] = "|cff1eff00|Hitem:6037:0:0:0:0:0:0:0|h[真银锭]|h|r", }, -- [22] { ["Count"] = 20, ["Link"] = "|cff1eff00|Hitem:6037:0:0:0:0:0:0:0|h[真银锭]|h|r", }, -- [23] { ["Count"] = 20, ["Link"] = "|cff1eff00|Hitem:6037:0:0:0:0:0:0:0|h[真银锭]|h|r", }, -- [24] { ["Count"] = 20, ["Link"] = "|cff1eff00|Hitem:3577:0:0:0:0:0:0:0|h[金锭]|h|r", }, -- [25] { ["Count"] = 3, ["Link"] = "|cff1eff00|Hitem:3577:0:0:0:0:0:0:0|h[金锭]|h|r", }, -- [26] { ["Count"] = 20, ["Link"] = "|cff1eff00|Hitem:3577:0:0:0:0:0:0:0|h[金锭]|h|r", }, -- [27] { ["Count"] = 20, ["Link"] = "|cff1eff00|Hitem:3577:0:0:0:0:0:0:0|h[金锭]|h|r", }, -- [28] { ["Count"] = 20, ["Link"] = "|cff1eff00|Hitem:3577:0:0:0:0:0:0:0|h[金锭]|h|r", }, -- [29] { ["Count"] = 20, ["Link"] = "|cff1eff00|Hitem:3577:0:0:0:0:0:0:0|h[金锭]|h|r", }, -- [30] { ["Count"] = 15, ["Link"] = "|cff1eff00|Hitem:2842:0:0:0:0:0:0:0|h[银锭]|h|r", }, -- [31] { ["Count"] = 20, ["Link"] = "|cff1eff00|Hitem:2842:0:0:0:0:0:0:0|h[银锭]|h|r", }, -- [32] { ["Count"] = 1, ["Link"] = "|cff1eff00|Hitem:12811:0:0:0:0:0:0:0|h[正义宝珠]|h|r", }, -- [33] { ["Count"] = 2, ["Link"] = "|cff1eff00|Hitem:21884:0:0:0:0:0:0:0|h[源生火焰]|h|r", }, -- [34] { ["Count"] = 3, ["Link"] = "|cff1eff00|Hitem:22456:0:0:0:0:0:0:0|h[源生暗影]|h|r", }, -- [35] { ["Count"] = 20, ["Link"] = "|cff1eff00|Hitem:22452:0:0:0:0:0:0:0|h[源生之土]|h|r", }, -- [36] ["BagLink"] = "|cffffffff|Hitem:23162:0:0:0:0:0:0:0|h[弗洛尔的无尽抗性宝箱]|h|r", ["BagCount"] = 0, ["Size"] = 36, }, [6] = { { ["Count"] = 1, ["Link"] = "|cffffffff|Hitem:23162:0:0:0:0:0:0:0|h[弗洛尔的无尽抗性宝箱]|h|r", }, -- [1] { ["Count"] = 1, ["Link"] = "|cffffffff|Hitem:6265:0:0:0:0:0:0:0|h[灵魂碎片]|h|r", }, -- [2] { ["Count"] = 20, ["Link"] = "|cffffffff|Hitem:3859:0:0:0:0:0:0:0|h[钢锭]|h|r", }, -- [3] { ["Count"] = 20, ["Link"] = "|cffffffff|Hitem:3859:0:0:0:0:0:0:0|h[钢锭]|h|r", }, -- [4] { ["Count"] = 20, ["Link"] = "|cffffffff|Hitem:3859:0:0:0:0:0:0:0|h[钢锭]|h|r", }, -- [5] { ["Count"] = 20, ["Link"] = "|cffffffff|Hitem:3859:0:0:0:0:0:0:0|h[钢锭]|h|r", }, -- [6] { ["Count"] = 18, ["Link"] = "|cffffffff|Hitem:3859:0:0:0:0:0:0:0|h[钢锭]|h|r", }, -- [7] { ["Count"] = 20, ["Link"] = "|cffffffff|Hitem:3575:0:0:0:0:0:0:0|h[铁锭]|h|r", }, -- [8] { ["Count"] = 20, ["Link"] = "|cffffffff|Hitem:3575:0:0:0:0:0:0:0|h[铁锭]|h|r", }, -- [9] { ["Count"] = 14, ["Link"] = "|cffffffff|Hitem:23445:0:0:0:0:0:0:0|h[魔铁锭]|h|r", }, -- [10] { ["Count"] = 20, ["Link"] = "|cffffffff|Hitem:2841:0:0:0:0:0:0:0|h[青铜锭]|h|r", }, -- [11] { ["Count"] = 20, ["Link"] = "|cffffffff|Hitem:23446:0:0:0:0:0:0:0|h[精金锭]|h|r", }, -- [12] { ["Count"] = 20, ["Link"] = "|cffffffff|Hitem:23446:0:0:0:0:0:0:0|h[精金锭]|h|r", }, -- [13] { ["Count"] = 20, ["Link"] = "|cffffffff|Hitem:23446:0:0:0:0:0:0:0|h[精金锭]|h|r", }, -- [14] { ["Count"] = 10, ["Link"] = "|cffffffff|Hitem:23446:0:0:0:0:0:0:0|h[精金锭]|h|r", }, -- [15] { ["Count"] = 20, ["Link"] = "|cffffffff|Hitem:12359:0:0:0:0:0:0:0|h[瑟银锭]|h|r", }, -- [16] { ["Count"] = 19, ["Link"] = "|cffffffff|Hitem:12359:0:0:0:0:0:0:0|h[瑟银锭]|h|r", }, -- [17] { ["Count"] = 20, ["Link"] = "|cffffffff|Hitem:12359:0:0:0:0:0:0:0|h[瑟银锭]|h|r", }, -- [18] { ["Count"] = 20, ["Link"] = "|cffffffff|Hitem:12359:0:0:0:0:0:0:0|h[瑟银锭]|h|r", }, -- [19] { ["Count"] = 20, ["Link"] = "|cffffffff|Hitem:12359:0:0:0:0:0:0:0|h[瑟银锭]|h|r", }, -- [20] { ["Count"] = 20, ["Link"] = "|cffffffff|Hitem:12359:0:0:0:0:0:0:0|h[瑟银锭]|h|r", }, -- [21] { ["Count"] = 20, ["Link"] = "|cffffffff|Hitem:12359:0:0:0:0:0:0:0|h[瑟银锭]|h|r", }, -- [22] { ["Count"] = 20, ["Link"] = "|cffffffff|Hitem:12359:0:0:0:0:0:0:0|h[瑟银锭]|h|r", }, -- [23] { ["Count"] = 20, ["Link"] = "|cffffffff|Hitem:12359:0:0:0:0:0:0:0|h[瑟银锭]|h|r", }, -- [24] { ["Count"] = 20, ["Link"] = "|cffffffff|Hitem:12359:0:0:0:0:0:0:0|h[瑟银锭]|h|r", }, -- [25] { ["Count"] = 20, ["Link"] = "|cffffffff|Hitem:12359:0:0:0:0:0:0:0|h[瑟银锭]|h|r", }, -- [26] { ["Count"] = 20, ["Link"] = "|cffffffff|Hitem:12359:0:0:0:0:0:0:0|h[瑟银锭]|h|r", }, -- [27] { ["Count"] = 20, ["Link"] = "|cffffffff|Hitem:3860:0:0:0:0:0:0:0|h[秘银锭]|h|r", }, -- [28] { ["Count"] = 20, ["Link"] = "|cffffffff|Hitem:3860:0:0:0:0:0:0:0|h[秘银锭]|h|r", }, -- [29] { ["Count"] = 15, ["Link"] = "|cffffffff|Hitem:3576:0:0:0:0:0:0:0|h[锡锭]|h|r", }, -- [30] { ["Count"] = 20, ["Link"] = "|cffffffff|Hitem:3576:0:0:0:0:0:0:0|h[锡锭]|h|r", }, -- [31] { ["Count"] = 20, ["Link"] = "|cffffffff|Hitem:3576:0:0:0:0:0:0:0|h[锡锭]|h|r", }, -- [32] { ["Count"] = 19, ["Link"] = "|cffffffff|Hitem:2840:0:0:0:0:0:0:0|h[铜锭]|h|r", }, -- [33] { ["Count"] = 1, ["Link"] = "|cffffffff|Hitem:24243:0:0:0:0:0:0:0|h[精金粉]|h|r", }, -- [34] { ["Count"] = 11, ["Link"] = "|cffffffff|Hitem:20963:0:0:0:0:0:0:0|h[秘银丝]|h|r", }, -- [35] { ["Count"] = 20, ["Link"] = "|cffffffff|Hitem:20816:0:0:0:0:0:0:0|h[精巧的铜线]|h|r", }, -- [36] ["BagLink"] = "|cffffffff|Hitem:23162:0:0:0:0:0:0:0|h[弗洛尔的无尽抗性宝箱]|h|r", ["BagCount"] = 0, ["Size"] = 36, }, [7] = { { ["Count"] = 20, ["Link"] = "|cffffffff|Hitem:20816:0:0:0:0:0:0:0|h[精巧的铜线]|h|r", }, -- [1] { ["Count"] = 20, ["Link"] = "|cffffffff|Hitem:20817:0:0:0:0:0:0:0|h[青铜底座]|h|r", }, -- [2] { ["Count"] = 1, ["Link"] = "|cffffffff|Hitem:4611:0:0:0:0:0:0:0|h[蓝珍珠]|h|r", }, -- [3] { ["Count"] = 2, ["Link"] = "|cffffffff|Hitem:9262:0:0:0:0:0:0:0|h[黑色硫酸盐]|h|r", }, -- [4] { ["Count"] = 2, ["Link"] = "|cffffffff|Hitem:9262:0:0:0:0:0:0:0|h[黑色硫酸盐]|h|r", }, -- [5] { ["Count"] = 3, ["Link"] = "|cffffffff|Hitem:5637:0:0:0:0:0:0:0|h[大牙齿]|h|r", }, -- [6] { ["Count"] = 1, ["Link"] = "|cffffffff|Hitem:7069:0:0:0:0:0:0:0|h[元素空气]|h|r", }, -- [7] { ["Count"] = 1, ["Link"] = "|cffffffff|Hitem:7081:0:0:0:0:0:0:0|h[风之气息]|h|r", }, -- [8] { ["Count"] = 2, ["Link"] = "|cffffffff|Hitem:7068:0:0:0:0:0:0:0|h[元素火焰]|h|r", }, -- [9] { ["Count"] = 10, ["Link"] = "|cffffffff|Hitem:7070:0:0:0:0:0:0:0|h[元素之水]|h|r", }, -- [10] { ["Count"] = 2, ["Link"] = "|cff1eff00|Hitem:22452:0:0:0:0:0:0:0|h[源生之土]|h|r", }, -- [11] { ["Count"] = 9, ["Link"] = "|cffffffff|Hitem:22575:0:0:0:0:0:0:0|h[生命微粒]|h|r", }, -- [12] { ["Count"] = 9, ["Link"] = "|cffffffff|Hitem:22574:0:0:0:0:0:0:0|h[火焰微粒]|h|r", }, -- [13] { ["Count"] = 5, ["Link"] = "|cffffffff|Hitem:22576:0:0:0:0:0:0:0|h[法力微粒]|h|r", }, -- [14] { ["Count"] = 5, ["Link"] = "|cffffffff|Hitem:22577:0:0:0:0:0:0:0|h[暗影微粒]|h|r", }, -- [15] { ["Count"] = 1, ["Link"] = "|cff1eff00|Hitem:21885:0:0:0:0:0:0:0|h[源生之水]|h|r", }, -- [16] { ["Count"] = 1, ["Link"] = "|cff0070dd|Hitem:24200:0:0:0:0:0:0:0|h[图鉴:火花艾露恩之星]|h|r", }, -- [17] { ["Count"] = 1, ["Link"] = "|cff1eff00|Hitem:23117:0:0:0:0:0:0:0|h[碧月石]|h|r", }, -- [18] { ["Count"] = 1, ["Link"] = "|cffffffff|Hitem:6265:0:0:0:0:0:0:0|h[灵魂碎片]|h|r", }, -- [19] { ["Count"] = 9, ["Link"] = "|cffffffff|Hitem:22578:0:0:0:0:0:0:0|h[水之微粒]|h|r", }, -- [20] { ["Count"] = 1, ["Link"] = "|cffffffff|Hitem:6265:0:0:0:0:0:0:0|h[灵魂碎片]|h|r", }, -- [21] { ["Count"] = 1, ["Link"] = "|cffffffff|Hitem:6265:0:0:0:0:0:0:0|h[灵魂碎片]|h|r", }, -- [22] { ["Count"] = 1, ["Link"] = "|cffffffff|Hitem:6265:0:0:0:0:0:0:0|h[灵魂碎片]|h|r", }, -- [23] { ["Count"] = 1, ["Link"] = "|cffffffff|Hitem:6265:0:0:0:0:0:0:0|h[灵魂碎片]|h|r", }, -- [24] { ["Count"] = 1, ["Link"] = "|cffffffff|Hitem:6265:0:0:0:0:0:0:0|h[灵魂碎片]|h|r", }, -- [25] { ["Count"] = 1, ["Link"] = "|cffffffff|Hitem:6265:0:0:0:0:0:0:0|h[灵魂碎片]|h|r", }, -- [26] { ["Count"] = 1, ["Link"] = "|cffffffff|Hitem:6265:0:0:0:0:0:0:0|h[灵魂碎片]|h|r", }, -- [27] { ["Count"] = 1, ["Link"] = "|cffffffff|Hitem:6265:0:0:0:0:0:0:0|h[灵魂碎片]|h|r", }, -- [28] { ["Count"] = 1, ["Link"] = "|cffffffff|Hitem:6265:0:0:0:0:0:0:0|h[灵魂碎片]|h|r", }, -- [29] { ["Count"] = 1, ["Link"] = "|cffffffff|Hitem:6265:0:0:0:0:0:0:0|h[灵魂碎片]|h|r", }, -- [30] { ["Count"] = 1, ["Link"] = "|cffffffff|Hitem:6265:0:0:0:0:0:0:0|h[灵魂碎片]|h|r", }, -- [31] { ["Count"] = 1, ["Link"] = "|cffffffff|Hitem:6265:0:0:0:0:0:0:0|h[灵魂碎片]|h|r", }, -- [32] { ["Count"] = 1, ["Link"] = "|cffffffff|Hitem:6265:0:0:0:0:0:0:0|h[灵魂碎片]|h|r", }, -- [33] { ["Count"] = 1, ["Link"] = "|cffffffff|Hitem:6265:0:0:0:0:0:0:0|h[灵魂碎片]|h|r", }, -- [34] { ["Count"] = 1, ["Link"] = "|cffffffff|Hitem:6265:0:0:0:0:0:0:0|h[灵魂碎片]|h|r", }, -- [35] { ["Count"] = 1, ["Link"] = "|cffffffff|Hitem:23573:0:0:0:0:0:0:0|h[硬化精金锭]|h|r", }, -- [36] ["BagLink"] = "|cffffffff|Hitem:23162:0:0:0:0:0:0:0|h[弗洛尔的无尽抗性宝箱]|h|r", ["BagCount"] = 0, ["Size"] = 36, }, [9] = { { ["Count"] = 1, ["Link"] = "|cff0070dd|Hitem:7726:0:0:0:0:0:0:0|h[血色指挥官之盾]|h|r", }, -- [1] { ["Count"] = 1, ["Link"] = "|cff0070dd|Hitem:16732:0:0:0:0:0:0:0|h[勇气腿铠]|h|r", }, -- [2] { ["Count"] = 1, ["Link"] = "|cff0070dd|Hitem:31152:0:0:0:0:0:0:0|h[神启护胸]|h|r", }, -- [3] { ["Count"] = 1, ["Link"] = "|cff0070dd|Hitem:7720:0:0:0:0:0:0:0|h[主教之冠]|h|r", }, -- [4] { ["Count"] = 1, ["Link"] = "|cff0070dd|Hitem:13091:0:0:0:0:0:0:0|h[莫里斯元帅的勋章]|h|r", }, -- [5] { ["Count"] = 1, ["Link"] = "|cff1eff00|Hitem:8309:0:0:0:0:0:0:0|h[英雄护腿]|h|r", }, -- [6] { ["Count"] = 1, ["Link"] = "|cff1eff00|Hitem:8302:0:0:0:0:0:0:0|h[英雄护腕]|h|r", }, -- [7] { ["Count"] = 1, ["Link"] = "|cff1eff00|Hitem:24954:0:0:0:0:0:-36:43|h[巫术之沼泽杀手头盔]|h|r", }, -- [8] { ["Count"] = 1, ["Link"] = "|cff1eff00|Hitem:21855:0:0:0:0:0:0:0|h[灵纹外套]|h|r", }, -- [9] { ["Count"] = 1, ["Link"] = "|cff1eff00|Hitem:8245:0:0:0:0:0:0:0|h[帝王红色外套]|h|r", }, -- [10] { ["Count"] = 1, ["Link"] = "|cff1eff00|Hitem:8292:0:0:0:0:0:0:0|h[奥法头巾]|h|r", }, -- [11] { ["Count"] = 1, ["Link"] = "|cff1eff00|Hitem:4324:0:0:0:0:0:0:0|h[碧蓝丝质外衣]|h|r", }, -- [12] { ["Count"] = 1, ["Link"] = "|cff1eff00|Hitem:14120:0:0:0:0:0:848:0|h[雄鹰之土著长袍]|h|r", }, -- [13] { ["Count"] = 1, ["Link"] = "|cff1eff00|Hitem:14091:0:0:0:0:0:754:0|h[夜枭之珠串长袍]|h|r", }, -- [14] { ["Count"] = 1, ["Link"] = "|cff1eff00|Hitem:31798:0:0:0:0:0:0:0|h[亡语者外套]|h|r", }, -- [15] { ["Count"] = 1, ["Link"] = "|cff1eff00|Hitem:21853:0:0:0:0:0:0:0|h[灵纹长靴]|h|r", }, -- [16] { ["Count"] = 1, ["Link"] = "|cff0070dd|Hitem:13076:0:0:0:0:0:0:0|h[巨人杀手护腕]|h|r", }, -- [17] { ["Count"] = 1, ["Link"] = "|cffa335ee|Hitem:20600:0:0:0:0:0:0:0|h[玛法里奥的徽记之戒]|h|r", }, -- [18] { ["Count"] = 1, ["Link"] = "|cffa335ee|Hitem:810:0:0:0:0:0:0:0|h[北风]|h|r", }, -- [19] ["BagLink"] = "|cffffffff|Hitem:23162:0:0:0:0:0:0:0|h[弗洛尔的无尽抗性宝箱]|h|r", ["BagCount"] = 0, ["Size"] = 36, }, [11] = { ["BagLink"] = "|cffffffff|Hitem:23162:0:0:0:0:0:0:0|h[弗洛尔的无尽抗性宝箱]|h|r", ["BagCount"] = 0, ["Size"] = 36, }, [10] = { ["BagLink"] = "|cffffffff|Hitem:23162:0:0:0:0:0:0:0|h[弗洛尔的无尽抗性宝箱]|h|r", ["BagCount"] = 0, ["Size"] = 36, }, [8] = { { ["Count"] = 2, ["Link"] = "|cffffffff|Hitem:3860:0:0:0:0:0:0:0|h[秘银锭]|h|r", }, -- [1] { ["Count"] = 76, ["Link"] = "|cffffffff|Hitem:11018:0:0:0:0:0:0:0|h[安戈洛的泥土]|h|r", }, -- [2] { ["Count"] = 20, ["Link"] = "|cffffffff|Hitem:10620:0:0:0:0:0:0:0|h[瑟银矿石]|h|r", }, -- [3] { ["Count"] = 20, ["Link"] = "|cffffffff|Hitem:10620:0:0:0:0:0:0:0|h[瑟银矿石]|h|r", }, -- [4] { ["Count"] = 20, ["Link"] = "|cffffffff|Hitem:10620:0:0:0:0:0:0:0|h[瑟银矿石]|h|r", }, -- [5] { ["Count"] = 4, ["Link"] = "|cff1eff00|Hitem:2776:0:0:0:0:0:0:0|h[金矿石]|h|r", }, -- [6] { ["Count"] = 18, ["Link"] = "|cffffffff|Hitem:10620:0:0:0:0:0:0:0|h[瑟银矿石]|h|r", }, -- [7] { ["Count"] = 1, ["Link"] = "|cff1eff00|Hitem:12363:0:0:0:0:0:0:0|h[奥术水晶]|h|r", }, -- [8] { ["Count"] = 2, ["Link"] = "|cffffffff|Hitem:7077:0:0:0:0:0:0:0|h[火焰之心]|h|r", }, -- [9] nil, -- [10] nil, -- [11] { ["Count"] = 1, ["Link"] = "|cff1eff00|Hitem:25333:0:0:0:0:0:-41:50|h[野兽之净化法杖]|h|r", }, -- [12] { ["Count"] = 1, ["Link"] = "|cffa335ee|Hitem:20581:0:0:0:0:0:0:0|h[猛烈生长法杖]|h|r", }, -- [13] { ["Count"] = 1, ["Link"] = "|cffa335ee|Hitem:23242:0:0:0:0:0:0:0|h[冰霜巨龙之爪]|h|r", }, -- [14] { ["Count"] = 1, ["Link"] = "|cffa335ee|Hitem:32336:0:0:0:0:0:0:0|h[背叛者的黑暗之弓]|h|r", }, -- [15] { ["Count"] = 1, ["Link"] = "|cffa335ee|Hitem:1263:0:0:0:0:0:0:0|h[碎灵]|h|r", }, -- [16] { ["Count"] = 1, ["Link"] = "|cffa335ee|Hitem:23056:0:0:0:0:0:0:0|h[扭曲虚空之锤]|h|r", }, -- [17] { ["Count"] = 1, ["Link"] = "|cff0070dd|Hitem:13060:0:0:0:0:0:0:0|h[缝衣针]|h|r", }, -- [18] { ["Count"] = 1, ["Link"] = "|cff0070dd|Hitem:13053:0:0:0:0:0:0:0|h[厄运制造者]|h|r", }, -- [19] { ["Count"] = 1, ["Link"] = "|cff0070dd|Hitem:31153:0:0:0:0:0:0:0|h[军团战斧]|h|r", }, -- [20] nil, -- [21] nil, -- [22] { ["Count"] = 1, ["Link"] = "|cff0070dd|Hitem:31305:0:0:0:0:0:0:0|h[塞德的刻刀]|h|r", }, -- [23] { ["Count"] = 1, ["Link"] = "|cff1eff00|Hitem:25277:0:0:0:0:0:-14:16|h[猛虎之冒险长枪]|h|r", }, -- [24] { ["Count"] = 1, ["Link"] = "|cff1eff00|Hitem:25261:0:0:0:0:0:-14:15|h[猛虎之强力弩弓]|h|r", }, -- [25] { ["Count"] = 1, ["Link"] = "|cff1eff00|Hitem:25141:0:0:0:0:0:-39:56|h[祈灵之哈兰战锤]|h|r", }, -- [26] { ["Count"] = 1, ["Link"] = "|cff1eff00|Hitem:25148:0:0:0:0:0:-11:19|h[猎鹰之集骨者轻剑]|h|r", }, -- [27] { ["Count"] = 1, ["Link"] = "|cff1eff00|Hitem:25149:0:0:0:0:0:-13:20|h[孤狼之男爵的宽剑]|h|r", }, -- [28] { ["Count"] = 1, ["Link"] = "|cffa335ee|Hitem:3075:0:0:0:0:0:0:0|h[烈焰之眼]|h|r", }, -- [29] { ["Count"] = 1, ["Link"] = "|cffa335ee|Hitem:21696:0:0:0:0:0:0:0|h[执政者长袍]|h|r", }, -- [30] { ["Count"] = 1, ["Link"] = "|cffa335ee|Hitem:21499:0:0:0:0:0:0:0|h[流沙外套]|h|r", }, -- [31] { ["Count"] = 1, ["Link"] = "|cffa335ee|Hitem:23049:0:0:0:0:0:0:0|h[萨菲隆的左眼]|h|r", }, -- [32] { ["Count"] = 1, ["Link"] = "|cffa335ee|Hitem:23060:0:0:0:0:0:0:0|h[骨镰之戒]|h|r", }, -- [33] { ["Count"] = 1, ["Link"] = "|cffa335ee|Hitem:23061:0:0:0:0:0:0:0|h[信仰之戒]|h|r", }, -- [34] { ["Count"] = 1, ["Link"] = "|cffa335ee|Hitem:1980:0:0:0:0:0:0:0|h[地狱指环]|h|r", }, -- [35] { ["Count"] = 1, ["Link"] = "|cff0070dd|Hitem:34105:0:0:0:0:0:0:0|h[千羽箭袋]|h|r", }, -- [36] ["BagLink"] = "|cffffffff|Hitem:23162:0:0:0:0:0:0:0|h[弗洛尔的无尽抗性宝箱]|h|r", ["BagCount"] = 0, ["Size"] = 36, }, [-1] = { { ["Count"] = 10, ["Link"] = "|cffffffff|Hitem:29736:0:0:0:0:0:0:0|h[奥术符文]|h|r", }, -- [1] { ["Count"] = 1, ["Link"] = "|cff0070dd|Hitem:13044:0:0:0:0:0:0:0|h[斩魔剑]|h|r", }, -- [2] { ["Count"] = 1, ["Link"] = "|cffa335ee|Hitem:23547:0:0:0:0:0:0:0|h[天灾的活力]|h|r", }, -- [3] { ["Count"] = 1, ["Link"] = "|cffa335ee|Hitem:23549:0:0:0:0:0:0:0|h[天灾的坚韧]|h|r", }, -- [4] { ["Count"] = 1, ["Link"] = "|cff1eff00|Hitem:12735:0:0:0:0:0:0:0|h[磨损的憎恶缝合线]|h|r", }, -- [5] { ["Count"] = 10, ["Link"] = "|cffffffff|Hitem:5075:0:0:0:0:0:0:0|h[血岩碎片]|h|r", }, -- [6] { ["Count"] = 1, ["Link"] = "|cffffffff|Hitem:22014:0:0:0:0:0:0:0|h[空火盆]|h|r", }, -- [7] { ["Count"] = 25, ["Link"] = "|cffffffff|Hitem:11018:0:0:0:0:0:0:0|h[安戈洛的泥土]|h|r", }, -- [8] { ["Count"] = 1, ["Link"] = "|cffffffff|Hitem:11482:0:0:0:0:0:0:0|h[水晶塔使用手册]|h|r", }, -- [9] { ["Count"] = 1, ["Link"] = "|cff0070dd|Hitem:24216:0:0:0:0:0:0:0|h[图鉴:反光黄晶玉]|h|r", }, -- [10] { ["Count"] = 5, ["Link"] = "|cff0070dd|Hitem:23438:0:0:0:0:0:0:0|h[艾露恩之星]|h|r", }, -- [11] { ["Count"] = 3, ["Link"] = "|cff0070dd|Hitem:23437:0:0:0:0:0:0:0|h[水玉]|h|r", }, -- [12] { ["Count"] = 2, ["Link"] = "|cff0070dd|Hitem:23436:0:0:0:0:0:0:0|h[红曜石]|h|r", }, -- [13] { ["Count"] = 3, ["Link"] = "|cff0070dd|Hitem:23441:0:0:0:0:0:0:0|h[夜目石]|h|r", }, -- [14] { ["Count"] = 6, ["Link"] = "|cff0070dd|Hitem:23439:0:0:0:0:0:0:0|h[黄晶玉]|h|r", }, -- [15] { ["Count"] = 3, ["Link"] = "|cff1eff00|Hitem:23112:0:0:0:0:0:0:0|h[德拉诺金钻]|h|r", }, -- [16] { ["Count"] = 2, ["Link"] = "|cff1eff00|Hitem:23112:0:0:0:0:0:0:0|h[德拉诺金钻]|h|r", }, -- [17] { ["Count"] = 2, ["Link"] = "|cff1eff00|Hitem:23117:0:0:0:0:0:0:0|h[碧月石]|h|r", }, -- [18] { ["Count"] = 4, ["Link"] = "|cff1eff00|Hitem:23117:0:0:0:0:0:0:0|h[碧月石]|h|r", }, -- [19] { ["Count"] = 1, ["Link"] = "|cff1eff00|Hitem:23079:0:0:0:0:0:0:0|h[翠榄石]|h|r", }, -- [20] { ["Count"] = 1, ["Link"] = "|cff1eff00|Hitem:23077:0:0:0:0:0:0:0|h[血榴石]|h|r", }, -- [21] { ["Count"] = 5, ["Link"] = "|cff1eff00|Hitem:23107:0:0:0:0:0:0:0|h[德拉诺影钻]|h|r", }, -- [22] { ["Count"] = 3, ["Link"] = "|cff1eff00|Hitem:12800:0:0:0:0:0:0:0|h[艾泽拉斯钻石]|h|r", }, -- [23] { ["Count"] = 11, ["Link"] = "|cff1eff00|Hitem:12364:0:0:0:0:0:0:0|h[巨型绿宝石]|h|r", }, -- [24] { ["Count"] = 20, ["Link"] = "|cff1eff00|Hitem:12363:0:0:0:0:0:0:0|h[奥术水晶]|h|r", }, -- [25] { ["Count"] = 5, ["Link"] = "|cff1eff00|Hitem:12361:0:0:0:0:0:0:0|h[蓝宝石]|h|r", }, -- [26] { ["Count"] = 16, ["Link"] = "|cff1eff00|Hitem:7910:0:0:0:0:0:0:0|h[红宝石]|h|r", }, -- [27] { ["Count"] = 20, ["Link"] = "|cff1eff00|Hitem:7910:0:0:0:0:0:0:0|h[红宝石]|h|r", }, -- [28] ["Size"] = 28, }, } JPack = { ["packing"] = false, ["asc"] = true, ["bankOpened"] = false, ["packingGroupIndex"] = 3, ["bagGroups"] = { }, ["packingBank"] = false, }
gpl-3.0
dickeyf/darkstar
scripts/zones/Northern_San_dOria/npcs/Lotine.lua
13
1027
----------------------------------- -- Area: Northern San d'Oria -- NPC: Lotine -- Type: Standard Info NPC -- @zone: 231 -- @pos -137.504 11.999 171.090 -- ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) rand = math.random(1,2); if (rand == 1) then player:startEvent(0x028c); else player:startEvent(0x0290); 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
dickeyf/darkstar
scripts/globals/spells/bluemagic/pollen.lua
27
1817
----------------------------------------- -- Spell: Pollen -- Restores HP -- Spell cost: 8 MP -- Monster Type: Vermin -- Spell Type: Magical (Light) -- Blue Magic Points: 1 -- Stat Bonus: CHR+1, HP+5 -- Level: 1 -- Casting Time: 2 seconds -- Recast Time: 5 seconds -- -- Combos: Resist Sleep ----------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local minCure = 14; local divisor = 1; local constant = -6; local power = getCurePowerOld(caster); if (power > 99) then divisor = 57; constant = 33.125; elseif (power > 59) then divisor = 2; constant = 9; end local final = getCureFinal(caster,spell,getBaseCureOld(power,divisor,constant),minCure,true); final = final + (final * (target:getMod(MOD_CURE_POTENCY_RCVD)/100)); if (target:getAllegiance() == caster:getAllegiance() and (target:getObjType() == TYPE_PC or target:getObjType() == TYPE_MOB)) then --Applying server mods.... final = final * CURE_POWER; end local diff = (target:getMaxHP() - target:getHP()); if (final > diff) then final = diff; end target:addHP(final); if (target:getAllegiance() == caster:getAllegiance() and (target:getObjType() == TYPE_PC or target:getObjType() == TYPE_MOB)) then caster:updateEnmityFromCure(target,final); end spell:setMsg(7); return final; end;
gpl-3.0
Turttle/darkstar
scripts/zones/Yorcia_Weald_U/Zone.lua
36
1119
----------------------------------- -- -- Zone: Yorcia Weald U -- ----------------------------------- require("scripts/globals/settings"); package.loaded["scripts/zones/Yorcia_Weald_U/TextIDs"] = nil; require("scripts/zones/Yorcia_Weald_U/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) cs = -1; 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
SalvationDevelopment/Salvation-Scripts-TCG
c79798060.lua
2
1878
--地縛神 Ccarayhua function c79798060.initial_effect(c) c:SetUniqueOnField(1,1,10000000,LOCATION_MZONE) -- local e4=Effect.CreateEffect(c) e4:SetType(EFFECT_TYPE_SINGLE) e4:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e4:SetRange(LOCATION_MZONE) e4:SetCode(EFFECT_SELF_DESTROY) e4:SetCondition(c79798060.sdcon) c:RegisterEffect(e4) --battle target local e5=Effect.CreateEffect(c) e5:SetType(EFFECT_TYPE_SINGLE) e5:SetCode(EFFECT_CANNOT_BE_BATTLE_TARGET) e5:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e5:SetRange(LOCATION_MZONE) e5:SetValue(aux.imval1) c:RegisterEffect(e5) --direct atk local e6=Effect.CreateEffect(c) e6:SetType(EFFECT_TYPE_SINGLE) e6:SetCode(EFFECT_DIRECT_ATTACK) c:RegisterEffect(e6) --destroy local e7=Effect.CreateEffect(c) e7:SetDescription(aux.Stringid(79798060,0)) e7:SetCategory(CATEGORY_DESTROY) e7:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F) e7:SetCode(EVENT_DESTROYED) e7:SetCondition(c79798060.descon) e7:SetTarget(c79798060.destg) e7:SetOperation(c79798060.desop) c:RegisterEffect(e7) end function c79798060.sdcon(e) local c=e:GetHandler() if c:IsStatus(STATUS_BATTLE_DESTROYED) then return false end local f1=Duel.GetFieldCard(0,LOCATION_SZONE,5) local f2=Duel.GetFieldCard(1,LOCATION_SZONE,5) return ((f1==nil or not f1:IsFaceup()) and (f2==nil or not f2:IsFaceup())) end function c79798060.descon(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() return not c:IsReason(REASON_BATTLE) and re and re:GetOwner()~=c end function c79798060.destg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end local g=Duel.GetMatchingGroup(aux.TRUE,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,nil) Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,g:GetCount(),0,0) end function c79798060.desop(e,tp,eg,ep,ev,re,r,rp) local g=Duel.GetMatchingGroup(aux.TRUE,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,nil) Duel.Destroy(g,REASON_EFFECT) end
gpl-2.0
dickeyf/darkstar
scripts/zones/Southern_San_dOria/npcs/Anxaberoute.lua
13
1463
----------------------------------- -- Area: Southern San dOria -- NPC: Anxaberoute -- Type: Standard Info NPC -- @zone: 230 -- @pos 108.892 0.000 -49.038 ----------------------------------- package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Southern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE); 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(0x0376); 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
Turttle/darkstar
scripts/globals/items/serving_of_patriarch_sautee.lua
36
1253
----------------------------------------- -- ID: 5677 -- Item: Serving of Patriarch Sautee -- Food Effect: 4Hrs, All Races ----------------------------------------- -- MP 60 -- Mind 7 -- MP Recovered While Healing 7 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,10800,5677); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_MP, 60); target:addMod(MOD_MND, 7); target:addMod(MOD_MPHEAL, 7); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_MP, 60); target:delMod(MOD_MND, 7); target:delMod(MOD_MPHEAL, 7); end;
gpl-3.0
Ablu/ValyriaTear
dat/config/boot.lua
1
10639
-- Boot animation script file -- Set the boot tablespace name. local ns = {} setmetatable(ns, {__index = _G}) boot = ns; setfenv(1, ns); -- The Boot instance local Boot; local animation_timer; -- Init all the needed variables function Initialize(boot_instance) Boot = boot_instance; Script = Boot:GetScriptSupervisor(); boot_state = Boot:GetState(); -- Load the necessary files bckgrnd_id = Script:AddImage("img/backdrops/boot/background.png", 1024, 768); logo_id = Script:AddImage("img/logos/valyria_logo_black.png", 630, 318); cloud_field_id = Script:AddImage("img/backdrops/boot/cloudfield.png", 248, 120); mist_id = Script:AddImage("img/backdrops/boot/cloudy_mist.png", 1024, 768); fog_id = Script:AddImage("img/backdrops/boot/fog.png", 1024, 768); crystal_id = Script:AddImage("img/backdrops/boot/crystal.png", 140, 220); crystal_shadow_id = Script:AddImage("img/backdrops/boot/crystal_shadow.png", 192, 168); satellite_id = Script:AddImage("img/backdrops/boot/satellite.png", 34, 34); satellite_shadow_id = Script:AddImage("img/backdrops/boot/satellite_shadow.png", 48, 32); flare_id = Script:AddImage("img/backdrops/boot/flare.png", 256, 256); menu_bar_id = Script:AddImage("img/menus/battle_bottom_menu.png", 1024, 128); -- Init the timer animation_timer = hoa_system.SystemTimer(7000, 0); end function Reset() if (Boot:GetState() == hoa_boot.BootMode.BOOT_STATE_MENU) then AudioManager:PlayMusic("mus/Soliloquy_1-OGA-mat-pablo.ogg"); end end -- The image alpha channel values local logo_alpha = 0.0; local bckgrnd_alpha = 0.0; local menu_bar_alpha = 0.0; -- cloud field members local x_positions1 = { -110.0, 0.0, 110.0, 220.0 , 330.0, 440.0, 550.0, 660.0, 770.0, 880.0, 990.0}; local y_position1 = 400.0; local x_positions2 = { -110.0, 0.0, 110.0, 220.0 , 330.0, 440.0, 550.0, 660.0, 770.0, 880.0, 990.0}; local y_position2 = 330.0; local x_positions3 = { -110.0, 0.0, 110.0, 220.0 , 330.0, 440.0, 550.0, 660.0, 770.0, 880.0, 990.0}; local y_position3 = 260.0; local x_positions4 = { -110.0, 0.0, 110.0, 220.0 , 330.0, 440.0, 550.0, 660.0, 770.0, 880.0, 990.0}; local y_position4 = 190.0; local x_positions5 = { -110.0, 0.0, 110.0, 220.0 , 330.0, 440.0, 550.0, 660.0, 770.0, 880.0, 990.0}; local y_position5 = 120.0; local x_positions6 = { -110.0, 0.0, 110.0, 220.0 , 330.0, 440.0, 550.0, 660.0, 770.0, 880.0, 990.0}; local y_position6 = 50.0; -- crystal members local crystal_decay = 0.0; local crystal_time = 0; -- satellite members local sat1_decay = 0.0; local sat1_x_position = -15.0; local sat1_time = 0; local sat1_behind = false; local sat2_decay = 20.0; local sat2_x_position = 80.0; local sat2_time = 0; local sat2_behind = false; local sat3_decay = 10.0; local sat3_x_position = 40.0; local sat3_time = 0; local sat3_behind = true; function UpdateIntroFade() -- After one second of black, start fade in the logo if (animation_timer:GetTimeExpired() > 1000 and animation_timer:GetTimeExpired() <= 4000) then logo_alpha = (animation_timer:GetTimeExpired() - 1000) / (4000 - 1000); elseif (animation_timer:GetTimeExpired() > 4000 and animation_timer:GetTimeExpired() <= 7000) then bckgrnd_alpha = (animation_timer:GetTimeExpired() - 4000) / (7000 - 4000); end end -- Put the x coord on screen function fix_pos(position) if (position <= -248.0) then return position + 1224.0; else return position; end end function UpdateBackgroundAnimation() local time_expired = SystemManager:GetUpdateTime(); -- deal with all the clouds for i=1, #x_positions1 do x_positions1[i] = fix_pos(x_positions1[i]) - 0.025 * time_expired; end for i=1, #x_positions2 do x_positions2[i] = fix_pos(x_positions2[i]) - 0.05 * time_expired; end for i=1, #x_positions3 do x_positions3[i] = fix_pos(x_positions3[i]) - 0.075 * time_expired; end for i=1, #x_positions4 do x_positions4[i] = fix_pos(x_positions4[i]) - 0.1 * time_expired; end for i=1, #x_positions5 do x_positions5[i] = fix_pos(x_positions5[i]) - 0.125 * time_expired; end for i=1, #x_positions6 do x_positions6[i] = fix_pos(x_positions6[i]) - 0.15 * time_expired; end -- Compute the crystal and shadow movement crystal_time = crystal_time + time_expired if (crystal_time >= 31400) then crystal_time = crystal_time - 31400; end crystal_decay = 10 + math.sin(0.002 * crystal_time) * 10; -- compute the satellites movement sat1_time = sat1_time + time_expired if (sat1_time >= 31400) then sat1_time = sat1_time - 31400; end sat1_decay = -5 + math.sin(0.003 * sat1_time) * 10; sat1_x_position = 50 + (math.sin(0.0008 * sat1_time - 0.785) * 75); if (sat1_behind) then if (sat1_x_position < -24.0) then sat1_behind = false; end else if (sat1_x_position > 124.0) then sat1_behind = true; end end sat2_time = sat2_time + time_expired if (sat2_time >= 31400) then sat2_time = sat2_time - 31400; end sat2_decay = -5 + math.sin(0.003 * sat2_time + 1.57) * 10; sat2_x_position = 50 + (math.sin(0.0008 * sat2_time + 3.14) * 75); if (sat2_behind) then if (sat2_x_position < -24.0) then sat2_behind = false; end else if (sat2_x_position > 124.0) then sat2_behind = true; end end sat3_time = sat3_time + time_expired if (sat3_time >= 31400) then sat3_time = sat3_time - 31400; end sat3_decay = -5 + math.sin(0.003 * sat3_time + 0.785) * 10; sat3_x_position = 50 + (math.sin(0.0008 * sat3_time + 0.785) * 75); if (sat3_behind) then if (sat3_x_position < -24.0) then sat3_behind = false; end else if (sat3_x_position > 124.0) then sat3_behind = true; end end end local music_started = false; local snow_started = false; -- Update the animation function Update() animation_timer:Update(); UpdateBackgroundAnimation(); if (Boot:GetState() == hoa_boot.BootMode.BOOT_STATE_INTRO) then -- Start the timer if (animation_timer:IsInitial() == true and animation_timer:IsRunning() ~= true) then animation_timer:Run(); elseif (animation_timer:IsFinished() == true) then -- Show the menu once the presentation is done Boot:ChangeState(hoa_boot.BootMode.BOOT_STATE_MENU); end -- Update the starting animation UpdateIntroFade(); else logo_alpha = 1.0; bckgrnd_alpha = 1.0; animation_timer:Finish(); end if (music_started == false) then AudioManager:PlayMusic("mus/Soliloquy_1-OGA-mat-pablo.ogg"); music_started = true; end -- Update the menu bar alpha in menu mode. if (Boot:GetState() == hoa_boot.BootMode.BOOT_STATE_MENU) then local time_expired = SystemManager:GetUpdateTime(); if (menu_bar_alpha < 0.6) then menu_bar_alpha = menu_bar_alpha + 0.001 * time_expired if menu_bar_alpha >= 0.6 then menu_bar_alpha = 0.6 end end if (snow_started == false) then Boot:GetParticleManager():AddParticleEffect("dat/effects/particles/snow.lua", 512.0, 384.0); snow_started = true; end end end function DrawCloudFieldLine(x_positions, y_position) for _,v in pairs(x_positions) do Script:DrawImage(cloud_field_id, v, y_position, hoa_video.Color(1.0, 1.0, 1.0, 0.6 * bckgrnd_alpha)); end end function DrawBackground() -- The background image Script:DrawImage(bckgrnd_id, 0.0, 769.0, hoa_video.Color(1.0, 1.0, 1.0, bckgrnd_alpha)); -- The passing clouds DrawCloudFieldLine(x_positions1, y_position1); DrawCloudFieldLine(x_positions2, y_position2); DrawCloudFieldLine(x_positions3, y_position3); DrawCloudFieldLine(x_positions4, y_position4); DrawCloudFieldLine(x_positions5, y_position5); DrawCloudFieldLine(x_positions6, y_position6); end function DrawPostEffects() -- front mist + fog Script:DrawImage(mist_id, 0.0, 769.0, hoa_video.Color(1.0, 1.0, 1.0, bckgrnd_alpha * 0.6)); Script:DrawImage(fog_id, 0.0, 769.0, hoa_video.Color(1.0, 1.0, 1.0, bckgrnd_alpha * 0.8)); -- satellite behind if (sat1_behind) then Script:DrawImage(satellite_shadow_id, 640.0 + sat1_decay + (sat1_x_position / 2.0), 330.0 - (sat1_x_position / 3.0), hoa_video.Color(1.0, 1.0, 1.0, bckgrnd_alpha * 0.3)); Script:DrawImage(satellite_id, 448.0 + sat1_x_position, 400.0 + sat1_decay, hoa_video.Color(1.0, 1.0, 1.0, bckgrnd_alpha * 0.7)); end if (sat2_behind) then Script:DrawImage(satellite_shadow_id, 640.0 + sat2_decay + (sat2_x_position / 2.0), 330.0 - (sat2_x_position / 3.0), hoa_video.Color(1.0, 1.0, 1.0, bckgrnd_alpha * 0.3)); Script:DrawImage(satellite_id, 448.0 + sat2_x_position, 400.0 + sat2_decay, hoa_video.Color(1.0, 1.0, 1.0, bckgrnd_alpha * 0.7)); end if (sat3_behind) then Script:DrawImage(satellite_shadow_id, 640.0 + sat3_decay + (sat3_x_position / 2.0), 330.0 - (sat3_x_position / 3.0), hoa_video.Color(1.0, 1.0, 1.0, bckgrnd_alpha * 0.3)); Script:DrawImage(satellite_id, 448.0 + sat3_x_position, 400.0 + sat3_decay, hoa_video.Color(1.0, 1.0, 1.0, bckgrnd_alpha * 0.7)); end -- Crystal Script:DrawImage(crystal_shadow_id, 498.0 + crystal_decay, 330.0, hoa_video.Color(1.0, 1.0, 1.0, bckgrnd_alpha * 0.3)); Script:DrawImage(crystal_id, 448.0, 400.0 + crystal_decay, hoa_video.Color(1.0, 1.0, 1.0, bckgrnd_alpha * 0.7)); Script:DrawImage(flare_id, 384.0, 440.0 + crystal_decay, hoa_video.Color(1.0, 1.0, 1.0, bckgrnd_alpha * 0.6)); -- satellite in front if (sat1_behind == false) then Script:DrawImage(satellite_shadow_id, 640.0 + sat1_decay + (sat1_x_position / 2.0), 330.0 - (sat1_x_position / 3.0), hoa_video.Color(1.0, 1.0, 1.0, bckgrnd_alpha * 0.3)); Script:DrawImage(satellite_id, 448.0 + sat1_x_position, 400.0 + sat1_decay, hoa_video.Color(1.0, 1.0, 1.0, bckgrnd_alpha * 0.7)); end if (sat2_behind == false) then Script:DrawImage(satellite_shadow_id, 640.0 + sat2_decay + (sat2_x_position / 2.0), 330.0 - (sat2_x_position / 3.0), hoa_video.Color(1.0, 1.0, 1.0, bckgrnd_alpha * 0.3)); Script:DrawImage(satellite_id, 448.0 + sat2_x_position, 400.0 + sat2_decay, hoa_video.Color(1.0, 1.0, 1.0, bckgrnd_alpha * 0.7)); end if (sat3_behind == false) then Script:DrawImage(satellite_shadow_id, 640.0 + sat3_decay + (sat3_x_position / 2.0), 330.0 - (sat3_x_position / 3.0), hoa_video.Color(1.0, 1.0, 1.0, bckgrnd_alpha * 0.3)); Script:DrawImage(satellite_id, 448.0 + sat3_x_position, 400.0 + sat3_decay, hoa_video.Color(1.0, 1.0, 1.0, bckgrnd_alpha * 0.7)); end -- A dark bar used to make the menu more visible if (Boot:GetState() == hoa_boot.BootMode.BOOT_STATE_MENU) then Script:DrawImage(menu_bar_id, 0.0, 128.0, hoa_video.Color(1.0, 1.0, 1.0, menu_bar_alpha)); end -- Logo VideoManager:Move(198.0, 750.0); Script:DrawImage(logo_id, 198.0, 750.0, hoa_video.Color(1.0, 1.0, 1.0, logo_alpha)); end
gpl-2.0
dickeyf/darkstar
scripts/zones/Port_Jeuno/npcs/Gekko.lua
13
1401
----------------------------------- -- Area: Port Jeuno -- NPC: Gekko -- Standard Merchant NPC ----------------------------------- require("scripts/globals/shop"); 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) player:showText(npc,GEKKO_SHOP_DIALOG); stock = {0x1036,2387, -- Eye Drops 0x1034,290, -- Antidote 0x1037,367, -- Echo Drops 0x1010,837, -- Potion 0x1020,4445, -- Ether 0x110d,120 , -- Rolanberry 0x00bf,36000, -- Autumn's End 0x00bc,31224, -- Acolyte's Grief 0x13dd,50400} -- Scroll of Regen IV 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
dickeyf/darkstar
scripts/globals/items/reishi_mushroom.lua
18
1174
----------------------------------------- -- ID: 4449 -- Item: reishi_mushroom -- Food Effect: 5Min, All Races ----------------------------------------- -- Strength -6 -- Mind 4 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,4449); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_STR, -6); target:addMod(MOD_MND, 4); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_STR, -6); target:delMod(MOD_MND, 4); end;
gpl-3.0
Turttle/darkstar
scripts/zones/Bastok_Mines/npcs/Odoba.lua
19
1145
----------------------------------- -- Area: Bastok Mines -- NPC: Odoba -- Guild Merchant NPC: Alchemy Guild -- @pos 108.473 5.017 1.089 234 ----------------------------------- package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/shop"); require("scripts/zones/Bastok_Mines/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:sendGuild(526,8,23,6)) then player:showText(npc, ODOBA_SHOP_DIALOG); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
SalvationDevelopment/Salvation-Scripts-TCG
c25853045.lua
2
2288
--FA-ブラック・レイ・ランサー function c25853045.initial_effect(c) --xyz summon aux.AddXyzProcedure(c,aux.FilterBoolFunction(Card.IsAttribute,ATTRIBUTE_WATER),4,3,c25853045.ovfilter,aux.Stringid(25853045,0)) c:EnableReviveLimit() --atk local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e1:SetRange(LOCATION_MZONE) e1:SetCode(EFFECT_UPDATE_ATTACK) e1:SetValue(c25853045.atkval) c:RegisterEffect(e1) --destroy replace local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_CONTINUOUS+EFFECT_TYPE_SINGLE) e2:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e2:SetCode(EFFECT_DESTROY_REPLACE) e2:SetRange(LOCATION_MZONE) e2:SetTarget(c25853045.reptg) c:RegisterEffect(e2) --destroy local e3=Effect.CreateEffect(c) e3:SetDescription(aux.Stringid(25853045,2)) e3:SetCategory(CATEGORY_DESTROY) e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e3:SetProperty(EFFECT_FLAG_CARD_TARGET) e3:SetCode(EVENT_BATTLE_DESTROYING) e3:SetCondition(aux.bdocon) e3:SetTarget(c25853045.destg) e3:SetOperation(c25853045.desop) c:RegisterEffect(e3) end function c25853045.ovfilter(c) return c:IsFaceup() and c:GetRank()==3 and c:IsAttribute(ATTRIBUTE_WATER) and c:GetOverlayCount()==0 end function c25853045.atkval(e,c) return c:GetOverlayCount()*200 end function c25853045.reptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():CheckRemoveOverlayCard(tp,1,REASON_EFFECT) end if Duel.SelectYesNo(tp,aux.Stringid(25853045,1)) then local g=e:GetHandler():GetOverlayGroup() Duel.SendtoGrave(g,REASON_EFFECT) return true else return false end end function c25853045.filter(c) return c:IsType(TYPE_SPELL+TYPE_TRAP) end function c25853045.destg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsOnField() and chkc:IsControler(1-tp) and c25853045.filter(chkc) end if chk==0 then return Duel.IsExistingTarget(c25853045.filter,tp,0,LOCATION_ONFIELD,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY) local g=Duel.SelectTarget(tp,c25853045.filter,tp,0,LOCATION_ONFIELD,1,1,nil) Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,1,0,0) end function c25853045.desop(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) then Duel.Destroy(tc,REASON_EFFECT) end end
gpl-2.0
SalvationDevelopment/Salvation-Scripts-TCG
c83519853.lua
5
3141
--魔聖騎士皇ランスロット function c83519853.initial_effect(c) c:SetUniqueOnField(1,0,83519853) --synchro summon aux.AddSynchroProcedure(c,nil,aux.NonTuner(Card.IsSetCard,0x107a),1) c:EnableReviveLimit() --equip local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(83519853,0)) e1:SetCategory(CATEGORY_EQUIP) e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e1:SetCode(EVENT_SPSUMMON_SUCCESS) e1:SetCondition(c83519853.condition) e1:SetTarget(c83519853.target) e1:SetOperation(c83519853.operation) c:RegisterEffect(e1) --tohand local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS) e2:SetCode(EVENT_BATTLE_DESTROYING) e2:SetCondition(c83519853.regcon) e2:SetOperation(c83519853.regop) c:RegisterEffect(e2) local e3=Effect.CreateEffect(c) e3:SetDescription(aux.Stringid(83519853,1)) e3:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH) e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O) e3:SetCode(EVENT_PHASE+PHASE_BATTLE) e3:SetRange(LOCATION_MZONE) e3:SetCountLimit(1) e3:SetCondition(c83519853.thcon) e3:SetTarget(c83519853.thtg) e3:SetOperation(c83519853.thop) c:RegisterEffect(e3) end function c83519853.condition(e,tp,eg,ep,ev,re,r,rp) return e:GetHandler():GetSummonType()==SUMMON_TYPE_SYNCHRO end function c83519853.filter(c,ec) return c:IsSetCard(0x207a) and c:IsType(TYPE_EQUIP) and c:CheckEquipTarget(ec) end function c83519853.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_SZONE)>0 and Duel.IsExistingMatchingCard(c83519853.filter,tp,LOCATION_DECK,0,1,nil,e:GetHandler()) end Duel.SetOperationInfo(0,CATEGORY_EQUIP,nil,1,tp,LOCATION_DECK) end function c83519853.operation(e,tp,eg,ep,ev,re,r,rp) if Duel.GetLocationCount(tp,LOCATION_SZONE)<=0 then return end local c=e:GetHandler() if c:IsFacedown() or not c:IsRelateToEffect(e) then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_EQUIP) local g=Duel.SelectMatchingCard(tp,c83519853.filter,tp,LOCATION_DECK,0,1,1,nil,c) local tc=g:GetFirst() if tc then Duel.Equip(tp,tc,c,true) end end function c83519853.regcon(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local bc=c:GetBattleTarget() return c:IsRelateToBattle() and bc:IsLocation(LOCATION_GRAVE) and bc:IsType(TYPE_MONSTER) end function c83519853.regop(e,tp,eg,ep,ev,re,r,rp) e:GetHandler():RegisterFlagEffect(83519853,RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END,0,1) end function c83519853.thcon(e,tp,eg,ep,ev,re,r,rp) return e:GetHandler():GetFlagEffect(83519853)~=0 end function c83519853.thfilter(c) return (c:IsSetCard(0x107a) or c:IsSetCard(0x207a)) and c:IsAbleToHand() end function c83519853.thtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c83519853.thfilter,tp,LOCATION_DECK,0,1,nil) end Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK) end function c83519853.thop(e,tp,eg,ep,ev,re,r,rp) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND) local g=Duel.SelectMatchingCard(tp,c83519853.thfilter,tp,LOCATION_DECK,0,1,1,nil) if g:GetCount()>0 then Duel.SendtoHand(g,nil,REASON_EFFECT) Duel.ConfirmCards(1-tp,g) end end
gpl-2.0
dickeyf/darkstar
scripts/zones/Rabao/npcs/Alfesar.lua
12
2419
----------------------------------- -- Area: Rabao -- NPC: Alfesar -- Standard Info NPC --Starts The Missing Piece ----------------------------------- package.loaded["scripts/zones/Rabao/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/zones/Rabao/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local TheMissingPiece = player:getQuestStatus(OUTLANDS,THE_MISSING_PIECE); local Fame = player:getFameLevel(RABAO); if (TheMissingPiece == QUEST_AVAILABLE and Fame >= 4) then -- start quest player:startEvent(0x0006); elseif (TheMissingPiece == QUEST_ACCEPTED and not(player:hasKeyItem(ANCIENT_TABLET_FRAGMENT))) then -- talk to again with quest activated player:startEvent(0x0007); elseif (TheMissingPiece == QUEST_ACCEPTED and player:hasKeyItem(ANCIENT_TABLET_FRAGMENT)) then -- successfully retrieve key item player:startEvent(0x0008); elseif (TheMissingPiece == QUEST_ACCEPTED and player:hasKeyItem(TABLET_OF_ANCIENT_MAGIC)) then -- They got their Key items. tell them to goto sandy player:startEvent(0x0009); else player:startEvent(0x0034); -- standard dialogue 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 == 0x0006) then player:addQuest(OUTLANDS,THE_MISSING_PIECE); elseif (csid == 0x0008) then -- give the player the key items he needs to complete the quest player:addKeyItem(TABLET_OF_ANCIENT_MAGIC); player:addKeyItem(LETTER_FROM_ALFESAR); player:delKeyItem(ANCIENT_TABLET_FRAGMENT); player:messageSpecial(KEYITEM_OBTAINED,TABLET_OF_ANCIENT_MAGIC); player:messageSpecial(KEYITEM_OBTAINED,LETTER_FROM_ALFESAR); end; end;
gpl-3.0
Turttle/darkstar
scripts/globals/mobskills/freezebite.lua
26
1287
----------------------------------- -- 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
omidtarh/fbot
plugins/danbooru.lua
616
1750
do local URL = "http://danbooru.donmai.us" local URL_NEW = "/posts.json" local URL_POP = "/explore/posts/popular.json" local scale_day = "?scale=day" local scale_week = "?scale=week" local scale_month = "?scale=month" local function get_post(url) local b, c, h = http.request(url) if c ~= 200 then return nil end local posts = json:decode(b) return posts[math.random(#posts)] end local function run(msg, matches) local url = URL if matches[1] == "!danbooru" then url = url .. URL_NEW else url = url .. URL_POP if matches[1] == "d" then url = url .. scale_day elseif matches[1] == "w" then url = url .. scale_week elseif matches[1] == "m" then url = url .. scale_month end end local post = get_post(url) if post then vardump(post) local img = URL .. post.large_file_url send_photo_from_url(get_receiver(msg), img) local txt = '' if post.tag_string_artist ~= '' then txt = 'Artist: ' .. post.tag_string_artist .. '\n' end if post.tag_string_character ~= '' then txt = txt .. 'Character: ' .. post.tag_string_character .. '\n' end if post.file_size ~= '' then txt = txt .. '[' .. math.ceil(post.file_size/1000) .. 'kb] ' .. URL .. post.file_url end return txt end end return { description = "Gets a random fresh or popular image from Danbooru", usage = { "!danbooru - gets a random fresh image from Danbooru 🔞", "!danboorud - random daily popular image 🔞", "!danbooruw - random weekly popular image 🔞", "!danboorum - random monthly popular image 🔞" }, patterns = { "^!danbooru$", "^!danbooru ?(d)$", "^!danbooru ?(w)$", "^!danbooru ?(m)$" }, run = run } end
gpl-2.0
adib1380/anit-spam-2
plugins/danbooru.lua
616
1750
do local URL = "http://danbooru.donmai.us" local URL_NEW = "/posts.json" local URL_POP = "/explore/posts/popular.json" local scale_day = "?scale=day" local scale_week = "?scale=week" local scale_month = "?scale=month" local function get_post(url) local b, c, h = http.request(url) if c ~= 200 then return nil end local posts = json:decode(b) return posts[math.random(#posts)] end local function run(msg, matches) local url = URL if matches[1] == "!danbooru" then url = url .. URL_NEW else url = url .. URL_POP if matches[1] == "d" then url = url .. scale_day elseif matches[1] == "w" then url = url .. scale_week elseif matches[1] == "m" then url = url .. scale_month end end local post = get_post(url) if post then vardump(post) local img = URL .. post.large_file_url send_photo_from_url(get_receiver(msg), img) local txt = '' if post.tag_string_artist ~= '' then txt = 'Artist: ' .. post.tag_string_artist .. '\n' end if post.tag_string_character ~= '' then txt = txt .. 'Character: ' .. post.tag_string_character .. '\n' end if post.file_size ~= '' then txt = txt .. '[' .. math.ceil(post.file_size/1000) .. 'kb] ' .. URL .. post.file_url end return txt end end return { description = "Gets a random fresh or popular image from Danbooru", usage = { "!danbooru - gets a random fresh image from Danbooru 🔞", "!danboorud - random daily popular image 🔞", "!danbooruw - random weekly popular image 🔞", "!danboorum - random monthly popular image 🔞" }, patterns = { "^!danbooru$", "^!danbooru ?(d)$", "^!danbooru ?(w)$", "^!danbooru ?(m)$" }, run = run } end
gpl-2.0
Turttle/darkstar
scripts/zones/La_Theine_Plateau/npcs/Augevinne.lua
17
1569
----------------------------------- -- Area: La Theine Plateau -- NPC: Augevinne -- Involved in Mission: The Rescue Drill -- @pos -361 39 266 102 ----------------------------------- package.loaded["scripts/zones/La_Theine_Plateau/TextIDs"] = nil; ----------------------------------- require("scripts/globals/missions"); require("scripts/zones/La_Theine_Plateau/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getCurrentMission(SANDORIA) == THE_RESCUE_DRILL) then local MissionStatus = player:getVar("MissionStatus"); if (MissionStatus >= 5 and MissionStatus <= 7) then player:startEvent(0x0067); elseif (MissionStatus == 8) then player:showText(npc, RESCUE_DRILL + 21); elseif (MissionStatus >= 9) then player:showText(npc, RESCUE_DRILL + 26); else player:showText(npc, RESCUE_DRILL); end else player:showText(npc, RESCUE_DRILL); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
SalvationDevelopment/Salvation-Scripts-TCG
c96864105.lua
2
1886
--CNo.73 激瀧瀑神アビス・スープラ function c96864105.initial_effect(c) --xyz summon aux.AddXyzProcedure(c,nil,6,3) c:EnableReviveLimit() --atk up local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(96864105,0)) e1:SetCategory(CATEGORY_ATKCHANGE) e1:SetType(EFFECT_TYPE_QUICK_O) e1:SetCode(EVENT_PRE_DAMAGE_CALCULATE) e1:SetRange(LOCATION_MZONE) e1:SetCondition(c96864105.atkcon) e1:SetCost(c96864105.atkcost) e1:SetOperation(c96864105.atkop) c:RegisterEffect(e1) --indes local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_SINGLE) e2:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e2:SetRange(LOCATION_MZONE) e2:SetCode(EFFECT_INDESTRUCTABLE_EFFECT) e2:SetCondition(c96864105.indcon) e2:SetValue(1) c:RegisterEffect(e2) end c96864105.xyz_number=73 function c96864105.atkcon(e,tp,eg,ep,ev,re,r,rp) local a=Duel.GetAttacker() local d=Duel.GetAttackTarget() return d and a:GetControler()~=d:GetControler() end function c96864105.atkcost(e,tp,eg,ep,ev,re,r,rp,chk) local c=e:GetHandler() if chk==0 then return c:CheckRemoveOverlayCard(tp,1,REASON_COST) and c:GetFlagEffect(96864105)==0 end c:RemoveOverlayCard(tp,1,1,REASON_COST) c:RegisterFlagEffect(96864105,RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_DAMAGE_CAL,0,1) end function c96864105.atkop(e,tp,eg,ep,ev,re,r,rp) local a=Duel.GetAttacker() local d=Duel.GetAttackTarget() if not a:IsRelateToBattle() or a:IsFacedown() or not d:IsRelateToBattle() or d:IsFacedown() then return end if a:IsControler(1-tp) then a,d=d,a end local e1=Effect.CreateEffect(e:GetHandler()) e1:SetOwnerPlayer(tp) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_UPDATE_ATTACK) e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_DAMAGE_CAL) e1:SetValue(d:GetAttack()) a:RegisterEffect(e1) end function c96864105.indcon(e) return e:GetHandler():GetOverlayGroup():IsExists(Card.IsCode,1,nil,36076683) end
gpl-2.0
SalvationDevelopment/Salvation-Scripts-TCG
c100912013.lua
2
3729
--LL-サファイア・スワロー --Lyrical Luscinia - Sapphire Swallow --Scripted by Eerie Code function c100912013.initial_effect(c) --Special Summon local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(100912013,0)) e1:SetCategory(CATEGORY_SPECIAL_SUMMON) e1:SetType(EFFECT_TYPE_IGNITION) e1:SetRange(LOCATION_HAND) e1:SetCountLimit(1,100912013) e1:SetCondition(c100912013.spcon) e1:SetTarget(c100912013.sptg) e1:SetOperation(c100912013.spop) c:RegisterEffect(e1) --effect gain local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS) e2:SetCode(EVENT_BE_MATERIAL) e2:SetCondition(c100912013.efcon) e2:SetOperation(c100912013.efop) c:RegisterEffect(e2) end function c100912013.cfilter(c) return c:IsFaceup() and c:IsRace(RACE_WINDBEAST) end function c100912013.spcon(e,tp,eg,ep,ev,re,r,rp) return Duel.IsExistingMatchingCard(c100912013.cfilter,tp,LOCATION_MZONE,0,1,nil) end function c100912013.spfilter(c,e,tp) return c:IsRace(RACE_WINDBEAST) and c:GetLevel()==1 and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function c100912013.sptg(e,tp,eg,ep,ev,re,r,rp,chk) local c=e:GetHandler() if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>1 and not Duel.IsPlayerAffectedByEffect(tp,59822133) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) and Duel.IsExistingMatchingCard(c100912013.spfilter,tp,LOCATION_HAND,0,1,c,e,tp) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,2,tp,LOCATION_HAND) end function c100912013.spop(e,tp,eg,ep,ev,re,r,rp) if Duel.GetLocationCount(tp,LOCATION_MZONE)<2 or Duel.IsPlayerAffectedByEffect(tp,59822133) then return end local c=e:GetHandler() if not c:IsRelateToEffect(e) then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectMatchingCard(tp,c100912013.spfilter,tp,LOCATION_HAND,0,1,1,c,e,tp) if g:GetCount()>0 then g:AddCard(c) Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP) end end function c100912013.efcon(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() return r==REASON_XYZ and c:GetReasonCard():IsAttribute(ATTRIBUTE_WIND) end function c100912013.efop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local rc=c:GetReasonCard() local p=rc:GetControler() local e1=Effect.CreateEffect(rc) e1:SetDescription(aux.Stringid(100912013,1)) e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e1:SetCode(EVENT_SPSUMMON_SUCCESS) e1:SetProperty(EFFECT_FLAG_DELAY+EFFECT_FLAG_CARD_TARGET) e1:SetCondition(c100912013.xyzcon) e1:SetTarget(c100912013.xyztg) e1:SetOperation(c100912013.xyzop) e1:SetReset(RESET_EVENT+0x1fe0000) rc:RegisterEffect(e1,true) if not rc:IsType(TYPE_EFFECT) then local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_SINGLE) e2:SetCode(EFFECT_ADD_TYPE) e2:SetValue(TYPE_EFFECT) e2:SetReset(RESET_EVENT+0x1fe0000) rc:RegisterEffect(e2,true) end end function c100912013.xyzcon(e,tp,eg,ep,ev,re,r,rp) return bit.band(e:GetHandler():GetSummonType(),SUMMON_TYPE_XYZ)==SUMMON_TYPE_XYZ end function c100912013.xyzfilter(c) return (c:IsSetCard(0x1f8) or c:IsCode(8491961)) and c:IsType(TYPE_MONSTER) end function c100912013.xyztg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsControler(tp) and chkc:IsLocation(LOCATION_GRAVE) and c100912013.xyzfilter(chkc) end if chk==0 then return Duel.IsExistingTarget(c100912013.xyzfilter,tp,LOCATION_GRAVE,0,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP) Duel.SelectTarget(tp,c100912013.xyzfilter,tp,LOCATION_GRAVE,0,1,1,nil) end function c100912013.xyzop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local tc=Duel.GetFirstTarget() if c:IsFaceup() and c:IsRelateToEffect(e) and tc:IsRelateToEffect(e) then Duel.Overlay(c,Group.FromCards(tc)) end end
gpl-2.0
SalvationDevelopment/Salvation-Scripts-TCG
c1580833.lua
2
2140
--ダイナミスト・ステゴサウラー function c1580833.initial_effect(c) --pendulum summon aux.EnablePendulumAttribute(c) --destroy replace local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_CONTINUOUS+EFFECT_TYPE_FIELD) e2:SetCode(EFFECT_DESTROY_REPLACE) e2:SetRange(LOCATION_PZONE) e2:SetTarget(c1580833.reptg) e2:SetValue(c1580833.repval) e2:SetOperation(c1580833.repop) c:RegisterEffect(e2) --destroy local e3=Effect.CreateEffect(c) e3:SetCategory(CATEGORY_DESTROY) e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O) e3:SetCode(EVENT_BATTLED) e3:SetRange(LOCATION_MZONE) e3:SetCondition(c1580833.descon) e3:SetTarget(c1580833.destg) e3:SetOperation(c1580833.desop) c:RegisterEffect(e3) end function c1580833.filter(c,tp) return c:IsFaceup() and c:IsControler(tp) and c:IsLocation(LOCATION_ONFIELD) and c:IsSetCard(0xd8) and (c:IsReason(REASON_BATTLE) or (c:IsReason(REASON_EFFECT) and c:GetReasonPlayer()~=tp)) end function c1580833.reptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return eg:IsExists(c1580833.filter,1,e:GetHandler(),tp) and not e:GetHandler():IsStatus(STATUS_DESTROY_CONFIRMED) end return Duel.SelectYesNo(tp,aux.Stringid(1580833,0)) end function c1580833.repval(e,c) return c1580833.filter(c,e:GetHandlerPlayer()) end function c1580833.repop(e,tp,eg,ep,ev,re,r,rp) Duel.Destroy(e:GetHandler(),REASON_EFFECT+REASON_REPLACE) end function c1580833.descon(e,tp,eg,ep,ev,re,r,rp) local a=Duel.GetAttacker() local d=Duel.GetAttackTarget() if not d then return false end if d:IsControler(tp) then a,d=d,a end return a:IsType(TYPE_PENDULUM) and a~=e:GetHandler() and d:IsControler(1-tp) end function c1580833.destg(e,tp,eg,ep,ev,re,r,rp,chk) local a=Duel.GetAttacker() local d=Duel.GetAttackTarget() if chk==0 then return a:IsDestructable() and d:IsDestructable() end local g=Group.FromCards(a,d) Duel.SetTargetCard(g) Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,2,0,0) end function c1580833.desop(e,tp,eg,ep,ev,re,r,rp) local g=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS):Filter(Card.IsRelateToEffect,nil,e) if g:GetCount()>0 then Duel.Destroy(g,REASON_EFFECT) end end
gpl-2.0
Turttle/darkstar
scripts/zones/RuAun_Gardens/npcs/HomePoint#5.lua
17
1250
----------------------------------- -- Area: RuAun_Gardens -- NPC: HomePoint#5 -- @pos 305 -42 -427 130 ----------------------------------- package.loaded["scripts/zones/RuAun_Gardens/TextIDs"] = nil; require("scripts/globals/settings"); require("scripts/zones/RuAun_Gardens/TextIDs"); require("scripts/globals/homepoint"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) homepointMenu( player, 0x2200, 63); 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 == 0x2200) then if (option == 1) then player:setHomePoint(); player:messageSpecial(HOMEPOINT_SET); else hpTeleport( player, option); end end end;
gpl-3.0
dickeyf/darkstar
scripts/zones/Buburimu_Peninsula/npcs/Stone_Monument.lua
13
1284
----------------------------------- -- Area: Buburimu Peninsula -- NPC: Stone Monument -- Involved in quest "An Explorer's Footsteps" -- @pos 320.755 -4.000 368.722 118 ----------------------------------- package.loaded["scripts/zones/Buburimu_Peninsula/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Buburimu_Peninsula/TextIDs"); ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0384); end; ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) if (trade:getItemCount() == 1 and trade:hasItemQty(571,1)) then player:tradeComplete(); player:addItem(570); player:messageSpecial(ITEM_OBTAINED,570); player:setVar("anExplorer-CurrentTablet",0x02000); 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
SalvationDevelopment/Salvation-Scripts-TCG
c100212002.lua
2
4561
--調弦の魔術師 --Tune Magician --Script by mercury233 --fusion and xyz limit not implemented function c100212002.initial_effect(c) --pendulum summon aux.EnablePendulumAttribute(c) --atk&def local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_FIELD) e1:SetCode(EFFECT_UPDATE_ATTACK) e1:SetRange(LOCATION_PZONE) e1:SetTargetRange(LOCATION_MZONE,0) e1:SetValue(c100212002.atkval) c:RegisterEffect(e1) local e2=e1:Clone() e2:SetCode(EFFECT_UPDATE_DEFENSE) c:RegisterEffect(e2) --cannot special summon local e3=Effect.CreateEffect(c) e3:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE+EFFECT_FLAG_SINGLE_RANGE) e3:SetType(EFFECT_TYPE_SINGLE) e3:SetRange(LOCATION_EXTRA) e3:SetCode(EFFECT_SPSUMMON_CONDITION) e3:SetValue(aux.FALSE) c:RegisterEffect(e3) --synchro custom local e4=Effect.CreateEffect(c) e4:SetType(EFFECT_TYPE_SINGLE) e4:SetCode(EFFECT_SYNCHRO_MATERIAL_CUSTOM) e4:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE) e4:SetTarget(c100212002.syntg) e4:SetValue(1) e4:SetOperation(c100212002.synop) c:RegisterEffect(e4) --fusion and xyz custom not implemented --local e5=Effect.CreateEffect(c) --local e6=Effect.CreateEffect(c) --spsummon success local e7=Effect.CreateEffect(c) e7:SetDescription(aux.Stringid(100212002,0)) e7:SetCategory(CATEGORY_SPECIAL_SUMMON) e7:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e7:SetCode(EVENT_SPSUMMON_SUCCESS) e7:SetCountLimit(1,100212002) e7:SetCondition(c100212002.spcon) e7:SetTarget(c100212002.sptg) e7:SetOperation(c100212002.spop) c:RegisterEffect(e7) end function c100212002.tuner_filter(c) return c:IsSetCard(0x98) and c:IsType(TYPE_PENDULUM) end function c100212002.atkfilter(c) return c:IsFaceup() and c:IsSetCard(0x98) and c:IsType(TYPE_PENDULUM) end function c100212002.atkval(e,c) local g=Duel.GetMatchingGroup(c100212002.atkfilter,c:GetControler(),LOCATION_EXTRA,0,nil) return g:GetClassCount(Card.GetCode)*100 end function c100212002.synfilter(c,syncard,tuner,f) return c:IsFaceup() and c:IsNotTuner() and c:IsCanBeSynchroMaterial(syncard,tuner) and c:IsSetCard(0x98) and c:IsType(TYPE_PENDULUM) and (f==nil or f(c)) end function c100212002.syntg(e,syncard,f,minc,maxc) local c=e:GetHandler() local lv=syncard:GetLevel()-c:GetLevel() if lv<=0 then return false end local g=Duel.GetMatchingGroup(c100212002.synfilter,syncard:GetControler(),LOCATION_MZONE,LOCATION_MZONE,c,syncard,c,f) local res=g:CheckWithSumEqual(Card.GetSynchroLevel,lv,minc,maxc,syncard) return res end function c100212002.synop(e,tp,eg,ep,ev,re,r,rp,syncard,f,minc,maxc) local c=e:GetHandler() local lv=syncard:GetLevel()-c:GetLevel() local g=Duel.GetMatchingGroup(c100212002.synfilter,syncard:GetControler(),LOCATION_MZONE,LOCATION_MZONE,c,syncard,c,f) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SMATERIAL) local sg=g:SelectWithSumEqual(tp,Card.GetSynchroLevel,lv,minc,maxc,syncard) Duel.SetSynchroMaterial(sg) end function c100212002.spcon(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() return c:GetSummonType()==SUMMON_TYPE_PENDULUM and c:IsPreviousLocation(LOCATION_HAND) end function c100212002.spfilter(c,e,tp) return c:IsSetCard(0x98) and c:IsType(TYPE_PENDULUM) and not c:IsCode(100212002) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function c100212002.sptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingMatchingCard(c100212002.spfilter,tp,LOCATION_DECK,0,1,nil,e,tp) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK) end function c100212002.spop(e,tp,eg,ep,ev,re,r,rp) if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectMatchingCard(tp,c100212002.spfilter,tp,LOCATION_DECK,0,1,1,nil,e,tp) local tc=g:GetFirst() if tc and Duel.SpecialSummonStep(tc,0,tp,tp,false,false,POS_FACEUP_DEFENSE) then local c=e:GetHandler() local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_DISABLE) e1:SetReset(RESET_EVENT+0x1fe0000) tc:RegisterEffect(e1,true) local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_SINGLE) e2:SetCode(EFFECT_DISABLE_EFFECT) e2:SetReset(RESET_EVENT+0x1fe0000) tc:RegisterEffect(e2,true) local e3=Effect.CreateEffect(c) e3:SetType(EFFECT_TYPE_SINGLE) e3:SetCode(EFFECT_LEAVE_FIELD_REDIRECT) e3:SetProperty(EFFECT_FLAG_CANNOT_DISABLE) e3:SetReset(RESET_EVENT+0x47e0000) e3:SetValue(LOCATION_REMOVED) tc:RegisterEffect(e3,true) Duel.SpecialSummonComplete() end end
gpl-2.0
SalvationDevelopment/Salvation-Scripts-TCG
c11264180.lua
2
2124
--TGX1-HL function c11264180.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_ATKCHANGE+CATEGORY_DESTROY) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DAMAGE_STEP) e1:SetCode(EVENT_FREE_CHAIN) e1:SetHintTiming(TIMING_DAMAGE_STEP) e1:SetCondition(c11264180.condition) e1:SetTarget(c11264180.target) e1:SetOperation(c11264180.activate) c:RegisterEffect(e1) end function c11264180.condition(e,tp,eg,ep,ev,re,r,rp) return Duel.GetCurrentPhase()~=PHASE_DAMAGE or not Duel.IsDamageCalculated() end function c11264180.filter(c) return c:IsFaceup() and c:IsSetCard(0x27) end function c11264180.dfilter(c) return c:IsType(TYPE_SPELL+TYPE_TRAP) end function c11264180.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(tp) and c11264180.filter(chkc) end if chk==0 then return Duel.IsExistingTarget(c11264180.filter,tp,LOCATION_MZONE,0,1,nil) and Duel.IsExistingMatchingCard(c11264180.dfilter,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,e:GetHandler()) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP) Duel.SelectTarget(tp,c11264180.filter,tp,LOCATION_MZONE,0,1,1,nil) local dg=Duel.GetMatchingGroup(c11264180.dfilter,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,e:GetHandler()) Duel.SetOperationInfo(0,CATEGORY_DESTROY,dg,1,0,0) end function c11264180.activate(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if not tc:IsRelateToEffect(e) or tc:IsFacedown() then return end local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_SET_ATTACK_FINAL) e1:SetReset(RESET_EVENT+0x1fe0000) e1:SetValue(tc:GetAttack()/2) tc:RegisterEffect(e1) local e2=Effect.CreateEffect(e:GetHandler()) e2:SetType(EFFECT_TYPE_SINGLE) e2:SetCode(EFFECT_SET_DEFENSE_FINAL) e2:SetReset(RESET_EVENT+0x1fe0000) e2:SetValue(tc:GetDefense()/2) tc:RegisterEffect(e2) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY) local dg=Duel.SelectMatchingCard(tp,c11264180.dfilter,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,1,e:GetHandler()) Duel.Destroy(dg,REASON_EFFECT) end
gpl-2.0
dickeyf/darkstar
scripts/zones/Port_San_dOria/npcs/Ilgusin.lua
13
1053
----------------------------------- -- Area: Port San d'Oria -- NPC: Ilgusin -- Type: Standard NPC -- @zone: 232 -- @pos -68.313 -6.5 -36.985 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x024f); 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
dickeyf/darkstar
scripts/zones/Yhoator_Jungle/npcs/Logging_Point.lua
13
1068
----------------------------------- -- Area: Yhoator Jungle -- NPC: Logging Point ----------------------------------- package.loaded["scripts/zones/Yhoator_Jungle/TextIDs"] = nil; ------------------------------------- require("scripts/globals/logging"); require("scripts/zones/Yhoator_Jungle/TextIDs"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) startLogging(player,player:getZoneID(),npc,trade,0x000A); end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) player:messageSpecial(LOGGING_IS_POSSIBLE_HERE,1021); 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
Turttle/darkstar
scripts/globals/weaponskills/shadowstitch.lua
18
1531
----------------------------------- -- Shadowstitch -- Dagger weapon skill -- Skill level: 70 -- Binds target. Chance of binding varies with TP. -- Does stack with Sneak Attack. -- Aligned with the Aqua Gorget. -- Aligned with the Aqua Belt. -- Element: None -- Modifiers: CHR:100% -- 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 = 1; params.ftp100 = 1; params.ftp200 = 1; params.ftp300 = 1; params.str_wsc = 0.0; 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.3; params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0; params.canCrit = false; params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0; params.atkmulti = 1; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.chr_wsc = 1.0; end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params); if damage > 0 then local tp = player:getTP(); local duration = (tp/100 * 5) + 5; if (target:hasStatusEffect(EFFECT_BIND) == false) then target:addStatusEffect(EFFECT_BIND, 1, 0, duration); end end damage = damage * WEAPON_SKILL_POWER return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
Andrew-Collins/nodemcu-firmware
app/cjson/tests/bench.lua
145
3247
#!/usr/bin/env lua -- This benchmark script measures wall clock time and should be -- run on an unloaded system. -- -- Your Mileage May Vary. -- -- Mark Pulford <mark@kyne.com.au> local json_module = os.getenv("JSON_MODULE") or "cjson" require "socket" local json = require(json_module) local util = require "cjson.util" local function find_func(mod, funcnames) for _, v in ipairs(funcnames) do if mod[v] then return mod[v] end end return nil end local json_encode = find_func(json, { "encode", "Encode", "to_string", "stringify", "json" }) local json_decode = find_func(json, { "decode", "Decode", "to_value", "parse" }) local function average(t) local total = 0 for _, v in ipairs(t) do total = total + v end return total / #t end function benchmark(tests, seconds, rep) local function bench(func, iter) -- Use socket.gettime() to measure microsecond resolution -- wall clock time. local t = socket.gettime() for i = 1, iter do func(i) end t = socket.gettime() - t -- Don't trust any results when the run lasted for less than a -- millisecond - return nil. if t < 0.001 then return nil end return (iter / t) end -- Roughly calculate the number of interations required -- to obtain a particular time period. local function calc_iter(func, seconds) local iter = 1 local rate -- Warm up the bench function first. func() while not rate do rate = bench(func, iter) iter = iter * 10 end return math.ceil(seconds * rate) end local test_results = {} for name, func in pairs(tests) do -- k(number), v(string) -- k(string), v(function) -- k(number), v(function) if type(func) == "string" then name = func func = _G[name] end local iter = calc_iter(func, seconds) local result = {} for i = 1, rep do result[i] = bench(func, iter) end -- Remove the slowest half (round down) of the result set table.sort(result) for i = 1, math.floor(#result / 2) do table.remove(result, 1) end test_results[name] = average(result) end return test_results end function bench_file(filename) local data_json = util.file_load(filename) local data_obj = json_decode(data_json) local function test_encode() json_encode(data_obj) end local function test_decode() json_decode(data_json) end local tests = {} if json_encode then tests.encode = test_encode end if json_decode then tests.decode = test_decode end return benchmark(tests, 0.1, 5) end -- Optionally load any custom configuration required for this module local success, data = pcall(util.file_load, ("bench-%s.lua"):format(json_module)) if success then util.run_script(data, _G) configure(json) end for i = 1, #arg do local results = bench_file(arg[i]) for k, v in pairs(results) do print(("%s\t%s\t%d"):format(arg[i], k, v)) end end -- vi:ai et sw=4 ts=4:
mit
nashuiliang/ABTestingGateway
admin/ab_action.lua
4
2681
local policyModule = require('abtesting.adapter.policy') local redisModule = require('abtesting.utils.redis') local systemConf = require('abtesting.utils.init') local handler = require('abtesting.error.handler').handler local utils = require('abtesting.utils.utils') local log = require('abtesting.utils.log') local ERRORINFO = require('abtesting.error.errcode').info local policy = require("admin.policy") local runtime = require('admin.runtime') local policygroup = require("admin.policygroup") local cjson = require('cjson.safe') local doresp = utils.doresp local dolog = utils.dolog local redisConf = systemConf.redisConf local divtypes = systemConf.divtypes local prefixConf = systemConf.prefixConf local policyLib = prefixConf.policyLibPrefix local runtimeLib = prefixConf.runtimeInfoPrefix local domain_name = prefixConf.domainname local ab_action = {} ab_action.policy_check = policy.check ab_action.policy_set = policy.set ab_action.policy_get = policy.get ab_action.policy_del = policy.del ab_action.runtime_set = runtime.set ab_action.runtime_del = runtime.del ab_action.runtime_get = runtime.get ab_action.policygroup_check = policygroup.check ab_action.policygroup_set = policygroup.set ab_action.policygroup_get = policygroup.get ab_action.policygroup_del = policygroup.del local get_uriargs_error = function() local info = ERRORINFO.ACTION_BLANK_ERROR local response = doresp(info, 'user req') log:errlog(dolog(info, desc)) ngx.say(response) return end local get_action_error = function() local info = ERRORINFO.ACTION_BLANK_ERROR local response = doresp(info, 'user req') log:errlog(dolog(info, desc)) ngx.say(response) return end local do_action_error = function(action) local info = ERRORINFO.DOACTION_ERROR local desc = action local response = doresp(info, desc) local errlog = dolog(info, desc) log:errlog(errlog) ngx.say(response) return end local red = redisModule:new(redisConf) local ok, err = red:connectdb() if not ok then local info = ERRORINFO.REDIS_CONNECT_ERROR local response = doresp(info, err) log:errlog(dolog(info, desc)) ngx.say(response) return end local args = ngx.req.get_uri_args() if args then local action = args.action local do_action = ab_action[action] if do_action then do_action({['db']=red}) -- local ok, info = do_action(policy, {['db']=red}) -- if not ok then -- do_action_error() -- end else do_action_error(action) end else get_uriargs_error() end
mit
SalvationDevelopment/Salvation-Scripts-TCG
c40659562.lua
2
1505
--守護者スフィンクス function c40659562.initial_effect(c) --turn set local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(40659562,0)) e1:SetCategory(CATEGORY_POSITION) e1:SetType(EFFECT_TYPE_IGNITION) e1:SetRange(LOCATION_MZONE) e1:SetTarget(c40659562.target) e1:SetOperation(c40659562.operation) c:RegisterEffect(e1) --to hand local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(40659562,1)) e2:SetCategory(CATEGORY_TOHAND) e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F) e2:SetCode(EVENT_FLIP_SUMMON_SUCCESS) e2:SetTarget(c40659562.thtg) e2:SetOperation(c40659562.thop) c:RegisterEffect(e2) end function c40659562.target(e,tp,eg,ep,ev,re,r,rp,chk) local c=e:GetHandler() if chk==0 then return c:IsCanTurnSet() and c:GetFlagEffect(40659562)==0 end c:RegisterFlagEffect(40659562,RESET_EVENT+0x1fc0000+RESET_PHASE+PHASE_END,0,1) Duel.SetOperationInfo(0,CATEGORY_POSITION,c,1,0,0) end function c40659562.operation(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if c:IsRelateToEffect(e) and c:IsFaceup() then Duel.ChangePosition(c,POS_FACEDOWN_DEFENSE) end end function c40659562.thtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end local g=Duel.GetMatchingGroup(Card.IsAbleToHand,tp,0,LOCATION_MZONE,nil) Duel.SetOperationInfo(0,CATEGORY_TOHAND,g,g:GetCount(),0,0) end function c40659562.thop(e,tp,eg,ep,ev,re,r,rp) local g=Duel.GetMatchingGroup(Card.IsAbleToHand,tp,0,LOCATION_MZONE,nil) Duel.SendtoHand(g,nil,REASON_EFFECT) end
gpl-2.0
dickeyf/darkstar
scripts/globals/weaponskills/shining_strike.lua
11
1313
----------------------------------- -- Shining Strike -- Club weapon skill -- Skill level: 5 -- Deals light elemental damage to enemy. Damage varies with TP. -- Aligned with the Thunder Gorget. -- Aligned with the Thunder Belt. -- Element: None -- Modifiers: STR:40% ; MND:40% -- 100%TP 200%TP 300%TP -- 1.625 3 4.625 ----------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID, tp, primary) local params = {}; params.ftp100 = 1; params.ftp200 = 1.75; params.ftp300 = 2.5; params.str_wsc = 0.2; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.2; params.chr_wsc = 0.0; params.ele = ELE_LIGHT; params.skill = SKILL_CLB; params.includemab = true; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.ftp100 = 1.625; params.ftp200 = 3; params.ftp300 = 4.625; params.str_wsc = 0.4; params.mnd_wsc = 0.4; end local damage, criticalHit, tpHits, extraHits = doMagicWeaponskill(player, target, wsID, params, tp, primary); return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
SalvationDevelopment/Salvation-Scripts-TCG
c511001416.lua
2
1249
--Iron Hans function c511001416.initial_effect(c) --spsummon local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_SPECIAL_SUMMON) e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e1:SetProperty(EFFECT_FLAG_DAMAGE_STEP) e1:SetCode(EVENT_SUMMON_SUCCESS) e1:SetTarget(c511001416.sptg) e1:SetOperation(c511001416.spop) c:RegisterEffect(e1) local e2=e1:Clone() e2:SetCode(EVENT_FLIP_SUMMON_SUCCESS) c:RegisterEffect(e2) local e3=e1:Clone() e3:SetCode(EVENT_SPSUMMON_SUCCESS) c:RegisterEffect(e3) end function c511001416.filter(c,e,tp) return c:IsCode(511001415) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function c511001416.sptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingMatchingCard(c511001416.filter,tp,LOCATION_DECK,0,1,nil,e,tp) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK) end function c511001416.spop(e,tp,eg,ep,ev,re,r,rp) if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectMatchingCard(tp,c511001416.filter,tp,LOCATION_DECK,0,1,1,nil,e,tp) if g:GetCount()>0 then Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP) end end
gpl-2.0
dickeyf/darkstar
scripts/zones/Apollyon/mobs/Proto-Omega.lua
8
3205
----------------------------------- -- Area: Apollyon (Central) -- MOB: Proto-Omega ----------------------------------- package.loaded["scripts/zones/Apollyon/TextIDs"] = nil; ----------------------------------- require("scripts/globals/limbus"); require("scripts/zones/Apollyon/TextIDs"); require("scripts/globals/titles"); require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------- -- onMobInitialize Action ----------------------------------- function onMobInitialize(mob) mob:setMobMod(MOBMOD_ADD_EFFECT,mob:getShortID()); end; ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) mob:setMobMod(MOBMOD_SUPERLINK, mob:getShortID()); mob:setMod(MOD_UDMGPHYS, -75); mob:setMod(MOD_UDMGRANGE, -75); mob:setMod(MOD_UDMGMAGIC, 0); end; ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob,target) local mobID = mob:getID(); local formTime = mob:getLocalVar("formWait") local lifePercent = mob:getHPP(); local currentForm = mob:getLocalVar("form") if (lifePercent < 70 and currentForm < 1) then currentForm = 1; mob:setLocalVar("form", currentForm) mob:AnimationSub(2); formTime = os.time() + 60; mob:setMod(MOD_UDMGPHYS, 0); mob:setMod(MOD_UDMGRANGE, 0); mob:setMod(MOD_UDMGMAGIC, -75); end if (currentForm == 1) then if (formTime < os.time()) then if (mob:AnimationSub() == 1) then mob:AnimationSub(2); else mob:AnimationSub(1); end mob:setLocalVar("formWait", os.time() + 60); end if (lifePercent < 30) then mob:AnimationSub(2); mob:setMod(MOD_UDMGPHYS, -50); mob:setMod(MOD_UDMGRANGE, -50); mob:setMod(MOD_UDMGMAGIC, -50); mob:addStatusEffect(EFFECT_REGAIN,7,3,0); -- The final form has Regain, mob:getStatusEffect(EFFECT_REGAIN):setFlag(32); currentForm = 2; mob:setLocalVar("form", currentForm) end end end; ----------------------------------- -- onAdditionalEffect ----------------------------------- function onAdditionalEffect(mob, player) local chance = 20; -- wiki lists ~20% stun chance local resist = applyResistanceAddEffect(mob,player,ELE_THUNDER,EFFECT_STUN); if (math.random(0,99) >= chance or resist <= 0.5) then return 0,0,0; else local duration = 5 * resist; if (player:hasStatusEffect(EFFECT_STUN) == false) then player:addStatusEffect(EFFECT_STUN, 0, 0, duration); end return SUBEFFECT_STUN, MSGBASIC_ADD_EFFECT_STATUS, EFFECT_STUN; end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer,ally) ally:addTitle(APOLLYON_RAVAGER); local mobX = mob:getXPos(); local mobY = mob:getYPos(); local mobZ = mob:getZPos(); GetNPCByID(16932864+39):setPos(mobX,mobY,mobZ); GetNPCByID(16932864+39):setStatus(STATUS_NORMAL); end;
gpl-3.0
wljcom/vlc
share/lua/modules/simplexml.lua
103
3732
--[==========================================================================[ simplexml.lua: Lua simple xml parser wrapper --[==========================================================================[ Copyright (C) 2010 Antoine Cellerier $Id$ Authors: Antoine Cellerier <dionoea at videolan dot org> 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. --]==========================================================================] module("simplexml",package.seeall) --[[ Returns the xml tree structure -- Each node is of one of the following types: -- { name (string), attributes (key->value map), children (node array) } -- text content (string) --]] local function parsexml(stream, errormsg) if not stream then return nil, errormsg end local xml = vlc.xml() local reader = xml:create_reader(stream) local tree local parents = {} local nodetype, nodename = reader:next_node() while nodetype > 0 do if nodetype == 1 then local node = { name= nodename, attributes= {}, children= {} } local attr, value = reader:next_attr() while attr ~= nil do node.attributes[attr] = value attr, value = reader:next_attr() end if tree then table.insert(tree.children, node) table.insert(parents, tree) end tree = node elseif nodetype == 2 then if #parents > 0 then local tmp = {} while nodename ~= tree.name do if #parents == 0 then error("XML parser error/faulty logic") end local child = tree tree = parents[#parents] table.remove(parents) table.remove(tree.children) table.insert(tmp, 1, child) for i, node in pairs(child.children) do table.insert(tmp, i+1, node) end child.children = {} end for _, node in pairs(tmp) do table.insert(tree.children, node) end tree = parents[#parents] table.remove(parents) end elseif nodetype == 3 then table.insert(tree.children, nodename) end nodetype, nodename = reader:next_node() end if #parents > 0 then error("XML parser error/Missing closing tags") end return tree end function parse_url(url) return parsexml(vlc.stream(url)) end function parse_string(str) return parsexml(vlc.memory_stream(str)) end function add_name_maps(tree) tree.children_map = {} for _, node in pairs(tree.children) do if type(node) == "table" then if not tree.children_map[node.name] then tree.children_map[node.name] = {} end table.insert(tree.children_map[node.name], node) add_name_maps(node) end end end
gpl-2.0
Turttle/darkstar
scripts/globals/abilities/pets/stone_iv.lua
20
1151
--------------------------------------------------- -- Stone 4 --------------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); require("scripts/globals/magic"); --------------------------------------------------- function onAbilityCheck(player, target, ability) return 0,0; end; function onPetAbility(target, pet, skill) local spell = getSpell(162); --calculate raw damage local dmg = calculateMagicDamage(381,2,pet,spell,target,ELEMENTAL_MAGIC_SKILL,MOD_INT,false); --get resist multiplier (1x if no resist) local resist = applyPlayerResistance(pet,-1,target,pet:getStat(MOD_INT)-target:getStat(MOD_INT),ELEMENTAL_MAGIC_SKILL, 2); --get the resisted damage dmg = dmg*resist; --add on bonuses (staff/day/weather/jas/mab/etc all go in this function) dmg = mobAddBonuses(pet,spell,target,dmg, 2); --add on TP bonuses local tp = skill:getTP(); if tp < 100 then tp = 100; end dmg = dmg * tp / 100; --add in final adjustments dmg = finalMagicAdjustments(pet,target,spell,dmg); return dmg; end
gpl-3.0
SalvationDevelopment/Salvation-Scripts-TCG
c2530830.lua
2
3195
--銀河眼の光波刃竜 function c2530830.initial_effect(c) --xyz summon aux.AddXyzProcedure(c,nil,9,3,c2530830.ovfilter,aux.Stringid(2530830,0)) c:EnableReviveLimit() --xyzlimit local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE) e1:SetCode(EFFECT_CANNOT_BE_XYZ_MATERIAL) e1:SetValue(1) c:RegisterEffect(e1) --destroy local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(2530830,1)) e2:SetCategory(CATEGORY_DESTROY) e2:SetType(EFFECT_TYPE_IGNITION) e2:SetRange(LOCATION_MZONE) e2:SetProperty(EFFECT_FLAG_CARD_TARGET) e2:SetCountLimit(1) e2:SetCost(c2530830.descost) e2:SetTarget(c2530830.destg) e2:SetOperation(c2530830.desop) c:RegisterEffect(e2) --special summon local e3=Effect.CreateEffect(c) e3:SetDescription(aux.Stringid(2530830,2)) e3:SetCategory(CATEGORY_SPECIAL_SUMMON) e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e3:SetCode(EVENT_TO_GRAVE) e3:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DELAY) e3:SetCondition(c2530830.condition) e3:SetTarget(c2530830.target) e3:SetOperation(c2530830.operation) c:RegisterEffect(e3) end function c2530830.ovfilter(c) return c:IsFaceup() and c:IsSetCard(0x107b) and c:IsType(TYPE_XYZ) and c:GetRank()==8 end function c2530830.descost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():CheckRemoveOverlayCard(tp,1,REASON_COST) end e:GetHandler():RemoveOverlayCard(tp,1,1,REASON_COST) end function c2530830.destg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsOnField() end if chk==0 then return Duel.IsExistingTarget(aux.TRUE,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY) local g=Duel.SelectTarget(tp,aux.TRUE,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,1,nil) Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,1,0,0) end function c2530830.desop(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) then Duel.Destroy(tc,REASON_EFFECT) end end function c2530830.condition(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() return rp==1-tp and c:GetPreviousControler()==tp and c:IsPreviousLocation(LOCATION_MZONE) and c:IsReason(REASON_DESTROY) and (c:IsReason(REASON_EFFECT) or (c:IsReason(REASON_BATTLE) and Duel.GetAttacker():IsControler(1-tp))) and bit.band(c:GetSummonType(),SUMMON_TYPE_XYZ)==SUMMON_TYPE_XYZ end function c2530830.filter(c,e,tp) return c:IsCode(18963306) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function c2530830.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c2530830.filter(chkc,e,tp) end if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingTarget(c2530830.filter,tp,LOCATION_GRAVE,0,1,nil,e,tp) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectTarget(tp,c2530830.filter,tp,LOCATION_GRAVE,0,1,1,nil,e,tp) Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0) end function c2530830.operation(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) then Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP) end end
gpl-2.0
SalvationDevelopment/Salvation-Scripts-TCG
c50260683.lua
2
3215
--No.36 先史遺産-超機関フォーク=ヒューク function c50260683.initial_effect(c) --xyz summon aux.AddXyzProcedure(c,aux.FilterBoolFunction(Card.IsSetCard,0x70),4,2) c:EnableReviveLimit() --atkdown local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(50260683,0)) e1:SetCategory(CATEGORY_ATKCHANGE) e1:SetType(EFFECT_TYPE_QUICK_O) e1:SetCode(EVENT_FREE_CHAIN) e1:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DAMAGE_STEP) e1:SetHintTiming(TIMING_DAMAGE_STEP) e1:SetRange(LOCATION_MZONE) e1:SetCountLimit(1) e1:SetCondition(c50260683.condition) e1:SetCost(c50260683.cost) e1:SetTarget(c50260683.target) e1:SetOperation(c50260683.operation) c:RegisterEffect(e1) --destroy local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(50260683,1)) e2:SetCategory(CATEGORY_DESTROY) e2:SetType(EFFECT_TYPE_IGNITION) e2:SetProperty(EFFECT_FLAG_CARD_TARGET) e2:SetRange(LOCATION_MZONE) e2:SetCost(c50260683.descost) e2:SetTarget(c50260683.destg) e2:SetOperation(c50260683.desop) c:RegisterEffect(e2) end c50260683.xyz_number=36 function c50260683.condition(e,tp,eg,ep,ev,re,r,rp) return Duel.GetCurrentPhase()~=PHASE_DAMAGE or not Duel.IsDamageCalculated() end function c50260683.cost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():CheckRemoveOverlayCard(tp,1,REASON_COST) end e:GetHandler():RemoveOverlayCard(tp,1,1,REASON_COST) end function c50260683.filter(c) return c:IsFaceup() and c:GetAttack()>0 end function c50260683.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsControler(1-tp) and chkc:IsLocation(LOCATION_MZONE) and c50260683.filter(chkc) end if chk==0 then return Duel.IsExistingTarget(c50260683.filter,tp,0,LOCATION_MZONE,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP) Duel.SelectTarget(tp,c50260683.filter,tp,0,LOCATION_MZONE,1,1,nil) end function c50260683.operation(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsFaceup() and tc:IsRelateToEffect(e) and tc:GetAttack()>0 then local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_SET_ATTACK_FINAL) e1:SetValue(0) e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END) tc:RegisterEffect(e1) end end function c50260683.descost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.CheckReleaseGroup(tp,Card.IsSetCard,1,nil,0x70) end local g=Duel.SelectReleaseGroup(tp,Card.IsSetCard,1,1,nil,0x70) Duel.Release(g,REASON_COST) end function c50260683.filter2(c) return c:IsFaceup() and c:GetAttack()~=c:GetBaseAttack() end function c50260683.destg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(1-tp) and c50260683.filter2(chkc) end if chk==0 then return Duel.IsExistingTarget(c50260683.filter2,tp,0,LOCATION_MZONE,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY) local g=Duel.SelectTarget(tp,c50260683.filter2,tp,0,LOCATION_MZONE,1,1,nil) Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,1,0,0) end function c50260683.desop(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsFaceup() and tc:IsRelateToEffect(e) and tc:GetAttack()~=tc:GetBaseAttack() then Duel.Destroy(tc,REASON_EFFECT) end end
gpl-2.0
Turttle/darkstar
scripts/zones/The_Eldieme_Necropolis/npcs/Treasure_Coffer.lua
17
4063
----------------------------------- -- Area: The Eldieme Necropolis -- NPC: Treasure Coffer -- @zone 195 ----------------------------------- package.loaded["scripts/zones/The_Eldieme_Necropolis/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/treasure"); require("scripts/globals/quests"); require("scripts/zones/The_Eldieme_Necropolis/TextIDs"); local TreasureType = "Coffer"; local TreasureLvL = 53; local TreasureMinLvL = 43; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- trade:hasItemQty(1046,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(1046,1) or trade:hasItemQty(1115,1) or trade:hasItemQty(1023,1) or trade:hasItemQty(1022,1)) and trade:getItemCount() == 1) then -- IMPORTANT ITEM: AF Keyitems, AF Items, & Map ----------- local mJob = player:getMainJob(); local zone = player:getZoneID(); local AFHandsActivated = player:getVar("BorghertzAlreadyActiveWithJob"); local listAF = getAFbyZone(zone); if ((AFHandsActivated == 8 or AFHandsActivated == 5 or AFHandsActivated == 1 or AFHandsActivated == 7) and player:hasKeyItem(OLD_GAUNTLETS) == false) then questItemNeeded = 1; else for nb = 1,table.getn(listAF),3 do if (player:getQuestStatus(JEUNO,listAF[nb + 1]) ~= QUEST_AVAILABLE and mJob == listAF[nb] and player:hasItem(listAF[nb + 2]) == false) then questItemNeeded = 2; break end end 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:addKeyItem(OLD_GAUNTLETS); player:messageSpecial(KEYITEM_OBTAINED,OLD_GAUNTLETS); -- Old Gauntlets (KI) elseif (questItemNeeded == 2) then for nb = 1,table.getn(listAF),3 do if (mJob == listAF[nb]) then player:addItem(listAF[nb + 2]); player:messageSpecial(ITEM_OBTAINED,listAF[nb + 2]); break end end else player:setVar("["..zone.."]".."Treasure_"..TreasureType,os.time() + math.random(CHEST_MIN_ILLUSION_TIME,CHEST_MAX_ILLUSION_TIME)); local loot = cofferLoot(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]); player:messageSpecial(GIL_OBTAINED,loot[2]); else -- Item player:addItem(loot[2]); player:messageSpecial(ITEM_OBTAINED,loot[2]); end end UpdateTreasureSpawnPoint(npc:getID()); else player:messageSpecial(CHEST_MIMIC); spawnMimic(zone,npc,player); UpdateTreasureSpawnPoint(npc:getID(), true); end end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(CHEST_LOCKED,1046); 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
mchaza/soka
src/libraries/LoveFrames/objects/internal/sliderbutton.lua
5
6369
--[[------------------------------------------------ -- Love Frames - A GUI library for LOVE -- -- Copyright (c) 2013 Kenny Shields -- --]]------------------------------------------------ -- sliderbutton class local newobject = loveframes.NewObject("sliderbutton", "loveframes_object_sliderbutton", true) --[[--------------------------------------------------------- - func: initialize() - desc: initializes the object --]]--------------------------------------------------------- function newobject:initialize(parent) self.type = "sliderbutton" self.width = 10 self.height = 20 self.staticx = 0 self.staticy = 0 self.startx = 0 self.clickx = 0 self.starty = 0 self.clicky = 0 self.intervals = true self.internal = true self.down = false self.dragging = false self.parent = parent -- apply template properties to the object loveframes.templates.ApplyToObject(self) end --[[--------------------------------------------------------- - func: update(deltatime) - desc: updates the object --]]--------------------------------------------------------- function newobject:update(dt) local visible = self.visible local alwaysupdate = self.alwaysupdate if not visible then if not alwaysupdate then return end end self:CheckHover() local x, y = love.mouse.getPosition() local intervals = self.intervals local progress = 0 local nvalue = 0 local pvalue = self.parent.value local hover = self.hover local down = self.down local hoverobject = loveframes.hoverobject local parent = self.parent local slidetype = parent.slidetype local dragging = self.dragging local base = loveframes.base local update = self.Update if not hover then self.down = false if hoverobject == self then self.hover = true end else if hoverobject == self then self.down = true end end if not down and hoverobject == self then self.hover = true end -- move to parent if there is a parent if parent ~= base then self.x = parent.x + self.staticx self.y = parent.y + self.staticy end -- start calculations if the button is being dragged if dragging then -- calculations for horizontal sliders if slidetype == "horizontal" then self.staticx = self.startx + (x - self.clickx) progress = self.staticx/(self.parent.width - self.width) nvalue = self.parent.min + (self.parent.max - self.parent.min) * progress nvalue = loveframes.util.Round(nvalue, self.parent.decimals) -- calculations for vertical sliders elseif slidetype == "vertical" then self.staticy = self.starty + (y - self.clicky) local space = self.parent.height - self.height local remaining = (self.parent.height - self.height) - self.staticy local percent = remaining/space nvalue = self.parent.min + (self.parent.max - self.parent.min) * percent nvalue = loveframes.util.Round(nvalue, self.parent.decimals) end if nvalue > self.parent.max then nvalue = self.parent.max end if nvalue < self.parent.min then nvalue = self.parent.min end self.parent.value = nvalue if self.parent.value == -0 then self.parent.value = math.abs(self.parent.value) end if nvalue ~= pvalue and nvalue >= self.parent.min and nvalue <= self.parent.max then if self.parent.OnValueChanged then self.parent.OnValueChanged(self.parent, self.parent.value) end end loveframes.hoverobject = self end if slidetype == "horizontal" then if (self.staticx + self.width) > self.parent.width then self.staticx = self.parent.width - self.width end if self.staticx < 0 then self.staticx = 0 end end if slidetype == "vertical" then if (self.staticy + self.height) > self.parent.height then self.staticy = self.parent.height - self.height end if self.staticy < 0 then self.staticy = 0 end end if update then update(self, dt) end end --[[--------------------------------------------------------- - func: draw() - desc: draws the object --]]--------------------------------------------------------- function newobject:draw() local visible = self.visible if not visible then return end local skins = loveframes.skins.available local skinindex = loveframes.config["ACTIVESKIN"] local defaultskin = loveframes.config["DEFAULTSKIN"] local selfskin = self.skin local skin = skins[selfskin] or skins[skinindex] local drawfunc = skin.DrawSliderButton or skins[defaultskin].DrawSliderButton local draw = self.Draw local drawcount = loveframes.drawcount -- set the object's draw order self:SetDrawOrder() if draw then draw(self) else drawfunc(self) end end --[[--------------------------------------------------------- - func: mousepressed(x, y, button) - desc: called when the player presses a mouse button --]]--------------------------------------------------------- function newobject:mousepressed(x, y, button) local visible = self.visible if not visible then return end local hover = self.hover if hover and button == "l" then local baseparent = self:GetBaseParent() if baseparent and baseparent.type == "frame" then baseparent:MakeTop() end self.down = true self.dragging = true self.startx = self.staticx self.clickx = x self.starty = self.staticy self.clicky = y loveframes.hoverobject = self end end --[[--------------------------------------------------------- - func: mousereleased(x, y, button) - desc: called when the player releases a mouse button --]]--------------------------------------------------------- function newobject:mousereleased(x, y, button) local visible = self.visible if not visible then return end local down = self.down local dragging = self.dragging if dragging then local parent = self.parent local onrelease = parent.OnRelease if onrelease then onrelease(parent) end end self.down = false self.dragging = false end --[[--------------------------------------------------------- - func: MoveToX(x) - desc: moves the object to the specified x position --]]--------------------------------------------------------- function newobject:MoveToX(x) self.staticx = x end --[[--------------------------------------------------------- - func: MoveToY(y) - desc: moves the object to the specified y position --]]--------------------------------------------------------- function newobject:MoveToY(y) self.staticy = y end
gpl-2.0
nagyistoce/OpenBird
cocos2d/external/lua/luajit/src/dynasm/dasm_x86.lua
73
58651
------------------------------------------------------------------------------ -- DynASM x86/x64 module. -- -- Copyright (C) 2005-2013 Mike Pall. All rights reserved. -- See dynasm.lua for full copyright notice. ------------------------------------------------------------------------------ local x64 = x64 -- Module information: local _info = { arch = x64 and "x64" or "x86", description = "DynASM x86/x64 module", version = "1.3.0", vernum = 10300, release = "2011-05-05", author = "Mike Pall", license = "MIT", } -- Exported glue functions for the arch-specific module. local _M = { _info = _info } -- Cache library functions. local type, tonumber, pairs, ipairs = type, tonumber, pairs, ipairs local assert, unpack, setmetatable = assert, unpack or table.unpack, setmetatable local _s = string local sub, format, byte, char = _s.sub, _s.format, _s.byte, _s.char local find, match, gmatch, gsub = _s.find, _s.match, _s.gmatch, _s.gsub local concat, sort = table.concat, table.sort local bit = bit or require("bit") local band, shl, shr = bit.band, bit.lshift, bit.rshift -- Inherited tables and callbacks. local g_opt, g_arch local wline, werror, wfatal, wwarn -- Action name list. -- CHECK: Keep this in sync with the C code! local action_names = { -- int arg, 1 buffer pos: "DISP", "IMM_S", "IMM_B", "IMM_W", "IMM_D", "IMM_WB", "IMM_DB", -- action arg (1 byte), int arg, 1 buffer pos (reg/num): "VREG", "SPACE", -- !x64: VREG support NYI. -- ptrdiff_t arg, 1 buffer pos (address): !x64 "SETLABEL", "REL_A", -- action arg (1 byte) or int arg, 2 buffer pos (link, offset): "REL_LG", "REL_PC", -- action arg (1 byte) or int arg, 1 buffer pos (link): "IMM_LG", "IMM_PC", -- action arg (1 byte) or int arg, 1 buffer pos (offset): "LABEL_LG", "LABEL_PC", -- action arg (1 byte), 1 buffer pos (offset): "ALIGN", -- action args (2 bytes), no buffer pos. "EXTERN", -- action arg (1 byte), no buffer pos. "ESC", -- no action arg, no buffer pos. "MARK", -- action arg (1 byte), no buffer pos, terminal action: "SECTION", -- no args, no buffer pos, terminal action: "STOP" } -- Maximum number of section buffer positions for dasm_put(). -- CHECK: Keep this in sync with the C code! local maxsecpos = 25 -- Keep this low, to avoid excessively long C lines. -- Action name -> action number (dynamically generated below). local map_action = {} -- First action number. Everything below does not need to be escaped. local actfirst = 256-#action_names -- Action list buffer and string (only used to remove dupes). local actlist = {} local actstr = "" -- Argument list for next dasm_put(). Start with offset 0 into action list. local actargs = { 0 } -- Current number of section buffer positions for dasm_put(). local secpos = 1 ------------------------------------------------------------------------------ -- Compute action numbers for action names. for n,name in ipairs(action_names) do local num = actfirst + n - 1 map_action[name] = num end -- Dump action names and numbers. local function dumpactions(out) out:write("DynASM encoding engine action codes:\n") for n,name in ipairs(action_names) do local num = map_action[name] out:write(format(" %-10s %02X %d\n", name, num, num)) end out:write("\n") end -- Write action list buffer as a huge static C array. local function writeactions(out, name) local nn = #actlist local last = actlist[nn] or 255 actlist[nn] = nil -- Remove last byte. if nn == 0 then nn = 1 end out:write("static const unsigned char ", name, "[", nn, "] = {\n") local s = " " for n,b in ipairs(actlist) do s = s..b.."," if #s >= 75 then assert(out:write(s, "\n")) s = " " end end out:write(s, last, "\n};\n\n") -- Add last byte back. end ------------------------------------------------------------------------------ -- Add byte to action list. local function wputxb(n) assert(n >= 0 and n <= 255 and n % 1 == 0, "byte out of range") actlist[#actlist+1] = n end -- Add action to list with optional arg. Advance buffer pos, too. local function waction(action, a, num) wputxb(assert(map_action[action], "bad action name `"..action.."'")) if a then actargs[#actargs+1] = a end if a or num then secpos = secpos + (num or 1) end end -- Add call to embedded DynASM C code. local function wcall(func, args) wline(format("dasm_%s(Dst, %s);", func, concat(args, ", ")), true) end -- Delete duplicate action list chunks. A tad slow, but so what. local function dedupechunk(offset) local al, as = actlist, actstr local chunk = char(unpack(al, offset+1, #al)) local orig = find(as, chunk, 1, true) if orig then actargs[1] = orig-1 -- Replace with original offset. for i=offset+1,#al do al[i] = nil end -- Kill dupe. else actstr = as..chunk end end -- Flush action list (intervening C code or buffer pos overflow). local function wflush(term) local offset = actargs[1] if #actlist == offset then return end -- Nothing to flush. if not term then waction("STOP") end -- Terminate action list. dedupechunk(offset) wcall("put", actargs) -- Add call to dasm_put(). actargs = { #actlist } -- Actionlist offset is 1st arg to next dasm_put(). secpos = 1 -- The actionlist offset occupies a buffer position, too. end -- Put escaped byte. local function wputb(n) if n >= actfirst then waction("ESC") end -- Need to escape byte. wputxb(n) end ------------------------------------------------------------------------------ -- Global label name -> global label number. With auto assignment on 1st use. local next_global = 10 local map_global = setmetatable({}, { __index = function(t, name) if not match(name, "^[%a_][%w_@]*$") then werror("bad global label") end local n = next_global if n > 246 then werror("too many global labels") end next_global = n + 1 t[name] = n return n end}) -- Dump global labels. local function dumpglobals(out, lvl) local t = {} for name, n in pairs(map_global) do t[n] = name end out:write("Global labels:\n") for i=10,next_global-1 do out:write(format(" %s\n", t[i])) end out:write("\n") end -- Write global label enum. local function writeglobals(out, prefix) local t = {} for name, n in pairs(map_global) do t[n] = name end out:write("enum {\n") for i=10,next_global-1 do out:write(" ", prefix, gsub(t[i], "@.*", ""), ",\n") end out:write(" ", prefix, "_MAX\n};\n") end -- Write global label names. local function writeglobalnames(out, name) local t = {} for name, n in pairs(map_global) do t[n] = name end out:write("static const char *const ", name, "[] = {\n") for i=10,next_global-1 do out:write(" \"", t[i], "\",\n") end out:write(" (const char *)0\n};\n") end ------------------------------------------------------------------------------ -- Extern label name -> extern label number. With auto assignment on 1st use. local next_extern = -1 local map_extern = setmetatable({}, { __index = function(t, name) -- No restrictions on the name for now. local n = next_extern if n < -256 then werror("too many extern labels") end next_extern = n - 1 t[name] = n return n end}) -- Dump extern labels. local function dumpexterns(out, lvl) local t = {} for name, n in pairs(map_extern) do t[-n] = name end out:write("Extern labels:\n") for i=1,-next_extern-1 do out:write(format(" %s\n", t[i])) end out:write("\n") end -- Write extern label names. local function writeexternnames(out, name) local t = {} for name, n in pairs(map_extern) do t[-n] = name end out:write("static const char *const ", name, "[] = {\n") for i=1,-next_extern-1 do out:write(" \"", t[i], "\",\n") end out:write(" (const char *)0\n};\n") end ------------------------------------------------------------------------------ -- Arch-specific maps. local map_archdef = {} -- Ext. register name -> int. name. local map_reg_rev = {} -- Int. register name -> ext. name. local map_reg_num = {} -- Int. register name -> register number. local map_reg_opsize = {} -- Int. register name -> operand size. local map_reg_valid_base = {} -- Int. register name -> valid base register? local map_reg_valid_index = {} -- Int. register name -> valid index register? local map_reg_needrex = {} -- Int. register name -> need rex vs. no rex. local reg_list = {} -- Canonical list of int. register names. local map_type = {} -- Type name -> { ctype, reg } local ctypenum = 0 -- Type number (for _PTx macros). local addrsize = x64 and "q" or "d" -- Size for address operands. -- Helper functions to fill register maps. local function mkrmap(sz, cl, names) local cname = format("@%s", sz) reg_list[#reg_list+1] = cname map_archdef[cl] = cname map_reg_rev[cname] = cl map_reg_num[cname] = -1 map_reg_opsize[cname] = sz if sz == addrsize or sz == "d" then map_reg_valid_base[cname] = true map_reg_valid_index[cname] = true end if names then for n,name in ipairs(names) do local iname = format("@%s%x", sz, n-1) reg_list[#reg_list+1] = iname map_archdef[name] = iname map_reg_rev[iname] = name map_reg_num[iname] = n-1 map_reg_opsize[iname] = sz if sz == "b" and n > 4 then map_reg_needrex[iname] = false end if sz == addrsize or sz == "d" then map_reg_valid_base[iname] = true map_reg_valid_index[iname] = true end end end for i=0,(x64 and sz ~= "f") and 15 or 7 do local needrex = sz == "b" and i > 3 local iname = format("@%s%x%s", sz, i, needrex and "R" or "") if needrex then map_reg_needrex[iname] = true end local name if sz == "o" then name = format("xmm%d", i) elseif sz == "f" then name = format("st%d", i) else name = format("r%d%s", i, sz == addrsize and "" or sz) end map_archdef[name] = iname if not map_reg_rev[iname] then reg_list[#reg_list+1] = iname map_reg_rev[iname] = name map_reg_num[iname] = i map_reg_opsize[iname] = sz if sz == addrsize or sz == "d" then map_reg_valid_base[iname] = true map_reg_valid_index[iname] = true end end end reg_list[#reg_list+1] = "" end -- Integer registers (qword, dword, word and byte sized). if x64 then mkrmap("q", "Rq", {"rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi"}) end mkrmap("d", "Rd", {"eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi"}) mkrmap("w", "Rw", {"ax", "cx", "dx", "bx", "sp", "bp", "si", "di"}) mkrmap("b", "Rb", {"al", "cl", "dl", "bl", "ah", "ch", "dh", "bh"}) map_reg_valid_index[map_archdef.esp] = false if x64 then map_reg_valid_index[map_archdef.rsp] = false end map_archdef["Ra"] = "@"..addrsize -- FP registers (internally tword sized, but use "f" as operand size). mkrmap("f", "Rf") -- SSE registers (oword sized, but qword and dword accessible). mkrmap("o", "xmm") -- Operand size prefixes to codes. local map_opsize = { byte = "b", word = "w", dword = "d", qword = "q", oword = "o", tword = "t", aword = addrsize, } -- Operand size code to number. local map_opsizenum = { b = 1, w = 2, d = 4, q = 8, o = 16, t = 10, } -- Operand size code to name. local map_opsizename = { b = "byte", w = "word", d = "dword", q = "qword", o = "oword", t = "tword", f = "fpword", } -- Valid index register scale factors. local map_xsc = { ["1"] = 0, ["2"] = 1, ["4"] = 2, ["8"] = 3, } -- Condition codes. local map_cc = { o = 0, no = 1, b = 2, nb = 3, e = 4, ne = 5, be = 6, nbe = 7, s = 8, ns = 9, p = 10, np = 11, l = 12, nl = 13, le = 14, nle = 15, c = 2, nae = 2, nc = 3, ae = 3, z = 4, nz = 5, na = 6, a = 7, pe = 10, po = 11, nge = 12, ge = 13, ng = 14, g = 15, } -- Reverse defines for registers. function _M.revdef(s) return gsub(s, "@%w+", map_reg_rev) end -- Dump register names and numbers local function dumpregs(out) out:write("Register names, sizes and internal numbers:\n") for _,reg in ipairs(reg_list) do if reg == "" then out:write("\n") else local name = map_reg_rev[reg] local num = map_reg_num[reg] local opsize = map_opsizename[map_reg_opsize[reg]] out:write(format(" %-5s %-8s %s\n", name, opsize, num < 0 and "(variable)" or num)) end end end ------------------------------------------------------------------------------ -- Put action for label arg (IMM_LG, IMM_PC, REL_LG, REL_PC). local function wputlabel(aprefix, imm, num) if type(imm) == "number" then if imm < 0 then waction("EXTERN") wputxb(aprefix == "IMM_" and 0 or 1) imm = -imm-1 else waction(aprefix.."LG", nil, num); end wputxb(imm) else waction(aprefix.."PC", imm, num) end end -- Put signed byte or arg. local function wputsbarg(n) if type(n) == "number" then if n < -128 or n > 127 then werror("signed immediate byte out of range") end if n < 0 then n = n + 256 end wputb(n) else waction("IMM_S", n) end end -- Put unsigned byte or arg. local function wputbarg(n) if type(n) == "number" then if n < 0 or n > 255 then werror("unsigned immediate byte out of range") end wputb(n) else waction("IMM_B", n) end end -- Put unsigned word or arg. local function wputwarg(n) if type(n) == "number" then if shr(n, 16) ~= 0 then werror("unsigned immediate word out of range") end wputb(band(n, 255)); wputb(shr(n, 8)); else waction("IMM_W", n) end end -- Put signed or unsigned dword or arg. local function wputdarg(n) local tn = type(n) if tn == "number" then wputb(band(n, 255)) wputb(band(shr(n, 8), 255)) wputb(band(shr(n, 16), 255)) wputb(shr(n, 24)) elseif tn == "table" then wputlabel("IMM_", n[1], 1) else waction("IMM_D", n) end end -- Put operand-size dependent number or arg (defaults to dword). local function wputszarg(sz, n) if not sz or sz == "d" or sz == "q" then wputdarg(n) elseif sz == "w" then wputwarg(n) elseif sz == "b" then wputbarg(n) elseif sz == "s" then wputsbarg(n) else werror("bad operand size") end end -- Put multi-byte opcode with operand-size dependent modifications. local function wputop(sz, op, rex) local r if rex ~= 0 and not x64 then werror("bad operand size") end if sz == "w" then wputb(102) end -- Needs >32 bit numbers, but only for crc32 eax, word [ebx] if op >= 4294967296 then r = op%4294967296 wputb((op-r)/4294967296) op = r end if op >= 16777216 then wputb(shr(op, 24)); op = band(op, 0xffffff) end if op >= 65536 then if rex ~= 0 then local opc3 = band(op, 0xffff00) if opc3 == 0x0f3a00 or opc3 == 0x0f3800 then wputb(64 + band(rex, 15)); rex = 0 end end wputb(shr(op, 16)); op = band(op, 0xffff) end if op >= 256 then local b = shr(op, 8) if b == 15 and rex ~= 0 then wputb(64 + band(rex, 15)); rex = 0 end wputb(b) op = band(op, 255) end if rex ~= 0 then wputb(64 + band(rex, 15)) end if sz == "b" then op = op - 1 end wputb(op) end -- Put ModRM or SIB formatted byte. local function wputmodrm(m, s, rm, vs, vrm) assert(m < 4 and s < 16 and rm < 16, "bad modrm operands") wputb(shl(m, 6) + shl(band(s, 7), 3) + band(rm, 7)) end -- Put ModRM/SIB plus optional displacement. local function wputmrmsib(t, imark, s, vsreg) local vreg, vxreg local reg, xreg = t.reg, t.xreg if reg and reg < 0 then reg = 0; vreg = t.vreg end if xreg and xreg < 0 then xreg = 0; vxreg = t.vxreg end if s < 0 then s = 0 end -- Register mode. if sub(t.mode, 1, 1) == "r" then wputmodrm(3, s, reg) if vsreg then waction("VREG", vsreg); wputxb(2) end if vreg then waction("VREG", vreg); wputxb(0) end return end local disp = t.disp local tdisp = type(disp) -- No base register? if not reg then local riprel = false if xreg then -- Indexed mode with index register only. -- [xreg*xsc+disp] -> (0, s, esp) (xsc, xreg, ebp) wputmodrm(0, s, 4) if imark == "I" then waction("MARK") end if vsreg then waction("VREG", vsreg); wputxb(2) end wputmodrm(t.xsc, xreg, 5) if vxreg then waction("VREG", vxreg); wputxb(3) end else -- Pure 32 bit displacement. if x64 and tdisp ~= "table" then wputmodrm(0, s, 4) -- [disp] -> (0, s, esp) (0, esp, ebp) if imark == "I" then waction("MARK") end wputmodrm(0, 4, 5) else riprel = x64 wputmodrm(0, s, 5) -- [disp|rip-label] -> (0, s, ebp) if imark == "I" then waction("MARK") end end if vsreg then waction("VREG", vsreg); wputxb(2) end end if riprel then -- Emit rip-relative displacement. if match("UWSiI", imark) then werror("NYI: rip-relative displacement followed by immediate") end -- The previous byte in the action buffer cannot be 0xe9 or 0x80-0x8f. wputlabel("REL_", disp[1], 2) else wputdarg(disp) end return end local m if tdisp == "number" then -- Check displacement size at assembly time. if disp == 0 and band(reg, 7) ~= 5 then -- [ebp] -> [ebp+0] (in SIB, too) if not vreg then m = 0 end -- Force DISP to allow [Rd(5)] -> [ebp+0] elseif disp >= -128 and disp <= 127 then m = 1 else m = 2 end elseif tdisp == "table" then m = 2 end -- Index register present or esp as base register: need SIB encoding. if xreg or band(reg, 7) == 4 then wputmodrm(m or 2, s, 4) -- ModRM. if m == nil or imark == "I" then waction("MARK") end if vsreg then waction("VREG", vsreg); wputxb(2) end wputmodrm(t.xsc or 0, xreg or 4, reg) -- SIB. if vxreg then waction("VREG", vxreg); wputxb(3) end if vreg then waction("VREG", vreg); wputxb(1) end else wputmodrm(m or 2, s, reg) -- ModRM. if (imark == "I" and (m == 1 or m == 2)) or (m == nil and (vsreg or vreg)) then waction("MARK") end if vsreg then waction("VREG", vsreg); wputxb(2) end if vreg then waction("VREG", vreg); wputxb(1) end end -- Put displacement. if m == 1 then wputsbarg(disp) elseif m == 2 then wputdarg(disp) elseif m == nil then waction("DISP", disp) end end ------------------------------------------------------------------------------ -- Return human-readable operand mode string. local function opmodestr(op, args) local m = {} for i=1,#args do local a = args[i] m[#m+1] = sub(a.mode, 1, 1)..(a.opsize or "?") end return op.." "..concat(m, ",") end -- Convert number to valid integer or nil. local function toint(expr) local n = tonumber(expr) if n then if n % 1 ~= 0 or n < -2147483648 or n > 4294967295 then werror("bad integer number `"..expr.."'") end return n end end -- Parse immediate expression. local function immexpr(expr) -- &expr (pointer) if sub(expr, 1, 1) == "&" then return "iPJ", format("(ptrdiff_t)(%s)", sub(expr,2)) end local prefix = sub(expr, 1, 2) -- =>expr (pc label reference) if prefix == "=>" then return "iJ", sub(expr, 3) end -- ->name (global label reference) if prefix == "->" then return "iJ", map_global[sub(expr, 3)] end -- [<>][1-9] (local label reference) local dir, lnum = match(expr, "^([<>])([1-9])$") if dir then -- Fwd: 247-255, Bkwd: 1-9. return "iJ", lnum + (dir == ">" and 246 or 0) end local extname = match(expr, "^extern%s+(%S+)$") if extname then return "iJ", map_extern[extname] end -- expr (interpreted as immediate) return "iI", expr end -- Parse displacement expression: +-num, +-expr, +-opsize*num local function dispexpr(expr) local disp = expr == "" and 0 or toint(expr) if disp then return disp end local c, dispt = match(expr, "^([+-])%s*(.+)$") if c == "+" then expr = dispt elseif not c then werror("bad displacement expression `"..expr.."'") end local opsize, tailops = match(dispt, "^(%w+)%s*%*%s*(.+)$") local ops, imm = map_opsize[opsize], toint(tailops) if ops and imm then if c == "-" then imm = -imm end return imm*map_opsizenum[ops] end local mode, iexpr = immexpr(dispt) if mode == "iJ" then if c == "-" then werror("cannot invert label reference") end return { iexpr } end return expr -- Need to return original signed expression. end -- Parse register or type expression. local function rtexpr(expr) if not expr then return end local tname, ovreg = match(expr, "^([%w_]+):(@[%w_]+)$") local tp = map_type[tname or expr] if tp then local reg = ovreg or tp.reg local rnum = map_reg_num[reg] if not rnum then werror("type `"..(tname or expr).."' needs a register override") end if not map_reg_valid_base[reg] then werror("bad base register override `"..(map_reg_rev[reg] or reg).."'") end return reg, rnum, tp end return expr, map_reg_num[expr] end -- Parse operand and return { mode, opsize, reg, xreg, xsc, disp, imm }. local function parseoperand(param) local t = {} local expr = param local opsize, tailops = match(param, "^(%w+)%s*(.+)$") if opsize then t.opsize = map_opsize[opsize] if t.opsize then expr = tailops end end local br = match(expr, "^%[%s*(.-)%s*%]$") repeat if br then t.mode = "xm" -- [disp] t.disp = toint(br) if t.disp then t.mode = x64 and "xm" or "xmO" break end -- [reg...] local tp local reg, tailr = match(br, "^([@%w_:]+)%s*(.*)$") reg, t.reg, tp = rtexpr(reg) if not t.reg then -- [expr] t.mode = x64 and "xm" or "xmO" t.disp = dispexpr("+"..br) break end if t.reg == -1 then t.vreg, tailr = match(tailr, "^(%b())(.*)$") if not t.vreg then werror("bad variable register expression") end end -- [xreg*xsc] or [xreg*xsc+-disp] or [xreg*xsc+-expr] local xsc, tailsc = match(tailr, "^%*%s*([1248])%s*(.*)$") if xsc then if not map_reg_valid_index[reg] then werror("bad index register `"..map_reg_rev[reg].."'") end t.xsc = map_xsc[xsc] t.xreg = t.reg t.vxreg = t.vreg t.reg = nil t.vreg = nil t.disp = dispexpr(tailsc) break end if not map_reg_valid_base[reg] then werror("bad base register `"..map_reg_rev[reg].."'") end -- [reg] or [reg+-disp] t.disp = toint(tailr) or (tailr == "" and 0) if t.disp then break end -- [reg+xreg...] local xreg, tailx = match(tailr, "^+%s*([@%w_:]+)%s*(.*)$") xreg, t.xreg, tp = rtexpr(xreg) if not t.xreg then -- [reg+-expr] t.disp = dispexpr(tailr) break end if not map_reg_valid_index[xreg] then werror("bad index register `"..map_reg_rev[xreg].."'") end if t.xreg == -1 then t.vxreg, tailx = match(tailx, "^(%b())(.*)$") if not t.vxreg then werror("bad variable register expression") end end -- [reg+xreg*xsc...] local xsc, tailsc = match(tailx, "^%*%s*([1248])%s*(.*)$") if xsc then t.xsc = map_xsc[xsc] tailx = tailsc end -- [...] or [...+-disp] or [...+-expr] t.disp = dispexpr(tailx) else -- imm or opsize*imm local imm = toint(expr) if not imm and sub(expr, 1, 1) == "*" and t.opsize then imm = toint(sub(expr, 2)) if imm then imm = imm * map_opsizenum[t.opsize] t.opsize = nil end end if imm then if t.opsize then werror("bad operand size override") end local m = "i" if imm == 1 then m = m.."1" end if imm >= 4294967168 and imm <= 4294967295 then imm = imm-4294967296 end if imm >= -128 and imm <= 127 then m = m.."S" end t.imm = imm t.mode = m break end local tp local reg, tailr = match(expr, "^([@%w_:]+)%s*(.*)$") reg, t.reg, tp = rtexpr(reg) if t.reg then if t.reg == -1 then t.vreg, tailr = match(tailr, "^(%b())(.*)$") if not t.vreg then werror("bad variable register expression") end end -- reg if tailr == "" then if t.opsize then werror("bad operand size override") end t.opsize = map_reg_opsize[reg] if t.opsize == "f" then t.mode = t.reg == 0 and "fF" or "f" else if reg == "@w4" or (x64 and reg == "@d4") then wwarn("bad idea, try again with `"..(x64 and "rsp'" or "esp'")) end t.mode = t.reg == 0 and "rmR" or (reg == "@b1" and "rmC" or "rm") end t.needrex = map_reg_needrex[reg] break end -- type[idx], type[idx].field, type->field -> [reg+offset_expr] if not tp then werror("bad operand `"..param.."'") end t.mode = "xm" t.disp = format(tp.ctypefmt, tailr) else t.mode, t.imm = immexpr(expr) if sub(t.mode, -1) == "J" then if t.opsize and t.opsize ~= addrsize then werror("bad operand size override") end t.opsize = addrsize end end end until true return t end ------------------------------------------------------------------------------ -- x86 Template String Description -- =============================== -- -- Each template string is a list of [match:]pattern pairs, -- separated by "|". The first match wins. No match means a -- bad or unsupported combination of operand modes or sizes. -- -- The match part and the ":" is omitted if the operation has -- no operands. Otherwise the first N characters are matched -- against the mode strings of each of the N operands. -- -- The mode string for each operand type is (see parseoperand()): -- Integer register: "rm", +"R" for eax, ax, al, +"C" for cl -- FP register: "f", +"F" for st0 -- Index operand: "xm", +"O" for [disp] (pure offset) -- Immediate: "i", +"S" for signed 8 bit, +"1" for 1, -- +"I" for arg, +"P" for pointer -- Any: +"J" for valid jump targets -- -- So a match character "m" (mixed) matches both an integer register -- and an index operand (to be encoded with the ModRM/SIB scheme). -- But "r" matches only a register and "x" only an index operand -- (e.g. for FP memory access operations). -- -- The operand size match string starts right after the mode match -- characters and ends before the ":". "dwb" or "qdwb" is assumed, if empty. -- The effective data size of the operation is matched against this list. -- -- If only the regular "b", "w", "d", "q", "t" operand sizes are -- present, then all operands must be the same size. Unspecified sizes -- are ignored, but at least one operand must have a size or the pattern -- won't match (use the "byte", "word", "dword", "qword", "tword" -- operand size overrides. E.g.: mov dword [eax], 1). -- -- If the list has a "1" or "2" prefix, the operand size is taken -- from the respective operand and any other operand sizes are ignored. -- If the list contains only ".", all operand sizes are ignored. -- If the list has a "/" prefix, the concatenated (mixed) operand sizes -- are compared to the match. -- -- E.g. "rrdw" matches for either two dword registers or two word -- registers. "Fx2dq" matches an st0 operand plus an index operand -- pointing to a dword (float) or qword (double). -- -- Every character after the ":" is part of the pattern string: -- Hex chars are accumulated to form the opcode (left to right). -- "n" disables the standard opcode mods -- (otherwise: -1 for "b", o16 prefix for "w", rex.w for "q") -- "X" Force REX.W. -- "r"/"R" adds the reg. number from the 1st/2nd operand to the opcode. -- "m"/"M" generates ModRM/SIB from the 1st/2nd operand. -- The spare 3 bits are either filled with the last hex digit or -- the result from a previous "r"/"R". The opcode is restored. -- -- All of the following characters force a flush of the opcode: -- "o"/"O" stores a pure 32 bit disp (offset) from the 1st/2nd operand. -- "S" stores a signed 8 bit immediate from the last operand. -- "U" stores an unsigned 8 bit immediate from the last operand. -- "W" stores an unsigned 16 bit immediate from the last operand. -- "i" stores an operand sized immediate from the last operand. -- "I" dito, but generates an action code to optionally modify -- the opcode (+2) for a signed 8 bit immediate. -- "J" generates one of the REL action codes from the last operand. -- ------------------------------------------------------------------------------ -- Template strings for x86 instructions. Ordered by first opcode byte. -- Unimplemented opcodes (deliberate omissions) are marked with *. local map_op = { -- 00-05: add... -- 06: *push es -- 07: *pop es -- 08-0D: or... -- 0E: *push cs -- 0F: two byte opcode prefix -- 10-15: adc... -- 16: *push ss -- 17: *pop ss -- 18-1D: sbb... -- 1E: *push ds -- 1F: *pop ds -- 20-25: and... es_0 = "26", -- 27: *daa -- 28-2D: sub... cs_0 = "2E", -- 2F: *das -- 30-35: xor... ss_0 = "36", -- 37: *aaa -- 38-3D: cmp... ds_0 = "3E", -- 3F: *aas inc_1 = x64 and "m:FF0m" or "rdw:40r|m:FF0m", dec_1 = x64 and "m:FF1m" or "rdw:48r|m:FF1m", push_1 = (x64 and "rq:n50r|rw:50r|mq:nFF6m|mw:FF6m" or "rdw:50r|mdw:FF6m").."|S.:6AS|ib:n6Ai|i.:68i", pop_1 = x64 and "rq:n58r|rw:58r|mq:n8F0m|mw:8F0m" or "rdw:58r|mdw:8F0m", -- 60: *pusha, *pushad, *pushaw -- 61: *popa, *popad, *popaw -- 62: *bound rdw,x -- 63: x86: *arpl mw,rw movsxd_2 = x64 and "rm/qd:63rM", fs_0 = "64", gs_0 = "65", o16_0 = "66", a16_0 = not x64 and "67" or nil, a32_0 = x64 and "67", -- 68: push idw -- 69: imul rdw,mdw,idw -- 6A: push ib -- 6B: imul rdw,mdw,S -- 6C: *insb -- 6D: *insd, *insw -- 6E: *outsb -- 6F: *outsd, *outsw -- 70-7F: jcc lb -- 80: add... mb,i -- 81: add... mdw,i -- 82: *undefined -- 83: add... mdw,S test_2 = "mr:85Rm|rm:85rM|Ri:A9ri|mi:F70mi", -- 86: xchg rb,mb -- 87: xchg rdw,mdw -- 88: mov mb,r -- 89: mov mdw,r -- 8A: mov r,mb -- 8B: mov r,mdw -- 8C: *mov mdw,seg lea_2 = "rx1dq:8DrM", -- 8E: *mov seg,mdw -- 8F: pop mdw nop_0 = "90", xchg_2 = "Rrqdw:90R|rRqdw:90r|rm:87rM|mr:87Rm", cbw_0 = "6698", cwde_0 = "98", cdqe_0 = "4898", cwd_0 = "6699", cdq_0 = "99", cqo_0 = "4899", -- 9A: *call iw:idw wait_0 = "9B", fwait_0 = "9B", pushf_0 = "9C", pushfd_0 = not x64 and "9C", pushfq_0 = x64 and "9C", popf_0 = "9D", popfd_0 = not x64 and "9D", popfq_0 = x64 and "9D", sahf_0 = "9E", lahf_0 = "9F", mov_2 = "OR:A3o|RO:A1O|mr:89Rm|rm:8BrM|rib:nB0ri|ridw:B8ri|mi:C70mi", movsb_0 = "A4", movsw_0 = "66A5", movsd_0 = "A5", cmpsb_0 = "A6", cmpsw_0 = "66A7", cmpsd_0 = "A7", -- A8: test Rb,i -- A9: test Rdw,i stosb_0 = "AA", stosw_0 = "66AB", stosd_0 = "AB", lodsb_0 = "AC", lodsw_0 = "66AD", lodsd_0 = "AD", scasb_0 = "AE", scasw_0 = "66AF", scasd_0 = "AF", -- B0-B7: mov rb,i -- B8-BF: mov rdw,i -- C0: rol... mb,i -- C1: rol... mdw,i ret_1 = "i.:nC2W", ret_0 = "C3", -- C4: *les rdw,mq -- C5: *lds rdw,mq -- C6: mov mb,i -- C7: mov mdw,i -- C8: *enter iw,ib leave_0 = "C9", -- CA: *retf iw -- CB: *retf int3_0 = "CC", int_1 = "i.:nCDU", into_0 = "CE", -- CF: *iret -- D0: rol... mb,1 -- D1: rol... mdw,1 -- D2: rol... mb,cl -- D3: rol... mb,cl -- D4: *aam ib -- D5: *aad ib -- D6: *salc -- D7: *xlat -- D8-DF: floating point ops -- E0: *loopne -- E1: *loope -- E2: *loop -- E3: *jcxz, *jecxz -- E4: *in Rb,ib -- E5: *in Rdw,ib -- E6: *out ib,Rb -- E7: *out ib,Rdw call_1 = x64 and "mq:nFF2m|J.:E8nJ" or "md:FF2m|J.:E8J", jmp_1 = x64 and "mq:nFF4m|J.:E9nJ" or "md:FF4m|J.:E9J", -- short: EB -- EA: *jmp iw:idw -- EB: jmp ib -- EC: *in Rb,dx -- ED: *in Rdw,dx -- EE: *out dx,Rb -- EF: *out dx,Rdw -- F0: *lock int1_0 = "F1", repne_0 = "F2", repnz_0 = "F2", rep_0 = "F3", repe_0 = "F3", repz_0 = "F3", -- F4: *hlt cmc_0 = "F5", -- F6: test... mb,i; div... mb -- F7: test... mdw,i; div... mdw clc_0 = "F8", stc_0 = "F9", -- FA: *cli cld_0 = "FC", std_0 = "FD", -- FE: inc... mb -- FF: inc... mdw -- misc ops not_1 = "m:F72m", neg_1 = "m:F73m", mul_1 = "m:F74m", imul_1 = "m:F75m", div_1 = "m:F76m", idiv_1 = "m:F77m", imul_2 = "rmqdw:0FAFrM|rIqdw:69rmI|rSqdw:6BrmS|riqdw:69rmi", imul_3 = "rmIqdw:69rMI|rmSqdw:6BrMS|rmiqdw:69rMi", movzx_2 = "rm/db:0FB6rM|rm/qb:|rm/wb:0FB6rM|rm/dw:0FB7rM|rm/qw:", movsx_2 = "rm/db:0FBErM|rm/qb:|rm/wb:0FBErM|rm/dw:0FBFrM|rm/qw:", bswap_1 = "rqd:0FC8r", bsf_2 = "rmqdw:0FBCrM", bsr_2 = "rmqdw:0FBDrM", bt_2 = "mrqdw:0FA3Rm|miqdw:0FBA4mU", btc_2 = "mrqdw:0FBBRm|miqdw:0FBA7mU", btr_2 = "mrqdw:0FB3Rm|miqdw:0FBA6mU", bts_2 = "mrqdw:0FABRm|miqdw:0FBA5mU", rdtsc_0 = "0F31", -- P1+ cpuid_0 = "0FA2", -- P1+ -- floating point ops fst_1 = "ff:DDD0r|xd:D92m|xq:nDD2m", fstp_1 = "ff:DDD8r|xd:D93m|xq:nDD3m|xt:DB7m", fld_1 = "ff:D9C0r|xd:D90m|xq:nDD0m|xt:DB5m", fpop_0 = "DDD8", -- Alias for fstp st0. fist_1 = "xw:nDF2m|xd:DB2m", fistp_1 = "xw:nDF3m|xd:DB3m|xq:nDF7m", fild_1 = "xw:nDF0m|xd:DB0m|xq:nDF5m", fxch_0 = "D9C9", fxch_1 = "ff:D9C8r", fxch_2 = "fFf:D9C8r|Fff:D9C8R", fucom_1 = "ff:DDE0r", fucom_2 = "Fff:DDE0R", fucomp_1 = "ff:DDE8r", fucomp_2 = "Fff:DDE8R", fucomi_1 = "ff:DBE8r", -- P6+ fucomi_2 = "Fff:DBE8R", -- P6+ fucomip_1 = "ff:DFE8r", -- P6+ fucomip_2 = "Fff:DFE8R", -- P6+ fcomi_1 = "ff:DBF0r", -- P6+ fcomi_2 = "Fff:DBF0R", -- P6+ fcomip_1 = "ff:DFF0r", -- P6+ fcomip_2 = "Fff:DFF0R", -- P6+ fucompp_0 = "DAE9", fcompp_0 = "DED9", fldcw_1 = "xw:nD95m", fstcw_1 = "xw:n9BD97m", fnstcw_1 = "xw:nD97m", fstsw_1 = "Rw:n9BDFE0|xw:n9BDD7m", fnstsw_1 = "Rw:nDFE0|xw:nDD7m", fclex_0 = "9BDBE2", fnclex_0 = "DBE2", fnop_0 = "D9D0", -- D9D1-D9DF: unassigned fchs_0 = "D9E0", fabs_0 = "D9E1", -- D9E2: unassigned -- D9E3: unassigned ftst_0 = "D9E4", fxam_0 = "D9E5", -- D9E6: unassigned -- D9E7: unassigned fld1_0 = "D9E8", fldl2t_0 = "D9E9", fldl2e_0 = "D9EA", fldpi_0 = "D9EB", fldlg2_0 = "D9EC", fldln2_0 = "D9ED", fldz_0 = "D9EE", -- D9EF: unassigned f2xm1_0 = "D9F0", fyl2x_0 = "D9F1", fptan_0 = "D9F2", fpatan_0 = "D9F3", fxtract_0 = "D9F4", fprem1_0 = "D9F5", fdecstp_0 = "D9F6", fincstp_0 = "D9F7", fprem_0 = "D9F8", fyl2xp1_0 = "D9F9", fsqrt_0 = "D9FA", fsincos_0 = "D9FB", frndint_0 = "D9FC", fscale_0 = "D9FD", fsin_0 = "D9FE", fcos_0 = "D9FF", -- SSE, SSE2 andnpd_2 = "rmo:660F55rM", andnps_2 = "rmo:0F55rM", andpd_2 = "rmo:660F54rM", andps_2 = "rmo:0F54rM", clflush_1 = "x.:0FAE7m", cmppd_3 = "rmio:660FC2rMU", cmpps_3 = "rmio:0FC2rMU", cmpsd_3 = "rrio:F20FC2rMU|rxi/oq:", cmpss_3 = "rrio:F30FC2rMU|rxi/od:", comisd_2 = "rro:660F2FrM|rx/oq:", comiss_2 = "rro:0F2FrM|rx/od:", cvtdq2pd_2 = "rro:F30FE6rM|rx/oq:", cvtdq2ps_2 = "rmo:0F5BrM", cvtpd2dq_2 = "rmo:F20FE6rM", cvtpd2ps_2 = "rmo:660F5ArM", cvtpi2pd_2 = "rx/oq:660F2ArM", cvtpi2ps_2 = "rx/oq:0F2ArM", cvtps2dq_2 = "rmo:660F5BrM", cvtps2pd_2 = "rro:0F5ArM|rx/oq:", cvtsd2si_2 = "rr/do:F20F2DrM|rr/qo:|rx/dq:|rxq:", cvtsd2ss_2 = "rro:F20F5ArM|rx/oq:", cvtsi2sd_2 = "rm/od:F20F2ArM|rm/oq:F20F2ArXM", cvtsi2ss_2 = "rm/od:F30F2ArM|rm/oq:F30F2ArXM", cvtss2sd_2 = "rro:F30F5ArM|rx/od:", cvtss2si_2 = "rr/do:F20F2CrM|rr/qo:|rxd:|rx/qd:", cvttpd2dq_2 = "rmo:660FE6rM", cvttps2dq_2 = "rmo:F30F5BrM", cvttsd2si_2 = "rr/do:F20F2CrM|rr/qo:|rx/dq:|rxq:", cvttss2si_2 = "rr/do:F30F2CrM|rr/qo:|rxd:|rx/qd:", ldmxcsr_1 = "xd:0FAE2m", lfence_0 = "0FAEE8", maskmovdqu_2 = "rro:660FF7rM", mfence_0 = "0FAEF0", movapd_2 = "rmo:660F28rM|mro:660F29Rm", movaps_2 = "rmo:0F28rM|mro:0F29Rm", movd_2 = "rm/od:660F6ErM|rm/oq:660F6ErXM|mr/do:660F7ERm|mr/qo:", movdqa_2 = "rmo:660F6FrM|mro:660F7FRm", movdqu_2 = "rmo:F30F6FrM|mro:F30F7FRm", movhlps_2 = "rro:0F12rM", movhpd_2 = "rx/oq:660F16rM|xr/qo:n660F17Rm", movhps_2 = "rx/oq:0F16rM|xr/qo:n0F17Rm", movlhps_2 = "rro:0F16rM", movlpd_2 = "rx/oq:660F12rM|xr/qo:n660F13Rm", movlps_2 = "rx/oq:0F12rM|xr/qo:n0F13Rm", movmskpd_2 = "rr/do:660F50rM", movmskps_2 = "rr/do:0F50rM", movntdq_2 = "xro:660FE7Rm", movnti_2 = "xrqd:0FC3Rm", movntpd_2 = "xro:660F2BRm", movntps_2 = "xro:0F2BRm", movq_2 = "rro:F30F7ErM|rx/oq:|xr/qo:n660FD6Rm", movsd_2 = "rro:F20F10rM|rx/oq:|xr/qo:nF20F11Rm", movss_2 = "rro:F30F10rM|rx/od:|xr/do:F30F11Rm", movupd_2 = "rmo:660F10rM|mro:660F11Rm", movups_2 = "rmo:0F10rM|mro:0F11Rm", orpd_2 = "rmo:660F56rM", orps_2 = "rmo:0F56rM", packssdw_2 = "rmo:660F6BrM", packsswb_2 = "rmo:660F63rM", packuswb_2 = "rmo:660F67rM", paddb_2 = "rmo:660FFCrM", paddd_2 = "rmo:660FFErM", paddq_2 = "rmo:660FD4rM", paddsb_2 = "rmo:660FECrM", paddsw_2 = "rmo:660FEDrM", paddusb_2 = "rmo:660FDCrM", paddusw_2 = "rmo:660FDDrM", paddw_2 = "rmo:660FFDrM", pand_2 = "rmo:660FDBrM", pandn_2 = "rmo:660FDFrM", pause_0 = "F390", pavgb_2 = "rmo:660FE0rM", pavgw_2 = "rmo:660FE3rM", pcmpeqb_2 = "rmo:660F74rM", pcmpeqd_2 = "rmo:660F76rM", pcmpeqw_2 = "rmo:660F75rM", pcmpgtb_2 = "rmo:660F64rM", pcmpgtd_2 = "rmo:660F66rM", pcmpgtw_2 = "rmo:660F65rM", pextrw_3 = "rri/do:660FC5rMU|xri/wo:660F3A15nrMU", -- Mem op: SSE4.1 only. pinsrw_3 = "rri/od:660FC4rMU|rxi/ow:", pmaddwd_2 = "rmo:660FF5rM", pmaxsw_2 = "rmo:660FEErM", pmaxub_2 = "rmo:660FDErM", pminsw_2 = "rmo:660FEArM", pminub_2 = "rmo:660FDArM", pmovmskb_2 = "rr/do:660FD7rM", pmulhuw_2 = "rmo:660FE4rM", pmulhw_2 = "rmo:660FE5rM", pmullw_2 = "rmo:660FD5rM", pmuludq_2 = "rmo:660FF4rM", por_2 = "rmo:660FEBrM", prefetchnta_1 = "xb:n0F180m", prefetcht0_1 = "xb:n0F181m", prefetcht1_1 = "xb:n0F182m", prefetcht2_1 = "xb:n0F183m", psadbw_2 = "rmo:660FF6rM", pshufd_3 = "rmio:660F70rMU", pshufhw_3 = "rmio:F30F70rMU", pshuflw_3 = "rmio:F20F70rMU", pslld_2 = "rmo:660FF2rM|rio:660F726mU", pslldq_2 = "rio:660F737mU", psllq_2 = "rmo:660FF3rM|rio:660F736mU", psllw_2 = "rmo:660FF1rM|rio:660F716mU", psrad_2 = "rmo:660FE2rM|rio:660F724mU", psraw_2 = "rmo:660FE1rM|rio:660F714mU", psrld_2 = "rmo:660FD2rM|rio:660F722mU", psrldq_2 = "rio:660F733mU", psrlq_2 = "rmo:660FD3rM|rio:660F732mU", psrlw_2 = "rmo:660FD1rM|rio:660F712mU", psubb_2 = "rmo:660FF8rM", psubd_2 = "rmo:660FFArM", psubq_2 = "rmo:660FFBrM", psubsb_2 = "rmo:660FE8rM", psubsw_2 = "rmo:660FE9rM", psubusb_2 = "rmo:660FD8rM", psubusw_2 = "rmo:660FD9rM", psubw_2 = "rmo:660FF9rM", punpckhbw_2 = "rmo:660F68rM", punpckhdq_2 = "rmo:660F6ArM", punpckhqdq_2 = "rmo:660F6DrM", punpckhwd_2 = "rmo:660F69rM", punpcklbw_2 = "rmo:660F60rM", punpckldq_2 = "rmo:660F62rM", punpcklqdq_2 = "rmo:660F6CrM", punpcklwd_2 = "rmo:660F61rM", pxor_2 = "rmo:660FEFrM", rcpps_2 = "rmo:0F53rM", rcpss_2 = "rro:F30F53rM|rx/od:", rsqrtps_2 = "rmo:0F52rM", rsqrtss_2 = "rmo:F30F52rM", sfence_0 = "0FAEF8", shufpd_3 = "rmio:660FC6rMU", shufps_3 = "rmio:0FC6rMU", stmxcsr_1 = "xd:0FAE3m", ucomisd_2 = "rro:660F2ErM|rx/oq:", ucomiss_2 = "rro:0F2ErM|rx/od:", unpckhpd_2 = "rmo:660F15rM", unpckhps_2 = "rmo:0F15rM", unpcklpd_2 = "rmo:660F14rM", unpcklps_2 = "rmo:0F14rM", xorpd_2 = "rmo:660F57rM", xorps_2 = "rmo:0F57rM", -- SSE3 ops fisttp_1 = "xw:nDF1m|xd:DB1m|xq:nDD1m", addsubpd_2 = "rmo:660FD0rM", addsubps_2 = "rmo:F20FD0rM", haddpd_2 = "rmo:660F7CrM", haddps_2 = "rmo:F20F7CrM", hsubpd_2 = "rmo:660F7DrM", hsubps_2 = "rmo:F20F7DrM", lddqu_2 = "rxo:F20FF0rM", movddup_2 = "rmo:F20F12rM", movshdup_2 = "rmo:F30F16rM", movsldup_2 = "rmo:F30F12rM", -- SSSE3 ops pabsb_2 = "rmo:660F381CrM", pabsd_2 = "rmo:660F381ErM", pabsw_2 = "rmo:660F381DrM", palignr_3 = "rmio:660F3A0FrMU", phaddd_2 = "rmo:660F3802rM", phaddsw_2 = "rmo:660F3803rM", phaddw_2 = "rmo:660F3801rM", phsubd_2 = "rmo:660F3806rM", phsubsw_2 = "rmo:660F3807rM", phsubw_2 = "rmo:660F3805rM", pmaddubsw_2 = "rmo:660F3804rM", pmulhrsw_2 = "rmo:660F380BrM", pshufb_2 = "rmo:660F3800rM", psignb_2 = "rmo:660F3808rM", psignd_2 = "rmo:660F380ArM", psignw_2 = "rmo:660F3809rM", -- SSE4.1 ops blendpd_3 = "rmio:660F3A0DrMU", blendps_3 = "rmio:660F3A0CrMU", blendvpd_3 = "rmRo:660F3815rM", blendvps_3 = "rmRo:660F3814rM", dppd_3 = "rmio:660F3A41rMU", dpps_3 = "rmio:660F3A40rMU", extractps_3 = "mri/do:660F3A17RmU|rri/qo:660F3A17RXmU", insertps_3 = "rrio:660F3A41rMU|rxi/od:", movntdqa_2 = "rmo:660F382ArM", mpsadbw_3 = "rmio:660F3A42rMU", packusdw_2 = "rmo:660F382BrM", pblendvb_3 = "rmRo:660F3810rM", pblendw_3 = "rmio:660F3A0ErMU", pcmpeqq_2 = "rmo:660F3829rM", pextrb_3 = "rri/do:660F3A14nRmU|rri/qo:|xri/bo:", pextrd_3 = "mri/do:660F3A16RmU", pextrq_3 = "mri/qo:660F3A16RmU", -- pextrw is SSE2, mem operand is SSE4.1 only phminposuw_2 = "rmo:660F3841rM", pinsrb_3 = "rri/od:660F3A20nrMU|rxi/ob:", pinsrd_3 = "rmi/od:660F3A22rMU", pinsrq_3 = "rmi/oq:660F3A22rXMU", pmaxsb_2 = "rmo:660F383CrM", pmaxsd_2 = "rmo:660F383DrM", pmaxud_2 = "rmo:660F383FrM", pmaxuw_2 = "rmo:660F383ErM", pminsb_2 = "rmo:660F3838rM", pminsd_2 = "rmo:660F3839rM", pminud_2 = "rmo:660F383BrM", pminuw_2 = "rmo:660F383ArM", pmovsxbd_2 = "rro:660F3821rM|rx/od:", pmovsxbq_2 = "rro:660F3822rM|rx/ow:", pmovsxbw_2 = "rro:660F3820rM|rx/oq:", pmovsxdq_2 = "rro:660F3825rM|rx/oq:", pmovsxwd_2 = "rro:660F3823rM|rx/oq:", pmovsxwq_2 = "rro:660F3824rM|rx/od:", pmovzxbd_2 = "rro:660F3831rM|rx/od:", pmovzxbq_2 = "rro:660F3832rM|rx/ow:", pmovzxbw_2 = "rro:660F3830rM|rx/oq:", pmovzxdq_2 = "rro:660F3835rM|rx/oq:", pmovzxwd_2 = "rro:660F3833rM|rx/oq:", pmovzxwq_2 = "rro:660F3834rM|rx/od:", pmuldq_2 = "rmo:660F3828rM", pmulld_2 = "rmo:660F3840rM", ptest_2 = "rmo:660F3817rM", roundpd_3 = "rmio:660F3A09rMU", roundps_3 = "rmio:660F3A08rMU", roundsd_3 = "rrio:660F3A0BrMU|rxi/oq:", roundss_3 = "rrio:660F3A0ArMU|rxi/od:", -- SSE4.2 ops crc32_2 = "rmqd:F20F38F1rM|rm/dw:66F20F38F1rM|rm/db:F20F38F0rM|rm/qb:", pcmpestri_3 = "rmio:660F3A61rMU", pcmpestrm_3 = "rmio:660F3A60rMU", pcmpgtq_2 = "rmo:660F3837rM", pcmpistri_3 = "rmio:660F3A63rMU", pcmpistrm_3 = "rmio:660F3A62rMU", popcnt_2 = "rmqdw:F30FB8rM", -- SSE4a extrq_2 = "rro:660F79rM", extrq_3 = "riio:660F780mUU", insertq_2 = "rro:F20F79rM", insertq_4 = "rriio:F20F78rMUU", lzcnt_2 = "rmqdw:F30FBDrM", movntsd_2 = "xr/qo:nF20F2BRm", movntss_2 = "xr/do:F30F2BRm", -- popcnt is also in SSE4.2 } ------------------------------------------------------------------------------ -- Arithmetic ops. for name,n in pairs{ add = 0, ["or"] = 1, adc = 2, sbb = 3, ["and"] = 4, sub = 5, xor = 6, cmp = 7 } do local n8 = shl(n, 3) map_op[name.."_2"] = format( "mr:%02XRm|rm:%02XrM|mI1qdw:81%XmI|mS1qdw:83%XmS|Ri1qdwb:%02Xri|mi1qdwb:81%Xmi", 1+n8, 3+n8, n, n, 5+n8, n) end -- Shift ops. for name,n in pairs{ rol = 0, ror = 1, rcl = 2, rcr = 3, shl = 4, shr = 5, sar = 7, sal = 4 } do map_op[name.."_2"] = format("m1:D1%Xm|mC1qdwb:D3%Xm|mi:C1%XmU", n, n, n) end -- Conditional ops. for cc,n in pairs(map_cc) do map_op["j"..cc.."_1"] = format("J.:n0F8%XJ", n) -- short: 7%X map_op["set"..cc.."_1"] = format("mb:n0F9%X2m", n) map_op["cmov"..cc.."_2"] = format("rmqdw:0F4%XrM", n) -- P6+ end -- FP arithmetic ops. for name,n in pairs{ add = 0, mul = 1, com = 2, comp = 3, sub = 4, subr = 5, div = 6, divr = 7 } do local nc = 0xc0 + shl(n, 3) local nr = nc + (n < 4 and 0 or (n % 2 == 0 and 8 or -8)) local fn = "f"..name map_op[fn.."_1"] = format("ff:D8%02Xr|xd:D8%Xm|xq:nDC%Xm", nc, n, n) if n == 2 or n == 3 then map_op[fn.."_2"] = format("Fff:D8%02XR|Fx2d:D8%XM|Fx2q:nDC%XM", nc, n, n) else map_op[fn.."_2"] = format("Fff:D8%02XR|fFf:DC%02Xr|Fx2d:D8%XM|Fx2q:nDC%XM", nc, nr, n, n) map_op[fn.."p_1"] = format("ff:DE%02Xr", nr) map_op[fn.."p_2"] = format("fFf:DE%02Xr", nr) end map_op["fi"..name.."_1"] = format("xd:DA%Xm|xw:nDE%Xm", n, n) end -- FP conditional moves. for cc,n in pairs{ b=0, e=1, be=2, u=3, nb=4, ne=5, nbe=6, nu=7 } do local nc = 0xdac0 + shl(band(n, 3), 3) + shl(band(n, 4), 6) map_op["fcmov"..cc.."_1"] = format("ff:%04Xr", nc) -- P6+ map_op["fcmov"..cc.."_2"] = format("Fff:%04XR", nc) -- P6+ end -- SSE FP arithmetic ops. for name,n in pairs{ sqrt = 1, add = 8, mul = 9, sub = 12, min = 13, div = 14, max = 15 } do map_op[name.."ps_2"] = format("rmo:0F5%XrM", n) map_op[name.."ss_2"] = format("rro:F30F5%XrM|rx/od:", n) map_op[name.."pd_2"] = format("rmo:660F5%XrM", n) map_op[name.."sd_2"] = format("rro:F20F5%XrM|rx/oq:", n) end ------------------------------------------------------------------------------ -- Process pattern string. local function dopattern(pat, args, sz, op, needrex) local digit, addin local opcode = 0 local szov = sz local narg = 1 local rex = 0 -- Limit number of section buffer positions used by a single dasm_put(). -- A single opcode needs a maximum of 5 positions. if secpos+5 > maxsecpos then wflush() end -- Process each character. for c in gmatch(pat.."|", ".") do if match(c, "%x") then -- Hex digit. digit = byte(c) - 48 if digit > 48 then digit = digit - 39 elseif digit > 16 then digit = digit - 7 end opcode = opcode*16 + digit addin = nil elseif c == "n" then -- Disable operand size mods for opcode. szov = nil elseif c == "X" then -- Force REX.W. rex = 8 elseif c == "r" then -- Merge 1st operand regno. into opcode. addin = args[1]; opcode = opcode + (addin.reg % 8) if narg < 2 then narg = 2 end elseif c == "R" then -- Merge 2nd operand regno. into opcode. addin = args[2]; opcode = opcode + (addin.reg % 8) narg = 3 elseif c == "m" or c == "M" then -- Encode ModRM/SIB. local s if addin then s = addin.reg opcode = opcode - band(s, 7) -- Undo regno opcode merge. else s = band(opcode, 15) -- Undo last digit. opcode = shr(opcode, 4) end local nn = c == "m" and 1 or 2 local t = args[nn] if narg <= nn then narg = nn + 1 end if szov == "q" and rex == 0 then rex = rex + 8 end if t.reg and t.reg > 7 then rex = rex + 1 end if t.xreg and t.xreg > 7 then rex = rex + 2 end if s > 7 then rex = rex + 4 end if needrex then rex = rex + 16 end wputop(szov, opcode, rex); opcode = nil local imark = sub(pat, -1) -- Force a mark (ugly). -- Put ModRM/SIB with regno/last digit as spare. wputmrmsib(t, imark, s, addin and addin.vreg) addin = nil else if opcode then -- Flush opcode. if szov == "q" and rex == 0 then rex = rex + 8 end if needrex then rex = rex + 16 end if addin and addin.reg == -1 then wputop(szov, opcode - 7, rex) waction("VREG", addin.vreg); wputxb(0) else if addin and addin.reg > 7 then rex = rex + 1 end wputop(szov, opcode, rex) end opcode = nil end if c == "|" then break end if c == "o" then -- Offset (pure 32 bit displacement). wputdarg(args[1].disp); if narg < 2 then narg = 2 end elseif c == "O" then wputdarg(args[2].disp); narg = 3 else -- Anything else is an immediate operand. local a = args[narg] narg = narg + 1 local mode, imm = a.mode, a.imm if mode == "iJ" and not match("iIJ", c) then werror("bad operand size for label") end if c == "S" then wputsbarg(imm) elseif c == "U" then wputbarg(imm) elseif c == "W" then wputwarg(imm) elseif c == "i" or c == "I" then if mode == "iJ" then wputlabel("IMM_", imm, 1) elseif mode == "iI" and c == "I" then waction(sz == "w" and "IMM_WB" or "IMM_DB", imm) else wputszarg(sz, imm) end elseif c == "J" then if mode == "iPJ" then waction("REL_A", imm) -- !x64 (secpos) else wputlabel("REL_", imm, 2) end else werror("bad char `"..c.."' in pattern `"..pat.."' for `"..op.."'") end end end end end ------------------------------------------------------------------------------ -- Mapping of operand modes to short names. Suppress output with '#'. local map_modename = { r = "reg", R = "eax", C = "cl", x = "mem", m = "mrm", i = "imm", f = "stx", F = "st0", J = "lbl", ["1"] = "1", I = "#", S = "#", O = "#", } -- Return a table/string showing all possible operand modes. local function templatehelp(template, nparams) if nparams == 0 then return "" end local t = {} for tm in gmatch(template, "[^%|]+") do local s = map_modename[sub(tm, 1, 1)] s = s..gsub(sub(tm, 2, nparams), ".", function(c) return ", "..map_modename[c] end) if not match(s, "#") then t[#t+1] = s end end return t end -- Match operand modes against mode match part of template. local function matchtm(tm, args) for i=1,#args do if not match(args[i].mode, sub(tm, i, i)) then return end end return true end -- Handle opcodes defined with template strings. map_op[".template__"] = function(params, template, nparams) if not params then return templatehelp(template, nparams) end local args = {} -- Zero-operand opcodes have no match part. if #params == 0 then dopattern(template, args, "d", params.op, nil) return end -- Determine common operand size (coerce undefined size) or flag as mixed. local sz, szmix, needrex for i,p in ipairs(params) do args[i] = parseoperand(p) local nsz = args[i].opsize if nsz then if sz and sz ~= nsz then szmix = true else sz = nsz end end local nrex = args[i].needrex if nrex ~= nil then if needrex == nil then needrex = nrex elseif needrex ~= nrex then werror("bad mix of byte-addressable registers") end end end -- Try all match:pattern pairs (separated by '|'). local gotmatch, lastpat for tm in gmatch(template, "[^%|]+") do -- Split off size match (starts after mode match) and pattern string. local szm, pat = match(tm, "^(.-):(.*)$", #args+1) if pat == "" then pat = lastpat else lastpat = pat end if matchtm(tm, args) then local prefix = sub(szm, 1, 1) if prefix == "/" then -- Match both operand sizes. if args[1].opsize == sub(szm, 2, 2) and args[2].opsize == sub(szm, 3, 3) then dopattern(pat, args, sz, params.op, needrex) -- Process pattern. return end else -- Match common operand size. local szp = sz if szm == "" then szm = x64 and "qdwb" or "dwb" end -- Default sizes. if prefix == "1" then szp = args[1].opsize; szmix = nil elseif prefix == "2" then szp = args[2].opsize; szmix = nil end if not szmix and (prefix == "." or match(szm, szp or "#")) then dopattern(pat, args, szp, params.op, needrex) -- Process pattern. return end end gotmatch = true end end local msg = "bad operand mode" if gotmatch then if szmix then msg = "mixed operand size" else msg = sz and "bad operand size" or "missing operand size" end end werror(msg.." in `"..opmodestr(params.op, args).."'") end ------------------------------------------------------------------------------ -- x64-specific opcode for 64 bit immediates and displacements. if x64 then function map_op.mov64_2(params) if not params then return { "reg, imm", "reg, [disp]", "[disp], reg" } end if secpos+2 > maxsecpos then wflush() end local opcode, op64, sz, rex local op64 = match(params[1], "^%[%s*(.-)%s*%]$") if op64 then local a = parseoperand(params[2]) if a.mode ~= "rmR" then werror("bad operand mode") end sz = a.opsize rex = sz == "q" and 8 or 0 opcode = 0xa3 else op64 = match(params[2], "^%[%s*(.-)%s*%]$") local a = parseoperand(params[1]) if op64 then if a.mode ~= "rmR" then werror("bad operand mode") end sz = a.opsize rex = sz == "q" and 8 or 0 opcode = 0xa1 else if sub(a.mode, 1, 1) ~= "r" or a.opsize ~= "q" then werror("bad operand mode") end op64 = params[2] opcode = 0xb8 + band(a.reg, 7) -- !x64: no VREG support. rex = a.reg > 7 and 9 or 8 end end wputop(sz, opcode, rex) waction("IMM_D", format("(unsigned int)(%s)", op64)) waction("IMM_D", format("(unsigned int)((%s)>>32)", op64)) end end ------------------------------------------------------------------------------ -- Pseudo-opcodes for data storage. local function op_data(params) if not params then return "imm..." end local sz = sub(params.op, 2, 2) if sz == "a" then sz = addrsize end for _,p in ipairs(params) do local a = parseoperand(p) if sub(a.mode, 1, 1) ~= "i" or (a.opsize and a.opsize ~= sz) then werror("bad mode or size in `"..p.."'") end if a.mode == "iJ" then wputlabel("IMM_", a.imm, 1) else wputszarg(sz, a.imm) end if secpos+2 > maxsecpos then wflush() end end end map_op[".byte_*"] = op_data map_op[".sbyte_*"] = op_data map_op[".word_*"] = op_data map_op[".dword_*"] = op_data map_op[".aword_*"] = op_data ------------------------------------------------------------------------------ -- Pseudo-opcode to mark the position where the action list is to be emitted. map_op[".actionlist_1"] = function(params) if not params then return "cvar" end local name = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeactions(out, name) end) end -- Pseudo-opcode to mark the position where the global enum is to be emitted. map_op[".globals_1"] = function(params) if not params then return "prefix" end local prefix = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeglobals(out, prefix) end) end -- Pseudo-opcode to mark the position where the global names are to be emitted. map_op[".globalnames_1"] = function(params) if not params then return "cvar" end local name = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeglobalnames(out, name) end) end -- Pseudo-opcode to mark the position where the extern names are to be emitted. map_op[".externnames_1"] = function(params) if not params then return "cvar" end local name = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeexternnames(out, name) end) end ------------------------------------------------------------------------------ -- Label pseudo-opcode (converted from trailing colon form). map_op[".label_2"] = function(params) if not params then return "[1-9] | ->global | =>pcexpr [, addr]" end if secpos+2 > maxsecpos then wflush() end local a = parseoperand(params[1]) local mode, imm = a.mode, a.imm if type(imm) == "number" and (mode == "iJ" or (imm >= 1 and imm <= 9)) then -- Local label (1: ... 9:) or global label (->global:). waction("LABEL_LG", nil, 1) wputxb(imm) elseif mode == "iJ" then -- PC label (=>pcexpr:). waction("LABEL_PC", imm) else werror("bad label definition") end -- SETLABEL must immediately follow LABEL_LG/LABEL_PC. local addr = params[2] if addr then local a = parseoperand(addr) if a.mode == "iPJ" then waction("SETLABEL", a.imm) else werror("bad label assignment") end end end map_op[".label_1"] = map_op[".label_2"] ------------------------------------------------------------------------------ -- Alignment pseudo-opcode. map_op[".align_1"] = function(params) if not params then return "numpow2" end if secpos+1 > maxsecpos then wflush() end local align = tonumber(params[1]) or map_opsizenum[map_opsize[params[1]]] if align then local x = align -- Must be a power of 2 in the range (2 ... 256). for i=1,8 do x = x / 2 if x == 1 then waction("ALIGN", nil, 1) wputxb(align-1) -- Action byte is 2**n-1. return end end end werror("bad alignment") end -- Spacing pseudo-opcode. map_op[".space_2"] = function(params) if not params then return "num [, filler]" end if secpos+1 > maxsecpos then wflush() end waction("SPACE", params[1]) local fill = params[2] if fill then fill = tonumber(fill) if not fill or fill < 0 or fill > 255 then werror("bad filler") end end wputxb(fill or 0) end map_op[".space_1"] = map_op[".space_2"] ------------------------------------------------------------------------------ -- Pseudo-opcode for (primitive) type definitions (map to C types). map_op[".type_3"] = function(params, nparams) if not params then return nparams == 2 and "name, ctype" or "name, ctype, reg" end local name, ctype, reg = params[1], params[2], params[3] if not match(name, "^[%a_][%w_]*$") then werror("bad type name `"..name.."'") end local tp = map_type[name] if tp then werror("duplicate type `"..name.."'") end if reg and not map_reg_valid_base[reg] then werror("bad base register `"..(map_reg_rev[reg] or reg).."'") end -- Add #type to defines. A bit unclean to put it in map_archdef. map_archdef["#"..name] = "sizeof("..ctype..")" -- Add new type and emit shortcut define. local num = ctypenum + 1 map_type[name] = { ctype = ctype, ctypefmt = format("Dt%X(%%s)", num), reg = reg, } wline(format("#define Dt%X(_V) (int)(ptrdiff_t)&(((%s *)0)_V)", num, ctype)) ctypenum = num end map_op[".type_2"] = map_op[".type_3"] -- Dump type definitions. local function dumptypes(out, lvl) local t = {} for name in pairs(map_type) do t[#t+1] = name end sort(t) out:write("Type definitions:\n") for _,name in ipairs(t) do local tp = map_type[name] local reg = tp.reg and map_reg_rev[tp.reg] or "" out:write(format(" %-20s %-20s %s\n", name, tp.ctype, reg)) end out:write("\n") end ------------------------------------------------------------------------------ -- Set the current section. function _M.section(num) waction("SECTION") wputxb(num) wflush(true) -- SECTION is a terminal action. end ------------------------------------------------------------------------------ -- Dump architecture description. function _M.dumparch(out) out:write(format("DynASM %s version %s, released %s\n\n", _info.arch, _info.version, _info.release)) dumpregs(out) dumpactions(out) end -- Dump all user defined elements. function _M.dumpdef(out, lvl) dumptypes(out, lvl) dumpglobals(out, lvl) dumpexterns(out, lvl) end ------------------------------------------------------------------------------ -- Pass callbacks from/to the DynASM core. function _M.passcb(wl, we, wf, ww) wline, werror, wfatal, wwarn = wl, we, wf, ww return wflush end -- Setup the arch-specific module. function _M.setup(arch, opt) g_arch, g_opt = arch, opt end -- Merge the core maps and the arch-specific maps. function _M.mergemaps(map_coreop, map_def) setmetatable(map_op, { __index = map_coreop }) setmetatable(map_def, { __index = map_archdef }) return map_op, map_def end return _M ------------------------------------------------------------------------------
mit
dickeyf/darkstar
scripts/zones/Port_San_dOria/npcs/Jaireto.lua
13
1355
----------------------------------- -- Area: Port San d'Oria -- NPC: Jaireto -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/zones/Port_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE); 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(0x2c7); 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
dickeyf/darkstar
scripts/zones/Norg/Zone.lua
12
2317
----------------------------------- -- -- Zone: Norg (252) -- ----------------------------------- package.loaded["scripts/zones/Norg/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/zones/Norg/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) 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(-19.238,-2.163,-63.964,187); end if (player:getCurrentMission(ZILART) == THE_NEW_FRONTIER) then cs = 0x0001; elseif (player:getCurrentMission(ZILART) == AWAKENING and player:getVar("ZilartStatus") == 0 or player:getVar("ZilartStatus") == 2) then cs = 0x00B0; 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); if (csid == 0x0001) then if (player:hasKeyItem(MAP_OF_NORG) == false) then player:addKeyItem(MAP_OF_NORG); player:messageSpecial(KEYITEM_OBTAINED,MAP_OF_NORG); end player:completeMission(ZILART,THE_NEW_FRONTIER); player:addMission(ZILART,WELCOME_TNORG); elseif (csid == 0x00B0) then player:setVar("ZilartStatus", player:getVar("ZilartStatus")+1); end end;
gpl-3.0
Turttle/darkstar
scripts/zones/Bastok_Markets/npcs/Shamarhaan.lua
38
1856
----------------------------------- -- Area: Bastok Markets -- NPC: Shamarhaan -- Type: Quest Starter -- Involved in quest: No Strings Attached -- @zone: 235 -- @pos -285.382 -13.021 -84.743 -- -- Auto-Script: Requires Verification. Verified standard dialog - thrydwolf 12/8/2011 ----------------------------------- package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Bastok_Markets/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local NoStringsAttached = player:getQuestStatus(AHT_URHGAN,NO_STRINGS_ATTACHED); local NoStringsAttachedProgress = player:getVar("NoStringsAttachedProgress"); if (player:getMainLvl() >= ADVANCED_JOB_LEVEL and NoStringsAttached == QUEST_AVAILABLE) then player:startEvent(0x01b2); -- initial cs to start the quest, go and see Iruki-Waraki at Whitegate elseif (NoStringsAttachedProgress == 1) then player:startEvent(0x01b3); -- reminder to go see Iruki-Waraki at Whitegate else player:startEvent(0x01b1); 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 == 0x01b2) then player:setVar("NoStringsAttachedProgress",1); player:addQuest(AHT_URHGAN,NO_STRINGS_ATTACHED); end; end;
gpl-3.0
SalvationDevelopment/Salvation-Scripts-TCG
c61468779.lua
5
2752
--地霊神グランソイル function c61468779.initial_effect(c) c:EnableReviveLimit() --cannot special summon local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE) e1:SetCode(EFFECT_SPSUMMON_CONDITION) c:RegisterEffect(e1) --special summon local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_FIELD) e2:SetCode(EFFECT_SPSUMMON_PROC) e2:SetProperty(EFFECT_FLAG_UNCOPYABLE) e2:SetRange(LOCATION_HAND) e2:SetCondition(c61468779.spcon) c:RegisterEffect(e2) --spsummon local e3=Effect.CreateEffect(c) e3:SetDescription(aux.Stringid(61468779,0)) e3:SetCategory(CATEGORY_SPECIAL_SUMMON) e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e3:SetCode(EVENT_SPSUMMON_SUCCESS) e3:SetProperty(EFFECT_FLAG_CARD_TARGET) e3:SetTarget(c61468779.sptg) e3:SetOperation(c61468779.spop) c:RegisterEffect(e3) --leave local e4=Effect.CreateEffect(c) e4:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS) e4:SetCode(EVENT_LEAVE_FIELD_P) e4:SetOperation(c61468779.leaveop) c:RegisterEffect(e4) end function c61468779.spcon(e,c) if c==nil then return true end return Duel.GetLocationCount(c:GetControler(),LOCATION_MZONE)>0 and Duel.GetMatchingGroupCount(Card.IsAttribute,c:GetControler(),LOCATION_GRAVE,0,nil,ATTRIBUTE_EARTH)==5 end function c61468779.filter(c,e,tp) return c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function c61468779.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_GRAVE) and c61468779.filter(chkc,e,tp) end if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingTarget(c61468779.filter,tp,LOCATION_GRAVE,LOCATION_GRAVE,1,nil,e,tp) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectTarget(tp,c61468779.filter,tp,LOCATION_GRAVE,LOCATION_GRAVE,1,1,nil,e,tp) Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0) end function c61468779.spop(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) then Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP) end end function c61468779.leaveop(e,tp,eg,ep,ev,re,r,rp) if e:GetHandler():IsFacedown() then return end local effp=e:GetHandler():GetControler() local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_FIELD) e1:SetCode(EFFECT_SKIP_BP) e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET) e1:SetTargetRange(1,0) if Duel.GetTurnPlayer()==effp then e1:SetLabel(Duel.GetTurnCount()) e1:SetCondition(c61468779.skipcon) e1:SetReset(RESET_PHASE+PHASE_END+RESET_SELF_TURN,2) else e1:SetReset(RESET_PHASE+PHASE_END+RESET_SELF_TURN,1) end Duel.RegisterEffect(e1,effp) end function c61468779.skipcon(e) return Duel.GetTurnCount()~=e:GetLabel() end
gpl-2.0
comru/google-diff-match-patch
lua/diff_match_patch.lua
265
73869
--[[ * Diff Match and Patch * * Copyright 2006 Google Inc. * http://code.google.com/p/google-diff-match-patch/ * * Based on the JavaScript implementation by Neil Fraser. * Ported to Lua by Duncan Cross. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. --]] --[[ -- Lua 5.1 and earlier requires the external BitOp library. -- This library is built-in from Lua 5.2 and later as 'bit32'. require 'bit' -- <http://bitop.luajit.org/> local band, bor, lshift = bit.band, bit.bor, bit.lshift --]] local band, bor, lshift = bit32.band, bit32.bor, bit32.lshift local type, setmetatable, ipairs, select = type, setmetatable, ipairs, select local unpack, tonumber, error = unpack, tonumber, error local strsub, strbyte, strchar, gmatch, gsub = string.sub, string.byte, string.char, string.gmatch, string.gsub local strmatch, strfind, strformat = string.match, string.find, string.format local tinsert, tremove, tconcat = table.insert, table.remove, table.concat local max, min, floor, ceil, abs = math.max, math.min, math.floor, math.ceil, math.abs local clock = os.clock -- Utility functions. local percentEncode_pattern = '[^A-Za-z0-9%-=;\',./~!@#$%&*%(%)_%+ %?]' local function percentEncode_replace(v) return strformat('%%%02X', strbyte(v)) end local function tsplice(t, idx, deletions, ...) local insertions = select('#', ...) for i = 1, deletions do tremove(t, idx) end for i = insertions, 1, -1 do -- do not remove parentheses around select tinsert(t, idx, (select(i, ...))) end end local function strelement(str, i) return strsub(str, i, i) end local function indexOf(a, b, start) if (#b == 0) then return nil end return strfind(a, b, start, true) end local htmlEncode_pattern = '[&<>\n]' local htmlEncode_replace = { ['&'] = '&amp;', ['<'] = '&lt;', ['>'] = '&gt;', ['\n'] = '&para;<br>' } -- Public API Functions -- (Exported at the end of the script) local diff_main, diff_cleanupSemantic, diff_cleanupEfficiency, diff_levenshtein, diff_prettyHtml local match_main local patch_make, patch_toText, patch_fromText, patch_apply --[[ * The data structure representing a diff is an array of tuples: * {{DIFF_DELETE, 'Hello'}, {DIFF_INSERT, 'Goodbye'}, {DIFF_EQUAL, ' world.'}} * which means: delete 'Hello', add 'Goodbye' and keep ' world.' --]] local DIFF_DELETE = -1 local DIFF_INSERT = 1 local DIFF_EQUAL = 0 -- Number of seconds to map a diff before giving up (0 for infinity). local Diff_Timeout = 1.0 -- Cost of an empty edit operation in terms of edit characters. local Diff_EditCost = 4 -- At what point is no match declared (0.0 = perfection, 1.0 = very loose). local Match_Threshold = 0.5 -- How far to search for a match (0 = exact location, 1000+ = broad match). -- A match this many characters away from the expected location will add -- 1.0 to the score (0.0 is a perfect match). local Match_Distance = 1000 -- When deleting a large block of text (over ~64 characters), how close do -- the contents have to be to match the expected contents. (0.0 = perfection, -- 1.0 = very loose). Note that Match_Threshold controls how closely the -- end points of a delete need to match. local Patch_DeleteThreshold = 0.5 -- Chunk size for context length. local Patch_Margin = 4 -- The number of bits in an int. local Match_MaxBits = 32 function settings(new) if new then Diff_Timeout = new.Diff_Timeout or Diff_Timeout Diff_EditCost = new.Diff_EditCost or Diff_EditCost Match_Threshold = new.Match_Threshold or Match_Threshold Match_Distance = new.Match_Distance or Match_Distance Patch_DeleteThreshold = new.Patch_DeleteThreshold or Patch_DeleteThreshold Patch_Margin = new.Patch_Margin or Patch_Margin Match_MaxBits = new.Match_MaxBits or Match_MaxBits else return { Diff_Timeout = Diff_Timeout; Diff_EditCost = Diff_EditCost; Match_Threshold = Match_Threshold; Match_Distance = Match_Distance; Patch_DeleteThreshold = Patch_DeleteThreshold; Patch_Margin = Patch_Margin; Match_MaxBits = Match_MaxBits; } end end -- --------------------------------------------------------------------------- -- DIFF API -- --------------------------------------------------------------------------- -- The private diff functions local _diff_compute, _diff_bisect, _diff_halfMatchI, _diff_halfMatch, _diff_cleanupSemanticScore, _diff_cleanupSemanticLossless, _diff_cleanupMerge, _diff_commonPrefix, _diff_commonSuffix, _diff_commonOverlap, _diff_xIndex, _diff_text1, _diff_text2, _diff_toDelta, _diff_fromDelta --[[ * Find the differences between two texts. Simplifies the problem by stripping * any common prefix or suffix off the texts before diffing. * @param {string} text1 Old string to be diffed. * @param {string} text2 New string to be diffed. * @param {boolean} opt_checklines Has no effect in Lua. * @param {number} opt_deadline Optional time when the diff should be complete * by. Used internally for recursive calls. Users should set DiffTimeout * instead. * @return {Array.<Array.<number|string>>} Array of diff tuples. --]] function diff_main(text1, text2, opt_checklines, opt_deadline) -- Set a deadline by which time the diff must be complete. if opt_deadline == nil then if Diff_Timeout <= 0 then opt_deadline = 2 ^ 31 else opt_deadline = clock() + Diff_Timeout end end local deadline = opt_deadline -- Check for null inputs. if text1 == nil or text1 == nil then error('Null inputs. (diff_main)') end -- Check for equality (speedup). if text1 == text2 then if #text1 > 0 then return {{DIFF_EQUAL, text1}} end return {} end -- LUANOTE: Due to the lack of Unicode support, Lua is incapable of -- implementing the line-mode speedup. local checklines = false -- Trim off common prefix (speedup). local commonlength = _diff_commonPrefix(text1, text2) local commonprefix if commonlength > 0 then commonprefix = strsub(text1, 1, commonlength) text1 = strsub(text1, commonlength + 1) text2 = strsub(text2, commonlength + 1) end -- Trim off common suffix (speedup). commonlength = _diff_commonSuffix(text1, text2) local commonsuffix if commonlength > 0 then commonsuffix = strsub(text1, -commonlength) text1 = strsub(text1, 1, -commonlength - 1) text2 = strsub(text2, 1, -commonlength - 1) end -- Compute the diff on the middle block. local diffs = _diff_compute(text1, text2, checklines, deadline) -- Restore the prefix and suffix. if commonprefix then tinsert(diffs, 1, {DIFF_EQUAL, commonprefix}) end if commonsuffix then diffs[#diffs + 1] = {DIFF_EQUAL, commonsuffix} end _diff_cleanupMerge(diffs) return diffs end --[[ * Reduce the number of edits by eliminating semantically trivial equalities. * @param {Array.<Array.<number|string>>} diffs Array of diff tuples. --]] function diff_cleanupSemantic(diffs) local changes = false local equalities = {} -- Stack of indices where equalities are found. local equalitiesLength = 0 -- Keeping our own length var is faster. local lastequality = nil -- Always equal to diffs[equalities[equalitiesLength]][2] local pointer = 1 -- Index of current position. -- Number of characters that changed prior to the equality. local length_insertions1 = 0 local length_deletions1 = 0 -- Number of characters that changed after the equality. local length_insertions2 = 0 local length_deletions2 = 0 while diffs[pointer] do if diffs[pointer][1] == DIFF_EQUAL then -- Equality found. equalitiesLength = equalitiesLength + 1 equalities[equalitiesLength] = pointer length_insertions1 = length_insertions2 length_deletions1 = length_deletions2 length_insertions2 = 0 length_deletions2 = 0 lastequality = diffs[pointer][2] else -- An insertion or deletion. if diffs[pointer][1] == DIFF_INSERT then length_insertions2 = length_insertions2 + #(diffs[pointer][2]) else length_deletions2 = length_deletions2 + #(diffs[pointer][2]) end -- Eliminate an equality that is smaller or equal to the edits on both -- sides of it. if lastequality and (#lastequality <= max(length_insertions1, length_deletions1)) and (#lastequality <= max(length_insertions2, length_deletions2)) then -- Duplicate record. tinsert(diffs, equalities[equalitiesLength], {DIFF_DELETE, lastequality}) -- Change second copy to insert. diffs[equalities[equalitiesLength] + 1][1] = DIFF_INSERT -- Throw away the equality we just deleted. equalitiesLength = equalitiesLength - 1 -- Throw away the previous equality (it needs to be reevaluated). equalitiesLength = equalitiesLength - 1 pointer = (equalitiesLength > 0) and equalities[equalitiesLength] or 0 length_insertions1, length_deletions1 = 0, 0 -- Reset the counters. length_insertions2, length_deletions2 = 0, 0 lastequality = nil changes = true end end pointer = pointer + 1 end -- Normalize the diff. if changes then _diff_cleanupMerge(diffs) end _diff_cleanupSemanticLossless(diffs) -- Find any overlaps between deletions and insertions. -- e.g: <del>abcxxx</del><ins>xxxdef</ins> -- -> <del>abc</del>xxx<ins>def</ins> -- e.g: <del>xxxabc</del><ins>defxxx</ins> -- -> <ins>def</ins>xxx<del>abc</del> -- Only extract an overlap if it is as big as the edit ahead or behind it. pointer = 2 while diffs[pointer] do if (diffs[pointer - 1][1] == DIFF_DELETE and diffs[pointer][1] == DIFF_INSERT) then local deletion = diffs[pointer - 1][2] local insertion = diffs[pointer][2] local overlap_length1 = _diff_commonOverlap(deletion, insertion) local overlap_length2 = _diff_commonOverlap(insertion, deletion) if (overlap_length1 >= overlap_length2) then if (overlap_length1 >= #deletion / 2 or overlap_length1 >= #insertion / 2) then -- Overlap found. Insert an equality and trim the surrounding edits. tinsert(diffs, pointer, {DIFF_EQUAL, strsub(insertion, 1, overlap_length1)}) diffs[pointer - 1][2] = strsub(deletion, 1, #deletion - overlap_length1) diffs[pointer + 1][2] = strsub(insertion, overlap_length1 + 1) pointer = pointer + 1 end else if (overlap_length2 >= #deletion / 2 or overlap_length2 >= #insertion / 2) then -- Reverse overlap found. -- Insert an equality and swap and trim the surrounding edits. tinsert(diffs, pointer, {DIFF_EQUAL, strsub(deletion, 1, overlap_length2)}) diffs[pointer - 1] = {DIFF_INSERT, strsub(insertion, 1, #insertion - overlap_length2)} diffs[pointer + 1] = {DIFF_DELETE, strsub(deletion, overlap_length2 + 1)} pointer = pointer + 1 end end pointer = pointer + 1 end pointer = pointer + 1 end end --[[ * Reduce the number of edits by eliminating operationally trivial equalities. * @param {Array.<Array.<number|string>>} diffs Array of diff tuples. --]] function diff_cleanupEfficiency(diffs) local changes = false -- Stack of indices where equalities are found. local equalities = {} -- Keeping our own length var is faster. local equalitiesLength = 0 -- Always equal to diffs[equalities[equalitiesLength]][2] local lastequality = nil -- Index of current position. local pointer = 1 -- The following four are really booleans but are stored as numbers because -- they are used at one point like this: -- -- (pre_ins + pre_del + post_ins + post_del) == 3 -- -- ...i.e. checking that 3 of them are true and 1 of them is false. -- Is there an insertion operation before the last equality. local pre_ins = 0 -- Is there a deletion operation before the last equality. local pre_del = 0 -- Is there an insertion operation after the last equality. local post_ins = 0 -- Is there a deletion operation after the last equality. local post_del = 0 while diffs[pointer] do if diffs[pointer][1] == DIFF_EQUAL then -- Equality found. local diffText = diffs[pointer][2] if (#diffText < Diff_EditCost) and (post_ins == 1 or post_del == 1) then -- Candidate found. equalitiesLength = equalitiesLength + 1 equalities[equalitiesLength] = pointer pre_ins, pre_del = post_ins, post_del lastequality = diffText else -- Not a candidate, and can never become one. equalitiesLength = 0 lastequality = nil end post_ins, post_del = 0, 0 else -- An insertion or deletion. if diffs[pointer][1] == DIFF_DELETE then post_del = 1 else post_ins = 1 end --[[ * Five types to be split: * <ins>A</ins><del>B</del>XY<ins>C</ins><del>D</del> * <ins>A</ins>X<ins>C</ins><del>D</del> * <ins>A</ins><del>B</del>X<ins>C</ins> * <ins>A</del>X<ins>C</ins><del>D</del> * <ins>A</ins><del>B</del>X<del>C</del> --]] if lastequality and ( (pre_ins+pre_del+post_ins+post_del == 4) or ( (#lastequality < Diff_EditCost / 2) and (pre_ins+pre_del+post_ins+post_del == 3) )) then -- Duplicate record. tinsert(diffs, equalities[equalitiesLength], {DIFF_DELETE, lastequality}) -- Change second copy to insert. diffs[equalities[equalitiesLength] + 1][1] = DIFF_INSERT -- Throw away the equality we just deleted. equalitiesLength = equalitiesLength - 1 lastequality = nil if (pre_ins == 1) and (pre_del == 1) then -- No changes made which could affect previous entry, keep going. post_ins, post_del = 1, 1 equalitiesLength = 0 else -- Throw away the previous equality. equalitiesLength = equalitiesLength - 1 pointer = (equalitiesLength > 0) and equalities[equalitiesLength] or 0 post_ins, post_del = 0, 0 end changes = true end end pointer = pointer + 1 end if changes then _diff_cleanupMerge(diffs) end end --[[ * Compute the Levenshtein distance; the number of inserted, deleted or * substituted characters. * @param {Array.<Array.<number|string>>} diffs Array of diff tuples. * @return {number} Number of changes. --]] function diff_levenshtein(diffs) local levenshtein = 0 local insertions, deletions = 0, 0 for x, diff in ipairs(diffs) do local op, data = diff[1], diff[2] if (op == DIFF_INSERT) then insertions = insertions + #data elseif (op == DIFF_DELETE) then deletions = deletions + #data elseif (op == DIFF_EQUAL) then -- A deletion and an insertion is one substitution. levenshtein = levenshtein + max(insertions, deletions) insertions = 0 deletions = 0 end end levenshtein = levenshtein + max(insertions, deletions) return levenshtein end --[[ * Convert a diff array into a pretty HTML report. * @param {Array.<Array.<number|string>>} diffs Array of diff tuples. * @return {string} HTML representation. --]] function diff_prettyHtml(diffs) local html = {} for x, diff in ipairs(diffs) do local op = diff[1] -- Operation (insert, delete, equal) local data = diff[2] -- Text of change. local text = gsub(data, htmlEncode_pattern, htmlEncode_replace) if op == DIFF_INSERT then html[x] = '<ins style="background:#e6ffe6;">' .. text .. '</ins>' elseif op == DIFF_DELETE then html[x] = '<del style="background:#ffe6e6;">' .. text .. '</del>' elseif op == DIFF_EQUAL then html[x] = '<span>' .. text .. '</span>' end end return tconcat(html) end -- --------------------------------------------------------------------------- -- UNOFFICIAL/PRIVATE DIFF FUNCTIONS -- --------------------------------------------------------------------------- --[[ * Find the differences between two texts. Assumes that the texts do not * have any common prefix or suffix. * @param {string} text1 Old string to be diffed. * @param {string} text2 New string to be diffed. * @param {boolean} checklines Has no effect in Lua. * @param {number} deadline Time when the diff should be complete by. * @return {Array.<Array.<number|string>>} Array of diff tuples. * @private --]] function _diff_compute(text1, text2, checklines, deadline) if #text1 == 0 then -- Just add some text (speedup). return {{DIFF_INSERT, text2}} end if #text2 == 0 then -- Just delete some text (speedup). return {{DIFF_DELETE, text1}} end local diffs local longtext = (#text1 > #text2) and text1 or text2 local shorttext = (#text1 > #text2) and text2 or text1 local i = indexOf(longtext, shorttext) if i ~= nil then -- Shorter text is inside the longer text (speedup). diffs = { {DIFF_INSERT, strsub(longtext, 1, i - 1)}, {DIFF_EQUAL, shorttext}, {DIFF_INSERT, strsub(longtext, i + #shorttext)} } -- Swap insertions for deletions if diff is reversed. if #text1 > #text2 then diffs[1][1], diffs[3][1] = DIFF_DELETE, DIFF_DELETE end return diffs end if #shorttext == 1 then -- Single character string. -- After the previous speedup, the character can't be an equality. return {{DIFF_DELETE, text1}, {DIFF_INSERT, text2}} end -- Check to see if the problem can be split in two. do local text1_a, text1_b, text2_a, text2_b, mid_common = _diff_halfMatch(text1, text2) if text1_a then -- A half-match was found, sort out the return data. -- Send both pairs off for separate processing. local diffs_a = diff_main(text1_a, text2_a, checklines, deadline) local diffs_b = diff_main(text1_b, text2_b, checklines, deadline) -- Merge the results. local diffs_a_len = #diffs_a diffs = diffs_a diffs[diffs_a_len + 1] = {DIFF_EQUAL, mid_common} for i, b_diff in ipairs(diffs_b) do diffs[diffs_a_len + 1 + i] = b_diff end return diffs end end return _diff_bisect(text1, text2, deadline) end --[[ * Find the 'middle snake' of a diff, split the problem in two * and return the recursively constructed diff. * See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations. * @param {string} text1 Old string to be diffed. * @param {string} text2 New string to be diffed. * @param {number} deadline Time at which to bail if not yet complete. * @return {Array.<Array.<number|string>>} Array of diff tuples. * @private --]] function _diff_bisect(text1, text2, deadline) -- Cache the text lengths to prevent multiple calls. local text1_length = #text1 local text2_length = #text2 local _sub, _element local max_d = ceil((text1_length + text2_length) / 2) local v_offset = max_d local v_length = 2 * max_d local v1 = {} local v2 = {} -- Setting all elements to -1 is faster in Lua than mixing integers and nil. for x = 0, v_length - 1 do v1[x] = -1 v2[x] = -1 end v1[v_offset + 1] = 0 v2[v_offset + 1] = 0 local delta = text1_length - text2_length -- If the total number of characters is odd, then -- the front path will collide with the reverse path. local front = (delta % 2 ~= 0) -- Offsets for start and end of k loop. -- Prevents mapping of space beyond the grid. local k1start = 0 local k1end = 0 local k2start = 0 local k2end = 0 for d = 0, max_d - 1 do -- Bail out if deadline is reached. if clock() > deadline then break end -- Walk the front path one step. for k1 = -d + k1start, d - k1end, 2 do local k1_offset = v_offset + k1 local x1 if (k1 == -d) or ((k1 ~= d) and (v1[k1_offset - 1] < v1[k1_offset + 1])) then x1 = v1[k1_offset + 1] else x1 = v1[k1_offset - 1] + 1 end local y1 = x1 - k1 while (x1 <= text1_length) and (y1 <= text2_length) and (strelement(text1, x1) == strelement(text2, y1)) do x1 = x1 + 1 y1 = y1 + 1 end v1[k1_offset] = x1 if x1 > text1_length + 1 then -- Ran off the right of the graph. k1end = k1end + 2 elseif y1 > text2_length + 1 then -- Ran off the bottom of the graph. k1start = k1start + 2 elseif front then local k2_offset = v_offset + delta - k1 if k2_offset >= 0 and k2_offset < v_length and v2[k2_offset] ~= -1 then -- Mirror x2 onto top-left coordinate system. local x2 = text1_length - v2[k2_offset] + 1 if x1 > x2 then -- Overlap detected. return _diff_bisectSplit(text1, text2, x1, y1, deadline) end end end end -- Walk the reverse path one step. for k2 = -d + k2start, d - k2end, 2 do local k2_offset = v_offset + k2 local x2 if (k2 == -d) or ((k2 ~= d) and (v2[k2_offset - 1] < v2[k2_offset + 1])) then x2 = v2[k2_offset + 1] else x2 = v2[k2_offset - 1] + 1 end local y2 = x2 - k2 while (x2 <= text1_length) and (y2 <= text2_length) and (strelement(text1, -x2) == strelement(text2, -y2)) do x2 = x2 + 1 y2 = y2 + 1 end v2[k2_offset] = x2 if x2 > text1_length + 1 then -- Ran off the left of the graph. k2end = k2end + 2 elseif y2 > text2_length + 1 then -- Ran off the top of the graph. k2start = k2start + 2 elseif not front then local k1_offset = v_offset + delta - k2 if k1_offset >= 0 and k1_offset < v_length and v1[k1_offset] ~= -1 then local x1 = v1[k1_offset] local y1 = v_offset + x1 - k1_offset -- Mirror x2 onto top-left coordinate system. x2 = text1_length - x2 + 1 if x1 > x2 then -- Overlap detected. return _diff_bisectSplit(text1, text2, x1, y1, deadline) end end end end end -- Diff took too long and hit the deadline or -- number of diffs equals number of characters, no commonality at all. return {{DIFF_DELETE, text1}, {DIFF_INSERT, text2}} end --[[ * Given the location of the 'middle snake', split the diff in two parts * and recurse. * @param {string} text1 Old string to be diffed. * @param {string} text2 New string to be diffed. * @param {number} x Index of split point in text1. * @param {number} y Index of split point in text2. * @param {number} deadline Time at which to bail if not yet complete. * @return {Array.<Array.<number|string>>} Array of diff tuples. * @private --]] function _diff_bisectSplit(text1, text2, x, y, deadline) local text1a = strsub(text1, 1, x - 1) local text2a = strsub(text2, 1, y - 1) local text1b = strsub(text1, x) local text2b = strsub(text2, y) -- Compute both diffs serially. local diffs = diff_main(text1a, text2a, false, deadline) local diffsb = diff_main(text1b, text2b, false, deadline) local diffs_len = #diffs for i, v in ipairs(diffsb) do diffs[diffs_len + i] = v end return diffs end --[[ * Determine the common prefix of two strings. * @param {string} text1 First string. * @param {string} text2 Second string. * @return {number} The number of characters common to the start of each * string. --]] function _diff_commonPrefix(text1, text2) -- Quick check for common null cases. if (#text1 == 0) or (#text2 == 0) or (strbyte(text1, 1) ~= strbyte(text2, 1)) then return 0 end -- Binary search. -- Performance analysis: http://neil.fraser.name/news/2007/10/09/ local pointermin = 1 local pointermax = min(#text1, #text2) local pointermid = pointermax local pointerstart = 1 while (pointermin < pointermid) do if (strsub(text1, pointerstart, pointermid) == strsub(text2, pointerstart, pointermid)) then pointermin = pointermid pointerstart = pointermin else pointermax = pointermid end pointermid = floor(pointermin + (pointermax - pointermin) / 2) end return pointermid end --[[ * Determine the common suffix of two strings. * @param {string} text1 First string. * @param {string} text2 Second string. * @return {number} The number of characters common to the end of each string. --]] function _diff_commonSuffix(text1, text2) -- Quick check for common null cases. if (#text1 == 0) or (#text2 == 0) or (strbyte(text1, -1) ~= strbyte(text2, -1)) then return 0 end -- Binary search. -- Performance analysis: http://neil.fraser.name/news/2007/10/09/ local pointermin = 1 local pointermax = min(#text1, #text2) local pointermid = pointermax local pointerend = 1 while (pointermin < pointermid) do if (strsub(text1, -pointermid, -pointerend) == strsub(text2, -pointermid, -pointerend)) then pointermin = pointermid pointerend = pointermin else pointermax = pointermid end pointermid = floor(pointermin + (pointermax - pointermin) / 2) end return pointermid end --[[ * Determine if the suffix of one string is the prefix of another. * @param {string} text1 First string. * @param {string} text2 Second string. * @return {number} The number of characters common to the end of the first * string and the start of the second string. * @private --]] function _diff_commonOverlap(text1, text2) -- Cache the text lengths to prevent multiple calls. local text1_length = #text1 local text2_length = #text2 -- Eliminate the null case. if text1_length == 0 or text2_length == 0 then return 0 end -- Truncate the longer string. if text1_length > text2_length then text1 = strsub(text1, text1_length - text2_length + 1) elseif text1_length < text2_length then text2 = strsub(text2, 1, text1_length) end local text_length = min(text1_length, text2_length) -- Quick check for the worst case. if text1 == text2 then return text_length end -- Start by looking for a single character match -- and increase length until no match is found. -- Performance analysis: http://neil.fraser.name/news/2010/11/04/ local best = 0 local length = 1 while true do local pattern = strsub(text1, text_length - length + 1) local found = strfind(text2, pattern, 1, true) if found == nil then return best end length = length + found - 1 if found == 1 or strsub(text1, text_length - length + 1) == strsub(text2, 1, length) then best = length length = length + 1 end end end --[[ * Does a substring of shorttext exist within longtext such that the substring * is at least half the length of longtext? * This speedup can produce non-minimal diffs. * Closure, but does not reference any external variables. * @param {string} longtext Longer string. * @param {string} shorttext Shorter string. * @param {number} i Start index of quarter length substring within longtext. * @return {?Array.<string>} Five element Array, containing the prefix of * longtext, the suffix of longtext, the prefix of shorttext, the suffix * of shorttext and the common middle. Or nil if there was no match. * @private --]] function _diff_halfMatchI(longtext, shorttext, i) -- Start with a 1/4 length substring at position i as a seed. local seed = strsub(longtext, i, i + floor(#longtext / 4)) local j = 0 -- LUANOTE: do not change to 1, was originally -1 local best_common = '' local best_longtext_a, best_longtext_b, best_shorttext_a, best_shorttext_b while true do j = indexOf(shorttext, seed, j + 1) if (j == nil) then break end local prefixLength = _diff_commonPrefix(strsub(longtext, i), strsub(shorttext, j)) local suffixLength = _diff_commonSuffix(strsub(longtext, 1, i - 1), strsub(shorttext, 1, j - 1)) if #best_common < suffixLength + prefixLength then best_common = strsub(shorttext, j - suffixLength, j - 1) .. strsub(shorttext, j, j + prefixLength - 1) best_longtext_a = strsub(longtext, 1, i - suffixLength - 1) best_longtext_b = strsub(longtext, i + prefixLength) best_shorttext_a = strsub(shorttext, 1, j - suffixLength - 1) best_shorttext_b = strsub(shorttext, j + prefixLength) end end if #best_common * 2 >= #longtext then return {best_longtext_a, best_longtext_b, best_shorttext_a, best_shorttext_b, best_common} else return nil end end --[[ * Do the two texts share a substring which is at least half the length of the * longer text? * @param {string} text1 First string. * @param {string} text2 Second string. * @return {?Array.<string>} Five element Array, containing the prefix of * text1, the suffix of text1, the prefix of text2, the suffix of * text2 and the common middle. Or nil if there was no match. * @private --]] function _diff_halfMatch(text1, text2) if Diff_Timeout <= 0 then -- Don't risk returning a non-optimal diff if we have unlimited time. return nil end local longtext = (#text1 > #text2) and text1 or text2 local shorttext = (#text1 > #text2) and text2 or text1 if (#longtext < 4) or (#shorttext * 2 < #longtext) then return nil -- Pointless. end -- First check if the second quarter is the seed for a half-match. local hm1 = _diff_halfMatchI(longtext, shorttext, ceil(#longtext / 4)) -- Check again based on the third quarter. local hm2 = _diff_halfMatchI(longtext, shorttext, ceil(#longtext / 2)) local hm if not hm1 and not hm2 then return nil elseif not hm2 then hm = hm1 elseif not hm1 then hm = hm2 else -- Both matched. Select the longest. hm = (#hm1[5] > #hm2[5]) and hm1 or hm2 end -- A half-match was found, sort out the return data. local text1_a, text1_b, text2_a, text2_b if (#text1 > #text2) then text1_a, text1_b = hm[1], hm[2] text2_a, text2_b = hm[3], hm[4] else text2_a, text2_b = hm[1], hm[2] text1_a, text1_b = hm[3], hm[4] end local mid_common = hm[5] return text1_a, text1_b, text2_a, text2_b, mid_common end --[[ * Given two strings, compute a score representing whether the internal * boundary falls on logical boundaries. * Scores range from 6 (best) to 0 (worst). * @param {string} one First string. * @param {string} two Second string. * @return {number} The score. * @private --]] function _diff_cleanupSemanticScore(one, two) if (#one == 0) or (#two == 0) then -- Edges are the best. return 6 end -- Each port of this function behaves slightly differently due to -- subtle differences in each language's definition of things like -- 'whitespace'. Since this function's purpose is largely cosmetic, -- the choice has been made to use each language's native features -- rather than force total conformity. local char1 = strsub(one, -1) local char2 = strsub(two, 1, 1) local nonAlphaNumeric1 = strmatch(char1, '%W') local nonAlphaNumeric2 = strmatch(char2, '%W') local whitespace1 = nonAlphaNumeric1 and strmatch(char1, '%s') local whitespace2 = nonAlphaNumeric2 and strmatch(char2, '%s') local lineBreak1 = whitespace1 and strmatch(char1, '%c') local lineBreak2 = whitespace2 and strmatch(char2, '%c') local blankLine1 = lineBreak1 and strmatch(one, '\n\r?\n$') local blankLine2 = lineBreak2 and strmatch(two, '^\r?\n\r?\n') if blankLine1 or blankLine2 then -- Five points for blank lines. return 5 elseif lineBreak1 or lineBreak2 then -- Four points for line breaks. return 4 elseif nonAlphaNumeric1 and not whitespace1 and whitespace2 then -- Three points for end of sentences. return 3 elseif whitespace1 or whitespace2 then -- Two points for whitespace. return 2 elseif nonAlphaNumeric1 or nonAlphaNumeric2 then -- One point for non-alphanumeric. return 1 end return 0 end --[[ * Look for single edits surrounded on both sides by equalities * which can be shifted sideways to align the edit to a word boundary. * e.g: The c<ins>at c</ins>ame. -> The <ins>cat </ins>came. * @param {Array.<Array.<number|string>>} diffs Array of diff tuples. --]] function _diff_cleanupSemanticLossless(diffs) local pointer = 2 -- Intentionally ignore the first and last element (don't need checking). while diffs[pointer + 1] do local prevDiff, nextDiff = diffs[pointer - 1], diffs[pointer + 1] if (prevDiff[1] == DIFF_EQUAL) and (nextDiff[1] == DIFF_EQUAL) then -- This is a single edit surrounded by equalities. local diff = diffs[pointer] local equality1 = prevDiff[2] local edit = diff[2] local equality2 = nextDiff[2] -- First, shift the edit as far left as possible. local commonOffset = _diff_commonSuffix(equality1, edit) if commonOffset > 0 then local commonString = strsub(edit, -commonOffset) equality1 = strsub(equality1, 1, -commonOffset - 1) edit = commonString .. strsub(edit, 1, -commonOffset - 1) equality2 = commonString .. equality2 end -- Second, step character by character right, looking for the best fit. local bestEquality1 = equality1 local bestEdit = edit local bestEquality2 = equality2 local bestScore = _diff_cleanupSemanticScore(equality1, edit) + _diff_cleanupSemanticScore(edit, equality2) while strbyte(edit, 1) == strbyte(equality2, 1) do equality1 = equality1 .. strsub(edit, 1, 1) edit = strsub(edit, 2) .. strsub(equality2, 1, 1) equality2 = strsub(equality2, 2) local score = _diff_cleanupSemanticScore(equality1, edit) + _diff_cleanupSemanticScore(edit, equality2) -- The >= encourages trailing rather than leading whitespace on edits. if score >= bestScore then bestScore = score bestEquality1 = equality1 bestEdit = edit bestEquality2 = equality2 end end if prevDiff[2] ~= bestEquality1 then -- We have an improvement, save it back to the diff. if #bestEquality1 > 0 then diffs[pointer - 1][2] = bestEquality1 else tremove(diffs, pointer - 1) pointer = pointer - 1 end diffs[pointer][2] = bestEdit if #bestEquality2 > 0 then diffs[pointer + 1][2] = bestEquality2 else tremove(diffs, pointer + 1, 1) pointer = pointer - 1 end end end pointer = pointer + 1 end end --[[ * Reorder and merge like edit sections. Merge equalities. * Any edit section can move as long as it doesn't cross an equality. * @param {Array.<Array.<number|string>>} diffs Array of diff tuples. --]] function _diff_cleanupMerge(diffs) diffs[#diffs + 1] = {DIFF_EQUAL, ''} -- Add a dummy entry at the end. local pointer = 1 local count_delete, count_insert = 0, 0 local text_delete, text_insert = '', '' local commonlength while diffs[pointer] do local diff_type = diffs[pointer][1] if diff_type == DIFF_INSERT then count_insert = count_insert + 1 text_insert = text_insert .. diffs[pointer][2] pointer = pointer + 1 elseif diff_type == DIFF_DELETE then count_delete = count_delete + 1 text_delete = text_delete .. diffs[pointer][2] pointer = pointer + 1 elseif diff_type == DIFF_EQUAL then -- Upon reaching an equality, check for prior redundancies. if count_delete + count_insert > 1 then if (count_delete > 0) and (count_insert > 0) then -- Factor out any common prefixies. commonlength = _diff_commonPrefix(text_insert, text_delete) if commonlength > 0 then local back_pointer = pointer - count_delete - count_insert if (back_pointer > 1) and (diffs[back_pointer - 1][1] == DIFF_EQUAL) then diffs[back_pointer - 1][2] = diffs[back_pointer - 1][2] .. strsub(text_insert, 1, commonlength) else tinsert(diffs, 1, {DIFF_EQUAL, strsub(text_insert, 1, commonlength)}) pointer = pointer + 1 end text_insert = strsub(text_insert, commonlength + 1) text_delete = strsub(text_delete, commonlength + 1) end -- Factor out any common suffixies. commonlength = _diff_commonSuffix(text_insert, text_delete) if commonlength ~= 0 then diffs[pointer][2] = strsub(text_insert, -commonlength) .. diffs[pointer][2] text_insert = strsub(text_insert, 1, -commonlength - 1) text_delete = strsub(text_delete, 1, -commonlength - 1) end end -- Delete the offending records and add the merged ones. if count_delete == 0 then tsplice(diffs, pointer - count_insert, count_insert, {DIFF_INSERT, text_insert}) elseif count_insert == 0 then tsplice(diffs, pointer - count_delete, count_delete, {DIFF_DELETE, text_delete}) else tsplice(diffs, pointer - count_delete - count_insert, count_delete + count_insert, {DIFF_DELETE, text_delete}, {DIFF_INSERT, text_insert}) end pointer = pointer - count_delete - count_insert + (count_delete>0 and 1 or 0) + (count_insert>0 and 1 or 0) + 1 elseif (pointer > 1) and (diffs[pointer - 1][1] == DIFF_EQUAL) then -- Merge this equality with the previous one. diffs[pointer - 1][2] = diffs[pointer - 1][2] .. diffs[pointer][2] tremove(diffs, pointer) else pointer = pointer + 1 end count_insert, count_delete = 0, 0 text_delete, text_insert = '', '' end end if diffs[#diffs][2] == '' then diffs[#diffs] = nil -- Remove the dummy entry at the end. end -- Second pass: look for single edits surrounded on both sides by equalities -- which can be shifted sideways to eliminate an equality. -- e.g: A<ins>BA</ins>C -> <ins>AB</ins>AC local changes = false pointer = 2 -- Intentionally ignore the first and last element (don't need checking). while pointer < #diffs do local prevDiff, nextDiff = diffs[pointer - 1], diffs[pointer + 1] if (prevDiff[1] == DIFF_EQUAL) and (nextDiff[1] == DIFF_EQUAL) then -- This is a single edit surrounded by equalities. local diff = diffs[pointer] local currentText = diff[2] local prevText = prevDiff[2] local nextText = nextDiff[2] if strsub(currentText, -#prevText) == prevText then -- Shift the edit over the previous equality. diff[2] = prevText .. strsub(currentText, 1, -#prevText - 1) nextDiff[2] = prevText .. nextDiff[2] tremove(diffs, pointer - 1) changes = true elseif strsub(currentText, 1, #nextText) == nextText then -- Shift the edit over the next equality. prevDiff[2] = prevText .. nextText diff[2] = strsub(currentText, #nextText + 1) .. nextText tremove(diffs, pointer + 1) changes = true end end pointer = pointer + 1 end -- If shifts were made, the diff needs reordering and another shift sweep. if changes then -- LUANOTE: no return value, but necessary to use 'return' to get -- tail calls. return _diff_cleanupMerge(diffs) end end --[[ * loc is a location in text1, compute and return the equivalent location in * text2. * e.g. 'The cat' vs 'The big cat', 1->1, 5->8 * @param {Array.<Array.<number|string>>} diffs Array of diff tuples. * @param {number} loc Location within text1. * @return {number} Location within text2. --]] function _diff_xIndex(diffs, loc) local chars1 = 1 local chars2 = 1 local last_chars1 = 1 local last_chars2 = 1 local x for _x, diff in ipairs(diffs) do x = _x if diff[1] ~= DIFF_INSERT then -- Equality or deletion. chars1 = chars1 + #diff[2] end if diff[1] ~= DIFF_DELETE then -- Equality or insertion. chars2 = chars2 + #diff[2] end if chars1 > loc then -- Overshot the location. break end last_chars1 = chars1 last_chars2 = chars2 end -- Was the location deleted? if diffs[x + 1] and (diffs[x][1] == DIFF_DELETE) then return last_chars2 end -- Add the remaining character length. return last_chars2 + (loc - last_chars1) end --[[ * Compute and return the source text (all equalities and deletions). * @param {Array.<Array.<number|string>>} diffs Array of diff tuples. * @return {string} Source text. --]] function _diff_text1(diffs) local text = {} for x, diff in ipairs(diffs) do if diff[1] ~= DIFF_INSERT then text[#text + 1] = diff[2] end end return tconcat(text) end --[[ * Compute and return the destination text (all equalities and insertions). * @param {Array.<Array.<number|string>>} diffs Array of diff tuples. * @return {string} Destination text. --]] function _diff_text2(diffs) local text = {} for x, diff in ipairs(diffs) do if diff[1] ~= DIFF_DELETE then text[#text + 1] = diff[2] end end return tconcat(text) end --[[ * Crush the diff into an encoded string which describes the operations * required to transform text1 into text2. * E.g. =3\t-2\t+ing -> Keep 3 chars, delete 2 chars, insert 'ing'. * Operations are tab-separated. Inserted text is escaped using %xx notation. * @param {Array.<Array.<number|string>>} diffs Array of diff tuples. * @return {string} Delta text. --]] function _diff_toDelta(diffs) local text = {} for x, diff in ipairs(diffs) do local op, data = diff[1], diff[2] if op == DIFF_INSERT then text[x] = '+' .. gsub(data, percentEncode_pattern, percentEncode_replace) elseif op == DIFF_DELETE then text[x] = '-' .. #data elseif op == DIFF_EQUAL then text[x] = '=' .. #data end end return tconcat(text, '\t') end --[[ * Given the original text1, and an encoded string which describes the * operations required to transform text1 into text2, compute the full diff. * @param {string} text1 Source string for the diff. * @param {string} delta Delta text. * @return {Array.<Array.<number|string>>} Array of diff tuples. * @throws {Errorend If invalid input. --]] function _diff_fromDelta(text1, delta) local diffs = {} local diffsLength = 0 -- Keeping our own length var is faster local pointer = 1 -- Cursor in text1 for token in gmatch(delta, '[^\t]+') do -- Each token begins with a one character parameter which specifies the -- operation of this token (delete, insert, equality). local tokenchar, param = strsub(token, 1, 1), strsub(token, 2) if (tokenchar == '+') then local invalidDecode = false local decoded = gsub(param, '%%(.?.?)', function(c) local n = tonumber(c, 16) if (#c ~= 2) or (n == nil) then invalidDecode = true return '' end return strchar(n) end) if invalidDecode then -- Malformed URI sequence. error('Illegal escape in _diff_fromDelta: ' .. param) end diffsLength = diffsLength + 1 diffs[diffsLength] = {DIFF_INSERT, decoded} elseif (tokenchar == '-') or (tokenchar == '=') then local n = tonumber(param) if (n == nil) or (n < 0) then error('Invalid number in _diff_fromDelta: ' .. param) end local text = strsub(text1, pointer, pointer + n - 1) pointer = pointer + n if (tokenchar == '=') then diffsLength = diffsLength + 1 diffs[diffsLength] = {DIFF_EQUAL, text} else diffsLength = diffsLength + 1 diffs[diffsLength] = {DIFF_DELETE, text} end else error('Invalid diff operation in _diff_fromDelta: ' .. token) end end if (pointer ~= #text1 + 1) then error('Delta length (' .. (pointer - 1) .. ') does not equal source text length (' .. #text1 .. ').') end return diffs end -- --------------------------------------------------------------------------- -- MATCH API -- --------------------------------------------------------------------------- local _match_bitap, _match_alphabet --[[ * Locate the best instance of 'pattern' in 'text' near 'loc'. * @param {string} text The text to search. * @param {string} pattern The pattern to search for. * @param {number} loc The location to search around. * @return {number} Best match index or -1. --]] function match_main(text, pattern, loc) -- Check for null inputs. if text == nil or pattern == nil or loc == nil then error('Null inputs. (match_main)') end if text == pattern then -- Shortcut (potentially not guaranteed by the algorithm) return 1 elseif #text == 0 then -- Nothing to match. return -1 end loc = max(1, min(loc, #text)) if strsub(text, loc, loc + #pattern - 1) == pattern then -- Perfect match at the perfect spot! (Includes case of null pattern) return loc else -- Do a fuzzy compare. return _match_bitap(text, pattern, loc) end end -- --------------------------------------------------------------------------- -- UNOFFICIAL/PRIVATE MATCH FUNCTIONS -- --------------------------------------------------------------------------- --[[ * Initialise the alphabet for the Bitap algorithm. * @param {string} pattern The text to encode. * @return {Object} Hash of character locations. * @private --]] function _match_alphabet(pattern) local s = {} local i = 0 for c in gmatch(pattern, '.') do s[c] = bor(s[c] or 0, lshift(1, #pattern - i - 1)) i = i + 1 end return s end --[[ * Locate the best instance of 'pattern' in 'text' near 'loc' using the * Bitap algorithm. * @param {string} text The text to search. * @param {string} pattern The pattern to search for. * @param {number} loc The location to search around. * @return {number} Best match index or -1. * @private --]] function _match_bitap(text, pattern, loc) if #pattern > Match_MaxBits then error('Pattern too long.') end -- Initialise the alphabet. local s = _match_alphabet(pattern) --[[ * Compute and return the score for a match with e errors and x location. * Accesses loc and pattern through being a closure. * @param {number} e Number of errors in match. * @param {number} x Location of match. * @return {number} Overall score for match (0.0 = good, 1.0 = bad). * @private --]] local function _match_bitapScore(e, x) local accuracy = e / #pattern local proximity = abs(loc - x) if (Match_Distance == 0) then -- Dodge divide by zero error. return (proximity == 0) and 1 or accuracy end return accuracy + (proximity / Match_Distance) end -- Highest score beyond which we give up. local score_threshold = Match_Threshold -- Is there a nearby exact match? (speedup) local best_loc = indexOf(text, pattern, loc) if best_loc then score_threshold = min(_match_bitapScore(0, best_loc), score_threshold) -- LUANOTE: Ideally we'd also check from the other direction, but Lua -- doesn't have an efficent lastIndexOf function. end -- Initialise the bit arrays. local matchmask = lshift(1, #pattern - 1) best_loc = -1 local bin_min, bin_mid local bin_max = #pattern + #text local last_rd for d = 0, #pattern - 1, 1 do -- Scan for the best match; each iteration allows for one more error. -- Run a binary search to determine how far from 'loc' we can stray at this -- error level. bin_min = 0 bin_mid = bin_max while (bin_min < bin_mid) do if (_match_bitapScore(d, loc + bin_mid) <= score_threshold) then bin_min = bin_mid else bin_max = bin_mid end bin_mid = floor(bin_min + (bin_max - bin_min) / 2) end -- Use the result from this iteration as the maximum for the next. bin_max = bin_mid local start = max(1, loc - bin_mid + 1) local finish = min(loc + bin_mid, #text) + #pattern local rd = {} for j = start, finish do rd[j] = 0 end rd[finish + 1] = lshift(1, d) - 1 for j = finish, start, -1 do local charMatch = s[strsub(text, j - 1, j - 1)] or 0 if (d == 0) then -- First pass: exact match. rd[j] = band(bor((rd[j + 1] * 2), 1), charMatch) else -- Subsequent passes: fuzzy match. -- Functions instead of operators make this hella messy. rd[j] = bor( band( bor( lshift(rd[j + 1], 1), 1 ), charMatch ), bor( bor( lshift(bor(last_rd[j + 1], last_rd[j]), 1), 1 ), last_rd[j + 1] ) ) end if (band(rd[j], matchmask) ~= 0) then local score = _match_bitapScore(d, j - 1) -- This match will almost certainly be better than any existing match. -- But check anyway. if (score <= score_threshold) then -- Told you so. score_threshold = score best_loc = j - 1 if (best_loc > loc) then -- When passing loc, don't exceed our current distance from loc. start = max(1, loc * 2 - best_loc) else -- Already passed loc, downhill from here on in. break end end end end -- No hope for a (better) match at greater error levels. if (_match_bitapScore(d + 1, loc) > score_threshold) then break end last_rd = rd end return best_loc end -- ----------------------------------------------------------------------------- -- PATCH API -- ----------------------------------------------------------------------------- local _patch_addContext, _patch_deepCopy, _patch_addPadding, _patch_splitMax, _patch_appendText, _new_patch_obj --[[ * Compute a list of patches to turn text1 into text2. * Use diffs if provided, otherwise compute it ourselves. * There are four ways to call this function, depending on what data is * available to the caller: * Method 1: * a = text1, b = text2 * Method 2: * a = diffs * Method 3 (optimal): * a = text1, b = diffs * Method 4 (deprecated, use method 3): * a = text1, b = text2, c = diffs * * @param {string|Array.<Array.<number|string>>} a text1 (methods 1,3,4) or * Array of diff tuples for text1 to text2 (method 2). * @param {string|Array.<Array.<number|string>>} opt_b text2 (methods 1,4) or * Array of diff tuples for text1 to text2 (method 3) or undefined (method 2). * @param {string|Array.<Array.<number|string>>} opt_c Array of diff tuples for * text1 to text2 (method 4) or undefined (methods 1,2,3). * @return {Array.<_new_patch_obj>} Array of patch objects. --]] function patch_make(a, opt_b, opt_c) local text1, diffs local type_a, type_b, type_c = type(a), type(opt_b), type(opt_c) if (type_a == 'string') and (type_b == 'string') and (type_c == 'nil') then -- Method 1: text1, text2 -- Compute diffs from text1 and text2. text1 = a diffs = diff_main(text1, opt_b, true) if (#diffs > 2) then diff_cleanupSemantic(diffs) diff_cleanupEfficiency(diffs) end elseif (type_a == 'table') and (type_b == 'nil') and (type_c == 'nil') then -- Method 2: diffs -- Compute text1 from diffs. diffs = a text1 = _diff_text1(diffs) elseif (type_a == 'string') and (type_b == 'table') and (type_c == 'nil') then -- Method 3: text1, diffs text1 = a diffs = opt_b elseif (type_a == 'string') and (type_b == 'string') and (type_c == 'table') then -- Method 4: text1, text2, diffs -- text2 is not used. text1 = a diffs = opt_c else error('Unknown call format to patch_make.') end if (diffs[1] == nil) then return {} -- Get rid of the null case. end local patches = {} local patch = _new_patch_obj() local patchDiffLength = 0 -- Keeping our own length var is faster. local char_count1 = 0 -- Number of characters into the text1 string. local char_count2 = 0 -- Number of characters into the text2 string. -- Start with text1 (prepatch_text) and apply the diffs until we arrive at -- text2 (postpatch_text). We recreate the patches one by one to determine -- context info. local prepatch_text, postpatch_text = text1, text1 for x, diff in ipairs(diffs) do local diff_type, diff_text = diff[1], diff[2] if (patchDiffLength == 0) and (diff_type ~= DIFF_EQUAL) then -- A new patch starts here. patch.start1 = char_count1 + 1 patch.start2 = char_count2 + 1 end if (diff_type == DIFF_INSERT) then patchDiffLength = patchDiffLength + 1 patch.diffs[patchDiffLength] = diff patch.length2 = patch.length2 + #diff_text postpatch_text = strsub(postpatch_text, 1, char_count2) .. diff_text .. strsub(postpatch_text, char_count2 + 1) elseif (diff_type == DIFF_DELETE) then patch.length1 = patch.length1 + #diff_text patchDiffLength = patchDiffLength + 1 patch.diffs[patchDiffLength] = diff postpatch_text = strsub(postpatch_text, 1, char_count2) .. strsub(postpatch_text, char_count2 + #diff_text + 1) elseif (diff_type == DIFF_EQUAL) then if (#diff_text <= Patch_Margin * 2) and (patchDiffLength ~= 0) and (#diffs ~= x) then -- Small equality inside a patch. patchDiffLength = patchDiffLength + 1 patch.diffs[patchDiffLength] = diff patch.length1 = patch.length1 + #diff_text patch.length2 = patch.length2 + #diff_text elseif (#diff_text >= Patch_Margin * 2) then -- Time for a new patch. if (patchDiffLength ~= 0) then _patch_addContext(patch, prepatch_text) patches[#patches + 1] = patch patch = _new_patch_obj() patchDiffLength = 0 -- Unlike Unidiff, our patch lists have a rolling context. -- http://code.google.com/p/google-diff-match-patch/wiki/Unidiff -- Update prepatch text & pos to reflect the application of the -- just completed patch. prepatch_text = postpatch_text char_count1 = char_count2 end end end -- Update the current character count. if (diff_type ~= DIFF_INSERT) then char_count1 = char_count1 + #diff_text end if (diff_type ~= DIFF_DELETE) then char_count2 = char_count2 + #diff_text end end -- Pick up the leftover patch if not empty. if (patchDiffLength > 0) then _patch_addContext(patch, prepatch_text) patches[#patches + 1] = patch end return patches end --[[ * Merge a set of patches onto the text. Return a patched text, as well * as a list of true/false values indicating which patches were applied. * @param {Array.<_new_patch_obj>} patches Array of patch objects. * @param {string} text Old text. * @return {Array.<string|Array.<boolean>>} Two return values, the * new text and an array of boolean values. --]] function patch_apply(patches, text) if patches[1] == nil then return text, {} end -- Deep copy the patches so that no changes are made to originals. patches = _patch_deepCopy(patches) local nullPadding = _patch_addPadding(patches) text = nullPadding .. text .. nullPadding _patch_splitMax(patches) -- delta keeps track of the offset between the expected and actual location -- of the previous patch. If there are patches expected at positions 10 and -- 20, but the first patch was found at 12, delta is 2 and the second patch -- has an effective expected position of 22. local delta = 0 local results = {} for x, patch in ipairs(patches) do local expected_loc = patch.start2 + delta local text1 = _diff_text1(patch.diffs) local start_loc local end_loc = -1 if #text1 > Match_MaxBits then -- _patch_splitMax will only provide an oversized pattern in -- the case of a monster delete. start_loc = match_main(text, strsub(text1, 1, Match_MaxBits), expected_loc) if start_loc ~= -1 then end_loc = match_main(text, strsub(text1, -Match_MaxBits), expected_loc + #text1 - Match_MaxBits) if end_loc == -1 or start_loc >= end_loc then -- Can't find valid trailing context. Drop this patch. start_loc = -1 end end else start_loc = match_main(text, text1, expected_loc) end if start_loc == -1 then -- No match found. :( results[x] = false -- Subtract the delta for this failed patch from subsequent patches. delta = delta - patch.length2 - patch.length1 else -- Found a match. :) results[x] = true delta = start_loc - expected_loc local text2 if end_loc == -1 then text2 = strsub(text, start_loc, start_loc + #text1 - 1) else text2 = strsub(text, start_loc, end_loc + Match_MaxBits - 1) end if text1 == text2 then -- Perfect match, just shove the replacement text in. text = strsub(text, 1, start_loc - 1) .. _diff_text2(patch.diffs) .. strsub(text, start_loc + #text1) else -- Imperfect match. Run a diff to get a framework of equivalent -- indices. local diffs = diff_main(text1, text2, false) if (#text1 > Match_MaxBits) and (diff_levenshtein(diffs) / #text1 > Patch_DeleteThreshold) then -- The end points match, but the content is unacceptably bad. results[x] = false else _diff_cleanupSemanticLossless(diffs) local index1 = 1 local index2 for y, mod in ipairs(patch.diffs) do if mod[1] ~= DIFF_EQUAL then index2 = _diff_xIndex(diffs, index1) end if mod[1] == DIFF_INSERT then text = strsub(text, 1, start_loc + index2 - 2) .. mod[2] .. strsub(text, start_loc + index2 - 1) elseif mod[1] == DIFF_DELETE then text = strsub(text, 1, start_loc + index2 - 2) .. strsub(text, start_loc + _diff_xIndex(diffs, index1 + #mod[2] - 1)) end if mod[1] ~= DIFF_DELETE then index1 = index1 + #mod[2] end end end end end end -- Strip the padding off. text = strsub(text, #nullPadding + 1, -#nullPadding - 1) return text, results end --[[ * Take a list of patches and return a textual representation. * @param {Array.<_new_patch_obj>} patches Array of patch objects. * @return {string} Text representation of patches. --]] function patch_toText(patches) local text = {} for x, patch in ipairs(patches) do _patch_appendText(patch, text) end return tconcat(text) end --[[ * Parse a textual representation of patches and return a list of patch objects. * @param {string} textline Text representation of patches. * @return {Array.<_new_patch_obj>} Array of patch objects. * @throws {Error} If invalid input. --]] function patch_fromText(textline) local patches = {} if (#textline == 0) then return patches end local text = {} for line in gmatch(textline, '([^\n]*)') do text[#text + 1] = line end local textPointer = 1 while (textPointer <= #text) do local start1, length1, start2, length2 = strmatch(text[textPointer], '^@@ %-(%d+),?(%d*) %+(%d+),?(%d*) @@$') if (start1 == nil) then error('Invalid patch string: "' .. text[textPointer] .. '"') end local patch = _new_patch_obj() patches[#patches + 1] = patch start1 = tonumber(start1) length1 = tonumber(length1) or 1 if (length1 == 0) then start1 = start1 + 1 end patch.start1 = start1 patch.length1 = length1 start2 = tonumber(start2) length2 = tonumber(length2) or 1 if (length2 == 0) then start2 = start2 + 1 end patch.start2 = start2 patch.length2 = length2 textPointer = textPointer + 1 while true do local line = text[textPointer] if (line == nil) then break end local sign; sign, line = strsub(line, 1, 1), strsub(line, 2) local invalidDecode = false local decoded = gsub(line, '%%(.?.?)', function(c) local n = tonumber(c, 16) if (#c ~= 2) or (n == nil) then invalidDecode = true return '' end return strchar(n) end) if invalidDecode then -- Malformed URI sequence. error('Illegal escape in patch_fromText: ' .. line) end line = decoded if (sign == '-') then -- Deletion. patch.diffs[#patch.diffs + 1] = {DIFF_DELETE, line} elseif (sign == '+') then -- Insertion. patch.diffs[#patch.diffs + 1] = {DIFF_INSERT, line} elseif (sign == ' ') then -- Minor equality. patch.diffs[#patch.diffs + 1] = {DIFF_EQUAL, line} elseif (sign == '@') then -- Start of next patch. break elseif (sign == '') then -- Blank line? Whatever. else -- WTF? error('Invalid patch mode "' .. sign .. '" in: ' .. line) end textPointer = textPointer + 1 end end return patches end -- --------------------------------------------------------------------------- -- UNOFFICIAL/PRIVATE PATCH FUNCTIONS -- --------------------------------------------------------------------------- local patch_meta = { __tostring = function(patch) local buf = {} _patch_appendText(patch, buf) return tconcat(buf) end } --[[ * Class representing one patch operation. * @constructor --]] function _new_patch_obj() return setmetatable({ --[[ @type {Array.<Array.<number|string>>} ]] diffs = {}; --[[ @type {?number} ]] start1 = 1; -- nil; --[[ @type {?number} ]] start2 = 1; -- nil; --[[ @type {number} ]] length1 = 0; --[[ @type {number} ]] length2 = 0; }, patch_meta) end --[[ * Increase the context until it is unique, * but don't let the pattern expand beyond Match_MaxBits. * @param {_new_patch_obj} patch The patch to grow. * @param {string} text Source text. * @private --]] function _patch_addContext(patch, text) if (#text == 0) then return end local pattern = strsub(text, patch.start2, patch.start2 + patch.length1 - 1) local padding = 0 -- LUANOTE: Lua's lack of a lastIndexOf function results in slightly -- different logic here than in other language ports. -- Look for the first two matches of pattern in text. If two are found, -- increase the pattern length. local firstMatch = indexOf(text, pattern) local secondMatch = nil if (firstMatch ~= nil) then secondMatch = indexOf(text, pattern, firstMatch + 1) end while (#pattern == 0 or secondMatch ~= nil) and (#pattern < Match_MaxBits - Patch_Margin - Patch_Margin) do padding = padding + Patch_Margin pattern = strsub(text, max(1, patch.start2 - padding), patch.start2 + patch.length1 - 1 + padding) firstMatch = indexOf(text, pattern) if (firstMatch ~= nil) then secondMatch = indexOf(text, pattern, firstMatch + 1) else secondMatch = nil end end -- Add one chunk for good luck. padding = padding + Patch_Margin -- Add the prefix. local prefix = strsub(text, max(1, patch.start2 - padding), patch.start2 - 1) if (#prefix > 0) then tinsert(patch.diffs, 1, {DIFF_EQUAL, prefix}) end -- Add the suffix. local suffix = strsub(text, patch.start2 + patch.length1, patch.start2 + patch.length1 - 1 + padding) if (#suffix > 0) then patch.diffs[#patch.diffs + 1] = {DIFF_EQUAL, suffix} end -- Roll back the start points. patch.start1 = patch.start1 - #prefix patch.start2 = patch.start2 - #prefix -- Extend the lengths. patch.length1 = patch.length1 + #prefix + #suffix patch.length2 = patch.length2 + #prefix + #suffix end --[[ * Given an array of patches, return another array that is identical. * @param {Array.<_new_patch_obj>} patches Array of patch objects. * @return {Array.<_new_patch_obj>} Array of patch objects. --]] function _patch_deepCopy(patches) local patchesCopy = {} for x, patch in ipairs(patches) do local patchCopy = _new_patch_obj() local diffsCopy = {} for i, diff in ipairs(patch.diffs) do diffsCopy[i] = {diff[1], diff[2]} end patchCopy.diffs = diffsCopy patchCopy.start1 = patch.start1 patchCopy.start2 = patch.start2 patchCopy.length1 = patch.length1 patchCopy.length2 = patch.length2 patchesCopy[x] = patchCopy end return patchesCopy end --[[ * Add some padding on text start and end so that edges can match something. * Intended to be called only from within patch_apply. * @param {Array.<_new_patch_obj>} patches Array of patch objects. * @return {string} The padding string added to each side. --]] function _patch_addPadding(patches) local paddingLength = Patch_Margin local nullPadding = '' for x = 1, paddingLength do nullPadding = nullPadding .. strchar(x) end -- Bump all the patches forward. for x, patch in ipairs(patches) do patch.start1 = patch.start1 + paddingLength patch.start2 = patch.start2 + paddingLength end -- Add some padding on start of first diff. local patch = patches[1] local diffs = patch.diffs local firstDiff = diffs[1] if (firstDiff == nil) or (firstDiff[1] ~= DIFF_EQUAL) then -- Add nullPadding equality. tinsert(diffs, 1, {DIFF_EQUAL, nullPadding}) patch.start1 = patch.start1 - paddingLength -- Should be 0. patch.start2 = patch.start2 - paddingLength -- Should be 0. patch.length1 = patch.length1 + paddingLength patch.length2 = patch.length2 + paddingLength elseif (paddingLength > #firstDiff[2]) then -- Grow first equality. local extraLength = paddingLength - #firstDiff[2] firstDiff[2] = strsub(nullPadding, #firstDiff[2] + 1) .. firstDiff[2] patch.start1 = patch.start1 - extraLength patch.start2 = patch.start2 - extraLength patch.length1 = patch.length1 + extraLength patch.length2 = patch.length2 + extraLength end -- Add some padding on end of last diff. patch = patches[#patches] diffs = patch.diffs local lastDiff = diffs[#diffs] if (lastDiff == nil) or (lastDiff[1] ~= DIFF_EQUAL) then -- Add nullPadding equality. diffs[#diffs + 1] = {DIFF_EQUAL, nullPadding} patch.length1 = patch.length1 + paddingLength patch.length2 = patch.length2 + paddingLength elseif (paddingLength > #lastDiff[2]) then -- Grow last equality. local extraLength = paddingLength - #lastDiff[2] lastDiff[2] = lastDiff[2] .. strsub(nullPadding, 1, extraLength) patch.length1 = patch.length1 + extraLength patch.length2 = patch.length2 + extraLength end return nullPadding end --[[ * Look through the patches and break up any which are longer than the maximum * limit of the match algorithm. * Intended to be called only from within patch_apply. * @param {Array.<_new_patch_obj>} patches Array of patch objects. --]] function _patch_splitMax(patches) local patch_size = Match_MaxBits local x = 1 while true do local patch = patches[x] if patch == nil then return end if patch.length1 > patch_size then local bigpatch = patch -- Remove the big old patch. tremove(patches, x) x = x - 1 local start1 = bigpatch.start1 local start2 = bigpatch.start2 local precontext = '' while bigpatch.diffs[1] do -- Create one of several smaller patches. local patch = _new_patch_obj() local empty = true patch.start1 = start1 - #precontext patch.start2 = start2 - #precontext if precontext ~= '' then patch.length1, patch.length2 = #precontext, #precontext patch.diffs[#patch.diffs + 1] = {DIFF_EQUAL, precontext} end while bigpatch.diffs[1] and (patch.length1 < patch_size-Patch_Margin) do local diff_type = bigpatch.diffs[1][1] local diff_text = bigpatch.diffs[1][2] if (diff_type == DIFF_INSERT) then -- Insertions are harmless. patch.length2 = patch.length2 + #diff_text start2 = start2 + #diff_text patch.diffs[#(patch.diffs) + 1] = bigpatch.diffs[1] tremove(bigpatch.diffs, 1) empty = false elseif (diff_type == DIFF_DELETE) and (#patch.diffs == 1) and (patch.diffs[1][1] == DIFF_EQUAL) and (#diff_text > 2 * patch_size) then -- This is a large deletion. Let it pass in one chunk. patch.length1 = patch.length1 + #diff_text start1 = start1 + #diff_text empty = false patch.diffs[#patch.diffs + 1] = {diff_type, diff_text} tremove(bigpatch.diffs, 1) else -- Deletion or equality. -- Only take as much as we can stomach. diff_text = strsub(diff_text, 1, patch_size - patch.length1 - Patch_Margin) patch.length1 = patch.length1 + #diff_text start1 = start1 + #diff_text if (diff_type == DIFF_EQUAL) then patch.length2 = patch.length2 + #diff_text start2 = start2 + #diff_text else empty = false end patch.diffs[#patch.diffs + 1] = {diff_type, diff_text} if (diff_text == bigpatch.diffs[1][2]) then tremove(bigpatch.diffs, 1) else bigpatch.diffs[1][2] = strsub(bigpatch.diffs[1][2], #diff_text + 1) end end end -- Compute the head context for the next patch. precontext = _diff_text2(patch.diffs) precontext = strsub(precontext, -Patch_Margin) -- Append the end context for this patch. local postcontext = strsub(_diff_text1(bigpatch.diffs), 1, Patch_Margin) if postcontext ~= '' then patch.length1 = patch.length1 + #postcontext patch.length2 = patch.length2 + #postcontext if patch.diffs[1] and (patch.diffs[#patch.diffs][1] == DIFF_EQUAL) then patch.diffs[#patch.diffs][2] = patch.diffs[#patch.diffs][2] .. postcontext else patch.diffs[#patch.diffs + 1] = {DIFF_EQUAL, postcontext} end end if not empty then x = x + 1 tinsert(patches, x, patch) end end end x = x + 1 end end --[[ * Emulate GNU diff's format. * Header: @@ -382,8 +481,9 @@ * @return {string} The GNU diff string. --]] function _patch_appendText(patch, text) local coords1, coords2 local length1, length2 = patch.length1, patch.length2 local start1, start2 = patch.start1, patch.start2 local diffs = patch.diffs if length1 == 1 then coords1 = start1 else coords1 = ((length1 == 0) and (start1 - 1) or start1) .. ',' .. length1 end if length2 == 1 then coords2 = start2 else coords2 = ((length2 == 0) and (start2 - 1) or start2) .. ',' .. length2 end text[#text + 1] = '@@ -' .. coords1 .. ' +' .. coords2 .. ' @@\n' local op -- Escape the body of the patch with %xx notation. for x, diff in ipairs(patch.diffs) do local diff_type = diff[1] if diff_type == DIFF_INSERT then op = '+' elseif diff_type == DIFF_DELETE then op = '-' elseif diff_type == DIFF_EQUAL then op = ' ' end text[#text + 1] = op .. gsub(diffs[x][2], percentEncode_pattern, percentEncode_replace) .. '\n' end return text end -- Expose the API local _M = {} _M.DIFF_DELETE = DIFF_DELETE _M.DIFF_INSERT = DIFF_INSERT _M.DIFF_EQUAL = DIFF_EQUAL _M.diff_main = diff_main _M.diff_cleanupSemantic = diff_cleanupSemantic _M.diff_cleanupEfficiency = diff_cleanupEfficiency _M.diff_levenshtein = diff_levenshtein _M.diff_prettyHtml = diff_prettyHtml _M.match_main = match_main _M.patch_make = patch_make _M.patch_toText = patch_toText _M.patch_fromText = patch_fromText _M.patch_apply = patch_apply -- Expose some non-API functions as well, for testing purposes etc. _M.diff_commonPrefix = _diff_commonPrefix _M.diff_commonSuffix = _diff_commonSuffix _M.diff_commonOverlap = _diff_commonOverlap _M.diff_halfMatch = _diff_halfMatch _M.diff_bisect = _diff_bisect _M.diff_cleanupMerge = _diff_cleanupMerge _M.diff_cleanupSemanticLossless = _diff_cleanupSemanticLossless _M.diff_text1 = _diff_text1 _M.diff_text2 = _diff_text2 _M.diff_toDelta = _diff_toDelta _M.diff_fromDelta = _diff_fromDelta _M.diff_xIndex = _diff_xIndex _M.match_alphabet = _match_alphabet _M.match_bitap = _match_bitap _M.new_patch_obj = _new_patch_obj _M.patch_addContext = _patch_addContext _M.patch_splitMax = _patch_splitMax _M.patch_addPadding = _patch_addPadding _M.settings = settings return _M
apache-2.0
dickeyf/darkstar
scripts/zones/RuAun_Gardens/npcs/HomePoint#3.lua
27
1266
----------------------------------- -- Area: RuAun_Gardens -- NPC: HomePoint#3 -- @pos -312 -42 -422 130 ----------------------------------- package.loaded["scripts/zones/RuAun_Gardens/TextIDs"] = nil; require("scripts/globals/settings"); require("scripts/zones/RuAun_Gardens/TextIDs"); require("scripts/globals/homepoint"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) homepointMenu( player, 0x21fe, 61); 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 == 0x21fe) then if (option == 1) then player:setHomePoint(); player:messageSpecial(HOMEPOINT_SET); else hpTeleport( player, option); end end end;
gpl-3.0
iskygame/skynet
lualib/skynet/manager.lua
72
1923
local skynet = require "skynet" local c = require "skynet.core" function skynet.launch(...) local addr = c.command("LAUNCH", table.concat({...}," ")) if addr then return tonumber("0x" .. string.sub(addr , 2)) end end function skynet.kill(name) if type(name) == "number" then skynet.send(".launcher","lua","REMOVE",name, true) name = skynet.address(name) end c.command("KILL",name) end function skynet.abort() c.command("ABORT") end local function globalname(name, handle) local c = string.sub(name,1,1) assert(c ~= ':') if c == '.' then return false end assert(#name <= 16) -- GLOBALNAME_LENGTH is 16, defined in skynet_harbor.h assert(tonumber(name) == nil) -- global name can't be number local harbor = require "skynet.harbor" harbor.globalname(name, handle) return true end function skynet.register(name) if not globalname(name) then c.command("REG", name) end end function skynet.name(name, handle) if not globalname(name, handle) then c.command("NAME", name .. " " .. skynet.address(handle)) end end local dispatch_message = skynet.dispatch_message function skynet.forward_type(map, start_func) c.callback(function(ptype, msg, sz, ...) local prototype = map[ptype] if prototype then dispatch_message(prototype, msg, sz, ...) else dispatch_message(ptype, msg, sz, ...) c.trash(msg, sz) end end, true) skynet.timeout(0, function() skynet.init_service(start_func) end) end function skynet.filter(f ,start_func) c.callback(function(...) dispatch_message(f(...)) end) skynet.timeout(0, function() skynet.init_service(start_func) end) end function skynet.monitor(service, query) local monitor if query then monitor = skynet.queryservice(true, service) else monitor = skynet.uniqueservice(true, service) end assert(monitor, "Monitor launch failed") c.command("MONITOR", string.format(":%08x", monitor)) return monitor end return skynet
mit
Turttle/darkstar
scripts/zones/RuLude_Gardens/npcs/Dugga.lua
34
1074
---------------------------------- -- Area: Ru'Lude Gardens -- NPC: Dugga -- Type: Item Deliverer -- @zone: 243 -- @pos -55.429 5.999 1.27 -- ----------------------------------- package.loaded["scripts/zones/RuLude_Gardens/TextIDs"] = nil; require("scripts/zones/RuLude_Gardens/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc, ITEM_DELIVERY_DIALOG); player:openSendBox(); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
SalvationDevelopment/Salvation-Scripts-TCG
c100000532.lua
2
1721
--¢å¢é¢ô¢ó¢ý¢ú¢í¢ö ¢à¢ñ¢ü¢ü function c100000532.initial_effect(c) --special summon local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_SPECIAL_SUMMON) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetTarget(c100000532.target) e1:SetOperation(c100000532.operation) c:RegisterEffect(e1) end function c100000532.filter(c,e,tp) return (c:GetCode()==100000533 or c:GetCode()==100000534 or c:GetCode()==100000537 or c:GetCode()==100000538) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function c100000532.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingMatchingCard(c100000532.filter,tp,LOCATION_HAND,0,1,nil,e,tp) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_HAND) end function c100000532.operation(e,tp,eg,ep,ev,re,r,rp) local ft=Duel.GetLocationCount(tp,LOCATION_MZONE) if ft<=0 then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectMatchingCard(tp,c100000532.filter,tp,LOCATION_HAND,0,1,ft,nil,e,tp) if g:GetCount()>0 then local fid=e:GetHandler():GetFieldID() local tc=g:GetFirst() while tc do Duel.SpecialSummonStep(tc,0,tp,tp,false,false,POS_FACEUP) local e2=Effect.CreateEffect(e:GetHandler()) e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS) e2:SetCode(EVENT_PHASE+PHASE_END) e2:SetCountLimit(1) e2:SetRange(LOCATION_MZONE) e2:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END) e2:SetOperation(c100000532.retop) tc:RegisterEffect(e2) tc=g:GetNext() end Duel.SpecialSummonComplete() end end function c100000532.retop(e,tp,eg,ep,ev,re,r,rp) Duel.SendtoDeck(e:GetHandler(),nil,0,REASON_EFFECT) end
gpl-2.0
SalvationDevelopment/Salvation-Scripts-TCG
c76473843.lua
2
2030
--マジェスティックP function c76473843.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) c:RegisterEffect(e1) --atk/def local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_FIELD) e2:SetCode(EFFECT_UPDATE_ATTACK) e2:SetRange(LOCATION_FZONE) e2:SetTargetRange(LOCATION_MZONE,LOCATION_MZONE) e2:SetTarget(aux.TargetBoolFunction(Card.IsSetCard,0xd0)) e2:SetValue(300) c:RegisterEffect(e2) local e3=e2:Clone() e3:SetCode(EFFECT_UPDATE_DEFENSE) c:RegisterEffect(e3) --spsummon local e4=Effect.CreateEffect(c) e4:SetDescription(aux.Stringid(76473843,0)) e4:SetCategory(CATEGORY_SPECIAL_SUMMON) e4:SetType(EFFECT_TYPE_IGNITION) e4:SetRange(LOCATION_FZONE) e4:SetCountLimit(1,76473843) e4:SetCost(c76473843.spcost) e4:SetTarget(c76473843.sptg) e4:SetOperation(c76473843.spop) c:RegisterEffect(e4) end function c76473843.cfilter(c) return c:IsRace(RACE_SPELLCASTER) and c:IsAttribute(ATTRIBUTE_WIND) end function c76473843.spcost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.CheckReleaseGroup(tp,c76473843.cfilter,1,nil) end local g=Duel.SelectReleaseGroup(tp,c76473843.cfilter,1,1,nil) Duel.Release(g,REASON_COST) end function c76473843.sptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>-1 and Duel.IsExistingMatchingCard(c76473843.spfilter,tp,LOCATION_DECK,0,1,nil,e,tp) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK) end function c76473843.spfilter(c,e,tp) return c:IsSetCard(0xd0) and c:IsLevelBelow(4) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function c76473843.spop(e,tp,eg,ep,ev,re,r,rp) if not e:GetHandler():IsRelateToEffect(e) or Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectMatchingCard(tp,c76473843.spfilter,tp,LOCATION_DECK,0,1,1,nil,e,tp) if g:GetCount()>0 then Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP) end end
gpl-2.0
SalvationDevelopment/Salvation-Scripts-TCG
c100213008.lua
2
1792
--失楽園 --Fallen Paradise --Scripted by Eerie Code function c100213008.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) c:RegisterEffect(e1) --Untargetable local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_FIELD) e2:SetCode(EFFECT_CANNOT_BE_EFFECT_TARGET) e2:SetRange(LOCATION_FZONE) e2:SetTarget(c100213008.immtg) e2:SetValue(aux.tgoval) e2:SetTargetRange(LOCATION_MZONE,0) c:RegisterEffect(e2) --Indes local e3=e2:Clone() e3:SetCode(EFFECT_INDESTRUCTABLE_EFFECT) e3:SetValue(c100213008.tgvalue) c:RegisterEffect(e3) --Draw local e4=Effect.CreateEffect(c) e4:SetCategory(CATEGORY_DRAW) e4:SetType(EFFECT_TYPE_IGNITION) e4:SetRange(LOCATION_FZONE) e4:SetProperty(EFFECT_FLAG_PLAYER_TARGET) e4:SetCountLimit(1,100213008) e4:SetCondition(c100213008.drcon) e4:SetTarget(c100213008.drtg) e4:SetOperation(c100213008.drop) c:RegisterEffect(e4) end function c100213008.immtg(e,c) return c:IsCode(6007213,32491822,69890967,43378048) end function c100213008.tgvalue(e,re,rp) return rp~=e:GetHandlerPlayer() end function c100213008.drcfilter(c) return c:IsFaceup() and c:IsCode(6007213,32491822,69890967,43378048) end function c100213008.drcon(e,tp,eg,ep,ev,re,r,rp) return Duel.IsExistingMatchingCard(c100213008.drcfilter,tp,LOCATION_MZONE,0,1,nil) end function c100213008.drtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsPlayerCanDraw(tp,2) end Duel.SetTargetPlayer(tp) Duel.SetTargetParam(2) Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,2) end function c100213008.drop(e,tp,eg,ep,ev,re,r,rp) if not e:GetHandler():IsRelateToEffect(e) then return end local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM) Duel.Draw(p,d,REASON_EFFECT) end
gpl-2.0
kidanger/danimate
danimate/Sprite.lua
1
4070
local drystal = require 'drystal' local Animation = require 'danimate.Animation' local SpritePart = require 'danimate.SpritePart' local Sprite = { x=0, y=0, w=0, h=0, dir=1, } Sprite.__index = Sprite function Sprite.new(x, y, w, h) local s = setmetatable({}, Sprite) s.x = x s.y = y s.w = w s.h = h s.parts = {} s.animations = {} s.indexes = {} return s end function Sprite:add_part(name, part, swapwith) part.name = name part.swapwith = swapwith self.parts[#self.parts + 1] = part self.parts[name] = part return self end function Sprite:add_parts(parts) for _, part in ipairs(parts) do self:add_part(part.name, SpritePart.new(part.sprite), part.swapwith) end end function Sprite:add_animation(animation) table.insert(self.animations, animation) self.indexes[animation.name] = #self.animations return self end function Sprite:add_animations(animations) for _, anim in ipairs(animations) do local a = Animation.new_from_table(anim) self:add_animation(a) end end function Sprite:set_animation(name, after) local index = self.indexes[name] if self.animation then self.animation:stop() else for _, p in ipairs(self.parts) do local key = self.animations[index][1].key[p.name] p.angle = key.angle p.x = key.x p.y = key.y end end self.animation = self.animations[index] self.animation:prepare(self.parts) self.animation.before_keyframe = function(key) local keyframe = key.key for _, p in ipairs(self.parts) do local angle_dest = keyframe[p.name].angle while p.angle < angle_dest - math.pi do p.angle = p.angle + math.pi * 2 end while p.angle > angle_dest + math.pi do p.angle = p.angle - math.pi * 2 end end end self.animation.after = function() if after then self:set_animation(after) end end self:start_animation() end function Sprite:stop_animation() self.animation:stop() end function Sprite:start_animation() self.animation:start() end function Sprite:update(dt) if self.animation then self.animation:update(dt) end end function Sprite:set_dir(dir) if self.dir ~= dir then self.dir = dir for _, p in ipairs(self.parts) do if p.swapwith and self.parts[p.swapwith] then p.futuresprite = self.parts[p.swapwith].sprite else p.futuresprite = p.sprite end end for _, p in ipairs(self.parts) do p.sprite = p.futuresprite p.futuresprite = nil end end end function Sprite:draw() for _, p in ipairs(self.parts) do if self.dir > 0 then p:draw(self.x, self.y) elseif self.dir < 0 then p:draw_flipped(self.x, self.y, self.w) end end end function Sprite:draw2() if not self.animation then return end local dx, dy = self.x, self.y for _, p in ipairs(self.parts) do local p1 = {x=p.x, y=p.y} local p2 = { x=p.x + math.cos(p.angle) * p.dist, y=p.y + math.sin(p.angle) * p.dist, } local k = self.animation.keyframe.key[p.name] or {x=0,y=0,angle=0} local p1b = {x=k.x, y=k.y} local p2b = { x=k.x + math.cos(k.angle) * p.dist, y=k.y + math.sin(k.angle) * p.dist, } local function isinside(point) return point_hovered(dx + point.x, dy + point.y, p.radius * 1.5) end local inside = isinside(p1) or isinside(p2) or isinside(p1b) or isinside(p2b) if inside then local function printpoint(pp, factor) --local mode = point_hovered(self.x + pp.x, self.y + pp.y, p.radius) and 'fill' or 'line' --love.graphics.circle(mode, pp.x, pp.y, p.radius * factor) if point_hovered(self.x + pp.x, self.y + pp.y, p.radius) then drystal.draw_circle(dx + pp.x, dy + pp.y, p.radius * factor) end drystal.draw_circle(dx + pp.x, dy + pp.y, p.radius * factor) end drystal.set_color '#3F3' drystal.set_color(50, 255, 50) printpoint(p1b, 1) printpoint(p2b, 1) drystal.set_color '#050' printpoint(p1, 0.5) printpoint(p2, 0.5) end end local mx, my = mousepos() if mx >= self.x and mx <= self.x + self.w and my >= self.y and my <= self.y + self.h then drystal.set_color '#777' drystal.draw_square(dx, dy, self.w, self.h) end end return Sprite
mit
Turttle/darkstar
scripts/zones/King_Ranperres_Tomb/npcs/_5a0.lua
17
2401
----------------------------------- -- Area: King Ranperre's Tomb -- DOOR: _5a0 (Heavy Stone Door) -- @pos -39.000 4.823 20.000 190 ----------------------------------- package.loaded["scripts/zones/King_Ranperres_Tomb/TextIDs"] = nil; ----------------------------------- require("scripts/globals/missions"); require("scripts/zones/King_Ranperres_Tomb/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local currentMission = player:getCurrentMission(SANDORIA); local MissionStatus = player:getVar("MissionStatus"); if (currentMission == RANPERRE_S_FINAL_REST and MissionStatus == 1) then if (GetMobAction(17555898) == 0 and GetMobAction(17555899) == 0 and GetMobAction(17555900) == 0) then if (player:getVar("Mission6-2MobKilled") == 1) then player:setVar("Mission6-2MobKilled",0); player:setVar("MissionStatus",2); else SpawnMob(17555898):updateClaim(player); SpawnMob(17555899):updateClaim(player); SpawnMob(17555900):updateClaim(player); end end elseif (currentMission == RANPERRE_S_FINAL_REST and MissionStatus == 2) then player:startEvent(0x0006); elseif (currentMission == RANPERRE_S_FINAL_REST and MissionStatus == 3) then player:startEvent(0x0007); elseif (currentMission == RANPERRE_S_FINAL_REST and MissionStatus == 8) then player:startEvent(0x0005); elseif (currentMission == THE_HEIR_TO_THE_LIGHT and MissionStatus == 6) then player:startEvent(0x000e); else player:messageSpecial(HEAVY_DOOR); 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 == 0x0005) then player:setVar("MissionStatus",9); elseif (csid == 0x000e) then player:setVar("MissionStatus",7); -- at this point 3 optional cs are available and open until watched (add 3 var to char?) end end;
gpl-3.0
SalvationDevelopment/Salvation-Scripts-TCG
c11439455.lua
2
2686
--月光蒼猫 function c11439455.initial_effect(c) --atk up local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(11439455,0)) e1:SetCategory(CATEGORY_ATKCHANGE) e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e1:SetCode(EVENT_SPSUMMON_SUCCESS) e1:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DELAY+EFFECT_FLAG_DAMAGE_STEP) e1:SetCountLimit(1,11439455) e1:SetTarget(c11439455.atktg) e1:SetOperation(c11439455.atkop) c:RegisterEffect(e1) --Special Summon local e3=Effect.CreateEffect(c) e3:SetDescription(aux.Stringid(11439455,1)) e3:SetCategory(CATEGORY_SPECIAL_SUMMON) e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e3:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DELAY) e3:SetCode(EVENT_DESTROYED) e3:SetCondition(c11439455.spcon) e3:SetTarget(c11439455.sptg) e3:SetOperation(c11439455.spop) c:RegisterEffect(e3) end function c11439455.atkfilter(c) return c:IsFaceup() and c:IsSetCard(0xdf) and not c:IsCode(11439455) end function c11439455.atktg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(tp) and c11439455.atkfilter(chkc) end if chk==0 then return Duel.IsExistingTarget(c11439455.atkfilter,tp,LOCATION_MZONE,0,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP) local g=Duel.SelectTarget(tp,c11439455.atkfilter,tp,LOCATION_MZONE,0,1,1,nil) Duel.SetOperationInfo(0,CATEGORY_ATKCHANGE,g,1,0,0) end function c11439455.atkop(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsFaceup() and tc:IsRelateToEffect(e) then local e2=Effect.CreateEffect(e:GetHandler()) e2:SetType(EFFECT_TYPE_SINGLE) e2:SetCode(EFFECT_SET_ATTACK_FINAL) e2:SetValue(tc:GetBaseAttack()*2) e2:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END) tc:RegisterEffect(e2) end end function c11439455.spcon(e,tp,eg,ep,ev,re,r,rp) return bit.band(r,REASON_EFFECT+REASON_BATTLE)~=0 and e:GetHandler():IsPreviousLocation(LOCATION_ONFIELD) end function c11439455.spfilter(c,e,tp) return c:IsSetCard(0xdf) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function c11439455.sptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingMatchingCard(c11439455.spfilter,tp,LOCATION_DECK,0,1,nil,e,tp) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK) end function c11439455.spop(e,tp,eg,ep,ev,re,r,rp) if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectMatchingCard(tp,c11439455.spfilter,tp,LOCATION_DECK,0,1,1,nil,e,tp) if g:GetCount()>0 then Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP) end end
gpl-2.0
Turttle/darkstar
scripts/zones/Oldton_Movalpolos/TextIDs.lua
7
1146
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 6379; -- You cannot obtain the item <item>. Come back after sorting your inventory. ITEM_OBTAINED = 6383; -- Obtained: <item>. GIL_OBTAINED = 6384; -- Obtained <number> gil. KEYITEM_OBTAINED = 6386; -- Obtained key item: <keyitem>. FISHING_MESSAGE_OFFSET = 7559; -- You can't fish here. -- Mining MINING_IS_POSSIBLE_HERE = 7685; -- Mining is possible here if you have -- Treasure Coffer/Chest Dialog CHEST_UNLOCKED = 7732; -- You unlock the chest! CHEST_FAIL = 7733; -- Fails to open the chest. CHEST_TRAP = 7734; -- The chest was trapped! CHEST_WEAK = 7735; -- You cannot open the chest when you are in a weakened state. CHEST_MIMIC = 7736; -- The chest was a mimic! CHEST_MOOGLE = 7737; -- You cannot open the chest while participating in the moogle event. CHEST_ILLUSION = 7738; -- The chest was but an illusion... CHEST_LOCKED = 7739; -- The chest appears to be locked. -- NPCs RAKOROK_DIALOGUE = 7709; -- Nsy pipul. Gattohre! I bisynw! -- conquest Base CONQUEST_BASE = 7040; -- Tallying conquest results...
gpl-3.0
SalvationDevelopment/Salvation-Scripts-TCG
c43642620.lua
9
1349
--マンモス・ゾンビ function c43642620.initial_effect(c) --self destroy local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e1:SetRange(LOCATION_MZONE) e1:SetCode(EFFECT_SELF_DESTROY) e1:SetCondition(c43642620.sdcon) c:RegisterEffect(e1) --damage local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(43642620,0)) e2:SetCategory(CATEGORY_DAMAGE) e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F) e2:SetCode(EVENT_LEAVE_FIELD) e2:SetCondition(c43642620.dmcon) e2:SetTarget(c43642620.dmtg) e2:SetOperation(c43642620.dmop) c:RegisterEffect(e2) end function c43642620.sdcon(e) return not Duel.IsExistingMatchingCard(Card.IsRace,e:GetHandlerPlayer(),LOCATION_GRAVE,0,1,nil,RACE_ZOMBIE) end function c43642620.dmcon(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() return c:IsReason(REASON_DESTROY) and c:IsPreviousPosition(POS_FACEUP) end function c43642620.dmtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end local c=e:GetHandler() Duel.SetTargetPlayer(c:GetPreviousControler()) Duel.SetTargetParam(1900) Duel.SetOperationInfo(0,CATEGORY_DAMAGE,nil,0,c:GetPreviousControler(),1900) end function c43642620.dmop(e,tp,eg,ep,ev,re,r,rp) local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM) Duel.Damage(p,d,REASON_EFFECT) end
gpl-2.0
dickeyf/darkstar
scripts/zones/LaLoff_Amphitheater/npcs/qm2.lua
13
2226
----------------------------------- -- Area: LaLoff_Amphitheater -- NPC: Shimmering Circle (BCNM Exits) ------------------------------------- package.loaded["scripts/zones/LaLoff_Amphitheater/TextIDs"] = nil; ------------------------------------- require("scripts/globals/bcnm"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/globals/missions"); require("scripts/zones/LaLoff_Amphitheater/TextIDs"); ---- 0: ---- 1: ---- 2: ---- 3: ---- 4: ---- 5: ---- 6: ---- 7: ---- 8: ---- 9: -- Death cutscenes: -- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,0,0); -- hume -- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,1,0); -- taru -- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,2,0); -- mithra -- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,3,0); -- elvaan -- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,4,0); -- galka -- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,5,0); -- divine might -- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,6,0); -- skip ending cs ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (TradeBCNM(player,player:getZoneID(),trade,npc)) then return; end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (EventTriggerBCNM(player,npc)) then return; end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("onUpdate CSID: %u",csid); -- printf("onUpdate RESULT: %u",option); if (EventUpdateBCNM(player,csid,option)) then return; end end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) --printf("onFinish CSID: %u",csid); --printf("onFinish RESULT: %u",option); if (EventFinishBCNM(player,csid,option)) then return; end end;
gpl-3.0
Turttle/darkstar
scripts/globals/items/salty_bretzel.lua
35
1296
----------------------------------------- -- ID: 5182 -- Item: salty_bretzel -- Food Effect: 5Min, All Races ----------------------------------------- -- Magic % 8 -- Magic Cap 60 -- Vitality 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,300,5182); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_FOOD_MPP, 8); target:addMod(MOD_FOOD_MP_CAP, 60); target:addMod(MOD_VIT, 2); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_FOOD_MPP, 8); target:delMod(MOD_FOOD_MP_CAP, 60); target:delMod(MOD_VIT, 2); end;
gpl-3.0
Turttle/darkstar
scripts/zones/Windurst_Waters_[S]/npcs/Ranpi-Monpi.lua
38
1048
----------------------------------- -- Area: Windurst Waters (S) -- NPC: Ranpi-Monpi -- Type: Standard NPC -- @zone: 94 -- @pos -115.452 -3 43.389 -- -- 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(0x0075); 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
dickeyf/darkstar
scripts/globals/items/roll_of_sylvan_excursion.lua
18
1574
----------------------------------------- -- ID: 5551 -- Item: Roll of Sylvan Excursion -- Food Effect: 4 Hrs, All Races ----------------------------------------- -- TODO: Group Effect -- HP +10 -- MP +3% Cap 15 -- Intelligence +3 -- HP Recovered while healing +2 -- MP Recovered while healing +5 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) result = 0 if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,14400,5551); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_FOOD_MPP, 3); target:addMod(MOD_FOOD_MP_CAP, 15); target:addMod(MOD_HP, 10); target:addMod(MOD_INT, 3); target:addMod(MOD_HPHEAL, 2); target:addMod(MOD_MPHEAL, 5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_FOOD_MPP, 3); target:delMod(MOD_FOOD_MP_CAP, 15); target:delMod(MOD_HP, 10); target:delMod(MOD_INT, 3); target:delMod(MOD_HPHEAL, 2); target:delMod(MOD_MPHEAL, 5); end;
gpl-3.0
dickeyf/darkstar
scripts/globals/items/bunch_of_wild_pamamas.lua
3
2389
----------------------------------------- -- ID: 4596 -- Item: Bunch of Wild Pamamas -- Food Effect: 30Min, All Races ----------------------------------------- -- Strength -3 -- Intelligence 1 -- Additional Effect with Opo-Opo Crown -- HP 50 -- MP 50 -- CHR 14 -- Additional Effect with Kinkobo or -- Primate Staff -- DELAY -90 -- ACC 10 -- Additional Effect with Primate Staff +1 -- DELAY -80 -- ACC 12 ----------------------------------------- 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,PamamasEquip(target),0,1800,4596); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) local power = effect:getPower(); if (power == 1 or power == 4 or power == 5) then target:addMod(MOD_HP, 50); target:addMod(MOD_MP, 50); target:addMod(MOD_AGI, -3); target:addMod(MOD_CHR, 14); end if (power == 2 or power == 4) then target:addMod(MOD_DELAY, -90); target:addMod(MOD_ACC, 10); end if (power == 3 or power == 5) then target:addMod(MOD_DELAY, -80); target:addMod(MOD_ACC, 12); end target:addMod(MOD_STR, -3); target:addMod(MOD_INT, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) local power = effect:getPower(); if (power == 1 or power == 4 or power == 5) then target:delMod(MOD_HP, 50); target:delMod(MOD_MP, 50); target:delMod(MOD_AGI, -3); target:delMod(MOD_CHR, 14); end if (power == 2 or power == 4) then target:delMod(MOD_DELAY, -90); target:delMod(MOD_ACC, 10); end if (power == 3 or power == 5) then target:delMod(MOD_DELAY, -80); target:delMod(MOD_ACC, 12); end target:delMod(MOD_STR, -3); target:delMod(MOD_INT, 1); end;
gpl-3.0
Turttle/darkstar
scripts/zones/The_Colosseum/Zone.lua
36
1116
----------------------------------- -- -- Zone: The_Colosseum -- ----------------------------------- require("scripts/globals/settings"); package.loaded["scripts/zones/The_Colosseum/TextIDs"] = nil; require("scripts/zones/The_Colosseum/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) cs = -1; 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
Turttle/darkstar
scripts/zones/Sea_Serpent_Grotto/npcs/Grounds_Tome.lua
34
1151
----------------------------------- -- Area: Sea Serpent Grotto -- NPC: Grounds Tome ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/groundsofvalor"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) startGov(GOV_EVENT_SEA_SERPENT_GROTTO,player); end; ----------------------------------- -- onEventSelection ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); updateGov(player,csid,option,804,805,806,807,808,809,810,811,0,0); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); finishGov(player,csid,option,804,805,806,807,808,809,810,811,0,0,GOV_MSG_SEA_SERPENT_GROTTO); end;
gpl-3.0
Turttle/darkstar
scripts/zones/Southern_San_dOria/npcs/Glenne.lua
13
3800
------------------------------------- -- Area: Southern San d'Oria -- NPC: Glenne -- Starts and Finishes Quest: A Sentry's Peril -- @zone 230 -- @pos -122 -2 15 ------------------------------------- package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/zones/Southern_San_dOria/TextIDs"); require("scripts/globals/pathfind"); local path = { -121.512833, -2.000000, 14.492509, -122.600044, -2.000000, 14.535807, -123.697128, -2.000000, 14.615446, -124.696846, -2.000000, 14.707844, -123.606018, -2.000000, 14.601295, -124.720863, -2.000000, 14.709210, -123.677681, -2.000000, 14.608237, -124.752579, -2.000000, 14.712106, -123.669525, -2.000000, 14.607473, -124.788277, -2.000000, 14.715488, -123.792847, -2.000000, 14.619405, -124.871826, -2.000000, 14.723736 }; function onSpawn(npc) npc:initNpcAi(); npc:setPos(pathfind.first(path)); onPath(npc); end; function onPath(npc) pathfind.patrol(npc, path); end; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == QUEST_ACCEPTED) then count = trade:getItemCount(); MagicFlyer = trade:hasItemQty(532,1); if (MagicFlyer == true and count == 1) then player:messageSpecial(FLYER_REFUSED); end elseif (player:getQuestStatus(SANDORIA,A_SENTRY_S_PERIL) == QUEST_ACCEPTED) then if (trade:hasItemQty(601,1) and trade:getItemCount() == 1) then player:startEvent(0x0201); npc:wait(-1); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) aSentrysPeril = player:getQuestStatus(SANDORIA,A_SENTRY_S_PERIL); npc:wait(-1); if (aSentrysPeril == QUEST_AVAILABLE) then player:startEvent(0x01fe); elseif (aSentrysPeril == QUEST_ACCEPTED) then if (player:hasItem(600) == true or player:hasItem(601) == true) then player:startEvent(0x0208); else player:startEvent(0x0284); end elseif (aSentrysPeril == QUEST_COMPLETED) then player:startEvent(0x0209); else npc:wait(0); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID2: %u",csid); --printf("RESULT2: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option,npc) --printf("CSID: %u",csid); --printf("RESULT: %u",option); npc:wait(5000); if (csid == 0x01fe and option == 0) then if (player:getFreeSlotsCount() > 0) then player:addQuest(SANDORIA,A_SENTRY_S_PERIL); player:addItem(600); player:messageSpecial(ITEM_OBTAINED,600); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,600); -- Dose of ointment end elseif (csid == 0x0284) then if (player:getFreeSlotsCount() > 0) then player:addItem(600); player:messageSpecial(ITEM_OBTAINED,600); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,600); -- Dose of ointment end elseif (csid == 0x0201) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,12832); -- Bronze Subligar else player:tradeComplete(); player:addTitle(RONFAURIAN_RESCUER); player:addItem(12832); player:messageSpecial(ITEM_OBTAINED,12832); -- Bronze Subligar player:addFame(SANDORIA,SAN_FAME*30); player:completeQuest(SANDORIA,A_SENTRY_S_PERIL); end end end;
gpl-3.0
eugeneia/snabb
lib/ljsyscall/syscall/linux/syscalls.lua
2
36238
-- This is the actual system calls for Linux local require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string = require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string local abi = require "syscall.abi" return function(S, hh, c, C, types) local ret64, retnum, retfd, retbool, retptr, retiter = hh.ret64, hh.retnum, hh.retfd, hh.retbool, hh.retptr, hh.retiter local ffi = require "ffi" local errno = ffi.errno local bit = require "syscall.bit" local t, pt, s = types.t, types.pt, types.s local h = require "syscall.helpers" local istype, mktype, getfd = h.istype, h.mktype, h.getfd if abi.abi32 then -- override open call with largefile -- TODO move this hack to c.lua instead function S.open(pathname, flags, mode) flags = c.O(flags, "LARGEFILE") return retfd(C.open(pathname, flags, c.MODE[mode])) end function S.openat(dirfd, pathname, flags, mode) flags = c.O(flags, "LARGEFILE") return retfd(C.openat(c.AT_FDCWD[dirfd], pathname, flags, c.MODE[mode])) end -- creat has no largefile flag so cannot be used function S.creat(pathname, mode) return S.open(pathname, "CREAT,WRONLY,TRUNC", mode) end end function S.pause() return retbool(C.pause()) end function S.acct(filename) return retbool(C.acct(filename)) end function S.getpriority(which, who) local ret, err = C.getpriority(c.PRIO[which], who or 0) if ret == -1 then return nil, t.error(err or errno()) end return 20 - ret -- adjust for kernel returned values as this is syscall not libc end -- we could allocate ptid, ctid, tls if required in flags instead. TODO add signal into flag parsing directly function S.clone(flags, signal, stack, ptid, tls, ctid) flags = c.CLONE[flags] + c.SIG[signal or 0] return retnum(C.clone(flags, stack, ptid, tls, ctid)) end if C.unshare then -- quite new, also not defined in rump yet function S.unshare(flags) return retbool(C.unshare(c.CLONE[flags])) end end if C.setns then function S.setns(fd, nstype) return retbool(C.setns(getfd(fd), c.CLONE[nstype])) end end function S.reboot(cmd) return retbool(C.reboot(c.LINUX_REBOOT.MAGIC1, c.LINUX_REBOOT.MAGIC2, c.LINUX_REBOOT_CMD[cmd])) end -- note waitid also provides rusage that Posix does not have, override default function S.waitid(idtype, id, options, infop, rusage) -- note order of args, as usually dont supply infop, rusage if not infop then infop = t.siginfo() end if not rusage and rusage ~= false then rusage = t.rusage() end local ret, err = C.waitid(c.P[idtype], id or 0, infop, c.W[options], rusage) if ret == -1 then return nil, t.error(err or errno()) end return infop, nil, rusage end function S.exit(status) C.exit_group(c.EXIT[status or 0]) end function S.sync_file_range(fd, offset, count, flags) return retbool(C.sync_file_range(getfd(fd), offset, count, c.SYNC_FILE_RANGE[flags])) end function S.getcwd(buf, size) size = size or c.PATH_MAX buf = buf or t.buffer(size) local ret, err = C.getcwd(buf, size) if ret == -1 then return nil, t.error(err or errno()) end return ffi.string(buf) end function S.statfs(path) local st = t.statfs() local ret, err = C.statfs(path, st) if ret == -1 then return nil, t.error(err or errno()) end return st end function S.fstatfs(fd) local st = t.statfs() local ret, err = C.fstatfs(getfd(fd), st) if ret == -1 then return nil, t.error(err or errno()) end return st end function S.mremap(old_address, old_size, new_size, flags, new_address) return retptr(C.mremap(old_address, old_size, new_size, c.MREMAP[flags], new_address)) end function S.remap_file_pages(addr, size, prot, pgoff, flags) return retbool(C.remap_file_pages(addr, size, c.PROT[prot], pgoff, c.MAP[flags])) end function S.fadvise(fd, advice, offset, len) -- note argument order TODO change back? return retbool(C.fadvise64(getfd(fd), offset or 0, len or 0, c.POSIX_FADV[advice])) end function S.fallocate(fd, mode, offset, len) return retbool(C.fallocate(getfd(fd), c.FALLOC_FL[mode], offset or 0, len)) end function S.posix_fallocate(fd, offset, len) return S.fallocate(fd, 0, offset, len) end function S.readahead(fd, offset, count) return retbool(C.readahead(getfd(fd), offset, count)) end -- TODO change to type? function S.uname() local u = t.utsname() local ret, err = C.uname(u) if ret == -1 then return nil, t.error(err or errno()) end return {sysname = ffi.string(u.sysname), nodename = ffi.string(u.nodename), release = ffi.string(u.release), version = ffi.string(u.version), machine = ffi.string(u.machine), domainname = ffi.string(u.domainname)} end function S.sethostname(s, len) return retbool(C.sethostname(s, len or #s)) end function S.setdomainname(s, len) return retbool(C.setdomainname(s, len or #s)) end if C.time then function S.time(time) return retnum(C.time(time)) end end function S.sysinfo(info) info = info or t.sysinfo() local ret, err = C.sysinfo(info) if ret == -1 then return nil, t.error(err or errno()) end return info end function S.signalfd(set, flags, fd) -- note different order of args, as fd usually empty. See also signalfd_read() set = mktype(t.sigset, set) if fd then fd = getfd(fd) else fd = -1 end -- note includes (hidden) size argument return retfd(C.signalfd(fd, set, s.sigset, c.SFD[flags])) end -- note that syscall does return timeout remaining but libc does not, due to standard prototype TODO use syscall -- note this is the only difference with NetBSD pollts, so could merge them function S.ppoll(fds, timeout, set) if timeout then timeout = mktype(t.timespec, timeout) end if set then set = mktype(t.sigset, set) end return retnum(C.ppoll(fds.pfd, #fds, timeout, set)) end if not S.poll then function S.poll(fd, timeout) if timeout then timeout = mktype(t.timespec, timeout / 1000) end return S.ppoll(fd, timeout) end end function S.mount(source, target, fstype, mountflags, data) return retbool(C.mount(source or "none", target, fstype, c.MS[mountflags], data)) end function S.umount(target, flags) return retbool(C.umount2(target, c.UMOUNT[flags])) end function S.prlimit(pid, resource, new_limit, old_limit) if new_limit then new_limit = mktype(t.rlimit, new_limit) end old_limit = old_limit or t.rlimit() local ret, err = C.prlimit64(pid or 0, c.RLIMIT[resource], new_limit, old_limit) if ret == -1 then return nil, t.error(err or errno()) end return old_limit end function S.epoll_create(flags) return retfd(C.epoll_create1(c.EPOLLCREATE[flags])) end function S.epoll_ctl(epfd, op, fd, event) if type(event) == "string" or type(event) == "number" then event = {events = event, fd = getfd(fd)} end event = mktype(t.epoll_event, event) return retbool(C.epoll_ctl(getfd(epfd), c.EPOLL_CTL[op], getfd(fd), event)) end if C.epoll_wait then function S.epoll_wait(epfd, events, timeout) local ret, err = C.epoll_wait(getfd(epfd), events.ep, #events, timeout or -1) return retiter(ret, err, events.ep) end else function S.epoll_wait(epfd, events, timeout) local ret, err = C.epoll_pwait(getfd(epfd), events.ep, #events, timeout or -1, nil) return retiter(ret, err, events.ep) end end function S.epoll_pwait(epfd, events, timeout, sigmask) if sigmask then sigmask = mktype(t.sigset, sigmask) end local ret, err = C.epoll_pwait(getfd(epfd), events.ep, #events, timeout or -1, sigmask) return retiter(ret, err, events.ep) end function S.splice(fd_in, off_in, fd_out, off_out, len, flags) local offin, offout = off_in, off_out if off_in and not ffi.istype(t.off1, off_in) then offin = t.off1() offin[0] = off_in end if off_out and not ffi.istype(t.off1, off_out) then offout = t.off1() offout[0] = off_out end return retnum(C.splice(getfd(fd_in), offin, getfd(fd_out), offout, len, c.SPLICE_F[flags])) end function S.vmsplice(fd, iov, flags) iov = mktype(t.iovecs, iov) return retnum(C.vmsplice(getfd(fd), iov.iov, #iov, c.SPLICE_F[flags])) end function S.tee(fd_in, fd_out, len, flags) return retnum(C.tee(getfd(fd_in), getfd(fd_out), len, c.SPLICE_F[flags])) end function S.inotify_init(flags) return retfd(C.inotify_init1(c.IN_INIT[flags])) end function S.inotify_add_watch(fd, pathname, mask) return retnum(C.inotify_add_watch(getfd(fd), pathname, c.IN[mask])) end function S.inotify_rm_watch(fd, wd) return retbool(C.inotify_rm_watch(getfd(fd), wd)) end function S.sendfile(out_fd, in_fd, offset, count) if type(offset) == "number" then offset = t.off1(offset) end return retnum(C.sendfile(getfd(out_fd), getfd(in_fd), offset, count)) end function S.eventfd(initval, flags) return retfd(C.eventfd(initval or 0, c.EFD[flags])) end function S.timerfd_create(clockid, flags) return retfd(C.timerfd_create(c.CLOCK[clockid], c.TFD[flags])) end function S.timerfd_settime(fd, flags, it, oldtime) oldtime = oldtime or t.itimerspec() local ret, err = C.timerfd_settime(getfd(fd), c.TFD_TIMER[flags or 0], mktype(t.itimerspec, it), oldtime) if ret == -1 then return nil, t.error(err or errno()) end return oldtime end function S.timerfd_gettime(fd, curr_value) curr_value = curr_value or t.itimerspec() local ret, err = C.timerfd_gettime(getfd(fd), curr_value) if ret == -1 then return nil, t.error(err or errno()) end return curr_value end function S.pivot_root(new_root, put_old) return retbool(C.pivot_root(new_root, put_old)) end -- aio functions function S.io_setup(nr_events) local ctx = t.aio_context1() local ret, err = C.io_setup(nr_events, ctx) if ret == -1 then return nil, t.error(err or errno()) end return ctx[0] end function S.io_destroy(ctx) return retbool(C.io_destroy(ctx)) end function S.io_cancel(ctx, iocb, result) result = result or t.io_event() local ret, err = C.io_cancel(ctx, iocb, result) if ret == -1 then return nil, t.error(err or errno()) end return result end function S.io_getevents(ctx, min, events, timeout) if timeout then timeout = mktype(t.timespec, timeout) end local ret, err = C.io_getevents(ctx, min or events.count, events.count, events.ev, timeout) return retiter(ret, err, events.ev) end -- iocb must persist until retrieved (as we get pointer), so cannot be passed as table must take t.iocb_array function S.io_submit(ctx, iocb) return retnum(C.io_submit(ctx, iocb.ptrs, iocb.nr)) end -- TODO prctl should be in a seperate file like ioctl fnctl (this is a Linux only interface) -- map for valid options for arg2 local prctlmap = { [c.PR.CAPBSET_READ] = c.CAP, [c.PR.CAPBSET_DROP] = c.CAP, [c.PR.SET_ENDIAN] = c.PR_ENDIAN, [c.PR.SET_FPEMU] = c.PR_FPEMU, [c.PR.SET_FPEXC] = c.PR_FP_EXC, [c.PR.SET_PDEATHSIG] = c.SIG, --[c.PR.SET_SECUREBITS] = c.SECBIT, -- TODO not defined yet [c.PR.SET_TIMING] = c.PR_TIMING, [c.PR.SET_TSC] = c.PR_TSC, [c.PR.SET_UNALIGN] = c.PR_UNALIGN, [c.PR.MCE_KILL] = c.PR_MCE_KILL, [c.PR.SET_SECCOMP] = c.SECCOMP_MODE, [c.PR.SET_NO_NEW_PRIVS] = h.booltoc, } local prctlrint = { -- returns an integer directly TODO add metatables to set names [c.PR.GET_DUMPABLE] = true, [c.PR.GET_KEEPCAPS] = true, [c.PR.CAPBSET_READ] = true, [c.PR.GET_TIMING] = true, [c.PR.GET_SECUREBITS] = true, [c.PR.MCE_KILL_GET] = true, [c.PR.GET_SECCOMP] = true, [c.PR.GET_NO_NEW_PRIVS] = true, } local prctlpint = { -- returns result in a location pointed to by arg2 [c.PR.GET_ENDIAN] = true, [c.PR.GET_FPEMU] = true, [c.PR.GET_FPEXC] = true, [c.PR.GET_PDEATHSIG] = true, [c.PR.GET_UNALIGN] = true, } -- this is messy, TODO clean up, its own file see above function S.prctl(option, arg2, arg3, arg4, arg5) local i, name option = c.PR[option] local m = prctlmap[option] if m then arg2 = m[arg2] end if option == c.PR.MCE_KILL and arg2 == c.PR_MCE_KILL.SET then arg3 = c.PR_MCE_KILL_OPT[arg3] elseif prctlpint[option] then i = t.int1() arg2 = ffi.cast(t.ulong, i) elseif option == c.PR.GET_NAME then name = t.buffer(16) arg2 = ffi.cast(t.ulong, name) elseif option == c.PR.SET_NAME then if type(arg2) == "string" then arg2 = ffi.cast(t.ulong, arg2) end elseif option == c.PR.SET_SECCOMP then arg3 = t.intptr(arg3 or 0) end local ret = C.prctl(option, arg2 or 0, arg3 or 0, arg4 or 0, arg5 or 0) if ret == -1 then return nil, t.error() end if prctlrint[option] then return ret end if prctlpint[option] then return i[0] end if option == c.PR.GET_NAME then if name[15] ~= 0 then return ffi.string(name, 16) end -- actually, 15 bytes seems to be longest, aways 0 terminated return ffi.string(name) end return true end function S.syslog(tp, buf, len) if not buf and (tp == 2 or tp == 3 or tp == 4) then if not len then -- this is the glibc name for the syslog syscall len = C.klogctl(10, nil, 0) -- get size so we can allocate buffer if len == -1 then return nil, t.error() end end buf = t.buffer(len) end local ret, err = C.klogctl(tp, buf or nil, len or 0) if ret == -1 then return nil, t.error(err or errno()) end if tp == 9 or tp == 10 then return tonumber(ret) end if tp == 2 or tp == 3 or tp == 4 then return ffi.string(buf, ret) end return true end function S.adjtimex(a) a = mktype(t.timex, a) local ret, err = C.adjtimex(a) if ret == -1 then return nil, t.error(err or errno()) end return t.adjtimex(ret, a) end if C.alarm then function S.alarm(s) return C.alarm(s) end end function S.setreuid(ruid, euid) return retbool(C.setreuid(ruid, euid)) end function S.setregid(rgid, egid) return retbool(C.setregid(rgid, egid)) end function S.getresuid(ruid, euid, suid) ruid, euid, suid = ruid or t.uid1(), euid or t.uid1(), suid or t.uid1() local ret, err = C.getresuid(ruid, euid, suid) if ret == -1 then return nil, t.error(err or errno()) end return true, nil, ruid[0], euid[0], suid[0] end function S.getresgid(rgid, egid, sgid) rgid, egid, sgid = rgid or t.gid1(), egid or t.gid1(), sgid or t.gid1() local ret, err = C.getresgid(rgid, egid, sgid) if ret == -1 then return nil, t.error(err or errno()) end return true, nil, rgid[0], egid[0], sgid[0] end function S.setresuid(ruid, euid, suid) return retbool(C.setresuid(ruid, euid, suid)) end function S.setresgid(rgid, egid, sgid) return retbool(C.setresgid(rgid, egid, sgid)) end function S.vhangup() return retbool(C.vhangup()) end function S.swapon(path, swapflags) return retbool(C.swapon(path, c.SWAP_FLAG[swapflags])) end function S.swapoff(path) return retbool(C.swapoff(path)) end if C.getrandom then function S.getrandom(buf, count, flags) return retnum(C.getrandom(buf, count or #buf or 64, c.GRND[flags])) end end if C.memfd_create then function S.memfd_create(name, flags) return retfd(C.memfd_create(name, c.MFD[flags])) end end -- capabilities. Somewhat complex kernel interface due to versioning, Posix requiring malloc in API. -- only support version 3, should be ok for recent kernels, or pass your own hdr, data in -- to detect capability API version, pass in hdr with empty version, version will be set function S.capget(hdr, data) -- normally just leave as nil for get, can pass pid in hdr = istype(t.user_cap_header, hdr) or t.user_cap_header(c.LINUX_CAPABILITY_VERSION[3], hdr or 0) if not data and hdr.version ~= 0 then data = t.user_cap_data2() end local ret, err = C.capget(hdr, data) if ret == -1 then return nil, t.error(err or errno()) end if not data then return hdr end return t.capabilities(hdr, data) end function S.capset(hdr, data) if ffi.istype(t.capabilities, hdr) then hdr, data = hdr:hdrdata() end return retbool(C.capset(hdr, data)) end function S.getcpu(cpu, node) cpu = cpu or t.uint1() node = node or t.uint1() local ret, err = C.getcpu(cpu, node) if ret == -1 then return nil, t.error(err or errno()) end return {cpu = cpu[0], node = node[0]} end function S.sched_getscheduler(pid) return retnum(C.sched_getscheduler(pid or 0)) end function S.sched_setscheduler(pid, policy, param) param = mktype(t.sched_param, param or 0) return retbool(C.sched_setscheduler(pid or 0, c.SCHED[policy], param)) end function S.sched_yield() return retbool(C.sched_yield()) end function S.sched_getaffinity(pid, mask, len) -- note len last as rarely used. All parameters optional mask = mktype(t.cpu_set, mask) local ret, err = C.sched_getaffinity(pid or 0, len or s.cpu_set, mask) if ret == -1 then return nil, t.error(err or errno()) end return mask end function S.sched_setaffinity(pid, mask, len) -- note len last as rarely used return retbool(C.sched_setaffinity(pid or 0, len or s.cpu_set, mktype(t.cpu_set, mask))) end local function get_maxnumnodes() local function readfile (filename) local ret = {} local bufsz = 1024 local buf = ffi.new("uint8_t[?]", bufsz) local fd, errno = S.open(filename, 0) if not fd then error(errno) end while true do local len = S.read(fd, buf, bufsz) table.insert(ret, ffi.string(buf, len)) if len ~= bufsz then break end end fd:close() return table.concat(ret) end local content = readfile("/proc/self/status") for line in content:gmatch("[^\n]+") do if line:match("^Mems_allowed:") then line = line:gsub("^Mems_allowed:%s+", "") -- In Mems_allowed each 9 characters (8 digit plus comma) represents -- a 32-bit mask. Total number of maxnumnodes is the total sum of -- the masks multiplied by 32. Line length is increased by one since -- there's no comma at the end of line. return math.floor(((#line+1)/9)*32) end end -- If we don't know, guess that the system has a max of 1024 nodes. return 1024 end local function ensure_bitmask(mask, size) if ffi.istype(t.bitmask, mask) then return mask end return t.bitmask(mask, size or get_maxnumnodes()) end function S.get_mempolicy(mode, mask, addr, flags) mode = mode or t.int1() mask = ensure_bitmask(mask); local ret, err = C.get_mempolicy(mode, mask.mask, mask.size, addr or 0, c.MPOL_FLAG[flags]) if ret == -1 then return nil, t.error(err or errno()) end return { mode=mode[0], mask=mask } end function S.set_mempolicy(mode, mask) mask = ensure_bitmask(mask); return retbool(C.set_mempolicy(c.MPOL_MODE[mode], mask.mask, mask.size)) end function S.migrate_pages(pid, from, to) from = ensure_bitmask(from); to = ensure_bitmask(to, from.size) assert(from.size == to.size, "incompatible nodemask sizes") return retbool(C.migrate_pages(pid or 0, from.size, from.mask, to.mask)) end function S.sched_get_priority_max(policy) return retnum(C.sched_get_priority_max(c.SCHED[policy])) end function S.sched_get_priority_min(policy) return retnum(C.sched_get_priority_min(c.SCHED[policy])) end function S.sched_setparam(pid, param) return retbool(C.sched_setparam(pid or 0, mktype(t.sched_param, param or 0))) end function S.sched_getparam(pid, param) param = mktype(t.sched_param, param or 0) local ret, err = C.sched_getparam(pid or 0, param) if ret == -1 then return nil, t.error(err or errno()) end return param.sched_priority -- only one useful parameter end function S.sched_rr_get_interval(pid, ts) ts = mktype(t.timespec, ts) local ret, err = C.sched_rr_get_interval(pid or 0, ts) if ret == -1 then return nil, t.error(err or errno()) end return ts end -- this is recommended way to size buffers for xattr local function growattrbuf(f, a, b) local len = 512 local buffer = t.buffer(len) local ret, err repeat if b then ret, err = f(a, b, buffer, len) else ret, err = f(a, buffer, len) end ret = tonumber(ret) if ret == -1 and (err or errno()) ~= c.E.RANGE then return nil, t.error(err or errno()) end if ret == -1 then len = len * 2 buffer = t.buffer(len) end until ret >= 0 return ffi.string(buffer, ret) end local function lattrbuf(f, a) local s, err = growattrbuf(f, a) if not s then return nil, err end local tab = h.split('\0', s) tab[#tab] = nil -- there is a trailing \0 so one extra return tab end -- TODO Note these should be in NetBSD too, but no useful filesystem (ex nfs) has xattr support, so never tested if C.listxattr then function S.listxattr(path) return lattrbuf(C.listxattr, path) end function S.llistxattr(path) return lattrbuf(C.llistxattr, path) end function S.flistxattr(fd) return lattrbuf(C.flistxattr, getfd(fd)) end end if C.setxattr then function S.setxattr(path, name, value, flags) return retbool(C.setxattr(path, name, value, #value, c.XATTR[flags])) end function S.lsetxattr(path, name, value, flags) return retbool(C.lsetxattr(path, name, value, #value, c.XATTR[flags])) end function S.fsetxattr(fd, name, value, flags) return retbool(C.fsetxattr(getfd(fd), name, value, #value, c.XATTR[flags])) end end if C.getxattr then function S.getxattr(path, name) return growattrbuf(C.getxattr, path, name) end function S.lgetxattr(path, name) return growattrbuf(C.lgetxattr, path, name) end function S.fgetxattr(fd, name) return growattrbuf(C.fgetxattr, getfd(fd), name) end end if C.removexattr then function S.removexattr(path, name) return retbool(C.removexattr(path, name)) end function S.lremovexattr(path, name) return retbool(C.lremovexattr(path, name)) end function S.fremovexattr(fd, name) return retbool(C.fremovexattr(getfd(fd), name)) end end -- helper function to set and return attributes in tables -- TODO this would make more sense as types? -- TODO listxattr should return an iterator not a table? local function xattr(list, get, set, remove, path, t) local l, err = list(path) if not l then return nil, err end if not t then -- no table, so read local r = {} for _, name in ipairs(l) do r[name] = get(path, name) -- ignore errors end return r end -- write for _, name in ipairs(l) do if t[name] then set(path, name, t[name]) -- ignore errors, replace t[name] = nil else remove(path, name) end end for name, value in pairs(t) do set(path, name, value) -- ignore errors, create end return true end if S.listxattr and S.getxattr then function S.xattr(path, t) return xattr(S.listxattr, S.getxattr, S.setxattr, S.removexattr, path, t) end function S.lxattr(path, t) return xattr(S.llistxattr, S.lgetxattr, S.lsetxattr, S.lremovexattr, path, t) end function S.fxattr(fd, t) return xattr(S.flistxattr, S.fgetxattr, S.fsetxattr, S.fremovexattr, fd, t) end end -- POSIX message queues. Note there is no mq_close as it is just close in Linux function S.mq_open(name, flags, mode, attr) local ret, err = C.mq_open(name, c.O[flags], c.MODE[mode], mktype(t.mq_attr, attr)) if ret == -1 then return nil, t.error(err or errno()) end return t.mqd(ret) end function S.mq_unlink(name) return retbool(C.mq_unlink(name)) end function S.mq_getsetattr(mqd, new, old) -- provided for completeness, but use getattr, setattr which are methods return retbool(C.mq_getsetattr(getfd(mqd), new, old)) end function S.mq_timedsend(mqd, msg_ptr, msg_len, msg_prio, abs_timeout) if abs_timeout then abs_timeout = mktype(t.timespec, abs_timeout) end return retbool(C.mq_timedsend(getfd(mqd), msg_ptr, msg_len or #msg_ptr, msg_prio or 0, abs_timeout)) end -- like read, return string if buffer not provided. Length required. TODO should we return prio? function S.mq_timedreceive(mqd, msg_ptr, msg_len, msg_prio, abs_timeout) if abs_timeout then abs_timeout = mktype(t.timespec, abs_timeout) end if msg_ptr then return retbool(C.mq_timedreceive(getfd(mqd), msg_ptr, msg_len or #msg_ptr, msg_prio, abs_timeout)) end msg_ptr = t.buffer(msg_len) local ret, err = C.mq_timedreceive(getfd(mqd), msg_ptr, msg_len or #msg_ptr, msg_prio, abs_timeout) if ret == -1 then return nil, t.error(err or errno()) end return ffi.string(msg_ptr,ret) end -- pty functions where not in common code TODO move to linux/libc? function S.grantpt(fd) return true end -- Linux does not need to do anything here (Musl does not) function S.unlockpt(fd) return S.ioctl(fd, "TIOCSPTLCK", 0) end function S.ptsname(fd) local pts, err = S.ioctl(fd, "TIOCGPTN") if not pts then return nil, err end return "/dev/pts/" .. tostring(pts) end function S.tcgetattr(fd) return S.ioctl(fd, "TCGETS") end local tcsets = { [c.TCSA.NOW] = "TCSETS", [c.TCSA.DRAIN] = "TCSETSW", [c.TCSA.FLUSH] = "TCSETSF", } function S.tcsetattr(fd, optional_actions, tio) local inc = c.TCSA[optional_actions] return S.ioctl(fd, tcsets[inc], tio) end function S.tcsendbreak(fd, duration) return S.ioctl(fd, "TCSBRK", pt.void(0)) -- Linux ignores duration end function S.tcdrain(fd) return S.ioctl(fd, "TCSBRK", pt.void(1)) -- note use of literal 1 cast to pointer end function S.tcflush(fd, queue_selector) return S.ioctl(fd, "TCFLSH", pt.void(c.TCFLUSH[queue_selector])) end function S.tcflow(fd, action) return S.ioctl(fd, "TCXONC", pt.void(c.TCFLOW[action])) end -- compat code for stuff that is not actually a syscall under Linux -- old rlimit functions in Linux are 32 bit only so now defined using prlimit function S.getrlimit(resource) return S.prlimit(0, resource) end function S.setrlimit(resource, rlim) local ret, err = S.prlimit(0, resource, rlim) if not ret then return nil, err end return true end function S.gethostname() local u, err = S.uname() if not u then return nil, err end return u.nodename end function S.getdomainname() local u, err = S.uname() if not u then return nil, err end return u.domainname end function S.killpg(pgrp, sig) return S.kill(-pgrp, sig) end -- helper function to read inotify structs as table from inotify fd, TODO could be in util function S.inotify_read(fd, buffer, len) len = len or 1024 buffer = buffer or t.buffer(len) local ret, err = S.read(fd, buffer, len) if not ret then return nil, err end return t.inotify_events(buffer, ret) end -- in Linux mkfifo is not a syscall, emulate function S.mkfifo(path, mode) return S.mknod(path, bit.bor(c.MODE[mode], c.S_I.FIFO)) end function S.mkfifoat(fd, path, mode) return S.mknodat(fd, path, bit.bor(c.MODE[mode], c.S_I.FIFO), 0) end -- in Linux getpagesize is not a syscall for most architectures. -- It is pretty obscure how you get the page size for architectures that have variable page size, I think it is coded into libc -- that matches kernel. Which is not much use for us. -- fortunately Linux (unlike BSD) checks correct offsets on mapping /dev/zero local pagesize -- store so we do not repeat this if not S.getpagesize then function S.getpagesize() if pagesize then return pagesize end local sz = 4096 local fd, err = S.open("/dev/zero", "rdwr") if not fd then return nil, err end while sz < 4096 * 1024 + 1024 do local mm, err = S.mmap(nil, sz, "read", "shared", fd, sz) if mm then S.munmap(mm, sz) pagesize = sz return sz end sz = sz * 2 end end end -- in Linux shm_open and shm_unlink are not syscalls local shm = "/dev/shm" function S.shm_open(pathname, flags, mode) if pathname:sub(1, 1) ~= "/" then pathname = "/" .. pathname end pathname = shm .. pathname return S.open(pathname, c.O(flags, "nofollow", "cloexec", "nonblock"), mode) end function S.shm_unlink(pathname) if pathname:sub(1, 1) ~= "/" then pathname = "/" .. pathname end pathname = shm .. pathname return S.unlink(pathname) end -- TODO setpgrp and similar - see the man page -- in Linux pathconf can just return constants -- TODO these could go into constants, although maybe better to get from here local PAGE_SIZE = S.getpagesize local NAME_MAX = 255 local PATH_MAX = 4096 -- TODO this is in constants, inconsistently local PIPE_BUF = 4096 local FILESIZEBITS = 64 local SYMLINK_MAX = 255 local _POSIX_LINK_MAX = 8 local _POSIX_MAX_CANON = 255 local _POSIX_MAX_INPUT = 255 local pathconf_values = { [c.PC.LINK_MAX] = _POSIX_LINK_MAX, [c.PC.MAX_CANON] = _POSIX_MAX_CANON, [c.PC.MAX_INPUT] = _POSIX_MAX_INPUT, [c.PC.NAME_MAX] = NAME_MAX, [c.PC.PATH_MAX] = PATH_MAX, [c.PC.PIPE_BUF] = PIPE_BUF, [c.PC.CHOWN_RESTRICTED] = 1, [c.PC.NO_TRUNC] = 1, [c.PC.VDISABLE] = 0, [c.PC.SYNC_IO] = 1, [c.PC.ASYNC_IO] = -1, [c.PC.PRIO_IO] = -1, [c.PC.SOCK_MAXBUF] = -1, [c.PC.FILESIZEBITS] = FILESIZEBITS, [c.PC.REC_INCR_XFER_SIZE] = PAGE_SIZE, [c.PC.REC_MAX_XFER_SIZE] = PAGE_SIZE, [c.PC.REC_MIN_XFER_SIZE] = PAGE_SIZE, [c.PC.REC_XFER_ALIGN] = PAGE_SIZE, [c.PC.ALLOC_SIZE_MIN] = PAGE_SIZE, [c.PC.SYMLINK_MAX] = SYMLINK_MAX, [c.PC["2_SYMLINKS"]] = 1, } function S.pathconf(_, name) local pc = pathconf_values[c.PC[name]] if type(pc) == "function" then pc = pc() end return pc end S.fpathconf = S.pathconf -- setegid and set euid are not syscalls function S.seteuid(euid) return S.setresuid(-1, euid, -1) end function S.setegid(egid) return S.setresgid(-1, egid, -1) end -- in Linux sysctl is not a sycall any more (well it is but legacy) -- note currently all returned as strings, may want to list which should be numbers function S.sysctl(name, new) name = "/proc/sys/" .. name:gsub("%.", "/") local fd, err = S.open(name, c.O.RDONLY) if not fd then return nil, err end local len = 1024 local old, err = S.read(fd, nil, len) if not old then return nil, err end old = old:sub(1, #old - 1) -- remove trailing newline local ok, err = S.close(fd) if not ok then return nil, err end if not new then return old end -- Reopen fd because we want to write at pos 0 local fd, err = S.open(name, c.O.WRONLY) if not fd then return nil, err end local ok, err = S.write(fd, new) if not ok then return nil, err end local ok, err = S.close(fd) if not ok then return nil, err end return old end -- BPF syscall has a complex semantics with one union serving for all purposes -- The interface exports both raw syscall and helper functions based on libbpf if C.bpf then local function ptr_to_u64(p) return ffi.cast('uint64_t', ffi.cast('void *', p)) end function S.bpf(cmd, attr) return C.bpf(c.BPF_CMD[cmd], attr) end function S.bpf_prog_load(type, insns, len, license, version, log_level) if not license then license = "GPL" end -- Must stay alive during the syscall local bpf_log_buf = ffi.new('char [?]', 64*1024) -- Must stay alive during the syscall if not version then -- We have no better way to extract current kernel hex-string other -- than parsing headers, compiling a helper function or reading /proc local ver_str, count = S.sysctl('kernel.osrelease'):match('%d+.%d+.%d+'), 2 version = 0 for i in ver_str:gmatch('%d+') do -- Convert 'X.Y.Z' to 0xXXYYZZ version = bit.bor(version, bit.lshift(tonumber(i), 8*count)) count = count - 1 end end local attr = t.bpf_attr1() attr[0].prog_type = c.BPF_PROG[type] attr[0].insns = ptr_to_u64(insns) attr[0].insn_cnt = len attr[0].license = ptr_to_u64(license) attr[0].log_buf = ptr_to_u64(bpf_log_buf) attr[0].log_size = ffi.sizeof(bpf_log_buf) attr[0].log_level = log_level or 1 attr[0].kern_version = version -- MUST match current kernel version local fd = S.bpf(c.BPF_CMD.PROG_LOAD, attr) if fd < 0 then return nil, t.error(errno()), ffi.string(bpf_log_buf) end return retfd(fd), ffi.string(bpf_log_buf) end function S.bpf_map_create(type, key_size, value_size, max_entries) local attr = t.bpf_attr1() attr[0].map_type = c.BPF_MAP[type] attr[0].key_size = key_size attr[0].value_size = value_size attr[0].max_entries = max_entries local fd = S.bpf(c.BPF_CMD.MAP_CREATE, attr) if fd < 0 then return nil, t.error(errno()) end return retfd(fd) end function S.bpf_map_op(op, fd, key, val_or_next, flags) local attr = t.bpf_attr1() attr[0].map_fd = getfd(fd) attr[0].key = ptr_to_u64(key) attr[0].value = ptr_to_u64(val_or_next) attr[0].flags = flags or 0 local ret = S.bpf(op, attr) if ret ~= 0 then return nil, t.error(errno()) end return ret end function S.bpf_obj_pin(path, fd, flags) local attr = t.bpf_attr1() local pathname = ffi.new("char[?]", #path+1) ffi.copy(pathname, path) attr[0].pathname = ptr_to_u64(pathname) attr[0].bpf_fd = getfd(fd) attr[0].file_flags = flags or 0 local ret = S.bpf(c.BPF_CMD.OBJ_PIN, attr) if ret ~= 0 then return nil, t.error(errno()) end return ret end function S.bpf_obj_get(path, flags) local attr = t.bpf_attr1() local pathname = ffi.new("char[?]", #path+1) ffi.copy(pathname, path) attr[0].pathname = ptr_to_u64(pathname) attr[0].file_flags = flags or 0 local ret = S.bpf(c.BPF_CMD.OBJ_GET, attr) if ret < 0 then return nil, t.error(errno()) end return retfd(ret) end end -- Linux performance monitoring if C.perf_event_open then -- Open perf event fd -- @note see man 2 perf_event_open -- @return fd, err function S.perf_event_open(attr, pid, cpu, group_fd, flags) if attr[0].size == 0 then attr[0].size = ffi.sizeof(attr[0]) end local fd = C.perf_event_open(attr, pid or 0, cpu or -1, group_fd or -1, c.PERF_FLAG[flags or 0]) if fd < 0 then return nil, t.error(errno()) end return retfd(fd) end -- Read the tracepoint configuration (see "/sys/kernel/debug/tracing/available_events") -- @param event_path path to tracepoint (e.g. "/sys/kernel/debug/tracing/events/syscalls/sys_enter_write") -- @return tp, err (e.g. 538, nil) function S.perf_tracepoint(event_path) local config = nil event_path = event_path.."/id" local fd, err = S.open(event_path, c.O.RDONLY) if fd then local ret, err = fd:read(nil, 256) if ret then config = tonumber(ret) end fd:close() end return config, err end -- Attach or detach a probe, same semantics as Lua tables. -- See https://www.kernel.org/doc/Documentation/trace/kprobetrace.txt -- (When the definition is not nil, it will be created, otherwise it will be detached) -- @param probe_type either "kprobe" or "uprobe", no other probe types are supported -- @param name chosen probe name (e.g. "myprobe") -- @param definition (set to nil to disable probe) (e.g. "do_sys_open $retval") -- @param retval true/false if this should be entrypoint probe or return probe -- @return tp, err (e.g. 1099, nil) function S.perf_probe(probe_type, name, definition, retval) local event_path = string.format('/sys/kernel/debug/tracing/%s_events', probe_type) local probe_path = string.format('/sys/kernel/debug/tracing/events/%ss/%s', probe_type, name) -- Check if probe already exists if definition and S.statfs(probe_path) then return nil, t.error(c.E.EEXIST) end local fd, err = S.open(event_path, "wronly, append") if not fd then return nil, err end -- Format a probe definition if not definition then definition = "-:"..name -- Detach else definition = string.format("%s:%s %s", retval and "r" or "p", name, definition) end local ok, err = fd:write(definition) fd:close() -- Return tracepoint or success if ok and definition then return S.perf_tracepoint(probe_path) end return ok, err end -- Attach perf event reader to tracepoint (see "/sys/kernel/debug/tracing/available_events") -- @param tp tracepoint identifier (e.g.: 538, use `S.perf_tracepoint()`) -- @param type perf_attr.sample_type (default: "raw") -- @param attrs table of attributes (e.g. {sample_type="raw, callchain"}, see `struct perf_event_attr`) -- @return reader, err function S.perf_attach_tracepoint(tp, pid, cpu, group_fd, attrs) local pe = t.perf_event_attr1() pe[0].type = "tracepoint" pe[0].config = tp pe[0].sample_type = "raw" pe[0].sample_period = 1 pe[0].wakeup_events = 1 if attrs then for k,v in pairs(attrs) do pe[0][k] = v end end -- Open perf event reader with given parameters local fd, err = S.perf_event_open(pe, pid, cpu, group_fd, "fd_cloexec") if not fd then return nil, err end return t.perf_reader(fd) end end return S end
apache-2.0
SalvationDevelopment/Salvation-Scripts-TCG
c97342942.lua
7
1338
--エクトプラズマー function c97342942.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) c:RegisterEffect(e1) --release local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(97342942,0)) e2:SetCategory(CATEGORY_RELEASE+CATEGORY_DAMAGE) e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F) e2:SetRange(LOCATION_SZONE) e2:SetProperty(EFFECT_FLAG_BOTH_SIDE) e2:SetCode(EVENT_PHASE+PHASE_END) e2:SetCountLimit(1) e2:SetCondition(c97342942.condition) e2:SetTarget(c97342942.target) e2:SetOperation(c97342942.operation) c:RegisterEffect(e2) end function c97342942.condition(e,tp,eg,ep,ev,re,r,rp) return Duel.GetTurnPlayer()==tp end function c97342942.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end Duel.SetOperationInfo(0,CATEGORY_RELEASE,nil,1,tp,LOCATION_MZONE) end function c97342942.rfilter(c,e) return c:IsFaceup() and c:IsReleasableByEffect() and not c:IsImmuneToEffect(e) end function c97342942.operation(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if not c:IsRelateToEffect(e) then return end local rg=Duel.SelectReleaseGroup(tp,c97342942.rfilter,1,1,e:GetHandler(),e) if Duel.Release(rg,REASON_EFFECT)>0 then local atk=rg:GetFirst():GetBaseAttack()/2 Duel.Damage(1-tp,atk,REASON_EFFECT) end end
gpl-2.0
Turttle/darkstar
scripts/globals/items/galette_des_rois.lua
39
1322
----------------------------------------- -- ID: 5875 -- Item: Galette Des Rois -- Food Effect: 180 Min, All Races ----------------------------------------- -- MP % 1 -- Intelligence +2 -- Random Jewel ----------------------------------------- require("scripts/globals/status"); require("scripts/zones/Bastok_Mines/TextIDs"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD)) then result = 246; end if (target:getFreeSlotsCount() == 0) then result = 308; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,10800,5875); local rand = math.random(784,815); target:addItem(rand); -- Random Jewel end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_MPP, 1); target:addMod(MOD_INT, 2); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_MPP, 1); target:delMod(MOD_INT, 2); end;
gpl-3.0