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 |
|---|---|---|---|---|---|
fengshao0907/Atlas-1 | lib/admin-sql.lua | 40 | 8858 | --[[ $%BEGINLICENSE%$
Copyright (c) 2008, Oracle and/or its affiliates. All rights reserved.
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; version 2 of the
License.
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 St, Fifth Floor, Boston, MA
02110-1301 USA
$%ENDLICENSE%$ --]]
---
-- map SQL commands to the hidden MySQL Protocol commands
--
-- some protocol commands are only available through the mysqladmin tool like
-- * ping
-- * shutdown
-- * debug
-- * statistics
--
-- ... while others are avaible
-- * process info (SHOW PROCESS LIST)
-- * process kill (KILL <id>)
--
-- ... and others are ignored
-- * time
--
-- that way we can test MySQL Servers more easily with "mysqltest"
--
---
-- recognize special SQL commands and turn them into COM_* sequences
--
function read_query(packet)
if packet:byte() ~= proxy.COM_QUERY then return end
if packet:sub(2) == "COMMIT SUICIDE" then
proxy.queries:append(proxy.COM_SHUTDOWN, string.char(proxy.COM_SHUTDOWN), { resultset_is_needed = true })
return proxy.PROXY_SEND_QUERY
elseif packet:sub(2) == "PING" then
proxy.queries:append(proxy.COM_PING, string.char(proxy.COM_PING), { resultset_is_needed = true })
return proxy.PROXY_SEND_QUERY
elseif packet:sub(2) == "STATISTICS" then
proxy.queries:append(proxy.COM_STATISTICS, string.char(proxy.COM_STATISTICS), { resultset_is_needed = true })
return proxy.PROXY_SEND_QUERY
elseif packet:sub(2) == "PROCINFO" then
proxy.queries:append(proxy.COM_PROCESS_INFO, string.char(proxy.COM_PROCESS_INFO), { resultset_is_needed = true })
return proxy.PROXY_SEND_QUERY
elseif packet:sub(2) == "TIME" then
proxy.queries:append(proxy.COM_TIME, string.char(proxy.COM_TIME), { resultset_is_needed = true })
return proxy.PROXY_SEND_QUERY
elseif packet:sub(2) == "DEBUG" then
proxy.queries:append(proxy.COM_DEBUG, string.char(proxy.COM_DEBUG), { resultset_is_needed = true })
return proxy.PROXY_SEND_QUERY
elseif packet:sub(2) == "PROCKILL" then
proxy.queries:append(proxy.COM_PROCESS_KILL, string.char(proxy.COM_PROCESS_KILL), { resultset_is_needed = true })
return proxy.PROXY_SEND_QUERY
elseif packet:sub(2) == "SETOPT" then
proxy.queries:append(proxy.COM_SET_OPTION, string.char(proxy.COM_SET_OPTION), { resultset_is_needed = true })
return proxy.PROXY_SEND_QUERY
elseif packet:sub(2) == "BINLOGDUMP" then
proxy.queries:append(proxy.COM_BINLOG_DUMP, string.char(proxy.COM_BINLOG_DUMP), { resultset_is_needed = true })
return proxy.PROXY_SEND_QUERY
elseif packet:sub(2) == "BINLOGDUMP1" then
proxy.queries:append(proxy.COM_BINLOG_DUMP,
string.char(proxy.COM_BINLOG_DUMP) ..
"\004\000\000\000" ..
"\000\000" ..
"\002\000\000\000" ..
"\000" ..
""
, { resultset_is_needed = true })
return proxy.PROXY_SEND_QUERY
elseif packet:sub(2) == "REGSLAVE" then
proxy.queries:append(proxy.COM_REGISTER_SLAVE, string.char(proxy.COM_REGISTER_SLAVE), { resultset_is_needed = true })
return proxy.PROXY_SEND_QUERY
elseif packet:sub(2) == "REGSLAVE1" then
proxy.queries:append(proxy.COM_REGISTER_SLAVE,
string.char(proxy.COM_REGISTER_SLAVE) ..
"\001\000\000\000" .. -- server-id
"\000" .. -- report-host
"\000" .. -- report-user
"\000" .. -- report-password ?
"\001\000" .. -- our port
"\000\000\000\000" .. -- recovery rank
"\001\000\000\000" .. -- master id ... what ever that is
""
, { resultset_is_needed = true })
return proxy.PROXY_SEND_QUERY
elseif packet:sub(2) == "PREP" then
proxy.queries:append(proxy.COM_STMT_PREPARE, string.char(proxy.COM_STMT_PREPARE), { resultset_is_needed = true })
return proxy.PROXY_SEND_QUERY
elseif packet:sub(2) == "PREP1" then
proxy.queries:append(proxy.COM_STMT_PREPARE, string.char(proxy.COM_STMT_PREPARE) .. "SELECT ?", { resultset_is_needed = true })
return proxy.PROXY_SEND_QUERY
elseif packet:sub(2) == "EXEC" then
proxy.queries:append(proxy.COM_STMT_EXECUTE, string.char(proxy.COM_STMT_EXECUTE), { resultset_is_needed = true })
return proxy.PROXY_SEND_QUERY
elseif packet:sub(2) == "EXEC1" then
proxy.queries:append(proxy.COM_STMT_EXECUTE,
string.char(proxy.COM_STMT_EXECUTE) ..
"\001\000\000\000" .. -- stmt-id
"\000" .. -- flags
"\001\000\000\000" .. -- iteration count
"\000" .. -- null-bits
"\001" .. -- new-parameters
"\000\254" ..
"\004" .. "1234" ..
"", { resultset_is_needed = true })
return proxy.PROXY_SEND_QUERY
elseif packet:sub(2) == "DEAL" then
proxy.queries:append(proxy.COM_STMT_CLOSE, string.char(proxy.COM_STMT_CLOSE), { resultset_is_needed = true })
return proxy.PROXY_SEND_QUERY
elseif packet:sub(2) == "DEAL1" then
proxy.queries:append(proxy.COM_STMT_CLOSE, string.char(proxy.COM_STMT_CLOSE) .. "\001\000\000\000", { resultset_is_needed = true })
return proxy.PROXY_SEND_QUERY
elseif packet:sub(2) == "RESET" then
proxy.queries:append(proxy.COM_STMT_RESET, string.char(proxy.COM_STMT_RESET), { resultset_is_needed = true })
return proxy.PROXY_SEND_QUERY
elseif packet:sub(2) == "RESET1" then
proxy.queries:append(proxy.COM_STMT_RESET, string.char(proxy.COM_STMT_RESET) .. "\001\000\000\000", { resultset_is_needed = true })
return proxy.PROXY_SEND_QUERY
elseif packet:sub(2) == "FETCH" then
proxy.queries:append(proxy.COM_STMT_FETCH, string.char(proxy.COM_STMT_FETCH), { resultset_is_needed = true })
return proxy.PROXY_SEND_QUERY
elseif packet:sub(2) == "FETCH1" then
proxy.queries:append(proxy.COM_STMT_FETCH, string.char(proxy.COM_STMT_FETCH) .. "\001\000\000\000" .. "\128\000\000\000", { resultset_is_needed = true })
return proxy.PROXY_SEND_QUERY
elseif packet:sub(2) == "FLIST" then
proxy.queries:append(proxy.COM_FIELD_LIST, string.char(proxy.COM_FIELD_LIST), { resultset_is_needed = true })
return proxy.PROXY_SEND_QUERY
elseif packet:sub(2) == "FLIST1" then
proxy.queries:append(proxy.COM_FIELD_LIST, string.char(proxy.COM_FIELD_LIST) .. "t1\000id\000\000\000", { resultset_is_needed = true })
return proxy.PROXY_SEND_QUERY
elseif packet:sub(2) == "TDUMP" then
proxy.queries:append(proxy.COM_TABLE_DUMP, string.char(proxy.COM_TABLE_DUMP), { resultset_is_needed = true })
return proxy.PROXY_SEND_QUERY
elseif packet:sub(2) == "TDUMP1" then
proxy.queries:append(proxy.COM_TABLE_DUMP, string.char(proxy.COM_TABLE_DUMP) .. "\004test\002t1", { resultset_is_needed = true })
return proxy.PROXY_SEND_QUERY
elseif packet:sub(2) == "TDUMP2" then
proxy.queries:append(proxy.COM_TABLE_DUMP, string.char(proxy.COM_TABLE_DUMP) .. "\004test\002t2", { resultset_is_needed = true })
return proxy.PROXY_SEND_QUERY
end
end
---
-- adjust the response to match the needs of COM_QUERY
-- where neccesary
--
-- * some commands return EOF (COM_SHUTDOWN),
-- * some are plain-text (COM_STATISTICS)
--
-- in the end the client sent us a COM_QUERY and we have to hide
-- all those specifics
function read_query_result(inj)
if inj.id == proxy.COM_SHUTDOWN or
inj.id == proxy.COM_SET_OPTION or
inj.id == proxy.COM_BINLOG_DUMP or
inj.id == proxy.COM_STMT_PREPARE or
inj.id == proxy.COM_STMT_FETCH or
inj.id == proxy.COM_FIELD_LIST or
inj.id == proxy.COM_TABLE_DUMP or
inj.id == proxy.COM_DEBUG then
-- translate the EOF packet from the COM_SHUTDOWN into a OK packet
-- to match the needs of the COM_QUERY we got
if inj.resultset.raw:byte() ~= 255 then
proxy.response = {
type = proxy.MYSQLD_PACKET_OK,
}
return proxy.PROXY_SEND_RESULT
end
elseif inj.id == proxy.COM_PING or
inj.id == proxy.COM_TIME or
inj.id == proxy.COM_PROCESS_KILL or
inj.id == proxy.COM_REGISTER_SLAVE or
inj.id == proxy.COM_STMT_EXECUTE or
inj.id == proxy.COM_STMT_RESET or
inj.id == proxy.COM_PROCESS_INFO then
-- no change needed
elseif inj.id == proxy.COM_STATISTICS then
-- the response a human readable plain-text
--
-- just turn it into a proper result-set
proxy.response = {
type = proxy.MYSQLD_PACKET_OK,
resultset = {
fields = {
{ name = "statisitics" }
},
rows = {
{ inj.resultset.raw }
}
}
}
return proxy.PROXY_SEND_RESULT
else
-- we don't know them yet, just return ERR to the client to
-- match the needs of COM_QUERY
print(("got: %q"):format(inj.resultset.raw))
proxy.response = {
type = proxy.MYSQLD_PACKET_ERR,
}
return proxy.PROXY_SEND_RESULT
end
end
| gpl-2.0 |
dschoeffm/MoonGen | rfc2544/master.lua | 9 | 7915 | package.path = package.path .. "rfc2544/?.lua;../rfc2544/?.lua;"
if master == nil then
master = "dummy"
end
local dpdk = require "dpdk"
local device = require "device"
local arp = require "proto.arp"
local throughput = require "benchmarks.throughput"
local latency = require "benchmarks.latency"
local frameloss = require "benchmarks.frameloss"
local backtoback = require "benchmarks.backtoback"
local utils = require "utils.utils"
local testreport = require "utils.testreport"
local conf = require "config"
local FRAME_SIZES = {64, 128, 256, 512, 1024, 1280, 1518}
local usageString = [[
--txport <txport>
--rxport <rxport>
--rths <throughput rate threshold>
--mlr <max throuput loss rate>
--bths <back-to-back frame threshold>
--duration <single test duration>
--iterations <amount of test iterations>
--din <DuT in interface name>
--dout <DuT out iterface name>
--dskip <skip DuT configuration>
--asksshpass <true|false> [ask at beginning for SSH password]
--sshpass <SSH password>
--sshuser <SSH user>
--sshport <SSH port>
--asksnmpcomm <true|false> [ask at beginning for SNMP community string]
--snmpcomm <SNMP community string>
--host <mgmt host name of the DuT>
]]
local date = os.date("%F_%H-%M")
function log(file, msg, linebreak)
print(msg)
file:write(msg)
if linebreak then
file:write("\n")
end
end
function master()
local arguments = utils.parseArguments(arg)
local txPort, rxPort = arguments.txport, arguments.rxport
if not txPort or not rxPort then
return print("usage: " .. usageString)
end
local rateThreshold = arguments.rths or 100
local btbThreshold = arguments.bths or 100
local duration = arguments.duration or 10
local maxLossRate = arguments.mlr or 0.001
local dskip = arguments.dskip
local numIterations = arguments.iterations
if type(arguments.sshpass) == "string" then
conf.setSSHPass(arguments.sshpass)
elseif arguments.asksshpass == "true" then
io.write("password: ")
conf.setSSHPass(io.read())
end
if type(arguments.sshuser) == "string" then
conf.setSSHUser(arguments.sshuser)
end
if type(arguments.sshport) == "string" then
conf.setSSHPort(tonumber(arguments.sshport))
elseif type(arguments.sshport) == "number" then
conf.setSSHPort(arguments.sshport)
end
if type(arguments.snmpcomm) == "string" then
conf.setSNMPComm(arguments.snmpcomm)
elseif arguments.asksnmpcomm == "true" then
io.write("snmp community: ")
conf.setSNMPComm(io.read())
end
if type(arguments.host) == "string" then
conf.setHost(arguments.host)
end
local dut = {
ifIn = arguments.din,
ifOut = arguments.dout
}
local rxDev, txDev
if txPort == rxPort then
-- sending and receiving from the same port
txDev = device.config({port = txPort, rxQueues = 3, txQueues = 5})
rxDev = txDev
else
-- two different ports, different configuration
txDev = device.config({port = txPort, rxQueues = 2, txQueues = 5})
rxDev = device.config({port = rxPort, rxQueues = 3, txQueues = 3})
end
device.waitForLinks()
-- launch background arp table task
if txPort == rxPort then
dpdk.launchLua(arp.arpTask, {
{
txQueue = txDev:getTxQueue(0),
rxQueue = txDev:getRxQueue(1),
ips = {"198.18.1.2", "198.19.1.2"}
}
})
else
dpdk.launchLua(arp.arpTask, {
{
txQueue = txDev:getTxQueue(0),
rxQueue = txDev:getRxQueue(1),
ips = {"198.18.1.2"}
},
{
txQueue = rxDev:getTxQueue(0),
rxQueue = rxDev:getRxQueue(1),
ips = {"198.19.1.2", "198.18.1.1"}
}
})
end
-- create testresult folder if not exist
-- there is no clean lua way without using 3rd party libs
local folderName = "testresults_" .. date
os.execute("mkdir -p " .. folderName)
local report = testreport.new(folderName .. "/rfc_2544_testreport.tex")
local results = {}
local thBench = throughput.benchmark()
thBench:init({
txQueues = {txDev:getTxQueue(1), txDev:getTxQueue(2), txDev:getTxQueue(3)},
rxQueues = {rxDev:getRxQueue(0)},
duration = duration,
rateThreshold = rateThreshold,
maxLossRate = maxLossRate,
skipConf = dskip,
dut = dut,
numIterations = numIterations,
})
local rates = {}
local file = io.open(folderName .. "/throughput.csv", "w")
log(file, thBench:getCSVHeader(), true)
for _, frameSize in ipairs(FRAME_SIZES) do
local result, avgRate = thBench:bench(frameSize)
rates[frameSize] = avgRate
-- save and report results
table.insert(results, result)
log(file, thBench:resultToCSV(result), true)
report:addThroughput(result, duration, maxLossRate, rateThreshold)
end
thBench:toTikz(folderName .. "/plot_throughput", unpack(results))
file:close()
results = {}
local latBench = latency.benchmark()
latBench:init({
txQueues = {txDev:getTxQueue(1), txDev:getTxQueue(2), txDev:getTxQueue(3), txDev:getTxQueue(4)},
-- different receiving queue, for timestamping filter
rxQueues = {rxDev:getRxQueue(2)},
duration = duration,
skipConf = dskip,
dut = dut,
})
file = io.open(folderName .. "/latency.csv", "w")
log(file, latBench:getCSVHeader(), true)
for _, frameSize in ipairs(FRAME_SIZES) do
local result = latBench:bench(frameSize, math.ceil(rates[frameSize] * (frameSize + 20) * 8))
-- save and report results
table.insert(results, result)
log(file, latBench:resultToCSV(result), true)
report:addLatency(result, duration)
end
latBench:toTikz(folderName .. "/plot_latency", unpack(results))
file:close()
results = {}
local flBench = frameloss.benchmark()
flBench:init({
txQueues = {txDev:getTxQueue(1), txDev:getTxQueue(2), txDev:getTxQueue(3)},
rxQueues = {rxDev:getRxQueue(0)},
duration = duration,
granularity = 0.05,
skipConf = dskip,
dut = dut,
})
file = io.open(folderName .. "/frameloss.csv", "w")
log(file, flBench:getCSVHeader(), true)
for _, frameSize in ipairs(FRAME_SIZES) do
local result = flBench:bench(frameSize)
-- save and report results
table.insert(results, result)
log(file, flBench:resultToCSV(result), true)
report:addFrameloss(result, duration)
end
flBench:toTikz(folderName .. "/plot_frameloss", unpack(results))
file:close()
results = {}
local btbBench = backtoback.benchmark()
btbBench:init({
txQueues = {txDev:getTxQueue(1)},
rxQueues = {rxDev:getRxQueue(0)},
granularity = btbThreshold,
skipConf = dskip,
numIterations = numIterations,
dut = dut,
})
file = io.open(folderName .. "/backtoback.csv", "w")
log(file, btbBench:getCSVHeader(), true)
for _, frameSize in ipairs(FRAME_SIZES) do
local result = btbBench:bench(frameSize)
-- save and report results
table.insert(results, result)
log(file, btbBench:resultToCSV(result), true)
report:addBackToBack(result, btbBench.duration, btbThreshold, txDev:getLinkStatus().speed)
end
btbBench:toTikz(folderName .. "/plot_backtoback", unpack(results))
file:close()
report:finalize()
end
| mit |
dicebox/minetest-france | minetest/builtin/mainmenu/tab_server.lua | 1 | 6540 | --Minetest
--Copyright (C) 2014 sapier
--
--This program is free software; you can redistribute it and/or modify
--it under the terms of the GNU Lesser General Public License as published by
--the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
--
--You should have received a copy of the GNU Lesser 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.
--------------------------------------------------------------------------------
local function get_formspec(tabview, name, tabdata)
local index = menudata.worldlist:get_current_index(
tonumber(core.setting_get("mainmenu_last_selected_world"))
)
local retval =
"button[4,4.15;2.6,0.5;world_delete;" .. fgettext("Delete") .. "]" ..
"button[6.5,4.15;2.8,0.5;world_create;" .. fgettext("New") .. "]" ..
"button[9.2,4.15;2.55,0.5;world_configure;" .. fgettext("Configure") .. "]" ..
"button[8.5,5;3.25,0.5;start_server;" .. fgettext("Start Game") .. "]" ..
"label[4,-0.25;" .. fgettext("Select World:") .. "]" ..
"checkbox[0.25,0.25;cb_creative_mode;" .. fgettext("Creative Mode") .. ";" ..
dump(core.setting_getbool("creative_mode")) .. "]" ..
"checkbox[0.25,0.7;cb_enable_damage;" .. fgettext("Enable Damage") .. ";" ..
dump(core.setting_getbool("enable_damage")) .. "]" ..
"checkbox[0.25,1.15;cb_server_announce;" .. fgettext("Public") .. ";" ..
dump(core.setting_getbool("server_announce")) .. "]" ..
"label[0.25,2.2;" .. fgettext("Name/Password") .. "]" ..
"field[0.55,3.2;3.5,0.5;te_playername;;" ..
core.formspec_escape(core.setting_get("name")) .. "]" ..
"pwdfield[0.55,4;3.5,0.5;te_passwd;]"
local bind_addr = core.setting_get("bind_address")
if bind_addr ~= nil and bind_addr ~= "" then
retval = retval ..
"field[0.55,5.2;2.25,0.5;te_serveraddr;" .. fgettext("Bind Address") .. ";" ..
core.formspec_escape(core.setting_get("bind_address")) .. "]" ..
"field[2.8,5.2;1.25,0.5;te_serverport;" .. fgettext("Port") .. ";" ..
core.formspec_escape(core.setting_get("port")) .. "]"
else
retval = retval ..
"field[0.55,5.2;3.5,0.5;te_serverport;" .. fgettext("Server Port") .. ";" ..
core.formspec_escape(core.setting_get("port")) .. "]"
end
retval = retval ..
"textlist[4,0.25;7.5,3.7;srv_worlds;" ..
menu_render_worldlist() ..
";" .. index .. "]"
return retval
end
--------------------------------------------------------------------------------
local function main_button_handler(this, fields, name, tabdata)
local world_doubleclick = false
if fields["srv_worlds"] ~= nil then
local event = core.explode_textlist_event(fields["srv_worlds"])
local selected = core.get_textlist_index("srv_worlds")
menu_worldmt_legacy(selected)
if event.type == "DCL" then
world_doubleclick = true
end
if event.type == "CHG" then
core.setting_set("mainmenu_last_selected_world",
menudata.worldlist:get_raw_index(core.get_textlist_index("srv_worlds")))
return true
end
end
if menu_handle_key_up_down(fields,"srv_worlds","mainmenu_last_selected_world") then
return true
end
if fields["cb_creative_mode"] then
core.setting_set("creative_mode", fields["cb_creative_mode"])
local selected = core.get_textlist_index("srv_worlds")
menu_worldmt(selected, "creative_mode", fields["cb_creative_mode"])
return true
end
if fields["cb_enable_damage"] then
core.setting_set("enable_damage", fields["cb_enable_damage"])
local selected = core.get_textlist_index("srv_worlds")
menu_worldmt(selected, "enable_damage", fields["cb_enable_damage"])
return true
end
if fields["cb_server_announce"] then
core.setting_set("server_announce", fields["cb_server_announce"])
local selected = core.get_textlist_index("srv_worlds")
menu_worldmt(selected, "server_announce", fields["cb_server_announce"])
return true
end
if fields["start_server"] ~= nil or
world_doubleclick or
fields["key_enter"] then
local selected = core.get_textlist_index("srv_worlds")
gamedata.selected_world = menudata.worldlist:get_raw_index(selected)
if selected ~= nil and gamedata.selected_world ~= 0 then
gamedata.playername = fields["te_playername"]
gamedata.password = fields["te_passwd"]
gamedata.port = fields["te_serverport"]
gamedata.address = ""
core.setting_set("port",gamedata.port)
if fields["te_serveraddr"] ~= nil then
core.setting_set("bind_address",fields["te_serveraddr"])
end
--update last game
local world = menudata.worldlist:get_raw_element(gamedata.selected_world)
if world then
local game, index = gamemgr.find_by_gameid(world.gameid)
core.setting_set("menu_last_game", game.id)
end
core.start()
else
gamedata.errormessage =
fgettext("No world created or selected!")
end
return true
end
if fields["world_create"] ~= nil then
local create_world_dlg = create_create_world_dlg(true)
create_world_dlg:set_parent(this)
create_world_dlg:show()
this:hide()
return true
end
if fields["world_delete"] ~= nil then
local selected = core.get_textlist_index("srv_worlds")
if selected ~= nil and
selected <= menudata.worldlist:size() then
local world = menudata.worldlist:get_list()[selected]
if world ~= nil and
world.name ~= nil and
world.name ~= "" then
local index = menudata.worldlist:get_raw_index(selected)
local delete_world_dlg = create_delete_world_dlg(world.name,index)
delete_world_dlg:set_parent(this)
delete_world_dlg:show()
this:hide()
end
end
return true
end
if fields["world_configure"] ~= nil then
local selected = core.get_textlist_index("srv_worlds")
if selected ~= nil then
local configdialog =
create_configure_world_dlg(
menudata.worldlist:get_raw_index(selected))
if (configdialog ~= nil) then
configdialog:set_parent(this)
configdialog:show()
this:hide()
end
end
return true
end
return false
end
--------------------------------------------------------------------------------
return {
name = "server",
caption = fgettext("Server"),
cbf_formspec = get_formspec,
cbf_button_handler = main_button_handler,
on_change = nil
}
| gpl-3.0 |
NSAKEY/prosody-modules | mod_vjud/vcard.lib.lua | 32 | 9198 | -- Copyright (C) 2011-2012 Kim Alvefur
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
-- TODO
-- Fix folding.
local st = require "util.stanza";
local t_insert, t_concat = table.insert, table.concat;
local type = type;
local next, pairs, ipairs = next, pairs, ipairs;
local from_text, to_text, from_xep54, to_xep54;
local line_sep = "\n";
local vCard_dtd; -- See end of file
local function fold_line()
error "Not implemented" --TODO
end
local function unfold_line()
error "Not implemented"
-- gsub("\r?\n[ \t]([^\r\n])", "%1");
end
local function vCard_esc(s)
return s:gsub("[,:;\\]", "\\%1"):gsub("\n","\\n");
end
local function vCard_unesc(s)
return s:gsub("\\?[\\nt:;,]", {
["\\\\"] = "\\",
["\\n"] = "\n",
["\\r"] = "\r",
["\\t"] = "\t",
["\\:"] = ":", -- FIXME Shouldn't need to espace : in values, just params
["\\;"] = ";",
["\\,"] = ",",
[":"] = "\29",
[";"] = "\30",
[","] = "\31",
});
end
local function item_to_xep54(item)
local t = st.stanza(item.name, { xmlns = "vcard-temp" });
local prop_def = vCard_dtd[item.name];
if prop_def == "text" then
t:text(item[1]);
elseif type(prop_def) == "table" then
if prop_def.types and item.TYPE then
if type(item.TYPE) == "table" then
for _,v in pairs(prop_def.types) do
for _,typ in pairs(item.TYPE) do
if typ:upper() == v then
t:tag(v):up();
break;
end
end
end
else
t:tag(item.TYPE:upper()):up();
end
end
if prop_def.props then
for _,v in pairs(prop_def.props) do
if item[v] then
t:tag(v):up();
end
end
end
if prop_def.value then
t:tag(prop_def.value):text(item[1]):up();
elseif prop_def.values then
local prop_def_values = prop_def.values;
local repeat_last = prop_def_values.behaviour == "repeat-last" and prop_def_values[#prop_def_values];
for i=1,#item do
t:tag(prop_def.values[i] or repeat_last):text(item[i]):up();
end
end
end
return t;
end
local function vcard_to_xep54(vCard)
local t = st.stanza("vCard", { xmlns = "vcard-temp" });
for i=1,#vCard do
t:add_child(item_to_xep54(vCard[i]));
end
return t;
end
function to_xep54(vCards)
if not vCards[1] or vCards[1].name then
return vcard_to_xep54(vCards)
else
local t = st.stanza("xCard", { xmlns = "vcard-temp" });
for i=1,#vCards do
t:add_child(vcard_to_xep54(vCards[i]));
end
return t;
end
end
function from_text(data)
data = data -- unfold and remove empty lines
:gsub("\r\n","\n")
:gsub("\n ", "")
:gsub("\n\n+","\n");
local vCards = {};
local c; -- current item
for line in data:gmatch("[^\n]+") do
local line = vCard_unesc(line);
local name, params, value = line:match("^([-%a]+)(\30?[^\29]*)\29(.*)$");
value = value:gsub("\29",":");
if #params > 0 then
local _params = {};
for k,isval,v in params:gmatch("\30([^=]+)(=?)([^\30]*)") do
k = k:upper();
local _vt = {};
for _p in v:gmatch("[^\31]+") do
_vt[#_vt+1]=_p
_vt[_p]=true;
end
if isval == "=" then
_params[k]=_vt;
else
_params[k]=true;
end
end
params = _params;
end
if name == "BEGIN" and value == "VCARD" then
c = {};
vCards[#vCards+1] = c;
elseif name == "END" and value == "VCARD" then
c = nil;
elseif vCard_dtd[name] then
local dtd = vCard_dtd[name];
local p = { name = name };
c[#c+1]=p;
--c[name]=p;
local up = c;
c = p;
if dtd.types then
for _, t in ipairs(dtd.types) do
local t = t:lower();
if ( params.TYPE and params.TYPE[t] == true)
or params[t] == true then
c.TYPE=t;
end
end
end
if dtd.props then
for _, p in ipairs(dtd.props) do
if params[p] then
if params[p] == true then
c[p]=true;
else
for _, prop in ipairs(params[p]) do
c[p]=prop;
end
end
end
end
end
if dtd == "text" or dtd.value then
t_insert(c, value);
elseif dtd.values then
local value = "\30"..value;
for p in value:gmatch("\30([^\30]*)") do
t_insert(c, p);
end
end
c = up;
end
end
return vCards;
end
local function item_to_text(item)
local value = {};
for i=1,#item do
value[i] = vCard_esc(item[i]);
end
value = t_concat(value, ";");
local params = "";
for k,v in pairs(item) do
if type(k) == "string" and k ~= "name" then
params = params .. (";%s=%s"):format(k, type(v) == "table" and t_concat(v,",") or v);
end
end
return ("%s%s:%s"):format(item.name, params, value)
end
local function vcard_to_text(vcard)
local t={};
t_insert(t, "BEGIN:VCARD")
for i=1,#vcard do
t_insert(t, item_to_text(vcard[i]));
end
t_insert(t, "END:VCARD")
return t_concat(t, line_sep);
end
function to_text(vCards)
if vCards[1] and vCards[1].name then
return vcard_to_text(vCards)
else
local t = {};
for i=1,#vCards do
t[i]=vcard_to_text(vCards[i]);
end
return t_concat(t, line_sep);
end
end
local function from_xep54_item(item)
local prop_name = item.name;
local prop_def = vCard_dtd[prop_name];
local prop = { name = prop_name };
if prop_def == "text" then
prop[1] = item:get_text();
elseif type(prop_def) == "table" then
if prop_def.value then --single item
prop[1] = item:get_child_text(prop_def.value) or "";
elseif prop_def.values then --array
local value_names = prop_def.values;
if value_names.behaviour == "repeat-last" then
for i=1,#item.tags do
t_insert(prop, item.tags[i]:get_text() or "");
end
else
for i=1,#value_names do
t_insert(prop, item:get_child_text(value_names[i]) or "");
end
end
elseif prop_def.names then
local names = prop_def.names;
for i=1,#names do
if item:get_child(names[i]) then
prop[1] = names[i];
break;
end
end
end
if prop_def.props_verbatim then
for k,v in pairs(prop_def.props_verbatim) do
prop[k] = v;
end
end
if prop_def.types then
local types = prop_def.types;
prop.TYPE = {};
for i=1,#types do
if item:get_child(types[i]) then
t_insert(prop.TYPE, types[i]:lower());
end
end
if #prop.TYPE == 0 then
prop.TYPE = nil;
end
end
-- A key-value pair, within a key-value pair?
if prop_def.props then
local params = prop_def.props;
for i=1,#params do
local name = params[i]
local data = item:get_child_text(name);
if data then
prop[name] = prop[name] or {};
t_insert(prop[name], data);
end
end
end
else
return nil
end
return prop;
end
local function from_xep54_vCard(vCard)
local tags = vCard.tags;
local t = {};
for i=1,#tags do
t_insert(t, from_xep54_item(tags[i]));
end
return t
end
function from_xep54(vCard)
if vCard.attr.xmlns ~= "vcard-temp" then
return nil, "wrong-xmlns";
end
if vCard.name == "xCard" then -- A collection of vCards
local t = {};
local vCards = vCard.tags;
for i=1,#vCards do
t[i] = from_xep54_vCard(vCards[i]);
end
return t
elseif vCard.name == "vCard" then -- A single vCard
return from_xep54_vCard(vCard)
end
end
-- This was adapted from http://xmpp.org/extensions/xep-0054.html#dtd
vCard_dtd = {
VERSION = "text", --MUST be 3.0, so parsing is redundant
FN = "text",
N = {
values = {
"FAMILY",
"GIVEN",
"MIDDLE",
"PREFIX",
"SUFFIX",
},
},
NICKNAME = "text",
PHOTO = {
props_verbatim = { ENCODING = { "b" } },
props = { "TYPE" },
value = "BINVAL", --{ "EXTVAL", },
},
BDAY = "text",
ADR = {
types = {
"HOME",
"WORK",
"POSTAL",
"PARCEL",
"DOM",
"INTL",
"PREF",
},
values = {
"POBOX",
"EXTADD",
"STREET",
"LOCALITY",
"REGION",
"PCODE",
"CTRY",
}
},
LABEL = {
types = {
"HOME",
"WORK",
"POSTAL",
"PARCEL",
"DOM",
"INTL",
"PREF",
},
value = "LINE",
},
TEL = {
types = {
"HOME",
"WORK",
"VOICE",
"FAX",
"PAGER",
"MSG",
"CELL",
"VIDEO",
"BBS",
"MODEM",
"ISDN",
"PCS",
"PREF",
},
value = "NUMBER",
},
EMAIL = {
types = {
"HOME",
"WORK",
"INTERNET",
"PREF",
"X400",
},
value = "USERID",
},
JABBERID = "text",
MAILER = "text",
TZ = "text",
GEO = {
values = {
"LAT",
"LON",
},
},
TITLE = "text",
ROLE = "text",
LOGO = "copy of PHOTO",
AGENT = "text",
ORG = {
values = {
behaviour = "repeat-last",
"ORGNAME",
"ORGUNIT",
}
},
CATEGORIES = {
values = "KEYWORD",
},
NOTE = "text",
PRODID = "text",
REV = "text",
SORTSTRING = "text",
SOUND = "copy of PHOTO",
UID = "text",
URL = "text",
CLASS = {
names = { -- The item.name is the value if it's one of these.
"PUBLIC",
"PRIVATE",
"CONFIDENTIAL",
},
},
KEY = {
props = { "TYPE" },
value = "CRED",
},
DESC = "text",
};
vCard_dtd.LOGO = vCard_dtd.PHOTO;
vCard_dtd.SOUND = vCard_dtd.PHOTO;
return {
from_text = from_text;
to_text = to_text;
from_xep54 = from_xep54;
to_xep54 = to_xep54;
-- COMPAT:
lua_to_text = to_text;
lua_to_xep54 = to_xep54;
text_to_lua = from_text;
text_to_xep54 = function (...) return to_xep54(from_text(...)); end;
xep54_to_lua = from_xep54;
xep54_to_text = function (...) return to_text(from_xep54(...)) end;
};
| mit |
tianxiawuzhei/cocos-quick-lua | quick/framework/cc/ui/UIPushButton.lua | 2 | 4731 |
--[[
Copyright (c) 2011-2014 chukong-inc.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
]]
--------------------------------
-- @module UIPushButton
--[[--
quick 按钮控件
]]
local UIButton = import(".UIButton")
local UIPushButton = class("UIPushButton", UIButton)
UIPushButton.NORMAL = "normal"
UIPushButton.PRESSED = "pressed"
UIPushButton.DISABLED = "disabled"
-- start --
--------------------------------
-- 按钮控件构建函数
-- @function [parent=#UIPushButton] ctor
-- @param table images 各种状态的图片
-- @param table options 参数表 其中scale9为是否缩放
--[[--
按钮控件构建函数
状态值:
- normal 正常状态
- pressed 按下状态
- disabled 无效状态
]]
-- end --
function UIPushButton:ctor(images, options)
UIPushButton.super.ctor(self, {
{name = "disable", from = {"normal", "pressed"}, to = "disabled"},
{name = "enable", from = {"disabled"}, to = "normal"},
{name = "press", from = "normal", to = "pressed"},
{name = "release", from = "pressed", to = "normal"},
}, "normal", options)
if type(images) ~= "table" then images = {normal = images} end
self:setButtonImage(UIPushButton.NORMAL, images["normal"], true)
self:setButtonImage(UIPushButton.PRESSED, images["pressed"], true)
self:setButtonImage(UIPushButton.DISABLED, images["disabled"], true)
self.args_ = {images, options}
end
function UIPushButton:setButtonImage(state, image, ignoreEmpty)
assert(state == UIPushButton.NORMAL
or state == UIPushButton.PRESSED
or state == UIPushButton.DISABLED,
string.format("UIPushButton:setButtonImage() - invalid state %s", tostring(state)))
UIPushButton.super.setButtonImage(self, state, image, ignoreEmpty)
if state == UIPushButton.NORMAL then
if not self.images_[UIPushButton.PRESSED] then
self.images_[UIPushButton.PRESSED] = image
end
if not self.images_[UIPushButton.DISABLED] then
self.images_[UIPushButton.DISABLED] = image
end
end
return self
end
function UIPushButton:onTouch_(event)
local name, x, y = event.name, event.x, event.y
if name == "began" then
self.touchBeganX = x
self.touchBeganY = y
if self:checkTouchInSprite_(x, y) then
self.fsm_:doEvent("press")
self:dispatchEvent({name = UIButton.PRESSED_EVENT, x = x, y = y, touchInTarget = true})
return true
end
return false
end
-- must the begin point and current point in Button Sprite
local touchInTarget = self:checkTouchInSprite_(self.touchBeganX, self.touchBeganY)
and self:checkTouchInSprite_(x, y)
if name == "moved" then
-- if touchInTarget and self.fsm_:canDoEvent("press") then
-- self.fsm_:doEvent("press")
-- self:dispatchEvent({name = UIButton.PRESSED_EVENT, x = x, y = y, touchInTarget = true})
-- printf("UIPushButton: moved")
if not touchInTarget and self.fsm_:canDoEvent("release") then
self.fsm_:doEvent("release")
self:dispatchEvent({name = UIButton.RELEASE_EVENT, x = x, y = y, touchInTarget = false})
end
else
if self.fsm_:canDoEvent("release") then
self.fsm_:doEvent("release")
self:dispatchEvent({name = UIButton.RELEASE_EVENT, x = x, y = y, touchInTarget = touchInTarget})
end
if name == "ended" and touchInTarget then
self:dispatchEvent({name = UIButton.CLICKED_EVENT, x = x, y = y, touchInTarget = true})
end
end
end
function UIPushButton:createCloneInstance_()
return UIPushButton.new(unpack(self.args_))
end
return UIPushButton
| mit |
mqmaker/witi-openwrt | package/ramips/ui/luci-mtk/src/applications/luci-olsr/luasrc/model/cbi/olsr/olsrdplugins6.lua | 32 | 7312 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2009 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local ip = require "luci.ip"
local fs = require "nixio.fs"
if arg[1] then
mp = Map("olsrd", translate("OLSR - Plugins"))
p = mp:section(TypedSection, "LoadPlugin", translate("Plugin configuration"))
p:depends("library", arg[1])
p.anonymous = true
ign = p:option(Flag, "ignore", translate("Enable"))
ign.enabled = "0"
ign.disabled = "1"
ign.rmempty = false
function ign.cfgvalue(self, section)
return Flag.cfgvalue(self, section) or "0"
end
lib = p:option(DummyValue, "library", translate("Library"))
lib.default = arg[1]
local function Range(x,y)
local t = {}
for i = x, y do t[#t+1] = i end
return t
end
local function Cidr2IpMask(val)
if val then
for i = 1, #val do
local cidr = ip.IPv4(val[i]) or ip.IPv6(val[i])
if cidr then
val[i] = cidr:network():string() .. " " .. cidr:mask():string()
end
end
return val
end
end
local function IpMask2Cidr(val)
if val then
for i = 1, #val do
local ip, mask = val[i]:gmatch("([^%s]+)%s+([^%s]+)")()
local cidr
if ip and mask and ip:match(":") then
cidr = ip.IPv6(ip, mask)
elseif ip and mask then
cidr = ip.IPv4(ip, mask)
end
if cidr then
val[i] = cidr:string()
end
end
return val
end
end
local knownPlParams = {
["olsrd_bmf.so.1.5.3"] = {
{ Value, "BmfInterface", "bmf0" },
{ Value, "BmfInterfaceIp", "10.10.10.234/24" },
{ Flag, "DoLocalBroadcast", "no" },
{ Flag, "CapturePacketsOnOlsrInterfaces", "yes" },
{ ListValue, "BmfMechanism", { "UnicastPromiscuous", "Broadcast" } },
{ Value, "BroadcastRetransmitCount", "2" },
{ Value, "FanOutLimit", "4" },
{ DynamicList, "NonOlsrIf", "br-lan" }
},
["olsrd_dyn_gw.so.0.4"] = {
{ Value, "Interval", "40" },
{ DynamicList, "Ping", "141.1.1.1" },
{ DynamicList, "HNA", "192.168.80.0/24", IpMask2Cidr, Cidr2IpMask }
},
["olsrd_httpinfo.so.0.1"] = {
{ Value, "port", "80" },
{ DynamicList, "Host", "163.24.87.3" },
{ DynamicList, "Net", "0.0.0.0/0", Cidr2IpMask }
},
["olsrd_nameservice.so.0.3"] = {
{ DynamicList, "name", "my-name.mesh" },
{ DynamicList, "hosts", "1.2.3.4 name-for-other-interface.mesh" },
{ Value, "suffix", ".olsr" },
{ Value, "hosts_file", "/path/to/hosts_file" },
{ Value, "add_hosts", "/path/to/file" },
{ Value, "dns_server", "141.1.1.1" },
{ Value, "resolv_file", "/path/to/resolv.conf" },
{ Value, "interval", "120" },
{ Value, "timeout", "240" },
{ Value, "lat", "12.123" },
{ Value, "lon", "12.123" },
{ Value, "latlon_file", "/var/run/latlon.js.ipv6" },
{ Value, "latlon_infile", "/var/run/gps.txt" },
{ Value, "sighup_pid_file", "/var/run/dnsmasq.pid" },
{ Value, "name_change_script", "/usr/local/bin/announce_new_hosts.sh" },
{ DynamicList, "service", "http://me.olsr:80|tcp|my little homepage" },
{ Value, "services_file", "/var/run/services_olsr" },
{ Value, "services_change_script", "/usr/local/bin/announce_new_services.sh" },
{ DynamicList, "mac", "xx:xx:xx:xx:xx:xx[,0-255]" },
{ Value, "macs_file", "/path/to/macs_file" },
{ Value, "macs_change_script", "/path/to/script" }
},
["olsrd_quagga.so.0.2.2"] = {
{ StaticList, "redistribute", {
"system", "kernel", "connect", "static", "rip", "ripng", "ospf",
"ospf6", "isis", "bgp", "hsls"
} },
{ ListValue, "ExportRoutes", { "only", "both" } },
{ Flag, "LocalPref", "true" },
{ Value, "Distance", Range(0,255) }
},
["olsrd_secure.so.0.5"] = {
{ Value, "Keyfile", "/etc/private-olsr.key" }
},
["olsrd_txtinfo.so.0.1"] = {
{ Value, "accept", "::1/128" }
},
["olsrd_jsoninfo.so.0.0"] = {
{ Value, "accept", "::1/128" },
{ Value, "port", "9090" },
{ Value, "UUIDFile", "/etc/olsrd/olsrd.uuid.ipv6" },
},
["olsrd_watchdog.so.0.1"] = {
{ Value, "file", "/var/run/olsrd.watchdog.ipv6" },
{ Value, "interval", "30" }
},
["olsrd_mdns.so.1.0.0"] = {
{ DynamicList, "NonOlsrIf", "lan" }
},
["olsrd_p2pd.so.0.1.0"] = {
{ DynamicList, "NonOlsrIf", "lan" },
{ Value, "P2pdTtl", "10" }
},
["olsrd_arprefresh.so.0.1"] = {},
["olsrd_dot_draw.so.0.3"] = {},
["olsrd_dyn_gw_plain.so.0.4"] = {},
["olsrd_pgraph.so.1.1"] = {},
["olsrd_tas.so.0.1"] = {}
}
-- build plugin options with dependencies
if knownPlParams[arg[1]] then
for _, option in ipairs(knownPlParams[arg[1]]) do
local otype, name, default, uci2cbi, cbi2uci = unpack(option)
local values
if type(default) == "table" then
values = default
default = default[1]
end
if otype == Flag then
local bool = p:option( Flag, name, name )
if default == "yes" or default == "no" then
bool.enabled = "yes"
bool.disabled = "no"
elseif default == "on" or default == "off" then
bool.enabled = "on"
bool.disabled = "off"
elseif default == "1" or default == "0" then
bool.enabled = "1"
bool.disabled = "0"
else
bool.enabled = "true"
bool.disabled = "false"
end
bool.optional = true
bool.default = default
bool:depends({ library = plugin })
else
local field = p:option( otype, name, name )
if values then
for _, value in ipairs(values) do
field:value( value )
end
end
if type(uci2cbi) == "function" then
function field.cfgvalue(self, section)
return uci2cbi(otype.cfgvalue(self, section))
end
end
if type(cbi2uci) == "function" then
function field.formvalue(self, section)
return cbi2uci(otype.formvalue(self, section))
end
end
field.optional = true
field.default = default
--field:depends({ library = arg[1] })
end
end
end
return mp
else
mpi = Map("olsrd6", translate("OLSR - Plugins"))
local plugins = {}
mpi.uci:foreach("olsrd6", "LoadPlugin",
function(section)
if section.library and not plugins[section.library] then
plugins[section.library] = true
end
end
)
-- create a loadplugin section for each found plugin
for v in fs.dir("/usr/lib") do
if v:sub(1, 6) == "olsrd_" then
if not plugins[v] then
mpi.uci:section(
"olsrd6", "LoadPlugin", nil,
{ library = v, ignore = 1 }
)
end
end
end
t = mpi:section( TypedSection, "LoadPlugin", translate("Plugins") )
t.anonymous = true
t.template = "cbi/tblsection"
t.override_scheme = true
function t.extedit(self, section)
local lib = self.map:get(section, "library") or ""
return luci.dispatcher.build_url("admin", "services", "olsrd6", "plugins") .. "/" .. lib
end
ign = t:option( Flag, "ignore", translate("Enabled") )
ign.enabled = "0"
ign.disabled = "1"
ign.rmempty = false
function ign.cfgvalue(self, section)
return Flag.cfgvalue(self, section) or "0"
end
t:option( DummyValue, "library", translate("Library") )
return mpi
end
| gpl-2.0 |
hleuwer/luayats | examples/rstp-test-play-pathcost.lua | 1 | 3403 | require "yats.rstp.play"
linkToBreak = tonumber(os.getenv("TK_LINK")) or 3
--linkToBreak = 1
NumberOfBridges = 7
-- Setting test non nil provides additional output.
--test = true
test = nil
-- Init the yats random generator.
yats.log:info("Init random generator.")
yats.sim:SetRand(10)
yats.sim:setSlotLength(1e-3)
-- logging options{"DEBUG", "INFO", "WARN", "ERROR", "FATAL"}
yats.ieeebridge.pdulog:setLevel("FATAL")
yats.ieeebridge.log:setLevel("ERROR")
-- Reset simulation time.
yats.log:info("Reset simulation time.")
yats.sim:ResetTime()
--
--sources--
--
start_delay =1
proc_time = 3
basemac={
"110000",
"220000",
"330000",
"340000",
"350000",
"360000",
"330700"
}
priorities = {
{[0] = 10},
{[0] = 12},
{[0] = 11},
{[0] = 12},
{[0] = 12},
{[0] = 12},
{[0] = 12}
}
bridge = {}
i=1
bridge[i] = yats.bridge{
"bridge["..i.."]",
process_speed = proc_time,
nport=2,
basemac=basemac[i],
vlans = priorities[i],
memberset = {[0]= {1,1,1,1}},
start_delay=start_delay or yats.random(1,2000),
out = {
{"bridge[7]","in"..2},
{"bridge["..(i+1).."]","in"..1},
}
}
for _,i in ipairs{2, 3, 4, 5, 6}
do
bridge[i] = yats.bridge{
"bridge["..i.."]",
process_speed = proc_time,
nport=2,
basemac=basemac[i],
vlans = priorities[i],
memberset = {[0]= {1,1,1,1}},
start_delay=start_delay or yats.random(1,2000),
out = {
{"bridge["..(i-1).."]","in"..2},
{"bridge["..(i+1).."]","in"..1}
}
}
end
i=7
bridge[i] = yats.bridge{
"bridge["..i.."]",
process_speed = proc_time,
nport=2,
basemac=basemac[i],
vlans = priorities[i],
memberset = {[0]= {1,1,1,1}},
start_delay=start_delay or yats.random(1,2000),
out = {
{"bridge["..(i-1).."]","in"..2},
{"bridge[1]","in"..1}
}
}
-- Connection management
yats.log:debug("connecting")
yats.sim:connect()
for i = 1, 7 do
bridge[i]:stateLog({1,2}, true)
bridge[i]:setCallback{
rxbpdu = playEventCallback,
portstate = playEventCallback,
-- flush = playEventCallback
}
end
yats.sim:run(10000, 10000)
for i = 1,7 do bridge[i]:show_port(0) end
-- Produce test result.
fwddelay = 6
maxage = 8
for _, i in ipairs{ 1, 2, 3, 4, 5, 6, 7 } do
assert(bridge[i]:config_stp(0, "max_age", maxage))
assert(bridge[i]:config_stp(0, "forward_delay", fwddelay))
end
for i = 1,7 do bridge[i]:show_port(0) end
yats.sim:run(90000, 10000)
for i = 1,7 do bridge[i]:show_port(0) end
print("Now we increase the pathcost of link "..linkToBreak)
local s2c = yats.ieeebridge.speed2pcost
if (linkToBreak < NumberOfBridges) then
bridge[linkToBreak]:config_port(0,{2}, "admin_port_path_cost", s2c(10))
bridge[linkToBreak+1]:config_port(0,{1}, "admin_port_path_cost", s2c(10))
else
bridge[linkToBreak]:config_port(0,{2}, "admin_port_path_cost", s2c(10))
bridge[1]:config_port(0,{1}, "admin_port_path_cost", s2c(10))
end
yats.sim:run(100000, 20000)
for i = 1,7 do bridge[i]:show_port(0) end
print("Now we decrease the pathcost of link "..linkToBreak)
if (linkToBreak < NumberOfBridges) then
bridge[linkToBreak]:config_port(0,{2}, "admin_port_path_cost", s2c(100))
bridge[linkToBreak+1]:config_port(0,{1}, "admin_port_path_cost", s2c(100))
else
bridge[linkToBreak]:config_port(0,{2}, "admin_port_path_cost", s2c(100))
bridge[1]:config_port(0,{1}, "admin_port_path_cost", s2c(100))
end
yats.sim:run(100000, 20000)
for i = 1,7 do bridge[i]:show_port(0) end
| gpl-2.0 |
bigdogmat/wire | lua/wire/client/cl_wire_map_interface.lua | 17 | 2510 | -- The client part of the wire map interface.
-- It's for the clientside wire ports adding and removing, also for the rendering stuff.
-- It's in in this folder, because point entities are serverside only.
-- Removing wire stuff and other changes that were done.
local OverRiddenEnts = {}
local function RemoveWire(Entity)
if (!IsValid(Entity)) then return end
local ID = Entity:EntIndex()
Entity._NextRBUpdate = nil
Entity.ppp = nil
OverRiddenEnts[ID] = nil
WireLib._RemoveWire(ID) -- Remove entity, so it doesn't count as a wire able entity anymore.
for key, value in pairs(Entity._Settings_WireMapInterfaceEnt or {}) do
if (!value or (value == 0) or (value == "")) then
Entity[key] = nil
else
Entity[key] = value
end
end
Entity._Settings_WireMapInterfaceEnt = nil
end
-- Adding wire stuff and changes.
usermessage.Hook("WireMapInterfaceEnt", function(data)
local Entity = data:ReadEntity()
local Flags = data:ReadChar()
local Remove = (Flags == -1)
if (!WIRE_CLIENT_INSTALLED) then return end
if (!IsValid(Entity)) then return end
if (Remove) then
RemoveWire(Entity)
return
end
Entity._Settings_WireMapInterfaceEnt = {}
if (bit.band(Flags, 1) > 0) then -- Protect in-/output entities from non-wire tools
Entity._Settings_WireMapInterfaceEnt.m_tblToolsAllowed = Entity.m_tblToolsAllowed or false
Entity.m_tblToolsAllowed = {"wire", "wire_adv", "wire_debugger", "wire_wirelink", "gui_wiring", "multi_wire"}
end
if (bit.band(Flags, 2) > 0) then -- Protect in-/output entities from the physgun
Entity._Settings_WireMapInterfaceEnt.PhysgunDisabled = Entity.PhysgunDisabled or false
Entity.PhysgunDisabled = true
end
local ID = Entity:EntIndex()
if (bit.band(Flags, 32) > 0) then -- Render Wires
OverRiddenEnts[ID] = true
else
OverRiddenEnts[ID] = nil
end
end)
-- Render bounds updating
hook.Add("Think", "WireMapInterface_Think", function()
for ID, _ in pairs(OverRiddenEnts) do
local self = Entity(ID)
if (!IsValid(self) or !WIRE_CLIENT_INSTALLED) then
OverRiddenEnts[ID] = nil
return
end
if (CurTime() >= (self._NextRBUpdate or 0)) then
self._NextRBUpdate = CurTime() + math.random(30,100) / 10
Wire_UpdateRenderBounds(self)
end
end
end)
-- Rendering
hook.Add("PostDrawOpaqueRenderables", "WireMapInterface_Draw", function()
for ID, _ in pairs(OverRiddenEnts) do
local self = Entity(ID)
if (!IsValid(self) or !WIRE_CLIENT_INSTALLED) then
OverRiddenEnts[ID] = nil
return
end
Wire_Render(self)
end
end)
| apache-2.0 |
FrisKAY/MineOS_Server | Applications/reload.lua | 1 | 1428 | local seri = require("serialization")
local fs = require("filesystem")
local github = require("github")
local args = {...}
---------------------------------------------------------------------------------------
local function printUsage()
print(" ")
print(" Использование:")
print(" reload <путь к файлу> - перезагружает файл с GitHub автора")
print(" ")
end
local function readFile()
local readedFile = ""
local file = io.open("System/OS/Applications.txt", "r")
readedFile = file:read("*a")
readedFile = seri.unserialize(readedFile)
file:close()
return readedFile
end
local function getGitHubUrl(name)
local massiv = readFile()
for i = 1, #massiv do
--print(massiv[i]["name"])
if massiv[i]["name"] == name then
return massiv[i]["url"]
end
end
end
local function reloadFromGitHub(url, name)
github.get("https://raw.githubusercontent.com/" .. url, name)
print(" ")
print("Файл " .. name .. " перезагружен из https://raw.githubusercontent.com/" .. url)
print(" ")
end
---------------------------------------------------------------------------------------
if #args < 1 then printUsage(); return end
local url = getGitHubUrl(args[1])
if not url then print(" "); io.stderr:write("На GitHub автора отсутствует указанный файл."); print(" ") end
reloadFromGitHub(url, args[1])
| gpl-3.0 |
cshore/luci | applications/luci-app-shadowsocks-libev/luasrc/model/cbi/shadowsocks-libev.lua | 39 | 3926 | -- Copyright 2015 Jian Chang <aa65535@live.com>
-- Licensed to the public under the Apache License 2.0.
local m, s, o, e, a
if luci.sys.call("pidof ss-redir >/dev/null") == 0 then
m = Map("shadowsocks-libev", translate("ShadowSocks-libev"), translate("ShadowSocks-libev is running"))
else
m = Map("shadowsocks-libev", translate("ShadowSocks-libev"), translate("ShadowSocks-libev is not running"))
end
e = {
"table",
"rc4",
"rc4-md5",
"aes-128-cfb",
"aes-192-cfb",
"aes-256-cfb",
"bf-cfb",
"camellia-128-cfb",
"camellia-192-cfb",
"camellia-256-cfb",
"cast5-cfb",
"des-cfb",
"idea-cfb",
"rc2-cfb",
"seed-cfb",
"salsa20",
"chacha20",
}
-- Global Setting
s = m:section(TypedSection, "shadowsocks-libev", translate("Global Setting"))
s.anonymous = true
o = s:option(Flag, "enable", translate("Enable"))
o.default = 1
o.rmempty = false
o = s:option(Value, "server", translate("Server Address"))
o.datatype = "ipaddr"
o.rmempty = false
o = s:option(Value, "server_port", translate("Server Port"))
o.datatype = "port"
o.rmempty = false
o = s:option(Value, "local_port", translate("Local Port"))
o.datatype = "port"
o.default = 1080
o.rmempty = false
o = s:option(Value, "timeout", translate("Connection Timeout"))
o.datatype = "uinteger"
o.default = 60
o.rmempty = false
o = s:option(Value, "password", translate("Password"))
o.password = true
o.rmempty = false
o = s:option(ListValue, "encrypt_method", translate("Encrypt Method"))
for i,v in ipairs(e) do
o:value(v)
end
o.rmempty = false
o = s:option(Value, "ignore_list", translate("Ignore List"))
o:value("/dev/null", translate("Disabled"))
o.default = "/dev/null"
o.rmempty = false
-- UDP Relay
s = m:section(TypedSection, "shadowsocks-libev", translate("UDP Relay"))
s.anonymous = true
o = s:option(ListValue, "udp_mode", translate("Relay Mode"))
o:value("0", translate("Disabled"))
o:value("1", translate("Enabled"))
o:value("2", translate("Custom"))
o.default = 0
o.rmempty = false
o = s:option(Value, "udp_server", translate("Server Address"))
o.datatype = "ipaddr"
o:depends("udp_mode", 2)
o = s:option(Value, "udp_server_port", translate("Server Port"))
o.datatype = "port"
o:depends("udp_mode", 2)
o = s:option(Value, "udp_local_port", translate("Local Port"))
o.datatype = "port"
o.default = 1081
o:depends("udp_mode", 2)
o = s:option(Value, "udp_timeout", translate("Connection Timeout"))
o.datatype = "uinteger"
o.default = 60
o:depends("udp_mode", 2)
o = s:option(Value, "udp_password", translate("Password"))
o.password = true
o:depends("udp_mode", 2)
o = s:option(ListValue, "udp_encrypt_method", translate("Encrypt Method"))
for i,v in ipairs(e) do
o:value(v)
end
o:depends("udp_mode", 2)
-- UDP Forward
s = m:section(TypedSection, "shadowsocks-libev", translate("UDP Forward"))
s.anonymous = true
o = s:option(Flag, "tunnel_enable", translate("Enable"))
o.default = 1
o.rmempty = false
o = s:option(Value, "tunnel_port", translate("UDP Local Port"))
o.datatype = "port"
o.default = 5300
o = s:option(Value, "tunnel_forward", translate("Forwarding Tunnel"))
o.default = "8.8.4.4:53"
-- Access Control
s = m:section(TypedSection, "shadowsocks-libev", translate("Access Control"))
s.anonymous = true
s:tab("lan_ac", translate("LAN"))
o = s:taboption("lan_ac", ListValue, "lan_ac_mode", translate("Access Control"))
o:value("0", translate("Disabled"))
o:value("1", translate("Allow listed only"))
o:value("2", translate("Allow all except listed"))
o.default = 0
o.rmempty = false
a = luci.sys.net.arptable() or {}
o = s:taboption("lan_ac", DynamicList, "lan_ac_ip", translate("LAN IP List"))
o.datatype = "ipaddr"
for i,v in ipairs(a) do
o:value(v["IP address"])
end
s:tab("wan_ac", translate("WAN"))
o = s:taboption("wan_ac", DynamicList, "wan_bp_ip", translate("Bypassed IP"))
o.datatype = "ip4addr"
o = s:taboption("wan_ac", DynamicList, "wan_fw_ip", translate("Forwarded IP"))
o.datatype = "ip4addr"
return m
| apache-2.0 |
boundary/boundary-nagios-plugins | metric_job_test.lua | 1 | 1145 | -- Copyright 2014 Boundary,Inc.
--
-- 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.
require("metric_job")
require("metric")
require("utils")
local LuaUnit = require("luaunit")
TestMetricJob = {}
function TestMetricJob:testConstructor()
local m = Metric:new()
local j = MetricJob:new()
assertEquals(j ~= nil,true)
end
function TestMetricJob:testRun()
local j = MetricJob:new()
assertEquals(j ~= nil,true)
end
function TestMetricJob:testUpdate()
local j = MetricJob:new()
local m = Metric:new()
local e = ExecProc:new()
e:setPath("echo")
m:setExec(e)
j:setMetric(m)
j:run()
assertEquals(1,1)
end
LuaUnit:run() | apache-2.0 |
dicebox/minetest-france | mods/farming/cocoa.lua | 3 | 4343 |
local S = farming.intllib
-- place cocoa
function place_cocoa(itemstack, placer, pointed_thing, plantname)
local pt = pointed_thing
-- check if pointing at a node
if not pt or pt.type ~= "node" then
return
end
local under = minetest.get_node(pt.under)
-- return if any of the nodes are not registered
if not minetest.registered_nodes[under.name] then
return
end
-- am I right-clicking on something that has a custom on_place set?
-- thanks to Krock for helping with this issue :)
local def = minetest.registered_nodes[under.name]
if def and def.on_rightclick then
return def.on_rightclick(pt.under, under, placer, itemstack)
end
-- check if pointing at jungletree
if under.name ~= "default:jungletree"
or minetest.get_node(pt.above).name ~= "air" then
return
end
-- add the node and remove 1 item from the itemstack
minetest.set_node(pt.above, {name = plantname})
minetest.sound_play("default_place_node", {pos = pt.above, gain = 1.0})
if not minetest.setting_getbool("creative_mode") then
itemstack:take_item()
-- check for refill
if itemstack:get_count() == 0 then
minetest.after(0.20,
farming.refill_plant,
placer,
"farming:cocoa_beans",
placer:get_wield_index()
)
end
end
return itemstack
end
-- cocoa beans
minetest.register_craftitem("farming:cocoa_beans", {
description = S("Cocoa Beans"),
inventory_image = "farming_cocoa_beans.png",
on_place = function(itemstack, placer, pointed_thing)
return place_cocoa(itemstack, placer, pointed_thing, "farming:cocoa_1")
end,
})
minetest.register_craft( {
output = "dye:brown 2",
recipe = {
{ "farming:cocoa_beans" },
}
})
-- chocolate cookie
minetest.register_craftitem("farming:cookie", {
description = S("Cookie"),
inventory_image = "farming_cookie.png",
on_use = minetest.item_eat(2),
})
minetest.register_craft( {
output = "farming:cookie 8",
recipe = {
{ "farming:wheat", "farming:cocoa_beans", "farming:wheat" },
}
})
-- bar of dark chocolate (thanks to Ice Pandora for her deviantart.com chocolate tutorial)
minetest.register_craftitem("farming:chocolate_dark", {
description = S("Bar of Dark Chocolate"),
inventory_image = "farming_chocolate_dark.png",
on_use = minetest.item_eat(3),
})
minetest.register_craft( {
output = "farming:chocolate_dark",
recipe = {
{ "farming:cocoa_beans", "farming:cocoa_beans", "farming:cocoa_beans" },
}
})
-- cocoa definition
local crop_def = {
drawtype = "plantlike",
tiles = {"farming_cocoa_1.png"},
paramtype = "light",
walkable = true,
drop = {
items = {
{items = {'farming:cocoa_beans 1'}, rarity = 2},
}
},
selection_box = {
type = "fixed",
fixed = {-0.3, -0.5, -0.3, 0.3, 0.5, 0.3}
},
groups = {
snappy = 3, flammable = 2, plant = 1, growing = 1,
not_in_creative_inventory=1, leafdecay = 1, leafdecay_drop = 1
},
sounds = default.node_sound_leaves_defaults()
}
-- stage 1
minetest.register_node("farming:cocoa_1", table.copy(crop_def))
-- stage2
crop_def.tiles = {"farming_cocoa_2.png"}
crop_def.drop = {
items = {
{items = {'farming:cocoa_beans 1'}, rarity = 1},
}
}
minetest.register_node("farming:cocoa_2", table.copy(crop_def))
-- stage 3 (final)
crop_def.tiles = {"farming_cocoa_3.png"}
crop_def.groups.growing = 0
crop_def.drop = {
items = {
{items = {'farming:cocoa_beans 2'}, rarity = 1},
{items = {'farming:cocoa_beans 1'}, rarity = 2},
}
}
minetest.register_node("farming:cocoa_3", table.copy(crop_def))
-- add random cocoa pods to jungle tree's
minetest.register_on_generated(function(minp, maxp)
if maxp.y < 0 then
return
end
local pos, dir
local cocoa = minetest.find_nodes_in_area(minp, maxp, "default:jungletree")
for n = 1, #cocoa do
pos = cocoa[n]
if minetest.find_node_near(pos, 1,
{"default:jungleleaves", "moretrees:jungletree_leaves_green"}) then
dir = math.random(1, 80)
if dir == 1 then
pos.x = pos.x + 1
elseif dir == 2 then
pos.x = pos.x - 1
elseif dir == 3 then
pos.z = pos.z + 1
elseif dir == 4 then
pos.z = pos.z -1
end
if dir < 5
and minetest.get_node(pos).name == "air"
and minetest.get_node_light(pos) > 12 then
--print ("Cocoa Pod added at " .. minetest.pos_to_string(pos))
minetest.swap_node(pos, {
name = "farming:cocoa_" .. tostring(math.random(1, 3))
})
end
end
end
end)
| gpl-3.0 |
pkulchenko/ZeroBraneEduPack | moai-samples/live-coding-simple/main.lua | 2 | 1032 | if not initialized then
MOAISim.openWindow("Live coding", 320, 480)
local viewport = MOAIViewport.new()
viewport:setSize(320, 480)
viewport:setScale(320, 480)
local gfxQuad = MOAIGfxQuad2D.new()
gfxQuad:setTexture("zbstudio.png")
gfxQuad:setRect(-32, -32, 32, 32)
prop1 = MOAIProp2D.new()
prop1:setDeck(gfxQuad)
prop2 = MOAIProp2D.new()
prop2:setDeck(gfxQuad)
local layer = MOAILayer2D.new()
layer:setViewport(viewport)
layer:insertProp(prop1)
layer:insertProp(prop2)
MOAISim.pushRenderPass(layer)
local thread = MOAICoroutine.new()
thread:run(function()
while true do
update()
coroutine.yield()
end
end)
initialized = true
end
function update()
prop1:setLoc(40, 80)
prop2:setLoc(-40, -120)
if MOAIGfxDevice.setClearColor then
MOAIGfxDevice.setClearColor(0.80,0.80,0.90,1)
else -- MOAI 1.4 changed setClearColor interface
MOAIGfxDevice.getFrameBuffer():setClearColor(0.80,0.80,0.90,1)
end
end
| mit |
arventwei/WioEngine | Tools/jamplus/src/luaplus/Src/Modules/luasec/src/ssl.lua | 1 | 4470 | ------------------------------------------------------------------------------
-- LuaSec 0.5
-- Copyright (C) 2006-2014 Bruno Silvestre
--
------------------------------------------------------------------------------
local _M = {}
local core = require("ssl.core")
local context = require("ssl.context")
local x509 = require("ssl.x509")
_VERSION = "0.5"
_COPYRIGHT = core.copyright()
-- Export
loadcertificate = x509.load
-- We must prevent the contexts to be collected before the connections,
-- otherwise the C registry will be cleared.
local registry = setmetatable({}, {__mode="k"})
--
--
--
local function optexec(func, param, ctx)
if param then
if type(param) == "table" then
return func(ctx, (unpack or table.unpack)(param))
else
return func(ctx, param)
end
end
return true
end
--
--
--
function _M.newcontext(cfg)
local succ, msg, ctx
-- Create the context
ctx, msg = context.create(cfg.protocol)
if not ctx then return nil, msg end
-- Mode
succ, msg = context.setmode(ctx, cfg.mode)
if not succ then return nil, msg end
-- Load the key
if cfg.key then
if cfg.password and
type(cfg.password) ~= "function" and
type(cfg.password) ~= "string"
then
return nil, "invalid password type"
end
succ, msg = context.loadkey(ctx, cfg.key, cfg.password)
if not succ then return nil, msg end
end
-- Load the certificate
if cfg.certificate then
succ, msg = context.loadcert(ctx, cfg.certificate)
if not succ then return nil, msg end
if cfg.key and context.checkkey then
succ = context.checkkey(ctx)
if not succ then return nil, "private key does not match public key" end
end
end
-- Load the CA certificates
if cfg.cafile or cfg.capath then
succ, msg = context.locations(ctx, cfg.cafile, cfg.capath)
if not succ then return nil, msg end
end
-- Set SSL ciphers
if cfg.ciphers then
succ, msg = context.setcipher(ctx, cfg.ciphers)
if not succ then return nil, msg end
end
-- Set the verification options
succ, msg = optexec(context.setverify, cfg.verify, ctx)
if not succ then return nil, msg end
-- Set SSL options
succ, msg = optexec(context.setoptions, cfg.options, ctx)
if not succ then return nil, msg end
-- Set the depth for certificate verification
if cfg.depth then
succ, msg = context.setdepth(ctx, cfg.depth)
if not succ then return nil, msg end
end
-- NOTE: Setting DH parameters and elliptic curves needs to come after
-- setoptions(), in case the user has specified the single_{dh,ecdh}_use
-- options.
-- Set DH parameters
if cfg.dhparam then
if type(cfg.dhparam) ~= "function" then
return nil, "invalid DH parameter type"
end
context.setdhparam(ctx, cfg.dhparam)
end
-- Set elliptic curve
if cfg.curve then
succ, msg = context.setcurve(ctx, cfg.curve)
if not succ then return nil, msg end
end
-- Set extra verification options
if cfg.verifyext and ctx.setverifyext then
succ, msg = optexec(ctx.setverifyext, cfg.verifyext, ctx)
if not succ then return nil, msg end
end
return ctx
end
--
--
--
function _M.wrap(sock, cfg)
local ctx, msg
if type(cfg) == "table" then
ctx, msg = _M.newcontext(cfg)
if not ctx then return nil, msg end
else
ctx = cfg
end
local s, msg = core.create(ctx)
if s then
core.setfd(s, sock:getfd())
sock:setfd(-1)
registry[s] = ctx
return s
end
return nil, msg
end
--
-- Extract connection information.
--
local function info(ssl, field)
local str, comp, err, protocol
comp, err = core.compression(ssl)
if err then
return comp, err
end
-- Avoid parser
if field == "compression" then
return comp
end
local info = {compression = comp}
str, info.bits, info.algbits, protocol = core.info(ssl)
if str then
info.cipher, info.protocol, info.key,
info.authentication, info.encryption, info.mac =
string.match(str,
"^(%S+)%s+(%S+)%s+Kx=(%S+)%s+Au=(%S+)%s+Enc=(%S+)%s+Mac=(%S+)")
info.export = (string.match(str, "%sexport%s*$") ~= nil)
end
if protocol then
info.protocol = protocol
end
if field then
return info[field]
end
-- Empty?
return ( (next(info)) and info )
end
--
-- Set method for SSL connections.
--
core.setmethod("info", info)
return _M
| mit |
facebook/fbcunn | fbcunn/init.lua | 1 | 3029 | require 'nn'
require 'fbnn'
require 'cunn'
require 'libfbcunn'
require 'fbcunn.cuda_ext'
include('AbstractParallel.lua')
include('BatchNormalization.lua')
include('CuBLASWrapper.lua')
include('DataParallel.lua')
include('FeatureLPPooling.lua')
include('FFTWrapper.lua')
include('HalfPrecision.lua')
include('LookupTableGPU.lua')
include('ModelParallel.lua')
include('OneBitDataParallel.lua')
include('OneBitQuantization.lua')
include('OneBitSGD.lua')
include('FFTCDefs.lua')
include('SpatialBatchNormalization.lua')
-- include('SpatialConvolutionFFT.lua')
-- include('SpatialConvolutionCuFFT.lua')
-- include('SpatialConvolutionFBFFT.lua')
-- include('SpatialConvolutionFBFFTGemm.lua')
-- include('SpatialConvolutionFFTTiled.lua')
-- include('SpatialConvolutionFFTTiledSync.lua')
-- include('SpatialConvolutionFFTTiledAsync.lua')
-- include('SpatialConvolutionFFTTiledIterated.lua')
-- include('SpatialConvolution.lua')
include('TemporalConvolutionFB.lua')
include('TemporalKMaxPooling.lua')
-- Monkey-patch module to include getParametersByDevice
-- Get the params of the module separated by device.
-- Returns the pair:
-- {0 = flat tensor containing CPU weights,
-- 1 = flat tensor containing weights from device 1,
-- ...
-- N = ... containing weights from device N},
-- {0 = flat tensor containing CPU grads,
-- 1 = ... containing grads from device 1, ...}
function nn.Module:getParametersByDevice()
local n_dev = cutorch.getDeviceCount()
local d2weights = {} -- Device => { tensor1, tensor2, ..., tensorN }
local d2grads = {} -- Device => { tensor1, tensor2, ..., tensorN }
local function tensor_to_dev(tensor)
local tnm = torch.typename(tensor)
if tnm == 'torch.CudaTensor' then
return tensor:getDevice()
end
return 0
end
local params, grads = self:parameters()
assert(#params == #grads)
-- Herd each tensor into appropriate row of weights,grads
for i = 1,#params do
local p = params[i]
local g = grads[i]
local d = tensor_to_dev(p)
if d ~= tensor_to_dev(g) then
error(("Improbable module; params,grads on devices %d,%d"):
format(d, tensor_to_dev(g)))
end
if not d2weights[d] then
d2weights[d] = {}
d2grads[d] = {}
end
table.insert(d2weights[d], p)
table.insert(d2grads[d], g)
end
local function gather(dev, params, grads)
if not params or #params == 0 then
return nil
end
if dev == 0 then
return nn.Module.flatten(params), nn.Module.flatten(grads)
end
return cutorch.withDevice(dev,
function() return nn.Module.flatten(params),
nn.Module.flatten(grads)
end)
end
local ret_params = { }
local ret_grads = { }
for d = 0,n_dev do -- sic
ret_params[d], ret_grads[d] = gather(d, d2weights[d], d2grads[d])
end
return ret_params, ret_grads
end
| bsd-3-clause |
nyov/luakit | lib/lousy/widget/tablist.lua | 8 | 3277 | -------------------------------------------------------------
-- @author Mason Larobina <mason.larobina@gmail.com> --
-- @copyright 2010 Mason Larobina --
-------------------------------------------------------------
-- Grab environment we need
local assert = assert
local setmetatable = setmetatable
local table = table
local type = type
local signal = require "lousy.signal"
local get_theme = require("lousy.theme").get
local capi = { widget = widget }
module "lousy.widget.tablist"
local data = setmetatable({}, { __mode = "k" })
function update(tlist, tabs, current)
-- Check function arguments
assert(data[tlist] and type(tlist.widget) == "widget", "invalid tablist widget")
assert(type(tabs) == "table", "invalid tabs table")
assert(current >= 0 and current <= #tabs, "current index out of range")
-- Hide tablist while re-drawing widgets
tlist.widget:hide()
local labels = data[tlist].labels
local theme = get_theme()
-- Make some new tab labels
local tcount, lcount = #tabs, #labels
if tcount > lcount then
for i = lcount+1, tcount do
local tl = { ebox = capi.widget{type = "eventbox"},
label = capi.widget{type = "label"} }
tl.label.font = theme.tab_font
tl.label.width = 1
tl.ebox.child = tl.label
tl.ebox:add_signal("button-release", function (e, mods, but)
return tlist:emit_signal("tab-clicked", i, mods, but)
end)
tl.ebox:add_signal("button-double-click", function (e, mods, but)
return tlist:emit_signal("tab-double-clicked", i, mods, but)
end)
tlist.widget:pack(tl.ebox, { expand = true, fill = true })
labels[i] = tl
end
end
-- Delete some tab labels
if lcount > tcount then
for i = tcount+1, lcount do
local tl = table.remove(labels, tcount+1)
tlist.widget:remove(tl.ebox)
tl.label:destroy()
tl.ebox:destroy()
end
end
-- Update titles & theme
local fg, bg = theme.tab_fg, theme.tab_bg
for i = 1, tcount do
local tab, l, e = tabs[i], labels[i].label, labels[i].ebox
local title = tab.title or "(Untitled)"
local fg, bg = tab.fg or fg, tab.bg or bg
if l.text ~= title then l.text = title end
if l.fg ~= fg then l.fg = fg end
if e.bg ~= bg then e.bg = bg end
end
-- Show tablist
if tcount > 0 then tlist.widget:show() end
-- Emit update signal
tlist:emit_signal("updated")
return tlist
end
function destroy(tlist)
-- Destroy all tablabels
update(tlist, {}, 0)
-- Destroy tablist container widget
tlist.widget:destroy()
-- Destroy private widget data
data[tlist] = nil
end
function new()
-- Create tablist widget table
local tlist = {
widget = capi.widget{type = "hbox"},
update = update,
destroy = destroy,
}
-- Save private widget data
data[tlist] = { labels = {}, }
-- Setup class signals
signal.setup(tlist)
return tlist
end
setmetatable(_M, { __call = function(_, ...) return new(...) end })
-- vim: et:sw=4:ts=8:sts=4:tw=80
| gpl-3.0 |
rickvanbodegraven/nodemcu-firmware | lua_modules/ds3231/ds3231.lua | 56 | 1905 | --------------------------------------------------------------------------------
-- DS3231 I2C module for NODEMCU
-- NODEMCU TEAM
-- LICENCE: http://opensource.org/licenses/MIT
-- Tobie Booth <tbooth@hindbra.in>
--------------------------------------------------------------------------------
local moduleName = ...
local M = {}
_G[moduleName] = M
-- Default value for i2c communication
local id = 0
--device address
local dev_addr = 0x68
local function decToBcd(val)
return((((val/10) - ((val/10)%1)) *16) + (val%10))
end
local function bcdToDec(val)
return((((val/16) - ((val/16)%1)) *10) + (val%16))
end
-- initialize i2c
--parameters:
--d: sda
--l: scl
function M.init(d, l)
if (d ~= nil) and (l ~= nil) and (d >= 0) and (d <= 11) and (l >= 0) and ( l <= 11) and (d ~= l) then
sda = d
scl = l
else
print("iic config failed!") return nil
end
print("init done")
i2c.setup(id, sda, scl, i2c.SLOW)
end
--get time from DS3231
function M.getTime()
i2c.start(id)
i2c.address(id, dev_addr, i2c.TRANSMITTER)
i2c.write(id, 0x00)
i2c.stop(id)
i2c.start(id)
i2c.address(id, dev_addr, i2c.RECEIVER)
local c=i2c.read(id, 7)
i2c.stop(id)
return bcdToDec(tonumber(string.byte(c, 1))),
bcdToDec(tonumber(string.byte(c, 2))),
bcdToDec(tonumber(string.byte(c, 3))),
bcdToDec(tonumber(string.byte(c, 4))),
bcdToDec(tonumber(string.byte(c, 5))),
bcdToDec(tonumber(string.byte(c, 6))),
bcdToDec(tonumber(string.byte(c, 7)))
end
--set time for DS3231
function M.setTime(second, minute, hour, day, date, month, year)
i2c.start(id)
i2c.address(id, dev_addr, i2c.TRANSMITTER)
i2c.write(id, 0x00)
i2c.write(id, decToBcd(second))
i2c.write(id, decToBcd(minute))
i2c.write(id, decToBcd(hour))
i2c.write(id, decToBcd(day))
i2c.write(id, decToBcd(date))
i2c.write(id, decToBcd(month))
i2c.write(id, decToBcd(year))
i2c.stop(id)
end
return M
| mit |
4w/xtend | xindustrial/molded_mese_crystals.lua | 2 | 3614 | local molds_output = _xtend.get_option('mese_molds_output')
local powder_output = _xtend.get_option('mese_powder_output')
local crystals_output = _xtend.get_option('molded_mese_crystal_output')
local loosed_cobble_output = _xtend.get_option('loosed_cobblestone_output')
local powder_output = _xtend.get_option('impured_mese_powder_output')
local crystals_cooktime = _xtend.get_option('molded_mese_crystal_cooktime')
-- Mese Crystal Mold
local moldMask = 'xindustrial_mese_crystal_mold_mask.png^[makealpha:0,0,0'
minetest.register_craftitem('xindustrial:mese_crystal_mold', {
description = _xtend.translate('Mese Crystal Mold'),
inventory_image = 'default_steel_block.png^[combine:16x16:0,0='..moldMask
})
minetest.register_craft({
output = 'xindustrial:mese_crystal_mold '..molds_output,
recipe = {
{'', 'default:steel_ingot', ''},
{'default:steel_ingot', '', 'default:steel_ingot'},
{'', 'default:steel_ingot', ''}
}
})
-- Mese Powder
local powderMask = 'xindustrial_mese_powder_mask.png^[makealpha:0,0,0'
local powderBase = 'default_mese_block.png^[transform:FXR90'
minetest.register_craftitem('xindustrial:mese_powder', {
description = _xtend.translate('Mese Powder'),
inventory_image = powderBase..'^[combine:16x16:0,0='..powderMask
})
minetest.register_craft({
output = 'xindustrial:mese_powder '..powder_output,
type = 'shapeless',
recipe = {'default:mese_crystal_fragment'}
})
-- Cutting agent
local lcMask = 'xindustrial_loosed_cobble_mask.png^[makealpha:0,0,0'
local lcBase = 'default_cobble.png'
minetest.register_craftitem('xindustrial:loosed_cobblestone', {
description = _xtend.translate('Loosed Cobblestone'),
inventory_image = lcBase..'^[combine:16x16:0,0='..lcMask
})
minetest.register_craft({ -- should be compatible with all mods :)
output = 'xindustrial:loosed_cobblestone '..loosed_cobble_output,
recipe = {
{'default:cobble', '', 'default:cobble'},
{'', '', ''},
{'default:cobble', '', ''}
}
})
-- Raw material for molding
local impuredPowder = '('..lcBase..'^[combine:16x16:0,0='..lcMask..')^('..powderBase..'^[combine:16x16:0,0='..powderMask..')^[makealpha:0,0,0'
minetest.register_craftitem('xindustrial:impured_mese_powder', {
description = _xtend.translate('Wet Impured Mese Powder'),
inventory_image = impuredPowder
})
minetest.register_craft({
output = 'xindustrial:impured_mese_powder '..powder_output,
type = 'shapeless',
recipe = {'xindustrial:loosed_cobblestone',
'xindustrial:mese_powder',
'bucket:bucket_water'},
replacements = {{'bucket:bucket_water', 'bucket:bucket_empty'}}
})
-- Create molded Mese crystal
local wmBase = 'default_mese_crystal.png^[colorize:#00000055'
minetest.register_craftitem('xindustrial:wet_molded_mese_crystal', {
description = _xtend.translate('Wet Molded Mese Crystal'),
inventory_image = '('..wmBase..')^[makealpha:0,0,0'
})
minetest.register_craft({
output = 'xindustrial:wet_molded_mese_crystal 1',
type = 'shapeless',
recipe = {'xindustrial:impured_mese_powder',
'xindustrial:mese_crystal_mold'}
})
-- Burning the molded Mese crystal
minetest.register_craftitem('xindustrial:molded_mese_crystal', {
description = _xtend.translate('Molded Mese Crystal'),
inventory_image = 'default_mese_crystal.png^[cracko:1:0'
})
minetest.register_craft({
type = 'cooking',
recipe = 'xindustrial:wet_molded_mese_crystal',
output = 'xindustrial:molded_mese_crystal '..crystals_output,
cooktime = crystals_cooktime
})
| gpl-3.0 |
TheOnePharaoh/YGOPro-Custom-Cards | script/c512000101.lua | 2 | 1479 | --Rescuer from the Grave
function c512000101.initial_effect(c)
--negate attack and end battle phase
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_QUICK_O)
e1:SetCode(EVENT_ATTACK_ANNOUNCE)
e1:SetRange(LOCATION_GRAVE)
e1:SetCondition(c512000101.con)
e1:SetCost(c512000101.cost)
e1:SetOperation(c512000101.op)
c:RegisterEffect(e1)
end
function c512000101.con(e,tp,eg,ep,ev,re,r,rp)
return tp~=Duel.GetTurnPlayer()
end
function c512000101.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then
if Duel.GetFlagEffect(tp,512000101)<3 then
return Duel.IsExistingMatchingCard(Card.IsAbleToRemoveAsCost,tp,LOCATION_GRAVE,0,5,nil)
else
return e:GetHandler():IsAbleToRemoveAsCost() and Duel.IsExistingMatchingCard(Card.IsAbleToRemoveAsCost,tp,LOCATION_GRAVE,0,4,e:GetHandler())
end
end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
if Duel.GetFlagEffect(tp,512000101)<3 then
local g=Duel.SelectMatchingCard(tp,Card.IsAbleToRemoveAsCost,tp,LOCATION_GRAVE,0,5,5,nil)
Duel.Remove(g,POS_FACEUP,REASON_COST)
else
Duel.Remove(e:GetHandler(),POS_FACEUP,REASON_COST)
local g=Duel.SelectMatchingCard(tp,Card.IsAbleToRemoveAsCost,tp,LOCATION_GRAVE,0,4,4,nil)
Duel.Remove(g,POS_FACEUP,REASON_COST)
end
Duel.RegisterFlagEffect(tp,512000101,0,0,0)
end
function c512000101.op(e,tp,eg,ep,ev,re,r,rp)
local sk=Duel.GetTurnPlayer()
Duel.BreakEffect()
Duel.SkipPhase(sk,PHASE_BATTLE,RESET_PHASE+PHASE_BATTLE,1)
end
| gpl-3.0 |
TheOnePharaoh/YGOPro-Custom-Cards | script/c11271.lua | 2 | 4234 | --Stymphal Garuda
function c11271.initial_effect(c)
--synchro summon
aux.AddSynchroProcedure(c,aux.FilterBoolFunction(Card.IsSetCard,0x2BF2),aux.NonTuner(nil),1)
c:EnableReviveLimit()
--atk change
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(11271,0))
e1:SetCategory(CATEGORY_ATKCHANGE)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetRange(LOCATION_MZONE)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCountLimit(1)
e1:SetTarget(c11271.atktg)
e1:SetOperation(c11271.atkop)
c:RegisterEffect(e1)
--damage
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(11271,1))
e2:SetCategory(CATEGORY_DAMAGE)
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e2:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e2:SetCode(EVENT_BE_MATERIAL)
e2:SetCondition(c11271.damcon)
e2:SetTarget(c11271.damtg)
e2:SetOperation(c11271.damop)
c:RegisterEffect(e2)
--special
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(11271,2))
e3:SetCategory(CATEGORY_SPECIAL_SUMMON)
e3:SetType(EFFECT_TYPE_IGNITION)
e3:SetRange(LOCATION_GRAVE)
e3:SetCountLimit(1,11271+EFFECT_COUNT_CODE_DUEL)
e3:SetCost(c11271.cost)
e3:SetTarget(c11271.target)
e3:SetOperation(c11271.operation)
c:RegisterEffect(e3)
end
function c11271.filter(c)
return c:IsFaceup() and c:IsType(TYPE_MONSTER)
end
function c11271.atktg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(1-tp) and c11271.filter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c11271.filter,tp,0,LOCATION_MZONE,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP)
Duel.SelectTarget(tp,c11271.filter,tp,0,LOCATION_MZONE,1,1,nil)
end
function c11271.atkop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc and tc:IsRelateToEffect(e) and tc:IsFaceup() then
Duel.NegateRelatedChain(tc,RESET_TURN_SET)
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetProperty(EFFECT_FLAG_COPY_INHERIT)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetReset(RESET_EVENT+0x1fe0000)
e1:SetValue(-500)
tc:RegisterEffect(e1)
local e2=Effect.CreateEffect(e:GetHandler())
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_DISABLE)
e2:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END)
tc:RegisterEffect(e2)
local e3=Effect.CreateEffect(e:GetHandler())
e3:SetType(EFFECT_TYPE_SINGLE)
e3:SetCode(EFFECT_DISABLE_EFFECT)
e3:SetValue(RESET_TURN_SET)
e3:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END)
tc:RegisterEffect(e3)
end
end
function c11271.damcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():IsPreviousPosition(POS_FACEUP) and e:GetHandler():IsPreviousLocation(LOCATION_ONFIELD) and r==REASON_SYNCHRO
end
function c11271.damtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetTargetPlayer(1-tp)
Duel.SetTargetParam(500)
Duel.SetOperationInfo(0,CATEGORY_DAMAGE,nil,0,1-tp,500)
end
function c11271.damop(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
function c11271.costfilter(c)
return c:IsFaceup() and c:IsDestructable() and c:IsSetCard(0x2BF2) and c:IsType(TYPE_MONSTER)
end
function c11271.cost(e,tp,eg,ep,ev,re,r,rp,chk)
local ft=Duel.GetLocationCount(tp,LOCATION_MZONE)
if chk==0 then
if ft<0 then return false end
if ft==0 then
return Duel.IsExistingMatchingCard(c11271.costfilter,tp,LOCATION_MZONE,0,1,nil)
else
return Duel.IsExistingMatchingCard(c11271.costfilter,tp,LOCATION_MZONE,0,1,nil)
end
end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY)
if ft==0 then
local g=Duel.SelectMatchingCard(tp,c11271.costfilter,tp,LOCATION_MZONE,0,1,1,nil)
Duel.Destroy(g,nil,REASON_COST)
else
local g=Duel.SelectMatchingCard(tp,c11271.costfilter,tp,LOCATION_MZONE,0,1,1,nil)
Duel.Destroy(g,nil,REASON_COST)
end
end
function c11271.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,false,false) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0)
end
function c11271.operation(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsRelateToEffect(e) then
Duel.SpecialSummon(c,0,tp,tp,false,false,POS_FACEUP_DEFENSE)
end
end
| gpl-3.0 |
TheOnePharaoh/YGOPro-Custom-Cards | script/c87002903.lua | 2 | 2814 | --May-Raias Deep Behemoth
function c87002903.initial_effect(c)
--special summon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(87002903,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e1:SetCode(EVENT_PHASE+PHASE_BATTLE)
e1:SetRange(LOCATION_MZONE)
e1:SetCondition(c87002903.spcon)
e1:SetCost(c87002903.spcost)
e1:SetTarget(c87002903.sptg)
e1:SetOperation(c87002903.spop)
c:RegisterEffect(e1)
--search
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(87002903,1))
e2:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH)
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e2:SetCode(EVENT_SPSUMMON_SUCCESS)
e2:SetCountLimit(1,87002903)
e2:SetCondition(c87002903.sccon)
e2:SetTarget(c87002903.sctg)
e2:SetOperation(c87002903.scop)
c:RegisterEffect(e2)
end
function c87002903.spcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():GetBattledGroupCount()>0
end
function c87002903.spcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():IsReleasable() end
Duel.Release(e:GetHandler(),REASON_COST)
end
function c87002903.filter(c,e,tp)
return c:IsLevelBelow(4) and c:IsSetCard(0xe291ca) and not c:IsCode(87002903) and c:IsCanBeSpecialSummoned(e,200,tp,false,false)
end
function c87002903.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>-1
and Duel.IsExistingMatchingCard(c87002903.filter,tp,LOCATION_HAND+LOCATION_DECK,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_HAND+LOCATION_DECK)
end
function c87002903.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,c87002903.filter,tp,LOCATION_HAND+LOCATION_DECK,0,1,1,nil,e,tp)
local tc=g:GetFirst()
if tc then
Duel.SpecialSummon(tc,200,tp,tp,false,false,POS_FACEUP)
tc:RegisterFlagEffect(tc:GetOriginalCode(),RESET_EVENT+0x1ff0000,0,0)
end
end
function c87002903.sccon(e,tp,eg,ep,ev,re,r,rp)
local st=e:GetHandler():GetSummonType()
return st>=(SUMMON_TYPE_SPECIAL+200) and st<(SUMMON_TYPE_SPECIAL+250)
end
function c87002903.scfilter(c)
return c:IsSetCard(0xe291ca) and c:IsType(TYPE_MONSTER) and not c:IsCode(87002903) and c:IsAbleToHand()
end
function c87002903.sctg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c87002903.scfilter,tp,LOCATION_DECK,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK)
end
function c87002903.scop(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectMatchingCard(tp,c87002903.scfilter,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-3.0 |
db260179/openwrt-bpi-r1-luci | contrib/luasrcdiet/lua/optlex.lua | 125 | 31588 | --[[--------------------------------------------------------------------
optlex.lua: does lexer-based optimizations
This file is part of LuaSrcDiet.
Copyright (c) 2008 Kein-Hong Man <khman@users.sf.net>
The COPYRIGHT file describes the conditions
under which this software may be distributed.
See the ChangeLog for more information.
----------------------------------------------------------------------]]
--[[--------------------------------------------------------------------
-- NOTES:
-- * For more lexer-based optimization ideas, see the TODO items or
-- look at technotes.txt.
-- * TODO: general string delimiter conversion optimizer
-- * TODO: (numbers) warn if overly significant digit
----------------------------------------------------------------------]]
local base = _G
local string = require "string"
module "optlex"
local match = string.match
local sub = string.sub
local find = string.find
local rep = string.rep
local print
------------------------------------------------------------------------
-- variables and data structures
------------------------------------------------------------------------
-- error function, can override by setting own function into module
error = base.error
warn = {} -- table for warning flags
local stoks, sinfos, stoklns -- source lists
local is_realtoken = { -- significant (grammar) tokens
TK_KEYWORD = true,
TK_NAME = true,
TK_NUMBER = true,
TK_STRING = true,
TK_LSTRING = true,
TK_OP = true,
TK_EOS = true,
}
local is_faketoken = { -- whitespace (non-grammar) tokens
TK_COMMENT = true,
TK_LCOMMENT = true,
TK_EOL = true,
TK_SPACE = true,
}
local opt_details -- for extra information
------------------------------------------------------------------------
-- true if current token is at the start of a line
-- * skips over deleted tokens via recursion
------------------------------------------------------------------------
local function atlinestart(i)
local tok = stoks[i - 1]
if i <= 1 or tok == "TK_EOL" then
return true
elseif tok == "" then
return atlinestart(i - 1)
end
return false
end
------------------------------------------------------------------------
-- true if current token is at the end of a line
-- * skips over deleted tokens via recursion
------------------------------------------------------------------------
local function atlineend(i)
local tok = stoks[i + 1]
if i >= #stoks or tok == "TK_EOL" or tok == "TK_EOS" then
return true
elseif tok == "" then
return atlineend(i + 1)
end
return false
end
------------------------------------------------------------------------
-- counts comment EOLs inside a long comment
-- * in order to keep line numbering, EOLs need to be reinserted
------------------------------------------------------------------------
local function commenteols(lcomment)
local sep = #match(lcomment, "^%-%-%[=*%[")
local z = sub(lcomment, sep + 1, -(sep - 1)) -- remove delims
local i, c = 1, 0
while true do
local p, q, r, s = find(z, "([\r\n])([\r\n]?)", i)
if not p then break end -- if no matches, done
i = p + 1
c = c + 1
if #s > 0 and r ~= s then -- skip CRLF or LFCR
i = i + 1
end
end
return c
end
------------------------------------------------------------------------
-- compares two tokens (i, j) and returns the whitespace required
-- * important! see technotes.txt for more information
-- * only two grammar/real tokens are being considered
-- * if "", no separation is needed
-- * if " ", then at least one whitespace (or EOL) is required
------------------------------------------------------------------------
local function checkpair(i, j)
local match = match
local t1, t2 = stoks[i], stoks[j]
--------------------------------------------------------------------
if t1 == "TK_STRING" or t1 == "TK_LSTRING" or
t2 == "TK_STRING" or t2 == "TK_LSTRING" then
return ""
--------------------------------------------------------------------
elseif t1 == "TK_OP" or t2 == "TK_OP" then
if (t1 == "TK_OP" and (t2 == "TK_KEYWORD" or t2 == "TK_NAME")) or
(t2 == "TK_OP" and (t1 == "TK_KEYWORD" or t1 == "TK_NAME")) then
return ""
end
if t1 == "TK_OP" and t2 == "TK_OP" then
-- for TK_OP/TK_OP pairs, see notes in technotes.txt
local op, op2 = sinfos[i], sinfos[j]
if (match(op, "^%.%.?$") and match(op2, "^%.")) or
(match(op, "^[~=<>]$") and op2 == "=") or
(op == "[" and (op2 == "[" or op2 == "=")) then
return " "
end
return ""
end
-- "TK_OP" + "TK_NUMBER" case
local op = sinfos[i]
if t2 == "TK_OP" then op = sinfos[j] end
if match(op, "^%.%.?%.?$") then
return " "
end
return ""
--------------------------------------------------------------------
else-- "TK_KEYWORD" | "TK_NAME" | "TK_NUMBER" then
return " "
--------------------------------------------------------------------
end
end
------------------------------------------------------------------------
-- repack tokens, removing deletions caused by optimization process
------------------------------------------------------------------------
local function repack_tokens()
local dtoks, dinfos, dtoklns = {}, {}, {}
local j = 1
for i = 1, #stoks do
local tok = stoks[i]
if tok ~= "" then
dtoks[j], dinfos[j], dtoklns[j] = tok, sinfos[i], stoklns[i]
j = j + 1
end
end
stoks, sinfos, stoklns = dtoks, dinfos, dtoklns
end
------------------------------------------------------------------------
-- number optimization
-- * optimization using string formatting functions is one way of doing
-- this, but here, we consider all cases and handle them separately
-- (possibly an idiotic approach...)
-- * scientific notation being generated is not in canonical form, this
-- may or may not be a bad thing, feedback welcome
-- * note: intermediate portions need to fit into a normal number range
-- * optimizations can be divided based on number patterns:
-- * hexadecimal:
-- (1) no need to remove leading zeros, just skip to (2)
-- (2) convert to integer if size equal or smaller
-- * change if equal size -> lose the 'x' to reduce entropy
-- (3) number is then processed as an integer
-- (4) note: does not make 0[xX] consistent
-- * integer:
-- (1) note: includes anything with trailing ".", ".0", ...
-- (2) remove useless fractional part, if present, e.g. 123.000
-- (3) remove leading zeros, e.g. 000123
-- (4) switch to scientific if shorter, e.g. 123000 -> 123e3
-- * with fraction:
-- (1) split into digits dot digits
-- (2) if no integer portion, take as zero (can omit later)
-- (3) handle degenerate .000 case, after which the fractional part
-- must be non-zero (if zero, it's matched as an integer)
-- (4) remove trailing zeros for fractional portion
-- (5) p.q where p > 0 and q > 0 cannot be shortened any more
-- (6) otherwise p == 0 and the form is .q, e.g. .000123
-- (7) if scientific shorter, convert, e.g. .000123 -> 123e-6
-- * scientific:
-- (1) split into (digits dot digits) [eE] ([+-] digits)
-- (2) if significand has ".", shift it out so it becomes an integer
-- (3) if significand is zero, just use zero
-- (4) remove leading zeros for significand
-- (5) shift out trailing zeros for significand
-- (6) examine exponent and determine which format is best:
-- integer, with fraction, scientific
------------------------------------------------------------------------
local function do_number(i)
local before = sinfos[i] -- 'before'
local z = before -- working representation
local y -- 'after', if better
--------------------------------------------------------------------
if match(z, "^0[xX]") then -- hexadecimal number
local v = base.tostring(base.tonumber(z))
if #v <= #z then
z = v -- change to integer, AND continue
else
return -- no change; stick to hex
end
end
--------------------------------------------------------------------
if match(z, "^%d+%.?0*$") then -- integer or has useless frac
z = match(z, "^(%d+)%.?0*$") -- int portion only
if z + 0 > 0 then
z = match(z, "^0*([1-9]%d*)$") -- remove leading zeros
local v = #match(z, "0*$")
local nv = base.tostring(v)
if v > #nv + 1 then -- scientific is shorter
z = sub(z, 1, #z - v).."e"..nv
end
y = z
else
y = "0" -- basic zero
end
--------------------------------------------------------------------
elseif not match(z, "[eE]") then -- number with fraction part
local p, q = match(z, "^(%d*)%.(%d+)$") -- split
if p == "" then p = 0 end -- int part zero
if q + 0 == 0 and p == 0 then
y = "0" -- degenerate .000 case
else
-- now, q > 0 holds and p is a number
local v = #match(q, "0*$") -- remove trailing zeros
if v > 0 then
q = sub(q, 1, #q - v)
end
-- if p > 0, nothing else we can do to simplify p.q case
if p + 0 > 0 then
y = p.."."..q
else
y = "."..q -- tentative, e.g. .000123
local v = #match(q, "^0*") -- # leading spaces
local w = #q - v -- # significant digits
local nv = base.tostring(#q)
-- e.g. compare 123e-6 versus .000123
if w + 2 + #nv < 1 + #q then
y = sub(q, -w).."e-"..nv
end
end
end
--------------------------------------------------------------------
else -- scientific number
local sig, ex = match(z, "^([^eE]+)[eE]([%+%-]?%d+)$")
ex = base.tonumber(ex)
-- if got ".", shift out fractional portion of significand
local p, q = match(sig, "^(%d*)%.(%d*)$")
if p then
ex = ex - #q
sig = p..q
end
if sig + 0 == 0 then
y = "0" -- basic zero
else
local v = #match(sig, "^0*") -- remove leading zeros
sig = sub(sig, v + 1)
v = #match(sig, "0*$") -- shift out trailing zeros
if v > 0 then
sig = sub(sig, 1, #sig - v)
ex = ex + v
end
-- examine exponent and determine which format is best
local nex = base.tostring(ex)
if ex == 0 then -- it's just an integer
y = sig
elseif ex > 0 and (ex <= 1 + #nex) then -- a number
y = sig..rep("0", ex)
elseif ex < 0 and (ex >= -#sig) then -- fraction, e.g. .123
v = #sig + ex
y = sub(sig, 1, v).."."..sub(sig, v + 1)
elseif ex < 0 and (#nex >= -ex - #sig) then
-- e.g. compare 1234e-5 versus .01234
-- gives: #sig + 1 + #nex >= 1 + (-ex - #sig) + #sig
-- -> #nex >= -ex - #sig
v = -ex - #sig
y = "."..rep("0", v)..sig
else -- non-canonical scientific representation
y = sig.."e"..ex
end
end--if sig
end
--------------------------------------------------------------------
if y and y ~= sinfos[i] then
if opt_details then
print("<number> (line "..stoklns[i]..") "..sinfos[i].." -> "..y)
opt_details = opt_details + 1
end
sinfos[i] = y
end
end
------------------------------------------------------------------------
-- string optimization
-- * note: works on well-formed strings only!
-- * optimizations on characters can be summarized as follows:
-- \a\b\f\n\r\t\v -- no change
-- \\ -- no change
-- \"\' -- depends on delim, other can remove \
-- \[\] -- remove \
-- \<char> -- general escape, remove \
-- \<eol> -- normalize the EOL only
-- \ddd -- if \a\b\f\n\r\t\v, change to latter
-- if other < ascii 32, keep ddd but zap leading zeros
-- if >= ascii 32, translate it into the literal, then also
-- do escapes for \\,\",\' cases
-- <other> -- no change
-- * switch delimiters if string becomes shorter
------------------------------------------------------------------------
local function do_string(I)
local info = sinfos[I]
local delim = sub(info, 1, 1) -- delimiter used
local ndelim = (delim == "'") and '"' or "'" -- opposite " <-> '
local z = sub(info, 2, -2) -- actual string
local i = 1
local c_delim, c_ndelim = 0, 0 -- "/' counts
--------------------------------------------------------------------
while i <= #z do
local c = sub(z, i, i)
----------------------------------------------------------------
if c == "\\" then -- escaped stuff
local j = i + 1
local d = sub(z, j, j)
local p = find("abfnrtv\\\n\r\"\'0123456789", d, 1, true)
------------------------------------------------------------
if not p then -- \<char> -- remove \
z = sub(z, 1, i - 1)..sub(z, j)
i = i + 1
------------------------------------------------------------
elseif p <= 8 then -- \a\b\f\n\r\t\v\\
i = i + 2 -- no change
------------------------------------------------------------
elseif p <= 10 then -- \<eol> -- normalize EOL
local eol = sub(z, j, j + 1)
if eol == "\r\n" or eol == "\n\r" then
z = sub(z, 1, i).."\n"..sub(z, j + 2)
elseif p == 10 then -- \r case
z = sub(z, 1, i).."\n"..sub(z, j + 1)
end
i = i + 2
------------------------------------------------------------
elseif p <= 12 then -- \"\' -- remove \ for ndelim
if d == delim then
c_delim = c_delim + 1
i = i + 2
else
c_ndelim = c_ndelim + 1
z = sub(z, 1, i - 1)..sub(z, j)
i = i + 1
end
------------------------------------------------------------
else -- \ddd -- various steps
local s = match(z, "^(%d%d?%d?)", j)
j = i + 1 + #s -- skip to location
local cv = s + 0
local cc = string.char(cv)
local p = find("\a\b\f\n\r\t\v", cc, 1, true)
if p then -- special escapes
s = "\\"..sub("abfnrtv", p, p)
elseif cv < 32 then -- normalized \ddd
s = "\\"..cv
elseif cc == delim then -- \<delim>
s = "\\"..cc
c_delim = c_delim + 1
elseif cc == "\\" then -- \\
s = "\\\\"
else -- literal character
s = cc
if cc == ndelim then
c_ndelim = c_ndelim + 1
end
end
z = sub(z, 1, i - 1)..s..sub(z, j)
i = i + #s
------------------------------------------------------------
end--if p
----------------------------------------------------------------
else-- c ~= "\\" -- <other> -- no change
i = i + 1
if c == ndelim then -- count ndelim, for switching delimiters
c_ndelim = c_ndelim + 1
end
----------------------------------------------------------------
end--if c
end--while
--------------------------------------------------------------------
-- switching delimiters, a long-winded derivation:
-- (1) delim takes 2+2*c_delim bytes, ndelim takes c_ndelim bytes
-- (2) delim becomes c_delim bytes, ndelim becomes 2+2*c_ndelim bytes
-- simplifying the condition (1)>(2) --> c_delim > c_ndelim
if c_delim > c_ndelim then
i = 1
while i <= #z do
local p, q, r = find(z, "([\'\"])", i)
if not p then break end
if r == delim then -- \<delim> -> <delim>
z = sub(z, 1, p - 2)..sub(z, p)
i = p
else-- r == ndelim -- <ndelim> -> \<ndelim>
z = sub(z, 1, p - 1).."\\"..sub(z, p)
i = p + 2
end
end--while
delim = ndelim -- actually change delimiters
end
--------------------------------------------------------------------
z = delim..z..delim
if z ~= sinfos[I] then
if opt_details then
print("<string> (line "..stoklns[I]..") "..sinfos[I].." -> "..z)
opt_details = opt_details + 1
end
sinfos[I] = z
end
end
------------------------------------------------------------------------
-- long string optimization
-- * note: warning flagged if trailing whitespace found, not trimmed
-- * remove first optional newline
-- * normalize embedded newlines
-- * reduce '=' separators in delimiters if possible
------------------------------------------------------------------------
local function do_lstring(I)
local info = sinfos[I]
local delim1 = match(info, "^%[=*%[") -- cut out delimiters
local sep = #delim1
local delim2 = sub(info, -sep, -1)
local z = sub(info, sep + 1, -(sep + 1)) -- lstring without delims
local y = ""
local i = 1
--------------------------------------------------------------------
while true do
local p, q, r, s = find(z, "([\r\n])([\r\n]?)", i)
-- deal with a single line
local ln
if not p then
ln = sub(z, i)
elseif p >= i then
ln = sub(z, i, p - 1)
end
if ln ~= "" then
-- flag a warning if there are trailing spaces, won't optimize!
if match(ln, "%s+$") then
warn.lstring = "trailing whitespace in long string near line "..stoklns[I]
end
y = y..ln
end
if not p then -- done if no more EOLs
break
end
-- deal with line endings, normalize them
i = p + 1
if p then
if #s > 0 and r ~= s then -- skip CRLF or LFCR
i = i + 1
end
-- skip first newline, which can be safely deleted
if not(i == 1 and i == p) then
y = y.."\n"
end
end
end--while
--------------------------------------------------------------------
-- handle possible deletion of one or more '=' separators
if sep >= 3 then
local chk, okay = sep - 1
-- loop to test ending delimiter with less of '=' down to zero
while chk >= 2 do
local delim = "%]"..rep("=", chk - 2).."%]"
if not match(y, delim) then okay = chk end
chk = chk - 1
end
if okay then -- change delimiters
sep = rep("=", okay - 2)
delim1, delim2 = "["..sep.."[", "]"..sep.."]"
end
end
--------------------------------------------------------------------
sinfos[I] = delim1..y..delim2
end
------------------------------------------------------------------------
-- long comment optimization
-- * note: does not remove first optional newline
-- * trim trailing whitespace
-- * normalize embedded newlines
-- * reduce '=' separators in delimiters if possible
------------------------------------------------------------------------
local function do_lcomment(I)
local info = sinfos[I]
local delim1 = match(info, "^%-%-%[=*%[") -- cut out delimiters
local sep = #delim1
local delim2 = sub(info, -sep, -1)
local z = sub(info, sep + 1, -(sep - 1)) -- comment without delims
local y = ""
local i = 1
--------------------------------------------------------------------
while true do
local p, q, r, s = find(z, "([\r\n])([\r\n]?)", i)
-- deal with a single line, extract and check trailing whitespace
local ln
if not p then
ln = sub(z, i)
elseif p >= i then
ln = sub(z, i, p - 1)
end
if ln ~= "" then
-- trim trailing whitespace if non-empty line
local ws = match(ln, "%s*$")
if #ws > 0 then ln = sub(ln, 1, -(ws + 1)) end
y = y..ln
end
if not p then -- done if no more EOLs
break
end
-- deal with line endings, normalize them
i = p + 1
if p then
if #s > 0 and r ~= s then -- skip CRLF or LFCR
i = i + 1
end
y = y.."\n"
end
end--while
--------------------------------------------------------------------
-- handle possible deletion of one or more '=' separators
sep = sep - 2
if sep >= 3 then
local chk, okay = sep - 1
-- loop to test ending delimiter with less of '=' down to zero
while chk >= 2 do
local delim = "%]"..rep("=", chk - 2).."%]"
if not match(y, delim) then okay = chk end
chk = chk - 1
end
if okay then -- change delimiters
sep = rep("=", okay - 2)
delim1, delim2 = "--["..sep.."[", "]"..sep.."]"
end
end
--------------------------------------------------------------------
sinfos[I] = delim1..y..delim2
end
------------------------------------------------------------------------
-- short comment optimization
-- * trim trailing whitespace
------------------------------------------------------------------------
local function do_comment(i)
local info = sinfos[i]
local ws = match(info, "%s*$") -- just look from end of string
if #ws > 0 then
info = sub(info, 1, -(ws + 1)) -- trim trailing whitespace
end
sinfos[i] = info
end
------------------------------------------------------------------------
-- returns true if string found in long comment
-- * this is a feature to keep copyright or license texts
------------------------------------------------------------------------
local function keep_lcomment(opt_keep, info)
if not opt_keep then return false end -- option not set
local delim1 = match(info, "^%-%-%[=*%[") -- cut out delimiters
local sep = #delim1
local delim2 = sub(info, -sep, -1)
local z = sub(info, sep + 1, -(sep - 1)) -- comment without delims
if find(z, opt_keep, 1, true) then -- try to match
return true
end
end
------------------------------------------------------------------------
-- main entry point
-- * currently, lexer processing has 2 passes
-- * processing is done on a line-oriented basis, which is easier to
-- grok due to the next point...
-- * since there are various options that can be enabled or disabled,
-- processing is a little messy or convoluted
------------------------------------------------------------------------
function optimize(option, toklist, semlist, toklnlist)
--------------------------------------------------------------------
-- set option flags
--------------------------------------------------------------------
local opt_comments = option["opt-comments"]
local opt_whitespace = option["opt-whitespace"]
local opt_emptylines = option["opt-emptylines"]
local opt_eols = option["opt-eols"]
local opt_strings = option["opt-strings"]
local opt_numbers = option["opt-numbers"]
local opt_keep = option.KEEP
opt_details = option.DETAILS and 0 -- upvalues for details display
print = print or base.print
if opt_eols then -- forced settings, otherwise won't work properly
opt_comments = true
opt_whitespace = true
opt_emptylines = true
end
--------------------------------------------------------------------
-- variable initialization
--------------------------------------------------------------------
stoks, sinfos, stoklns -- set source lists
= toklist, semlist, toklnlist
local i = 1 -- token position
local tok, info -- current token
local prev -- position of last grammar token
-- on same line (for TK_SPACE stuff)
--------------------------------------------------------------------
-- changes a token, info pair
--------------------------------------------------------------------
local function settoken(tok, info, I)
I = I or i
stoks[I] = tok or ""
sinfos[I] = info or ""
end
--------------------------------------------------------------------
-- processing loop (PASS 1)
--------------------------------------------------------------------
while true do
tok, info = stoks[i], sinfos[i]
----------------------------------------------------------------
local atstart = atlinestart(i) -- set line begin flag
if atstart then prev = nil end
----------------------------------------------------------------
if tok == "TK_EOS" then -- end of stream/pass
break
----------------------------------------------------------------
elseif tok == "TK_KEYWORD" or -- keywords, identifiers,
tok == "TK_NAME" or -- operators
tok == "TK_OP" then
-- TK_KEYWORD and TK_OP can't be optimized without a big
-- optimization framework; it would be more of an optimizing
-- compiler, not a source code compressor
-- TK_NAME that are locals needs parser to analyze/optimize
prev = i
----------------------------------------------------------------
elseif tok == "TK_NUMBER" then -- numbers
if opt_numbers then
do_number(i) -- optimize
end
prev = i
----------------------------------------------------------------
elseif tok == "TK_STRING" or -- strings, long strings
tok == "TK_LSTRING" then
if opt_strings then
if tok == "TK_STRING" then
do_string(i) -- optimize
else
do_lstring(i) -- optimize
end
end
prev = i
----------------------------------------------------------------
elseif tok == "TK_COMMENT" then -- short comments
if opt_comments then
if i == 1 and sub(info, 1, 1) == "#" then
-- keep shbang comment, trim whitespace
do_comment(i)
else
-- safe to delete, as a TK_EOL (or TK_EOS) always follows
settoken() -- remove entirely
end
elseif opt_whitespace then -- trim whitespace only
do_comment(i)
end
----------------------------------------------------------------
elseif tok == "TK_LCOMMENT" then -- long comments
if keep_lcomment(opt_keep, info) then
------------------------------------------------------------
-- if --keep, we keep a long comment if <msg> is found;
-- this is a feature to keep copyright or license texts
if opt_whitespace then -- trim whitespace only
do_lcomment(i)
end
prev = i
elseif opt_comments then
local eols = commenteols(info)
------------------------------------------------------------
-- prepare opt_emptylines case first, if a disposable token
-- follows, current one is safe to dump, else keep a space;
-- it is implied that the operation is safe for '-', because
-- current is a TK_LCOMMENT, and must be separate from a '-'
if is_faketoken[stoks[i + 1]] then
settoken() -- remove entirely
tok = ""
else
settoken("TK_SPACE", " ")
end
------------------------------------------------------------
-- if there are embedded EOLs to keep and opt_emptylines is
-- disabled, then switch the token into one or more EOLs
if not opt_emptylines and eols > 0 then
settoken("TK_EOL", rep("\n", eols))
end
------------------------------------------------------------
-- if optimizing whitespaces, force reinterpretation of the
-- token to give a chance for the space to be optimized away
if opt_whitespace and tok ~= "" then
i = i - 1 -- to reinterpret
end
------------------------------------------------------------
else -- disabled case
if opt_whitespace then -- trim whitespace only
do_lcomment(i)
end
prev = i
end
----------------------------------------------------------------
elseif tok == "TK_EOL" then -- line endings
if atstart and opt_emptylines then
settoken() -- remove entirely
elseif info == "\r\n" or info == "\n\r" then
-- normalize the rest of the EOLs for CRLF/LFCR only
-- (note that TK_LCOMMENT can change into several EOLs)
settoken("TK_EOL", "\n")
end
----------------------------------------------------------------
elseif tok == "TK_SPACE" then -- whitespace
if opt_whitespace then
if atstart or atlineend(i) then
-- delete leading and trailing whitespace
settoken() -- remove entirely
else
------------------------------------------------------------
-- at this point, since leading whitespace have been removed,
-- there should be a either a real token or a TK_LCOMMENT
-- prior to hitting this whitespace; the TK_LCOMMENT case
-- only happens if opt_comments is disabled; so prev ~= nil
local ptok = stoks[prev]
if ptok == "TK_LCOMMENT" then
-- previous TK_LCOMMENT can abut with anything
settoken() -- remove entirely
else
-- prev must be a grammar token; consecutive TK_SPACE
-- tokens is impossible when optimizing whitespace
local ntok = stoks[i + 1]
if is_faketoken[ntok] then
-- handle special case where a '-' cannot abut with
-- either a short comment or a long comment
if (ntok == "TK_COMMENT" or ntok == "TK_LCOMMENT") and
ptok == "TK_OP" and sinfos[prev] == "-" then
-- keep token
else
settoken() -- remove entirely
end
else--is_realtoken
-- check a pair of grammar tokens, if can abut, then
-- delete space token entirely, otherwise keep one space
local s = checkpair(prev, i + 1)
if s == "" then
settoken() -- remove entirely
else
settoken("TK_SPACE", " ")
end
end
end
------------------------------------------------------------
end
end
----------------------------------------------------------------
else
error("unidentified token encountered")
end
----------------------------------------------------------------
i = i + 1
end--while
repack_tokens()
--------------------------------------------------------------------
-- processing loop (PASS 2)
--------------------------------------------------------------------
if opt_eols then
i = 1
-- aggressive EOL removal only works with most non-grammar tokens
-- optimized away because it is a rather simple scheme -- basically
-- it just checks 'real' token pairs around EOLs
if stoks[1] == "TK_COMMENT" then
-- first comment still existing must be shbang, skip whole line
i = 3
end
while true do
tok, info = stoks[i], sinfos[i]
--------------------------------------------------------------
if tok == "TK_EOS" then -- end of stream/pass
break
--------------------------------------------------------------
elseif tok == "TK_EOL" then -- consider each TK_EOL
local t1, t2 = stoks[i - 1], stoks[i + 1]
if is_realtoken[t1] and is_realtoken[t2] then -- sanity check
local s = checkpair(i - 1, i + 1)
if s == "" then
settoken() -- remove entirely
end
end
end--if tok
--------------------------------------------------------------
i = i + 1
end--while
repack_tokens()
end
--------------------------------------------------------------------
if opt_details and opt_details > 0 then print() end -- spacing
return stoks, sinfos, stoklns
end
| apache-2.0 |
TheOnePharaoh/YGOPro-Custom-Cards | script/c43811018.lua | 2 | 5368 | --Phantasm Death Colossus
function c43811018.initial_effect(c)
--Special Limit
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE)
e1:SetCode(EFFECT_SPSUMMON_CONDITION)
e1:SetValue(c43811018.splimit)
c:RegisterEffect(e1)
--Unaffected
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e2:SetCode(EFFECT_IMMUNE_EFFECT)
e2:SetRange(LOCATION_MZONE)
e2:SetValue(c43811018.efilter)
c:RegisterEffect(e2)
--Skip Draw
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(99899504,0))
e3:SetCategory(CATEGORY_REMOVE)
e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F)
e3:SetProperty(EFFECT_FLAG_CARD_TARGET)
e3:SetCode(EVENT_PREDRAW)
e3:SetRange(LOCATION_MZONE)
e3:SetCondition(c43811018.remcon)
e3:SetTarget(c43811018.remtg)
e3:SetOperation(c43811018.remop)
c:RegisterEffect(e3)
--Special Summon
local e4=Effect.CreateEffect(c)
e4:SetDescription(aux.Stringid(43811018,1))
e4:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F)
e4:SetCategory(CATEGORY_SPECIAL_SUMMON)
e4:SetCode(EVENT_PHASE+PHASE_STANDBY)
e4:SetRange(LOCATION_REMOVED)
e4:SetCountLimit(1)
e4:SetCondition(c43811018.spcon)
e4:SetTarget(c43811018.sptg)
e4:SetOperation(c43811018.spop)
c:RegisterEffect(e4)
--Negate
local e5=Effect.CreateEffect(c)
e5:SetDescription(aux.Stringid(43811018,2))
e5:SetCategory(CATEGORY_DISABLE)
e5:SetType(EFFECT_TYPE_QUICK_O)
e5:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DAMAGE_STEP)
e5:SetRange(LOCATION_MZONE)
e5:SetCode(EVENT_CHAINING)
e5:SetCountLimit(1)
e5:SetCondition(c43811018.negcon)
e5:SetCost(c43811018.negcost)
e5:SetTarget(c43811018.negtg)
e5:SetOperation(c43811018.negop)
c:RegisterEffect(e5)
--Destroy
local e6=Effect.CreateEffect(c)
e6:SetDescription(aux.Stringid(43811018,3))
e6:SetCategory(CATEGORY_DESTROY)
e6:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e6:SetProperty(EFFECT_FLAG_DELAY+EFFECT_FLAG_DAMAGE_STEP)
e6:SetCode(EVENT_TO_GRAVE)
e6:SetTarget(c43811018.destg)
e6:SetOperation(c43811018.desop)
c:RegisterEffect(e6)
end
function c43811018.splimit(e,se,sp,st)
return se:GetHandler():IsCode(43811012) or e:GetHandler()==se:GetHandler()
end
function c43811018.efilter(e,re)
return e:GetOwnerPlayer()~=re:GetOwnerPlayer() and re:IsActiveType(TYPE_MONSTER)
end
function c43811018.remcon(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetTurnPlayer()~=tp and Duel.GetFieldGroupCount(tp,0,LOCATION_DECK)>0
end
function c43811018.remtg(e,tp,eg,ep,ev,re,r,rp,chk)
local tp=Duel.GetTurnPlayer()
if chk==0 then return e:GetHandler():IsAbleToRemove() end
local dt=Duel.GetDrawCount(tp)
if dt~=0 and Duel.SelectYesNo(tp,aux.Stringid(43811018,0)) then
e:SetLabel(1)
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e1:SetCode(EFFECT_DRAW_COUNT)
e1:SetTargetRange(1,0)
e1:SetReset(RESET_PHASE+PHASE_DRAW)
e1:SetValue(0)
Duel.RegisterEffect(e1,tp)
else e:SetLabel(0) end
end
function c43811018.remop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if e:GetLabel()==1 and c:IsRelateToEffect(e) then
Duel.Remove(c,POS_FACEUP,REASON_EFFECT)
end
end
function c43811018.spcon(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetTurnPlayer()==tp
end
function c43811018.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)
and Duel.IsExistingMatchingCard(Card.IsDiscardable,tp,LOCATION_HAND,0,1,nil) end
if Duel.SelectYesNo(tp,aux.Stringid(43811017,1)) then
Duel.DiscardHand(tp,Card.IsDiscardable,1,1,REASON_COST+REASON_DISCARD,nil)
e:SetLabel(1)
end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),0,0,0)
end
function c43811018.spop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsRelateToEffect(e) and e:GetLabel()==1 then
Duel.SpecialSummon(c,0,tp,tp,false,false,POS_FACEUP)
end
end
function c43811018.negcon(e,tp,eg,ep,ev,re,r,rp,chk)
local loc=Duel.GetChainInfo(ev,CHAININFO_TRIGGERING_LOCATION)
return not e:GetHandler():IsStatus(STATUS_BATTLE_DESTROYED) and ep~=tp
and Duel.IsChainDisablable(ev)
end
function c43811018.nfilter(c)
return c:IsSetCard(0x90e) and c:IsType(TYPE_MONSTER) and c:IsAbleToDeckAsCost()
end
function c43811018.negcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c43811018.nfilter,tp,LOCATION_GRAVE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TODECK)
local g=Duel.SelectMatchingCard(tp,c43811018.nfilter,tp,LOCATION_GRAVE,0,1,1,nil)
Duel.SendtoDeck(g,nil,2,REASON_COST)
end
function c43811018.negtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_DISABLE,eg,1,0,0)
end
function c43811018.negop(e,tp,eg,ep,ev,re,r,rp)
Duel.NegateActivation(ev)
if re:GetHandler():IsRelateToEffect(re) then
Duel.Destroy(eg,REASON_EFFECT)
end
end
function c43811018.destg(e,tp,eg,ep,ev,re,r,rp,chk)
local g=Duel.GetMatchingGroup(Card.IsDestructable,tp,0,LOCATION_SZONE,nil)
if chk==0 then return g:GetCount()>0 end
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,g:GetCount(),0,0)
end
function c43811018.desop(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetMatchingGroup(Card.IsDestructable,tp,0,LOCATION_SZONE,nil)
Duel.Destroy(g,REASON_EFFECT)
end | gpl-3.0 |
waytim/darkstar | scripts/globals/mobskills/Vorpal_Wheel.lua | 37 | 1063 | ---------------------------------------------
-- Vorpal Wheel
--
-- Description: Throws a slicing wheel at a single target.
-- Type: Physical
-- Utsusemi/Blink absorb: No
-- Range: Unknown
-- Notes: Only used by Gulool Ja Ja, and will use it as a counterattack to any spells cast on him. Damage increases as his health drops. Can be Shield Blocked.
---------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
return 0;
end;
function onMobWeaponSkill(target, mob, skill)
local numhits = 1;
local accmod = 1;
-- Increase damage as health drops
local dmgmod = (1 - (mob:getHP() / mob:getMaxHP())) * 6;
local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_SLASH,info.hitslanded);
target:delHP(dmg);
return dmg;
end;
| gpl-3.0 |
ffxinfinity/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Windurst_Woods/npcs/Gioh_Ajihri.lua | 6 | 2709 | -----------------------------------
-- Area: Windurst Woods
-- NPC: Gioh Ajihri
-- Starts & Finishes Repeatable Quest: Twinstone Bonding
-----------------------------------
package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/zones/Windurst_Woods/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
GiohAijhriSpokenTo = player:getVar("GiohAijhriSpokenTo");
NeedToZone = player:needToZone();
if (GiohAijhriSpokenTo == 1 and NeedToZone == false) then
count = trade:getItemCount();
TwinstoneEarring = trade:hasItemQty(13360,1);
if (TwinstoneEarring == true and count == 1) then
player:startEvent(0x01ea);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
TwinstoneBonding = player:getQuestStatus(WINDURST,TWINSTONE_BONDING);
Fame = player:getFameLevel(WINDURST);
if (TwinstoneBonding == QUEST_COMPLETED) then
if (player:needToZone()) then
player:startEvent(0x01eb,0,13360);
else
player:startEvent(0x01e8,0,13360);
end
elseif (TwinstoneBonding == QUEST_ACCEPTED) then
player:startEvent(0x01e8,0,13360);
elseif (TwinstoneBonding == QUEST_AVAILABLE and Fame >= 2) then
player:startEvent(0x01e7,0,13360);
else
player:startEvent(0x01a8);
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 == 0x01e7) then
player:addQuest(WINDURST,TWINSTONE_BONDING);
player:setVar("GiohAijhriSpokenTo",1);
elseif (csid == 0x01ea) then
TwinstoneBonding = player:getQuestStatus(WINDURST,TWINSTONE_BONDING);
player:tradeComplete();
player:needToZone(true);
player:setVar("GiohAijhriSpokenTo",0);
if (TwinstoneBonding == QUEST_ACCEPTED) then
player:completeQuest(WINDURST,TWINSTONE_BONDING);
player:addFame(WINDURST,WIN_FAME*80);
player:addItem(17154);
player:messageSpecial(ITEM_OBTAINED,17154);
player:addTitle(BOND_FIXER);
else
player:addFame(WINDURST,WIN_FAME*10);
player:addGil(GIL_RATE*900);
player:messageSpecial(GIL_OBTAINED,GIL_RATE*900);
end
elseif (csid == 0x01e8) then
player:setVar("GiohAijhriSpokenTo",1);
end
end;
| gpl-3.0 |
wanmaple/MWFrameworkForCocosLua | asset/src/cocos/cocos2d/OpenglConstants.lua | 100 | 27127 |
if not gl then return end
gl.GCCSO_SHADER_BINARY_FJ = 0x9260
gl._3DC_XY_AMD = 0x87fa
gl._3DC_X_AMD = 0x87f9
gl.ACTIVE_ATTRIBUTES = 0x8b89
gl.ACTIVE_ATTRIBUTE_MAX_LENGTH = 0x8b8a
gl.ACTIVE_PROGRAM_EXT = 0x8259
gl.ACTIVE_TEXTURE = 0x84e0
gl.ACTIVE_UNIFORMS = 0x8b86
gl.ACTIVE_UNIFORM_MAX_LENGTH = 0x8b87
gl.ALIASED_LINE_WIDTH_RANGE = 0x846e
gl.ALIASED_POINT_SIZE_RANGE = 0x846d
gl.ALL_COMPLETED_NV = 0x84f2
gl.ALL_SHADER_BITS_EXT = 0xffffffff
gl.ALPHA = 0x1906
gl.ALPHA16F_EXT = 0x881c
gl.ALPHA32F_EXT = 0x8816
gl.ALPHA8_EXT = 0x803c
gl.ALPHA8_OES = 0x803c
gl.ALPHA_BITS = 0xd55
gl.ALPHA_TEST_FUNC_QCOM = 0xbc1
gl.ALPHA_TEST_QCOM = 0xbc0
gl.ALPHA_TEST_REF_QCOM = 0xbc2
gl.ALREADY_SIGNALED_APPLE = 0x911a
gl.ALWAYS = 0x207
gl.AMD_compressed_3DC_texture = 0x1
gl.AMD_compressed_ATC_texture = 0x1
gl.AMD_performance_monitor = 0x1
gl.AMD_program_binary_Z400 = 0x1
gl.ANGLE_depth_texture = 0x1
gl.ANGLE_framebuffer_blit = 0x1
gl.ANGLE_framebuffer_multisample = 0x1
gl.ANGLE_instanced_arrays = 0x1
gl.ANGLE_pack_reverse_row_order = 0x1
gl.ANGLE_program_binary = 0x1
gl.ANGLE_texture_compression_dxt3 = 0x1
gl.ANGLE_texture_compression_dxt5 = 0x1
gl.ANGLE_texture_usage = 0x1
gl.ANGLE_translated_shader_source = 0x1
gl.ANY_SAMPLES_PASSED_CONSERVATIVE_EXT = 0x8d6a
gl.ANY_SAMPLES_PASSED_EXT = 0x8c2f
gl.APPLE_copy_texture_levels = 0x1
gl.APPLE_framebuffer_multisample = 0x1
gl.APPLE_rgb_422 = 0x1
gl.APPLE_sync = 0x1
gl.APPLE_texture_format_BGRA8888 = 0x1
gl.APPLE_texture_max_level = 0x1
gl.ARM_mali_program_binary = 0x1
gl.ARM_mali_shader_binary = 0x1
gl.ARM_rgba8 = 0x1
gl.ARRAY_BUFFER = 0x8892
gl.ARRAY_BUFFER_BINDING = 0x8894
gl.ATC_RGBA_EXPLICIT_ALPHA_AMD = 0x8c93
gl.ATC_RGBA_INTERPOLATED_ALPHA_AMD = 0x87ee
gl.ATC_RGB_AMD = 0x8c92
gl.ATTACHED_SHADERS = 0x8b85
gl.BACK = 0x405
gl.BGRA8_EXT = 0x93a1
gl.BGRA_EXT = 0x80e1
gl.BGRA_IMG = 0x80e1
gl.BINNING_CONTROL_HINT_QCOM = 0x8fb0
gl.BLEND = 0xbe2
gl.BLEND_COLOR = 0x8005
gl.BLEND_DST_ALPHA = 0x80ca
gl.BLEND_DST_RGB = 0x80c8
gl.BLEND_EQUATION = 0x8009
gl.BLEND_EQUATION_ALPHA = 0x883d
gl.BLEND_EQUATION_RGB = 0x8009
gl.BLEND_SRC_ALPHA = 0x80cb
gl.BLEND_SRC_RGB = 0x80c9
gl.BLUE_BITS = 0xd54
gl.BOOL = 0x8b56
gl.BOOL_VEC2 = 0x8b57
gl.BOOL_VEC3 = 0x8b58
gl.BOOL_VEC4 = 0x8b59
gl.BUFFER = 0x82e0
gl.BUFFER_ACCESS_OES = 0x88bb
gl.BUFFER_MAPPED_OES = 0x88bc
gl.BUFFER_MAP_POINTER_OES = 0x88bd
gl.BUFFER_OBJECT_EXT = 0x9151
gl.BUFFER_SIZE = 0x8764
gl.BUFFER_USAGE = 0x8765
gl.BYTE = 0x1400
gl.CCW = 0x901
gl.CLAMP_TO_BORDER_NV = 0x812d
gl.CLAMP_TO_EDGE = 0x812f
gl.COLOR_ATTACHMENT0 = 0x8ce0
gl.COLOR_ATTACHMENT0_NV = 0x8ce0
gl.COLOR_ATTACHMENT10_NV = 0x8cea
gl.COLOR_ATTACHMENT11_NV = 0x8ceb
gl.COLOR_ATTACHMENT12_NV = 0x8cec
gl.COLOR_ATTACHMENT13_NV = 0x8ced
gl.COLOR_ATTACHMENT14_NV = 0x8cee
gl.COLOR_ATTACHMENT15_NV = 0x8cef
gl.COLOR_ATTACHMENT1_NV = 0x8ce1
gl.COLOR_ATTACHMENT2_NV = 0x8ce2
gl.COLOR_ATTACHMENT3_NV = 0x8ce3
gl.COLOR_ATTACHMENT4_NV = 0x8ce4
gl.COLOR_ATTACHMENT5_NV = 0x8ce5
gl.COLOR_ATTACHMENT6_NV = 0x8ce6
gl.COLOR_ATTACHMENT7_NV = 0x8ce7
gl.COLOR_ATTACHMENT8_NV = 0x8ce8
gl.COLOR_ATTACHMENT9_NV = 0x8ce9
gl.COLOR_ATTACHMENT_EXT = 0x90f0
gl.COLOR_BUFFER_BIT = 0x4000
gl.COLOR_BUFFER_BIT0_QCOM = 0x1
gl.COLOR_BUFFER_BIT1_QCOM = 0x2
gl.COLOR_BUFFER_BIT2_QCOM = 0x4
gl.COLOR_BUFFER_BIT3_QCOM = 0x8
gl.COLOR_BUFFER_BIT4_QCOM = 0x10
gl.COLOR_BUFFER_BIT5_QCOM = 0x20
gl.COLOR_BUFFER_BIT6_QCOM = 0x40
gl.COLOR_BUFFER_BIT7_QCOM = 0x80
gl.COLOR_CLEAR_VALUE = 0xc22
gl.COLOR_EXT = 0x1800
gl.COLOR_WRITEMASK = 0xc23
gl.COMPARE_REF_TO_TEXTURE_EXT = 0x884e
gl.COMPILE_STATUS = 0x8b81
gl.COMPRESSED_RGBA_ASTC_10x10_KHR = 0x93bb
gl.COMPRESSED_RGBA_ASTC_10x5_KHR = 0x93b8
gl.COMPRESSED_RGBA_ASTC_10x6_KHR = 0x93b9
gl.COMPRESSED_RGBA_ASTC_10x8_KHR = 0x93ba
gl.COMPRESSED_RGBA_ASTC_12x10_KHR = 0x93bc
gl.COMPRESSED_RGBA_ASTC_12x12_KHR = 0x93bd
gl.COMPRESSED_RGBA_ASTC_4x4_KHR = 0x93b0
gl.COMPRESSED_RGBA_ASTC_5x4_KHR = 0x93b1
gl.COMPRESSED_RGBA_ASTC_5x5_KHR = 0x93b2
gl.COMPRESSED_RGBA_ASTC_6x5_KHR = 0x93b3
gl.COMPRESSED_RGBA_ASTC_6x6_KHR = 0x93b4
gl.COMPRESSED_RGBA_ASTC_8x5_KHR = 0x93b5
gl.COMPRESSED_RGBA_ASTC_8x6_KHR = 0x93b6
gl.COMPRESSED_RGBA_ASTC_8x8_KHR = 0x93b7
gl.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG = 0x8c03
gl.COMPRESSED_RGBA_PVRTC_2BPPV2_IMG = 0x9137
gl.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG = 0x8c02
gl.COMPRESSED_RGBA_PVRTC_4BPPV2_IMG = 0x9138
gl.COMPRESSED_RGBA_S3TC_DXT1_EXT = 0x83f1
gl.COMPRESSED_RGBA_S3TC_DXT3_ANGLE = 0x83f2
gl.COMPRESSED_RGBA_S3TC_DXT5_ANGLE = 0x83f3
gl.COMPRESSED_RGB_PVRTC_2BPPV1_IMG = 0x8c01
gl.COMPRESSED_RGB_PVRTC_4BPPV1_IMG = 0x8c00
gl.COMPRESSED_RGB_S3TC_DXT1_EXT = 0x83f0
gl.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR = 0x93db
gl.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR = 0x93d8
gl.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR = 0x93d9
gl.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR = 0x93da
gl.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR = 0x93dc
gl.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR = 0x93dd
gl.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR = 0x93d0
gl.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR = 0x93d1
gl.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR = 0x93d2
gl.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR = 0x93d3
gl.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR = 0x93d4
gl.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR = 0x93d5
gl.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR = 0x93d6
gl.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR = 0x93d7
gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_NV = 0x8c4d
gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_NV = 0x8c4e
gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_NV = 0x8c4f
gl.COMPRESSED_SRGB_S3TC_DXT1_NV = 0x8c4c
gl.COMPRESSED_TEXTURE_FORMATS = 0x86a3
gl.CONDITION_SATISFIED_APPLE = 0x911c
gl.CONSTANT_ALPHA = 0x8003
gl.CONSTANT_COLOR = 0x8001
gl.CONTEXT_FLAG_DEBUG_BIT = 0x2
gl.CONTEXT_ROBUST_ACCESS_EXT = 0x90f3
gl.COUNTER_RANGE_AMD = 0x8bc1
gl.COUNTER_TYPE_AMD = 0x8bc0
gl.COVERAGE_ALL_FRAGMENTS_NV = 0x8ed5
gl.COVERAGE_ATTACHMENT_NV = 0x8ed2
gl.COVERAGE_AUTOMATIC_NV = 0x8ed7
gl.COVERAGE_BUFFERS_NV = 0x8ed3
gl.COVERAGE_BUFFER_BIT_NV = 0x8000
gl.COVERAGE_COMPONENT4_NV = 0x8ed1
gl.COVERAGE_COMPONENT_NV = 0x8ed0
gl.COVERAGE_EDGE_FRAGMENTS_NV = 0x8ed6
gl.COVERAGE_SAMPLES_NV = 0x8ed4
gl.CPU_OPTIMIZED_QCOM = 0x8fb1
gl.CULL_FACE = 0xb44
gl.CULL_FACE_MODE = 0xb45
gl.CURRENT_PROGRAM = 0x8b8d
gl.CURRENT_QUERY_EXT = 0x8865
gl.CURRENT_VERTEX_ATTRIB = 0x8626
gl.CW = 0x900
gl.DEBUG_CALLBACK_FUNCTION = 0x8244
gl.DEBUG_CALLBACK_USER_PARAM = 0x8245
gl.DEBUG_GROUP_STACK_DEPTH = 0x826d
gl.DEBUG_LOGGED_MESSAGES = 0x9145
gl.DEBUG_NEXT_LOGGED_MESSAGE_LENGTH = 0x8243
gl.DEBUG_OUTPUT = 0x92e0
gl.DEBUG_OUTPUT_SYNCHRONOUS = 0x8242
gl.DEBUG_SEVERITY_HIGH = 0x9146
gl.DEBUG_SEVERITY_LOW = 0x9148
gl.DEBUG_SEVERITY_MEDIUM = 0x9147
gl.DEBUG_SEVERITY_NOTIFICATION = 0x826b
gl.DEBUG_SOURCE_API = 0x8246
gl.DEBUG_SOURCE_APPLICATION = 0x824a
gl.DEBUG_SOURCE_OTHER = 0x824b
gl.DEBUG_SOURCE_SHADER_COMPILER = 0x8248
gl.DEBUG_SOURCE_THIRD_PARTY = 0x8249
gl.DEBUG_SOURCE_WINDOW_SYSTEM = 0x8247
gl.DEBUG_TYPE_DEPRECATED_BEHAVIOR = 0x824d
gl.DEBUG_TYPE_ERROR = 0x824c
gl.DEBUG_TYPE_MARKER = 0x8268
gl.DEBUG_TYPE_OTHER = 0x8251
gl.DEBUG_TYPE_PERFORMANCE = 0x8250
gl.DEBUG_TYPE_POP_GROUP = 0x826a
gl.DEBUG_TYPE_PORTABILITY = 0x824f
gl.DEBUG_TYPE_PUSH_GROUP = 0x8269
gl.DEBUG_TYPE_UNDEFINED_BEHAVIOR = 0x824e
gl.DECR = 0x1e03
gl.DECR_WRAP = 0x8508
gl.DELETE_STATUS = 0x8b80
gl.DEPTH24_STENCIL8_OES = 0x88f0
gl.DEPTH_ATTACHMENT = 0x8d00
gl.DEPTH_BITS = 0xd56
gl.DEPTH_BUFFER_BIT = 0x100
gl.DEPTH_BUFFER_BIT0_QCOM = 0x100
gl.DEPTH_BUFFER_BIT1_QCOM = 0x200
gl.DEPTH_BUFFER_BIT2_QCOM = 0x400
gl.DEPTH_BUFFER_BIT3_QCOM = 0x800
gl.DEPTH_BUFFER_BIT4_QCOM = 0x1000
gl.DEPTH_BUFFER_BIT5_QCOM = 0x2000
gl.DEPTH_BUFFER_BIT6_QCOM = 0x4000
gl.DEPTH_BUFFER_BIT7_QCOM = 0x8000
gl.DEPTH_CLEAR_VALUE = 0xb73
gl.DEPTH_COMPONENT = 0x1902
gl.DEPTH_COMPONENT16 = 0x81a5
gl.DEPTH_COMPONENT16_NONLINEAR_NV = 0x8e2c
gl.DEPTH_COMPONENT16_OES = 0x81a5
gl.DEPTH_COMPONENT24_OES = 0x81a6
gl.DEPTH_COMPONENT32_OES = 0x81a7
gl.DEPTH_EXT = 0x1801
gl.DEPTH_FUNC = 0xb74
gl.DEPTH_RANGE = 0xb70
gl.DEPTH_STENCIL_OES = 0x84f9
gl.DEPTH_TEST = 0xb71
gl.DEPTH_WRITEMASK = 0xb72
gl.DITHER = 0xbd0
gl.DMP_shader_binary = 0x1
gl.DONT_CARE = 0x1100
gl.DRAW_BUFFER0_NV = 0x8825
gl.DRAW_BUFFER10_NV = 0x882f
gl.DRAW_BUFFER11_NV = 0x8830
gl.DRAW_BUFFER12_NV = 0x8831
gl.DRAW_BUFFER13_NV = 0x8832
gl.DRAW_BUFFER14_NV = 0x8833
gl.DRAW_BUFFER15_NV = 0x8834
gl.DRAW_BUFFER1_NV = 0x8826
gl.DRAW_BUFFER2_NV = 0x8827
gl.DRAW_BUFFER3_NV = 0x8828
gl.DRAW_BUFFER4_NV = 0x8829
gl.DRAW_BUFFER5_NV = 0x882a
gl.DRAW_BUFFER6_NV = 0x882b
gl.DRAW_BUFFER7_NV = 0x882c
gl.DRAW_BUFFER8_NV = 0x882d
gl.DRAW_BUFFER9_NV = 0x882e
gl.DRAW_BUFFER_EXT = 0xc01
gl.DRAW_FRAMEBUFFER_ANGLE = 0x8ca9
gl.DRAW_FRAMEBUFFER_APPLE = 0x8ca9
gl.DRAW_FRAMEBUFFER_BINDING_ANGLE = 0x8ca6
gl.DRAW_FRAMEBUFFER_BINDING_APPLE = 0x8ca6
gl.DRAW_FRAMEBUFFER_BINDING_NV = 0x8ca6
gl.DRAW_FRAMEBUFFER_NV = 0x8ca9
gl.DST_ALPHA = 0x304
gl.DST_COLOR = 0x306
gl.DYNAMIC_DRAW = 0x88e8
gl.ELEMENT_ARRAY_BUFFER = 0x8893
gl.ELEMENT_ARRAY_BUFFER_BINDING = 0x8895
gl.EQUAL = 0x202
gl.ES_VERSION_2_0 = 0x1
gl.ETC1_RGB8_OES = 0x8d64
gl.ETC1_SRGB8_NV = 0x88ee
gl.EXTENSIONS = 0x1f03
gl.EXT_blend_minmax = 0x1
gl.EXT_color_buffer_half_float = 0x1
gl.EXT_debug_label = 0x1
gl.EXT_debug_marker = 0x1
gl.EXT_discard_framebuffer = 0x1
gl.EXT_map_buffer_range = 0x1
gl.EXT_multi_draw_arrays = 0x1
gl.EXT_multisampled_render_to_texture = 0x1
gl.EXT_multiview_draw_buffers = 0x1
gl.EXT_occlusion_query_boolean = 0x1
gl.EXT_read_format_bgra = 0x1
gl.EXT_robustness = 0x1
gl.EXT_sRGB = 0x1
gl.EXT_separate_shader_objects = 0x1
gl.EXT_shader_framebuffer_fetch = 0x1
gl.EXT_shader_texture_lod = 0x1
gl.EXT_shadow_samplers = 0x1
gl.EXT_texture_compression_dxt1 = 0x1
gl.EXT_texture_filter_anisotropic = 0x1
gl.EXT_texture_format_BGRA8888 = 0x1
gl.EXT_texture_rg = 0x1
gl.EXT_texture_storage = 0x1
gl.EXT_texture_type_2_10_10_10_REV = 0x1
gl.EXT_unpack_subimage = 0x1
gl.FALSE = 0x0
gl.FASTEST = 0x1101
gl.FENCE_CONDITION_NV = 0x84f4
gl.FENCE_STATUS_NV = 0x84f3
gl.FIXED = 0x140c
gl.FJ_shader_binary_GCCSO = 0x1
gl.FLOAT = 0x1406
gl.FLOAT_MAT2 = 0x8b5a
gl.FLOAT_MAT3 = 0x8b5b
gl.FLOAT_MAT4 = 0x8b5c
gl.FLOAT_VEC2 = 0x8b50
gl.FLOAT_VEC3 = 0x8b51
gl.FLOAT_VEC4 = 0x8b52
gl.FRAGMENT_SHADER = 0x8b30
gl.FRAGMENT_SHADER_BIT_EXT = 0x2
gl.FRAGMENT_SHADER_DERIVATIVE_HINT_OES = 0x8b8b
gl.FRAGMENT_SHADER_DISCARDS_SAMPLES_EXT = 0x8a52
gl.FRAMEBUFFER = 0x8d40
gl.FRAMEBUFFER_ATTACHMENT_ANGLE = 0x93a3
gl.FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT = 0x8210
gl.FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT = 0x8211
gl.FRAMEBUFFER_ATTACHMENT_OBJECT_NAME = 0x8cd1
gl.FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE = 0x8cd0
gl.FRAMEBUFFER_ATTACHMENT_TEXTURE_3D_ZOFFSET_OES = 0x8cd4
gl.FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE = 0x8cd3
gl.FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL = 0x8cd2
gl.FRAMEBUFFER_ATTACHMENT_TEXTURE_SAMPLES_EXT = 0x8d6c
gl.FRAMEBUFFER_BINDING = 0x8ca6
gl.FRAMEBUFFER_COMPLETE = 0x8cd5
gl.FRAMEBUFFER_INCOMPLETE_ATTACHMENT = 0x8cd6
gl.FRAMEBUFFER_INCOMPLETE_DIMENSIONS = 0x8cd9
gl.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT = 0x8cd7
gl.FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_ANGLE = 0x8d56
gl.FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_APPLE = 0x8d56
gl.FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_EXT = 0x8d56
gl.FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_IMG = 0x9134
gl.FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_NV = 0x8d56
gl.FRAMEBUFFER_UNDEFINED_OES = 0x8219
gl.FRAMEBUFFER_UNSUPPORTED = 0x8cdd
gl.FRONT = 0x404
gl.FRONT_AND_BACK = 0x408
gl.FRONT_FACE = 0xb46
gl.FUNC_ADD = 0x8006
gl.FUNC_REVERSE_SUBTRACT = 0x800b
gl.FUNC_SUBTRACT = 0x800a
gl.GENERATE_MIPMAP_HINT = 0x8192
gl.GEQUAL = 0x206
gl.GPU_OPTIMIZED_QCOM = 0x8fb2
gl.GREATER = 0x204
gl.GREEN_BITS = 0xd53
gl.GUILTY_CONTEXT_RESET_EXT = 0x8253
gl.HALF_FLOAT_OES = 0x8d61
gl.HIGH_FLOAT = 0x8df2
gl.HIGH_INT = 0x8df5
gl.IMG_multisampled_render_to_texture = 0x1
gl.IMG_program_binary = 0x1
gl.IMG_read_format = 0x1
gl.IMG_shader_binary = 0x1
gl.IMG_texture_compression_pvrtc = 0x1
gl.IMG_texture_compression_pvrtc2 = 0x1
gl.IMPLEMENTATION_COLOR_READ_FORMAT = 0x8b9b
gl.IMPLEMENTATION_COLOR_READ_TYPE = 0x8b9a
gl.INCR = 0x1e02
gl.INCR_WRAP = 0x8507
gl.INFO_LOG_LENGTH = 0x8b84
gl.INNOCENT_CONTEXT_RESET_EXT = 0x8254
gl.INT = 0x1404
gl.INT_10_10_10_2_OES = 0x8df7
gl.INT_VEC2 = 0x8b53
gl.INT_VEC3 = 0x8b54
gl.INT_VEC4 = 0x8b55
gl.INVALID_ENUM = 0x500
gl.INVALID_FRAMEBUFFER_OPERATION = 0x506
gl.INVALID_OPERATION = 0x502
gl.INVALID_VALUE = 0x501
gl.INVERT = 0x150a
gl.KEEP = 0x1e00
gl.KHR_debug = 0x1
gl.KHR_texture_compression_astc_ldr = 0x1
gl.LEQUAL = 0x203
gl.LESS = 0x201
gl.LINEAR = 0x2601
gl.LINEAR_MIPMAP_LINEAR = 0x2703
gl.LINEAR_MIPMAP_NEAREST = 0x2701
gl.LINES = 0x1
gl.LINE_LOOP = 0x2
gl.LINE_STRIP = 0x3
gl.LINE_WIDTH = 0xb21
gl.LINK_STATUS = 0x8b82
gl.LOSE_CONTEXT_ON_RESET_EXT = 0x8252
gl.LOW_FLOAT = 0x8df0
gl.LOW_INT = 0x8df3
gl.LUMINANCE = 0x1909
gl.LUMINANCE16F_EXT = 0x881e
gl.LUMINANCE32F_EXT = 0x8818
gl.LUMINANCE4_ALPHA4_OES = 0x8043
gl.LUMINANCE8_ALPHA8_EXT = 0x8045
gl.LUMINANCE8_ALPHA8_OES = 0x8045
gl.LUMINANCE8_EXT = 0x8040
gl.LUMINANCE8_OES = 0x8040
gl.LUMINANCE_ALPHA = 0x190a
gl.LUMINANCE_ALPHA16F_EXT = 0x881f
gl.LUMINANCE_ALPHA32F_EXT = 0x8819
gl.MALI_PROGRAM_BINARY_ARM = 0x8f61
gl.MALI_SHADER_BINARY_ARM = 0x8f60
gl.MAP_FLUSH_EXPLICIT_BIT_EXT = 0x10
gl.MAP_INVALIDATE_BUFFER_BIT_EXT = 0x8
gl.MAP_INVALIDATE_RANGE_BIT_EXT = 0x4
gl.MAP_READ_BIT_EXT = 0x1
gl.MAP_UNSYNCHRONIZED_BIT_EXT = 0x20
gl.MAP_WRITE_BIT_EXT = 0x2
gl.MAX_3D_TEXTURE_SIZE_OES = 0x8073
gl.MAX_COLOR_ATTACHMENTS_NV = 0x8cdf
gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS = 0x8b4d
gl.MAX_CUBE_MAP_TEXTURE_SIZE = 0x851c
gl.MAX_DEBUG_GROUP_STACK_DEPTH = 0x826c
gl.MAX_DEBUG_LOGGED_MESSAGES = 0x9144
gl.MAX_DEBUG_MESSAGE_LENGTH = 0x9143
gl.MAX_DRAW_BUFFERS_NV = 0x8824
gl.MAX_EXT = 0x8008
gl.MAX_FRAGMENT_UNIFORM_VECTORS = 0x8dfd
gl.MAX_LABEL_LENGTH = 0x82e8
gl.MAX_MULTIVIEW_BUFFERS_EXT = 0x90f2
gl.MAX_RENDERBUFFER_SIZE = 0x84e8
gl.MAX_SAMPLES_ANGLE = 0x8d57
gl.MAX_SAMPLES_APPLE = 0x8d57
gl.MAX_SAMPLES_EXT = 0x8d57
gl.MAX_SAMPLES_IMG = 0x9135
gl.MAX_SAMPLES_NV = 0x8d57
gl.MAX_SERVER_WAIT_TIMEOUT_APPLE = 0x9111
gl.MAX_TEXTURE_IMAGE_UNITS = 0x8872
gl.MAX_TEXTURE_MAX_ANISOTROPY_EXT = 0x84ff
gl.MAX_TEXTURE_SIZE = 0xd33
gl.MAX_VARYING_VECTORS = 0x8dfc
gl.MAX_VERTEX_ATTRIBS = 0x8869
gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS = 0x8b4c
gl.MAX_VERTEX_UNIFORM_VECTORS = 0x8dfb
gl.MAX_VIEWPORT_DIMS = 0xd3a
gl.MEDIUM_FLOAT = 0x8df1
gl.MEDIUM_INT = 0x8df4
gl.MIN_EXT = 0x8007
gl.MIRRORED_REPEAT = 0x8370
gl.MULTISAMPLE_BUFFER_BIT0_QCOM = 0x1000000
gl.MULTISAMPLE_BUFFER_BIT1_QCOM = 0x2000000
gl.MULTISAMPLE_BUFFER_BIT2_QCOM = 0x4000000
gl.MULTISAMPLE_BUFFER_BIT3_QCOM = 0x8000000
gl.MULTISAMPLE_BUFFER_BIT4_QCOM = 0x10000000
gl.MULTISAMPLE_BUFFER_BIT5_QCOM = 0x20000000
gl.MULTISAMPLE_BUFFER_BIT6_QCOM = 0x40000000
gl.MULTISAMPLE_BUFFER_BIT7_QCOM = 0x80000000
gl.MULTIVIEW_EXT = 0x90f1
gl.NEAREST = 0x2600
gl.NEAREST_MIPMAP_LINEAR = 0x2702
gl.NEAREST_MIPMAP_NEAREST = 0x2700
gl.NEVER = 0x200
gl.NICEST = 0x1102
gl.NONE = 0x0
gl.NOTEQUAL = 0x205
gl.NO_ERROR = 0x0
gl.NO_RESET_NOTIFICATION_EXT = 0x8261
gl.NUM_COMPRESSED_TEXTURE_FORMATS = 0x86a2
gl.NUM_PROGRAM_BINARY_FORMATS_OES = 0x87fe
gl.NUM_SHADER_BINARY_FORMATS = 0x8df9
gl.NV_coverage_sample = 0x1
gl.NV_depth_nonlinear = 0x1
gl.NV_draw_buffers = 0x1
gl.NV_draw_instanced = 0x1
gl.NV_fbo_color_attachments = 0x1
gl.NV_fence = 0x1
gl.NV_framebuffer_blit = 0x1
gl.NV_framebuffer_multisample = 0x1
gl.NV_generate_mipmap_sRGB = 0x1
gl.NV_instanced_arrays = 0x1
gl.NV_read_buffer = 0x1
gl.NV_read_buffer_front = 0x1
gl.NV_read_depth = 0x1
gl.NV_read_depth_stencil = 0x1
gl.NV_read_stencil = 0x1
gl.NV_sRGB_formats = 0x1
gl.NV_shadow_samplers_array = 0x1
gl.NV_shadow_samplers_cube = 0x1
gl.NV_texture_border_clamp = 0x1
gl.NV_texture_compression_s3tc_update = 0x1
gl.NV_texture_npot_2D_mipmap = 0x1
gl.OBJECT_TYPE_APPLE = 0x9112
gl.OES_EGL_image = 0x1
gl.OES_EGL_image_external = 0x1
gl.OES_compressed_ETC1_RGB8_texture = 0x1
gl.OES_compressed_paletted_texture = 0x1
gl.OES_depth24 = 0x1
gl.OES_depth32 = 0x1
gl.OES_depth_texture = 0x1
gl.OES_element_index_uint = 0x1
gl.OES_fbo_render_mipmap = 0x1
gl.OES_fragment_precision_high = 0x1
gl.OES_get_program_binary = 0x1
gl.OES_mapbuffer = 0x1
gl.OES_packed_depth_stencil = 0x1
gl.OES_required_internalformat = 0x1
gl.OES_rgb8_rgba8 = 0x1
gl.OES_standard_derivatives = 0x1
gl.OES_stencil1 = 0x1
gl.OES_stencil4 = 0x1
gl.OES_surfaceless_context = 0x1
gl.OES_texture_3D = 0x1
gl.OES_texture_float = 0x1
gl.OES_texture_float_linear = 0x1
gl.OES_texture_half_float = 0x1
gl.OES_texture_half_float_linear = 0x1
gl.OES_texture_npot = 0x1
gl.OES_vertex_array_object = 0x1
gl.OES_vertex_half_float = 0x1
gl.OES_vertex_type_10_10_10_2 = 0x1
gl.ONE = 0x1
gl.ONE_MINUS_CONSTANT_ALPHA = 0x8004
gl.ONE_MINUS_CONSTANT_COLOR = 0x8002
gl.ONE_MINUS_DST_ALPHA = 0x305
gl.ONE_MINUS_DST_COLOR = 0x307
gl.ONE_MINUS_SRC_ALPHA = 0x303
gl.ONE_MINUS_SRC_COLOR = 0x301
gl.OUT_OF_MEMORY = 0x505
gl.PACK_ALIGNMENT = 0xd05
gl.PACK_REVERSE_ROW_ORDER_ANGLE = 0x93a4
gl.PALETTE4_R5_G6_B5_OES = 0x8b92
gl.PALETTE4_RGB5_A1_OES = 0x8b94
gl.PALETTE4_RGB8_OES = 0x8b90
gl.PALETTE4_RGBA4_OES = 0x8b93
gl.PALETTE4_RGBA8_OES = 0x8b91
gl.PALETTE8_R5_G6_B5_OES = 0x8b97
gl.PALETTE8_RGB5_A1_OES = 0x8b99
gl.PALETTE8_RGB8_OES = 0x8b95
gl.PALETTE8_RGBA4_OES = 0x8b98
gl.PALETTE8_RGBA8_OES = 0x8b96
gl.PERCENTAGE_AMD = 0x8bc3
gl.PERFMON_GLOBAL_MODE_QCOM = 0x8fa0
gl.PERFMON_RESULT_AMD = 0x8bc6
gl.PERFMON_RESULT_AVAILABLE_AMD = 0x8bc4
gl.PERFMON_RESULT_SIZE_AMD = 0x8bc5
gl.POINTS = 0x0
gl.POLYGON_OFFSET_FACTOR = 0x8038
gl.POLYGON_OFFSET_FILL = 0x8037
gl.POLYGON_OFFSET_UNITS = 0x2a00
gl.PROGRAM = 0x82e2
gl.PROGRAM_BINARY_ANGLE = 0x93a6
gl.PROGRAM_BINARY_FORMATS_OES = 0x87ff
gl.PROGRAM_BINARY_LENGTH_OES = 0x8741
gl.PROGRAM_OBJECT_EXT = 0x8b40
gl.PROGRAM_PIPELINE_BINDING_EXT = 0x825a
gl.PROGRAM_PIPELINE_OBJECT_EXT = 0x8a4f
gl.PROGRAM_SEPARABLE_EXT = 0x8258
gl.QCOM_alpha_test = 0x1
gl.QCOM_binning_control = 0x1
gl.QCOM_driver_control = 0x1
gl.QCOM_extended_get = 0x1
gl.QCOM_extended_get2 = 0x1
gl.QCOM_perfmon_global_mode = 0x1
gl.QCOM_tiled_rendering = 0x1
gl.QCOM_writeonly_rendering = 0x1
gl.QUERY = 0x82e3
gl.QUERY_OBJECT_EXT = 0x9153
gl.QUERY_RESULT_AVAILABLE_EXT = 0x8867
gl.QUERY_RESULT_EXT = 0x8866
gl.R16F_EXT = 0x822d
gl.R32F_EXT = 0x822e
gl.R8_EXT = 0x8229
gl.READ_BUFFER_EXT = 0xc02
gl.READ_BUFFER_NV = 0xc02
gl.READ_FRAMEBUFFER_ANGLE = 0x8ca8
gl.READ_FRAMEBUFFER_APPLE = 0x8ca8
gl.READ_FRAMEBUFFER_BINDING_ANGLE = 0x8caa
gl.READ_FRAMEBUFFER_BINDING_APPLE = 0x8caa
gl.READ_FRAMEBUFFER_BINDING_NV = 0x8caa
gl.READ_FRAMEBUFFER_NV = 0x8ca8
gl.RED_BITS = 0xd52
gl.RED_EXT = 0x1903
gl.RENDERBUFFER = 0x8d41
gl.RENDERBUFFER_ALPHA_SIZE = 0x8d53
gl.RENDERBUFFER_BINDING = 0x8ca7
gl.RENDERBUFFER_BLUE_SIZE = 0x8d52
gl.RENDERBUFFER_DEPTH_SIZE = 0x8d54
gl.RENDERBUFFER_GREEN_SIZE = 0x8d51
gl.RENDERBUFFER_HEIGHT = 0x8d43
gl.RENDERBUFFER_INTERNAL_FORMAT = 0x8d44
gl.RENDERBUFFER_RED_SIZE = 0x8d50
gl.RENDERBUFFER_SAMPLES_ANGLE = 0x8cab
gl.RENDERBUFFER_SAMPLES_APPLE = 0x8cab
gl.RENDERBUFFER_SAMPLES_EXT = 0x8cab
gl.RENDERBUFFER_SAMPLES_IMG = 0x9133
gl.RENDERBUFFER_SAMPLES_NV = 0x8cab
gl.RENDERBUFFER_STENCIL_SIZE = 0x8d55
gl.RENDERBUFFER_WIDTH = 0x8d42
gl.RENDERER = 0x1f01
gl.RENDER_DIRECT_TO_FRAMEBUFFER_QCOM = 0x8fb3
gl.REPEAT = 0x2901
gl.REPLACE = 0x1e01
gl.REQUIRED_TEXTURE_IMAGE_UNITS_OES = 0x8d68
gl.RESET_NOTIFICATION_STRATEGY_EXT = 0x8256
gl.RG16F_EXT = 0x822f
gl.RG32F_EXT = 0x8230
gl.RG8_EXT = 0x822b
gl.RGB = 0x1907
gl.RGB10_A2_EXT = 0x8059
gl.RGB10_EXT = 0x8052
gl.RGB16F_EXT = 0x881b
gl.RGB32F_EXT = 0x8815
gl.RGB565 = 0x8d62
gl.RGB565_OES = 0x8d62
gl.RGB5_A1 = 0x8057
gl.RGB5_A1_OES = 0x8057
gl.RGB8_OES = 0x8051
gl.RGBA = 0x1908
gl.RGBA16F_EXT = 0x881a
gl.RGBA32F_EXT = 0x8814
gl.RGBA4 = 0x8056
gl.RGBA4_OES = 0x8056
gl.RGBA8_OES = 0x8058
gl.RGB_422_APPLE = 0x8a1f
gl.RG_EXT = 0x8227
gl.SAMPLER = 0x82e6
gl.SAMPLER_2D = 0x8b5e
gl.SAMPLER_2D_ARRAY_SHADOW_NV = 0x8dc4
gl.SAMPLER_2D_SHADOW_EXT = 0x8b62
gl.SAMPLER_3D_OES = 0x8b5f
gl.SAMPLER_CUBE = 0x8b60
gl.SAMPLER_CUBE_SHADOW_NV = 0x8dc5
gl.SAMPLER_EXTERNAL_OES = 0x8d66
gl.SAMPLES = 0x80a9
gl.SAMPLE_ALPHA_TO_COVERAGE = 0x809e
gl.SAMPLE_BUFFERS = 0x80a8
gl.SAMPLE_COVERAGE = 0x80a0
gl.SAMPLE_COVERAGE_INVERT = 0x80ab
gl.SAMPLE_COVERAGE_VALUE = 0x80aa
gl.SCISSOR_BOX = 0xc10
gl.SCISSOR_TEST = 0xc11
gl.SGX_BINARY_IMG = 0x8c0a
gl.SGX_PROGRAM_BINARY_IMG = 0x9130
gl.SHADER = 0x82e1
gl.SHADER_BINARY_DMP = 0x9250
gl.SHADER_BINARY_FORMATS = 0x8df8
gl.SHADER_BINARY_VIV = 0x8fc4
gl.SHADER_COMPILER = 0x8dfa
gl.SHADER_OBJECT_EXT = 0x8b48
gl.SHADER_SOURCE_LENGTH = 0x8b88
gl.SHADER_TYPE = 0x8b4f
gl.SHADING_LANGUAGE_VERSION = 0x8b8c
gl.SHORT = 0x1402
gl.SIGNALED_APPLE = 0x9119
gl.SLUMINANCE8_ALPHA8_NV = 0x8c45
gl.SLUMINANCE8_NV = 0x8c47
gl.SLUMINANCE_ALPHA_NV = 0x8c44
gl.SLUMINANCE_NV = 0x8c46
gl.SRC_ALPHA = 0x302
gl.SRC_ALPHA_SATURATE = 0x308
gl.SRC_COLOR = 0x300
gl.SRGB8_ALPHA8_EXT = 0x8c43
gl.SRGB8_NV = 0x8c41
gl.SRGB_ALPHA_EXT = 0x8c42
gl.SRGB_EXT = 0x8c40
gl.STACK_OVERFLOW = 0x503
gl.STACK_UNDERFLOW = 0x504
gl.STATE_RESTORE = 0x8bdc
gl.STATIC_DRAW = 0x88e4
gl.STENCIL_ATTACHMENT = 0x8d20
gl.STENCIL_BACK_FAIL = 0x8801
gl.STENCIL_BACK_FUNC = 0x8800
gl.STENCIL_BACK_PASS_DEPTH_FAIL = 0x8802
gl.STENCIL_BACK_PASS_DEPTH_PASS = 0x8803
gl.STENCIL_BACK_REF = 0x8ca3
gl.STENCIL_BACK_VALUE_MASK = 0x8ca4
gl.STENCIL_BACK_WRITEMASK = 0x8ca5
gl.STENCIL_BITS = 0xd57
gl.STENCIL_BUFFER_BIT = 0x400
gl.STENCIL_BUFFER_BIT0_QCOM = 0x10000
gl.STENCIL_BUFFER_BIT1_QCOM = 0x20000
gl.STENCIL_BUFFER_BIT2_QCOM = 0x40000
gl.STENCIL_BUFFER_BIT3_QCOM = 0x80000
gl.STENCIL_BUFFER_BIT4_QCOM = 0x100000
gl.STENCIL_BUFFER_BIT5_QCOM = 0x200000
gl.STENCIL_BUFFER_BIT6_QCOM = 0x400000
gl.STENCIL_BUFFER_BIT7_QCOM = 0x800000
gl.STENCIL_CLEAR_VALUE = 0xb91
gl.STENCIL_EXT = 0x1802
gl.STENCIL_FAIL = 0xb94
gl.STENCIL_FUNC = 0xb92
gl.STENCIL_INDEX1_OES = 0x8d46
gl.STENCIL_INDEX4_OES = 0x8d47
gl.STENCIL_INDEX8 = 0x8d48
gl.STENCIL_PASS_DEPTH_FAIL = 0xb95
gl.STENCIL_PASS_DEPTH_PASS = 0xb96
gl.STENCIL_REF = 0xb97
gl.STENCIL_TEST = 0xb90
gl.STENCIL_VALUE_MASK = 0xb93
gl.STENCIL_WRITEMASK = 0xb98
gl.STREAM_DRAW = 0x88e0
gl.SUBPIXEL_BITS = 0xd50
gl.SYNC_CONDITION_APPLE = 0x9113
gl.SYNC_FENCE_APPLE = 0x9116
gl.SYNC_FLAGS_APPLE = 0x9115
gl.SYNC_FLUSH_COMMANDS_BIT_APPLE = 0x1
gl.SYNC_GPU_COMMANDS_COMPLETE_APPLE = 0x9117
gl.SYNC_OBJECT_APPLE = 0x8a53
gl.SYNC_STATUS_APPLE = 0x9114
gl.TEXTURE = 0x1702
gl.TEXTURE0 = 0x84c0
gl.TEXTURE1 = 0x84c1
gl.TEXTURE10 = 0x84ca
gl.TEXTURE11 = 0x84cb
gl.TEXTURE12 = 0x84cc
gl.TEXTURE13 = 0x84cd
gl.TEXTURE14 = 0x84ce
gl.TEXTURE15 = 0x84cf
gl.TEXTURE16 = 0x84d0
gl.TEXTURE17 = 0x84d1
gl.TEXTURE18 = 0x84d2
gl.TEXTURE19 = 0x84d3
gl.TEXTURE2 = 0x84c2
gl.TEXTURE20 = 0x84d4
gl.TEXTURE21 = 0x84d5
gl.TEXTURE22 = 0x84d6
gl.TEXTURE23 = 0x84d7
gl.TEXTURE24 = 0x84d8
gl.TEXTURE25 = 0x84d9
gl.TEXTURE26 = 0x84da
gl.TEXTURE27 = 0x84db
gl.TEXTURE28 = 0x84dc
gl.TEXTURE29 = 0x84dd
gl.TEXTURE3 = 0x84c3
gl.TEXTURE30 = 0x84de
gl.TEXTURE31 = 0x84df
gl.TEXTURE4 = 0x84c4
gl.TEXTURE5 = 0x84c5
gl.TEXTURE6 = 0x84c6
gl.TEXTURE7 = 0x84c7
gl.TEXTURE8 = 0x84c8
gl.TEXTURE9 = 0x84c9
gl.TEXTURE_2D = 0xde1
gl.TEXTURE_3D_OES = 0x806f
gl.TEXTURE_BINDING_2D = 0x8069
gl.TEXTURE_BINDING_3D_OES = 0x806a
gl.TEXTURE_BINDING_CUBE_MAP = 0x8514
gl.TEXTURE_BINDING_EXTERNAL_OES = 0x8d67
gl.TEXTURE_BORDER_COLOR_NV = 0x1004
gl.TEXTURE_COMPARE_FUNC_EXT = 0x884d
gl.TEXTURE_COMPARE_MODE_EXT = 0x884c
gl.TEXTURE_CUBE_MAP = 0x8513
gl.TEXTURE_CUBE_MAP_NEGATIVE_X = 0x8516
gl.TEXTURE_CUBE_MAP_NEGATIVE_Y = 0x8518
gl.TEXTURE_CUBE_MAP_NEGATIVE_Z = 0x851a
gl.TEXTURE_CUBE_MAP_POSITIVE_X = 0x8515
gl.TEXTURE_CUBE_MAP_POSITIVE_Y = 0x8517
gl.TEXTURE_CUBE_MAP_POSITIVE_Z = 0x8519
gl.TEXTURE_DEPTH_QCOM = 0x8bd4
gl.TEXTURE_EXTERNAL_OES = 0x8d65
gl.TEXTURE_FORMAT_QCOM = 0x8bd6
gl.TEXTURE_HEIGHT_QCOM = 0x8bd3
gl.TEXTURE_IMAGE_VALID_QCOM = 0x8bd8
gl.TEXTURE_IMMUTABLE_FORMAT_EXT = 0x912f
gl.TEXTURE_INTERNAL_FORMAT_QCOM = 0x8bd5
gl.TEXTURE_MAG_FILTER = 0x2800
gl.TEXTURE_MAX_ANISOTROPY_EXT = 0x84fe
gl.TEXTURE_MAX_LEVEL_APPLE = 0x813d
gl.TEXTURE_MIN_FILTER = 0x2801
gl.TEXTURE_NUM_LEVELS_QCOM = 0x8bd9
gl.TEXTURE_OBJECT_VALID_QCOM = 0x8bdb
gl.TEXTURE_SAMPLES_IMG = 0x9136
gl.TEXTURE_TARGET_QCOM = 0x8bda
gl.TEXTURE_TYPE_QCOM = 0x8bd7
gl.TEXTURE_USAGE_ANGLE = 0x93a2
gl.TEXTURE_WIDTH_QCOM = 0x8bd2
gl.TEXTURE_WRAP_R_OES = 0x8072
gl.TEXTURE_WRAP_S = 0x2802
gl.TEXTURE_WRAP_T = 0x2803
gl.TIMEOUT_EXPIRED_APPLE = 0x911b
gl.TIMEOUT_IGNORED_APPLE = 0xffffffffffffffff
gl.TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE = 0x93a0
gl.TRIANGLES = 0x4
gl.TRIANGLE_FAN = 0x6
gl.TRIANGLE_STRIP = 0x5
gl.TRUE = 0x1
gl.UNKNOWN_CONTEXT_RESET_EXT = 0x8255
gl.UNPACK_ALIGNMENT = 0xcf5
gl.UNPACK_ROW_LENGTH = 0xcf2
gl.UNPACK_SKIP_PIXELS = 0xcf4
gl.UNPACK_SKIP_ROWS = 0xcf3
gl.UNSIGNALED_APPLE = 0x9118
gl.UNSIGNED_BYTE = 0x1401
gl.UNSIGNED_INT = 0x1405
gl.UNSIGNED_INT64_AMD = 0x8bc2
gl.UNSIGNED_INT_10_10_10_2_OES = 0x8df6
gl.UNSIGNED_INT_24_8_OES = 0x84fa
gl.UNSIGNED_INT_2_10_10_10_REV_EXT = 0x8368
gl.UNSIGNED_NORMALIZED_EXT = 0x8c17
gl.UNSIGNED_SHORT = 0x1403
gl.UNSIGNED_SHORT_1_5_5_5_REV_EXT = 0x8366
gl.UNSIGNED_SHORT_4_4_4_4 = 0x8033
gl.UNSIGNED_SHORT_4_4_4_4_REV_EXT = 0x8365
gl.UNSIGNED_SHORT_4_4_4_4_REV_IMG = 0x8365
gl.UNSIGNED_SHORT_5_5_5_1 = 0x8034
gl.UNSIGNED_SHORT_5_6_5 = 0x8363
gl.UNSIGNED_SHORT_8_8_APPLE = 0x85ba
gl.UNSIGNED_SHORT_8_8_REV_APPLE = 0x85bb
gl.VALIDATE_STATUS = 0x8b83
gl.VENDOR = 0x1f00
gl.VERSION = 0x1f02
gl.VERTEX_ARRAY_BINDING_OES = 0x85b5
gl.VERTEX_ARRAY_OBJECT_EXT = 0x9154
gl.VERTEX_ATTRIB_ARRAY_BUFFER_BINDING = 0x889f
gl.VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE = 0x88fe
gl.VERTEX_ATTRIB_ARRAY_DIVISOR_NV = 0x88fe
gl.VERTEX_ATTRIB_ARRAY_ENABLED = 0x8622
gl.VERTEX_ATTRIB_ARRAY_NORMALIZED = 0x886a
gl.VERTEX_ATTRIB_ARRAY_POINTER = 0x8645
gl.VERTEX_ATTRIB_ARRAY_SIZE = 0x8623
gl.VERTEX_ATTRIB_ARRAY_STRIDE = 0x8624
gl.VERTEX_ATTRIB_ARRAY_TYPE = 0x8625
gl.VERTEX_SHADER = 0x8b31
gl.VERTEX_SHADER_BIT_EXT = 0x1
gl.VIEWPORT = 0xba2
gl.VIV_shader_binary = 0x1
gl.WAIT_FAILED_APPLE = 0x911d
gl.WRITEONLY_RENDERING_QCOM = 0x8823
gl.WRITE_ONLY_OES = 0x88b9
gl.Z400_BINARY_AMD = 0x8740
gl.ZERO = 0x0
gl.VERTEX_ATTRIB_POINTER_VEC3 = 0
gl.VERTEX_ATTRIB_POINTER_COLOR4B = 1
| apache-2.0 |
waytim/darkstar | scripts/globals/items/soft-boiled_egg.lua | 18 | 1174 | -----------------------------------------
-- ID: 4532
-- Item: soft-boiled_egg
-- Food Effect: 60Min, All Races
-----------------------------------------
-- Health 20
-- Magic 20
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,3600,4532);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 20);
target:addMod(MOD_MP, 20);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 20);
target:delMod(MOD_MP, 20);
end;
| gpl-3.0 |
Em30-tm-lua/Emc | .luarocks/share/lua/5.2/luarocks/path_cmd.lua | 18 | 2345 |
--- @module luarocks.path_cmd
-- Driver for the `luarocks path` command.
local path_cmd = {}
local util = require("luarocks.util")
local deps = require("luarocks.deps")
local cfg = require("luarocks.cfg")
path_cmd.help_summary = "Return the currently configured package path."
path_cmd.help_arguments = ""
path_cmd.help = [[
Returns the package path currently configured for this installation
of LuaRocks, formatted as shell commands to update LUA_PATH and LUA_CPATH.
--bin Adds the system path to the output
--append Appends the paths to the existing paths. Default is to prefix
the LR paths to the existing paths.
--lr-path Exports the Lua path (not formatted as shell command)
--lr-cpath Exports the Lua cpath (not formatted as shell command)
--lr-bin Exports the system path (not formatted as shell command)
On Unix systems, you may run:
eval `luarocks path`
And on Windows:
luarocks path > "%temp%\_lrp.bat" && call "%temp%\_lrp.bat" && del "%temp%\_lrp.bat"
]]
--- Driver function for "path" command.
-- @return boolean This function always succeeds.
function path_cmd.run(...)
local flags = util.parse_flags(...)
local deps_mode = deps.get_deps_mode(flags)
local lr_path, lr_cpath, lr_bin = cfg.package_paths()
local path_sep = cfg.export_path_separator
if flags["lr-path"] then
util.printout(util.remove_path_dupes(lr_path, ';'))
return true
elseif flags["lr-cpath"] then
util.printout(util.remove_path_dupes(lr_cpath, ';'))
return true
elseif flags["lr-bin"] then
util.printout(util.remove_path_dupes(lr_bin, path_sep))
return true
end
if flags["append"] then
lr_path = package.path .. ";" .. lr_path
lr_cpath = package.cpath .. ";" .. lr_cpath
lr_bin = os.getenv("PATH") .. path_sep .. lr_bin
else
lr_path = lr_path.. ";" .. package.path
lr_cpath = lr_cpath .. ";" .. package.cpath
lr_bin = lr_bin .. path_sep .. os.getenv("PATH")
end
util.printout(cfg.export_lua_path:format(util.remove_path_dupes(lr_path, ';')))
util.printout(cfg.export_lua_cpath:format(util.remove_path_dupes(lr_cpath, ';')))
if flags["bin"] then
util.printout(cfg.export_path:format(util.remove_path_dupes(lr_bin, path_sep)))
end
return true
end
return path_cmd
| gpl-2.0 |
ffxinfinity/ffxinfinity | FFXI Server-Development/Build Files/scripts/globals/items/serving_of_beaugreen_sautee.lua | 3 | 1304 | -----------------------------------------
-- ID: 4572
-- Item: serving_of_beaugreen_sautee
-- Food Effect: 180Min, All Races
-----------------------------------------
-- Agility 1
-- Vitality -1
-- Ranged ATT % 7
-- Ranged ATT Cap 15
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,10800,4572);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_AGI, 1);
target:addMod(MOD_VIT, -1);
target:addMod(MOD_FOOD_RATTP, 7);
target:addMod(MOD_FOOD_RATT_CAP, 15);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_AGI, 1);
target:delMod(MOD_VIT, -1);
target:delMod(MOD_FOOD_RATTP, 7);
target:delMod(MOD_FOOD_RATT_CAP, 15);
end;
| gpl-3.0 |
waytim/darkstar | scripts/zones/Leujaoam_Sanctum/instances/leujaoam_cleansing.lua | 28 | 2422 | -----------------------------------
--
-- Assault: Leujaoam Cleansing
--
-----------------------------------
require("scripts/globals/instance")
local Leujaoam = require("scripts/zones/Leujaoam_Sanctum/IDs");
-----------------------------------
-- afterInstanceRegister
-----------------------------------
function afterInstanceRegister(player)
local instance = player:getInstance();
player:messageSpecial(Leujaoam.text.ASSAULT_01_START, 1);
player:messageSpecial(Leujaoam.text.TIME_TO_COMPLETE, instance:getTimeLimit());
end;
-----------------------------------
-- onInstanceCreated
-----------------------------------
function onInstanceCreated(instance)
for i,v in pairs(Leujaoam.mobs[1]) do
SpawnMob(v, instance);
end
local rune = instance:getEntity(bit.band(Leujaoam.npcs.RUNE_OF_RELEASE, 0xFFF), TYPE_NPC);
local box = instance:getEntity(bit.band(Leujaoam.npcs.ANCIENT_LOCKBOX, 0xFFF), TYPE_NPC);
rune:setPos(476,8.479,39,49);
box:setPos(476,8.479,40,49);
instance:getEntity(bit.band(Leujaoam.npcs._1XN, 0xFFF), TYPE_NPC):setAnimation(8);
end;
-----------------------------------
-- onInstanceTimeUpdate
-----------------------------------
function onInstanceTimeUpdate(instance, elapsed)
updateInstanceTime(instance, elapsed, Leujaoam.text)
end;
-----------------------------------
-- onInstanceFailure
-----------------------------------
function onInstanceFailure(instance)
local chars = instance:getChars();
for i,v in pairs(chars) do
v:messageSpecial(Leujaoam.text.MISSION_FAILED,10,10);
v:startEvent(0x66);
end
end;
-----------------------------------
-- onInstanceProgressUpdate
-----------------------------------
function onInstanceProgressUpdate(instance, progress)
if (progress >= 15) then
instance:complete();
end
end;
-----------------------------------
-- onInstanceComplete
-----------------------------------
function onInstanceComplete(instance)
local chars = instance:getChars();
for i,v in pairs(chars) do
v:messageSpecial(Leujaoam.text.RUNE_UNLOCKED_POS, 8, 8);
end
local rune = instance:getEntity(bit.band(Leujaoam.npcs.RUNE_OF_RELEASE, 0xFFF), TYPE_NPC);
local box = instance:getEntity(bit.band(Leujaoam.npcs.ANCIENT_LOCKBOX, 0xFFF), TYPE_NPC);
rune:setStatus(STATUS_NORMAL);
box:setStatus(STATUS_NORMAL);
end;
| gpl-3.0 |
ffxinfinity/ffxinfinity | FFXI Server-Development/Build Files/scripts/globals/weaponskills/uriel_blade.lua | 2 | 1391 | -----------------------------------
-- Uriel Blade
-- Sword weapon skill
-- Skill Level: NA
-- Delivers and area attack that deals light elemental damage. Damage varies with TP. Additional effect Flash.
-- Only avaliable durring Campaign Battle while weilding a Griffinclaw
-- Aligned with the Thunder Gorget & Breeze Gorget.
-- Aligned with the Thunder Belt & Breeze Belt.
-- Element: Light
-- Modifiers: STR:32% MND:32%
-- 100%TP 200%TP 300%TP
-- 4.50 6.00 7.50
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function OnUseWeaponSkill(player, target, wsID)
local params = {};
params.numHits = 1;
params.ftp100 = 4.5; params.ftp200 = 6.0; params.ftp300 = 7.5;
params.str_wsc = 0.32; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.32; 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, tpHits, extraHits = doPhysicalWeaponskill(player, target, params);
if(target:hasStatusEffect(EFFECT_FLASH) == false) then
target:addStatusEffect(EFFECT_FLASH, 100, 0, 30);
end
return tpHits, extraHits, damage;
end
| gpl-3.0 |
waytim/darkstar | scripts/zones/East_Sarutabaruta/npcs/Signpost.lua | 13 | 2116 | -----------------------------------
-- Area: East Sarutabaruta
-- NPC: Signpost
-----------------------------------
package.loaded["scripts/zones/East_Sarutabaruta/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/East_Sarutabaruta/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local X = player:getXPos();
local Z = player:getZPos();
if ((X > 83.9 and X < 96.7) and (Z < -339.8 and Z > -352.6)) then
player:messageSpecial(SIGNPOST_OFFSET);
elseif ((X > 191.5 and X < 204.3) and (Z < -265.03 and Z > -277.13)) then
player:messageSpecial(SIGNPOST_OFFSET+1);
elseif ((X > 212.9 and X < 225) and (Z < -24.8 and Z > -37.7)) then
player:messageSpecial(SIGNPOST_OFFSET+2);
elseif ((X > -0.4 and X < 12.6) and (Z < -42.9 and Z > -54.9)) then
player:messageSpecial(SIGNPOST_OFFSET+3);
elseif ((X > -135.3 and X < -122.3) and (Z < -55.04 and Z > -67.14)) then
player:messageSpecial(SIGNPOST_OFFSET+4);
elseif ((X > -80.5 and X < -67.4) and (Z < 454.8 and Z > 442.7)) then
player:messageSpecial(SIGNPOST_OFFSET+5);
elseif ((X > 144.1 and X < 157.1) and (Z < 386.7 and Z > 374.6)) then
player:messageSpecial(SIGNPOST_OFFSET+6);
elseif ((X > -94.9 and X < -82.9) and (Z < -279.5 and Z > -292.4)) then
player:messageSpecial(SIGNPOST_OFFSET+7);
elseif ((X > -55.8 and X < -43.8) and (Z < -120.5 and Z > -133.5)) then
player:messageSpecial(SIGNPOST_OFFSET+8);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--print("CSID: %u",csid);
--print("RESULT: %u",option);
end; | gpl-3.0 |
TheOnePharaoh/YGOPro-Custom-Cards | script/c1143291.lua | 2 | 5278 | --ANTI-MATTER Dark Being, Zoohgtf
function c1143291.initial_effect(c)
--self destruct
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS)
e1:SetCode(EVENT_SUMMON_SUCCESS)
e1:SetOperation(c1143291.effop)
c:RegisterEffect(e1)
local e2=e1:Clone()
e2:SetCode(EVENT_SPSUMMON_SUCCESS)
c:RegisterEffect(e2)
--cannot be effect target
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_SINGLE)
e3:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e3:SetRange(LOCATION_MZONE)
e3:SetCode(EFFECT_CANNOT_BE_EFFECT_TARGET)
e3:SetValue(aux.tgoval)
c:RegisterEffect(e3)
--remove&damage
local e4=Effect.CreateEffect(c)
e4:SetDescription(aux.Stringid(1143291,0))
e4:SetCategory(CATEGORY_TODECK)
e4:SetProperty(EFFECT_FLAG_CARD_TARGET)
e4:SetType(EFFECT_TYPE_IGNITION)
e4:SetRange(LOCATION_MZONE)
e4:SetCountLimit(1)
e4:SetCost(c1143291.tdcost)
e4:SetTarget(c1143291.tdtg)
e4:SetOperation(c1143291.tdop)
c:RegisterEffect(e4)
--spsummon
local e5=Effect.CreateEffect(c)
e5:SetDescription(aux.Stringid(1143291,1))
e5:SetCategory(CATEGORY_SPECIAL_SUMMON+CATEGORY_TOHAND)
e5:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e5:SetCode(EVENT_REMOVE)
e5:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DELAY)
e5:SetCountLimit(1,1143291)
e5:SetTarget(c1143291.sptg)
e5:SetOperation(c1143291.spop)
c:RegisterEffect(e5)
if not c1143291.global_check then
c1143291.global_check=true
local ge1=Effect.GlobalEffect()
ge1:SetType(EFFECT_TYPE_FIELD)
ge1:SetCode(EFFECT_TO_GRAVE_REDIRECT)
ge1:SetTargetRange(LOCATION_DECK+LOCATION_HAND+LOCATION_MZONE+LOCATION_OVERLAY,LOCATION_HAND+LOCATION_DECK+LOCATION_MZONE+LOCATION_OVERLAY)
ge1:SetTarget(aux.TargetBoolFunction(Card.IsCode,1143291))
ge1:SetValue(LOCATION_REMOVED)
Duel.RegisterEffect(ge1,0)
end
end
function c1143291.effop(e,tp,eg,ep,ev,re,r,rp)
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e1:SetRange(LOCATION_MZONE)
e1:SetCode(EVENT_PHASE+PHASE_END)
e1:SetOperation(c1143291.desop)
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END,2)
e1:SetLabel(0)
e1:SetCountLimit(1)
e:GetHandler():RegisterEffect(e1)
end
function c1143291.desop(e,tp,eg,ep,ev,re,r,rp)
if e:GetLabel()>0 then
Duel.Destroy(e:GetHandler(),REASON_EFFECT)
else
e:SetLabel(1)
end
end
function c1143291.costfilter(co)
return co:IsSetCard(0xaf75) and not co:IsCode(1143291) and co:IsAbleToRemoveAsCost()
end
function c1143291.tdcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c1143291.costfilter,tp,LOCATION_HAND+LOCATION_ONFIELD,0,2,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local g=Duel.SelectMatchingCard(tp,c1143291.costfilter,tp,LOCATION_HAND+LOCATION_ONFIELD,0,2,2,nil)
Duel.Remove(g,POS_FACEUP,REASON_COST)
end
function c1143291.tdfilter(c)
return c:IsFaceup() and c:IsAbleToDeck()
end
function c1143291.tdtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_ONFIELD) and c1143291.tdfilter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c1143291.tdfilter,tp,0,LOCATION_ONFIELD,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TODECK)
local g=Duel.SelectTarget(tp,c1143291.tdfilter,tp,0,LOCATION_ONFIELD,1,3,nil)
Duel.SetOperationInfo(0,CATEGORY_TODECK,g,g:GetCount(),0,0)
end
function c1143291.tdop(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.SendtoDeck(g,nil,2,REASON_EFFECT)
end
end
function c1143291.spfilter(c,e,tp)
return c:IsType(TYPE_MONSTER) and c:IsSetCard(0xaf75) and c:IsLevelBelow(4) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c1143291.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_DECK) and chkc:IsControler(tp) and c1143291.spfilter(chkc,e,tp) end
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingTarget(c1143291.spfilter,tp,LOCATION_DECK,0,1,nil,e,tp) end
local ft=2
if Duel.IsPlayerAffectedByEffect(tp,59822133) then ft=1 end
ft=math.min(ft,Duel.GetLocationCount(tp,LOCATION_MZONE))
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectTarget(tp,c1143291.spfilter,tp,LOCATION_DECK,0,1,ft,nil,e,tp)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,g:GetCount(),0,0)
end
function c1143291.thfilter(c)
return c:IsSetCard(0xaf75) and not c:IsCode(1143291) and c:IsAbleToHand()
end
function c1143291.spop(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 Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP)~=0 then
local sg=Duel.GetMatchingGroup(c1143291.thfilter,tp,LOCATION_REMOVED,0,nil)
if sg:GetCount()>0 and Duel.SelectYesNo(tp,aux.Stringid(1143291,2)) then
Duel.BreakEffect()
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
sg=sg:Select(tp,1,1,nil)
Duel.SendtoHand(sg,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,sg)
Duel.ShuffleDeck(tp)
end
end
end
| gpl-3.0 |
waytim/darkstar | scripts/zones/Bastok_Markets/npcs/Sinon.lua | 14 | 4321 | -----------------------------------
-- Area: Bastok Markets
-- NPC: Sinon
-- Armor Storage NPC
-----------------------------------
package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/armorstorage");
require("scripts/zones/Bastok_Markets/TextIDs");
Deposit = 0x018b;
Withdrawl = 0x018c;
ArraySize = table.getn(StorageArray);
G1 = 0;
G2 = 0;
G3 = 0;
G4 = 0;
G5 = 0;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
for SetId = 1,ArraySize,11 do
TradeCount = trade:getItemCount();
T1 = trade:hasItemQty(StorageArray[SetId + 5],1);
if (T1 == true) then
if (player:hasKeyItem(StorageArray[SetId + 10]) == false) then
if (TradeCount == StorageArray[SetId + 3]) then
T2 = trade:hasItemQty(StorageArray[SetId + 4],1);
T3 = trade:hasItemQty(StorageArray[SetId + 6],1);
T4 = trade:hasItemQty(StorageArray[SetId + 7],1);
T5 = trade:hasItemQty(StorageArray[SetId + 8],1);
if (StorageArray[SetId + 4] == 0) then
T2 = true;
end;
if (StorageArray[SetId + 6] == 0) then
T3 = true;
end;
if (StorageArray[SetId + 7] == 0) then
T4 = true;
end;
if (StorageArray[SetId + 8] == 0) then
T5 = true;
end;
if (T2 == true and T3 == true and T4 == true and T5 == true) then
player:startEvent(Deposit,0,0,0,0,0,StorageArray[SetId + 9]);
player:addKeyItem(StorageArray[SetId + 10]);
player:messageSpecial(KEYITEM_OBTAINED,StorageArray[SetId + 10]);
break;
end;
end;
end;
end;
end;
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
CurrGil = player:getGil();
for KeyItem = 11,ArraySize,11 do
if player:hasKeyItem(StorageArray[KeyItem]) then
if StorageArray[KeyItem - 9] == 1 then
G1 = G1 + StorageArray[KeyItem - 8];
elseif StorageArray[KeyItem - 9] == 2 then
G2 = G2 + StorageArray[KeyItem - 8];
elseif StorageArray[KeyItem - 9] == 3 then
G3 = G3 + StorageArray[KeyItem - 8];
elseif StorageArray[KeyItem - 9] == 4 then
G4 = G4 + StorageArray[KeyItem - 8];
elseif StorageArray[KeyItem - 9] == 6 then
G5 = G5 + StorageArray[KeyItem - 8];
end;
end;
end;
player:startEvent(Withdrawl,G1,G2,G3,G4,CurrGil,G5);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
if (csid == Withdrawl) then
player:updateEvent(StorageArray[option * 11 - 6],
StorageArray[option * 11 - 5],
StorageArray[option * 11 - 4],
StorageArray[option * 11 - 3],
StorageArray[option * 11 - 2],
StorageArray[option * 11 - 1]);
end;
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
if (csid == Withdrawl) then
if (option > 0 and option <= StorageArray[ArraySize] - 10) then
if (player:getFreeSlotsCount() >= StorageArray[option * 11 - 7]) then
for Item = 2,6,1 do
if (StorageArray[option * 11 - Item] > 0) then
player:addItem(StorageArray[option * 11 - Item],1);
player:messageSpecial(ITEM_OBTAINED,StorageArray[option * 11 - Item]);
end;
end;
player:delKeyItem(StorageArray[option * 11]);
player:setGil(player:getGil() - StorageArray[option * 11 - 1]);
else
for Item = 2,6,1 do
if (StorageArray[option * 11 - Item] > 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,StorageArray[option * 11 - Item]);
end;
end;
end;
end;
end;
if (csid == Deposit) then
player:tradeComplete();
end;
end; | gpl-3.0 |
TheOnePharaoh/YGOPro-Custom-Cards | script/c888000008.lua | 2 | 1595 | --Evil HERO Swamp Demon
function c888000008.initial_effect(c)
--fusion material
c:EnableReviveLimit()
aux.AddFusionProcCode2(c,79979666,84327329,true,true)
--spsummon condition
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE)
e1:SetCode(EFFECT_SPSUMMON_CONDITION)
e1:SetValue(c888000008.splimit)
c:RegisterEffect(e1)
--to defense
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS)
e2:SetCode(EVENT_DAMAGE_STEP_END)
e2:SetCondition(c888000008.poscon)
e2:SetOperation(c888000008.posop)
c:RegisterEffect(e2)
--change battle target
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(888000008,1))
e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e3:SetCode(EVENT_BE_BATTLE_TARGET)
e3:SetRange(LOCATION_MZONE)
e3:SetCondition(c888000008.cbcon)
e3:SetOperation(c888000008.cbop)
c:RegisterEffect(e3)
end
c888000008.dark_calling=true
function c888000008.splimit(e,se,sp,st)
return st==SUMMON_TYPE_FUSION+0x10
end
function c888000008.poscon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler()==Duel.GetAttacker() and e:GetHandler():IsRelateToBattle()
end
function c888000008.posop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsAttackPos() then
Duel.ChangePosition(c,POS_FACEUP_DEFENSE)
end
end
function c888000008.cbcon(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local bt=eg:GetFirst()
return c~=bt and bt:GetControler()==c:GetControler()
end
function c888000008.cbop(e,tp,eg,ep,ev,re,r,rp)
Duel.ChangeAttackTarget(e:GetHandler())
end | gpl-3.0 |
wanmaple/MWFrameworkForCocosLua | frameworks/cocos2d-x/cocos/scripting/lua-bindings/auto/api/Widget.lua | 5 | 17791 |
--------------------------------
-- @module Widget
-- @extend ProtectedNode,LayoutParameterProtocol
-- @parent_module ccui
--------------------------------
-- Changes the percent that is widget's percent size<br>
-- param percent that is widget's percent size
-- @function [parent=#Widget] setSizePercent
-- @param self
-- @param #vec2_table percent
--------------------------------
--
-- @function [parent=#Widget] getCustomSize
-- @param self
-- @return size_table#size_table ret (return value: size_table)
--------------------------------
--
-- @function [parent=#Widget] getLeftBoundary
-- @param self
-- @return float#float ret (return value: float)
--------------------------------
-- Sets whether the widget should be flipped horizontally or not.<br>
-- param bFlippedX true if the widget should be flipped horizaontally, false otherwise.
-- @function [parent=#Widget] setFlippedX
-- @param self
-- @param #bool flippedX
--------------------------------
-- callbackName getter and setter.
-- @function [parent=#Widget] setCallbackName
-- @param self
-- @param #string callbackName
--------------------------------
-- Gets the Virtual Renderer of widget.<br>
-- For example, a button's Virtual Renderer is it's texture renderer.<br>
-- return Node pointer.
-- @function [parent=#Widget] getVirtualRenderer
-- @param self
-- @return Node#Node ret (return value: cc.Node)
--------------------------------
-- brief Allow widget touch events to propagate to its parents. Set false will disable propagation<br>
-- since v3.3
-- @function [parent=#Widget] setPropagateTouchEvents
-- @param self
-- @param #bool isPropagate
--------------------------------
-- return true represent the widget use Unify Size, false represent the widget couldn't use Unify Size
-- @function [parent=#Widget] isUnifySizeEnabled
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
-- Returns size percent of widget<br>
-- return size percent
-- @function [parent=#Widget] getSizePercent
-- @param self
-- @return vec2_table#vec2_table ret (return value: vec2_table)
--------------------------------
-- Set the percent(x,y) of the widget in OpenGL coordinates<br>
-- param percent The percent (x,y) of the widget in OpenGL coordinates
-- @function [parent=#Widget] setPositionPercent
-- @param self
-- @param #vec2_table percent
--------------------------------
-- brief Specify widget to swallow touches or not<br>
-- since v3.3
-- @function [parent=#Widget] setSwallowTouches
-- @param self
-- @param #bool swallow
--------------------------------
--
-- @function [parent=#Widget] getLayoutSize
-- @param self
-- @return size_table#size_table ret (return value: size_table)
--------------------------------
-- Sets whether the widget is hilighted<br>
-- The default value is false, a widget is default to not hilighted<br>
-- param hilight true if the widget is hilighted, false if the widget is not hilighted.
-- @function [parent=#Widget] setHighlighted
-- @param self
-- @param #bool hilight
--------------------------------
-- Changes the position type of the widget<br>
-- see PositionType<br>
-- param type the position type of widget
-- @function [parent=#Widget] setPositionType
-- @param self
-- @param #int type
--------------------------------
-- Query whether the widget ignores user deinfed content size or not<br>
-- return bool
-- @function [parent=#Widget] isIgnoreContentAdaptWithSize
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
--
-- @function [parent=#Widget] getVirtualRendererSize
-- @param self
-- @return size_table#size_table ret (return value: size_table)
--------------------------------
-- Determines if the widget is highlighted<br>
-- return true if the widget is highlighted, false if the widget is not hignlighted .
-- @function [parent=#Widget] isHighlighted
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
-- Gets LayoutParameter of widget.<br>
-- see LayoutParameter<br>
-- param type Relative or Linear<br>
-- return LayoutParameter
-- @function [parent=#Widget] getLayoutParameter
-- @param self
-- @return LayoutParameter#LayoutParameter ret (return value: ccui.LayoutParameter)
--------------------------------
-- Set a event handler to the widget in order to use cocostudio editor and framework
-- @function [parent=#Widget] addCCSEventListener
-- @param self
-- @param #function callback
--------------------------------
-- Gets the position type of the widget<br>
-- see PositionType<br>
-- return type the position type of widget
-- @function [parent=#Widget] getPositionType
-- @param self
-- @return int#int ret (return value: int)
--------------------------------
--
-- @function [parent=#Widget] getTopBoundary
-- @param self
-- @return float#float ret (return value: float)
--------------------------------
-- Note: when you set _ignoreSize to true, no matther you call setContentSize or not, <br>
-- the widget size is always equal to the return value of the member function getVirtualRendererSize.<br>
-- param ignore, set member variabl _ignoreSize to ignore
-- @function [parent=#Widget] ignoreContentAdaptWithSize
-- @param self
-- @param #bool ignore
--------------------------------
-- When a widget is in a layout, you could call this method to get the next focused widget within a specified direction. <br>
-- If the widget is not in a layout, it will return itself<br>
-- param dir the direction to look for the next focused widget in a layout<br>
-- param current the current focused widget<br>
-- return the next focused widget in a layout
-- @function [parent=#Widget] findNextFocusedWidget
-- @param self
-- @param #int direction
-- @param #ccui.Widget current
-- @return Widget#Widget ret (return value: ccui.Widget)
--------------------------------
-- Determines if the widget is enabled<br>
-- return true if the widget is enabled, false if the widget is disabled.
-- @function [parent=#Widget] isEnabled
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
-- return whether the widget is focused or not
-- @function [parent=#Widget] isFocused
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
--
-- @function [parent=#Widget] getTouchBeganPosition
-- @param self
-- @return vec2_table#vec2_table ret (return value: vec2_table)
--------------------------------
-- Determines if the widget is touch enabled<br>
-- return true if the widget is touch enabled, false if the widget is touch disabled.
-- @function [parent=#Widget] isTouchEnabled
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
--
-- @function [parent=#Widget] getCallbackName
-- @param self
-- @return string#string ret (return value: string)
--------------------------------
--
-- @function [parent=#Widget] getActionTag
-- @param self
-- @return int#int ret (return value: int)
--------------------------------
-- Gets world position of widget.<br>
-- return world position of widget.
-- @function [parent=#Widget] getWorldPosition
-- @param self
-- @return vec2_table#vec2_table ret (return value: vec2_table)
--------------------------------
-- return true represent the widget could accept focus, false represent the widget couldn't accept focus
-- @function [parent=#Widget] isFocusEnabled
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
-- param focus pass true to let the widget get focus or pass false to let the widget lose focus<br>
-- return void
-- @function [parent=#Widget] setFocused
-- @param self
-- @param #bool focus
--------------------------------
--
-- @function [parent=#Widget] setActionTag
-- @param self
-- @param #int tag
--------------------------------
-- Sets whether the widget is touch enabled<br>
-- The default value is false, a widget is default to touch disabled<br>
-- param visible true if the widget is touch enabled, false if the widget is touch disabled.
-- @function [parent=#Widget] setTouchEnabled
-- @param self
-- @param #bool enabled
--------------------------------
-- Sets whether the widget should be flipped vertically or not.<br>
-- param bFlippedY true if the widget should be flipped vertically, flase otherwise.
-- @function [parent=#Widget] setFlippedY
-- @param self
-- @param #bool flippedY
--------------------------------
-- Sets whether the widget is enabled<br>
-- true if the widget is enabled, widget may be touched , false if the widget is disabled, widget cannot be touched.<br>
-- The default value is true, a widget is default to enabled<br>
-- param enabled
-- @function [parent=#Widget] setEnabled
-- @param self
-- @param #bool enabled
--------------------------------
--
-- @function [parent=#Widget] getRightBoundary
-- @param self
-- @return float#float ret (return value: float)
--------------------------------
-- To set the bright style of widget.<br>
-- see BrightStyle<br>
-- param style BrightStyle::NORMAL means the widget is in normal state, BrightStyle::HIGHLIGHT means the widget is in highlight state.
-- @function [parent=#Widget] setBrightStyle
-- @param self
-- @param #int style
--------------------------------
-- Sets a LayoutParameter to widget.<br>
-- see LayoutParameter<br>
-- param LayoutParameter pointer<br>
-- param type Relative or Linear
-- @function [parent=#Widget] setLayoutParameter
-- @param self
-- @param #ccui.LayoutParameter parameter
--------------------------------
--
-- @function [parent=#Widget] clone
-- @param self
-- @return Widget#Widget ret (return value: ccui.Widget)
--------------------------------
-- param enable pass true/false to enable/disable the focus ability of a widget<br>
-- return void
-- @function [parent=#Widget] setFocusEnabled
-- @param self
-- @param #bool enable
--------------------------------
--
-- @function [parent=#Widget] getBottomBoundary
-- @param self
-- @return float#float ret (return value: float)
--------------------------------
-- Determines if the widget is bright<br>
-- return true if the widget is bright, false if the widget is dark.
-- @function [parent=#Widget] isBright
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
-- param enable Unify Size of a widget<br>
-- return void
-- @function [parent=#Widget] setUnifySizeEnabled
-- @param self
-- @param #bool enable
--------------------------------
-- Return whether the widget is propagate touch events to its parents or not<br>
-- since v3.3
-- @function [parent=#Widget] isPropagateTouchEvents
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
--
-- @function [parent=#Widget] getCurrentFocusedWidget
-- @param self
-- @return Widget#Widget ret (return value: ccui.Widget)
--------------------------------
-- Checks a point if is in widget's space<br>
-- param point<br>
-- return true if the point is in widget's space, flase otherwise.
-- @function [parent=#Widget] hitTest
-- @param self
-- @param #vec2_table pt
-- @return bool#bool ret (return value: bool)
--------------------------------
-- when a widget calls this method, it will get focus immediately.
-- @function [parent=#Widget] requestFocus
-- @param self
--------------------------------
-- @overload self, size_table
-- @overload self
-- @function [parent=#Widget] updateSizeAndPosition
-- @param self
-- @param #size_table parentSize
--------------------------------
--
-- @function [parent=#Widget] getTouchMovePosition
-- @param self
-- @return vec2_table#vec2_table ret (return value: vec2_table)
--------------------------------
-- Gets the size type of widget.<br>
-- see SizeType<br>
-- param type that is widget's size type
-- @function [parent=#Widget] getSizeType
-- @param self
-- @return int#int ret (return value: int)
--------------------------------
--
-- @function [parent=#Widget] getCallbackType
-- @param self
-- @return string#string ret (return value: string)
--------------------------------
--
-- @function [parent=#Widget] addTouchEventListener
-- @param self
-- @param #function callback
--------------------------------
--
-- @function [parent=#Widget] getTouchEndPosition
-- @param self
-- @return vec2_table#vec2_table ret (return value: vec2_table)
--------------------------------
-- Gets the percent (x,y) of the widget in OpenGL coordinates<br>
-- see setPosition(const Vec2&)<br>
-- return The percent (x,y) of the widget in OpenGL coordinates
-- @function [parent=#Widget] getPositionPercent
-- @param self
-- @return vec2_table#vec2_table ret (return value: vec2_table)
--------------------------------
-- Set a click event handler to the widget
-- @function [parent=#Widget] addClickEventListener
-- @param self
-- @param #function callback
--------------------------------
-- Returns the flag which indicates whether the widget is flipped horizontally or not.<br>
-- It only flips the texture of the widget, and not the texture of the widget's children.<br>
-- Also, flipping the texture doesn't alter the anchorPoint.<br>
-- If you want to flip the anchorPoint too, and/or to flip the children too use:<br>
-- widget->setScaleX(sprite->getScaleX() * -1);<br>
-- return true if the widget is flipped horizaontally, false otherwise.
-- @function [parent=#Widget] isFlippedX
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
-- Return the flag which indicates whether the widget is flipped vertically or not.<br>
-- It only flips the texture of the widget, and not the texture of the widget's children.<br>
-- Also, flipping the texture doesn't alter the anchorPoint.<br>
-- If you want to flip the anchorPoint too, and/or to flip the children too use:<br>
-- widget->setScaleY(widget->getScaleY() * -1);<br>
-- return true if the widget is flipped vertically, flase otherwise.
-- @function [parent=#Widget] isFlippedY
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
--
-- @function [parent=#Widget] isClippingParentContainsPoint
-- @param self
-- @param #vec2_table pt
-- @return bool#bool ret (return value: bool)
--------------------------------
-- Changes the size type of widget.<br>
-- see SizeType<br>
-- param type that is widget's size type
-- @function [parent=#Widget] setSizeType
-- @param self
-- @param #int type
--------------------------------
-- Sets whether the widget is bright<br>
-- The default value is true, a widget is default to bright<br>
-- param visible true if the widget is bright, false if the widget is dark.
-- @function [parent=#Widget] setBright
-- @param self
-- @param #bool bright
--------------------------------
-- callbackType getter and setter.
-- @function [parent=#Widget] setCallbackType
-- @param self
-- @param #string callbackType
--------------------------------
-- Return whether the widget is swallowing touch or not<br>
-- since v3.3
-- @function [parent=#Widget] isSwallowTouches
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
--
-- @function [parent=#Widget] enableDpadNavigation
-- @param self
-- @param #bool enable
--------------------------------
-- Allocates and initializes a widget.
-- @function [parent=#Widget] create
-- @param self
-- @return Widget#Widget ret (return value: ccui.Widget)
--------------------------------
--
-- @function [parent=#Widget] setScaleY
-- @param self
-- @param #float scaleY
--------------------------------
--
-- @function [parent=#Widget] setScaleX
-- @param self
-- @param #float scaleX
--------------------------------
--
-- @function [parent=#Widget] getScaleY
-- @param self
-- @return float#float ret (return value: float)
--------------------------------
--
-- @function [parent=#Widget] getScaleX
-- @param self
-- @return float#float ret (return value: float)
--------------------------------
-- Returns the "class name" of widget.
-- @function [parent=#Widget] getDescription
-- @param self
-- @return string#string ret (return value: string)
--------------------------------
-- @overload self, float, float
-- @overload self, float
-- @function [parent=#Widget] setScale
-- @param self
-- @param #float scalex
-- @param #float scaley
--------------------------------
-- Changes the position (x,y) of the widget in OpenGL coordinates<br>
-- Usually we use p(x,y) to compose Vec2 object.<br>
-- The original point (0,0) is at the left-bottom corner of screen.<br>
-- param position The position (x,y) of the widget in OpenGL coordinates
-- @function [parent=#Widget] setPosition
-- @param self
-- @param #vec2_table pos
--------------------------------
--
-- @function [parent=#Widget] setContentSize
-- @param self
-- @param #size_table contentSize
--------------------------------
--
-- @function [parent=#Widget] getScale
-- @param self
-- @return float#float ret (return value: float)
--------------------------------
-- Default constructor
-- @function [parent=#Widget] Widget
-- @param self
return nil
| apache-2.0 |
ffxinfinity/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Sea_Serpent_Grotto/npcs/_4w5.lua | 4 | 2598 | -----------------------------------
-- Area: Sea Serpent Grotto
-- NPC: Silver Beastcoin Door
-- @zone 176
-- @pos 280 18.549 -100
-----------------------------------
package.loaded["scripts/zones/Sea_Serpent_Grotto/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Sea_Serpent_Grotto/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if(trade:hasItemQty(750,1) and trade:getItemCount() == 1) then
if(player:getVar("SSG_SilverDoor") == 7) then
npc:openDoor(5) --Open the door if a silver beastcoin has been traded after checking the door the required number of times
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
X = player:getXPos();
Z = player:getZPos();
SilverDoorCheck = player:getVar("SSG_SilverDoor");
if(X <= 280 and Z >= -104) then
if(SilverDoorCheck == 0) then --Door has never been checked
player:messageSpecial(FIRST_CHECK);
player:setVar("SSG_SilverDoor",1);
elseif(SilverDoorCheck == 1) then --Door has been checked once
player:messageSpecial(SECOND_CHECK);
player:setVar("SSG_SilverDoor",2);
elseif(SilverDoorCheck == 2) then --Door has been checked twice
player:messageSpecial(THIRD_CHECK);
player:setVar("SSG_SilverDoor",3);
elseif(SilverDoorCheck == 3) then --Door has been checked three times
player:messageSpecial(FOURTH_CHECK);
player:setVar("SSG_SilverDoor",4);
elseif(SilverDoorCheck == 4) then --Door has been checked four times
player:messageSpecial(FIFTH_CHECK);
player:setVar("SSG_SilverDoor",5);
elseif(SilverDoorCheck == 5) then --Door has been checked five times
player:messageSpecial(SILVER_CHECK);
player:setVar("SSG_SilverDoor",6);
elseif(SilverDoorCheck == 6 or SilverDoorCheck == 7) then --Door has been checked six or more times
player:messageSpecial(COMPLETED_CHECK,750);
player:setVar("SSG_SilverDoor",7);
end
return 1 --Keep the door closed
elseif(X > 280 and Z < -100) then
return -1 --Open the door if coming from the "inside"
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 |
ffxinfinity/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Metalworks/npcs/Raibaht.lua | 2 | 2648 | -----------------------------------
-- Area: Metalworks
-- NPC: Raibaht
-- Starts and Finishes Quest: Dark Legacy
-- Involved in Quest: The Usual, Riding on the Clouds
-- @zone 237
-- @pos -27 -10 -1
-----------------------------------
package.loaded["scripts/zones/Metalworks/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/zones/Metalworks/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if(player:getQuestStatus(JEUNO,RIDING_ON_THE_CLOUDS) == QUEST_ACCEPTED and player:getVar("ridingOnTheClouds_2") == 7) then
if(trade:hasItemQty(1127,1) and trade:getItemCount() == 1) then -- Trade Kindred seal
player:setVar("ridingOnTheClouds_2",0);
player:tradeComplete();
player:addKeyItem(SMILING_STONE);
player:messageSpecial(KEYITEM_OBTAINED,SMILING_STONE);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
darkLegacy = player:getQuestStatus(BASTOK,DARK_LEGACY);
mLvl = player:getMainLvl();
mJob = player:getMainJob();
if(darkLegacy == QUEST_AVAILABLE and mJob == 8 and mLvl >= AF1_QUEST_LEVEL) then
player:startEvent(0x02ef); -- Start Quest "Dark Legacy"
elseif(player:hasKeyItem(DARKSTEEL_FORMULA)) then
player:startEvent(0x02f3); -- Finish Quest "Dark Legacy"
elseif(player:hasKeyItem(127) and player:getVar("TheUsual_Event") ~= 1) then
player:startEvent(0x01fe);
else
player:startEvent(0x01f5);
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 == 0x01fe and option == 0) then
player:setVar("TheUsual_Event",1);
elseif(csid == 0x02ef) then
player:addQuest(BASTOK,DARK_LEGACY);
player:setVar("darkLegacyCS",1);
elseif(csid == 0x02f3) then
if(player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,16798); -- Raven Scythe
else
player:delKeyItem(DARKSTEEL_FORMULA);
player:addItem(16798);
player:messageSpecial(ITEM_OBTAINED, 16798); -- Raven Scythe
player:setVar("darkLegacyCS",0);
player:addFame(BASTOK,AF1_FAME);
player:completeQuest(BASTOK,DARK_LEGACY);
end
end
end; | gpl-3.0 |
waytim/darkstar | scripts/zones/LaLoff_Amphitheater/npcs/qm1_5.lua | 13 | 2440 | -----------------------------------
-- Area: LaLoff_Amphitheater
-- NPC: Shimmering Circle (BCNM Entrances)
-------------------------------------
package.loaded["scripts/zones/LaLoff_Amphitheater/TextIDs"] = nil;
package.loaded["scripts/globals/bcnm"] = 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");
-- Death cutscenes:
-- player:startEvent(0x7d01,1,instance:getFastestTime(),1,instance:getTimeInside(),1,0,0); -- hume
-- player:startEvent(0x7d01,1,instance:getFastestTime(),1,instance:getTimeInside(),1,1,0); -- taru
-- player:startEvent(0x7d01,1,instance:getFastestTime(),1,instance:getTimeInside(),1,2,0); -- mithra
-- player:startEvent(0x7d01,1,instance:getFastestTime(),1,instance:getTimeInside(),1,3,0); -- elvaan
-- player:startEvent(0x7d01,1,instance:getFastestTime(),1,instance:getTimeInside(),1,4,0); -- galka
-- player:startEvent(0x7d01,1,instance:getFastestTime(),1,instance:getTimeInside(),1,5,0); -- divine might
-- param 1: entrance #
-- param 2: fastest time
-- param 3: unknown
-- param 4: clear time
-- param 5: zoneid
-- param 6: exit cs (0-4 AA, 5 DM, 6-10 neo AA, 11 neo DM)
-- param 7: skip (0 - no skip, 1 - prompt, 2 - force)
-- param 8: 0
-----------------------------------
-- 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,5)) 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 |
db260179/openwrt-bpi-r1-luci | applications/luci-app-ddns/luasrc/model/cbi/ddns/overview.lua | 3 | 9548 | -- Copyright 2014-2017 Christian Schoenebeck <christian dot schoenebeck at gmail dot com>
-- Licensed to the public under the Apache License 2.0.
local NXFS = require "nixio.fs"
local CTRL = require "luci.controller.ddns" -- this application's controller
local DISP = require "luci.dispatcher"
local HTTP = require "luci.http"
local SYS = require "luci.sys"
local DDNS = require "luci.tools.ddns" -- ddns multiused functions
-- show hints ?
show_hints = not (DDNS.check_ipv6() -- IPv6 support
and DDNS.check_ssl() -- HTTPS support
and DDNS.check_proxy() -- Proxy support
and DDNS.check_bind_host() -- DNS TCP support
)
-- correct ddns-scripts version
need_update = DDNS.ipkg_ver_compare(DDNS.ipkg_ver_installed("ddns-scripts"), "<<", CTRL.DDNS_MIN)
-- html constants
font_red = [[<font color="red">]]
font_off = [[</font>]]
bold_on = [[<strong>]]
bold_off = [[</strong>]]
-- cbi-map definition -- #######################################################
m = Map("ddns")
-- first need to close <a> from cbi map template our <a> closed by template
m.title = [[</a><a href="javascript:alert(']]
.. translate("Version Information")
.. [[\n\nluci-app-ddns]]
.. [[\n\t]] .. translate("Version") .. [[:\t]] .. DDNS.ipkg_ver_installed("luci-app-ddns")
.. [[\n\nddns-scripts ]] .. translate("required") .. [[:]]
.. [[\n\t]] .. translate("Version") .. [[:\t]] .. CTRL.DDNS_MIN .. [[ ]] .. translate("or higher")
.. [[\n\nddns-scripts ]] .. translate("installed") .. [[:]]
.. [[\n\t]] .. translate("Version") .. [[:\t]] .. DDNS.ipkg_ver_installed("ddns-scripts")
.. [[\n\n]]
.. [[')">]]
.. translate("Dynamic DNS")
m.description = translate("Dynamic DNS allows that your router can be reached with " ..
"a fixed hostname while having a dynamically changing " ..
"IP address.")
m.on_after_commit = function(self)
if self.changed then -- changes ?
local command = CTRL.luci_helper
if SYS.init.enabled("ddns") then -- ddns service enabled, restart all
command = command .. " -- restart"
os.execute(command)
else -- ddns service disabled, send SIGHUP to running
command = command .. " -- reload"
os.execute(command)
end
end
end
-- SimpleSection definiton -- ##################################################
-- with all the JavaScripts we need for "a good Show"
a = m:section( SimpleSection )
a.template = "ddns/overview_status"
-- SimpleSection definition -- #################################################
-- show Hints to optimize installation and script usage
-- only show if service not enabled
-- or no IPv6 support
-- or not GNU Wget and not cURL (for https support)
-- or not GNU Wget but cURL without proxy support
-- or not BIND's host
-- or ddns-scripts package need update
if show_hints or need_update or not SYS.init.enabled("ddns") then
s = m:section( SimpleSection, translate("Hints") )
-- ddns_scripts needs to be updated for full functionality
if need_update then
local dv = s:option(DummyValue, "_update_needed")
dv.titleref = DISP.build_url("admin", "system", "packages")
dv.rawhtml = true
dv.title = font_red .. bold_on ..
translate("Software update required") .. bold_off .. font_off
dv.value = translate("The currently installed 'ddns-scripts' package did not support all available settings.") ..
"<br />" ..
translate("Please update to the current version!")
end
-- DDNS Service disabled
if not SYS.init.enabled("ddns") then
local dv = s:option(DummyValue, "_not_enabled")
dv.titleref = DISP.build_url("admin", "system", "startup")
dv.rawhtml = true
dv.title = bold_on ..
translate("DDNS Autostart disabled") .. bold_off
dv.value = translate("Currently DDNS updates are not started at boot or on interface events." .. "<br />" ..
"You can start/stop each configuration here. It will run until next reboot.")
end
-- Show more hints on a separate page
if show_hints then
local dv = s:option(DummyValue, "_separate")
dv.titleref = DISP.build_url("admin", "services", "ddns", "hints")
dv.rawhtml = true
dv.title = bold_on ..
translate("Show more") .. bold_off
dv.value = translate("Follow this link" .. "<br />" ..
"You will find more hints to optimize your system to run DDNS scripts with all options")
end
end
-- TableSection definition -- ##################################################
ts = m:section( TypedSection, "service",
translate("Overview"),
translate("Below is a list of configured DDNS configurations and their current state.")
.. "<br />"
.. translate("If you want to send updates for IPv4 and IPv6 you need to define two separate Configurations "
.. "i.e. 'myddns_ipv4' and 'myddns_ipv6'")
.. "<br />"
.. [[<a href="]] .. DISP.build_url("admin", "services", "ddns", "global") .. [[">]]
.. translate("To change global settings click here") .. [[</a>]] )
ts.sectionhead = translate("Configuration")
ts.template = "cbi/tblsection"
ts.addremove = true
ts.extedit = DISP.build_url("admin", "services", "ddns", "detail", "%s")
function ts.create(self, name)
AbstractSection.create(self, name)
HTTP.redirect( self.extedit:format(name) )
end
-- Lookup_Host and registered IP -- #################################################
dom = ts:option(DummyValue, "_lookupIP",
translate("Lookup Hostname") .. "<br />" .. translate("Registered IP") )
dom.template = "ddns/overview_doubleline"
function dom.set_one(self, section)
local lookup = self.map:get(section, "lookup_host") or ""
if lookup ~= "" then
return lookup
else
return [[<em>]] .. translate("config error") .. [[</em>]]
end
end
function dom.set_two(self, section)
local lookup_host = self.map:get(section, "lookup_host") or ""
if lookup_host == "" then return "" end
local dnsserver = self.map:get(section, "dnsserver") or ""
local use_ipv6 = tonumber(self.map:get(section, "use_ipv6") or 0)
local force_ipversion = tonumber(self.map:get(section, "force_ipversion") or 0)
local force_dnstcp = tonumber(self.map:get(section, "force_dnstcp") or 0)
local is_glue = tonumber(self.map:get(section, "is_glue") or 0)
local command = CTRL.luci_helper .. [[ -]]
if (use_ipv6 == 1) then command = command .. [[6]] end
if (force_ipversion == 1) then command = command .. [[f]] end
if (force_dnstcp == 1) then command = command .. [[t]] end
if (is_glue == 1) then command = command .. [[g]] end
command = command .. [[l ]] .. lookup_host
if (#dnsserver > 0) then command = command .. [[ -d ]] .. dnsserver end
command = command .. [[ -- get_registered_ip]]
local ip = SYS.exec(command)
if ip == "" then ip = translate("no data") end
return ip
end
-- enabled
ena = ts:option( Flag, "enabled",
translate("Enabled"))
ena.template = "ddns/overview_enabled"
ena.rmempty = false
function ena.parse(self, section)
DDNS.flag_parse(self, section)
end
-- show PID and next update
upd = ts:option( DummyValue, "_update",
translate("Last Update") .. "<br />" .. translate("Next Update"))
upd.template = "ddns/overview_doubleline"
function upd.set_one(self, section) -- fill Last Update
-- get/validate last update
local uptime = SYS.uptime()
local lasttime = DDNS.get_lastupd(section)
if lasttime > uptime then -- /var might not be linked to /tmp and cleared on reboot
lasttime = 0
end
-- no last update happen
if lasttime == 0 then
return translate("never")
-- we read last update
else
-- calc last update
-- os.epoch - sys.uptime + lastupdate(uptime)
local epoch = os.time() - uptime + lasttime
-- use linux date to convert epoch
return DDNS.epoch2date(epoch)
end
end
function upd.set_two(self, section) -- fill Next Update
-- get enabled state
local enabled = tonumber(self.map:get(section, "enabled") or 0)
local datenext = translate("unknown error") -- formatted date of next update
-- get force seconds
local force_interval = tonumber(self.map:get(section, "force_interval") or 72)
local force_unit = self.map:get(section, "force_unit") or "hours"
local force_seconds = DDNS.calc_seconds(force_interval, force_unit)
-- get last update and get/validate PID
local uptime = SYS.uptime()
local lasttime = DDNS.get_lastupd(section)
if lasttime > uptime then -- /var might not be linked to /tmp and cleared on reboot
lasttime = 0
end
local pid = DDNS.get_pid(section)
-- calc next update
if lasttime > 0 then
local epoch = os.time() - uptime + lasttime + force_seconds
-- use linux date to convert epoch
datelast = DDNS.epoch2date(epoch)
end
-- process running but update needs to happen
if pid > 0 and ( lasttime + force_seconds - uptime ) < 0 then
datenext = translate("Verify")
-- run once
elseif force_seconds == 0 then
datenext = translate("Run once")
-- no process running and NOT enabled
elseif pid == 0 and enabled == 0 then
datenext = translate("Disabled")
-- no process running and NOT
elseif pid == 0 and enabled ~= 0 then
datenext = translate("Stopped")
end
return datenext
end
-- start/stop button
btn = ts:option( Button, "_startstop",
translate("Process ID") .. "<br />" .. translate("Start / Stop") )
btn.template = "ddns/overview_startstop"
function btn.cfgvalue(self, section)
local pid = DDNS.get_pid(section)
if pid > 0 then
btn.inputtitle = "PID: " .. pid
btn.inputstyle = "reset"
btn.disabled = false
elseif (self.map:get(section, "enabled") or "0") ~= "0" then
btn.inputtitle = translate("Start")
btn.inputstyle = "apply"
btn.disabled = false
else
btn.inputtitle = "----------"
btn.inputstyle = "button"
btn.disabled = true
end
return true
end
return m
| apache-2.0 |
ffxinfinity/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Port_San_dOria/npcs/Bonarpant.lua | 6 | 1318 | -----------------------------------
-- Area: Port San d'Oria
-- NPC: Bonarpant
-- 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(0x253);
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 |
waytim/darkstar | scripts/globals/mobskills/Wanion.lua | 43 | 1329 | ---------------------------------------------------
-- Wanion
-- AoE of all status ailments it has.
---------------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------------
function onMobSkillCheck(target,mob,skill)
return 0;
end;
function onMobWeaponSkill(target, mob, skill)
-- list of effects to give in AoE
local effects = {EFFECT_SLOW, EFFECT_DIA, EFFECT_BIO, EFFECT_WEIGHT, EFFECT_DEFENSE_DOWN, EFFECT_PARALYSIS, EFFECT_BLINDNESS, EFFECT_SILENCE, EFFECT_POISON}
local lastEffect = 0;
local effectCount = false;
for i, effect in ipairs(effects) do
if (mob:hasStatusEffect(effect) == true) then
effectCount = true;
local currentEffect = mob:getStatusEffect(effect);
local msg = MobStatusEffectMove(mob, target, effect, currentEffect:getPower(), 3, 120);
if (msg == MSG_ENFEEB_IS) then
lastEffect = effect;
end
end
end
-- all resisted
if (lastEffect == 0) then
skill:setMsg(MSG_RESIST);
end
-- no effects present
if (effectCount == false) then
skill:setMsg(MSG_NO_EFFECT);
end
return lastEffect;
end;
| gpl-3.0 |
waytim/darkstar | scripts/globals/abilities/pets/flaming_crush.lua | 29 | 1356 | ---------------------------------------------------
-- Flaming Crush M=10, 2, 2? (STILL don't know)
---------------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/summon");
require("scripts/globals/magic");
require("scripts/globals/monstertpmoves");
---------------------------------------------------
function onAbilityCheck(player, target, ability)
return 0,0;
end;
function onPetAbility(target, pet, skill)
local numhits = 3;
local accmod = 1;
local dmgmod = 10;
local dmgmodsubsequent = 1;
local totaldamage = 0;
local damage = AvatarPhysicalMove(pet,target,skill,numhits,accmod,dmgmod,dmgmodsubsequent,TP_NO_EFFECT,1,2,3);
--get resist multiplier (1x if no resist)
local resist = applyPlayerResistance(pet,-1,target,pet:getStat(MOD_INT)-target:getStat(MOD_INT),ELEMENTAL_MAGIC_SKILL, ELE_FIRE);
--get the resisted damage
damage.dmg = damage.dmg*resist;
--add on bonuses (staff/day/weather/jas/mab/etc all go in this function)
damage.dmg = mobAddBonuses(pet,spell,target,damage.dmg,1);
totaldamage = AvatarFinalAdjustments(damage.dmg,pet,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_BLUNT,numhits);
target:delHP(totaldamage);
target:updateEnmityFromDamage(pet,totaldamage);
return totaldamage;
end | gpl-3.0 |
grit-engine/grit-engine | engine/tests/engine/gfx_ranged_instances/test.lua | 2 | 1557 | gfx_colour_grade(`neutral.lut.png`)
gfx_fade_dither_map `stipple.png`
gfx_register_shader(`Money`, {
tex = {
uniformKind = "TEXTURE2D",
},
vertexCode = [[
var normal_ws = rotate_to_world(vert.normal.xyz);
]],
dangsCode = [[
out.diffuse = sample(mat.tex, vert.coord0.xy).rgb;
out.gloss = 0;
out.specular = 0;
out.normal = normal_ws;
]],
additionalCode = [[
// out.colour = sample(mat.tex, vert.coord0.xy).rgb;
// out.colour = Float3(1, 1, 1);
]],
})
-- Used by Money.mesh.
register_material(`Money`, {
shader = `Money`,
tex = `Money_d.dds`,
additionalLighting = false,
})
print "Loading Money_d.dds"
disk_resource_load(`Money_d.dds`)
print "Loading Money.mesh"
disk_resource_load(`Money.mesh`)
gfx_sunlight_direction(vec(0, 0, -1))
gfx_sunlight_diffuse(vec(1, 1, 1))
gfx_sunlight_specular(vec(1, 1, 1))
b = gfx_instances_make(`Money.mesh`)
b.castShadows = false
b:add(vec(0, 0, 0), quat(1, 0, 0, 0), 1)
b:add(vec(0.4, 0, 0), quat(1, 0, 0, 0), 1)
b:add(vec(0, 0.4, 0), quat(1, 0, 0, 0), 1)
b:add(vec(0.4, 0.4, 0), quat(1, 0, 0, 0), 1)
b:add(vec(0.4, 0.8, 0), quat(0, 1, 0, 0), 1)
b:add(vec(0.8, 0.8, 0), quat(0, 1, 0, 0), 0.5)
-- b2 = gfx_body_make(`Money.mesh`)
-- b2.castShadows = false
gfx_render(0.1, vec(0.04362189, -0.9296255, 0.5302261), quat(0.9800102, -0.1631184, 0.01870036, -0.1123512))
gfx_render(0.1, vec(0.04362189, -0.9296255, 0.5302261), quat(0.9800102, -0.1631184, 0.01870036, -0.1123512))
gfx_screenshot('output.png')
| mit |
TheOnePharaoh/YGOPro-Custom-Cards | script/c66666611.lua | 2 | 2359 | --Aetherial Counterforce
function c66666611.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_NEGATE+CATEGORY_DESTROY+CATEGORY_DRAW)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_CHAINING)
e1:SetCountLimit(1,66666611)
e1:SetCondition(c66666611.condition)
e1:SetCost(c66666611.cost)
e1:SetTarget(c66666611.target)
e1:SetOperation(c66666611.activate)
c:RegisterEffect(e1)
end
function c66666611.condition(e,tp,eg,ep,ev,re,r,rp)
return (re:IsActiveType(TYPE_MONSTER) or re:IsHasType(EFFECT_TYPE_ACTIVATE)) and Duel.IsChainNegatable(ev)
end
function c66666611.cfilter(c)
return c:IsFaceup() and c:IsSetCard(0x144) and c:IsDestructable()and c:IsType(TYPE_PENDULUM)
end
function c66666611.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c66666611.cfilter,tp,LOCATION_SZONE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY)
local g=Duel.SelectMatchingCard(tp,c66666611.cfilter,tp,LOCATION_SZONE,0,1,1,nil)
Duel.Destroy(g,REASON_COST)
end
function c66666611.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsPlayerCanDraw(tp,1) 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)
Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,1)
end
end
function c66666611.activate(e,tp,eg,ep,ev,re,r,rp)
if not Duel.NegateActivation(ev) then return end
if re:GetHandler():IsRelateToEffect(re) and Duel.Destroy(eg,REASON_EFFECT)~=0 then
Duel.BreakEffect()
Duel.Draw(tp,1,REASON_EFFECT)
end
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetProperty(EFFECT_FLAG_SET_AVAILABLE)
e1:SetCode(EFFECT_FORBIDDEN)
e1:SetTargetRange(0x7f,0x7f)
e1:SetTarget(c66666611.bantg)
e1:SetLabel(ac)
e1:SetReset(RESET_PHASE+PHASE_END)
Duel.RegisterEffect(e1,tp)
local e2=Effect.CreateEffect(e:GetHandler())
e2:SetType(EFFECT_TYPE_FIELD)
e2:SetCode(EFFECT_DISABLE)
e2:SetTargetRange(0x7f,0x7f)
e2:SetTarget(c66666611.bantg)
e2:SetLabel(ac)
e2:SetReset(RESET_PHASE+PHASE_END)
Duel.RegisterEffect(e2,tp)
end
function c66666611.aclimit(e,re,tp)
return re:IsHasType(EFFECT_TYPE_ACTIVATE) and re:GetHandler():IsCode(e:GetLabel())
end
function c66666611.bantg(e,c)
return c:IsCode(e:GetLabel())
end
| gpl-3.0 |
waytim/darkstar | scripts/zones/Xarcabard/npcs/qm7.lua | 12 | 1491 | -----------------------------------
-- Area: Xarcabard
-- NPC: qm7 (???)
-- Involved in Quests: RNG AF3 quest - Unbridled Passion
-- @pos -295.065 -25.054 151.250 112
-----------------------------------
package.loaded["scripts/zones/Xarcabard/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/Xarcabard/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
local koenigsTiger = 17236205;
function onTrigger(player,npc)
local UnbridledPassionCS = player:getVar("unbridledPassion");
local tigerAction = GetMobAction(koenigsTiger);
if (UnbridledPassionCS == 4 and tigerAction == 0) then -- prevent repeated playback while the tiger is already up and fighting
player:startEvent(0x0008);
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 == 0x0008) then
SpawnMob(koenigsTiger,240):updateClaim(player);
end
end; | gpl-3.0 |
waytim/darkstar | scripts/zones/Abyssea-Tahrongi/npcs/qm14.lua | 17 | 1888 | -----------------------------------
-- Zone: Abyssea-Tahrongi
-- NPC: ???
-- Spawns: Glavoid
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/keyitems");
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
--[[
if (GetMobAction(16961950) == ACTION_NONE) then -- NM not already spawned from this
if (player:hasKeyItem(FAT_LINED_COCKATRICE_SKIN) and player:hasKeyItem(SODDEN_SANDWORM_HUSK)
and player:hasKeyItem(LUXURIANT_MANTICORE_MANE) -- I broke it into 3 lines at the 'and' because it was so long.
and player:hasKeyItem(STICKY_GNAT_WING)) then
player:startEvent(1020, FAT_LINED_COCKATRICE_SKIN, SODDEN_SANDWORM_HUSK, LUXURIANT_MANTICORE_MANE, STICKY_GNAT_WING); -- Ask if player wants to use KIs
else
player:startEvent(1021, FAT_LINED_COCKATRICE_SKIN, SODDEN_SANDWORM_HUSK, LUXURIANT_MANTICORE_MANE, STICKY_GNAT_WING); -- Do not ask, because player is missing at least 1.
end
end
]]
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID2: %u",csid);
-- printf("RESULT2: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 1020 and option == 1) then
SpawnMob(16961950):updateClaim(player); -- Spawn NM, Despawn after inactive for 5 minutes (pt has to reclaim within 5 of a wipe)
player:delKeyItem(FAT_LINED_COCKATRICE_SKIN);
player:delKeyItem(SODDEN_SANDWORM_HUSK);
player:delKeyItem(LUXURIANT_MANTICORE_MANE);
player:delKeyItem(STICKY_GNAT_WING);
end
end; | gpl-3.0 |
waytim/darkstar | scripts/zones/Selbina/npcs/Tilala.lua | 13 | 1151 | -----------------------------------
-- Area: Selbina
-- NPC: Tilala
-- Guild Merchant NPC: Clothcrafting Guild
-- @pos 14.344 -7.912 10.276 248
-----------------------------------
package.loaded["scripts/zones/Selbina/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/shop");
require("scripts/zones/Selbina/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:sendGuild(516,6,21,0)) then
player:showText(npc,CLOTHCRAFT_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 |
ffxinfinity/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Port_Bastok/npcs/Oggbi.lua | 4 | 3115 | -----------------------------------
-- Area: Port Bastok
-- NPC: Oggbi
-- Starts and Finishes: Ghosts of the Past, The First Meeting
-- @zone 236
-- @pos -159 -7 5
-----------------------------------
package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/zones/Port_Bastok/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if(player:getQuestStatus(BASTOK,GHOSTS_OF_THE_PAST) == QUEST_ACCEPTED) then
if(trade:hasItemQty(13122,1) and trade:getItemCount() == 1) then -- Trade Miner's Pendant
player:startEvent(0x00e8); -- Finish Quest "Ghosts of the Past"
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
ghostsOfThePast = player:getQuestStatus(BASTOK,GHOSTS_OF_THE_PAST);
theFirstMeeting = player:getQuestStatus(BASTOK,THE_FIRST_MEETING);
mLvl = player:getMainLvl();
mJob = player:getMainJob();
if(ghostsOfThePast == QUEST_AVAILABLE and mJob == 2 and mLvl >= 40) then
player:startEvent(0x00e7); -- Start Quest "Ghosts of the Past"
elseif(ghostsOfThePast == QUEST_COMPLETED and player:needToZone() == false and theFirstMeeting == QUEST_AVAILABLE and mJob == 2 and mLvl >= 50) then
player:startEvent(0x00e9); -- Start Quest "The First Meeting"
elseif(player:hasKeyItem(LETTER_FROM_DALZAKK) and player:hasKeyItem(SANDORIAN_MARTIAL_ARTS_SCROLL)) then
player:startEvent(0x00ea); -- Finish Quest "The First Meeting"
else
player:startEvent(0x00e6); -- Standard Dialog
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if(csid == 0x00e7) then
player:addQuest(BASTOK,GHOSTS_OF_THE_PAST);
elseif(csid == 0x00e8) then
if(player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,17478); -- Beat Cesti
else
player:tradeComplete();
player:addItem(17478);
player:messageSpecial(ITEM_OBTAINED,17478); -- Beat Cesti
player:needToZone(true);
player:addFame(BASTOK,AF1_FAME);
player:completeQuest(BASTOK,GHOSTS_OF_THE_PAST);
end
elseif(csid == 0x00e9) then
player:addQuest(BASTOK,THE_FIRST_MEETING);
elseif(csid == 0x00ea) then
if(player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,14090); -- Temple Gaiters
else
player:delKeyItem(LETTER_FROM_DALZAKK);
player:delKeyItem(SANDORIAN_MARTIAL_ARTS_SCROLL);
player:addItem(14090);
player:messageSpecial(ITEM_OBTAINED,14090); -- Temple Gaiters
player:addFame(BASTOK,AF2_FAME);
player:completeQuest(BASTOK,THE_FIRST_MEETING);
end
end
end; | gpl-3.0 |
ffxinfinity/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Windurst_Waters/npcs/Leepe-Hoppe.lua | 2 | 7656 | -----------------------------------
-- Area: Windurst Waters
-- NPC: Leepe-Hoppe
-- Involved in Mission 1-3
-- @pos 13 -9 -197 238
-----------------------------------
package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/missions");
require("scripts/globals/keyitems");
require("scripts/zones/Windurst_Waters/TextIDs");
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
moonlitPath = player:getQuestStatus(WINDURST,THE_MOONLIT_PATH)
realday = tonumber(os.date("%j")); -- %M for next minute, %j for next day
-- Check if we are on Windurst Mission 1-3
if(player:getCurrentMission(WINDURST) == THE_PRICE_OF_PEACE) then
MissionStatus = player:getVar("MissionStatus");
if(player:hasKeyItem(FOOD_OFFERINGS) == false and player:hasKeyItem(DRINK_OFFERINGS) == false) then
player:startEvent(0x008c);
elseif(MissionStatus >= 1 and MissionStatus < 3) then
player:startEvent(0x008e); -- Keep displaying the instructions
end
elseif(player:getQuestStatus(WINDURST,FOOD_FOR_THOUGHT) == QUEST_ACCEPTED) then
player:startEvent(0x0137);
-- The Moonlit Path and Other Fenrir Stuff!
elseif(moonlitPath == QUEST_AVAILABLE and
player:getFameLevel(WINDURST) >= 6 and
player:getFameLevel(SANDORIA) >= 6 and
player:getFameLevel(BASTOK) >= 6 and
player:getFameLevel(NORG) >= 4) then -- Fenrir flag event
player:startEvent(0x034a,0,1125);
elseif(moonlitPath == QUEST_ACCEPTED) then
if(player:hasKeyItem(MOON_BAUBLE)) then -- Default text after acquiring moon bauble and before fighting Fenrir
player:startEvent(0x034d,0,1125,334);
elseif(player:hasKeyItem(WHISPER_OF_THE_MOON)) then -- First turn-in
player:startEvent(0x034e,0,13399,1208,1125,0,18165,13572);
elseif(player:hasKeyItem(WHISPER_OF_FLAMES) and
player:hasKeyItem(WHISPER_OF_TREMORS) and
player:hasKeyItem(WHISPER_OF_TIDES) and
player:hasKeyItem(WHISPER_OF_GALES) and
player:hasKeyItem(WHISPER_OF_FROST) and
player:hasKeyItem(WHISPER_OF_STORMS)) then
-- Collected the whispers
player:startEvent(0x034c,0,1125,334);
else -- Talked to after flag without the whispers
player:startEvent(0x034b,0,1125);
end
elseif(moonlitPath == QUEST_COMPLETED) then
if(player:hasKeyItem(MOON_BAUBLE)) then -- Default text after acquiring moon bauble and before fighting Fenrir
player:startEvent(0x034d,0,1125,334);
elseif(player:hasKeyItem(WHISPER_OF_THE_MOON)) then -- Repeat turn-in
local availRewards = 0
if(player:hasItem(18165)) then availRewards = availRewards + 1; end -- Fenrir's Stone
if(player:hasItem(13572)) then availRewards = availRewards + 2; end -- Fenrir's Cape
if(player:hasItem(13138)) then availRewards = availRewards + 4; end -- Fenrir's Torque
if(player:hasItem(13399)) then availRewards = availRewards + 8; end -- Fenrir's Earring
if(player:hasItem(1208)) then availRewards = availRewards + 16; end -- Ancient's Key
if(player:hasSpell(297)) then availRewards = availRewards + 64; end -- Pact
player:startEvent(0x0352,0,13399,1208,1125,availRewards,18165,13572);
elseif(realday ~= player:getVar("MoonlitPath_date")) then --24 hours have passed, flag a new fight
player:startEvent(0x0350,0,1125,334);
else
player:startEvent(0x034f,0,1125); -- Yes, this will indefinitely replace his standard dialogue!
end
---------------------------
else
player:startEvent(0x0159); -- 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 == 0x008c) then
player:setVar("MissionStatus",1);
player:setVar("ohbiru_dohbiru_talk",0);
player:addKeyItem(FOOD_OFFERINGS);
player:messageSpecial(KEYITEM_OBTAINED,FOOD_OFFERINGS);
player:addKeyItem(DRINK_OFFERINGS);
player:messageSpecial(KEYITEM_OBTAINED,DRINK_OFFERINGS);
-- Moonlit Path and Other Fenrir Stuff
elseif(csid == 0x034a and option == 2) then
player:addQuest(WINDURST,THE_MOONLIT_PATH);
elseif(csid == 0x034c) then
player:addKeyItem(MOON_BAUBLE);
player:messageSpecial(KEYITEM_OBTAINED,MOON_BAUBLE);
player:delKeyItem(WHISPER_OF_FLAMES);
player:delKeyItem(WHISPER_OF_TREMORS);
player:delKeyItem(WHISPER_OF_TIDES);
player:delKeyItem(WHISPER_OF_GALES);
player:delKeyItem(WHISPER_OF_FROST);
player:delKeyItem(WHISPER_OF_STORMS);
player:delQuest(OUTLANDS,TRIAL_BY_FIRE);
player:delQuest(BASTOK,TRIAL_BY_EARTH);
player:delQuest(OUTLANDS,TRIAL_BY_WATER);
player:delQuest(OUTLANDS,TRIAL_BY_WIND);
player:delQuest(SANDORIA,TRIAL_BY_ICE);
player:delQuest(OTHER_AREAS,TRIAL_BY_LIGHTNING);
elseif(csid == 0x034e) then -- Turn-in event
player:addTitle(HEIR_OF_THE_NEW_MOON);
player:delKeyItem(WHISPER_OF_THE_MOON);
player:setVar("MoonlitPath_date", os.date("%j")); -- %M for next minute, %j for next day
player:addFame(WINDURST,30);
player:completeQuest(WINDURST,THE_MOONLIT_PATH);
reward = 0
if(option == 1) then reward = 18165; -- Fenrir's Stone
elseif(option == 2) then reward = 13572; -- Fenrir's Cape
elseif(option == 3) then reward = 13138; -- Fenrir's Torque
elseif(option == 4) then reward = 13399; -- Fenrir's Earring
elseif(option == 5) then reward = 1208; -- Ancient's Key
elseif(option == 6) then
player:addGil(GIL_RATE*10000);
player:messageSpecial(GIL_OBTAINED,GIL_RATE*10000); -- Gil
elseif(option == 7) then
player:addSpell(297) -- Pact
end
if(player:getFreeSlotsCount() == 0 and reward ~= 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,reward);
elseif(reward ~= 0) then
player:addItem(reward);
player:messageSpecial(ITEM_OBTAINED,reward);
end
if(player:getNation() == WINDURST and player:getRank() == 10 and player:getQuestStatus(WINDURST,THE_PROMISE) == QUEST_COMPLETED) then
player:addKeyItem(DARK_MANA_ORB);
player:messageSpecial(KEYITEM_OBTAINED,DARK_MANA_ORB);
end
elseif(csid == 0x0352) then -- Repeat turn-in event
player:addTitle(HEIR_OF_THE_NEW_MOON);
player:delKeyItem(WHISPER_OF_THE_MOON);
player:setVar("MoonlitPath_date", os.date("%j")); -- %M for next minute, %j for next day
player:addFame(WINDURST,30);
reward = 0
if(option == 1) then reward = 18165; -- Fenrir's Stone
elseif(option == 2) then reward = 13572; -- Fenrir's Cape
elseif(option == 3) then reward = 13138; -- Fenrir's Torque
elseif(option == 4) then reward = 13399; -- Fenrir's Earring
elseif(option == 5) then reward = 1208; -- Ancient's Key
elseif(option == 6) then
player:addGil(GIL_RATE*10000);
player:messageSpecial(GIL_OBTAINED,GIL_RATE*15000); -- Gil
elseif(option == 7) then
player:addSpell(297) -- Pact
end
if(player:getFreeSlotsCount() == 0 and reward ~= 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,reward);
elseif(reward ~= 0) then
player:addItem(reward);
player:messageSpecial(ITEM_OBTAINED,reward);
end
if(player:getNation() == WINDURST and player:getRank() == 10 and player:getQuestStatus(WINDURST,THE_PROMISE) == QUEST_COMPLETED) then
player:addKeyItem(DARK_MANA_ORB);
player:messageSpecial(KEYITEM_OBTAINED,DARK_MANA_ORB);
end
elseif(csid == 0x0350) then
player:addKeyItem(MOON_BAUBLE);
player:messageSpecial(KEYITEM_OBTAINED,MOON_BAUBLE);
end
end; | gpl-3.0 |
ffxinfinity/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/The_Eldieme_Necropolis/npcs/_5fo.lua | 2 | 2330 | -----------------------------------
-- Area: The Eldieme Necropolis
-- NPC: North Plate
-- @zone 195
-- @pos 174 -32 50
-- 17576327
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local state0 = 8;
local state1 = 9;
if (npc:getAnimation() == 8) then
state0 = 9;
state1 = 8;
end
-- Gates
-- Shiva's Gate
GetNPCByID(17576304):setAnimation(state0);
GetNPCByID(17576305):setAnimation(state0);
GetNPCByID(17576306):setAnimation(state0);
GetNPCByID(17576307):setAnimation(state0);
GetNPCByID(17576308):setAnimation(state0);
-- Odin's Gate
GetNPCByID(17576309):setAnimation(state1);
GetNPCByID(17576310):setAnimation(state1);
GetNPCByID(17576311):setAnimation(state1);
GetNPCByID(17576312):setAnimation(state1);
GetNPCByID(17576313):setAnimation(state1);
-- Leviathan's Gate
GetNPCByID(17576314):setAnimation(state0);
GetNPCByID(17576315):setAnimation(state0);
GetNPCByID(17576316):setAnimation(state0);
GetNPCByID(17576317):setAnimation(state0);
GetNPCByID(17576318):setAnimation(state0);
-- Titan's Gate
GetNPCByID(17576319):setAnimation(state1);
GetNPCByID(17576320):setAnimation(state1);
GetNPCByID(17576321):setAnimation(state1);
GetNPCByID(17576322):setAnimation(state1);
GetNPCByID(17576323):setAnimation(state1);
-- Plates
-- East Plate
GetNPCByID(17576324):setAnimation(state0);
GetNPCByID(17576325):setAnimation(state0);
-- North Plate
GetNPCByID(17576326):setAnimation(state0);
GetNPCByID(17576327):setAnimation(state0);
-- West Plate
GetNPCByID(17576328):setAnimation(state0);
GetNPCByID(17576329):setAnimation(state0);
-- South Plate
GetNPCByID(17576330):setAnimation(state0);
GetNPCByID(17576331):setAnimation(state0);
return 0;
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
jixianliang/DBProxy | lib/rw-splitting.lua | 4 | 28990 | --[[ $%BEGINLICENSE%$
Copyright (c) 2007, 2009, Oracle and/or its affiliates. All rights reserved.
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; version 2 of the
License.
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 St, Fifth Floor, Boston, MA
02110-1301 USA
$%ENDLICENSE%$ --]]
---
-- a flexible statement based load balancer with connection pooling
--
-- * build a connection pool of min_idle_connections for each backend and maintain
-- its size
-- *
--
--
local commands = require("proxy.commands")
local tokenizer = require("proxy.tokenizer")
local lb = require("proxy.balance")
local auto_config = require("proxy.auto-config")
local parser = require("proxy.parser")
local log = require("proxy.log")
local charset = require("proxy.charset")
local split = require("proxy.split")
local config_file = string.format("proxy.conf.config_%s", proxy.global.config.instance)
local config = require(config_file)
local auth = require("proxy.auth")
--- config
--
-- connection pool
local level = log.level
local write_log = log.write_log
local write_sql = log.write_sql
local write_des = log.write_des
local write_query = log.write_query
local lvs_ip = config.lvs_ip
local proxy_cnf = string.format("%s/../conf/%s.cnf", proxy.global.config.logpath, proxy.global.config.instance)
function update_rwsplit()
local weight = 0
for i = 1, #proxy.global.backends do
if weight < proxy.global.backends[i].weight then
weight = proxy.global.backends[i].weight
end
end
proxy.global.config.rwsplit = {
min_idle_connections = config.min_idle_connections,
max_idle_connections = 500,
is_debug = config.debug_info,
is_auth = config.is_auth,
max_weight = weight,
cur_weight = weight,
next_ndx = 1,
ndx_num = #proxy.global.backends
}
end
if not proxy.global.config.rwsplit then update_rwsplit() end
---
-- read/write splitting sends all non-transactional SELECTs to the slaves
--
-- is_in_transaction tracks the state of the transactions
local is_in_transaction = false
-- if this was a SELECT SQL_CALC_FOUND_ROWS ... stay on the same connections
local is_in_select_calc_found_rows = false
local is_in_lock = false
--log.init_log(proxy.global.config.rwsplit.log_level, proxy.global.config.rwsplit.is_rt, proxy.global.config.rwsplit.is_sql)
log.init_log()
-- Global tokens
g_tokens = {}
-- SPLIT SQL FOR Mutil table
merge_res = {
sub_sql_num = 0,
sub_sql_exed = 0,
rows = {},
sortindex = false,
sorttype = false,
limit = 5000
}
---
-- get a connection to a backend
--
-- as long as we don't have enough connections in the pool, create new connections
--
function connect_server()
write_log(level.DEBUG, "ENTER CONNECT_SERVER")
--for i = 1, #proxy.global.backends do --global¶ÔÓ¦chassis_private£¿
--print(proxy.global.backends[i].dst.name)
--end
--print("---------------------------------")
local is_debug = proxy.global.config.rwsplit.is_debug
local is_auth = proxy.global.config.rwsplit.is_auth
-- make sure that we connect to each backend at least ones to
-- keep the connections to the servers alive
--
-- on read_query we can switch the backends again to another backend
local client_src = proxy.connection.client.src.name
local client_dst = proxy.connection.client.dst.name
if is_debug then
print()
print("[connect_server] " .. client_src) --connection¶ÔÓ¦½á¹¹network_mysqld_con
print("[connect_server] " .. client_dst) --connection¶ÔÓ¦½á¹¹network_mysqld_con
end
write_log(level.INFO, "[connect_server] ", client_src) --connection¶ÔÓ¦½á¹¹network_mysqld_con
write_log(level.INFO, "[connect_server] ", client_dst) --connection¶ÔÓ¦½á¹¹network_mysqld_con
local client_ip = string.sub(client_src, 1, string.find(client_src, ':')-1)
for i = 1, #lvs_ip do
if client_ip == lvs_ip[i] then
io.input(proxy_cnf)
for line in io.lines() do
line = line:lower()
if string.find(line, "online") ~= nil then
line = string.gsub(line, "%s*online%s*=%s*", "")
line = string.gsub(line, "%s*", "")
if line == "false" then
proxy.response =
{
type = proxy.MYSQLD_PACKET_ERR,
errmsg = "Proxy Warning - Offline Now"
}
return proxy.PROXY_SEND_RESULT
end
end
end
io.close(proxy_cnf)
io.input(stdin)
break
end
end
if is_auth and auth.allow_ip(client_ip) == false then
proxy.response =
{
type = proxy.MYSQLD_PACKET_ERR,
errmsg = "Proxy Warning - IP Forbidden"
}
return proxy.PROXY_SEND_RESULT
end
local rw_ndx = 0
-- init all backends
for i = 1, #proxy.global.backends do
local s = proxy.global.backends[i] --s¶ÔÓ¦½á¹¹network_backend_t
local pool = s.pool -- we don't have a username yet, try to find a connections which is idling. pool¶ÔÓ¦½á¹¹network_connection_pool
local cur_idle = pool.users[""].cur_idle_connections --cur_idle_connections¶ÔӦʲô£¿
pool.min_idle_connections = proxy.global.config.rwsplit.min_idle_connections
pool.max_idle_connections = proxy.global.config.rwsplit.max_idle_connections
if is_debug then
print(" [".. i .."].connected_clients = " .. s.connected_clients)
print(" [".. i .."].pool.cur_idle = " .. cur_idle)
print(" [".. i .."].pool.max_idle = " .. pool.max_idle_connections)
print(" [".. i .."].pool.min_idle = " .. pool.min_idle_connections)
print(" [".. i .."].type = " .. s.type) --type µÄÀàÐÍÊÇenum backend_type_t
print(" [".. i .."].state = " .. s.state) --stateµÄÀàÐÍÊÇenum backend_state_t
end
write_log(level.INFO, " [", i, "].connected_clients = ", s.connected_clients)
write_log(level.INFO, " [", i, "].pool.cur_idle = ", cur_idle)
write_log(level.INFO, " [", i, "].pool.max_idle = ", pool.max_idle_connections)
write_log(level.INFO, " [", i, "].pool.min_idle = ", pool.min_idle_connections)
write_log(level.INFO, " [", i, "].type = ", s.type) --type µÄÀàÐÍÊÇenum backend_type_t
write_log(level.INFO, " [", i, "].state = ", s.state) --stateµÄÀàÐÍÊÇenum backend_state_t
-- prefer connections to the master
if s.type == proxy.BACKEND_TYPE_RW and
s.state ~= proxy.BACKEND_STATE_DOWN and
s.state ~= proxy.BACKEND_STATE_OFFLINE and
cur_idle < pool.min_idle_connections then
proxy.connection.backend_ndx = i --connectionÓÖ¶ÔÓ¦½á¹¹network_mysqld_con_lua_t£¿
break
elseif s.type == proxy.BACKEND_TYPE_RO and
s.state ~= proxy.BACKEND_STATE_DOWN and
s.state ~= proxy.BACKEND_STATE_OFFLINE and
cur_idle < pool.min_idle_connections then
proxy.connection.backend_ndx = i
break
elseif s.type == proxy.BACKEND_TYPE_RW and
s.state ~= proxy.BACKEND_STATE_DOWN and
s.state ~= proxy.BACKEND_STATE_OFFLINE and
rw_ndx == 0 then
rw_ndx = i
end
end
if proxy.connection.backend_ndx == 0 then --backend_ndx¶ÔÓ¦network_mysqld_con_lua_t.backend_ndx£¬ÈôΪ0˵Ã÷ÉÏÃæµÄÅжÏ×ߵĵÚ3Ìõ·¾¶
if is_debug then
print(" [" .. rw_ndx .. "] taking master as default") --´ÓmasterµÄÁ¬½Ó³ØÀïȡһ¸öÁ¬½Ó
end
write_log(level.INFO, " [", rw_ndx, "] taking master as default") --´ÓmasterµÄÁ¬½Ó³ØÀïȡһ¸öÁ¬½Ó
proxy.connection.backend_ndx = rw_ndx
end
-- pick a random backend
--
-- we someone have to skip DOWN backends
-- ok, did we got a backend ?
if proxy.connection.server then --connectionÓÖ¶ÔÓ¦»ØÁ˽ṹnetwork_mysqld_con£¿
if is_debug then
print(" using pooled connection from: " .. proxy.connection.backend_ndx) --´ÓmasterµÄÁ¬½Ó³ØÀïȡһ¸öÁ¬½Ó·µ»Ø¸ø¿Í»§¶Ë
end
write_log(level.INFO, " using pooled connection from: ", proxy.connection.backend_ndx) --´ÓmasterµÄÁ¬½Ó³ØÀïȡһ¸öÁ¬½Ó·µ»Ø¸ø¿Í»§¶Ë
write_log(level.DEBUG, "LEAVE CONNECT_SERVER")
-- stay with it
return proxy.PROXY_IGNORE_RESULT
end
if is_debug then
print(" [" .. proxy.connection.backend_ndx .. "] idle-conns below min-idle") --´´½¨ÐÂÁ¬½Ó
end
write_log(level.INFO, " [", proxy.connection.backend_ndx, "] idle-conns below min-idle") --´´½¨ÐÂÁ¬½Ó
write_log(level.DEBUG, "LEAVE CONNECT_SERVER")
-- open a new connection
end
---
-- put the successfully authed connection into the connection pool
--
-- @param auth the context information for the auth
--
-- auth.packet is the packet
function read_auth_result( auth )
write_log(level.DEBUG, "ENTER READ_AUTH_RESULT")
if is_debug then
print("[read_auth_result] " .. proxy.connection.client.src.name)
end
write_log(level.INFO, "[read_auth_result] " .. proxy.connection.client.src.name)
if auth.packet:byte() == proxy.MYSQLD_PACKET_OK then
-- auth was fine, disconnect from the server
proxy.connection.backend_ndx = 0 --auth³É¹¦£¬°ÑÁ¬½Ó·Å»ØÁ¬½Ó³Ø
elseif auth.packet:byte() == proxy.MYSQLD_PACKET_EOF then
-- we received either a
--
-- * MYSQLD_PACKET_ERR and the auth failed or
-- * MYSQLD_PACKET_EOF which means a OLD PASSWORD (4.0) was sent
print("(read_auth_result) ... not ok yet");
elseif auth.packet:byte() == proxy.MYSQLD_PACKET_ERR then
-- auth failed
end
write_log(level.DEBUG, "LEAVE READ_AUTH_RESULT")
end
---
-- read/write splitting
function read_query( packet )
write_log(level.DEBUG, "ENTER READ_QUERY")
local is_debug = proxy.global.config.rwsplit.is_debug
local cmd = commands.parse(packet)
local c = proxy.connection.client
local r = auto_config.handle(cmd)
if r then
write_log(level.DEBUG, "LEAVE READ_QUERY")
return r
end
local tokens, attr
local norm_query
-- looks like we have to forward this statement to a backend
if is_debug then
print("[read_query] " .. proxy.connection.client.src.name)
print(" current backend = " .. proxy.connection.backend_ndx)
print(" client default db = " .. c.default_db) --default_db¶ÔÓ¦network_socket.default_db
print(" client username = " .. c.username) --username¶ÔӦʲô£¿
if cmd.type == proxy.COM_QUERY then
print(" query = " .. cmd.query)
end
end
write_log(level.INFO, "[read_query] ", proxy.connection.client.src.name)
write_log(level.INFO, " current backend = ", proxy.connection.backend_ndx)
write_log(level.INFO, " client default db = ", c.default_db) --default_db¶ÔÓ¦network_socket.default_db
write_log(level.INFO, " client username = ", c.username) --username¶ÔӦʲô£¿
if cmd.type == proxy.COM_QUERY then
write_log(level.INFO, " query = ", cmd.query)
-- write_sql(cmd.query)
end
if cmd.type == proxy.COM_QUIT then --quit;»òctrl-D
-- don't send COM_QUIT to the backend. We manage the connection
-- in all aspects.
proxy.response = {
type = proxy.MYSQLD_PACKET_OK,
}
if is_debug then
print(" (QUIT) current backend = " .. proxy.connection.backend_ndx)
end
write_log(level.INFO, " (QUIT) current backend = ", proxy.connection.backend_ndx)
write_log(level.DEBUG, "LEAVE READ_QUERY")
return proxy.PROXY_SEND_RESULT
end
--print("cmd.type = " .. cmd.type)
if cmd.type == proxy.COM_QUERY then
local new_sql, status
tokens, attr = tokenizer.tokenize(cmd.query)
-- set global
g_tokens = tokens
-- sql ½âÎöʧ°ÜÔòÁ¢¼´·µ»Ø¸ø¿Í»§¶Ë
new_sql, status = split.sql_parse(tokens, cmd.query)
if status == -1 then
proxy.queries:reset()
write_log(level.DEBUG, "LEAVE READ_QUERY")
write_query(cmd.query, c.src.name)
return proxy.PROXY_SEND_RESULT
end
if status == 1 then
if #new_sql > 1 then --·Ö±í(¶à¾ä)£¬´òsql.log£¬ÓÐÐòºÅ
-- init muti sql
merge_res.sub_sql_exed = 0
merge_res.sub_sql_num = 0
merge_res.rows = {}
for id = 1, #new_sql do
proxy.queries:append(6, string.char(proxy.COM_QUERY) .. new_sql[id], { resultset_is_needed = true })
merge_res.sub_sql_num = merge_res.sub_sql_num + 1
end
elseif #new_sql == 1 then --·Ö±í(1¾ä)£¬´òsql.log£¬ÓÐÐòºÅ
proxy.queries:append(7, string.char(proxy.COM_QUERY) .. new_sql[1], { resultset_is_needed = true })
else --²»·Ö±íÇÒsql_type²»Îª4£¬´òsql.log£¬ÎÞÐòºÅ
proxy.queries:append(8, packet, { resultset_is_needed = true })
end
else --²»·Ö±íÇÒsql_typeΪ4£¬²»´òsql.log
proxy.queries:append(1, packet, { resultset_is_needed = true })
end
else --ÀàÐͲ»ÊÇCOM_QUERY£¬²»´òsql.log
proxy.queries:append(1, packet, { resultset_is_needed = true })
end
-- read/write splitting
--
-- send all non-transactional SELECTs to a slave
if not is_in_transaction and not is_in_lock and
cmd.type == proxy.COM_QUERY then
--tokens = tokens or assert(tokenizer.tokenize(cmd.query))
local stmt = string.upper(tokenizer.first_stmt_token(tokens).text) --ÃüÁî×Ö·û´®µÄµÚÒ»¸öµ¥´Ê
if stmt == "SELECT" and tokens[2].text:upper() == "GET_LOCK" then
is_in_lock = true
end
if stmt == "SELECT" or stmt == "SET" or stmt == "SHOW" or stmt == "DESC" then --TK_**µÄ¶¨ÒåÔÚlib/sql-tokenizer.hÀï
is_in_select_calc_found_rows = false --³õʼ»¯Îªfalse
local is_insert_id = false
for i = 1, #tokens do
-- local token = tokens[i]
-- SQL_CALC_FOUND_ROWS + FOUND_ROWS() have to be executed
-- on the same connection
-- print("token: " .. token.token_name)
-- print(" val: " .. token.text)
local text = tokens[i].text:upper()
if text == "SQL_CALC_FOUND_ROWS" then
is_in_select_calc_found_rows = true --SQL_CALC_FOUND_ROWSÖ¸Á½«is_in_select_calc_found_rowsÉèΪtrue
else
if text == "LAST_INSERT_ID" or text == "@@INSERT_ID" or text == "@@LAST_INSERT_ID" then
is_insert_id = true
end
end
-- we found the two special token, we can't find more
if is_insert_id and is_in_select_calc_found_rows then --and»¹ÊÇor£¿
break
end
end
-- if we ask for the last-insert-id we have to ask it on the original
-- connection
if proxy.connection.backend_ndx == 0 then
if not is_insert_id then
if attr == 1 or is_in_lock then
proxy.connection.backend_ndx = lb.idle_failsafe_rw() --idle_failsafe_rw¶¨ÒåÔÚbalance.luaÀ·µ»ØµÚһ̨³Ø²»Îª¿ÕµÄmaster»úÆ÷µÄÐòºÅ
else
-- local backend_ndx = lb.idle_ro() --idle_ro¶¨ÒåÔÚbalance.luaÀ·µ»Øµ±Ç°Á¬½ÓµÄ¿Í»§¶ËÊýÁ¿×îÉÙµÄslave»úÆ÷µÄÐòºÅ
if proxy.global.config.rwsplit.max_weight == -1 then update_rwsplit() end
local backend_ndx = lb.cycle_read_ro()
if backend_ndx > 0 then
proxy.connection.backend_ndx = backend_ndx
end
end
else
proxy.connection.backend_ndx = lb.idle_failsafe_rw() --idle_failsafe_rw¶¨ÒåÔÚbalance.luaÀ·µ»ØµÚһ̨³Ø²»Îª¿ÕµÄmaster»úÆ÷µÄÐòºÅ
-- print(" found a SELECT LAST_INSERT_ID(), staying on the same backend")
end
end
end
end
if proxy.connection.backend_ndx == 0 and cmd.type == proxy.COM_INIT_DB then
if proxy.global.config.rwsplit.max_weight == -1 then update_rwsplit() end
proxy.connection.backend_ndx = lb.cycle_read_ro()
end
-- no backend selected yet, pick a master
if proxy.connection.backend_ndx == 0 then
-- we don't have a backend right now
--
-- let's pick a master as a good default
--
proxy.connection.backend_ndx = lb.idle_failsafe_rw() --idle_failsafe_rw¶¨ÒåÔÚbalance.luaÀ·µ»ØµÚһ̨³Ø²»Îª¿ÕµÄmaster»úÆ÷µÄÐòºÅ
end
-- by now we should have a backend
--
-- in case the master is down, we have to close the client connections
-- otherwise we can go on
if proxy.connection.backend_ndx == 0 then --ËùÓÐbackend״̬¶¼ÊÇDOWNµ¼ÖµÄÇé¿ö
--[[
for i = 1, #proxy.global.backends do --global¶ÔÓ¦chassis_private£¿
print("backend[".. i .."] :" .. proxy.global.backends[i].dst.name)
end
]]
write_log(level.DEBUG, "LEAVE READ_QUERY")
if cmd.type == proxy.COM_QUERY then write_query(cmd.query, c.src.name) end
return proxy.PROXY_SEND_QUERY --Ϊʲô·µ»ØSEND_QUERY¶ø²»ÊÇERRORÖ®ÀࣿÒòΪconnection.serverΪ¿Õ
end
local s = proxy.connection.server
-- if client and server db don't match, adjust the server-side
--
-- skip it if we send a INIT_DB anyway
if cmd.type == proxy.COM_QUERY then
if c.default_db then
-- if not s.default_db or c.default_db ~= s.default_db then
proxy.queries:prepend(2, string.char(proxy.COM_INIT_DB) .. c.default_db, { resultset_is_needed = true }) --inj.idÉèΪ2
-- end
end
charset.modify_charset(tokens, c, s)
end
-- send to master
if is_debug then
if proxy.connection.backend_ndx > 0 then
local b = proxy.global.backends[proxy.connection.backend_ndx]
print(" sending to backend : " .. b.dst.name);
print(" server src port : " .. proxy.connection.server.src.port)
print(" is_slave : " .. tostring(b.type == proxy.BACKEND_TYPE_RO));
print(" server default db: " .. s.default_db)
print(" server username : " .. s.username)
end
print(" in_trans : " .. tostring(is_in_transaction))
print(" in_calc_found : " .. tostring(is_in_select_calc_found_rows))
print(" COM_QUERY : " .. tostring(cmd.type == proxy.COM_QUERY))
end
if proxy.connection.backend_ndx > 0 then
local b = proxy.global.backends[proxy.connection.backend_ndx]
write_log(level.INFO, " sending to backend : ", b.dst.name);
write_log(level.INFO, " server src port : ", proxy.connection.server.src.port)
write_log(level.INFO, " is_slave : ", tostring(b.type == proxy.BACKEND_TYPE_RO));
write_log(level.INFO, " server default db: ", s.default_db)
write_log(level.INFO, " server username : ", s.username)
end
write_log(level.INFO, " in_trans : ", tostring(is_in_transaction))
write_log(level.INFO, " in_calc_found : ", tostring(is_in_select_calc_found_rows))
write_log(level.INFO, " COM_QUERY : ", tostring(cmd.type == proxy.COM_QUERY))
write_log(level.DEBUG, "LEAVE READ_QUERY")
return proxy.PROXY_SEND_QUERY
end
---
-- as long as we are in a transaction keep the connection
-- otherwise release it so another client can use it
function read_query_result( inj )
write_log(level.DEBUG, "ENTER READ_QUERY_RESULT")
local is_debug = proxy.global.config.rwsplit.is_debug
local res = assert(inj.resultset)
local flags = res.flags
local src_name = proxy.connection.client.src.name
local dst_name = proxy.global.backends[proxy.connection.backend_ndx].dst.name
if inj.id == 1 then
-- write_des(0, inj)
elseif inj.id == 8 then
if res.query_status == proxy.MYSQLD_PACKET_ERR then
-- write_sql("response failure: " .. inj.query:sub(2))
write_sql(inj, src_name, dst_name)
else
write_des(0, inj, src_name, dst_name)
end
elseif inj.id == 7 then
if res.query_status == proxy.MYSQLD_PACKET_ERR then
write_sql(inj, src_name, dst_name)
else
write_des(1, inj, src_name, dst_name)
end
else
-- ignore the result of the USE <default_db>
-- the DB might not exist on the backend, what do do ?
--
local re = proxy.PROXY_IGNORE_RESULT
if inj.id == 2 then
-- the injected INIT_DB failed as the slave doesn't have this DB
-- or doesn't have permissions to read from it
if res.query_status == proxy.MYSQLD_PACKET_ERR then
proxy.queries:reset()
proxy.response = {
type = proxy.MYSQLD_PACKET_ERR,
errmsg = "can't change DB ".. proxy.connection.client.default_db ..
" to on slave " .. proxy.global.backends[proxy.connection.backend_ndx].dst.name
}
re = proxy.PROXY_SEND_RESULT
end
elseif inj.id == 3 then
if res.query_status == proxy.MYSQLD_PACKET_ERR then
proxy.queries:reset()
proxy.response = {
type = proxy.MYSQLD_PACKET_ERR,
errmsg = "can't change charset_client " .. proxy.connection.client.charset_client ..
" to on slave " .. proxy.global.backends[proxy.connection.backend_ndx].dst.name
}
re = proxy.PROXY_SEND_RESULT
end
elseif inj.id == 4 then
if res.query_status == proxy.MYSQLD_PACKET_ERR then
proxy.queries:reset()
proxy.response = {
type = proxy.MYSQLD_PACKET_ERR,
errmsg = "can't change charset_results " .. proxy.connection.client.charset_results ..
" to on slave " .. proxy.global.backends[proxy.connection.backend_ndx].dst.name
}
re = proxy.PROXY_SEND_RESULT
end
elseif inj.id == 5 then
if res.query_status == proxy.MYSQLD_PACKET_ERR then
proxy.queries:reset()
proxy.response = {
type = proxy.MYSQLD_PACKET_ERR,
errmsg = "can't change charset_connection " .. proxy.connection.client.charset_connection ..
" to on slave " .. proxy.global.backends[proxy.connection.backend_ndx].dst.name
}
re = proxy.PROXY_SEND_RESULT
end
elseif inj.id == 6 then
-- merge the field-definition
local fields = {}
for n = 1, #inj.resultset.fields do
fields[#fields + 1] = {
type = inj.resultset.fields[n].type,
name = inj.resultset.fields[n].name,
}
end
-- append the rows to the result-set storage
if res.query_status == proxy.MYSQLD_PACKET_OK then
-- get attribute
merge_res.sortindex, merge_res.sorttype = parser.get_sort(g_tokens, fields)
merge_res.limit = parser.get_limit(g_tokens)
--[[
print(merge_res.sortindex)
print(merge_res.sorttype)
print(merge_res.limit)
]]
-- merge rows
merge_res.rows = split.merge_rows(merge_res.rows, inj.resultset.rows, merge_res.sorttype, merge_res.sortindex, merge_res.limit)
elseif res.query_status == proxy.MYSQLD_PACKET_ERR then
write_log(level.ERROR, "response failure: " .. inj.query:sub(2))
write_sql(inj, src_name, dst_name)
end
-- finished one response
merge_res.sub_sql_exed = merge_res.sub_sql_exed + 1
write_des(merge_res.sub_sql_exed, inj, src_name, dst_name)
-- finished all sub response
if merge_res.sub_sql_exed >= merge_res.sub_sql_num and #fields > 0 then
-- generate response struct
proxy.queries:reset()
proxy.response = {
type = proxy.MYSQLD_PACKET_OK,
resultset = {
rows = merge_res.rows,
fields = fields
}
}
return proxy.PROXY_SEND_RESULT
elseif merge_res.sub_sql_exed >= merge_res.sub_sql_num and #fields < 1 then
proxy.queries:reset()
proxy.response = {
type = proxy.MYSQLD_PACKET_ERR,
errmsg = "Proxy Warning - Query failure"
}
return proxy.PROXY_SEND_RESULT
end
end
if re == proxy.PROXY_SEND_RESULT and proxy.response.type == proxy.MYSQLD_PACKET_ERR then
write_log(level.ERROR, proxy.response.errmsg)
end
write_log(level.DEBUG, "LEAVE READ_QUERY_RESULT")
return re
end
if is_in_transaction == false or flags.in_trans == true then
is_in_transaction = flags.in_trans
else
if inj.query:sub(2, 7):upper() == "COMMIT" or inj.query:sub(2, 9):upper() == "ROLLBACK" then
is_in_transaction = false
end
end
if is_in_lock then
if string.match(inj.query:sub(2):upper(), "SELECT RELEASE_LOCK(.*)") then
is_in_lock = false
end
end
--[[
if is_in_transaction and flags.in_trans == false and inj.query:upper() ~= "ROLLBACK" and inj.query:upper() ~= "COMMIT" then
-- is_in_transaction = false
else
is_in_transaction = flags.in_trans
end
]]
local have_last_insert_id = (res.insert_id and (res.insert_id > 0))
if not is_in_transaction and
not is_in_select_calc_found_rows and
not have_last_insert_id and
not is_in_lock then
-- release the backend
proxy.connection.backend_ndx = 0 --½«Á¬½Ó·Å»ØÁ¬½Ó³Ø
else
if is_debug then
print("(read_query_result) staying on the same backend")
print(" in_trans : " .. tostring(is_in_transaction))
print(" in_calc_found : " .. tostring(is_in_select_calc_found_rows))
print(" have_insert_id : " .. tostring(have_last_insert_id))
end
write_log(level.INFO, "(read_query_result) staying on the same backend")
write_log(level.INFO, " in_trans : ", tostring(is_in_transaction))
write_log(level.INFO, " in_calc_found : ", tostring(is_in_select_calc_found_rows))
write_log(level.INFO, " have_insert_id : ", tostring(have_last_insert_id))
end
write_log(level.DEBUG, "LEAVE READ_QUERY_RESULT")
end
---
-- close the connections if we have enough connections in the pool
--
-- @return nil - close connection
-- IGNORE_RESULT - store connection in the pool
function disconnect_client()
write_log(level.DEBUG, "ENTER DISCONNECT_CLIENT")
local is_debug = proxy.global.config.rwsplit.is_debug
if is_debug then
print("[disconnect_client] " .. proxy.connection.client.src.name)
end
write_log(level.INFO, "[disconnect_client] ", proxy.connection.client.src.name)
-- make sure we are disconnection from the connection
-- to move the connection into the pool
if is_in_transaction or is_in_lock then
proxy.connection.backend_ndx = -1
else
proxy.connection.backend_ndx = 0
end
write_log(level.DEBUG, "LEAVE DISCONNECT_CLIENT")
end
| gpl-2.0 |
waytim/darkstar | scripts/zones/Lower_Jeuno/npcs/Creepstix.lua | 12 | 1561 | -----------------------------------
-- Area: Lower Jeuno
-- NPC: Creepstix
-- Standard Merchant NPC
-----------------------------------
require("scripts/globals/shop");
package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil;
require("scripts/zones/Lower_Jeuno/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,CREEPSTIX_SHOP_DIALOG);
stock = {0x139f,8160, -- Scroll of Goblin Gavotte
0x127e,7074, -- Scroll of Protectra II
0x1282,1700, -- Scroll of Shellra
0x13e1,73740, -- Scroll of Gain-VIT
0x13e4,77500, -- Scroll of Gain-MND
0x13e2,85680, -- Scroll of Gain-AGI
0x13e5,81900, -- Scroll of Gain-CHR
0x13e8,73740, -- Scroll of Boost-VIT
0x13eb,77500, -- Scroll of Boost-MND
0x13e9,85680, -- Scroll of Boost-AGI
0x13ec,81900, -- Scroll of Boost-CHR
0x12f1,130378} -- Scroll of Addle
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 |
TheOnePharaoh/YGOPro-Custom-Cards | script/c20912320.lua | 2 | 19695 | --Action Field - The Sacred Sword's Pedestal
function c20912320.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetProperty(EFFECT_FLAG_UNCOPYABLE+EFFECT_FLAG_CANNOT_DISABLE)
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e1:SetCode(EVENT_PREDRAW)
e1:SetCountLimit(1)
e1:SetRange(LOCATION_HAND+LOCATION_DECK)
e1:SetOperation(c20912320.op)
c:RegisterEffect(e1)
--redirect
local e2=Effect.CreateEffect(c)
e2:SetCode(EVENT_LEAVE_FIELD)
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS)
e2:SetOperation(c20912320.repop)
c:RegisterEffect(e2)
--unaffectable
local e5=Effect.CreateEffect(c)
e5:SetType(EFFECT_TYPE_SINGLE)
e5:SetProperty(EFFECT_FLAG_SINGLE_RANGE+EFFECT_FLAG_UNCOPYABLE+EFFECT_FLAG_CANNOT_DISABLE)
e5:SetRange(LOCATION_SZONE)
e5:SetCode(EFFECT_CANNOT_BE_EFFECT_TARGET)
e5:SetValue(1)
c:RegisterEffect(e5)
local e6=e5:Clone()
e6:SetCode(EFFECT_IMMUNE_EFFECT)
e6:SetValue(c20912320.ctcon2)
c:RegisterEffect(e6)
--cannot set
local e7=Effect.CreateEffect(c)
e7:SetType(EFFECT_TYPE_FIELD)
e7:SetCode(EFFECT_CANNOT_SSET)
e7:SetRange(LOCATION_SZONE)
e7:SetProperty(EFFECT_FLAG_PLAYER_TARGET+EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE)
e7:SetTargetRange(1,0)
e7:SetTarget(c20912320.sfilter)
c:RegisterEffect(e7)
-- Add Action Card
local e8=Effect.CreateEffect(c)
e8:SetDescription(aux.Stringid(20912320,0))
e8:SetType(EFFECT_TYPE_QUICK_O)
e8:SetRange(LOCATION_SZONE)
e8:SetCode(EVENT_FREE_CHAIN)
e8:SetCondition(c20912320.condition)
e8:SetTarget(c20912320.Acttarget)
e8:SetOperation(c20912320.operation)
c:RegisterEffect(e8)
--atk
local e9=Effect.CreateEffect(c)
e9:SetDescription(aux.Stringid(20912320,1))
e9:SetCategory(CATEGORY_ATKCHANGE)
e9:SetType(EFFECT_TYPE_TRIGGER_O+EFFECT_TYPE_FIELD)
e9:SetRange(LOCATION_SZONE)
e9:SetCode(EVENT_PHASE+PHASE_STANDBY)
e9:SetLabel(1)
e9:SetCountLimit(1,20912320)
e9:SetCondition(c20912320.effcon)
e9:SetTarget(c20912320.target5)
e9:SetOperation(c20912320.operation5)
c:RegisterEffect(e9)
--discard
local e10=Effect.CreateEffect(c)
e10:SetDescription(aux.Stringid(20912320,2))
e10:SetCategory(CATEGORY_TOGRAVE)
e10:SetType(EFFECT_TYPE_TRIGGER_O+EFFECT_TYPE_FIELD)
e10:SetRange(LOCATION_SZONE)
e10:SetCode(EVENT_PHASE+PHASE_STANDBY)
e10:SetLabel(3)
e10:SetCountLimit(1,20912320)
e10:SetCondition(c20912320.effcon)
e10:SetTarget(c20912320.target1)
e10:SetOperation(c20912320.operation1)
c:RegisterEffect(e10)
--Special Summon
local e11=Effect.CreateEffect(c)
e11:SetDescription(aux.Stringid(20912320,3))
e11:SetCategory(CATEGORY_SPECIAL_SUMMON)
e11:SetType(EFFECT_TYPE_TRIGGER_O+EFFECT_TYPE_FIELD)
e11:SetRange(LOCATION_SZONE)
e11:SetCode(EVENT_PHASE+PHASE_STANDBY)
e11:SetLabel(6)
e11:SetCountLimit(1,20912320)
e11:SetCondition(c20912320.effcon)
e11:SetTarget(c20912320.target2)
e11:SetOperation(c20912320.operation2)
c:RegisterEffect(e11)
--tohand
local e12=Effect.CreateEffect(c)
e12:SetDescription(aux.Stringid(20912320,4))
e12:SetCategory(CATEGORY_TOHAND)
e12:SetType(EFFECT_TYPE_TRIGGER_O+EFFECT_TYPE_FIELD)
e12:SetRange(LOCATION_SZONE)
e12:SetCode(EVENT_PHASE+PHASE_STANDBY)
e12:SetProperty(EFFECT_FLAG_CARD_TARGET)
e12:SetLabel(9)
e12:SetCountLimit(1,20912320)
e12:SetCondition(c20912320.effcon)
e12:SetTarget(c20912320.target3)
e12:SetOperation(c20912320.operation3)
c:RegisterEffect(e12)
-- draw
local e13=Effect.CreateEffect(c)
e13:SetDescription(aux.Stringid(20912320,5))
e13:SetCategory(CATEGORY_DRAW)
e13:SetType(EFFECT_TYPE_TRIGGER_O+EFFECT_TYPE_FIELD)
e13:SetRange(LOCATION_SZONE)
e13:SetCode(EVENT_PHASE+PHASE_STANDBY)
e13:SetCountLimit(1,20912320)
e13:SetCondition(c20912320.condition4)
e13:SetTarget(c20912320.target4)
e13:SetOperation(c20912320.operation4)
c:RegisterEffect(e13)
--search
local e14=Effect.CreateEffect(c)
e14:SetDescription(aux.Stringid(20912320,6))
e14:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH)
e14:SetType(EFFECT_TYPE_TRIGGER_O+EFFECT_TYPE_FIELD)
e14:SetRange(LOCATION_SZONE)
e14:SetCode(EVENT_PHASE+PHASE_STANDBY)
e14:SetCountLimit(1,20912320)
e14:SetCondition(c20912320.condition5)
e14:SetTarget(c20912320.target6)
e14:SetOperation(c20912320.operation6)
c:RegisterEffect(e14)
--stay
local eb=Effect.CreateEffect(c)
eb:SetType(EFFECT_TYPE_FIELD)
eb:SetCode(EFFECT_CANNOT_TO_DECK)
eb:SetRange(LOCATION_SZONE)
eb:SetTargetRange(LOCATION_SZONE,0)
eb:SetTarget(c20912320.tgn)
c:RegisterEffect(eb)
local ec=eb:Clone()
ec:SetCode(EFFECT_CANNOT_TO_HAND)
c:RegisterEffect(ec)
local ed=eb:Clone()
ed:SetCode(EFFECT_CANNOT_TO_GRAVE)
c:RegisterEffect(ed)
local ee=eb:Clone()
ee:SetCode(EFFECT_CANNOT_REMOVE)
c:RegisterEffect(ee)
end
function c20912320.ctcon2(e,re)
return re:GetHandler()~=e:GetHandler()
end
--speed Duel Filter
function c20912320.SDfilter(c)
return c:GetCode()==511004001
end
--vanilla mode filter
function c20912320.Vfilter(c)
return c:GetCode()==511004002
end
function c20912320.op(e,tp,eg,ep,ev,re,r,rp,chk)
local tc=Duel.GetFieldCard(tp,LOCATION_SZONE,5)
local tc2=Duel.GetFieldCard(1-tp,LOCATION_SZONE,5)
--check if number of card >20 if speed duel or >40 if other duel
if Duel.IsExistingMatchingCard(c20912320.SDfilter,tp,LOCATION_DECK+LOCATION_HAND+LOCATION_REMOVED,0,1,nil) and Duel.GetMatchingGroup(nil,tp,LOCATION_HAND+LOCATION_DECK,0,nil):GetCount()<20 then
Duel.Win(1-tp,0x55)
end
if Duel.GetMatchingGroup(nil,tp,LOCATION_HAND+LOCATION_DECK,0,e:GetHandler()):GetCount()<40 and not Duel.IsExistingMatchingCard(c20912320.SDfilter,tp,LOCATION_DECK+LOCATION_HAND+LOCATION_REMOVED,0,1,nil) then
Duel.Win(1-tp,0x55)
end
--move to field
if tc==nil then
Duel.MoveToField(e:GetHandler(),tp,tp,LOCATION_SZONE,POS_FACEUP,true)
if tc2==nil then
local token=Duel.CreateToken(tp,20912320,nil,nil,nil,nil,nil,nil)
Duel.SpecialSummonStep(token,0,tp,tp,false,false,POS_FACEUP)
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetCode(EFFECT_CHANGE_TYPE)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e1:SetReset(RESET_EVENT+0x1fc0000)
e1:SetValue(TYPE_SPELL+TYPE_FIELD)
token:RegisterEffect(e1)
Duel.MoveToField(token,tp,1-tp,LOCATION_SZONE,POS_FACEUP,true)
Duel.SpecialSummonComplete()
end
-- add ability Yell when Vanilla mode activated
-- if Duel.IsExistingMatchingCard(c20912320.Vfilter,tp,LOCATION_DECK+LOCATION_HAND+LOCATION_REMOVED,0,1,nil) then
-- c20912320.tableAction.push(95000200)
-- end
else
Duel.SendtoDeck(e:GetHandler(),nil,-2,REASON_EFFECT)
end
if e:GetHandler():GetPreviousLocation()==LOCATION_HAND then
Duel.Draw(tp,1,REASON_RULE)
end
end
function c20912320.sfilter(e,c,tp)
return c:IsType(TYPE_FIELD)
end
function c20912320.tgn(e,c)
return c==e:GetHandler()
end
-- Add Action Card
function c20912320.Acttarget(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.Hint(HINT_SELECTMSG,tp,564)
if Duel.GetFieldGroupCount(tp,LOCATION_DECK,0)==0 then
local g=Duel.GetDecktopGroup(tp,1)
local tc=g:GetFirst()
math.randomseed( tc:getcode() )
end
i = math.random(20)
ac=math.random(1,tableAction_size)
e:SetLabel(tableAction[ac])
end
function c20912320.operation(e,tp,eg,ep,ev,re,r,rp)
local dc=Duel.TossDice(tp,1)
if dc==2 or dc==3 or dc==4 or dc==6 then
Duel.RegisterFlagEffect(tp,20912320,RESET_PHASE+PHASE_END,0,1)
end
if dc==1 or dc==2 then
--- check action Trap
if (e:GetLabel()==20912325 or e:GetLabel()==20912326) then
local token=Duel.CreateToken(tp,e:GetLabel(),nil,nil,nil,nil,nil,nil)
Duel.SpecialSummonStep(token,0,tp,tp,false,false,POS_FACEUP)
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetCode(EFFECT_CHANGE_TYPE)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e1:SetReset(RESET_EVENT+0x1fc0000)
e1:SetValue(TYPE_TRAP)
token:RegisterEffect(e1)
Duel.MoveToField(token,tp,tp,LOCATION_SZONE,POS_FACEUP,true)
Duel.SpecialSummonComplete()
if not Duel.IsExistingTarget(Card.IsFaceup,tp,LOCATION_MZONE,0,1,nil) then
Duel.SendtoGrave(token,nil,REASON_RULE) end
local tc=token
Duel.ConfirmCards(tp,tc)
if tc:IsType(TYPE_TRAP) then
local te=tc:GetActivateEffect()
local tep=tc:GetControler()
if not te then
Duel.Destroy(tc,REASON_EFFECT)
else
local condition=te:GetCondition()
local cost=te:GetCost()
local target=te:GetTarget()
local operation=te:GetOperation()
if te:GetCode()==EVENT_FREE_CHAIN and not tc:IsStatus(STATUS_SET_TURN)
and (not condition or condition(te,tep,eg,ep,ev,re,r,rp))
and (not cost or cost(te,tep,eg,ep,ev,re,r,rp,0))
and (not target or target(te,tep,eg,ep,ev,re,r,rp,0)) then
Duel.ClearTargetCard()
e:SetProperty(te:GetProperty())
Duel.Hint(HINT_CARD,0,tc:GetOriginalCode())
Duel.ChangePosition(tc,POS_FACEUP)
if tc:GetType()==TYPE_TRAP then
tc:CancelToGrave(false)
end
tc:CreateEffectRelation(te)
if cost then cost(te,tep,eg,ep,ev,re,r,rp,1) end
if target then target(te,tep,eg,ep,ev,re,r,rp,1) end
local g=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS)
if g then
local tg=g:GetFirst()
while tg do
tg:CreateEffectRelation(te)
tg=g:GetNext()
end
end
Duel.BreakEffect()
if operation then operation(te,tep,eg,ep,ev,re,r,rp) end
tc:ReleaseEffectRelation(te)
if tg then
tg=g:GetFirst()
while tg do
tg:ReleaseEffectRelation(te)
tg=g:GetNext()
end
end
else
Duel.Destroy(tc,REASON_EFFECT)
end
end
end
else
---Action Spell
local token=Duel.CreateToken(tp,e:GetLabel(),nil,nil,nil,nil,nil,nil)
Duel.SpecialSummonStep(token,0,tp,tp,false,false,POS_FACEUP)
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetCode(EFFECT_CHANGE_TYPE)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e1:SetReset(RESET_EVENT+0x1fc0000)
e1:SetValue(TYPE_SPELL+TYPE_QUICKPLAY)
token:RegisterEffect(e1)
Duel.SendtoHand(token,nil,REASON_EFFECT)
Duel.SpecialSummonComplete()
end
end
if dc==5 or dc==6 then
--- check action Trap
if (e:GetLabel()==20912325 or e:GetLabel()==20912326) then
local token=Duel.CreateToken(1-tp,e:GetLabel(),nil,nil,nil,nil,nil,nil)
Duel.SpecialSummonStep(token,0,1-tp,1-tp,false,false,POS_FACEUP)
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetCode(EFFECT_CHANGE_TYPE)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e1:SetReset(RESET_EVENT+0x1fc0000)
e1:SetValue(TYPE_TRAP)
token:RegisterEffect(e1)
Duel.MoveToField(token,1-tp,1-tp,LOCATION_SZONE,POS_FACEUP,true)
Duel.SpecialSummonComplete()
if not Duel.IsExistingTarget(Card.IsFaceup,tp,LOCATION_MZONE,0,1,nil) then
Duel.SendtoGrave(token,nil,REASON_RULE) end
local tc=token
Duel.ConfirmCards(tp,tc)
if tc:IsType(TYPE_TRAP) then
local te=tc:GetActivateEffect()
local tep=tc:GetControler()
if not te then
Duel.Destroy(tc,REASON_EFFECT)
else
local condition=te:GetCondition()
local cost=te:GetCost()
local target=te:GetTarget()
local operation=te:GetOperation()
if te:GetCode()==EVENT_FREE_CHAIN and not tc:IsStatus(STATUS_SET_TURN)
and (not condition or condition(te,tep,eg,ep,ev,re,r,rp))
and (not cost or cost(te,tep,eg,ep,ev,re,r,rp,0))
and (not target or target(te,tep,eg,ep,ev,re,r,rp,0)) then
Duel.ClearTargetCard()
e:SetProperty(te:GetProperty())
Duel.Hint(HINT_CARD,0,tc:GetOriginalCode())
Duel.ChangePosition(tc,POS_FACEUP)
if tc:GetType()==TYPE_TRAP then
tc:CancelToGrave(false)
end
tc:CreateEffectRelation(te)
if cost then cost(te,tep,eg,ep,ev,re,r,rp,1) end
if target then target(te,tep,eg,ep,ev,re,r,rp,1) end
local g=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS)
if g then
local tg=g:GetFirst()
while tg do
tg:CreateEffectRelation(te)
tg=g:GetNext()
end
end
Duel.BreakEffect()
if operation then operation(te,tep,eg,ep,ev,re,r,rp) end
tc:ReleaseEffectRelation(te)
if tg then
tg=g:GetFirst()
while tg do
tg:ReleaseEffectRelation(te)
tg=g:GetNext()
end
end
else
Duel.Destroy(tc,REASON_EFFECT)
end
end
end
else
---Action Spell
local token=Duel.CreateToken(1-tp,e:GetLabel(),nil,nil,nil,nil,nil,nil)
Duel.SpecialSummonStep(token,0,1-tp,1-tp,false,false,POS_FACEUP)
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetCode(EFFECT_CHANGE_TYPE)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e1:SetReset(RESET_EVENT+0x1fc0000)
e1:SetValue(TYPE_SPELL+TYPE_QUICKPLAY)
token:RegisterEffect(e1)
Duel.SendtoHand(token,1-tp,REASON_EFFECT)
Duel.SpecialSummonComplete()
end
end
end
function c20912320.condition(e,tp,eg,ep,ev,re,r,rp)
return not Duel.IsExistingMatchingCard(c20912320.cfilter,tp,LOCATION_SZONE+LOCATION_HAND,0,1,nil)
and Duel.GetFlagEffect(e:GetHandlerPlayer(),20912320)==0
and not e:GetHandler():IsStatus(STATUS_CHAINING)
end
function c20912320.cfilter(c)
return c:IsSetCard(0xac1)
end
tableAction = {
20912321,
20912322,
20912323,
20912324,
20912325,
20912326
}
tableAction_size=6
function c20912320.repop(e)
local c=e:GetHandler()
if c:GetFlagEffect(900000007)==0 then
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e1:SetCode(EVENT_CHAIN_END)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e1:SetLabelObject(c)
e1:SetOperation(c20912320.returnop)
Duel.RegisterEffect(e1,0)
c:RegisterFlagEffect(900000007,0,0,1)
end
Duel.SendtoDeck(c,nil,-2,REASON_RULE)
end
function c20912320.returnop(e)
local c=e:GetLabelObject()
local tp=c:GetControler()
local fc=Duel.GetFieldCard(tp,LOCATION_SZONE,5)
if not fc then
Duel.MoveToField(c,tp,tp,LOCATION_SZONE,POS_FACEUP,true)
end
if fc and fc:GetFlagEffect(120912320)==0 then
--action card get
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(20912320,0))
e1:SetType(EFFECT_TYPE_QUICK_O)
e1:SetRange(LOCATION_SZONE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE)
e1:SetCondition(c20912320.condition)
e1:SetTarget(c20912320.Acttarget)
e1:SetOperation(c20912320.operation)
e1:SetReset(RESET_EVENT+0x1fe0000)
fc:RegisterEffect(e1)
--cannot set
local e4=Effect.CreateEffect(c)
e4:SetType(EFFECT_TYPE_FIELD)
e4:SetCode(EFFECT_CANNOT_SSET)
e4:SetRange(LOCATION_SZONE)
e4:SetProperty(EFFECT_FLAG_PLAYER_TARGET+EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE)
e4:SetTargetRange(1,0)
e4:SetReset(RESET_EVENT+0x1fe0000)
e4:SetTarget(c20912320.sfilter)
fc:RegisterEffect(e4)
fc:RegisterFlagEffect(120912320,RESET_EVENT+0x1fe0000,0,1)
end
end
function c20912320.confilter(c)
return c:IsFaceup() and c:IsSetCard(0xd0a2) and c:IsType(TYPE_MONSTER)
end
function c20912320.effcon(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetTurnPlayer()~=tp then return false end
local g=Duel.GetMatchingGroup(c20912320.confilter,tp,LOCATION_GRAVE,0,nil)
return g:GetClassCount(Card.GetCode)>=e:GetLabel()
end
function c20912320.filter1(c)
return c:IsSetCard(0xd0a2) and c:IsAbleToGrave()
end
function c20912320.target1(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c20912320.filter1,tp,LOCATION_DECK,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOGRAVE,0,1,tp,LOCATION_DECK)
end
function c20912320.operation1(e,tp,eg,ep,ev,re,r,rp)
if not e:GetHandler():IsRelateToEffect(e) then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE)
local g=Duel.SelectMatchingCard(tp,c20912320.filter1,tp,LOCATION_DECK,0,1,1,nil)
Duel.SendtoGrave(g,REASON_EFFECT)
end
function c20912320.filter2(c,e,tp)
return c:IsSetCard(0xd0a2) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c20912320.target2(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c20912320.filter2,tp,LOCATION_HAND,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_HAND)
end
function c20912320.eqfilter(c,tc,tp)
return c:IsType(TYPE_EQUIP) and c:IsSetCard(0xd0a2) and c:CheckEquipTarget(tc) and c:CheckUniqueOnField(tp)
end
function c20912320.operation2(e,tp,eg,ep,ev,re,r,rp)
if not e:GetHandler():IsRelateToEffect(e) then return end
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c20912320.filter2,tp,LOCATION_HAND,0,1,1,nil,e,tp)
local tc=g:GetFirst()
if Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP)==0 then return end
local tg=Duel.GetMatchingGroup(c20912320.eqfilter,tp,LOCATION_HAND,0,nil,tc,tp)
if tg:GetCount()>0 and Duel.GetLocationCount(tp,LOCATION_SZONE)>0 and Duel.SelectYesNo(tp,aux.Stringid(20912320,7)) then
Duel.BreakEffect()
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_EQUIP)
local sg=tg:Select(tp,1,1,nil)
Duel.Equip(tp,sg:GetFirst(),tc,true)
end
end
function c20912320.thfilter(c)
return c:IsSetCard(0xd0a2) and c:IsType(TYPE_MONSTER) and c:IsAbleToHand()
end
function c20912320.target3(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c20912320.thfilter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c20912320.thfilter,tp,LOCATION_GRAVE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectTarget(tp,c20912320.thfilter,tp,LOCATION_GRAVE,0,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_TOHAND,g,1,0,0)
end
function c20912320.operation3(e,tp,eg,ep,ev,re,r,rp)
if not e:GetHandler():IsRelateToEffect(e) then return end
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.SendtoHand(tc,nil,REASON_EFFECT)
end
end
function c20912320.condition4(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetTurnPlayer()~=tp then return false end
local g=Duel.GetMatchingGroup(c20912320.confilter,tp,LOCATION_GRAVE,0,nil)
return g:GetClassCount(Card.GetCode)==12
end
function c20912320.target4(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsPlayerCanDraw(tp,1) end
Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,1)
end
function c20912320.operation4(e,tp,eg,ep,ev,re,r,rp)
if not e:GetHandler():IsRelateToEffect(e) then return end
Duel.Draw(tp,1,REASON_EFFECT)
end
function c20912320.filter5(c)
return c:IsFaceup() and c:IsSetCard(0xd0a2) and c:IsType(TYPE_MONSTER)
end
function c20912320.target5(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c20912320.filter5,tp,LOCATION_MZONE,0,1,nil) end
end
function c20912320.operation5(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetMatchingGroup(c20912320.filter5,tp,LOCATION_MZONE,0,nil)
local tc=g:GetFirst()
while tc do
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetValue(300)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END)
tc:RegisterEffect(e1)
tc=g:GetNext()
end
end
function c20912320.condition5(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetTurnPlayer()~=tp then return false end
local g=Duel.GetMatchingGroup(c20912320.confilter,tp,LOCATION_GRAVE,0,nil)
return g:GetClassCount(Card.GetCode)==15
end
function c20912320.thfilter2(c)
return c:IsSetCard(0xd0a2) and c:IsType(TYPE_EQUIP) and c:IsAbleToHand()
end
function c20912320.target6(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c20912320.thfilter2,tp,LOCATION_DECK,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK)
end
function c20912320.operation6(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectMatchingCard(tp,c20912320.thfilter2,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-3.0 |
ffxinfinity/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Lufaise_Meadows/npcs/Ghost_Talker_IM.lua | 4 | 2902 | -----------------------------------
-- Area: Lufaise Meadows
-- NPC: Ghost Talker, I.M.
-- Border Conquest Guards
-- @pos 414.659 0.905 -52.417 24
-----------------------------------
package.loaded["scripts/zones/Lufaise_Meadows/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/conquest");
require("scripts/zones/Lufaise_Meadows/TextIDs");
guardnation = BASTOK; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno
guardtype = 4; -- 1: city, 2: foreign, 3: outpost, 4: border
region = TAVNAZIANARCH;
csid = 0x7ff8;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
tradeConquestGuard(player,npc,trade,guardnation,guardtype);
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if(player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then
if(supplyRunFresh(player) == 1) then
player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies !
else
player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use."
player:delKeyItem(getSupplyKey(region));
player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region));
player:setVar("supplyQuest_region",0);
end
else
arg1 = getArg1(guardnation, player) - 1;
if(arg1 >= 1792) then -- foreign, non-allied
player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0);
else -- citizen or allied
player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("OPTION: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("OPTION: %u",option);
if(option == 1) then
duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600;
player:delStatusEffect(EFFECT_SIGNET);
player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet
elseif(option == 2) then
player:delKeyItem(getSupplyKey(region));
player:addCP(supplyReward[region + 1])
player:messageSpecial(CONQUEST); -- "You've earned conquest points!"
if(hasOutpost(player, region+5) == 0) then
supply_quests = 2^(region+5);
player:addNationTeleport(guardnation,supply_quests);
player:setVar("supplyQuest_region",0);
end
elseif(option == 4) then
if(player:delGil(giltosetHP(guardnation,player))) then
player:setHomePoint();
player:messageSpecial(CONQUEST + 94); -- "Your home point has been set."
else
player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here."
end
end
end; | gpl-3.0 |
gfgtdf/wesnoth-old | data/ai/micro_ais/cas/ca_recruit_random.lua | 4 | 4694 | local H = wesnoth.require "helper"
local AH = wesnoth.require("ai/lua/ai_helper.lua")
local LS = wesnoth.require "location_set"
local recruit_type
local ca_recruit_random = {}
function ca_recruit_random:evaluation(cfg)
-- Random recruiting from all the units the side has
-- Check if leader is on keep
local leader = wesnoth.units.find_on_map { side = wesnoth.current.side, canrecruit = 'yes' }[1]
if (not leader) or (not wesnoth.get_terrain_info(wesnoth.get_terrain(leader.x, leader.y)).keep) then
return 0
end
-- Find all connected castle hexes
local castle_map = LS.of_pairs({ { leader.x, leader.y } })
local width, height, border = wesnoth.get_map_size()
local new_castle_hex_found = true
while new_castle_hex_found do
new_castle_hex_found = false
local new_hexes = {}
castle_map:iter(function(x, y)
for xa,ya in H.adjacent_tiles(x, y) do
if (not castle_map:get(xa, ya))
and (xa >= 1) and (xa <= width)
and (ya >= 1) and (ya <= height)
then
local is_castle = wesnoth.get_terrain_info(wesnoth.get_terrain(xa, ya)).castle
if is_castle then
table.insert(new_hexes, { xa, ya })
new_castle_hex_found = true
end
end
end
end)
for _,hex in ipairs(new_hexes) do
castle_map:insert(hex[1], hex[2])
end
end
-- Check if there is space left for recruiting
local no_space = true
castle_map:iter(function(x, y)
local unit = wesnoth.units.get(x, y)
if (not unit) then
no_space = false
end
end)
if no_space then return 0 end
-- Set up the probability array
local probabilities, probability_sum = {}, 0
-- Go through all the types listed in [probability] tags (which can be comma-separated lists)
for prob in wml.child_range(cfg, "probability") do
types = AH.split(prob.type, ",")
for _,typ in ipairs(types) do -- 'type' is a reserved keyword in Lua
-- If this type is in the recruit list, add it
for _,recruit in ipairs(wesnoth.sides[wesnoth.current.side].recruit) do
if (recruit == typ) then
probabilities[typ] = { value = prob.probability }
probability_sum = probability_sum + prob.probability
break
end
end
end
end
-- Now we add in all the unit types not listed in [probability] tags
for _,recruit in ipairs(wesnoth.sides[wesnoth.current.side].recruit) do
if (not probabilities[recruit]) then
probabilities[recruit] = { value = 1 }
probability_sum = probability_sum + 1
end
end
-- Now eliminate all those that are too expensive (unless cfg.skip_low_gold_recruiting is set)
if cfg.skip_low_gold_recruiting then
for typ,probability in pairs(probabilities) do -- 'type' is a reserved keyword in Lua
if (wesnoth.unit_types[typ].cost > wesnoth.sides[wesnoth.current.side].gold) then
probability_sum = probability_sum - probability.value
probabilities[typ] = nil
end
end
end
-- Now set up the cumulative probability values for each type
-- Both min and max need to be set as the order of pairs() is not guaranteed
local cum_prob = 0
for typ,probability in pairs(probabilities) do
probabilities[typ].p_i = cum_prob
cum_prob = cum_prob + probability.value
probabilities[typ].p_f = cum_prob
end
-- We always call the exec function, no matter if the selected unit is affordable
-- The point is that this will blacklist the CA if an unaffordable recruit was
-- chosen -> no cheaper recruits will be selected in subsequent calls
if (cum_prob > 0) then
local rand_prob = math.random(cum_prob)
for typ,probability in pairs(probabilities) do
if (probability.p_i < rand_prob) and (rand_prob <= probability.p_f) then
recruit_type = typ
break
end
end
else
recruit_type = wesnoth.sides[wesnoth.current.side].recruit[1]
end
return cfg.ca_score
end
function ca_recruit_random:execution(cfg)
-- Let this function blacklist itself if the chosen recruit is too expensive
if wesnoth.unit_types[recruit_type].cost <= wesnoth.sides[wesnoth.current.side].gold then
AH.checked_recruit(ai, recruit_type)
end
end
return ca_recruit_random
| gpl-2.0 |
ffxinfinity/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Heavens_Tower/npcs/Foo_Beibo.lua | 4 | 1036 | -----------------------------------
-- Area: Heavens Tower
-- NPC: Foo Beibo
-- Type: Standard NPC
-- @zone: 242
-- @pos: 10.717 -46 -28.629
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Heavens_Tower/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0057);
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 |
waytim/darkstar | scripts/globals/abilities/wind_maneuver.lua | 19 | 1605 | -----------------------------------
-- Ability: Wind Maneuver
-- Enhances the effect of wind attachments. Must have animator equipped.
-- Obtained: Puppetmaster level 1
-- Recast Time: 10 seconds (shared with all maneuvers)
-- Duration: 1 minute
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------
-- onAbilityCheck
-----------------------------------
function onAbilityCheck(player,target,ability)
if (player:getWeaponSubSkillType(SLOT_RANGED) == 10 and
not player:hasStatusEffect(EFFECT_OVERLOAD)) then
return 0,0;
else
return 71,0;
end
end;
-----------------------------------
-- onUseAbility
-----------------------------------
function onUseAbility(player,target,ability)
local burden = 15;
if (target:getStat(MOD_AGI) < target:getPet():getStat(MOD_AGI)) then
burden = 20;
end
local overload = target:addBurden(ELE_WIND-1, burden);
if (overload ~= 0) then
target:removeAllManeuvers();
target:addStatusEffect(EFFECT_OVERLOAD, 0, 0, overload);
else
local level;
if (target:getMainJob() == JOBS.PUP) then
level = target:getMainLvl()
else
level = target:getSubLvl()
end
local bonus = 1 + (level/15) + target:getMod(MOD_MANEUVER_BONUS);
if (target:getActiveManeuvers() == 3) then
target:removeOldestManeuver();
end
target:addStatusEffect(EFFECT_WIND_MANEUVER, bonus, 0, 60);
end
return EFFECT_WIND_MANEUVER;
end; | gpl-3.0 |
waytim/darkstar | scripts/zones/Rabao/npcs/Dancing_Wolf.lua | 13 | 1654 | -----------------------------------
-- Area: Rabao
-- NPC: Dancing Wolf
-- Type: Standard NPC
-- @zone: 247
-- @pos 7.619 7 81.209
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Rabao/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getCurrentMission(BASTOK) == THE_SALT_OF_THE_EARTH and player:getVar("BASTOK91") == 1) then
player:startEvent(0x0066);
elseif (player:getCurrentMission(BASTOK) == THE_SALT_OF_THE_EARTH and player:getVar("BASTOK91") == 2) then
player:startEvent(0x0067);
elseif (player:getCurrentMission(BASTOK) == THE_SALT_OF_THE_EARTH and player:getVar("BASTOK91") == 3 and player:hasKeyItem(MIRACLESALT)) then
player:startEvent(0x0068);
elseif (player:getVar("BASTOK91") == 4) then
player:startEvent(0x0069);
else
player:startEvent(0x006A);
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 == 0x0066) then
player:setVar("BASTOK91",2);
elseif (csid == 0x0068) then
player:setVar("BASTOK91",4);
end
end;
| gpl-3.0 |
TheOnePharaoh/YGOPro-Custom-Cards | script/c83030016.lua | 2 | 1532 | --Carefree Gate
function c83030016.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetCountLimit(1,83030016+EFFECT_COUNT_CODE_OATH)
e1:SetCost(c83030016.cost)
e1:SetTarget(c83030016.target)
e1:SetOperation(c83030016.activate)
c:RegisterEffect(e1)
end
function c83030016.costfilter(c)
return c:IsSetCard(0x833) and c:IsType(TYPE_MONSTER) and not c:IsPublic()
end
function c83030016.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c83030016.costfilter,tp,LOCATION_HAND,0,1,e:GetHandler()) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_CONFIRM)
local g=Duel.SelectMatchingCard(tp,c83030016.costfilter,tp,LOCATION_HAND,0,1,1,e:GetHandler())
Duel.ConfirmCards(1-tp,g)
Duel.RaiseSingleEvent(g:GetFirst(),83030012,e,REASON_COST,tp,tp,0)
Duel.ShuffleHand(tp)
end
function c83030016.filter(c)
return c:IsSetCard(0x833) and c:IsType(TYPE_MONSTER) and c:IsAbleToHand()
end
function c83030016.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c83030016.filter,tp,LOCATION_DECK,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK)
end
function c83030016.activate(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectMatchingCard(tp,c83030016.filter,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-3.0 |
waytim/darkstar | scripts/zones/Bastok_Markets/npcs/Raghd.lua | 16 | 1292 | -----------------------------------
-- Area: Bastok Markets
-- NPC: Raghd
-- Standard Merchant NPC
--
-- Updated Aug-09-2013 by Zerahn, based on bgwiki and gamerescape
-----------------------------------
require("scripts/globals/shop");
package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil;
require("scripts/zones/Bastok_Markets/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,RAGHD_SHOP_DIALOG);
stock = {
0x3490, 1125,1, --Silver Ring
0x340F, 1125,1, --Silver Earring
0x3499, 180,2, --Brass Ring
0x348E, 68,3 --Copper Ring
}
showNationShop(player, BASTOK, 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 |
waytim/darkstar | scripts/zones/Apollyon/mobs/Barometz.lua | 4 | 1272 | -----------------------------------
-- Area: Apollyon NE
-- NPC: Barometz
-----------------------------------
package.loaded["scripts/zones/Apollyon/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/limbus");
require("scripts/zones/Apollyon/TextIDs");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, player, isKiller)
local mobID = mob:getID();
-- print(mobID);
local mobX = mob:getXPos();
local mobY = mob:getYPos();
local mobZ = mob:getZPos();
if (mobID ==16933045) then -- time T2
GetNPCByID(16932864+81):setPos(459,-1,29);
GetNPCByID(16932864+81):setStatus(STATUS_NORMAL);
elseif (mobID ==16933049) then -- time T3
GetNPCByID(16932864+82):setPos(480,-1,-39);
GetNPCByID(16932864+82):setStatus(STATUS_NORMAL);
elseif (mobID ==16933055) then -- item
GetNPCByID(16932864+119):setPos(mobX,mobY,mobZ);
GetNPCByID(16932864+119):setStatus(STATUS_NORMAL);
end
end; | gpl-3.0 |
Shayan123456/botttttt | plugins/inpm.lua | 243 | 3007 | do
local function pairsByKeys (t, f)
local a = {}
for n in pairs(t) do table.insert(a, n) end
table.sort(a, f)
local i = 0 -- iterator variable
local iter = function () -- iterator function
i = i + 1
if a[i] == nil then return nil
else return a[i], t[a[i]]
end
end
return iter
end
local function chat_list(msg)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] then
return 'No groups at the moment'
end
local message = 'List of Groups:\n*Use /join (ID) to join*\n\n '
for k,v in pairs(data[tostring(groups)]) do
local settings = data[tostring(v)]['settings']
for m,n in pairsByKeys(settings) do
if m == 'set_name' then
name = n
end
end
message = message .. '👥 '.. name .. ' (ID: ' .. v .. ')\n\n '
end
local file = io.open("./groups/lists/listed_groups.txt", "w")
file:write(message)
file:flush()
file:close()
return message
end
local function run(msg, matches)
if msg.to.type ~= 'chat' or is_sudo(msg) or is_admin(msg) and is_realm(msg) then
local data = load_data(_config.moderation.data)
if matches[1] == 'join' and data[tostring(matches[2])] then
if is_banned(msg.from.id, matches[2]) then
return 'You are banned.'
end
if is_gbanned(msg.from.id) then
return 'You are globally banned.'
end
if data[tostring(matches[2])]['settings']['lock_member'] == 'yes' and not is_owner2(msg.from.id, matches[2]) then
return 'Group is private.'
end
local chat_id = "chat#id"..matches[2]
local user_id = "user#id"..msg.from.id
chat_add_user(chat_id, user_id, ok_cb, false)
local group_name = data[tostring(matches[2])]['settings']['set_name']
return "Added you to chat:\n\n👥"..group_name.." (ID:"..matches[2]..")"
elseif matches[1] == 'join' and not data[tostring(matches[2])] then
return "Chat not found."
end
if matches[1] == 'chats'then
if is_admin(msg) and msg.to.type == 'chat' then
return chat_list(msg)
elseif msg.to.type ~= 'chat' then
return chat_list(msg)
end
end
if matches[1] == 'chatlist'then
if is_admin(msg) and msg.to.type == 'chat' then
send_document("chat#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false)
elseif msg.to.type ~= 'chat' then
send_document("user#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false)
end
end
end
end
return {
patterns = {
"^[/!](chats)$",
"^[/!](chatlist)$",
"^[/!](join) (.*)$",
"^[/!](kickme) (.*)$",
"^!!tgservice (chat_add_user)$"
},
run = run,
}
end
| gpl-2.0 |
TheOnePharaoh/YGOPro-Custom-Cards | script/c90000078.lua | 2 | 5444 | --Black Flag Artificer
function c90000078.initial_effect(c)
--Pendulum Summon
aux.EnablePendulumAttribute(c)
--Pendulum Limit
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET+EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_CANNOT_NEGATE)
e1:SetCode(EFFECT_CANNOT_SPECIAL_SUMMON)
e1:SetRange(LOCATION_PZONE)
e1:SetTargetRange(1,0)
e1:SetTarget(c90000078.tg)
c:RegisterEffect(e1)
--Scale Change
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetRange(LOCATION_PZONE)
e2:SetCountLimit(1)
e2:SetCost(c90000078.cost)
e2:SetOperation(c90000078.operation)
c:RegisterEffect(e2)
--Special Summon
local e3=Effect.CreateEffect(c)
e3:SetCategory(CATEGORY_SPECIAL_SUMMON)
e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e3:SetCode(EVENT_BATTLE_DESTROYED)
e3:SetRange(LOCATION_PZONE)
e3:SetCountLimit(1)
e3:SetTarget(c90000078.target)
e3:SetOperation(c90000078.operation2)
c:RegisterEffect(e3)
--Special Summon
local e4=Effect.CreateEffect(c)
e4:SetType(EFFECT_TYPE_FIELD)
e4:SetProperty(EFFECT_FLAG_UNCOPYABLE)
e4:SetCode(EFFECT_SPSUMMON_PROC)
e4:SetRange(LOCATION_HAND)
e4:SetCondition(c90000078.condition)
c:RegisterEffect(e4)
--Pierce
local e5=Effect.CreateEffect(c)
e5:SetType(EFFECT_TYPE_FIELD)
e5:SetCode(EFFECT_PIERCE)
e5:SetRange(LOCATION_MZONE)
e5:SetTargetRange(LOCATION_MZONE,0)
e5:SetTarget(aux.TargetBoolFunction(Card.IsRace,RACE_ZOMBIE))
c:RegisterEffect(e5)
--Pierce X2
local e6=Effect.CreateEffect(c)
e6:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e6:SetCode(EVENT_PRE_BATTLE_DAMAGE)
e6:SetRange(LOCATION_MZONE)
e6:SetCondition(c90000078.condition2)
e6:SetOperation(c90000078.operation3)
c:RegisterEffect(e6)
--Change Equip
local e7=Effect.CreateEffect(c)
e7:SetCategory(CATEGORY_EQUIP)
e7:SetType(EFFECT_TYPE_QUICK_O)
e7:SetProperty(EFFECT_FLAG_CARD_TARGET)
e7:SetCode(EVENT_FREE_CHAIN)
e7:SetRange(LOCATION_MZONE)
e7:SetHintTiming(0,TIMING_EQUIP)
e7:SetCountLimit(1)
e7:SetTarget(c90000078.target2)
e7:SetOperation(c90000078.operation4)
c:RegisterEffect(e7)
end
function c90000078.tg(e,c,sump,sumtype,sumpos,targetp)
return not c:IsRace(RACE_ZOMBIE) and bit.band(sumtype,SUMMON_TYPE_PENDULUM)==SUMMON_TYPE_PENDULUM
end
function c90000078.filter(c)
return c:IsRace(RACE_ZOMBIE) and not c:IsPublic()
end
function c90000078.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c90000078.filter,tp,LOCATION_HAND,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_CONFIRM)
local g=Duel.SelectMatchingCard(tp,c90000078.filter,tp,LOCATION_HAND,0,1,1,nil)
Duel.ConfirmCards(1-tp,g)
Duel.ShuffleHand(tp)
e:SetLabel(g:GetFirst():GetLevel())
end
function c90000078.operation(e,tp,eg,ep,ev,re,r,rp)
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_CHANGE_LSCALE)
e1:SetValue(e:GetLabel())
e1:SetReset(RESET_EVENT+0x1ff0000)
e:GetHandler():RegisterEffect(e1)
local e2=e1:Clone()
e2:SetCode(EFFECT_CHANGE_RSCALE)
e:GetHandler():RegisterEffect(e2)
end
function c90000078.target(e,tp,eg,ep,ev,re,r,rp,chk)
local tc=eg:GetFirst()
if chk==0 then return Duel.GetLocationCount(tc:GetPreviousControler(),LOCATION_MZONE)>0 and eg:GetCount()==1 and tc:IsRace(RACE_ZOMBIE)
and tc:IsReason(REASON_BATTLE) and tc:IsCanBeSpecialSummoned(e,0,tp,false,false,POS_FACEUP_ATTACK,tc:GetPreviousControler()) end
tc:CreateEffectRelation(e)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,eg,1,0,0)
end
function c90000078.operation2(e,tp,eg,ep,ev,re,r,rp)
local tc=eg:GetFirst()
if tc:IsRelateToEffect(e) then
Duel.SpecialSummon(tc,0,tp,tc:GetPreviousControler(),false,false,POS_FACEUP_ATTACK)
end
end
function c90000078.condition(e,c)
if c==nil then return true end
return Duel.GetLocationCount(c:GetControler(),LOCATION_MZONE)>0
and Duel.GetFieldGroupCount(c:GetControler(),LOCATION_MZONE,0,nil)<Duel.GetFieldGroupCount(c:GetControler(),0,LOCATION_MZONE,nil)
end
function c90000078.condition2(e,tp,eg,ep,ev,re,r,rp)
local tc=eg:GetFirst()
return ep~=tp and tc:IsRace(RACE_ZOMBIE) and tc:GetBattleTarget()~=nil and tc:GetBattleTarget():IsDefensePos()
end
function c90000078.operation3(e,tp,eg,ep,ev,re,r,rp)
Duel.ChangeBattleDamage(ep,ev*2)
end
function c90000078.filter2(tc,ec)
return tc:IsFaceup() and ec:CheckEquipTarget(tc)
end
function c90000078.filter3(c)
return c:IsType(TYPE_EQUIP) and c:GetEquipTarget()~=nil
and Duel.IsExistingTarget(c90000078.filter2,0,LOCATION_MZONE,LOCATION_MZONE,1,c:GetEquipTarget(),c)
end
function c90000078.target2(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingTarget(c90000078.filter3,tp,LOCATION_SZONE,LOCATION_SZONE,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,aux.Stringid(90000078,0))
local g=Duel.SelectTarget(tp,c90000078.filter3,tp,LOCATION_SZONE,LOCATION_SZONE,1,1,nil)
local ec=g:GetFirst()
e:SetLabelObject(ec)
Duel.Hint(HINT_SELECTMSG,tp,aux.Stringid(90000078,1))
local tc=Duel.SelectTarget(tp,c90000078.filter2,tp,LOCATION_MZONE,LOCATION_MZONE,1,1,ec:GetEquipTarget(),ec)
end
function c90000078.operation4(e,tp,eg,ep,ev,re,r,rp)
local ec=e:GetLabelObject()
local g=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS)
local tc=g:GetFirst()
if tc==ec then tc=g:GetNext() end
if ec:IsFaceup() and ec:IsRelateToEffect(e) then
if tc:IsFaceup() and tc:IsRelateToEffect(e) then
Duel.Equip(tp,ec,tc)
else
Duel.SendtoGrave(ec,REASON_EFFECT)
end
end
end | gpl-3.0 |
ffxinfinity/ffxinfinity | FFXI Server-Development/Build Files/scripts/globals/items/pot_of_san_dorian_tea.lua | 3 | 1100 | -----------------------------------------
-- ID: 4494
-- Item: pot_of_san_dorian_tea
-- Food Effect: 180Min, All Races
-----------------------------------------
-- Vitality -2
-- Charisma 2
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,10800,4494);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_VIT, -2);
target:addMod(MOD_CHR, 2);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_VIT, -2);
target:delMod(MOD_CHR, 2);
end;
| gpl-3.0 |
waytim/darkstar | scripts/zones/Windurst_Walls/npcs/Shinchai-Tocchai.lua | 13 | 1066 | -----------------------------------
-- Area: Windurst Walls
-- NPC: Shinchai-Tocchai
-- Type: Moghouse Renter
-- @zone: 239
-- @pos -220.551 -0.001 -116.916
--
-- Auto-Script: Requires Verification (Verfied by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Windurst_Walls/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x01f9);
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 |
gfgtdf/wesnoth-old | data/campaigns/World_Conquest/lua/map/generator/savannah.lua | 4 | 2031 |
local function generate(length, villages, castle, iterations, size, players, island)
local res = wct_generator_settings_arguments( length, villages, castle, iterations, size, players, island)
res.max_lakes=10
res.min_lake_height=150
res.lake_size=125
res.river_frequency=100
res.temperature_size=8
res.roads=12
res.road_windiness=10
res.height = {
dr_height(900, "Uh"),
dr_height(800, "Uu"),
dr_height(750, "Xu"),
dr_height(725, "Mm^Xm"),
dr_height(675, "Mm"),
dr_height(550, "Hh"),
dr_height(175, "Gs"),
dr_height(30, "Ds"),
dr_height(1, "Ww"),
dr_height(0, "Wo"),
}
res.convert = {
-- swamp appears on low land, at moderate temperatures
dr_convert(nil, 300, 300, 700, "Gg,Gs", "Ss"),
-- jungle appears at moderately high temperatures
dr_temperature("Gg,Gs", 380, 430, "Gs^Ft"),
dr_temperature("Gg,Gs", 460, 520, "Gs^Ft"),
-- fungus appears at medium temperatures and extremely high elevation
-- DR_CONVERT MIN_HT MAX_HT MIN_TMP MAX_TMP FROM TO
dr_convert(825, 950, 500, 525, "Uu, Uh", "Uu^Uf"),
dr_convert(825, 950, 550, 575, "Uu, Uh", "Uu^Uf"),
dr_convert(825, 950, 600, 625, "Uu, Uh", "Uu^Uf"),
-- lava appears at extreme temperatures and elevation
dr_convert(800, nil, 900, nil, "Uu, Uh, Uu^Uf", "Ql"),
-- desert appears at high temperatures
dr_temperature("Gs", 475, 500, "Dd"),
dr_temperature("Gs", 600, 650, "Dd"),
dr_temperature("Gs", 725, 775, "Dd"),
dr_temperature("Gs", 800, 999, "Dd"),
-- dunes appear at extreme temperatures
dr_temperature("Hh", 625, 650, "Hd"),
dr_temperature("Hh", 750, 775, "Hd"),
dr_temperature("Hh", 825, 999, "Hd"),
}
res.road_cost = {
wct_generator_road_cost_classic(),
dr_road("Ds", "Re", 15),
dr_road("Dd", "Re", 15),
dr_road("Gs^Ft", "Re", 20),
dr_bridge("Ww", "Ww^Bw", "Ce", 50),
}
res.village = {
wct_generator_village(2, 8, 8, 4, 3, 2, 6, 3, 3, 3, 5, 1)
}
res.castle = {
valid_terrain="Gs, Gg, Gs^Fp, Hh, Ds, Dd",
min_distance=12,
}
return default_generate_map(res)
end
return generate
| gpl-2.0 |
galek/crown | 3rdparty/bx/scripts/genie.lua | 22 | 1993 | --
-- Copyright 2010-2021 Branimir Karadzic. All rights reserved.
-- License: https://github.com/bkaradzic/bx#license-bsd-2-clause
--
newoption {
trigger = "with-amalgamated",
description = "Enable amalgamated build.",
}
newoption {
trigger = "with-crtnone",
description = "Enable build without CRT.",
}
solution "bx"
configurations {
"Debug",
"Release",
}
platforms {
"x32",
"x64",
"Native", -- for targets where bitness is not specified
}
language "C++"
BX_DIR = path.getabsolute("..")
BX_BUILD_DIR = path.join(BX_DIR, ".build")
BX_THIRD_PARTY_DIR = path.join(BX_DIR, "3rdparty")
dofile "toolchain.lua"
toolchain(BX_BUILD_DIR, BX_THIRD_PARTY_DIR)
function copyLib()
end
dofile "bx.lua"
dofile "bin2c.lua"
dofile "lemon.lua"
project "bx.test"
kind "ConsoleApp"
debugdir (path.join(BX_DIR, "tests"))
removeflags {
"NoExceptions",
}
includedirs {
path.join(BX_DIR, "include"),
BX_THIRD_PARTY_DIR,
}
files {
path.join(BX_DIR, "tests/*_test.cpp"),
path.join(BX_DIR, "tests/*.h"),
path.join(BX_DIR, "tests/dbg.*"),
}
links {
"bx",
}
configuration { "vs* or mingw*" }
links {
"psapi",
}
configuration { "android*" }
targetextension ".so"
linkoptions {
"-shared",
}
configuration { "linux-*" }
links {
"pthread",
}
configuration { "osx*" }
links {
"Cocoa.framework",
}
configuration {}
strip()
project "bx.bench"
kind "ConsoleApp"
debugdir (path.join(BX_DIR, "tests"))
includedirs {
path.join(BX_DIR, "include"),
BX_THIRD_PARTY_DIR,
}
files {
path.join(BX_DIR, "tests/*_bench.cpp"),
path.join(BX_DIR, "tests/*_bench.h"),
path.join(BX_DIR, "tests/dbg.*"),
}
links {
"bx",
}
configuration { "vs* or mingw*" }
links {
"psapi",
}
configuration { "android*" }
targetextension ".so"
linkoptions {
"-shared",
}
configuration { "linux-*" }
links {
"pthread",
}
configuration { "osx*" }
links {
"Cocoa.framework",
}
configuration {}
strip()
| mit |
ffxinfinity/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Windurst_Waters_[S]/npcs/Ampiro-Mapiro.lua | 4 | 1054 | -----------------------------------
-- Area: Windurst Waters (S)
-- NPC: Ampiro-Mapiro
-- Type: Standard NPC
-- @zone: 94
-- @pos: 131.380 -6.75 174.169
--
-- 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(0x01a7);
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 |
ffxinfinity/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Norg/npcs/Colleraie.lua | 4 | 1029 | -----------------------------------
-- Area: Norg
-- NPC: Colleraie
-- Type: Event Scene Replayer
-- @zone: 252
-- @pos: -24.684 0.097 -39.409
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Norg/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x00af);
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 |
gfgtdf/wesnoth-old | data/campaigns/World_Conquest/lua/map/tools/filter_converter.lua | 4 | 5022 |
----------------------------------------------------------
---- A helper tool, that works (mostly) indpendently ----
---- of the rest to convert location filter wml to ----
---- the filter syntax used in this addon ----
---- (map:get_locations) ----
----------------------------------------------------------
local and_to_all = {
["and"] = "all",
["or"] = "any",
["not"] = "none"
}
local comp_tags = {
any = true,
all = true,
none = true,
notall = true,
}
function compose_filter_1(tag, f1, f2)
if tag == f1[1] then
if tag == f2[1] then
for i = 2, #f2 do
table.insert(f1, f2[i])
end
else
table.insert(f1, f2)
end
return f1
else
if tag == f2[1] then
table.insert(f2, 2, f1)
return f2
else
return {tag, f1, f2}
end
end
end
function compose_filter(tag, f1, f2)
local res = compose_filter_1(tag, f1, f2)
if #res == 2 then
return res[2]
end
return res
end
function parse_wml_filter(cfg)
local res = { "all" }
if cfg.x then
table.insert(res, { "x", cfg.x})
end
if cfg.y then
table.insert(res, { "y", cfg.y})
end
if cfg.terrain then
table.insert(res, { "terrain", cfg.terrain})
end
if cfg.find_in then
table.insert(res, { "find_in_wml", cfg.find_in})
end
for ad in wml.child_range(cfg, "filter_adjacent_location") do
table.insert(res, { "adjacent", parse_wml_filter(ad), adjacent = ad.adjacent, count = ad.count })
end
if #res == 1 then
print("empty filter")
end
if #res == 2 then
res = res[2]
end
for i, v in ipairs(cfg) do
local tag = and_to_all[v[1]]
local content = v[2]
if tag ~= nil then
local subfilter = parse_wml_filter(content)
if tag == "none" then
subfilter = { "none", subfilter }
tag = "all"
end
res = compose_filter(tag, res, subfilter)
end
end
if cfg.radius then
local filter_radius = wml.get_child(cfg, "filter_radius")
filter_radius = filter_radius and parse_wml_filter(filter_radius)
res = { "radius", cfg.radius, res, filter_radius = filter_radius }
end
return res
end
local function value_to_str(val)
if val == nil then
return "nil"
elseif type(val) == "number" or type(val) == "boolean" then
return tostring(val)
elseif type(val) == "string" then
return string.format("%q", val)
else
error("unknown type:'" .. type(val) .. "'")
end
end
function print_filter(f, indent)
local res = {}
indent = indent or 0
local function write(str)
res[#res + 1] = str
end
local function write_newline()
res[#res + 1] = "\n" .. string.rep("\t", indent)
end
local function write_filter(filter)
if filter[1] == "adjacent" then
write("f.adjacent(")
write_filter(filter[2])
if (filter.adjacent or filter.count) then
write(", " .. value_to_str(filter.adjacent))
write(", " .. value_to_str(filter.count))
end
write(")")
end
if filter[1] == "x" or filter[1] == "y" or filter[1] == "terrain" or filter[1] == "find_in_wml" then
write("f." .. filter[1] .. "(")
write(value_to_str(filter[2]))
write(")")
end
if filter[1] == "radius" then
--f_radius(r, f, f_r)
write("f.radius(")
write(value_to_str(filter[2]))
write(", ")
write_filter(filter[3])
if filter.filter_radius then
write(", ")
write_filter(filter.filter_radius)
end
write(")")
end
if comp_tags[filter[1]] then
write("f." .. filter[1] .. "(")
indent = indent + 1
for i = 2, #filter do
local is_last = (i == #filter)
write_newline()
write_filter(filter[i])
if not is_last then
write(",")
end
end
indent = indent - 1
write_newline()
write(")")
end
end
write_filter(f)
return table.concat(res, "")
end
function print_set_terrain(filter, terrain, extra)
std_print("set_terrain { " .. value_to_str(terrain) .. ",")
std_print("\t" .. print_filter(filter, 1) .. ",")
for k, v in pairs(extra) do
std_print("\t" .. k .. " = " .. value_to_str(v) .. ",")
end
std_print("}")
end
function convert_filter()
local cfg = wml.parse(wesnoth.read_file("./filterdata.cfg"))
std_print("")
for i, v in ipairs(cfg) do
local tag = v[1]
local content = v[2]
if tag == "terrain" then
local terrain = content.terrain
content.terrain = nil
local f = parse_wml_filter(content)
print_set_terrain(f, terrain, { layer = content.layer })
end
if tag == "wc2_terrain" then
for change in wml.child_range(content, "change") do
local terrain = change.terrain
local f = parse_wml_filter(wml.get_child(change, "filter"))
local extras = {}
for k, v in pairs(change) do
if type(k) == "string" and k ~= "terrain" then
extras[k] = v
end
end
print_set_terrain(f, terrain, extras)
end
end
if tag == "store_locations" then
local variable = content.variable
local f = parse_wml_filter(content)
std_print("local " .. variable .. " = map:get_locations(" .. print_filter(f, 1) .. ")")
end
end
--local filter = parse_wml_filter(cfg)
--std_print(print_filter(filter))
end
convert_filter()
| gpl-2.0 |
Kefta/gs_lib | lua/code_gs/lib/cl_render.lua | 1 | 6785 | -- FIXME: Add GetTexture and GetMaterial?
local gs_lib_clearpixelbuffer = CreateConVar("gs_lib_clearpixelbuffer", "0", FCVAR_ARCHIVE, "Clears the pixel buffer before rendering starts, preventing tearing when looking at a leak")
hook.Add("PreRender", "gs_lib", function()
if (gs_lib_clearpixelbuffer:GetBool()) then
cam.Start2D()
surface.SetDrawColor(0, 0, 0, 255)
surface.DrawRect(0, 0, ScrW(), ScrH())
cam.End2D()
end
end)
function render.GetViewPortPosition()
return 0, 0 -- FIXME
end
-- FIXME: Change next update
function render.GetRenderTargetDimensions()
local texRT = render.GetRenderTarget()
return texRT:Width(), texRT:Height()
end
function render.ViewDrawFade(col, pMaterial)
pMaterial:AlphaModulate(col.a)
pMaterial:ColorModulate(col)
-- Attempt to set ignorez; not guarenteed to work
local PrevIgnoreZ = pMaterial:GetInt("$ignorez")
if (PrevIgnoreZ == nil or PrevIgnoreZ == 0) then
pMaterial:SetInt("$ignorez", 1)
pMaterial:Recompute()
render.SetMaterial(pMaterial)
end
local flUOffset = 0.5 / pMaterial:GetMappingWidth()
local flInvUOffset = 1 - flUOffset
local flVOffset = 0.5 / pMaterial:GetMappingHeight()
local flInvVOffset = 1 - flVOffset
-- FIXME
local iWidth, iHeight = render.GetRenderTargetDimensions()
render.SetViewPort(0, 0, iWidth, iHeight)
local x, y = render.GetViewPortPosition()
// adjusted xys
local x1 = x - 0.5
local x2 = x + iWidth
local y1 = y - 0.5
local y2 = y + iHeight
// adjust nominal uvs to reflect adjusted xys
local u1 = math.FLerp(flUOffset, flInvUOffset, x, x2, x1)
local u2 = math.FLerp(flUOffset, flInvUOffset, x, x2, x2)
local v1 = math.FLerp(flVOffset, flInvVOffset, y, y2, y1)
local v2 = math.FLerp(flVOffset, flInvVOffset, y, y2, y2)
-- Use the dynamic mesh
mesh.Begin(MATERIAL_QUADS, 1)
-- Top left
mesh.Position(Vector(x1, y1))
mesh.TexCoord(0, u1, v1)
mesh.AdvanceVertex()
-- Top right
mesh.Position(Vector(x2, y1))
mesh.TexCoord(0, u2, v1)
mesh.AdvanceVertex()
-- Bottom right
mesh.Position(Vector(x2, y2))
mesh.TexCoord(0, u2, v2)
mesh.AdvanceVertex()
-- Bottom left
mesh.Position(Vector(x1, y2))
mesh.TexCoord(0, u1, v2)
mesh.AdvanceVertex()
mesh.End()
if (PrevIgnoreZ == nil) then
pMaterial:SetUndefined("$ignorez")
pMaterial:Recompute()
render.SetMaterial(pMaterial)
elseif (PrevIgnoreZ == 0) then
pMaterial:SetInt("$ignorez", PrevIgnoreZ)
pMaterial:Recompute()
render.SetMaterial(pMaterial)
end
end
function render.DrawScreenSpaceRectangle(
iDestX, iDestY, iWidth, iHeight, // Rect to draw into in screen space
flSrcTextureX0, flSrcTextureY0, // which texel you want to appear at destx/y
flSrcTextureX1, flSrcTextureY1, // which texel you want to appear at destx+width-1, desty+height-1
iSrcTextureWidth, iSrcTextureHeight, // needed for fixup
iXDice --[[= 1]], iYDice --[[= 1]]) // Amount to tessellate the ... -- I believe the correct answer is "quad." Some programmer went on a lunch break and couldn't finish the fucking comment
if (iXDice == nil) then
iXDice = 1
end
if (iYDice == nil) then
iYDice = 1
end
render.DrawScreenQuad()
local iScreenWidth, iScreenHeight = render.GetRenderTargetDimensions()
// Get the current viewport size
local iViewWidth = ScrW()
local iViewHeight = ScrH()
// map from screen pixel coords to -1..1
local flLeftX = math.FLerp(-1, 1, 0, iViewWidth, iDestX - 0.5)
local flRightX = math.FLerp(-1, 1, 0, iViewWidth, iDestX + iWidth - 0.5)
local flTopY = math.FLerp(-1, 1, 0, iViewHeight, iDestY - 0.5)
local flBottomY = math.FLerp(-1, 1, 0, iViewHeight, iDestY + iHeight - 0.5)
local flTexelsPerPixelX = iWidth > 1 and 0.5 * ((flSrcTextureX1 - flSrcTextureX0) / (iWidth - 1)) or 0
local flTexelsPerPixelY = iHeight > 1 and 0.5 * ((flSrcTextureY1 - flSrcTextureY0) / (iHeight - 1)) or 0
local flOOTexWidth = 1 / iSrcTextureWidth
local flOOTexHeight = 1 / iSrcTextureHeight
local flLeftU = (flSrcTextureX0 + 0.5 - flTexelsPerPixelX) * flOOTexWidth
local flRightU = (flSrcTextureX1 + 0.5 + flTexelsPerPixelX) * flOOTexWidth
local flTopV = (flSrcTextureY0 + 0.5 - flTexelsPerPixelY) * flOOTexHeight
local flBottomV = (flSrcTextureY1 + 0.5 + flTexelsPerPixelY) * flOOTexHeight
mesh.Begin(MATERIAL_QUADS, iXDice * iYDice)
// Dice the quad up...
if (iXDice > 1 or iYDice > 1) then
// Screen height and width of a subrect
local flWidth = (flRightX - flLeftX) / iXDice
local flHeight = (flTopY - flBottomY) / iYDice
// UV height and width of a subrect
local flUWidth = (flRightU - flLeftU) / iXDice
local flVHeight = (flBottomV - flTopV) / iYDice
for x = 1, iXDice do
for y = 1, iYDice do
local xprev = x-1
local yprev = y-1
// Top left
mesh.Position(Vector(flLeftX + xprev * flWidth, flTopY - yprev * flHeight))
mesh.Normal(vector_up)
mesh.TexCoord(0, flLeftU + xprev * flUWidth, flTopV + yprev * flVHeight)
mesh.TangentS(vector_left)
mesh.TangentT(vector_forward)
mesh.AdvanceVertex()
// Top right (x+1)
mesh.Position(Vector(flLeftX + x * flWidth, flTopY - yprev * flHeight))
mesh.Normal(vector_up)
mesh.TexCoord(0, flLeftU + x * flUWidth, flTopV + yprev * flVHeight)
mesh.TangentS(vector_left)
mesh.TangentT(vector_forward)
mesh.AdvanceVertex()
// Bottom right (x+1), (y+1)
mesh.Position(Vector(flLeftX + x * flWidth, flTopY - y * flHeight))
mesh.Normal(vector_up)
mesh.TexCoord(0, flLeftU + x * flUWidth, flTopV + y * flVHeight)
mesh.TangentS(vector_left)
mesh.TangentT(vector_forward)
mesh.AdvanceVertex()
// Bottom left (y+1)
mesh.Position(Vector(flLeftX + xprev * flWidth, flTopY - y * flHeight))
mesh.Normal(vector_up)
mesh.TexCoord(0, flLeftU + xprev * flUWidth, flTopV + y * flVHeight)
mesh.TangentS(vector_left)
mesh.TangentT(vector_forward)
mesh.AdvanceVertex()
end
end
else // just one quad
-- Top left
mesh.Position(Vector(flLeftX, flTopY))
mesh.Normal(vector_up)
mesh.TexCoord(0, flLeftU, flTopV)
mesh.TangentS(vector_left)
mesh.TangentT(vector_forward)
mesh.AdvanceVertex()
-- Top right
mesh.Position(Vector(flRightX, flTopY))
mesh.Normal(vector_up)
mesh.TexCoord(0, flRightU, flTopV)
mesh.TangentS(vector_left)
mesh.TangentT(vector_forward)
mesh.AdvanceVertex()
-- Bottom left
mesh.Position(Vector(flRightX, flBottomY))
mesh.Normal(vector_up)
mesh.TexCoord(0, flRightU, flBottomV)
mesh.TangentS(vector_left)
mesh.TangentT(vector_forward)
mesh.AdvanceVertex()
-- Bottom right
mesh.Position(Vector(flLeftX, flBottomY))
mesh.Normal(vector_up)
mesh.TexCoord(0, flLeftU, flBottomV)
mesh.TangentS(vector_left)
mesh.TangentT(vector_forward)
mesh.AdvanceVertex()
end
mesh.End()
end
| mit |
TheOnePharaoh/YGOPro-Custom-Cards | script/c99990141.lua | 2 | 3600 | --SAO - Asuna ALO
function c99990141.initial_effect(c)
--synchro summon
aux.AddSynchroProcedure2(c,nil,aux.NonTuner(Card.IsSetCard,9999))
c:EnableReviveLimit()
--500 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:SetCondition(c99990141.acon)
e1:SetValue(500)
c:RegisterEffect(e1)
--Pierceing
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_PIERCE)
c:RegisterEffect(e2)
--Recover 500 Lp
local e3=Effect.CreateEffect(c)
e3:SetCategory(CATEGORY_RECOVER)
e3:SetCode(EVENT_BATTLE_DESTROYING)
e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e3:SetCondition(c99990141.condition)
e3:SetTarget(c99990141.target)
e3:SetOperation(c99990141.operation)
c:RegisterEffect(e3)
--ATK/DEF
local e4=Effect.CreateEffect(c)
e4:SetCategory(CATEGORY_ATKCHANGE)
e4:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F)
e4:SetCode(EVENT_BATTLE_DESTROYED)
e4:SetRange(LOCATION_MZONE)
e4:SetCondition(c99990141.atkcon)
e4:SetOperation(c99990141.atkop)
c:RegisterEffect(e4)
local e5=Effect.CreateEffect(c)
e5:SetCategory(CATEGORY_ATKCHANGE)
e5:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F)
e5:SetCode(EVENT_BATTLE_DESTROYED)
e5:SetRange(LOCATION_MZONE)
e5:SetCondition(c99990141.atkcon2)
e5:SetOperation(c99990141.atkop)
c:RegisterEffect(e5)
local e6=Effect.CreateEffect(c)
e6:SetCategory(CATEGORY_ATKCHANGE)
e6:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F)
e6:SetCode(EVENT_BATTLE_DESTROYED)
e6:SetRange(LOCATION_MZONE)
e6:SetCondition(c99990141.atkcon3)
e6:SetOperation(c99990141.atkop)
c:RegisterEffect(e6)
end
function c99990141.acon(e)
local ph=Duel.GetCurrentPhase()
if ph~=PHASE_DAMAGE and ph~=PHASE_DAMAGE_CAL then return false end
local a=Duel.GetAttacker()
local d=Duel.GetAttackTarget()
return e:GetHandler()==a and d and d:IsDefensePos()
end
function c99990141.condition(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local bc=c:GetBattleTarget()
return c:IsRelateToBattle()
end
function c99990141.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetTargetPlayer(tp)
Duel.SetTargetParam(500)
Duel.SetOperationInfo(0,CATEGORY_RECOVER,nil,0,tp,500)
end
function c99990141.operation(e,tp,eg,ep,ev,re,r,rp)
local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM)
Duel.Recover(p,d,REASON_EFFECT)
end
function c99990141.atkcon(e,tp,eg,ep,ev,re,r,rp)
local tc=eg:GetFirst()
local bc=tc:GetBattleTarget()
return tc:IsReason(REASON_BATTLE) and bc:IsRelateToBattle() and bc:IsControler(tp) and bc:IsSetCard(9999)
end
function c99990141.atkcon2(e,tp,eg,ep,ev,re,r,rp)
local tc=eg:GetFirst()
local bc=tc:GetBattleTarget()
if tc==nil then return false
elseif tc:IsType(TYPE_MONSTER) and bc:IsControler(tp) and bc:IsSetCard(9999) and tc:IsReason(REASON_BATTLE) and bc:IsReason(REASON_BATTLE) then return true end
end
function c99990141.atkcon3(e,tp,eg,ep,ev,re,r,rp)
local tc=eg:GetFirst()
local bc=tc:GetBattleTarget()
if tc==nil then return false
elseif bc:IsType(TYPE_MONSTER) and tc:IsControler(tp) and tc:IsSetCard(9999) and bc:IsReason(REASON_BATTLE) and tc:IsReason(REASON_BATTLE) then return true end
end
function c99990141.atkop(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_UPDATE_ATTACK)
e1:SetValue(200)
e1:SetReset(RESET_EVENT+0x1ff0000)
c:RegisterEffect(e1)
local e2=e1:Clone()
e2:SetCode(EFFECT_UPDATE_DEFENSE)
c:RegisterEffect(e2)
end | gpl-3.0 |
ffxinfinity/ffxinfinity | FFXI Server-Development/Build Files/scripts/globals/items/steamed_catfish.lua | 3 | 1384 | -----------------------------------------
-- ID: 4557
-- Item: steamed_catfish
-- Food Effect: 180Min, All Races
-----------------------------------------
-- Health 30
-- Magic % 1
-- Vitality 3
-- Intelligence 1
-- Mind -3
-- Earth Res 10
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,10800,4557);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 30);
target:addMod(MOD_MPP, 1);
target:addMod(MOD_VIT, 3);
target:addMod(MOD_INT, 1);
target:addMod(MOD_MND, -3);
target:addMod(MOD_EARTHRES, 5);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 30);
target:delMod(MOD_MPP, 1);
target:delMod(MOD_VIT, 3);
target:delMod(MOD_INT, 1);
target:delMod(MOD_MND, -3);
target:delMod(MOD_EARTHRES, 5);
end;
| gpl-3.0 |
waytim/darkstar | scripts/zones/Giddeus/npcs/Harvesting_Point.lua | 13 | 1059 | -----------------------------------
-- Area: Giddeus
-- NPC: Harvesting Point
-----------------------------------
package.loaded["scripts/zones/Giddeus/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/harvesting");
require("scripts/zones/Giddeus/TextIDs");
-----------------------------------
-- onTrade
-----------------------------------
function onTrade(player,npc,trade)
startHarvesting(player,player:getZoneID(),npc,trade,0x0046);
end;
-----------------------------------
-- onTrigger
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(HARVESTING_IS_POSSIBLE_HERE,1020);
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 |
chrox/koreader | frontend/ui/screensaver.lua | 4 | 5094 | local DocumentRegistry = require("document/documentregistry")
local UIManager = require("ui/uimanager")
local Screen = require("device").screen
local DocSettings = require("docsettings")
local DEBUG = require("dbg")
local _ = require("gettext")
local Screensaver = {
}
function Screensaver:getCoverImage(file)
local ImageWidget = require("ui/widget/imagewidget")
local CenterContainer = require("ui/widget/container/centercontainer")
local FrameContainer = require("ui/widget/container/framecontainer")
local AlphaContainer = require("ui/widget/container/alphacontainer")
local image_height
local image_width
local screen_height = Screen:getHeight()
local screen_width = Screen:getWidth()
local doc = DocumentRegistry:openDocument(file)
if doc then
local image = doc:getCoverPageImage()
doc:close()
local lastfile = G_reader_settings:readSetting("lastfile")
local data = DocSettings:open(lastfile)
local proportional_cover = data:readSetting("proportional_screensaver")
if image then
if proportional_cover then
image_height = image:getHeight()
image_width = image:getWidth()
local image_ratio = image_width / image_height
if image_ratio < 1 then
image_height = screen_height
image_width = image_height * image_ratio
else
image_width = screen_width
image_height = image_width / image_ratio
end
else
image_height = screen_height
image_width = screen_width
end
local image_widget = ImageWidget:new{
image = image,
width = image_width,
height = image_height,
}
return AlphaContainer:new{
alpha = 1,
height = screen_height,
width = screen_width,
CenterContainer:new{
dimen = Screen:getSize(),
FrameContainer:new{
bordersize = 0,
padding = 0,
height = screen_height,
width = screen_width,
image_widget
}
}
}
end
end
end
function Screensaver:getRandomImage(dir)
local ImageWidget = require("ui/widget/imagewidget")
local pics = {}
local i = 0
math.randomseed(os.time())
for entry in lfs.dir(dir) do
if lfs.attributes(dir .. entry, "mode") == "file" then
local extension = string.lower(string.match(entry, ".+%.([^.]+)") or "")
if extension == "jpg" or extension == "jpeg" or extension == "png" then
i = i + 1
pics[i] = entry
end
end
end
local image = pics[math.random(i)]
if image then
image = dir .. image
if lfs.attributes(image, "mode") == "file" then
return ImageWidget:new{
file = image,
width = Screen:getWidth(),
height = Screen:getHeight(),
}
end
end
end
function Screensaver:show()
DEBUG("show screensaver")
local InfoMessage = require("ui/widget/infomessage")
-- first check book cover image
if KOBO_SCREEN_SAVER_LAST_BOOK then
local lastfile = G_reader_settings:readSetting("lastfile")
if lastfile then
local data = DocSettings:open(lastfile)
local exclude = data:readSetting("exclude_screensaver")
if not exclude then
self.suspend_msg = self:getCoverImage(lastfile)
end
end
end
-- then screensaver directory or file image
if not self.suspend_msg then
if type(KOBO_SCREEN_SAVER) == "string" then
local file = KOBO_SCREEN_SAVER
if lfs.attributes(file, "mode") == "directory" then
if string.sub(file,string.len(file)) ~= "/" then
file = file .. "/"
end
self.suspend_msg = self:getRandomImage(file)
elseif lfs.attributes(file, "mode") == "file" then
local ImageWidget = require("ui/widget/imagewidget")
self.suspend_msg = ImageWidget:new{
file = file,
width = Screen:getWidth(),
height = Screen:getHeight(),
}
end
end
end
-- fallback to suspended message
if not self.suspend_msg then
self.suspend_msg = InfoMessage:new{ text = _("Suspended") }
UIManager:show(self.suspend_msg)
else
-- refresh whole screen for other types
UIManager:show(self.suspend_msg, "full")
end
end
function Screensaver:close()
DEBUG("close screensaver")
if self.suspend_msg then
UIManager:close(self.suspend_msg)
self.suspend_msg = nil
end
end
return Screensaver
| agpl-3.0 |
ffxinfinity/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Moh_Gates/Zone.lua | 3 | 1050 | -----------------------------------
--
-- Zone: Moh Gates
--
-----------------------------------
require("scripts/globals/settings");
package.loaded["scripts/zones/Moh_Gates/TextIDs"] = nil;
require("scripts/zones/Moh_Gates/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 |
ffxinfinity/ffxinfinity | FFXI Server-Development/Build Files/scripts/globals/spells/banishga_iii.lua | 2 | 1062 | -----------------------------------------
-- Spell: Banishga 3
-- Deals light damage to an enemy.
-----------------------------------------
require("scripts/globals/magic");
require("scripts/globals/status");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function OnMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
--calculate raw damage
dmg = calculateMagicDamage(480,1,caster,spell,target,DIVINE_MAGIC_SKILL,MOD_MND,false);
--get resist multiplier (1x if no resist)
resist = applyResistance(caster,spell,target,caster:getStat(MOD_MND)-target:getStat(MOD_MND),DIVINE_MAGIC_SKILL,1.0);
--get the resisted damage
dmg = dmg*resist;
--add on bonuses (staff/day/weather/jas/mab/etc all go in this function)
dmg = addBonuses(caster,spell,target,dmg);
--add in target adjustment
dmg = adjustForTarget(target,dmg);
--add in final adjustments
dmg = finalMagicAdjustments(caster,target,spell,dmg);
return dmg;
end; | gpl-3.0 |
waytim/darkstar | scripts/globals/items/loach_slop.lua | 18 | 1515 | -----------------------------------------
-- ID: 5669
-- Item: loach_slop
-- Food Effect: 3Hour,Group Food, All Races
-----------------------------------------
-- Accuracy % 7
-- Accuracy Cap 15
-- HP % 7
-- HP Cap 15
-- Evasion 3
-- (Did Not Add Group Food Effect)
-----------------------------------------
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,5669);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_FOOD_ACCP, 7);
target:addMod(MOD_FOOD_ACC_CAP, 15);
target:addMod(MOD_FOOD_HPP, 7);
target:addMod(MOD_FOOD_HP_CAP, 15);
target:addMod(MOD_EVA, 3);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_FOOD_ACCP, 7);
target:delMod(MOD_FOOD_ACC_CAP, 15);
target:delMod(MOD_FOOD_HPP, 7);
target:delMod(MOD_FOOD_HP_CAP, 15);
target:delMod(MOD_EVA, 3);
end;
| gpl-3.0 |
ffxinfinity/ffxinfinity | FFXI Server-Development/Build Files/scripts/globals/effects/shock.lua | 2 | 1139 | -----------------------------------
--
-- EFFECT_SHOCK
--
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_STR, -getElementalDebuffStatDownFromDOT(effect:getPower()));
end;
-----------------------------------
-- onEffectTick Action
-----------------------------------
function onEffectTick(target,effect)
if(target:hasStatusEffect(EFFECT_STONESKIN)) then
local skin = target:getMod(MOD_STONESKIN);
local dmg = effect:getPower();
if(skin >= dmg) then --absorb all damage
target:delMod(MOD_STONESKIN,effect:getPower());
else
target:delStatusEffect(EFFECT_STONESKIN);
target:delHP(dmg - skin);
target:wakeUp();
end
else
target:delHP(effect:getPower());
target:wakeUp();
end
end;
-----------------------------------
-- onEffectLose Action
-----------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_STR, -getElementalDebuffStatDownFromDOT(effect:getPower()));
end; | gpl-3.0 |
TheOnePharaoh/YGOPro-Custom-Cards | script/c160002427.lua | 2 | 2655 | --Bio-Dragun of Gust Vine
function c160002427.initial_effect(c)
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(160002427,0))
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_FLIP+EFFECT_TYPE_TRIGGER_O)
e1:SetProperty(EFFECT_FLAG_DELAY)
e1:SetCountLimit(1,160002427)
e1:SetTarget(c160002427.target)
e1:SetOperation(c160002427.operation)
c:RegisterEffect(e1)
--spsummon
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(160002427,1))
e2:SetCategory(CATEGORY_SPECIAL_SUMMON)
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e2:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DELAY)
e2:SetCode(EVENT_TO_GRAVE)
e2:SetCountLimit(1,160002427)
e2:SetCondition(c160002427.spcon)
e2:SetTarget(c160002427.sptg)
e2:SetOperation(c160002427.spop)
c:RegisterEffect(e2)
end
function c160002427.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsPlayerCanDiscardDeck(tp,5) end
end
function c160002427.filter(c)
return c:IsAbleToHand() and (c:IsSetCard(0x786d) and c:IsType(TYPE_SPELL+TYPE_TRAP))
end
function c160002427.operation(e,tp,eg,ep,ev,re,r,rp)
if not Duel.IsPlayerCanDiscardDeck(tp,5) then return end
Duel.ConfirmDecktop(tp,5)
local g=Duel.GetDecktopGroup(tp,5)
if g:GetCount()>0 then
Duel.DisableShuffleCheck()
if g:IsExists(c160002427.filter,1,nil) and Duel.SelectYesNo(tp,aux.Stringid(160002427,1)) then
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local sg=g:FilterSelect(tp,c160002427.filter,1,1,nil)
Duel.SendtoHand(sg,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,sg)
Duel.ShuffleHand(tp)
g:Sub(sg)
end
Duel.SendtoGrave(g,REASON_EFFECT+REASON_REVEAL)
end
end
function c160002427.spcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():IsReason(REASON_EFFECT)
end
function c160002427.filter2(c,e,tp)
return c:IsSetCard(0x786d) and c:IsLevelBelow(3) and not c:IsCode(160002427) and c:IsCanBeSpecialSummoned(e,0,tp,false,false,POS_FACEDOWN)
end
function c160002427.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c160002427.filter2(chkc,e,tp) end
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingTarget(c160002427.filter2,tp,LOCATION_GRAVE,0,1,nil,e,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectTarget(tp,c160002427.filter2,tp,LOCATION_GRAVE,0,1,1,nil,e,tp)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0)
end
function c160002427.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_FACEDOWN_DEFENSE)
Duel.ConfirmCards(1-tp,tc)
end
end | gpl-3.0 |
TheOnePharaoh/YGOPro-Custom-Cards | script/c59821140.lua | 2 | 8794 | --Samuel, The Darkness of Aetheria
function c59821140.initial_effect(c)
c:EnableReviveLimit()
--pendulum summon
aux.EnablePendulumAttribute(c)
--spsummon condition
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_SPSUMMON_CONDITION)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE)
c:RegisterEffect(e1)
--atk down
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD)
e2:SetRange(LOCATION_PZONE)
e2:SetCode(EFFECT_UPDATE_ATTACK)
e2:SetTargetRange(0,LOCATION_MZONE)
e2:SetValue(-200)
c:RegisterEffect(e2)
--place pcard
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(59821140,1))
e3:SetType(EFFECT_TYPE_IGNITION)
e3:SetRange(LOCATION_PZONE)
e3:SetCountLimit(1,59821140)
e3:SetCondition(c59821140.pencon)
e3:SetTarget(c59821140.pentg)
e3:SetOperation(c59821140.penop)
c:RegisterEffect(e3)
--destroy
local e4=Effect.CreateEffect(c)
e4:SetDescription(aux.Stringid(59821140,0))
e4:SetCategory(CATEGORY_DESTROY)
e4:SetType(EFFECT_TYPE_IGNITION)
e4:SetRange(LOCATION_PZONE)
e4:SetProperty(EFFECT_FLAG_CARD_TARGET)
e4:SetCountLimit(1,59821140)
e4:SetTarget(c59821140.destrotg)
e4:SetOperation(c59821140.destroop)
c:RegisterEffect(e4)
--indes
local e5=Effect.CreateEffect(c)
e5:SetType(EFFECT_TYPE_SINGLE)
e5:SetCode(EFFECT_INDESTRUCTABLE_EFFECT)
e5:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e5:SetRange(LOCATION_MZONE)
e5:SetValue(c59821140.tgvalue)
c:RegisterEffect(e5)
--immune spell
local e6=Effect.CreateEffect(c)
e6:SetType(EFFECT_TYPE_SINGLE)
e6:SetCode(EFFECT_IMMUNE_EFFECT)
e6:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e6:SetRange(LOCATION_MZONE)
e6:SetValue(c59821140.efilter)
c:RegisterEffect(e6)
--selfdes
local e7=Effect.CreateEffect(c)
e7:SetType(EFFECT_TYPE_SINGLE)
e7:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e7:SetRange(LOCATION_MZONE)
e7:SetCode(EFFECT_SELF_DESTROY)
e7:SetCondition(c59821140.sdcon)
c:RegisterEffect(e7)
--must attack
local e8=Effect.CreateEffect(c)
e8:SetType(EFFECT_TYPE_FIELD)
e8:SetCode(EFFECT_MUST_ATTACK)
e8:SetRange(LOCATION_MZONE)
e8:SetTargetRange(0,LOCATION_MZONE)
c:RegisterEffect(e8)
local e9=e8:Clone()
e9:SetCode(EFFECT_MUST_ATTACK_MONSTER)
c:RegisterEffect(e9)
local e10=Effect.CreateEffect(c)
e10:SetType(EFFECT_TYPE_SINGLE)
e10:SetCode(EFFECT_MUST_BE_ATTACKED)
e10:SetValue(1)
c:RegisterEffect(e10)
--atkup
local e11=Effect.CreateEffect(c)
e11:SetType(EFFECT_TYPE_SINGLE)
e11:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e11:SetCode(EFFECT_UPDATE_ATTACK)
e11:SetRange(LOCATION_MZONE)
e11:SetValue(c59821140.atkval)
c:RegisterEffect(e11)
--cannot attack
local e12=Effect.CreateEffect(c)
e12:SetType(EFFECT_TYPE_SINGLE)
e12:SetCode(EFFECT_CANNOT_ATTACK)
c:RegisterEffect(e12)
--damage
local e13=Effect.CreateEffect(c)
e13:SetCategory(CATEGORY_DAMAGE)
e13:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F)
e13:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_DELAY)
e13:SetRange(LOCATION_MZONE)
e13:SetCode(EVENT_PHASE+PHASE_END)
e13:SetCountLimit(1)
e13:SetCondition(c59821140.damcon)
e13:SetTarget(c59821140.damtg)
e13:SetOperation(c59821140.damop)
c:RegisterEffect(e13)
--to pzone
local e14=Effect.CreateEffect(c)
e14:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DELAY)
e14:SetCategory(CATEGORY_DESTROY)
e14:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e14:SetCode(EVENT_DESTROYED)
e14:SetCondition(c59821140.con)
e14:SetOperation(c59821140.op)
c:RegisterEffect(e14)
--cannot attack
local e15=Effect.CreateEffect(c)
e15:SetDescription(aux.Stringid(59821140,2))
e15:SetType(EFFECT_TYPE_QUICK_O)
e15:SetRange(LOCATION_MZONE)
e15:SetCode(EVENT_FREE_CHAIN)
e15:SetHintTiming(0,TIMING_MAIN_END)
e15:SetCountLimit(1,59821140)
e15:SetCondition(c59821140.negcon)
e15:SetCost(c59821140.negcost)
e15:SetOperation(c59821140.negop)
c:RegisterEffect(e15)
end
c59821140.daedra_tribution=59821107
function c59821140.damcon(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetTurnPlayer()~=tp and Duel.GetActivityCount(1-tp,ACTIVITY_ATTACK)==0
end
function c59821140.damtg(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 c59821140.damop(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
function c59821140.penfilter4(c)
return c:IsSetCard(0xa1a2)
end
function c59821140.tgvalue(e,re,rp)
return rp~=e:GetHandlerPlayer()
end
function c59821140.pencon(e,tp,eg,ep,ev,re,r,rp)
local seq=e:GetHandler():GetSequence()
return Duel.GetFieldCard(tp,LOCATION_SZONE,13-seq)==nil
end
function c59821140.pentg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c59821140.penfilter4,tp,LOCATION_GRAVE+LOCATION_EXTRA,0,1,nil) end
end
function c59821140.penop(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOFIELD)
local g=Duel.SelectMatchingCard(tp,c59821140.penfilter4,tp,LOCATION_GRAVE+LOCATION_EXTRA,0,1,1,nil)
if g:GetCount()>0 then
local tc=g:GetFirst()
Duel.MoveToField(tc,tp,tp,LOCATION_SZONE,POS_FACEUP,true)
end
end
function c59821140.destrofilter(c)
return c:IsFaceup() and c:IsSetCard(0xa1a2) and c:IsDestructable()
end
function c59821140.destrotg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return false end
if chk==0 then return Duel.IsExistingTarget(c59821140.destrofilter,tp,LOCATION_ONFIELD,0,1,e:GetHandler())
and Duel.IsExistingTarget(Card.IsDestructable,tp,0,LOCATION_ONFIELD,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY)
local g1=Duel.SelectTarget(tp,c59821140.destrofilter,tp,LOCATION_ONFIELD,0,1,1,e:GetHandler())
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY)
local g2=Duel.SelectTarget(tp,Card.IsDestructable,tp,0,LOCATION_ONFIELD,1,1,nil)
g1:Merge(g2)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g1,2,0,0)
end
function c59821140.destroop(e,tp,eg,ep,ev,re,r,rp)
if not e:GetHandler():IsRelateToEffect(e) then return end
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
function c59821140.efilter(e,te)
return e:GetHandlerPlayer()~=te:GetHandlerPlayer() and te:IsActiveType(TYPE_SPELL)
end
function c59821140.sdcon(e)
return e:GetHandler():IsPosition(POS_FACEUP_DEFENSE)
end
function c59821140.atkval(e,c)
return Duel.GetMatchingGroupCount(c59821140.atkfilter,c:GetControler(),LOCATION_EXTRA,0,nil)*1000
end
function c59821140.atkfilter(c)
return c:IsFaceup() and c:IsSetCard(0xa1a2)
end
function c59821140.penfilter1(c)
return c:IsDestructable() and c:GetSequence()==6
end
function c59821140.penfilter2(c)
return c:IsDestructable() and c:GetSequence()==7
end
function c59821140.con(e,tp,eg,ep,ev,re,r,rp)
local p1=Duel.GetFieldCard(tp,LOCATION_SZONE,6)
local p2=Duel.GetFieldCard(tp,LOCATION_SZONE,7)
if not p1 and not p2 then return false end
return (e:GetHandler():IsReason(REASON_EFFECT) or e:GetHandler():IsReason(REASON_BATTLE)) and
(p1 and p1:IsDestructable()) or (p2 and p2:IsDestructable()) and e:GetHandler():GetPreviousLocation()==LOCATION_MZONE
end
function c59821140.op(e,tp,eg,ep,ev,re,r,rp)
local p1=Duel.GetFieldCard(tp,LOCATION_SZONE,6)
local p2=Duel.GetFieldCard(tp,LOCATION_SZONE,7)
local g1=nil
local g2=nil
if p1 then
g1=Duel.GetMatchingGroup(c59821140.penfilter1,tp,LOCATION_SZONE,0,nil)
end
if p2 then
g2=Duel.GetMatchingGroup(c59821140.penfilter2,tp,LOCATION_SZONE,0,nil)
if g1 then
g1:Merge(g2)
else
g1=g2
end
end
if g1 and Duel.Destroy(g1,REASON_EFFECT)~=0 then
local c=e:GetHandler()
Duel.MoveToField(c,tp,tp,LOCATION_SZONE,POS_FACEUP,true)
end
end
function c59821140.negcon(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetTurnPlayer()~=tp and Duel.GetCurrentPhase()==PHASE_MAIN1
end
function c59821140.negcfil(c)
return c:IsFaceup() and c:IsType(TYPE_PENDULUM) and c:IsSetCard(0xa1a2) and c:IsAbleToRemoveAsCost()
end
function c59821140.negcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetFlagEffect(tp,59821140+1)==0 and Duel.IsExistingMatchingCard(c59821140.negcfil,tp,LOCATION_EXTRA,0,1,nil) end
Duel.RegisterFlagEffect(tp,59821140+1,RESET_PHASE+PHASE_END,0,1)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local g=Duel.SelectMatchingCard(tp,c59821140.negcfil,tp,LOCATION_EXTRA,0,1,1,nil)
Duel.Remove(g,POS_FACEUP,REASON_COST)
end
function c59821140.negop(e,tp,eg,ep,ev,re,r,rp)
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_CANNOT_ATTACK_ANNOUNCE)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e1:SetReset(RESET_PHASE+PHASE_END)
e1:SetTargetRange(0,1)
Duel.RegisterEffect(e1,tp)
end
| gpl-3.0 |
TheEggi/FTCCustom | extensions/Nightblade.lua | 1 | 2716 | -- Watch for FTC initialization
CALLBACK_MANAGER:RegisterCallback( "FTC_Ready" , function() InitializeNightblade() end )
-- Register the callback to fire whenever a spell is cast
function InitializeNightblade()
if ( FTC.Player.class == "Nightblade" ) then
-- Shadow Barrier
FTC.Nightblade = { ["stealth"] = GetUnitStealthState('player') }
EVENT_MANAGER:RegisterForEvent( "FTC" , EVENT_STEALTH_STATE_CHANGED , FTC.NightbladeStealth )
-- Refreshing Shadows
CALLBACK_MANAGER:RegisterCallback("FTC_SpellCast" , function( ability ) FTC.NightbladeRefreshing( ability ) end )
end
end
--[[
* Runs on the EVENT_STEALTH_STATE_CHANGED listener.
* Watches for changes in a Nightblade's stealth state to trigger Shadow Barrier
]]--
function FTC.NightbladeStealth( eventCode , unitTag , stealthState )
-- Are we coming out of stealth?
if ( ( FTC.Nightblade.stealth == STEALTH_STATE_HIDDEN or FTC.Nightblade.stealth == STEALTH_STATE_STEALTH or FTC.Nightblade.stealth == STEALTH_STATE_HIDDEN_ALMOST_DETECTED or FTC.Nightblade.stealth == STEALTH_STATE_STEALTH_ALMOST_DETECTED ) and ( stealthState == STEALTH_STATE_DETECTED or stealthState == STEALTH_STATE_NONE ) ) then
-- Trigger a buff
if ( FTC.init.Buffs ) then
local ms = GetGameTimeMilliseconds()
local newBuff = {
["name"] = "Shadow Barrier",
["begin"] = ms / 1000,
["ends"] = ( ms / 1000 ) + 4.6,
["debuff"] = false,
["stacks"] = 0,
["tag"] = 'player',
["icon"] = '/esoui/art/icons/ability_rogue_052.dds',
}
FTC.Buffs.Player["Shadow Barrier"] = newBuff
end
end
-- Save the previous stealthed state
FTC.Nightblade.stealth = stealthState
end
--[[
* Runs on FTC_SpellCast callback
* Triggers the Refreshing Shadows passive when a nightblade uses a Shadow ability
]]--
function FTC.NightbladeRefreshing( ability )
-- Bail if no ability is passed
if ( ability == nil ) then return end
-- Is it a
local shadows = { "Shadow Cloak", "Shadowy Disguise", "Dark Cloak", "Veiled Strike", "Surprise Attack", "Concealed Weapon", "Path of Darkness", "Twisting Path", "Refreshing Path", "Aspect of Terror", "Mass Hysteria", "Manifestation of Terror", "Summon Shade", "Dark Shades", "Shadow Image", "Consuming Darkness", "Bolstering Darkness", "Veil of Blades" }
for i = 1 , #shadows do
if ( shadows[i] == ability.name ) then
local ms = GetGameTimeMilliseconds()
local newBuff = {
["name"] = "Refreshing Shadows",
["begin"] = ms / 1000,
["ends"] = ( ms / 1000 ) + 6,
["debuff"] = false,
["stacks"] = 0,
["tag"] = 'player',
["icon"] = '/esoui/art/icons/ability_rogue_050.dds',
}
FTC.Buffs.Player["Refreshing Shadows"] = newBuff
break
end
end
end | apache-2.0 |
waytim/darkstar | scripts/globals/mobskills/Pinning_Shot.lua | 33 | 1044 | ---------------------------------------------
-- Pinning Shot
--
-- Description: Delivers a threefold ranged attack to targets in an area of effect. Additional effect: Bind
-- Type: Physical
-- Utsusemi/Blink absorb: 2-3 shadows
-- Range: Unknown
-- Notes: Used only by Medusa.
---------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
return 0;
end;
function onMobWeaponSkill(target, mob, skill)
local numhits = math.random(2, 3);
local accmod = 1;
local dmgmod = 1;
local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_RANGED,MOBPARAM_PIERCE,info.hitslanded);
local typeEffect = EFFECT_BIND;
MobPhysicalStatusEffectMove(mob, target, skill, typeEffect, 1, 0, 60);
target:delHP(dmg);
return dmg;
end;
| gpl-3.0 |
CaptainPRICE/wire | lua/entities/gmod_wire_egp/lib/init.lua | 18 | 1289 | EGP = {}
--------------------------------------------------------
-- Include all other files
--------------------------------------------------------
function EGP:Initialize()
local Folder = "entities/gmod_wire_egp/lib/egplib/"
local entries = file.Find( Folder .. "*.lua", "LUA")
for _, entry in ipairs( entries ) do
if (SERVER) then
AddCSLuaFile( Folder .. entry )
end
include( Folder .. entry )
end
end
EGP:Initialize()
local EGP = EGP
EGP.ConVars = {}
EGP.ConVars.MaxObjects = CreateConVar( "wire_egp_max_objects", 300, { FCVAR_NOTIFY, FCVAR_SERVER_CAN_EXECUTE, FCVAR_ARCHIVE } )
EGP.ConVars.MaxPerSec = CreateConVar( "wire_egp_max_bytes_per_sec", 10000, { FCVAR_NOTIFY, FCVAR_SERVER_CAN_EXECUTE, FCVAR_ARCHIVE } ) -- Keep between 2500-40000
EGP.ConVars.MaxVertices = CreateConVar( "wire_egp_max_poly_vertices", 1024, { FCVAR_NOTIFY, FCVAR_SERVER_CAN_EXECUTE, FCVAR_ARCHIVE } )
EGP.ConVars.AllowEmitter = CreateConVar( "wire_egp_allow_emitter", 1, { FCVAR_NOTIFY, FCVAR_SERVER_CAN_EXECUTE, FCVAR_ARCHIVE } )
EGP.ConVars.AllowHUD = CreateConVar( "wire_egp_allow_hud", 1, { FCVAR_NOTIFY, FCVAR_SERVER_CAN_EXECUTE, FCVAR_ARCHIVE } )
EGP.ConVars.AllowScreen = CreateConVar( "wire_egp_allow_screen", 1, { FCVAR_NOTIFY, FCVAR_SERVER_CAN_EXECUTE, FCVAR_ARCHIVE } )
| apache-2.0 |
ffxinfinity/ffxinfinity | FFXI Server-Development/Build Files/scripts/globals/items/hedgehog_pie.lua | 3 | 1831 | -----------------------------------------
-- ID: 5146
-- Item: hedgehog_pie
-- Food Effect: 180Min, All Races
-----------------------------------------
-- Health 55
-- Strength 6
-- Vitality 2
-- Intelligence -3
-- Mind 3
-- Magic Regen While Healing 2
-- Attack % 18
-- Attack Cap 90
-- Accuracy 5
-- Ranged ATT % 18
-- Ranged ATT Cap 90
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,10800,5146);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 55);
target:addMod(MOD_STR, 6);
target:addMod(MOD_VIT, 2);
target:addMod(MOD_INT, -3);
target:addMod(MOD_MND, 3);
target:addMod(MOD_MPHEAL, 2);
target:addMod(MOD_FOOD_ATTP, 18);
target:addMod(MOD_FOOD_ATT_CAP, 90);
target:addMod(MOD_ACC, 5);
target:addMod(MOD_FOOD_RATTP, 18);
target:addMod(MOD_FOOD_RATT_CAP, 90);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 55);
target:delMod(MOD_STR, 6);
target:delMod(MOD_VIT, 2);
target:delMod(MOD_INT, -3);
target:delMod(MOD_MND, 3);
target:delMod(MOD_MPHEAL, 2);
target:delMod(MOD_FOOD_ATTP, 18);
target:delMod(MOD_FOOD_ATT_CAP, 90);
target:delMod(MOD_ACC, 5);
target:delMod(MOD_FOOD_RATTP, 18);
target:delMod(MOD_FOOD_RATT_CAP, 90);
end;
| gpl-3.0 |
LuaDist2/prosody | plugins/mod_groups.lua | 3 | 3761 | -- Prosody IM
-- Copyright (C) 2008-2010 Matthew Wild
-- Copyright (C) 2008-2010 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local groups;
local members;
local groups_file;
local jid, datamanager = require "util.jid", require "util.datamanager";
local jid_prep = jid.prep;
local module_host = module:get_host();
function inject_roster_contacts(event)
local username, host= event.username, event.host;
--module:log("debug", "Injecting group members to roster");
local bare_jid = username.."@"..host;
if not members[bare_jid] and not members[false] then return; end -- Not a member of any groups
local roster = event.roster;
local function import_jids_to_roster(group_name)
for jid in pairs(groups[group_name]) do
-- Add them to roster
--module:log("debug", "processing jid %s in group %s", tostring(jid), tostring(group_name));
if jid ~= bare_jid then
if not roster[jid] then roster[jid] = {}; end
roster[jid].subscription = "both";
if groups[group_name][jid] then
roster[jid].name = groups[group_name][jid];
end
if not roster[jid].groups then
roster[jid].groups = { [group_name] = true };
end
roster[jid].groups[group_name] = true;
roster[jid].persist = false;
end
end
end
-- Find groups this JID is a member of
if members[bare_jid] then
for _, group_name in ipairs(members[bare_jid]) do
--module:log("debug", "Importing group %s", group_name);
import_jids_to_roster(group_name);
end
end
-- Import public groups
if members[false] then
for _, group_name in ipairs(members[false]) do
--module:log("debug", "Importing group %s", group_name);
import_jids_to_roster(group_name);
end
end
if roster[false] then
roster[false].version = true;
end
end
function remove_virtual_contacts(username, host, datastore, data)
if host == module_host and datastore == "roster" then
local new_roster = {};
for jid, contact in pairs(data) do
if contact.persist ~= false then
new_roster[jid] = contact;
end
end
if new_roster[false] then
new_roster[false].version = nil; -- Version is void
end
return username, host, datastore, new_roster;
end
return username, host, datastore, data;
end
function module.load()
groups_file = module:get_option_string("groups_file");
if not groups_file then return; end
module:hook("roster-load", inject_roster_contacts);
datamanager.add_callback(remove_virtual_contacts);
groups = { default = {} };
members = { };
local curr_group = "default";
for line in io.lines(groups_file) do
if line:match("^%s*%[.-%]%s*$") then
curr_group = line:match("^%s*%[(.-)%]%s*$");
if curr_group:match("^%+") then
curr_group = curr_group:gsub("^%+", "");
if not members[false] then
members[false] = {};
end
members[false][#members[false]+1] = curr_group; -- Is a public group
end
module:log("debug", "New group: %s", tostring(curr_group));
groups[curr_group] = groups[curr_group] or {};
else
-- Add JID
local entryjid, name = line:match("([^=]*)=?(.*)");
module:log("debug", "entryjid = '%s', name = '%s'", entryjid, name);
local jid;
jid = jid_prep(entryjid:match("%S+"));
if jid then
module:log("debug", "New member of %s: %s", tostring(curr_group), tostring(jid));
groups[curr_group][jid] = name or false;
members[jid] = members[jid] or {};
members[jid][#members[jid]+1] = curr_group;
end
end
end
module:log("info", "Groups loaded successfully");
end
function module.unload()
datamanager.remove_callback(remove_virtual_contacts);
end
-- Public for other modules to access
function group_contains(group_name, jid)
return groups[group_name][jid];
end
| mit |
dmccuskey/dmc-sockets | examples/dmc-sockets-basic/dmc_corona/lib/dmc_lua/lua_class.lua | 16 | 14025 | --====================================================================--
-- dmc_lua/lua_class.lua
--
-- Documentation: http://docs.davidmccuskey.com/
--====================================================================--
--[[
The MIT License (MIT)
Copyright (c) 2015 David McCuskey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
--]]
--====================================================================--
--== DMC Lua Library : Lua Objects
--====================================================================--
-- Semantic Versioning Specification: http://semver.org/
local VERSION = "0.1.0"
--====================================================================--
--== Imports
-- none
--====================================================================--
--== Setup, Constants
-- cache globals
local assert, type, rawget, rawset = assert, type, rawget, rawset
local getmetatable, setmetatable = getmetatable, setmetatable
local sformat = string.format
local tinsert = table.insert
local tremove = table.remove
-- table for copies from lua_utils
local Utils = {}
-- forward declare
local ClassBase
--====================================================================--
--== Class Support Functions
--== Start: copy from lua_utils ==--
-- extend()
-- Copy key/values from one table to another
-- Will deep copy any value from first table which is itself a table.
--
-- @param fromTable the table (object) from which to take key/value pairs
-- @param toTable the table (object) in which to copy key/value pairs
-- @return table the table (object) that received the copied items
--
function Utils.extend( fromTable, toTable )
if not fromTable or not toTable then
error( "table can't be nil" )
end
function _extend( fT, tT )
for k,v in pairs( fT ) do
if type( fT[ k ] ) == "table" and
type( tT[ k ] ) == "table" then
tT[ k ] = _extend( fT[ k ], tT[ k ] )
elseif type( fT[ k ] ) == "table" then
tT[ k ] = _extend( fT[ k ], {} )
else
tT[ k ] = v
end
end
return tT
end
return _extend( fromTable, toTable )
end
--== End: copy from lua_utils ==--
-- registerCtorName
-- add names for the constructor
--
local function registerCtorName( name, class )
class = class or ClassBase
--==--
assert( type( name ) == 'string', "ctor name should be string" )
assert( class.is_class, "Class is not is_class" )
class[ name ] = class.__ctor__
return class[ name ]
end
-- registerDtorName
-- add names for the destructor
--
local function registerDtorName( name, class )
class = class or ClassBase
--==--
assert( type( name ) == 'string', "dtor name should be string" )
assert( class.is_class, "Class is not is_class" )
class[ name ] = class.__dtor__
return class[ name ]
end
--[[
obj:superCall( 'string', ... )
obj:superCall( Class, 'string', ... )
--]]
-- superCall()
-- function to intelligently find methods in object hierarchy
--
local function superCall( self, ... )
local args = {...}
local arg1 = args[1]
assert( type(arg1)=='table' or type(arg1)=='string', "superCall arg not table or string" )
--==--
-- pick off arguments
local parent_lock, method, params
if type(arg1) == 'table' then
parent_lock = tremove( args, 1 )
method = tremove( args, 1 )
else
method = tremove( args, 1 )
end
params = args
local self_dmc_super = self.__dmc_super
local super_flag = ( self_dmc_super ~= nil )
local result = nil
-- finds method name in class hierarchy
-- returns found class or nil
-- @params classes list of Classes on which to look, table/list
-- @params name name of method to look for, string
-- @params lock Class object with which to constrain searching
--
local function findMethod( classes, name, lock )
if not classes then return end -- when using mixins, etc
local cls = nil
for _, class in ipairs( classes ) do
if not lock or class == lock then
if rawget( class, name ) then
cls = class
break
else
-- check parents for method
cls = findMethod( class.__parents, name )
if cls then break end
end
end
end
return cls
end
local c, s -- class, super
-- structure in which to save our place
-- in case superCall() is invoked again
--
if self_dmc_super == nil then
self.__dmc_super = {} -- a stack
self_dmc_super = self.__dmc_super
-- find out where we are in hierarchy
s = findMethod( { self.__class }, method )
tinsert( self_dmc_super, s )
end
-- pull Class from stack and search for method on Supers
-- look for method on supers
-- call method if found
--
c = self_dmc_super[ # self_dmc_super ]
-- TODO: when c==nil
-- if c==nil or type(c)~='table' then return end
s = findMethod( c.__parents, method, parent_lock )
if s then
tinsert( self_dmc_super, s )
result = s[method]( self, unpack( args ) )
tremove( self_dmc_super, # self_dmc_super )
end
-- this is the first iteration and last
-- so clean up callstack, etc
--
if super_flag == false then
parent_lock = nil
tremove( self_dmc_super, # self_dmc_super )
self.__dmc_super = nil
end
return result
end
-- initializeObject
-- this is the beginning of object initialization
-- either Class or Instance
-- this is what calls the parent constructors, eg new()
-- called from newClass(), __create__(), __call()
--
-- @params obj the object context
-- @params params table with :
-- set_isClass = true/false
-- data contains {...}
--
local function initializeObject( obj, params )
params = params or {}
--==--
assert( params.set_isClass ~= nil, "initializeObject requires paramter 'set_isClass'" )
local is_class = params.set_isClass
local args = params.data or {}
-- set Class/Instance flag
obj.__is_class = params.set_isClass
-- call Parent constructors, if any
-- do in reverse
--
local parents = obj.__parents
for i = #parents, 1, -1 do
local parent = parents[i]
assert( parent, "Lua Objects: parent is nil, check parent list" )
rawset( obj, '__parent_lock', parent )
if parent.__new__ then
parent.__new__( obj, unpack( args ) )
end
end
rawset( obj, '__parent_lock', nil )
return obj
end
-- newindexFunc()
-- override the normal Lua lookup functionality to allow
-- property setter functions
--
-- @param t object table
-- @param k key
-- @param v value
--
local function newindexFunc( t, k, v )
local o, f
-- check for key in setters table
o = rawget( t, '__setters' ) or {}
f = o[k]
if f then
-- found setter, so call it
f(t,v)
else
-- place key/value directly on object
rawset( t, k, v )
end
end
-- multiindexFunc()
-- override the normal Lua lookup functionality to allow
-- property getter functions
--
-- @param t object table
-- @param k key
--
local function multiindexFunc( t, k )
local o, val
--== do key lookup in different places on object
-- check for key in getters table
o = rawget( t, '__getters' ) or {}
if o[k] then return o[k](t) end
-- check for key directly on object
val = rawget( t, k )
if val ~= nil then return val end
-- check OO hierarchy
-- check Parent Lock else all of Parents
--
o = rawget( t, '__parent_lock' )
if o then
if o then val = o[k] end
if val ~= nil then return val end
else
local par = rawget( t, '__parents' )
for _, o in ipairs( par ) do
if o[k] ~= nil then
val = o[k]
break
end
end
if val ~= nil then return val end
end
return nil
end
-- blessObject()
-- create new object, setup with Lua OO aspects, dmc-style aspects
-- @params inheritance table of supers/parents (dmc-style objects)
-- @params params
-- params.object
-- params.set_isClass
--
local function blessObject( inheritance, params )
params = params or {}
params.object = params.object or {}
params.set_isClass = params.set_isClass == true and true or false
--==--
local o = params.object
local o_id = tostring(o)
local mt = {
__index = multiindexFunc,
__newindex = newindexFunc,
__tostring = function(obj)
return obj:__tostring__(o_id)
end,
__call = function( cls, ... )
return cls:__ctor__( ... )
end
}
setmetatable( o, mt )
-- add Class property, access via getters:supers()
o.__parents = inheritance
o.__is_dmc = true
-- create lookup tables - setters, getters
o.__setters = {}
o.__getters = {}
-- copy down all getters/setters of parents
-- do in reverse order, to match order of property lookup
for i = #inheritance, 1, -1 do
local cls = inheritance[i]
if cls.__getters then
o.__getters = Utils.extend( cls.__getters, o.__getters )
end
if cls.__setters then
o.__setters = Utils.extend( cls.__setters, o.__setters )
end
end
return o
end
local function newClass( inheritance, params )
inheritance = inheritance or {}
params = params or {}
params.set_isClass = true
params.name = params.name or "<unnamed class>"
--==--
assert( type( inheritance ) == 'table', "first parameter should be nil, a Class, or a list of Classes" )
-- wrap single-class into table list
-- testing for DMC-Style objects
-- TODO: see if we can test for other Class libs
--
if inheritance.is_class == true then
inheritance = { inheritance }
elseif ClassBase and #inheritance == 0 then
-- add default base Class
tinsert( inheritance, ClassBase )
end
local o = blessObject( inheritance, {} )
initializeObject( o, params )
-- add Class property, access via getters:class()
o.__class = o
-- add Class property, access via getters:NAME()
o.__name = params.name
return o
end
-- backward compatibility
--
local function inheritsFrom( baseClass, options, constructor )
baseClass = baseClass == nil and baseClass or { baseClass }
return newClass( baseClass, options )
end
--====================================================================--
--== Base Class
--====================================================================--
ClassBase = newClass( nil, { name="Class Class" } )
-- __ctor__ method
-- called by 'new()' and other registrations
--
function ClassBase:__ctor__( ... )
local params = {
data = {...},
set_isClass = false
}
--==--
local o = blessObject( { self.__class }, params )
initializeObject( o, params )
return o
end
-- __dtor__ method
-- called by 'destroy()' and other registrations
--
function ClassBase:__dtor__()
self:__destroy__()
end
function ClassBase:__new__( ... )
return self
end
function ClassBase:__tostring__( id )
return sformat( "%s (%s)", self.NAME, id )
end
function ClassBase:__destroy__()
end
function ClassBase.__getters:NAME()
return self.__name
end
function ClassBase.__getters:class()
return self.__class
end
function ClassBase.__getters:supers()
return self.__parents
end
function ClassBase.__getters:is_class()
return self.__is_class
end
-- deprecated
function ClassBase.__getters:is_intermediate()
return self.__is_class
end
function ClassBase.__getters:is_instance()
return not self.__is_class
end
function ClassBase.__getters:version()
return self.__version
end
function ClassBase:isa( the_class )
local isa = false
local cur_class = self.class
-- test self
if cur_class == the_class then
isa = true
-- test parents
else
local parents = self.__parents
for i=1, #parents do
local parent = parents[i]
if parent.isa then
isa = parent:isa( the_class )
end
if isa == true then break end
end
end
return isa
end
-- optimize()
-- move super class methods to object
--
function ClassBase:optimize()
function _optimize( obj, inheritance )
if not inheritance or #inheritance == 0 then return end
for i=#inheritance,1,-1 do
local parent = inheritance[i]
-- climb up the hierarchy
_optimize( obj, parent.__parents )
-- make local references to all functions
for k,v in pairs( parent ) do
if type( v ) == 'function' then
obj[ k ] = v
end
end
end
end
_optimize( self, { self.__class } )
end
-- deoptimize()
-- remove super class (optimized) methods from object
--
function ClassBase:deoptimize()
for k,v in pairs( self ) do
if type( v ) == 'function' then
self[ k ] = nil
end
end
end
-- Setup Class Properties (function references)
registerCtorName( 'new', ClassBase )
registerDtorName( 'destroy', ClassBase )
ClassBase.superCall = superCall
--====================================================================--
--== Lua Objects Exports
--====================================================================--
-- makeNewClassGlobal
-- modifies the global namespace with newClass()
-- add or remove
--
local function makeNewClassGlobal( is_global )
is_global = is_global~=nil and is_global or true
if _G.newClass ~= nil then
print( "WARNING: newClass exists in global namespace" )
elseif is_global == true then
_G.newClass = newClass
else
_G.newClass = nil
end
end
makeNewClassGlobal() -- start it off
return {
__version=VERSION,
__superCall=superCall, -- for testing
setNewClassGlobal=makeNewClassGlobal,
registerCtorName=registerCtorName,
registerDtorName=registerDtorName,
inheritsFrom=inheritsFrom, -- backwards compatibility
newClass=newClass,
Class=ClassBase
}
| mit |
waytim/darkstar | scripts/globals/items/m&p_doner_kabob.lua | 18 | 1159 | -----------------------------------------
-- ID: 5717
-- Item: M&P Doner Kabob
-- Food Effect: 5Min, All Races
-----------------------------------------
-- HP 5%
-- MP 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,300,5717);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HPP, 5);
target:addMod(MOD_MPP, 5);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HPP, 5);
target:delMod(MOD_MPP, 5);
end;
| gpl-3.0 |
ffxinfinity/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Port_Windurst/npcs/Kuroido-Moido.lua | 3 | 3324 | -----------------------------------
-- Area: Port Windurst
-- NPC: Kuriodo-Moido
-- Involved In Quest: Making Amends, Wonder Wands
-- Starts and Finishes: Making Amens!
-- Working 100%
-----------------------------------
package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/zones/Port_Windurst/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
MakingAmends = player:getQuestStatus(WINDURST,MAKING_AMENDS); --First quest in series
MakingAmens = player:getQuestStatus(WINDURST,MAKING_AMENS); --Second quest in series
WonderWands = player:getQuestStatus(WINDURST,WONDER_WANDS); --Third and final quest in series
pfame = player:getFameLevel(WINDURST);
needToZone = player:needToZone();
BrokenWand = player:hasKeyItem(128);
if (MakingAmends == QUEST_ACCEPTED) then -- MAKING AMENDS: During Quest
player:startEvent(0x0114);
elseif (MakingAmends == QUEST_COMPLETED and MakingAmens ~= QUEST_COMPLETED and WonderWands ~= QUEST_COMPLETED and needToZone) then -- MAKING AMENDS: After Quest
player:startEvent(0x0117);
elseif (MakingAmends == QUEST_COMPLETED and MakingAmens == QUEST_AVAILABLE) then
if (pfame >=4 and not needToZone) then
player:startEvent(0x0118); -- Start Making Amens! if prerequisites are met
else
player:startEvent(0x0117); -- MAKING AMENDS: After Quest
end
elseif (MakingAmens == QUEST_ACCEPTED and not BrokenWand) then -- Reminder for Making Amens!
player:startEvent(0x011b);
elseif (MakingAmens == QUEST_ACCEPTED and BrokenWand) then -- Complete Making Amens!
player:startEvent(0x011c,GIL_RATE*6000);
elseif (MakingAmens == QUEST_COMPLETED) then
if (WonderWands == QUEST_ACCEPTED) then -- During Wonder Wands dialogue
player:startEvent(0x0105);
elseif (WonderWands == QUEST_COMPLETED) then -- Post Wonder Wands dialogue
player:startEvent(0x010a);
else
player:startEvent(0x011e,0,937); -- Post Making Amens! dialogue (before Wonder Wands)
end
else
rand = math.random(1,2);
if (rand == 1) then
player:startEvent(0x00e1); -- Standard Conversation
else
player:startEvent(0x00e2); -- Standard Conversation
end
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 == 0x0118) then
player:addQuest(WINDURST,MAKING_AMENS);
elseif (csid == 0x011c) then
player:needToZone(true);
player:delKeyItem(BROKEN_WAND);
player:addTitle(HAKKURURINKURUS_BENEFACTOR);
player:addGil(GIL_RATE*6000);
player:messageSpecial(GIL_OBTAINED,GIL_RATE*6000);
player:addFame(WINDURST,WIN_FAME*150);
player:completeQuest(WINDURST,MAKING_AMENS);
end
end;
| gpl-3.0 |
gfgtdf/wesnoth-old | data/lua/feeding.lua | 8 | 1383 |
local _ = wesnoth.textdomain 'wesnoth-help'
local T = wml.tag
local on_event = wesnoth.require("on_event")
-- The feeding event code
on_event("die", function()
local ec = wesnoth.current.event_context
if not ec.x1 or not ec.y1 or not ec.x2 or not ec.y2 then
return
end
local u_killer = wesnoth.units.get(ec.x2, ec.y2)
local u_victim = wesnoth.units.get(ec.x1, ec.y1)
if not u_killer or not u_killer:matches { ability = "feeding" } then
return
end
if not u_victim or u_victim:matches { status = "unplagueable" } then
return
end
local u_killer_cfg = u_killer.__cfg
for i,v in ipairs(wml.get_child(u_killer_cfg, "modifications"))do
if v[1] == "object" and v[2].feeding == true then
local effect = wml.get_child(v[2], "effect")
effect.increase_total = effect.increase_total + 1
u_killer_cfg.max_hitpoints = u_killer_cfg.max_hitpoints + 1
u_killer_cfg.hitpoints = u_killer_cfg.hitpoints + 1
wesnoth.units.to_map(u_killer_cfg)
wesnoth.interface.float_label(ec.x2, ec.y2, _ "+1 max HP", "0,255,0")
return
end
end
-- reaching this point means that the unit didn't have the feedng object yet.
u_killer:add_modification("object", {
feeding = true,
T.effect {
apply_to = "hitpoints",
increase_total = 1,
},
})
u_killer.hitpoints = u_killer.hitpoints + 1
wesnoth.interface.float_label(ec.x2, ec.y2, _ "+1 max HP", "0,255,0")
end)
| gpl-2.0 |
waytim/darkstar | scripts/zones/Jugner_Forest/npcs/Pure_Heart_IM.lua | 13 | 3323 | -----------------------------------
-- Area: Jugner Forest
-- NPC: Pure Heart, I.M.
-- Type: Border Conquest Guards
-- @pos 570.732 -2.637 553.508 104
-----------------------------------
package.loaded["scripts/zones/Jugner_Forest/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/conquest");
require("scripts/zones/Jugner_Forest/TextIDs");
local guardnation = BASTOK; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno
local guardtype = 4; -- 1: city, 2: foreign, 3: outpost, 4: border
local region = NORVALLEN;
local csid = 0x7ff8;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
tradeConquestGuard(player,npc,trade,guardnation,guardtype);
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then
if (supplyRunFresh(player) == 1) then
player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies !
else
player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use."
player:delKeyItem(getSupplyKey(region));
player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region));
player:setVar("supplyQuest_region",0);
end
else
local arg1 = getArg1(guardnation, player) - 1;
if (arg1 >= 1792) then -- foreign, non-allied
player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0);
else -- citizen or allied
player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
if (option == 1) then
local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600;
player:delStatusEffect(EFFECT_SIGIL);
player:delStatusEffect(EFFECT_SANCTION);
player:delStatusEffect(EFFECT_SIGNET);
player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet
elseif (option == 2) then
player:delKeyItem(getSupplyKey(region));
player:addCP(supplyReward[region + 1])
player:messageSpecial(CONQUEST); -- "You've earned conquest points!"
if (hasOutpost(player, region+5) == 0) then
local supply_quests = 2^(region+5);
player:addNationTeleport(guardnation,supply_quests);
player:setVar("supplyQuest_region",0);
end
elseif (option == 4) then
if (player:delGil(giltosetHP(guardnation,player))) then
player:setHomePoint();
player:messageSpecial(CONQUEST + 94); -- "Your home point has been set."
else
player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here."
end
end
end; | gpl-3.0 |
GPUOpen-LibrariesAndSDKs/SilhouetteTessellation11 | amd_sdk/premake/premake5_minimal.lua | 8 | 1336 | dofile ("../../premake/amd_premake_util.lua")
workspace "AMD_SDK_Minimal"
configurations { "Debug", "Release" }
platforms { "x64" }
location "../build"
filename ("AMD_SDK_Minimal" .. _AMD_VS_SUFFIX)
startproject "AMD_SDK_Minimal"
filter "platforms:x64"
system "Windows"
architecture "x64"
project "AMD_SDK_Minimal"
kind "StaticLib"
language "C++"
location "../build"
filename ("AMD_SDK_Minimal" .. _AMD_VS_SUFFIX)
uuid "EBB939DC-98E4-49DF-B1F1-D2E80A11F60A"
targetdir "../lib"
objdir "../build/%{_AMD_SAMPLE_DIR_LAYOUT_MINIMAL}"
warnings "Extra"
floatingpoint "Fast"
-- Specify WindowsTargetPlatformVersion here for VS2015
windowstarget (_AMD_WIN_SDK_VERSION)
files { "../inc/**.h", "../src/**.h", "../src/**.cpp", "../src/**.hlsl" }
defines { "AMD_SDK_MINIMAL" }
filter "configurations:Debug"
defines { "WIN32", "_DEBUG", "DEBUG", "PROFILE", "_WINDOWS", "_LIB", "_WIN32_WINNT=0x0601" }
flags { "Symbols", "FatalWarnings", "Unicode" }
targetsuffix ("_Debug" .. _AMD_VS_SUFFIX)
filter "configurations:Release"
defines { "WIN32", "NDEBUG", "_WINDOWS", "_LIB", "_WIN32_WINNT=0x0601" }
flags { "LinkTimeOptimization", "Symbols", "FatalWarnings", "Unicode" }
targetsuffix ("_Release" .. _AMD_VS_SUFFIX)
optimize "On"
| mit |
ffxinfinity/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Upper_Jeuno/npcs/Ajithaam.lua | 2 | 4071 | -----------------------------------
-- Area: Upper Jeuno
-- NPC: Ajithaam
-- @zone 244
-- @pos -82 0 160 244
-----------------------------------
package.loaded["scripts/zones/Upper_Jeuno/TextIDs"] = nil;
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/globals/missions");
require("scripts/globals/keyitems");
require("scripts/zones/Upper_Jeuno/TextIDs");
-----------------------------------
--[[
Bitmask Designations:
Ru'Lude Gardens (South to North)
00001 (H-9) Albiona (near the downstairs fountain and embassies)
00002 (G-8) Crooked Arrow (by the steps leading to the Auction House)
00004 (H-7) Muhoho (upstairs on the palace balcony)
00008 (G-7) Adolie (in the palace Guard Post)
00010 (I-6) Yavoraile (in the palace Dining Hall)
Upper Jeuno (North to South)
00020 (G-7) Sibila-Mobla (wanders outside M&P's Market)
00040 (G-8) Shiroro (in the house with Nekha Shachaba outside)
00080 (G-8) Luto Mewrilah (north-west of the Temple of the Goddess)
00100 (H-9) Renik (Just east of the Temple of the Goddess)
00200 (H-9) Hinda (inside the Temple of the Goddess, she is the first person on the left as you enter)
Lower Jeuno (North to South)
00400 (J-7) Sutarara (Neptune's Spire Inn, 2nd door on the left, outside of the Tenshodo)
00800 (I-7) Saprut (top of the stairs above AH)
01000 (H-9) Bluffnix (Gobbiebag quest NPC, in Muckvix's Junk Shop)
02000 (H-10) Naruru (Merchant's House on the middle level above Muckvix's Junk Shop)
04000 (G-10) Gurdern (across from the Chocobo Stables)
Port Jeuno (West to East)
08000 (G-8) Red Ghost (pacing back and forth between Bastok & San d'Oria Air Travel Agencies)
10000 (H-8) Karl (Show all three kids the badge)
20000 (H-8) Shami (BCNM Orb NPC)
40000 (I-8) Rinzei (west of the Windurst Airship Agency, next to Sagheera)
80000 (I-8) Sagheera (west of the Windurst Airship Agency)
]]--
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (trade:getGil() == 300 and trade:getItemCount() == 1 and player:getQuestStatus(JEUNO,LURE_OF_THE_WILDCAT_JEUNO) == QUEST_COMPLETED and
player:hasKeyItem(BOARDING_PERMIT) == true) then -- and player:getMissionStatus(TOAU,PRESIDENT_SALAHEEM) == 2) then
-- Needs a check for at least traded an invitation card to Naja Salaheem
player:startEvent(10177);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local LureJeuno = player:getQuestStatus(JEUNO,LURE_OF_THE_WILDCAT_JEUNO);
local WildcatJeuno = player:getVar("WildcatJeuno");
if (LureJeuno ~= 2 and ENABLE_TOAU == 1) then
if (LureJeuno == 0) then
player:startEvent(10088);
else
if (WildcatJeuno == 0) then
player:startEvent(10089);
elseif (player:isMaskFull(WildcatJeuno,20) == true) then
player:startEvent(10091);
else
player:startEvent(10090);
end
end
elseif(player:getCurrentMission(TOAU) >= 2)then
player:startEvent(10176);
else
player:startEvent(10092);
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 == 10088) then
player:addQuest(JEUNO,LURE_OF_THE_WILDCAT_JEUNO);
player:setVar("WildcatJeuno",0);
player:addKeyItem(WHITE_SENTINEL_BADGE);
elseif(csid == 10091) then
player:completeQuest(JEUNO,LURE_OF_THE_WILDCAT_JEUNO);
player:addFame(JEUNO,150);
player:setVar("WildcatJeuno",0);
player:delKeyItem(WHITE_SENTINEL_BADGE);
player:addKeyItem(WHITE_INVITATION_CARD);
player:messageSpecial(KEYITEM_OBTAINED,WHITE_INVITATION_CARD);
elseif(csid == 10177)then
player:setPos(27.608, -6.000, -124.462, 192, 0x32); -- Aht Urhgan Whitegate (Pos in not correct needs verify).
end
end;
| gpl-3.0 |
neuralartgui/neuralartgui | _CombinedContainer/data/neuralart/main.lua | 1 | 8681 | --
-- An implementation of the method described in 'A Neural Algorithm of Artistic
-- Style' by Leon Gatys, Alexander Ecker, and Matthias Bethge.
--
-- http://arxiv.org/abs/1508.06576
--
require 'torch'
require 'nn'
require 'image'
require 'paths'
require 'optim'
local pl = require('pl.import_into')()
local printf = pl.utils.printf
local basepath = '/neuralart'
local cmd = torch.CmdLine()
cmd:text()
cmd:text('A Neural Algorithm of Artistic Style')
cmd:text()
cmd:text('Options:')
cmd:option('--model', 'vgg', '{inception, vgg}. Model to use.')
cmd:option('--style', 'none', 'Path to style image')
cmd:option('--content', 'none', 'Path to content image')
cmd:option('--style_factor', 2e9, 'Trade-off factor between style and content')
cmd:option('--num_iters', 500, 'Number of iterations')
cmd:option('--size', 500, 'Length of image long edge (0 to use original content size)')
cmd:option('--display_interval', 0, 'Iterations between image displays (0 to suppress display)')
cmd:option('--smoothness', 0, 'Total variation norm regularization strength (higher for smoother output)')
cmd:option('--init', 'image', '{image, random}. Initialization mode for optimized image.')
cmd:option('--backend', 'cunn', '{cunn, cudnn}. Neural network CUDA backend.')
cmd:option('--optimizer', 'lbfgs', '{sgd, lbfgs}. Optimization algorithm.')
cmd:option('--cpu', false, 'Optimize on CPU (only with VGG network).')
cmd:option('--output_dir', 'frames', 'Output directory to save to.' )
opt = cmd:parse(arg)
if opt.size <= 0 then
opt.size = nil
end
if not opt.cpu then
require 'cutorch'
require 'cunn'
end
paths.dofile(basepath ..'/models/util.lua')
paths.dofile(basepath ..'/models/vgg19.lua')
paths.dofile(basepath ..'/models/inception.lua')
paths.dofile(basepath ..'/images.lua')
paths.dofile(basepath ..'/costs.lua')
-- check for model files
local inception_path = basepath .. '/models/inception_caffe.th'
local vgg_path = basepath .. '/models/vgg_normalized.th'
if opt.model == 'inception' then
if not paths.filep(inception_path) then
print('ERROR: could not find Inception model weights at ' .. inception_path)
print('run download_models.sh to download model weights')
error('')
end
if opt.cpu then
error('CPU optimization only works with VGG model')
end
elseif opt.model == 'vgg' then
if not paths.filep(vgg_path) then
print('ERROR: could not find VGG model weights at ' .. vgg_path)
print('run download_models.sh to download model weights')
error('')
end
else
error('invalid model: ' .. opt.model)
end
-- load model
local model, style_weights, content_weights
if opt.model == 'inception' then
style_weights = {
['conv1/7x7_s2'] = 1,
['conv2/3x3'] = 1,
['inception_3a'] = 1,
['inception_3b'] = 1,
['inception_4a'] = 1,
['inception_4b'] = 1,
['inception_4c'] = 1,
['inception_4d'] = 1,
['inception_4e'] = 1,
}
content_weights = {
['inception_3a'] = 1,
['inception_4a'] = 1,
}
model = create_inception(inception_path, opt.backend)
elseif opt.model == 'vgg' then
style_weights = {
['conv1_1'] = 1,
['conv2_1'] = 1,
['conv3_1'] = 1,
['conv4_1'] = 1,
['conv5_1'] = 1,
}
content_weights = {
['conv4_2'] = 1,
}
model = create_vgg(vgg_path, opt.backend)
end
-- run on GPU
if opt.cpu then
model:float()
else
model:cuda()
end
collectgarbage()
-- compute normalization factor
local style_weight_sum = 0
local content_weight_sum = 0
for k, v in pairs(style_weights) do
style_weight_sum = style_weight_sum + v
end
for k, v in pairs(content_weights) do
content_weight_sum = content_weight_sum + v
end
print('load content')
io.flush()
-- load content image
local img = preprocess(image.load(opt.content), opt.size)
if not opt.cpu then
img = img:cuda()
end
print('load content forward')
print('*possibleerror:137')
io.flush()
model:forward(img)
print('load content collect activations')
io.flush()
local img_activations, _ = collect_activations(model, content_weights, {})
print('load style')
io.flush()
-- load style image
local art = preprocess(
image.load(opt.style), math.max(img:size(3), img:size(4))
)
if not opt.cpu then
art = art:cuda()
end
print('load style forward')
print('*possibleerror:137')
io.flush()
model:forward(art)
local _, art_grams = collect_activations(model, {}, style_weights)
art = nil
collectgarbage()
function opfunc(input)
-- forward prop
model:forward(input)
-- backpropagate
local loss = 0
local grad = opt.cpu and torch.FloatTensor() or torch.CudaTensor()
grad:resize(model.output:size()):zero()
for i = #model.modules, 1, -1 do
local module_input = (i == 1) and input or model.modules[i - 1].output
local module = model.modules[i]
local name = module._name
-- add content gradient
if name and content_weights[name] then
local c_loss, c_grad = content_grad(module.output, img_activations[name])
local w = content_weights[name] / content_weight_sum
--printf('[content]\t%s\t%.2e\n', name, w * c_loss)
loss = loss + w * c_loss
grad:add(w, c_grad)
end
-- add style gradient
if name and style_weights[name] then
local s_loss, s_grad = style_grad(module.output, art_grams[name])
local w = opt.style_factor * style_weights[name] / style_weight_sum
--printf('[style]\t%s\t%.2e\n', name, w * s_loss)
loss = loss + w * s_loss
grad:add(w, s_grad)
end
grad = module:backward(module_input, grad)
end
-- total variation regularization for denoising
grad:add(total_var_grad(input):mul(opt.smoothness))
return loss, grad:view(-1)
end
print('prepare start image to optimize')
io.flush()
-- image to optimize
local input
if opt.init == 'image' then
input = img
elseif opt.init == 'random' then
input = preprocess(
torch.randn(3, img:size(3), img:size(4)):mul(0.1):add(0.5):clamp(0, 1)
)
if not opt.cpu then
input = input:cuda()
end
else
error('unrecognized initialization option: ' .. opt.init)
end
print('deprocess input')
io.flush()
local timer = torch.Timer()
local output = depreprocess(input):double()
if opt.display_interval > 0 then
-- image.display(output)
end
-- make directory to save intermediate frames
local frames_dir = opt.output_dir
if not paths.dirp(frames_dir) then
paths.mkdir(frames_dir)
end
-- image.save(paths.concat(frames_dir, '0000.jpg'), output)
-- gui Output
-- print("*savedimage:0000.jpg")
-- print("*stepcomplete:1")
-- set optimizer options
local optim_state
if opt.optimizer == 'sgd' then
optim_state = {
momentum = 0.9,
dampening = 0.0,
}
if opt.model == 'inception' then
optim_state.learningRate = 5e-2
else
optim_state.learningRate = 1e-3
end
elseif opt.optimizer == 'lbfgs' then
optim_state = {
maxIter = 3,
learningRate = 1,
}
else
error('unknown optimizer: ' .. opt.optimizer)
end
print('start optimize')
io.flush()
-- GUI Output
print('*totalprogress:0.0')
io.flush()
-- optimize
for i = 1, opt.num_iters do
collectgarbage()
local progress = ((i * 100)/opt.num_iters)
print(string.format('*stepstarted:%d',i))
io.flush()
local _, loss = optim[opt.optimizer](opfunc, input, optim_state)
loss = loss[1]
-- anneal learning rate
if opt.optimizer == 'sgd' and i % 100 == 0 then
optim_state.learningRate = 0.75 * optim_state.learningRate
end
if i % 10 == 0 then
printf('iter %5d\tloss %8.2e\tlr %8.2e\ttime %4.1f\n',
i, loss, optim_state.learningRate, timer:time().real)
end
print('*possibleerror:137')
io.flush()
-- if i <= 20 or i % 5 == 0 then
output = depreprocess(input):double()
if opt.display_interval > 0 and i % opt.display_interval == 0 then
-- image.display(output)
end
image.save(paths.concat(frames_dir, string.format('%04d.jpg',i)), output)
print(string.format('*totalprogress:%.2f',progress))
print(string.format('*savedimage:%s',paths.concat(frames_dir, string.format('%04d.jpg',i))))
print(string.format('*stepcomplete:%d',i))
io.flush()
-- end
end
print("*allcomplete")
output = depreprocess(input)
if opt.display_interval > 0 then
-- image.display(output)
end
| mit |
ffxinfinity/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Aht_Urhgan_Whitegate/npcs/Yahsra.lua | 2 | 1058 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Yahsra
-- Type: Assault Mission Giver
-- @zone: 50
-- @pos: 120.967 0.161 -44.002
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0117);
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 |
waytim/darkstar | scripts/zones/Abyssea-Attohwa/npcs/qm19.lua | 17 | 1523 | -----------------------------------
-- Zone: Abyssea-Attohwa
-- NPC: ???
-- Spawns: Ulhuadshi
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/keyitems");
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
--[[
if (GetMobAction(17658276) == ACTION_NONE) then -- NM not already spawned from this
if (player:hasKeyItem(MUCID_WORM_SEGMENT) and player:hasKeyItem(SHRIVELED_HECTEYES_STALK)) then
player:startEvent(1022, MUCID_WORM_SEGMENT, SHRIVELED_HECTEYES_STALK); -- Ask if player wants to use KIs
else
player:startEvent(1023, MUCID_WORM_SEGMENT, SHRIVELED_HECTEYES_STALK); -- Do not ask, because player is missing at least 1.
end
end
]]
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID2: %u",csid);
-- printf("RESULT2: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 1022 and option == 1) then
SpawnMob(17658276):updateClaim(player); -- Spawn NM, Despawn after inactive for 5 minutes (pt has to reclaim within 5 of a wipe)
player:delKeyItem(MUCID_WORM_SEGMENT);
player:delKeyItem(SHRIVELED_HECTEYES_STALK);
end
end; | gpl-3.0 |
waytim/darkstar | scripts/zones/Apollyon/bcnms/NW_Apollyon.lua | 35 | 1116 | -----------------------------------
-- Area: Appolyon
-- Name:
-----------------------------------
require("scripts/globals/limbus");
require("scripts/globals/keyitems");
-- After registering the BCNM via bcnmRegister(bcnmid)
function onBcnmRegister(player,instance)
SetServerVariable("[NW_Apollyon]UniqueID",GenerateLimbusKey());
HideArmouryCrates(GetInstanceRegion(1290),APPOLLYON_NW_SW);
end;
-- Physically entering the BCNM via bcnmEnter(bcnmid)
function onBcnmEnter(player,instance)
player:setVar("limbusbitmap",0);
player:setVar("characterLimbusKey",GetServerVariable("[NW_Apollyon]UniqueID"));
player:setVar("LimbusID",1290);
player:delKeyItem(COSMOCLEANSE);
player:delKeyItem(RED_CARD);
end;
-- Leaving the Dynamis by every mean possible, given by the LeaveCode
-- 3=Disconnected or warped out (if dyna is empty: launch 4 after 3)
-- 4=Finish
function onBcnmLeave(player,instance,leavecode)
--print("leave code "..leavecode);
if (leavecode == 4) then
player:setPos(-668,0.1,-666);
ResetPlayerLimbusVariable(player)
end
end; | gpl-3.0 |
ffxinfinity/ffxinfinity | FFXI Server-Development/Build Files/scripts/globals/items/porcupine_pie.lua | 3 | 1811 | -----------------------------------------
-- ID: 5156
-- Item: porcupine_pie
-- Food Effect: 30Min, All Races
-----------------------------------------
-- HP 55
-- Strength 6
-- Vitality 2
-- Intelligence -3
-- Mind 3
-- MP recovered while healing 2
-- Accuracy 5
-- Attack % 18 (cap 95)
-- Ranged Attack % 18 (cap 95)
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,14400,5156);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 55);
target:addMod(MOD_STR, 6);
target:addMod(MOD_VIT, 2);
target:addMod(MOD_INT, -3);
target:addMod(MOD_MND, 3);
target:addMod(MOD_MPHEAL, 2);
target:addMod(MOD_ACC, 5);
target:addMod(MOD_FOOD_ATTP, 18);
target:addMod(MOD_FOOD_ATT_CAP, 95);
target:addMod(MOD_FOOD_RATTP, 18);
target:addMod(MOD_FOOD_RATT_CAP, 95);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 55);
target:delMod(MOD_STR, 6);
target:delMod(MOD_VIT, 2);
target:delMod(MOD_INT, -3);
target:delMod(MOD_MND, 3);
target:delMod(MOD_MPHEAL, 2);
target:delMod(MOD_ACC, 5);
target:delMod(MOD_FOOD_ATTP, 18);
target:delMod(MOD_FOOD_ATT_CAP, 95);
target:delMod(MOD_FOOD_RATTP, 18);
target:delMod(MOD_FOOD_RATT_CAP, 95);
end;
| gpl-3.0 |
TheOnePharaoh/YGOPro-Custom-Cards | script/c77662914.lua | 2 | 8994 | --Vocalist Alternation Hakaine Maiko
function c77662914.initial_effect(c)
--xyz summon
aux.AddXyzProcedure(c,aux.FilterBoolFunction(Card.IsRace,RACE_MACHINE),7,2)
c:EnableReviveLimit()
--pendulum summon
aux.EnablePendulumAttribute(c)
--xyz summon success
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(77662914,0))
e1:SetCategory(CATEGORY_DRAW)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e1:SetCode(EVENT_SPSUMMON_SUCCESS)
e1:SetCondition(c77662914.drcon)
e1:SetTarget(c77662914.drtarg)
e1:SetOperation(c77662914.drop)
c:RegisterEffect(e1)
--spsummon
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(77662914,1))
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetRange(LOCATION_MZONE)
e2:SetCountLimit(1)
e2:SetCondition(c77662914.spcon)
e2:SetTarget(c77662914.sptg)
e2:SetOperation(c77662914.spop)
c:RegisterEffect(e2)
--negate
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(77662914,2))
e3:SetCategory(CATEGORY_NEGATE+CATEGORY_DESTROY)
e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_QUICK_O)
e3:SetCode(EVENT_CHAINING)
e3:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DAMAGE_CAL)
e3:SetRange(LOCATION_MZONE)
e3:SetCondition(c77662914.discon)
e3:SetCost(c77662914.discost)
e3:SetTarget(c77662914.distg)
e3:SetOperation(c77662914.disop)
c:RegisterEffect(e3)
--splimit
local e4=Effect.CreateEffect(c)
e4:SetType(EFFECT_TYPE_FIELD)
e4:SetRange(LOCATION_PZONE)
e4:SetCode(EFFECT_CANNOT_SPECIAL_SUMMON)
e4:SetProperty(EFFECT_FLAG_PLAYER_TARGET+EFFECT_FLAG_CANNOT_DISABLE)
e4:SetTargetRange(1,0)
e4:SetTarget(c77662914.splimit)
e4:SetCondition(c77662914.splimcon)
c:RegisterEffect(e4)
--to pzone
local e5=Effect.CreateEffect(c)
e5:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DELAY)
e5:SetCategory(CATEGORY_DESTROY)
e5:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e5:SetCode(EVENT_DESTROYED)
e5:SetCondition(c77662914.con)
e5:SetOperation(c77662914.op)
c:RegisterEffect(e5)
--scale
local e6=Effect.CreateEffect(c)
e6:SetType(EFFECT_TYPE_SINGLE)
e6:SetCode(EFFECT_CHANGE_LSCALE)
e6:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e6:SetRange(LOCATION_PZONE)
e6:SetCondition(c77662914.sccon)
e6:SetValue(3)
c:RegisterEffect(e6)
local e7=e6:Clone()
e7:SetCode(EFFECT_CHANGE_RSCALE)
c:RegisterEffect(e7)
--lv change
local e8=Effect.CreateEffect(c)
e8:SetDescription(aux.Stringid(77662914,3))
e8:SetType(EFFECT_TYPE_IGNITION)
e8:SetCountLimit(1)
e8:SetRange(LOCATION_PZONE)
e8:SetTarget(c77662914.lvtg)
e8:SetOperation(c77662914.lvop)
c:RegisterEffect(e8)
end
function c77662914.drcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():GetSummonType()==SUMMON_TYPE_XYZ
end
function c77662914.drtarg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsPlayerCanDraw(tp,1) end
Duel.SetTargetPlayer(tp)
Duel.SetTargetParam(1)
Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,1)
end
function c77662914.drop(e,tp,eg,ep,ev,re,r,rp)
local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM)
Duel.Draw(p,d,REASON_EFFECT)
end
function c77662914.spcon(e,tp,eg,ep,ev,re,r,rp)
local ct1=Duel.GetFieldGroupCount(tp,LOCATION_ONFIELD,0)
local ct2=Duel.GetFieldGroupCount(tp,0,LOCATION_ONFIELD)
if ct1>=ct2 then return false end
local ph=Duel.GetCurrentPhase()
if Duel.GetTurnPlayer()==tp then
return ph==PHASE_MAIN1 or ph==PHASE_MAIN2
else
return (ph>=PHASE_BATTLE_START and ph<=PHASE_BATTLE)
end
end
function c77662914.specfilter(c,e,tp)
return c:IsCanBeSpecialSummoned(e,0,tp,false,false) and c:IsType(TYPE_MONSTER)
end
function c77662914.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
local g=e:GetHandler():GetOverlayGroup()
local count=0
local tc=g:GetFirst()
while tc do
if c77662914.specfilter(tc,e,tp) then
count=count+1
end
tc=g:GetNext()
end
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.GetLocationCount(tp,LOCATION_MZONE)>=count end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_OVERLAY)
end
function c77662914.spop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local g=c:GetOverlayGroup()
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0
or Duel.GetLocationCount(tp,LOCATION_MZONE)<g:GetCount() then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F)
e1:SetProperty(EFFECT_FLAG_INITIAL+EFFECT_FLAG_REPEAT)
e1:SetCode(EVENT_PHASE+PHASE_END)
e1:SetRange(LOCATION_MZONE)
e1:SetCountLimit(1)
e1:SetReset(RESET_EVENT+0x1ee0000+RESET_PHASE+PHASE_END)
e1:SetCondition(c77662914.retcon)
e1:SetOperation(c77662914.retop)
c:RegisterEffect(e1)
local sg=g:FilterSelect(tp,c77662914.specfilter,g:GetCount(),g:GetCount(),nil,e,tp)
local tc=sg:GetFirst()
while tc do
Duel.SpecialSummonStep(tc,0,tp,tp,false,false,POS_FACEUP)
c:SetCardTarget(tc)
tc=sg:GetNext()
end
Duel.SpecialSummonComplete()
end
function c77662914.retcon(e,tp,eg,ep,ev,re,r,rp)
local tc=e:GetHandler():GetCardTarget()
return tc:GetCount()>0
end
function c77662914.retop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local g=c:GetCardTarget()
local tc=g:GetFirst()
while tc do
if tc:IsLocation(LOCATION_MZONE) then
Duel.Overlay(c,tc)
end
tc=g:GetNext()
end
end
function c77662914.discon(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsStatus(STATUS_BATTLE_DESTROYED) then return false end
if not re:IsHasProperty(EFFECT_FLAG_CARD_TARGET) then return false end
local tg=Duel.GetChainInfo(ev,CHAININFO_TARGET_CARDS)
return tg and tg:IsContains(c) and Duel.IsChainNegatable(ev)
end
function c77662914.discost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.CheckLPCost(tp,600) end
Duel.PayLPCost(tp,600)
end
function c77662914.distg(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 c77662914.disop(e,tp,eg,ep,ev,re,r,rp)
Duel.NegateActivation(ev)
if re:GetHandler():IsRelateToEffect(re) then
Duel.Destroy(eg,REASON_EFFECT)
end
end
function c77662914.splimit(e,c,sump,sumtype,sumpos,targetp)
if c:IsRace(RACE_MACHINE) then return false end
return bit.band(sumtype,SUMMON_TYPE_PENDULUM)==SUMMON_TYPE_PENDULUM
end
function c77662914.splimcon(e)
return not e:GetHandler():IsForbidden()
end
function c77662914.penfilter1(c)
return c:IsDestructable() and c:GetSequence()==6
end
function c77662914.penfilter2(c)
return c:IsDestructable() and c:GetSequence()==7
end
function c77662914.con(e,tp,eg,ep,ev,re,r,rp)
local p1=Duel.GetFieldCard(tp,LOCATION_SZONE,6)
local p2=Duel.GetFieldCard(tp,LOCATION_SZONE,7)
if not p1 and not p2 then return false end
return (e:GetHandler():IsReason(REASON_EFFECT) or e:GetHandler():IsReason(REASON_BATTLE)) and
(p1 and p1:IsDestructable()) or (p2 and p2:IsDestructable()) and e:GetHandler():GetPreviousLocation()==LOCATION_MZONE
end
function c77662914.op(e,tp,eg,ep,ev,re,r,rp)
local p1=Duel.GetFieldCard(tp,LOCATION_SZONE,6)
local p2=Duel.GetFieldCard(tp,LOCATION_SZONE,7)
local g1=nil
local g2=nil
if p1 then
g1=Duel.GetMatchingGroup(c77662914.penfilter1,tp,LOCATION_SZONE,0,nil)
end
if p2 then
g2=Duel.GetMatchingGroup(c77662914.penfilter2,tp,LOCATION_SZONE,0,nil)
if g1 then
g1:Merge(g2)
else
g1=g2
end
end
if g1 and Duel.Destroy(g1,REASON_EFFECT)~=0 then
local c=e:GetHandler()
Duel.MoveToField(c,tp,tp,LOCATION_SZONE,POS_FACEUP,true)
end
end
function c77662914.sccon(e)
local seq=e:GetHandler():GetSequence()
local tc=Duel.GetFieldCard(e:GetHandlerPlayer(),LOCATION_SZONE,13-seq)
return not tc or (not tc:IsCode(98442213) and not tc:IsCode(98442212) and not tc:IsCode(38299892) and not tc:IsCode(38299891) and not tc:IsCode(77662914) and not tc:IsCode(77662928))
end
function c77662914.desfilter(c)
return c:IsFaceup() and not c:IsRace(RACE_MACHINE)
end
function c77662914.descon(e)
return Duel.IsExistingMatchingCard(c77662914.desfilter,e:GetHandlerPlayer(),LOCATION_MZONE,0,1,nil)
end
function c77662914.levelfilter(c)
return c:IsFaceup() and c:IsSetCard(0x0dac405)
end
function c77662914.lvtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c77662914.levelfilter,tp,LOCATION_MZONE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,aux.Stringid(77662914,4))
local lv=Duel.AnnounceNumber(tp,1,2,3,4,5,6,7,8,9,10)
e:SetLabel(lv)
end
function c77662914.lvop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if not c:IsRelateToEffect(e) then return end
local g=Duel.GetMatchingGroup(c77662914.levelfilter,tp,LOCATION_MZONE,0,nil)
local tc=g:GetFirst()
while tc do
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_CHANGE_LEVEL)
e1:SetValue(e:GetLabel())
e1:SetReset(RESET_EVENT+0x1fe0000)
tc:RegisterEffect(e1)
tc=g:GetNext()
end
end | gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.