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 |
|---|---|---|---|---|---|
ddumont/darkstar | scripts/zones/Mhaura/Zone.lua | 13 | 2946 | -----------------------------------
--
-- Zone: Mhaura (249)
--
-----------------------------------
package.loaded["scripts/zones/Mhaura/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/zone");
require("scripts/zones/Mhaura/TextIDs");
require("scripts/globals/missions");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
SetExplorerMoogles(17797253);
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
local currentday = tonumber(os.date("%j"));
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
if (prevZone == 221 or prevZone == 47) then
cs = 0x00ca;
player:setPos(14.960,-3.430,18.423,192);
else
player:setPos(0.003,-6.252,117.971,65);
end
end
if (player:getCurrentMission(COP) == DAWN and player:getVar("PromathiaStatus")==3 and player:getVar("Promathia_kill_day") ~= currentday and player:getVar("COP_shikarees_story")== 0 ) then
cs=0x0142;
end
return cs;
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onTransportEvent
-----------------------------------
function onTransportEvent(player,transport)
if ((transport == 47) or (transport == 46)) then
if (not(player:hasKeyItem(BOARDING_PERMIT)) or ENABLE_TOAU == 0) then
player:setPos(8.200,-1.363,3.445,192);
player:messageSpecial(DO_NOT_POSSESS, BOARDING_PERMIT);
else
player:startEvent(0x00c8);
end
else
player:startEvent(0x00c8);
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 == 0x00c8) then
local DepartureTime = VanadielHour();
if (DepartureTime % 8 == 0) then
player:setPos(0,0,0,0,220); -- Boat to Selbina
elseif (DepartureTime % 8 == 4) then
player:setPos(0,0,0,0,46); -- Boat to Aht Urhgan
else
player:setPos(8,-1,5,62,249); -- Something went wrong, dump them on the dock for safety.
end
elseif (csid == 0x0142) then
player:setVar("COP_shikarees_story",1);
end
end; | gpl-3.0 |
kennethlombardi/moai-graphics | half-edge-mesh/editor/createStarfield.lua | 2 | 1115 | dofile("Pickle.lua")
layer1 = {
type = "Layer",
name = "starfield.lua",
visible = "true",
propContainer = {},
position = {x = 0, y = 0, z = 0},
scripts = {"starfield.lua"}
};
width = 1280;
height = 720;
objectCount = 10;
for i = 1, objectCount do
position = {};
scale = {x = 3, y = 3, z = 3};
local randx = math.random(600, 800);
position.z = -1000
local angle = math.random(1, 360);
position.x = randx * math.cos(angle);
position.y = randx * math.sin(angle);
prop = {
type = "PropCube",
name = "Prop"..i,
position = position,
scale = scale,
scripts = {"speedline.lua"},
shaderName = "shader",
textureName = "whiteSquare.png",
rotation = {x = 0, y = 0, z = 0},
}
table.insert(layer1.propContainer, prop);
end
layers = {};
table.insert(layers, layer1);
local function pickleThis()
layerCount = 0;
for k,v in pairs(layers) do
file = io.open(".\\generated\\starfield"..".lua", "wt");
s = "deserialize (\"Layer\",\n";
file:write(s);
s = pickle(v);
file:write(s);
s = ")\n\n";
file:write(s);
file:close();
layerCount = layerCount + 1;
end
end
pickleThis();
| mit |
Squeakz/darkstar | scripts/zones/Caedarva_Mire/npcs/Nuimahn.lua | 13 | 1386 | -----------------------------------
-- Area: Caedarva Mire
-- NPC: Nuimahn
-- Type: Alzadaal Undersea Ruins
-- @pos -380 0 -381 79
-----------------------------------
package.loaded["scripts/zones/Caedarva_Mire/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/zones/Caedarva_Mire/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (trade:getItemCount() == 1 and trade:hasItemQty(2185,1)) then
player:tradeComplete();
player:startEvent(0x00cb);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getZPos() < -281) then
player:startEvent(0x00cc); -- leaving
else
player:startEvent(0x00ca); -- entering
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 == 0x00cb) then
player:setPos(-515,-6.5,740,0,72);
end
end; | gpl-3.0 |
rodoviario/wordgrinder | src/lua/_prologue.lua | 3 | 1421 | -- © 2008 David Given.
-- WordGrinder is licensed under the MIT open source license. See the COPYING
-- file in this distribution for the full text.
-- Urrgh, luajit's path defaults to all the wrong places. This is painfully
-- evil but does at least work.
if jit then
package.path = package.path ..
";/usr/share/lua/5.1/?.lua;/usr/share/lua/5.1/?/init.lua"
package.cpath = package.cpath ..
";/usr/lib/x86_64-linux-gnu/lua/5.1/?.so;/usr/lib/lua/5.1/?.so;/usr/local/lib/lua/5.1/loadall.so"
end
-- Load the LFS module if needed (Windows has it built in).
if not lfs then
lfs = require "lfs"
end
-- Bit library fallbacks. (LuaJIT vs Lua 5.2 incompatibilities.)
if not bit32 then
bit32 =
{
bxor = bit.bxor,
band = bit.band,
bor = bit.bor,
btest = function(a, b)
return bit.band(a, b) ~= 0
end
}
end
-- Make sure that reads of undefined global variables fail. Note: this will
-- prevent us from storing nil in a global.
if DEBUG then
local allowed =
{
X11_BLACK_COLOUR = true,
X11_BOLD_MODIFIER = true,
X11_BRIGHT_COLOUR = true,
X11_DIM_COLOUR = true,
X11_FONT = true,
X11_ITALIC_MODIFIER = true,
X11_NORMAL_COLOUR = true,
}
setmetatable(_G,
{
__index = function(self, k)
if not allowed[k] then
error("read from undefined local '"..k.."'")
end
return rawget(_G, k)
end
}
)
end
-- Global definitions that the various source files need.
Cmd = {}
| mit |
ddumont/darkstar | scripts/globals/items/ear_of_grilled_corn.lua | 12 | 1288 | -----------------------------------------
-- ID: 4334
-- Item: ear_of_grilled_corn
-- Food Effect: 60Min, All Races
-----------------------------------------
-- Health 10
-- Vitality 4
-- Health Regen While Healing 1
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,3600,4334);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 10);
target:addMod(MOD_VIT, 4);
target:addMod(MOD_HPHEAL, 1);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 10);
target:delMod(MOD_VIT, 4);
target:delMod(MOD_HPHEAL, 1);
end;
| gpl-3.0 |
smartdevicelink/sdl_atf_test_scripts | test_scripts/Policies/External_UCS/External_Consent_ON/028_ATF_Policies_External_Consent_ON_same_notification_user_consent_allowed_externalConsentStatus_disallowed.lua | 1 | 7823 | require('user_modules/script_runner').isTestApplicable({ { extendedPolicy = { "EXTERNAL_PROPRIETARY" } } })
-------------------------------------- Requirement summary -------------------------------------------
-- [Policies] External UCS: externalConsentStatus vs. consentedFunctions priority
--
------------------------------------------------------------------------------------------------------
------------------------------------General Settings for Configuration--------------------------------
------------------------------------------------------------------------------------------------------
require('user_modules/all_common_modules')
local common_functions_external_consent = require('user_modules/shared_testcases_custom/ATF_Policies_External_Consent_common_functions')
------------------------------------------------------------------------------------------------------
---------------------------------------Common Variables-----------------------------------------------
------------------------------------------------------------------------------------------------------
local id_group_1
local policy_file = config.pathToSDL .. "storage/policy.sqlite"
------------------------------------------------------------------------------------------------------
---------------------------------------Preconditions--------------------------------------------------
------------------------------------------------------------------------------------------------------
-- Start SDL and register application
common_functions_external_consent:PreconditonSteps("mobileConnection","mobileSession")
-- Activate application
common_steps:ActivateApplication("Activate_Application_1", config.application1.registerAppInterfaceParams.appName)
------------------------------------------------------------------------------------------------------
------------------------------------------Tests-------------------------------------------------------
------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------
-- TEST 04:
-- In case:
-- SDL received SDL.OnAppPermissionConsent that contains both (consentedFunctions:allowed, externalConsentStatus)
-- and according to externalConsentStatus "functional_grouping" for the assigned app is "userDisallowed"
-- SDL must
-- change "functional_grouping" status according to externalConsentStatus to "userDisallowed"
--------------------------------------------------------------------------
-- Test 04.02:
-- Description: disallowed_by_external_consent_entities_on exists. HMI -> SDL: OnAppPermissionConsent(externalConsentStatus ON, function allowed)
-- Expected Result: requested RPC is disallowed by External Consent
--------------------------------------------------------------------------
-- Precondition:
-- Prepare JSON file with consent groups. Add all consent group names into app_polices of applications
-- Request Policy Table Update.
--------------------------------------------------------------------------
Test[TEST_NAME_ON.."Precondition_Update_Policy_Table"] = function(self)
-- create json for PTU from sdl_preloaded_pt.json
local data = common_functions_external_consent:ConvertPreloadedToJson()
-- insert Group001 into "functional_groupings"
data.policy_table.functional_groupings.Group001 = {
user_consent_prompt = "ConsentGroup001",
disallowed_by_external_consent_entities_on = {{
entityType = 2,
entityID = 5
}},
rpcs = {
SubscribeWayPoints = {
hmi_levels = {"BACKGROUND", "FULL", "LIMITED"}
}
}
}
--insert application "0000001" which belong to functional group "Group001" into "app_policies"
data.policy_table.app_policies["0000001"] = {
keep_context = false,
steal_focus = false,
priority = "NONE",
default_hmi = "NONE",
groups = {"Base-4", "Group001"}
}
--insert "ConsentGroup001" into "consumer_friendly_messages"
data.policy_table.consumer_friendly_messages.messages["ConsentGroup001"] = {languages = {}}
data.policy_table.consumer_friendly_messages.messages.ConsentGroup001.languages["en-us"] = {
tts = "tts_test",
label = "label_test",
textBody = "textBody_test"
}
-- create json file for Policy Table Update
common_functions_external_consent:CreateJsonFileForPTU(data, "/tmp/ptu_update.json")
-- remove preload_pt from json file
local parent_item = {"policy_table","module_config"}
local removed_json_items = {"preloaded_pt"}
common_functions:RemoveItemsFromJsonFile("/tmp/ptu_update.json", parent_item, removed_json_items)
-- update policy table
common_functions_external_consent:UpdatePolicy(self, "/tmp/ptu_update.json")
end
--------------------------------------------------------------------------
-- Precondition:
-- Check GetListOfPermissions response with empty externalConsentStatus array list. Get group id.
--------------------------------------------------------------------------
Test[TEST_NAME_ON.."Precondition_GetListOfPermissions"] = function(self)
--hmi side: sending SDL.GetListOfPermissions request to SDL
local request_id = self.hmiConnection:SendRequest("SDL.GetListOfPermissions")
-- hmi side: expect SDL.GetListOfPermissions response
EXPECT_HMIRESPONSE(request_id,{
result = {
code = 0,
method = "SDL.GetListOfPermissions",
allowedFunctions = {{name = "ConsentGroup001", allowed = nil}},
externalConsentStatus = {}
}
})
:Do(function(_,data)
id_group_1 = common_functions_external_consent:GetGroupId(data, "ConsentGroup001")
end)
end
--------------------------------------------------------------------------
-- Precondition:
-- HMI sends OnAppPermissionConsent with consented function = allowed and External Consent status = ON
--------------------------------------------------------------------------
Test[TEST_NAME_ON .. "Precondition_HMI_sends_OnAppPermissionConsent"] = function(self)
hmi_app_id_1 = common_functions:GetHmiAppId(config.application1.registerAppInterfaceParams.appName, self)
-- hmi side: sending SDL.OnAppPermissionConsent for applications
self.hmiConnection:SendNotification("SDL.OnAppPermissionConsent", {
appID = hmi_app_id_1, source = "GUI",
externalConsentStatus = {{entityType = 2, entityID = 5, status = "ON"}},
consentedFunctions = {{name = "ConsentGroup001", id = id_group_1, allowed = true}}
})
self.mobileSession:ExpectNotification("OnPermissionsChange")
:ValidIf(function(_,data)
local validate_result = common_functions_external_consent:ValidateHMIPermissions(data,
"SubscribeWayPoints", {allowed = {}, userDisallowed = {"BACKGROUND","FULL","LIMITED"}})
return validate_result
end)
end
--------------------------------------------------------------------------
-- Main check:
-- RPC is disallowed to process.
--------------------------------------------------------------------------
Test[TEST_NAME_ON .. "MainCheck_RPC_is_disallowed"] = function(self)
--mobile side: send SubscribeWayPoints request
local corid = self.mobileSession:SendRPC("SubscribeWayPoints",{})
--mobile side: SubscribeWayPoints response
EXPECT_RESPONSE("SubscribeWayPoints", {success = false , resultCode = "USER_DISALLOWED"})
EXPECT_NOTIFICATION("OnHashChange")
:Times(0)
common_functions:DelayedExp(5000)
end
-- end Test 04.02
----------------------------------------------------
---------------------------------------------------------------------------------------------
--------------------------------------Postcondition------------------------------------------
---------------------------------------------------------------------------------------------
-- Stop SDL
Test["Stop_SDL"] = function(self)
StopSDL()
end
| bsd-3-clause |
jorgifumi/luci | modules/luci-mod-admin-full/luasrc/model/cbi/admin_network/network.lua | 48 | 2480 | -- Copyright 2008 Steven Barth <steven@midlink.org>
-- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
local fs = require "nixio.fs"
m = Map("network", translate("Interfaces"))
m.pageaction = false
m:section(SimpleSection).template = "admin_network/iface_overview"
-- Show ATM bridge section if we have the capabilities
if fs.access("/usr/sbin/br2684ctl") then
atm = m:section(TypedSection, "atm-bridge", translate("ATM Bridges"),
translate("ATM bridges expose encapsulated ethernet in AAL5 " ..
"connections as virtual Linux network interfaces which can " ..
"be used in conjunction with DHCP or PPP to dial into the " ..
"provider network."))
atm.addremove = true
atm.anonymous = true
atm.create = function(self, section)
local sid = TypedSection.create(self, section)
local max_unit = -1
m.uci:foreach("network", "atm-bridge",
function(s)
local u = tonumber(s.unit)
if u ~= nil and u > max_unit then
max_unit = u
end
end)
m.uci:set("network", sid, "unit", max_unit + 1)
m.uci:set("network", sid, "atmdev", 0)
m.uci:set("network", sid, "encaps", "llc")
m.uci:set("network", sid, "payload", "bridged")
m.uci:set("network", sid, "vci", 35)
m.uci:set("network", sid, "vpi", 8)
return sid
end
atm:tab("general", translate("General Setup"))
atm:tab("advanced", translate("Advanced Settings"))
vci = atm:taboption("general", Value, "vci", translate("ATM Virtual Channel Identifier (VCI)"))
vpi = atm:taboption("general", Value, "vpi", translate("ATM Virtual Path Identifier (VPI)"))
encaps = atm:taboption("general", ListValue, "encaps", translate("Encapsulation mode"))
encaps:value("llc", translate("LLC"))
encaps:value("vc", translate("VC-Mux"))
atmdev = atm:taboption("advanced", Value, "atmdev", translate("ATM device number"))
unit = atm:taboption("advanced", Value, "unit", translate("Bridge unit number"))
payload = atm:taboption("advanced", ListValue, "payload", translate("Forwarding mode"))
payload:value("bridged", translate("bridged"))
payload:value("routed", translate("routed"))
m.pageaction = true
end
local network = require "luci.model.network"
if network:has_ipv6() then
local s = m:section(NamedSection, "globals", "globals", translate("Global network options"))
local o = s:option(Value, "ula_prefix", translate("IPv6 ULA-Prefix"))
o.datatype = "ip6addr"
o.rmempty = true
m.pageaction = true
end
return m
| apache-2.0 |
jchuang1977/luci-1 | modules/luci-mod-admin-full/luasrc/model/cbi/admin_network/network.lua | 48 | 2480 | -- Copyright 2008 Steven Barth <steven@midlink.org>
-- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
local fs = require "nixio.fs"
m = Map("network", translate("Interfaces"))
m.pageaction = false
m:section(SimpleSection).template = "admin_network/iface_overview"
-- Show ATM bridge section if we have the capabilities
if fs.access("/usr/sbin/br2684ctl") then
atm = m:section(TypedSection, "atm-bridge", translate("ATM Bridges"),
translate("ATM bridges expose encapsulated ethernet in AAL5 " ..
"connections as virtual Linux network interfaces which can " ..
"be used in conjunction with DHCP or PPP to dial into the " ..
"provider network."))
atm.addremove = true
atm.anonymous = true
atm.create = function(self, section)
local sid = TypedSection.create(self, section)
local max_unit = -1
m.uci:foreach("network", "atm-bridge",
function(s)
local u = tonumber(s.unit)
if u ~= nil and u > max_unit then
max_unit = u
end
end)
m.uci:set("network", sid, "unit", max_unit + 1)
m.uci:set("network", sid, "atmdev", 0)
m.uci:set("network", sid, "encaps", "llc")
m.uci:set("network", sid, "payload", "bridged")
m.uci:set("network", sid, "vci", 35)
m.uci:set("network", sid, "vpi", 8)
return sid
end
atm:tab("general", translate("General Setup"))
atm:tab("advanced", translate("Advanced Settings"))
vci = atm:taboption("general", Value, "vci", translate("ATM Virtual Channel Identifier (VCI)"))
vpi = atm:taboption("general", Value, "vpi", translate("ATM Virtual Path Identifier (VPI)"))
encaps = atm:taboption("general", ListValue, "encaps", translate("Encapsulation mode"))
encaps:value("llc", translate("LLC"))
encaps:value("vc", translate("VC-Mux"))
atmdev = atm:taboption("advanced", Value, "atmdev", translate("ATM device number"))
unit = atm:taboption("advanced", Value, "unit", translate("Bridge unit number"))
payload = atm:taboption("advanced", ListValue, "payload", translate("Forwarding mode"))
payload:value("bridged", translate("bridged"))
payload:value("routed", translate("routed"))
m.pageaction = true
end
local network = require "luci.model.network"
if network:has_ipv6() then
local s = m:section(NamedSection, "globals", "globals", translate("Global network options"))
local o = s:option(Value, "ula_prefix", translate("IPv6 ULA-Prefix"))
o.datatype = "ip6addr"
o.rmempty = true
m.pageaction = true
end
return m
| apache-2.0 |
smartdevicelink/sdl_atf_test_scripts | test_scripts/API/SDL_Passenger_Mode/commonPassengerMode.lua | 1 | 5037 | ---------------------------------------------------------------------------------------------------
-- Common module
---------------------------------------------------------------------------------------------------
--[[ General configuration parameters ]]
config.defaultProtocolVersion = 2
config.checkAllValidations = true
config.application1.registerAppInterfaceParams.isMediaApplication = false
--[[ Required Shared libraries ]]
local actions = require("user_modules/sequences/actions")
local utils = require("user_modules/utils")
local json = require("modules/json")
local test = require("user_modules/dummy_connecttest")
local SDL = require("SDL")
--[[ Module ]]
local c = actions
--[[ Variables ]]
local wrnMsg
c.language = "EN-US"
--[[ Common Functions ]]
function c.registerAppWithOnDD(pAppId)
c.registerApp(pAppId)
c.getMobileSession(pAppId):ExpectNotification("OnDriverDistraction", { state = "DD_OFF" })
end
function c.expOnDriverDistraction(pState, pLockScreenDismissalEnabled, pAppId)
c.getMobileSession(pAppId):ExpectNotification("OnDriverDistraction", { state = pState })
:ValidIf(function(_, d)
if pLockScreenDismissalEnabled == nil and d.payload.lockScreenDismissalEnabled ~= nil then
return false, d.payload.state .. ": Parameter `lockScreenDismissalEnabled` is not expected"
end
if pLockScreenDismissalEnabled ~= d.payload.lockScreenDismissalEnabled then
return false, d.payload.state .. ": Parameter `lockScreenDismissalEnabled` is not the same as expected"
end
return true
end)
:ValidIf(function(_, d)
if d.payload.lockScreenDismissalEnabled == true then
if d.payload.lockScreenDismissalWarning == nil then
return false, d.payload.state .. "(" .. tostring(d.payload.lockScreenDismissalEnabled) .. ")"
.. ": Parameter `lockScreenDismissalWarning` is missing"
elseif d.payload.lockScreenDismissalWarning ~= wrnMsg then
return false, d.payload.state .. "(" .. tostring(d.payload.lockScreenDismissalEnabled) .. ")"
.. ": The value for parameter `lockScreenDismissalWarning` is not the same as expected"
end
elseif d.payload.lockScreenDismissalWarning ~= nil then
return false, d.payload.state .. "(" .. tostring(d.payload.lockScreenDismissalEnabled) .. ")"
.. ": Parameter `lockScreenDismissalWarning` is not expected"
end
return true
end)
end
function c.onDriverDistraction(pState, pLockScreenDismissalEnabled, pAppId)
if not pAppId then pAppId = 1 end
c.getHMIConnection():SendNotification("UI.OnDriverDistraction", { state = pState })
c.expOnDriverDistraction(pState, pLockScreenDismissalEnabled, pAppId)
end
local preconditionsOrig = c.preconditions
function c.preconditions()
preconditionsOrig()
SDL.PreloadedPT.backup()
end
local postconditionsOrig = c.postconditions
function c.postconditions()
postconditionsOrig()
SDL.PreloadedPT.restore()
end
local function setLockScreenWrnMsg(pMessages)
local lang = string.lower(c.language)
local warnSec = pMessages["LockScreenDismissalWarning"]
if warnSec == nil then
test:FailTestCase("'LockScreenDismissalWarning' message section is not defined in 'sdl_preloaded_pt' file")
else
local msg = "'LockScreenDismissalWarning' message for '" .. lang .. "' is not defined in 'sdl_preloaded_pt' file"
if lang == "en-us" and warnSec.languages[lang] == nil then
test:FailTestCase(msg)
return
end
if warnSec.languages[lang] == nil then
utils.cprint(35, msg)
utils.cprint(35, "'en-us' should be used instead")
lang = "en-us"
end
wrnMsg = warnSec.languages[lang].textBody
end
end
function c.updatePreloadedPT(pLockScreenDismissalEnabled, pUpdateFunc)
local pt = SDL.PreloadedPT.get()
pt.policy_table.functional_groupings["DataConsent-2"].rpcs = json.null
pt.policy_table.module_config.lock_screen_dismissal_enabled = pLockScreenDismissalEnabled
if pUpdateFunc then
pUpdateFunc(pt)
end
setLockScreenWrnMsg(pt.policy_table.consumer_friendly_messages.messages)
SDL.PreloadedPT.set(pt)
end
local function deactivateAppToLimited()
c.getHMIConnection():SendNotification("BasicCommunication.OnAppDeactivated",
{ appID = c.getHMIAppId() })
c.getMobileSession():ExpectNotification("OnHMIStatus",
{ hmiLevel = "LIMITED", audioStreamingState = "AUDIBLE", systemContext = "MAIN" })
end
local function deactivateAppToBackground()
c.getHMIConnection():SendNotification("BasicCommunication.OnEventChanged", {
eventName = "EMBEDDED_NAVI", isActive = true
})
c.getMobileSession():ExpectNotification("OnHMIStatus",
{ hmiLevel = "BACKGROUND", audioStreamingState = "NOT_AUDIBLE", systemContext = "MAIN" })
end
c.hmiLevel = {
[1] = { name = "NONE", func = function() end },
[2] = { name = "FULL", func = c.activateApp },
[3] = { name = "LIMITED", func = deactivateAppToLimited },
[4] = { name = "BACKGROUND", func = deactivateAppToBackground }
}
c.pairs = utils.spairs
return c
| bsd-3-clause |
ddumont/darkstar | scripts/zones/Arrapago_Reef/npcs/_jic.lua | 27 | 3547 | -----------------------------------
-- Area: Arrapago Reef
-- Door: Runic Seal
-- @pos 36 -10 620 54
-----------------------------------
package.loaded["scripts/zones/Arrapago_Reef/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/missions");
require("scripts/globals/besieged");
require("scripts/zones/Arrapago_Reef/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(ILRUSI_ASSAULT_ORDERS)) then
local assaultid = player:getCurrentAssault();
local recommendedLevel = getRecommendedAssaultLevel(assaultid);
local armband = 0;
if (player:hasKeyItem(ASSAULT_ARMBAND)) then
armband = 1;
end
player:startEvent(0x00DB, assaultid, -4, 0, recommendedLevel, 2, armband);
else
player:messageSpecial(NOTHING_HAPPENS);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option,target)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
local assaultid = player:getCurrentAssault();
local cap = bit.band(option, 0x03);
if (cap == 0) then
cap = 99;
elseif (cap == 1) then
cap = 70;
elseif (cap == 2) then
cap = 60;
else
cap = 50;
end
player:setVar("AssaultCap", cap);
local party = player:getParty();
if (party ~= nil) then
for i,v in ipairs(party) do
if (not (v:hasKeyItem(ILRUSI_ASSAULT_ORDERS) and v:getCurrentAssault() == assaultid)) then
player:messageText(target,MEMBER_NO_REQS, false);
player:instanceEntry(target,1);
return;
elseif (v:getZone() == player:getZone() and v:checkDistance(player) > 50) then
player:messageText(target,MEMBER_TOO_FAR, false);
player:instanceEntry(target,1);
return;
end
end
end
player:createInstance(player:getCurrentAssault(), 55);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option,target)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x6C or (csid == 0xDB and option == 4)) then
player:setPos(0,0,0,0,55);
end
end;
-----------------------------------
-- onInstanceLoaded
-----------------------------------
function onInstanceCreated(player,target,instance)
if (instance) then
instance:setLevelCap(player:getVar("AssaultCap"));
player:setVar("AssaultCap", 0);
player:setInstance(instance);
player:instanceEntry(target,4);
player:delKeyItem(ILRUSI_ASSAULT_ORDERS);
player:delKeyItem(ASSAULT_ARMBAND);
if (party ~= nil) then
for i,v in ipairs(party) do
if v:getID() ~= player:getID() and v:getZone() == player:getZone() then
v:setInstance(instance);
v:startEvent(0x6C, 2);
v:delKeyItem(ILRUSI_ASSAULT_ORDERS);
end
end
end
else
player:messageText(target,CANNOT_ENTER, false);
player:instanceEntry(target,3);
end
end; | gpl-3.0 |
jlcvp/otxserver | data/monster/aquatics/deepling_tyrant.lua | 2 | 3524 | local mType = Game.createMonsterType("Deepling Tyrant")
local monster = {}
monster.description = "a deepling tyrant"
monster.experience = 4200
monster.outfit = {
lookType = 442,
lookHead = 0,
lookBody = 0,
lookLegs = 0,
lookFeet = 0,
lookAddons = 0,
lookMount = 0
}
monster.raceId = 861
monster.Bestiary = {
class = "Aquatic",
race = BESTY_RACE_AQUATIC,
toKill = 2500,
FirstUnlock = 100,
SecondUnlock = 1000,
CharmsPoints = 50,
Stars = 4,
Occurrence = 2,
Locations = "Fiehonja."
}
monster.health = 4500
monster.maxHealth = 4500
monster.race = "blood"
monster.corpse = 13751
monster.speed = 310
monster.manaCost = 0
monster.changeTarget = {
interval = 4000,
chance = 10
}
monster.strategiesTarget = {
nearest = 70,
health = 10,
damage = 10,
random = 10,
}
monster.flags = {
summonable = false,
attackable = true,
hostile = true,
convinceable = false,
pushable = false,
rewardBoss = false,
illusionable = false,
canPushItems = true,
canPushCreatures = true,
staticAttackChance = 70,
targetDistance = 1,
runHealth = 20,
healthHidden = false,
isBlockable = false,
canWalkOnEnergy = false,
canWalkOnFire = true,
canWalkOnPoison = false
}
monster.light = {
level = 0,
color = 0
}
monster.voices = {
interval = 5000,
chance = 10,
{text = "QJELL NETA NA!!", yell = false}
}
monster.loot = {
{name = "gold coin", chance = 100000, maxCount = 100},
{name = "gold coin", chance = 100000, maxCount = 100},
{name = "platinum coin", chance = 70000, maxCount = 4},
{name = "deepling breaktime snack", chance = 35520},
{name = "great mana potion", chance = 32640, maxCount = 3},
{name = "great health potion", chance = 33430, maxCount = 3},
{name = "deepling claw", chance = 29960},
{name = "eye of a deepling", chance = 29610},
{name = "deepling guard belt buckle", chance = 23700},
{name = "small sapphire", chance = 9410, maxCount = 5},
{name = "heavy trident", chance = 3530},
{name = "deepling squelcher", chance = 1440},
{name = "guardian axe", chance = 1340},
{name = "ornate crossbow", chance = 1190},
{name = "deepling backpack", chance = 410},
{name = "foxtail", chance = 30}
}
monster.attacks = {
{name ="melee", interval = 2000, chance = 100, minDamage = 0, maxDamage = -501, effect = CONST_ME_DRAWBLOOD},
{name ="combat", interval = 2000, chance = 20, type = COMBAT_PHYSICALDAMAGE, minDamage = 0, maxDamage = -375, range = 7, shootEffect = CONST_ANI_WHIRLWINDSWORD, target = true},
{name ="combat", interval = 2000, chance = 15, type = COMBAT_DROWNDAMAGE, minDamage = -180, maxDamage = -215, range = 7, shootEffect = CONST_ANI_SPEAR, effect = CONST_ME_LOSEENERGY, target = true}
}
monster.defenses = {
defense = 45,
armor = 54,
{name ="combat", interval = 2000, chance = 15, type = COMBAT_HEALING, minDamage = 200, maxDamage = 400, effect = CONST_ME_MAGIC_BLUE, target = false}
}
monster.elements = {
{type = COMBAT_PHYSICALDAMAGE, percent = 0},
{type = COMBAT_ENERGYDAMAGE, percent = -10},
{type = COMBAT_EARTHDAMAGE, percent = -10},
{type = COMBAT_FIREDAMAGE, percent = 100},
{type = COMBAT_LIFEDRAIN, percent = 0},
{type = COMBAT_MANADRAIN, percent = 0},
{type = COMBAT_DROWNDAMAGE, percent = 100},
{type = COMBAT_ICEDAMAGE, percent = 100},
{type = COMBAT_HOLYDAMAGE , percent = 0},
{type = COMBAT_DEATHDAMAGE , percent = 10}
}
monster.immunities = {
{type = "paralyze", condition = true},
{type = "outfit", condition = false},
{type = "invisible", condition = true},
{type = "bleed", condition = false}
}
mType:register(monster)
| gpl-2.0 |
EnigmaTeam/EnigmaBot | plugins/9gag.lua | 1 | 1086 | do
local function get_9GAG()
local url = "http://api-9gag.herokuapp.com/"
local b,c = http.request(url)
if c ~= 200 then return nil end
local gag = json:decode(b)
-- random max json table size
local i = math.random(#gag)
local link_image = gag[i].src
local title = gag[i].title
if link_image:sub(0,2) == '//' then
link_image = msg.text:sub(3,-1)
end
return link_image, title
end
local function send_title(cb_extra, success, result)
if success then
send_msg(cb_extra[1], cb_extra[2], ok_cb, false)
end
end
local function run(msg, matches)
local receiver = get_receiver(msg)
local url, title = get_9GAG()
send_photo_from_url(receiver, url, send_title, {receiver, title})
return false
end
return {
description = "9GAG for Telegram",
usage = "از دستور\n#9gag\nبرای دریافت تصاویر تصادفی استفاده کنید\nبرای دیدن سایر دستورات عبارت\n@helpیا\n!help\nرا تایپ نمایید\n\n#MR_ENIGMA",
patterns = {
"^[!/#]9gag$",
"^/9gag@mrenigma_bot$"
},
run = run
}
end
| gpl-2.0 |
smartdevicelink/sdl_atf_test_scripts | test_scripts/API/PutFile/002_PutFile_with_crc_MultiFrame.lua | 1 | 2085 | ---------------------------------------------------------------------------------------------------
-- Proposal: https://github.com/smartdevicelink/sdl_evolution/blob/master/proposals/0037-Expand-Mobile-putfile-RPC.md
-- User story:TBD
-- Use case:TBD
--
-- Requirement summary:
-- TBD
--
-- Description:
-- In case:
-- 1. Mobile application sends a PutFile "Multiple Frame" with a known counted checksum to the SDL.
-- 2. Mobile application sends a PutFile "Multiple Frame" with a incorrect counted checksum to the SDL.
-- SDL does:
-- 1. Receive PutFile "Multiple Frame" and verify the counted checksum from the Mobile app and respond with result code "SUCCESS".
-- 2. Receive PutFile "Multiple Frame" and verify the counted checksum from the Mobile app and respond with result code "CORRUPTED_DATA".
---------------------------------------------------------------------------------------------------
--[[ Required Shared libraries ]]
local runner = require('user_modules/script_runner')
local common = require('test_scripts/API/PutFile/commonPutFile')
--[[ Test Configuration ]]
runner.testSettings.isSelfIncluded = false
--[[ Local Variables ]]
local usedFile = "./files/icon.png"
local paramsCorrSum = common.putFileParams()
paramsCorrSum.crc = common.getCheckSum(usedFile)
local paramsIncorrSum = common.putFileParams()
paramsIncorrSum.crc = common.getCheckSum(usedFile) - 100
local corrDataResult = {
success = false,
resultCode = "CORRUPTED_DATA",
info = "CRC Check on file failed. File upload has been cancelled, please retry."
}
--[[ Scenario ]]
runner.Title("Preconditions")
runner.Step("Clean environment", common.preconditions)
runner.Step("Start SDL, HMI, connect Mobile, start Session", common.start)
runner.Step("App registration", common.registerApp)
runner.Title("Test")
runner.Step("Upload file with correct checksum", common.putFile, {paramsCorrSum, usedFile})
runner.Step("Upload file with incorrect checksum", common.putFile, {paramsIncorrSum, usedFile, corrDataResult})
runner.Title("Postconditions")
runner.Step("Stop SDL", common.postconditions)
| bsd-3-clause |
jlcvp/otxserver | data/monster/quests/killing_in_the_name_of/deathbine.lua | 2 | 3023 | local mType = Game.createMonsterType("Deathbine")
local monster = {}
monster.description = "Deathbine"
monster.experience = 340
monster.outfit = {
lookType = 120,
lookHead = 0,
lookBody = 0,
lookLegs = 0,
lookFeet = 0,
lookAddons = 0,
lookMount = 0
}
monster.health = 525
monster.maxHealth = 525
monster.race = "venom"
monster.corpse = 6047
monster.speed = 240
monster.manaCost = 0
monster.changeTarget = {
interval = 5000,
chance = 8
}
monster.strategiesTarget = {
nearest = 70,
health = 10,
damage = 10,
random = 10,
}
monster.flags = {
summonable = false,
attackable = true,
hostile = true,
convinceable = false,
pushable = false,
rewardBoss = false,
illusionable = false,
canPushItems = true,
canPushCreatures = true,
staticAttackChance = 90,
targetDistance = 1,
runHealth = 0,
healthHidden = false,
isBlockable = false,
canWalkOnEnergy = false,
canWalkOnFire = false,
canWalkOnPoison = false
}
monster.light = {
level = 0,
color = 0
}
monster.voices = {
interval = 5000,
chance = 10,
}
monster.loot = {
{id = 10300, chance = 100000}, -- carniphila seeds
{id = 3035, chance = 100000, maxCount = 5}, -- platinum coin
{id = 3740, chance = 100000}, -- shadow herb
{id = 3032, chance = 100000, maxCount = 4}, -- small emerald
{id = 3728, chance = 50000}, -- dark mushroom
{id = 647, chance = 50000}, -- seeds
{id = 814, chance = 50000}, -- terra amulet
{id = 813, chance = 50000}, -- terra boots
{id = 8084, chance = 50000}, -- springsprout rod
{id = 5014, chance = 5555}, -- mandrake
{id = 12320, chance = 2854} -- sweet smelling bait
}
monster.attacks = {
{name ="melee", interval = 2000, chance = 100, skill = 30, attack = 100, condition = {type = CONDITION_POISON, totalDamage = 5, interval = 4000}},
{name ="combat", interval = 1000, chance = 25, type = COMBAT_EARTHDAMAGE, minDamage = -60, maxDamage = -90, range = 7, shootEffect = CONST_ANI_POISON, effect = CONST_ME_HITBYPOISON, target = false},
{name ="speed", interval = 1000, chance = 34, speedChange = -850, range = 7, shootEffect = CONST_ANI_POISON, effect = CONST_ME_HITBYPOISON, target = false, duration = 30000},
{name ="combat", interval = 1000, chance = 12, type = COMBAT_EARTHDAMAGE, minDamage = -40, maxDamage = -130, radius = 3, effect = CONST_ME_POISONAREA, target = false}
}
monster.defenses = {
defense = 10,
armor = 26
}
monster.elements = {
{type = COMBAT_PHYSICALDAMAGE, percent = 0},
{type = COMBAT_ENERGYDAMAGE, percent = 10},
{type = COMBAT_EARTHDAMAGE, percent = 100},
{type = COMBAT_FIREDAMAGE, percent = -20},
{type = COMBAT_LIFEDRAIN, percent = 0},
{type = COMBAT_MANADRAIN, percent = 0},
{type = COMBAT_DROWNDAMAGE, percent = 0},
{type = COMBAT_ICEDAMAGE, percent = 35},
{type = COMBAT_HOLYDAMAGE , percent = 0},
{type = COMBAT_DEATHDAMAGE , percent = 0}
}
monster.immunities = {
{type = "paralyze", condition = false},
{type = "outfit", condition = false},
{type = "invisible", condition = true},
{type = "bleed", condition = false}
}
mType:register(monster)
| gpl-2.0 |
jlcvp/otxserver | data/monster/quests/in_service_of_yalahar/rift_lord.lua | 2 | 1755 | local mType = Game.createMonsterType("Rift Lord")
local monster = {}
monster.description = "a rift lord"
monster.experience = 0
monster.outfit = {
lookType = 12,
lookHead = 9,
lookBody = 19,
lookLegs = 9,
lookFeet = 85,
lookAddons = 0,
lookMount = 0
}
monster.health = 5
monster.maxHealth = 5
monster.race = "fire"
monster.corpse = 0
monster.speed = 200
monster.manaCost = 0
monster.changeTarget = {
interval = 0,
chance = 0
}
monster.strategiesTarget = {
nearest = 70,
health = 10,
damage = 10,
random = 10,
}
monster.flags = {
summonable = false,
attackable = true,
hostile = false,
convinceable = false,
pushable = false,
rewardBoss = false,
illusionable = false,
canPushItems = true,
canPushCreatures = false,
staticAttackChance = 98,
targetDistance = 1,
runHealth = 0,
healthHidden = false,
isBlockable = false,
canWalkOnEnergy = false,
canWalkOnFire = false,
canWalkOnPoison = false
}
monster.light = {
level = 0,
color = 0
}
monster.voices = {
interval = 5000,
chance = 10,
}
monster.loot = {
}
monster.defenses = {
defense = 5,
armor = 10
}
monster.elements = {
{type = COMBAT_PHYSICALDAMAGE, percent = 0},
{type = COMBAT_ENERGYDAMAGE, percent = 0},
{type = COMBAT_EARTHDAMAGE, percent = 0},
{type = COMBAT_FIREDAMAGE, percent = 0},
{type = COMBAT_LIFEDRAIN, percent = 0},
{type = COMBAT_MANADRAIN, percent = 0},
{type = COMBAT_DROWNDAMAGE, percent = 0},
{type = COMBAT_ICEDAMAGE, percent = 0},
{type = COMBAT_HOLYDAMAGE , percent = 0},
{type = COMBAT_DEATHDAMAGE , percent = 0}
}
monster.immunities = {
{type = "paralyze", condition = false},
{type = "outfit", condition = false},
{type = "invisible", condition = false},
{type = "bleed", condition = false}
}
mType:register(monster)
| gpl-2.0 |
Squeakz/darkstar | scripts/zones/Port_Windurst/npcs/HomePoint#1.lua | 27 | 1275 | -----------------------------------
-- Area: Port Windurst
-- NPC: HomePoint#1
-- @pos -68.216 -4.000 111.761 240
-----------------------------------
package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil;
require("scripts/globals/settings");
require("scripts/zones/Port_Windurst/TextIDs");
require("scripts/globals/homepoint");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
homepointMenu( player, 0x21fc, 22);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x21fc) then
if (option == 1) then
player:setHomePoint();
player:messageSpecial(HOMEPOINT_SET);
else
hpTeleport( player, option);
end
end
end; | gpl-3.0 |
lemonkit/VisualCocos | frameworks/cocos2d-x/cocos/scripting/lua-bindings/auto/api/GridAction.lua | 11 | 1389 |
--------------------------------
-- @module GridAction
-- @extend ActionInterval
-- @parent_module cc
--------------------------------
-- brief Get the pointer of GridBase.<br>
-- return The pointer of GridBase.
-- @function [parent=#GridAction] getGrid
-- @param self
-- @return GridBase#GridBase ret (return value: cc.GridBase)
--------------------------------
-- brief Initializes the action with size and duration.<br>
-- param duration The duration of the GridAction. It's a value in seconds.<br>
-- param gridSize The size of the GridAction should be.<br>
-- return Return true when the initialization success, otherwise return false.
-- @function [parent=#GridAction] initWithDuration
-- @param self
-- @param #float duration
-- @param #size_table gridSize
-- @return bool#bool ret (return value: bool)
--------------------------------
--
-- @function [parent=#GridAction] startWithTarget
-- @param self
-- @param #cc.Node target
-- @return GridAction#GridAction self (return value: cc.GridAction)
--------------------------------
--
-- @function [parent=#GridAction] clone
-- @param self
-- @return GridAction#GridAction ret (return value: cc.GridAction)
--------------------------------
--
-- @function [parent=#GridAction] reverse
-- @param self
-- @return GridAction#GridAction ret (return value: cc.GridAction)
return nil
| mit |
satanoff/testantispam | plugins/anti-flood.lua | 281 | 2422 | local NUM_MSG_MAX = 5 -- Max number of messages per TIME_CHECK seconds
local TIME_CHECK = 5
local function kick_user(user_id, chat_id)
local chat = 'chat#id'..chat_id
local user = 'user#id'..user_id
chat_del_user(chat, user, function (data, success, result)
if success ~= 1 then
local text = 'I can\'t kick '..data.user..' but should be kicked'
send_msg(data.chat, '', ok_cb, nil)
end
end, {chat=chat, user=user})
end
local function run (msg, matches)
if msg.to.type ~= 'chat' then
return 'Anti-flood works only on channels'
else
local chat = msg.to.id
local hash = 'anti-flood:enabled:'..chat
if matches[1] == 'enable' then
redis:set(hash, true)
return 'Anti-flood enabled on chat'
end
if matches[1] == 'disable' then
redis:del(hash)
return 'Anti-flood disabled on chat'
end
end
end
local function pre_process (msg)
-- Ignore service msg
if msg.service then
print('Service message')
return msg
end
local hash_enable = 'anti-flood:enabled:'..msg.to.id
local enabled = redis:get(hash_enable)
if enabled then
print('anti-flood enabled')
-- Check flood
if msg.from.type == 'user' then
-- Increase the number of messages from the user on the chat
local hash = 'anti-flood:'..msg.from.id..':'..msg.to.id..':msg-num'
local msgs = tonumber(redis:get(hash) or 0)
if msgs > NUM_MSG_MAX then
local receiver = get_receiver(msg)
local user = msg.from.id
local text = 'User '..user..' is flooding'
local chat = msg.to.id
send_msg(receiver, text, ok_cb, nil)
if msg.to.type ~= 'chat' then
print("Flood in not a chat group!")
elseif user == tostring(our_id) then
print('I won\'t kick myself')
elseif is_sudo(msg) then
print('I won\'t kick an admin!')
else
-- Ban user
-- TODO: Check on this plugin bans
local bhash = 'banned:'..msg.to.id..':'..msg.from.id
redis:set(bhash, true)
kick_user(user, chat)
end
msg = nil
end
redis:setex(hash, TIME_CHECK, msgs+1)
end
end
return msg
end
return {
description = 'Plugin to kick flooders from group.',
usage = {},
patterns = {
'^!antiflood (enable)$',
'^!antiflood (disable)$'
},
run = run,
privileged = true,
pre_process = pre_process
}
| gpl-2.0 |
theonlywild/telegram-bot | plugins/anti-flood.lua | 281 | 2422 | local NUM_MSG_MAX = 5 -- Max number of messages per TIME_CHECK seconds
local TIME_CHECK = 5
local function kick_user(user_id, chat_id)
local chat = 'chat#id'..chat_id
local user = 'user#id'..user_id
chat_del_user(chat, user, function (data, success, result)
if success ~= 1 then
local text = 'I can\'t kick '..data.user..' but should be kicked'
send_msg(data.chat, '', ok_cb, nil)
end
end, {chat=chat, user=user})
end
local function run (msg, matches)
if msg.to.type ~= 'chat' then
return 'Anti-flood works only on channels'
else
local chat = msg.to.id
local hash = 'anti-flood:enabled:'..chat
if matches[1] == 'enable' then
redis:set(hash, true)
return 'Anti-flood enabled on chat'
end
if matches[1] == 'disable' then
redis:del(hash)
return 'Anti-flood disabled on chat'
end
end
end
local function pre_process (msg)
-- Ignore service msg
if msg.service then
print('Service message')
return msg
end
local hash_enable = 'anti-flood:enabled:'..msg.to.id
local enabled = redis:get(hash_enable)
if enabled then
print('anti-flood enabled')
-- Check flood
if msg.from.type == 'user' then
-- Increase the number of messages from the user on the chat
local hash = 'anti-flood:'..msg.from.id..':'..msg.to.id..':msg-num'
local msgs = tonumber(redis:get(hash) or 0)
if msgs > NUM_MSG_MAX then
local receiver = get_receiver(msg)
local user = msg.from.id
local text = 'User '..user..' is flooding'
local chat = msg.to.id
send_msg(receiver, text, ok_cb, nil)
if msg.to.type ~= 'chat' then
print("Flood in not a chat group!")
elseif user == tostring(our_id) then
print('I won\'t kick myself')
elseif is_sudo(msg) then
print('I won\'t kick an admin!')
else
-- Ban user
-- TODO: Check on this plugin bans
local bhash = 'banned:'..msg.to.id..':'..msg.from.id
redis:set(bhash, true)
kick_user(user, chat)
end
msg = nil
end
redis:setex(hash, TIME_CHECK, msgs+1)
end
end
return msg
end
return {
description = 'Plugin to kick flooders from group.',
usage = {},
patterns = {
'^!antiflood (enable)$',
'^!antiflood (disable)$'
},
run = run,
privileged = true,
pre_process = pre_process
}
| gpl-2.0 |
Squeakz/darkstar | scripts/commands/delitem.lua | 7 | 1695 | ---------------------------------------------------------------------------------------------------
-- func: @delitem
-- desc: Deletes a single item held by a player, if they have it.
---------------------------------------------------------------------------------------------------
require("scripts/globals/status");
cmdprops =
{
permission = 1,
parameters = "is"
};
function onTrigger(player, itemId, target)
if (itemId == nil or tonumber(itemId) == 0 or tonumber(itemId) == nil or itemId == 0) then
player:PrintToPlayer("You must enter a valid item ID.");
player:PrintToPlayer("@delitem <ID> <player>");
return;
end
if (target == nil) then
player:PrintToPlayer("You must enter a valid target name.");
player:PrintToPlayer("@delitem <ID> <player>");
return;
end
local targ = GetPlayerByName(target);
if (targ ~= nil) then
for i = LOC_INVENTORY, LOC_WARDROBE2 do -- inventory locations enums
if (targ:hasItem(itemId, i)) then
targ:delItem(itemId, 1, i);
player:PrintToPlayer(string.format("Item with ID %u deleted from player '%s'.", itemId, target));
break;
end
if (i == LOC_WARDROBE2) then -- Wardrobe 2 is the last inventory location, if it reaches this point then the player does not have the item anywhere.
player:PrintToPlayer(string.format("Player '%s' does not have item with ID %u", target, itemId));
end
end
else
player:PrintToPlayer(string.format("Player named '%s' not found!", target));
player:PrintToPlayer("@delitem <ID> <player>");
end
end; | gpl-3.0 |
Squeakz/darkstar | scripts/globals/items/ice_brand.lua | 41 | 1056 | -----------------------------------------
-- ID: 16937
-- Ice Brand
-- Additional Effect: Ice Damage
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------
-- onAdditionalEffect Action
-----------------------------------
function onAdditionalEffect(player,target,damage)
local chance = 10;
if (math.random(0,99) >= chance) then
return 0,0,0;
else
local dmg = math.random(7,21);
local params = {};
params.bonusmab = 0;
params.includemab = false;
dmg = addBonusesAbility(player, ELE_ICE, target, dmg, params);
dmg = dmg * applyResistanceAddEffect(player,target,ELE_ICE,0);
dmg = adjustForTarget(target,dmg,ELE_ICE);
dmg = finalMagicNonSpellAdjustments(player,target,ELE_ICE,dmg);
local message = MSGBASIC_ADD_EFFECT_DMG;
if (dmg < 0) then
message = MSGBASIC_ADD_EFFECT_HEAL;
end
return SUBEFFECT_ICE_DAMAGE,message,dmg;
end
end; | gpl-3.0 |
jlcvp/otxserver | data/monster/raids/grorlam.lua | 2 | 2488 | local mType = Game.createMonsterType("Grorlam")
local monster = {}
monster.description = "Grorlam"
monster.experience = 2400
monster.outfit = {
lookType = 205,
lookHead = 0,
lookBody = 0,
lookLegs = 0,
lookFeet = 0,
lookAddons = 0,
lookMount = 0
}
monster.health = 3000
monster.maxHealth = 3000
monster.race = "blood"
monster.corpse = 6005
monster.speed = 240
monster.manaCost = 0
monster.changeTarget = {
interval = 5000,
chance = 3
}
monster.strategiesTarget = {
nearest = 100,
}
monster.flags = {
summonable = false,
attackable = true,
hostile = true,
convinceable = false,
pushable = false,
rewardBoss = false,
illusionable = false,
canPushItems = true,
canPushCreatures = true,
staticAttackChance = 90,
targetDistance = 1,
runHealth = 0,
healthHidden = false,
isBlockable = false,
canWalkOnEnergy = false,
canWalkOnFire = false,
canWalkOnPoison = false
}
monster.light = {
level = 0,
color = 0
}
monster.voices = {
interval = 5000,
chance = 10,
}
monster.loot = {
{id = 3031, chance = 100000, maxCount = 20}, -- gold coin
{id = 3377, chance = 10000}, -- scale armor
{id = 1781, chance = 20000, maxCount = 5}, -- small stone
{id = 3283, chance = 2500} -- carlin sword
}
monster.attacks = {
{name ="melee", interval = 2000, chance = 100, skill = 75, attack = 60},
{name ="combat", interval = 1000, chance = 15, type = COMBAT_PHYSICALDAMAGE, minDamage = -150, maxDamage = -200, range = 7, shootEffect = CONST_ANI_LARGEROCK, target = false}
}
monster.defenses = {
defense = 25,
armor = 15,
{name ="combat", interval = 1000, chance = 25, type = COMBAT_HEALING, minDamage = 100, maxDamage = 150, effect = CONST_ME_MAGIC_BLUE, target = false},
{name ="speed", interval = 1000, chance = 6, speedChange = 270, effect = CONST_ME_MAGIC_RED, target = false, duration = 6000}
}
monster.elements = {
{type = COMBAT_PHYSICALDAMAGE, percent = 30},
{type = COMBAT_ENERGYDAMAGE, percent = 20},
{type = COMBAT_EARTHDAMAGE, percent = 100},
{type = COMBAT_FIREDAMAGE, percent = -10},
{type = COMBAT_LIFEDRAIN, percent = 0},
{type = COMBAT_MANADRAIN, percent = 0},
{type = COMBAT_DROWNDAMAGE, percent = 0},
{type = COMBAT_ICEDAMAGE, percent = 0},
{type = COMBAT_HOLYDAMAGE , percent = 20},
{type = COMBAT_DEATHDAMAGE , percent = -5}
}
monster.immunities = {
{type = "paralyze", condition = true},
{type = "outfit", condition = false},
{type = "invisible", condition = true},
{type = "bleed", condition = false}
}
mType:register(monster)
| gpl-2.0 |
Squeakz/darkstar | scripts/globals/items/bowl_of_pomodoro_sauce.lua | 18 | 1182 | -----------------------------------------
-- ID: 5194
-- Item: Bowl of Pomodoro Sauce
-- Food Effect: 5Min, All Races
-----------------------------------------
-- Intelligence 2
-- Mind 2
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,5194);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_INT, 2);
target:addMod(MOD_MND, 2);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_INT, 2);
target:delMod(MOD_MND, 2);
end;
| gpl-3.0 |
Squeakz/darkstar | scripts/zones/Bostaunieux_Oubliette/Zone.lua | 19 | 2204 | -----------------------------------
--
-- Zone: Bostaunieux_Oubliette (167)
--
-----------------------------------
package.loaded["scripts/zones/Bostaunieux_Oubliette/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Bostaunieux_Oubliette/TextIDs");
require("scripts/globals/zone");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
local tomes = {17461580,17461581,17461582};
SetGroundsTome(tomes);
-- Drexerion the Condemned
SetRespawnTime(17461338, 900, 10800);
-- Phanduron the Condemned
SetRespawnTime(17461343, 900, 10800);
-- Bloodsucker
SetRespawnTime(17461478, 3600, 3600);
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then
player:setPos(99.978,-25.647,72.867,61);
end
return cs;
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
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 |
Squeakz/darkstar | scripts/globals/mobskills/Spirits_Within.lua | 17 | 1747 | ---------------------------------------------
-- Spirits Within
--
-- Description: Delivers an unavoidable attack. Damage varies with HP and TP.
-- Type: Magical/Breath
-- Ignores shadows and most damage reduction.
-- Range: Melee
---------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/utils");
require("scripts/globals/monstertpmoves");
require("scripts/zones/Throne_Room/TextIDs");
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
if (mob:getFamily() == 482) then
target:showText(mob,YOUR_ANSWER);
return 0;
else
return 0;
end;
function onMobWeaponSkill(target, mob, skill)
if (mob:getFamily() == 482) then
target:showText(mob,RETURN_TO_THE_DARKNESS);
else
mob:messageBasic(43, 0, 686+256);
end
local tp = skill:getTP();
local hp = mob:getHP();
local dmg = 0;
-- Should produce 1000 - 3750 @ full HP using the player formula, assuming 8k HP for AA EV.
-- dmg * 2.5, as wiki claims ~2500 at 100% HP, until a better formula comes along.
if tp <= 2000 then -- 1000 - 2000
dmg = math.floor(hp * (math.floor(0.16 * tp) + 16) / 256);
else -- 2001 - 3000
dmg = math.floor(hp * (math.floor(0.72 * tp) - 96) / 256);
end
dmg = dmg * 2.5;
-- Believe it or not, it's been proven to be breath damage.
dmg = target:breathDmgTaken(dmg);
--handling phalanx
dmg = dmg - target:getMod(MOD_PHALANX);
if (dmg < 0) then
return 0;
end
dmg = utils.stoneskin(target, dmg);
if (dmg > 0) then
target:wakeUp();
target:updateEnmityFromDamage(mob,dmg);
end
target:delHP(dmg);
return dmg;
end
end;
| gpl-3.0 |
smartdevicelink/sdl_atf_test_scripts | test_scripts/Security/SSLHandshakeFlow/016_Non-Navi-Predefined_cert_valid_PTU_is_not_started.lua | 1 | 1947 | ---------------------------------------------------------------------------------------------------
-- Issues:
-- https://github.com/smartdevicelink/sdl_core/issues/2190
-- https://github.com/smartdevicelink/sdl_core/issues/2191
---------------------------------------------------------------------------------------------------
--[[ Required Shared libraries ]]
local runner = require('user_modules/script_runner')
local common = require("test_scripts/Security/SSLHandshakeFlow/common")
--[[ Test Configuration ]]
runner.testSettings.isSelfIncluded = false
config.application1.registerAppInterfaceParams.appHMIType = { "DEFAULT" }
local function unregisterApp()
local cid = common.getMobileSession():SendRPC("UnregisterAppInterface", {})
common.getMobileSession():ExpectResponse(cid, { success = true, resultCode = "SUCCESS" })
common.getHMIConnection():ExpectNotification("BasicCommunication.OnAppUnregistered")
end
local function registerApp()
local cid = common.getMobileSession():SendRPC("RegisterAppInterface", common.getConfigAppParams())
common.getMobileSession():ExpectResponse(cid, { success = true, resultCode = "SUCCESS" })
common.getHMIConnection():ExpectNotification("BasicCommunication.OnAppRegistered")
common.getHMIConnection():ExpectNotification("SDL.OnStatusUpdate")
:Times(0)
end
--[[ Scenario ]]
runner.Title("Preconditions")
runner.Step("Clean environment", common.preconditions)
runner.Step("Init SDL certificates", common.initSDLCertificates, { "./files/Security/client_credential.pem" })
runner.Step("Start SDL, HMI, connect Mobile, start Session", common.start)
runner.Title("Test")
runner.Step("Register App", common.registerApp)
runner.Step("PolicyTableUpdate", common.policyTableUpdate)
runner.Step("Disconnect App", unregisterApp)
runner.Step("Connect App PTU is not started", registerApp)
runner.Title("Postconditions")
runner.Step("Stop SDL, clean-up certificates", common.postconditions)
| bsd-3-clause |
cp1337/devland | data/npc/scripts/runes.lua | 1 | 14382 | local focus = 0
local talk_start = 0
local target = 0
local following = false
local attacking = false
function onThingMove(creature, thing, oldpos, oldstackpos)
end
function onCreatureAppear(creature)
end
function onCreatureDisappear(cid, pos)
if focus == cid then
selfSay('Good bye then.')
focus = 0
talk_start = 0
end
end
function onCreatureTurn(creature)
end
function msgcontains(txt, str)
return (string.find(txt, str) and not string.find(txt, '(%w+)' .. str) and not string.find(txt, str .. '(%w+)'))
end
function onCreatureSay(cid, type, msg)
local msg = string.lower(msg)
if msgcontains(msg, 'hi') and focus == 0 and getDistanceToCreature(cid) < 4 then
selfSay('Welcome ' .. getCreatureName(cid) .. '! Whats your need?')
focus = cid
talk_start = os.clock()
TurnToPlayer(cid)
elseif msgcontains(msg, 'hi') and focus ~= cid and getDistanceToCreature(cid) < 4 then
selfSay('Sorry, ' .. getCreatureName(cid) .. '! I talk to you in a minute.')
elseif focus == cid then
talk_start = os.clock()
if msgcontains(msg, 'job') then
selfSay('I am the head alchemist of this City. I keep the secret recipies of our ancestors. Besides, I am selling mana and life fluids,spellbooks, wands, rods and runes.')
-- Main Runes ---------------------------------------------------------------------------------
elseif msgcontains(msg, 'spell rune') then
selfSay('I sell missile runes, explosive runes, field runes, wall runes, bomb runes, healing runes, convince creature rune and chameleon rune.')
elseif msgcontains(msg, 'missile runes') then
selfSay('I can offer you light magic missile runes, heavy magic missile runes and sudden death runes.')
elseif msgcontains(msg, 'explosive runes') then
selfSay('I can offer you fireball runes, great fireball runes and explosion runes.')
elseif msgcontains(msg, 'field runes') then
selfSay('I can offer you fire field runes, energy field runes, poison field runes and destroy field runes.')
elseif msgcontains(msg, 'wall runes') then
selfSay('I can offer you fire wall runes, energy wall runes and poison wall runes.')
elseif msgcontains(msg, 'bomb runes') then
selfSay('I can offer you firebomb runes.')
elseif msgcontains(msg, 'healing runes') then
selfSay('I can offer you antidote runes, intense healing runes and ultimate healing runes.')
-- Runes ---------------------------------------------------------------------------------
elseif msgcontains(msg, 'light magic missile') then
count = getCount(msg)
cost = count*10
talk_state = 20
if count >= 2 then
selfSay('Do you want to buy ' .. count .. ' light magic missile runes for ' .. cost .. '.')
else
selfSay('Do you want to buy a light magic missile rune for 10 gold?')
end
elseif msgcontains(msg, 'heavy magic missile') then
count = getCount(msg)
cost = count*20
talk_state = 21
if count >= 2 then
selfSay('Do you want to buy ' .. count .. ' heavy magic missile runes for ' .. cost .. '.')
else
selfSay('Do you want to buy a heavy magic missile rune for 20 gold?')
end
elseif msgcontains(msg, 'sudden death') then
count = getCount(msg)
cost = count*230
talk_state = 22
if count >= 2 then
selfSay('Do you want to buy ' .. count .. ' sudden death runes for ' .. cost .. '.')
else
selfSay('Do you want to buy a sudden death rune for 230 gold?')
end
elseif msgcontains(msg, 'great fireball') then
count = getCount(msg)
cost = count*45
talk_state = 23
if count >= 2 then
selfSay('Do you want to buy ' .. count .. ' great fireball runes for ' .. cost .. '.')
else
selfSay('Do you want to buy a great fireball rune for 45 gold?')
end
elseif msgcontains(msg, 'explosion') then
count = getCount(msg)
cost = count*60
talk_state = 24
if count >= 2 then
selfSay('Do you want to buy ' .. count .. ' explosion runes for ' .. cost .. '.')
else
selfSay('Do you want to buy a explosion rune for 60 gold?')
end
elseif msgcontains(msg, 'fire field') then
count = getCount(msg)
cost = count*20
talk_state = 25
if count >= 2 then
selfSay('Do you want to buy ' .. count .. ' fire field runes for ' .. cost .. '.')
else
selfSay('Do you want to buy a fire field rune for 20 gold?')
end
elseif msgcontains(msg, 'energy field') then
count = getCount(msg)
cost = count*30
talk_state = 26
if count >= 2 then
selfSay('Do you want to buy ' .. count .. ' energy field runes for ' .. cost .. '.')
else
selfSay('Do you want to buy a energy field rune for 30 gold?')
end
elseif msgcontains(msg, 'poison field') then
count = getCount(msg)
cost = count*15
talk_state = 27
if count >= 2 then
selfSay('Do you want to buy ' .. count .. ' poison field runes for ' .. cost .. '.')
else
selfSay('Do you want to buy a poison field rune for 15 gold?')
end
elseif msgcontains(msg, 'destroy field') then
count = getCount(msg)
cost = count*20
talk_state = 28
if count >= 2 then
selfSay('Do you want to buy ' .. count .. ' destroy field runes for ' .. cost .. '.')
else
selfSay('Do you want to buy a destroy field rune for 20 gold?')
end
elseif msgcontains(msg, 'fire wall') then
count = getCount(msg)
cost = count*45
talk_state = 29
if count >= 2 then
selfSay('Do you want to buy ' .. count .. ' fire wall runes for ' .. cost .. '.')
else
selfSay('Do you want to buy a fire wall rune for 45 gold?')
end
elseif msgcontains(msg, 'energy wall') then
count = getCount(msg)
cost = count*60
talk_state = 30
if count >= 2 then
selfSay('Do you want to buy ' .. count .. ' energy wall runes for ' .. cost .. '.')
else
selfSay('Do you want to buy a energy wall rune for 60 gold?')
end
elseif msgcontains(msg, 'poison wall') then
count = getCount(msg)
cost = count*35
talk_state = 31
if count >= 2 then
selfSay('Do you want to buy ' .. count .. ' poison wall runes for ' .. cost .. '.')
else
selfSay('Do you want to buy a poison wall rune for 35 gold?')
end
elseif msgcontains(msg, 'antidote') then
count = getCount(msg)
cost = count*45
talk_state = 32
if count >= 2 then
selfSay('Do you want to buy ' .. count .. ' antidote runes for ' .. cost .. '.')
else
selfSay('Do you want to buy a antidote rune for 45 gold?')
end
elseif msgcontains(msg, 'intense healing') then
count = getCount(msg)
cost = count*65
talk_state = 33
if count >= 2 then
selfSay('Do you want to buy ' .. count .. ' intense healing runes for ' .. cost .. '.')
else
selfSay('Do you want to buy a intense healing rune for 65 gold?')
end
elseif msgcontains(msg, 'ultimate healing') then
count = getCount(msg)
cost = count*130
talk_state = 34
if count >= 2 then
selfSay('Do you want to buy ' .. count .. ' ultimate healing runes for ' .. cost .. '.')
else
selfSay('Do you want to buy a ultimate healing rune for 130 gold?')
end
elseif msgcontains(msg, 'blank') then
count = getCount(msg)
cost = count*10
talk_state = 35
if count >= 2 then
selfSay('Do you want to buy ' .. count .. ' blank runes for ' .. cost .. '.')
else
selfSay('Do you want to buy a blank rune for 10 gold?')
end
-- Wands and Rods --------------------------------------------------------------------------
elseif msgcontains(msg, 'Wand of Vortex') then
talk_state = 50
selfSay('This wand is only for sorcerers of level 7 and above. Would you like to buy a wand of vortex for 500 gold?')
elseif msgcontains(msg, 'Wand of Dragonbreath') then
talk_state = 51
selfSay('This wand is only for sorcerers of level 13 and above. Would you like to buy a wand of dragonbreath for 1000 gold?')
elseif msgcontains(msg, 'Wand of Plague') then
talk_state = 52
selfSay('This wand is only for sorcerers of level 19 and above. Would you like to buy a wand of plague for 5000 gold?')
elseif msgcontains(msg, 'Wand of Cosmic Energy') then
talk_state = 53
selfSay('This wand is only for sorcerers of level 26 and above. Would you like to buy a wand of cosmic energy for 10000 gold?')
elseif msgcontains(msg, 'Wand of Inferno') then
selfSay('Sorry, this wand contains magic far too powerful and we are afraid to store it here. I heard they have a few of these at the Premium academy though.')
elseif msgcontains(msg, 'Snakebite Rod') then
talk_state = 55
selfSay('This rod is only for druids of level 7 and above. Would you like to buy a snakebite rod for 500 gold?')
elseif msgcontains(msg, 'Moonlight Rod') then
talk_state = 56
selfSay('This rod is only for druids of level 13 and above. Would you like to buy a moonlight rod for 1000 gold?')
elseif msgcontains(msg, 'Volcanic Rod') then
talk_state = 57
selfSay('This rod is only for druids of level 19 and above. Would you like to buy a volcanic rod for 5000 gold?')
elseif msgcontains(msg, 'Quagmire Rod') then
talk_state = 58
selfSay('This rod is only for druids of level 26 and above. Would you like to buy a quagmire rod for 10000 gold?')
elseif msgcontains(msg, 'Tempest Rod') then
selfSay('Sorry, this rod contains magic far too powerful and we are afraid to store it here. I heard they have a few of these at the Premium academy though.')
elseif msgcontains(msg, 'wand') or msgcontains(msg, 'wands') then
selfSay('Wands can be wielded by sorcerers only and have a certain level requirement. There are five different wands, would you like to hear about them?')
talk_state = 2
elseif msgcontains(msg, 'rod') or msgcontains(msg, 'rods') then
selfSay('Rods can be wielded by druids only and have a certain level requirement. There are five different rods, would you like to hear about them?')
talk_state = 3
-- Others --------------------------------------------------------------------------------
elseif msgcontains(msg, 'mana fluid') or msgcontains(msg, 'mana fluids') then
count = getCount(msg)
cost = count*55
talk_state = 36
if count >= 2 then
selfSay('Do you want to buy ' .. count .. ' mana fluids for ' .. cost .. '.')
else
selfSay('Do you want to buy mana fluid for 55 gold')
end
elseif msgcontains(msg, 'life fluid') or msgcontains(msg, 'life fluids') then
count = getCount(msg)
cost = count*60
talk_state = 37
if count >= 2 then
selfSay('Do you want to buy ' .. count .. ' life fluids for ' .. cost .. '.')
else
selfSay('Do you want to buy life fluid for 60 gold')
end
elseif msgcontains(msg, 'spellbook') then
talk_state = 38
selfSay('A spellbook is a nice tool for beginners. Do you want to buy one for 150 gold?')
-- Yes -----------------------------------------------------------------------------------
elseif msgcontains(msg, 'yes') then
if talk_state == 2 then
selfSay('The names of the wands are \'Wand of Vortex\', \'Wand of Dragonbreath\', \'Wand of Plague\', \'Wand of Cosmic Energy\' and \'Wand ofInferno\'. Which one would you like to buy?')
elseif talk_state == 3 then
selfSay('The names of the rods are \'Snakebite Rod\', \'Moonlight Rod\', \'Volcanic Rod\', \'Quagmire Rod\', and \'Tempest Rod\'. Which one would you like to buy?')
elseif talk_state == 20 then
buy(cid,2287,count,10)
elseif talk_state == 21 then
buy(cid,2311,count,20)
elseif talk_state == 22 then
buy(cid,2268,count,230)
elseif talk_state == 23 then
buy(cid,2304,count,45)
elseif talk_state == 24 then
buy(cid,2313,count,60)
elseif talk_state == 25 then
buy(cid,2301,count,20)
elseif talk_state == 26 then
buy(cid,2277,count,30)
elseif talk_state == 27 then
buy(cid,2285,count,15)
elseif talk_state == 28 then
buy(cid,2261,count,20)
elseif talk_state == 29 then
buy(cid,2303,count,45)
elseif talk_state == 30 then
buy(cid,2279,count,60)
elseif talk_state == 31 then
buy(cid,2289,count,35)
elseif talk_state == 32 then
buy(cid,2266,count,45)
elseif talk_state == 33 then
buy(cid,2265,count,65)
elseif talk_state == 34 then
buy(cid,2273,count,130)
elseif talk_state == 35 then
buy(cid,2260,count,10)
elseif talk_state == 36 then
buyFluidContainer(cid,2006,count,55,7)
elseif talk_state == 37 then
buyFluidContainer(cid,2006,count,60,10)
elseif talk_state == 38 then
buy(cid,2175,1,150)
elseif talk_state == 50 then
buy(cid,2190,1,500)
elseif talk_state == 51 then
buy(cid,2191,1,1000)
elseif talk_state == 52 then
buy(cid,2188,1,5000)
elseif talk_state == 53 then
buy(cid,2189,1,10000)
elseif talk_state == 55 then
buy(cid,2182,1,500)
elseif talk_state == 56 then
buy(cid,2186,1,1000)
elseif talk_state == 37 then
buy(cid,2185,1,5000)
elseif talk_state == 58 then
buy(cid,2181,1,10000)
end
-- NO ------------------------------------------------------------------------------------
elseif msgcontains(msg, 'no') then
if talk_state >= 2 then
selfSay('Ok, maybe next time.')
else
end
-- END -----------------------------------------------------------------------------------
elseif string.find(msg, '(%a*)bye(%a*)') and getDistanceToCreature(cid) < 4 then
selfSay('Good bye.')
focus = 0
talk_start = 0
end
end
end
function onCreatureChangeOutfit(creature)
end
function onThink()
if (os.clock() - talk_start) > 30 then
if focus > 0 then
selfSay('Next Please...')
end
focus = 0
end
if focus ~= 0 then
if getDistanceToCreature(focus) > 5 then
selfSay('Good bye then.')
focus = 0
end
end
end
| gpl-2.0 |
satanoff/testantispam | plugins/danbooru.lua | 616 | 1750 | do
local URL = "http://danbooru.donmai.us"
local URL_NEW = "/posts.json"
local URL_POP = "/explore/posts/popular.json"
local scale_day = "?scale=day"
local scale_week = "?scale=week"
local scale_month = "?scale=month"
local function get_post(url)
local b, c, h = http.request(url)
if c ~= 200 then return nil end
local posts = json:decode(b)
return posts[math.random(#posts)]
end
local function run(msg, matches)
local url = URL
if matches[1] == "!danbooru" then
url = url .. URL_NEW
else
url = url .. URL_POP
if matches[1] == "d" then
url = url .. scale_day
elseif matches[1] == "w" then
url = url .. scale_week
elseif matches[1] == "m" then
url = url .. scale_month
end
end
local post = get_post(url)
if post then
vardump(post)
local img = URL .. post.large_file_url
send_photo_from_url(get_receiver(msg), img)
local txt = ''
if post.tag_string_artist ~= '' then
txt = 'Artist: ' .. post.tag_string_artist .. '\n'
end
if post.tag_string_character ~= '' then
txt = txt .. 'Character: ' .. post.tag_string_character .. '\n'
end
if post.file_size ~= '' then
txt = txt .. '[' .. math.ceil(post.file_size/1000) .. 'kb] ' .. URL .. post.file_url
end
return txt
end
end
return {
description = "Gets a random fresh or popular image from Danbooru",
usage = {
"!danbooru - gets a random fresh image from Danbooru 🔞",
"!danboorud - random daily popular image 🔞",
"!danbooruw - random weekly popular image 🔞",
"!danboorum - random monthly popular image 🔞"
},
patterns = {
"^!danbooru$",
"^!danbooru ?(d)$",
"^!danbooru ?(w)$",
"^!danbooru ?(m)$"
},
run = run
}
end | gpl-2.0 |
yeewang/openwrt-luci | applications/luci-pbx/luasrc/model/cbi/pbx-google.lua | 146 | 5490 | --[[
Copyright 2011 Iordan Iordanov <iiordanov (AT) gmail.com>
This file is part of luci-pbx.
luci-pbx is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
luci-pbx 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 luci-pbx. If not, see <http://www.gnu.org/licenses/>.
]]--
if nixio.fs.access("/etc/init.d/asterisk") then
server = "asterisk"
elseif nixio.fs.access("/etc/init.d/freeswitch") then
server = "freeswitch"
else
server = ""
end
modulename = "pbx-google"
googlemodulename = "pbx-google"
defaultstatus = "dnd"
defaultstatusmessage = "PBX online, may lose messages"
m = Map (modulename, translate("Google Accounts"),
translate("This is where you set up your Google (Talk and Voice) Accounts, in order to start \
using them for dialing and receiving calls (voice chat and real phone calls). Please \
make at least one voice call using the Google Talk plugin installable through the \
GMail interface, and then log out from your account everywhere. Click \"Add\" \
to add as many accounts as you wish."))
-- Recreate the config, and restart services after changes are commited to the configuration.
function m.on_after_commit(self)
-- Create a field "name" for each account that identifies the account in the backend.
commit = false
m.uci:foreach(modulename, "gtalk_jabber",
function(s1)
if s1.username ~= nil then
name=string.gsub(s1.username, "%W", "_")
if s1.name ~= name then
m.uci:set(modulename, s1['.name'], "name", name)
commit = true
end
end
end)
if commit == true then m.uci:commit(modulename) end
luci.sys.call("/etc/init.d/pbx-" .. server .. " restart 1\>/dev/null 2\>/dev/null")
luci.sys.call("/etc/init.d/asterisk restart 1\>/dev/null 2\>/dev/null")
end
-----------------------------------------------------------------------------
s = m:section(TypedSection, "gtalk_jabber", translate("Google Voice/Talk Accounts"))
s.anonymous = true
s.addremove = true
s:option(Value, "username", translate("Email"))
pwd = s:option(Value, "secret", translate("Password"),
translate("When your password is saved, it disappears from this field and is not displayed \
for your protection. The previously saved password will be changed only when you \
enter a value different from the saved one."))
pwd.password = true
pwd.rmempty = false
-- We skip reading off the saved value and return nothing.
function pwd.cfgvalue(self, section)
return ""
end
-- We check the entered value against the saved one, and only write if the entered value is
-- something other than the empty string, and it differes from the saved value.
function pwd.write(self, section, value)
local orig_pwd = m:get(section, self.option)
if value and #value > 0 and orig_pwd ~= value then
Value.write(self, section, value)
end
end
p = s:option(ListValue, "register",
translate("Enable Incoming Calls (set Status below)"),
translate("When somebody starts voice chat with your GTalk account or calls the GVoice, \
number (if you have Google Voice), the call will be forwarded to any users \
that are online (registered using a SIP device or softphone) and permitted to \
receive the call. If you have Google Voice, you must go to your GVoice settings and \
forward calls to Google chat in order to actually receive calls made to your \
GVoice number. If you have trouble receiving calls from GVoice, experiment \
with the Call Screening option in your GVoice Settings. Finally, make sure no other \
client is online with this account (browser in gmail, mobile/desktop Google Talk \
App) as it may interfere."))
p:value("yes", translate("Yes"))
p:value("no", translate("No"))
p.default = "yes"
p = s:option(ListValue, "make_outgoing_calls", translate("Enable Outgoing Calls"),
translate("Use this account to make outgoing calls as configured in the \"Call Routing\" section."))
p:value("yes", translate("Yes"))
p:value("no", translate("No"))
p.default = "yes"
st = s:option(ListValue, "status", translate("Google Talk Status"))
st:depends("register", "yes")
st:value("dnd", translate("Do Not Disturb"))
st:value("away", translate("Away"))
st:value("available", translate("Available"))
st.default = defaultstatus
stm = s:option(Value, "statusmessage", translate("Google Talk Status Message"),
translate("Avoid using anything but alpha-numeric characters, space, comma, and period."))
stm:depends("register", "yes")
stm.default = defaultstatusmessage
return m
| apache-2.0 |
smartdevicelink/sdl_atf_test_scripts | user_modules/IsReady_Template/testCasesForVR_IsReady.lua | 1 | 8732 | local testCasesForVR_IsReady = {}
require('atf.util')
local events = require("events")
--[[@InitHMI_onReady_without_VR_IsReady_available_false: replace original InitHMIOnReady from connecttest
--! without expect VR.IsReady
--! @parameters: exp_occur - times to wait VR.<<RPC>>
--! in case VR.IsReady(available = false), exp_occur = 0, else exp_occur = 1
--]]
function testCasesForVR_IsReady.InitHMI_onReady_without_VR_IsReady(self, exp_occur)
if(exp_occur == nil) then exp_occur = 0 end
local function ExpectRequest(name, mandatory, params)
local event = events.Event()
event.level = 2
event.matches = function(_, data) return data.method == name end
return
EXPECT_HMIEVENT(event, name)
:Times(mandatory and 1 or AnyNumber())
:Do(function(_, data)
self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", params)
end)
end
ExpectRequest("BasicCommunication.MixingAudioSupported",
true,
{ attenuatedSupported = true })
ExpectRequest("BasicCommunication.GetSystemInfo", false,
{
ccpu_version = "ccpu_version",
language = "EN-US",
wersCountryCode = "wersCountryCode"
})
ExpectRequest("UI.GetLanguage", true, { language = "EN-US" })
:Times(exp_occur)
:Timeout(20000)
ExpectRequest("VR.GetLanguage", true, { language = "EN-US" })
ExpectRequest("TTS.GetLanguage", true, { language = "EN-US" })
ExpectRequest("UI.ChangeRegistration", false, { }):Pin()
ExpectRequest("TTS.SetGlobalProperties", false, { }):Pin()
ExpectRequest("BasicCommunication.UpdateDeviceList", false, { }):Pin()
ExpectRequest("VR.ChangeRegistration", false, { }):Pin()
ExpectRequest("TTS.ChangeRegistration", false, { }):Pin()
ExpectRequest("VR.GetSupportedLanguages", true, {
languages = {
"EN-US","ES-MX","FR-CA","DE-DE","ES-ES","EN-GB","RU-RU",
"TR-TR","PL-PL","FR-FR","IT-IT","SV-SE","PT-PT","NL-NL",
"ZH-TW","JA-JP","AR-SA","KO-KR","PT-BR","CS-CZ","DA-DK",
"NO-NO","NL-BE","EL-GR","HU-HU","FI-FI","SK-SK" }
})
ExpectRequest("TTS.GetSupportedLanguages", true, {
languages = {
"EN-US","ES-MX","FR-CA","DE-DE","ES-ES","EN-GB","RU-RU",
"TR-TR","PL-PL","FR-FR","IT-IT","SV-SE","PT-PT","NL-NL",
"ZH-TW","JA-JP","AR-SA","KO-KR","PT-BR","CS-CZ","DA-DK",
"NO-NO","NL-BE","EL-GR","HU-HU","FI-FI","SK-SK" }
})
ExpectRequest("UI.GetSupportedLanguages", true, {
languages = {
"EN-US","ES-MX","FR-CA","DE-DE","ES-ES","EN-GB","RU-RU",
"TR-TR","PL-PL","FR-FR","IT-IT","SV-SE","PT-PT","NL-NL",
"ZH-TW","JA-JP","AR-SA","KO-KR","PT-BR","CS-CZ","DA-DK",
"NO-NO","NL-BE","EL-GR","HU-HU","FI-FI","SK-SK" }
})
:Times(exp_occur)
:Timeout(20000)
ExpectRequest("VehicleInfo.GetVehicleType", true, {
vehicleType =
{
make = "Ford",
model = "Fiesta",
modelYear = "2013",
trim = "SE"
}
})
ExpectRequest("VehicleInfo.GetVehicleData", true, { vin = "52-452-52-752" })
local function button_capability(name, shortPressAvailable, longPressAvailable, upDownAvailable)
return
{
name = name,
shortPressAvailable = shortPressAvailable == nil and true or shortPressAvailable,
longPressAvailable = longPressAvailable == nil and true or longPressAvailable,
upDownAvailable = upDownAvailable == nil and true or upDownAvailable
}
end
local buttons_capabilities =
{
capabilities =
{
button_capability("PRESET_0"),
button_capability("PRESET_1"),
button_capability("PRESET_2"),
button_capability("PRESET_3"),
button_capability("PRESET_4"),
button_capability("PRESET_5"),
button_capability("PRESET_6"),
button_capability("PRESET_7"),
button_capability("PRESET_8"),
button_capability("PRESET_9"),
button_capability("OK", true, false, true),
button_capability("SEEKLEFT"),
button_capability("SEEKRIGHT"),
button_capability("TUNEUP"),
button_capability("TUNEDOWN")
},
presetBankCapabilities = { onScreenPresetsAvailable = true }
}
ExpectRequest("Buttons.GetCapabilities", true, buttons_capabilities)
ExpectRequest("VR.GetCapabilities", true, { vrCapabilities = { "TEXT" } })
ExpectRequest("TTS.GetCapabilities", true, {
speechCapabilities = { "TEXT", "PRE_RECORDED" },
prerecordedSpeechCapabilities =
{
"HELP_JINGLE",
"INITIAL_JINGLE",
"LISTEN_JINGLE",
"POSITIVE_JINGLE",
"NEGATIVE_JINGLE"
}
})
local function text_field(name, characterSet, width, rows)
return
{
name = name,
characterSet = characterSet or "UTF_8",
width = width or 500,
rows = rows or 1
}
end
local function image_field(name, width, height)
return
{
name = name,
imageTypeSupported =
{
"GRAPHIC_BMP",
"GRAPHIC_JPEG",
"GRAPHIC_PNG"
},
imageResolution =
{
resolutionWidth = width or 64,
resolutionHeight = height or 64
}
}
end
ExpectRequest("UI.GetCapabilities", true, {
displayCapabilities =
{
displayType = "GEN2_8_DMA",
displayName = "GENERIC_DISPLAY",
textFields =
{
text_field("mainField1"),
text_field("mainField2"),
text_field("mainField3"),
text_field("mainField4"),
text_field("statusBar"),
text_field("mediaClock"),
text_field("mediaTrack"),
text_field("alertText1"),
text_field("alertText2"),
text_field("alertText3"),
text_field("scrollableMessageBody"),
text_field("initialInteractionText"),
text_field("navigationText1"),
text_field("navigationText2"),
text_field("ETA"),
text_field("totalDistance"),
text_field("audioPassThruDisplayText1"),
text_field("audioPassThruDisplayText2"),
text_field("sliderHeader"),
text_field("sliderFooter"),
text_field("menuName"),
text_field("secondaryText"),
text_field("tertiaryText"),
text_field("timeToDestination"),
text_field("turnText"),
text_field("menuTitle"),
text_field("locationName"),
text_field("locationDescription"),
text_field("addressLines"),
text_field("phoneNumber")
},
imageFields =
{
image_field("softButtonImage"),
image_field("choiceImage"),
image_field("choiceSecondaryImage"),
image_field("vrHelpItem"),
image_field("turnIcon"),
image_field("menuIcon"),
image_field("cmdIcon"),
image_field("showConstantTBTIcon"),
image_field("locationImage")
},
mediaClockFormats =
{
"CLOCK1",
"CLOCK2",
"CLOCK3",
"CLOCKTEXT1",
"CLOCKTEXT2",
"CLOCKTEXT3",
"CLOCKTEXT4"
},
graphicSupported = true,
imageCapabilities = { "DYNAMIC", "STATIC" },
templatesAvailable = { "TEMPLATE" },
screenParams =
{
resolution = { resolutionWidth = 800, resolutionHeight = 480 },
touchEventAvailable =
{
pressAvailable = true,
multiTouchAvailable = true,
doublePressAvailable = false
}
},
numCustomPresetsAvailable = 10
},
audioPassThruCapabilities =
{
samplingRate = "44KHZ",
bitsPerSample = "8_BIT",
audioType = "PCM"
},
hmiZoneCapabilities = "FRONT",
softButtonCapabilities =
{
{
shortPressAvailable = true,
longPressAvailable = true,
upDownAvailable = true,
imageSupported = true
}
}
})
:Times(exp_occur)
:Timeout(20000)
--ExpectRequest("VR.IsReady", true, { available = true })
ExpectRequest("TTS.IsReady", true, { available = true })
ExpectRequest("UI.IsReady", true, { available = true })
ExpectRequest("Navigation.IsReady", true, { available = true })
ExpectRequest("VehicleInfo.IsReady", true, { available = true })
self.applications = { }
ExpectRequest("BasicCommunication.UpdateAppList", false, { })
:Pin()
:Do(function(_, data)
self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", { })
self.applications = { }
for _, app in pairs(data.params.applications) do
self.applications[app.appName] = app.appID
end
end)
self.hmiConnection:SendNotification("BasicCommunication.OnReady")
end
return testCasesForVR_IsReady | bsd-3-clause |
Squeakz/darkstar | scripts/zones/Buburimu_Peninsula/npcs/Stone_Monument.lua | 13 | 1284 | -----------------------------------
-- Area: Buburimu Peninsula
-- NPC: Stone Monument
-- Involved in quest "An Explorer's Footsteps"
-- @pos 320.755 -4.000 368.722 118
-----------------------------------
package.loaded["scripts/zones/Buburimu_Peninsula/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Buburimu_Peninsula/TextIDs");
-----------------------------------
-- onTrigger
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0384);
end;
-----------------------------------
-- onTrade
-----------------------------------
function onTrade(player,npc,trade)
if (trade:getItemCount() == 1 and trade:hasItemQty(571,1)) then
player:tradeComplete();
player:addItem(570);
player:messageSpecial(ITEM_OBTAINED,570);
player:setVar("anExplorer-CurrentTablet",0x02000);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
Adirelle/oUF | elements/raidtargetindicator.lua | 10 | 2510 | --[[
# Element: Raid Target Indicator
Handles the visibility and updating of an indicator based on the unit's raid target assignment.
## Widget
RaidTargetIndicator - A `Texture` used to display the raid target icon.
## Notes
A default texture will be applied if the widget is a Texture and doesn't have a texture set.
## Examples
-- Position and size
local RaidTargetIndicator = self:CreateTexture(nil, 'OVERLAY')
RaidTargetIndicator:SetSize(16, 16)
RaidTargetIndicator:SetPoint('TOPRIGHT', self)
-- Register it with oUF
self.RaidTargetIndicator = RaidTargetIndicator
--]]
local _, ns = ...
local oUF = ns.oUF
local GetRaidTargetIndex = GetRaidTargetIndex
local SetRaidTargetIconTexture = SetRaidTargetIconTexture
local function Update(self, event)
local element = self.RaidTargetIndicator
--[[ Callback: RaidTargetIndicator:PreUpdate()
Called before the element has been updated.
* self - the RaidTargetIndicator element
--]]
if(element.PreUpdate) then
element:PreUpdate()
end
local index = GetRaidTargetIndex(self.unit)
if(index) then
SetRaidTargetIconTexture(element, index)
element:Show()
else
element:Hide()
end
--[[ Callback: RaidTargetIndicator:PostUpdate(index)
Called after the element has been updated.
* self - the RaidTargetIndicator element
* index - the index of the raid target marker (number?)[1-8]
--]]
if(element.PostUpdate) then
return element:PostUpdate(index)
end
end
local function Path(self, ...)
--[[ Override: RaidTargetIndicator.Override(self, event)
Used to completely override the internal update function.
* self - the parent object
* event - the event triggering the update (string)
--]]
return (self.RaidTargetIndicator.Override or Update) (self, ...)
end
local function ForceUpdate(element)
if(not element.__owner.unit) then return end
return Path(element.__owner, 'ForceUpdate')
end
local function Enable(self)
local element = self.RaidTargetIndicator
if(element) then
element.__owner = self
element.ForceUpdate = ForceUpdate
self:RegisterEvent('RAID_TARGET_UPDATE', Path, true)
if(element:IsObjectType('Texture') and not element:GetTexture()) then
element:SetTexture([[Interface\TargetingFrame\UI-RaidTargetingIcons]])
end
return true
end
end
local function Disable(self)
local element = self.RaidTargetIndicator
if(element) then
element:Hide()
self:UnregisterEvent('RAID_TARGET_UPDATE', Path)
end
end
oUF:AddElement('RaidTargetIndicator', Path, Enable, Disable)
| mit |
teto/home | config/nvim/lua/init-manual.lua | 1 | 82597 | -- vim: set noet fdm=marker fenc=utf-8 ff=unix sts=0 sw=4 ts=4 :
-- https://github.com/nanotee/nvim-lua-guide#using-meta-accessors
-- https://www.reddit.com/r/neovim/comments/o8dlwg/how_to_append_to_an_option_in_lua/
-- local configs = require'nvim_lsp/configs'
local has_telescope, telescope = pcall(require, 'telescope')
local has_fzf_lua, _ = pcall(require, 'fzf-lua')
-- my treesitter config
local myMenu = require('teto.menu')
-- local packerCfg =
local packer = require('packer')
local use, _ = packer.use, packer.use_rocks
local nnoremap = vim.keymap.set
local map = vim.keymap.set
-- HOW TO TEST our fork of plenary
-- vim.opt.rtp:prepend(os.getenv("HOME").."/neovim/plenary.nvim")
-- local reload = require'plenary.reload'
-- reload.reload_module('plenary')
-- require'plenary'
vim.g.mapleader = ' '
vim.g.maplocalleader = ' '
vim.g.matchparen = 0
vim.g.mousemoveevent = 1
packer.init({
autoremove = false,
})
-- vim.cmd([[
-- augroup packer_user_config
-- autocmd!
-- autocmd BufWritePost /home/teto/config/nvim/init-manual.lua source <afile> | PackerCompile
-- augroup end
-- ]])
-- local function file_exists(name)
-- local f=io.open(name,"r")
-- if f~=nil then io.close(f) return true else return false end
-- end
-- main config {{{
-- vim.opt.splitbelow = true -- on horizontal splits
vim.opt.splitright = true -- on vertical split
vim.opt.title = true -- vim will change terminal title
-- look at :h statusline to see the available 'items'
-- to count the number of buffer
-- echo len(filter(range(1, bufnr('$')), 'buflisted(v:val)'))
-- let &titlestring=" %t %{len(filter(range(1, bufnr('$')), 'buflisted(v:val)')) } - NVIM"
vim.opt.titlestring = "%{getpid().':'.getcwd()}"
-- Indentation {{{
vim.opt.tabstop = 4 -- a tab takes 4 characters (local to buffer) abrege en ts
vim.opt.shiftwidth = 4 -- Number of spaces to use per step of (auto)indent.
-- set smarttab -- when inserting tab in front a line, use shiftwidth
-- vim.opt.smartindent = false -- might need to disable ?
-- vim.opt.cindent = true
-- set cinkeys-=0# " list of keys that cause reindenting in insert mode
-- set indentkeys-=0#
vim.opt.softtabstop = 0 -- inserts a mix of <Tab> and spaces, 0 disablres it
-- "set expandtab " replace <Tab with spaces
-- }}}
vim.opt.showmatch = true
vim.opt.showcmd = true
vim.opt.showfulltag = true
vim.opt.hidden = true -- you can open a new buffer even if current is unsaved (error E37) =
vim.opt.shiftround = true -- round indent to multiple of 'shiftwidth'
-- Use visual bell instead of beeping when doing something wrong
vim.opt.visualbell = true
-- easier to test visualbell with it
vim.opt.errorbells = true
-- start scrolling before reaching end of screen in order to keep more context
-- set it to a big value
vim.opt.scrolloff = 2
-- inverts the meaning of g in substitution, ie with gdefault, change all occurences
vim.opt.gdefault = true
vim.opt.cpoptions = 'aABceFsn' -- vi ComPatibility options
-- " should not be a default ?
-- set cpoptions-=_
-- vim.g.vimsyn_embed = 'lP' -- support embedded lua, python and ruby
-- don't syntax-highlight long lines
vim.opt.synmaxcol = 300
vim.g.did_install_default_menus = 1 -- avoid stupid menu.vim (saves ~100ms)
vim.o.swapfile = false
vim.opt.number = true
vim.opt.relativenumber = true
vim.o.laststatus = 3
-- vim.opt.conceallevel = 2
vim.opt.concealcursor = 'nc'
vim.opt.showmode = false -- Show the current mode on command line
vim.opt.cursorline = true -- highlight cursor line
vim.opt.termguicolors = true
-- set noautoread " to prevent from interfering with our plugin
-- set breakat=80 " characters at which wrap can break line
vim.opt.wrap = true
vim.opt.linebreak = true -- better display (makes sense only with wrap)
vim.opt.breakindent = true -- preserve or add indentation on wrap
--
vim.opt.modeline = true
vim.opt.modelines = 4 -- number of lines checked
vim.opt.backspace = { 'indent', 'eol', 'start' }
-- Search parameters {{{
vim.opt.hlsearch = true -- highlight search terms
vim.opt.incsearch = true -- show search matches as you type
vim.opt.ignorecase = true -- ignore case when searching
vim.opt.smartcase = true -- take case into account if search entry has capitals in it
vim.opt.wrapscan = true -- prevent from going back to the beginning of the file
vim.opt.inccommand = 'nosplit'
vim.opt.mouse = 'a'
-- https://github.com/neovim/neovim/issues/14921
vim.opt.mousemodel = 'popup_setpos'
vim.opt.signcolumn = 'auto:3'
--set shada=!,'50,<1000,s100,:0,n/home/teto/.cache/nvim/shada
-- added 'n' to defaults to allow wrapping lines to overlap with numbers
-- n => ? used for wrapped lines as well
-- vim.opt.matchpairs+=<:> -- Characters for which % should work
-- TODO to use j/k over
vim.opt.whichwrap = vim.opt.whichwrap + '<,>,h,l'
-- nnoremap <Leader>/ :set hlsearch! hls?<CR> " toggle search highlighting
-- }}}
-- folding config {{{
-- " block,hor,mark,percent,quickfix,search,tag,undo
-- " set foldopen+=all " specifies commands for which folds should open
-- " set foldclose=all
-- "set foldtext=
vim.opt.fillchars = vim.opt.fillchars + 'foldopen:▾,foldsep:│,foldclose:▸'
vim.opt.fillchars = vim.opt.fillchars + 'msgsep:‾'
vim.opt.fillchars = vim.opt.fillchars + 'diff: ' -- \
-- hi MsgSeparator ctermbg=black ctermfg=white
-- " hi DiffDelete guibg=red
-- }}}
-- default behavior for diff=filler,vertical
vim.opt.diffopt = 'filler,vertical'
-- neovim > change to default ?
vim.opt.diffopt:append('hiddenoff')
vim.opt.diffopt:append('iwhiteall')
vim.opt.diffopt:append('internal,algorithm:patience')
vim.opt.undofile = true
-- let undos persist across open/close
vim.opt.undodir = vim.fn.stdpath('data') .. '/undo/'
vim.opt.sessionoptions:remove('terminal')
vim.opt.sessionoptions:remove('help')
--}}}
-- :tnoremap <Esc> <C-\><C-n>
map('t', '<Esc>', '<C-\\><C-n>')
-- nnoremap{ "n", "<C-N><C-N>", function () vim.opt.invnumber end }
-- clipboard {{{
-- X clipboard gets aliased to +
vim.opt.clipboard = 'unnamedplus'
-- copy to external clipboard
-- nnoremap({'n', 'gp', '"+p' })
-- nnoremap({'n', 'gy', '"+y' })
-- }}}
-- wildmenu completion
-- TODO must be number
-- vim.opt.wildchar=("<Tab>"):byte()
-- display a menu when need to complete a command
-- list:longest, " list breaks the pum
vim.opt.wildmode = { 'longest', 'list' } -- longest,list' => fills out longest then show list
-- set wildoptions+=pum
-- TODO ajouter sur le ticket nix
vim.g.hoogle_fzf_cache_file = vim.fn.stdpath('cache') .. '/hoogle_cache.json'
vim.opt.wildmenu = true
-- vim.opt.omnifunc='v:lua.vim.lsp.omnifunc'
vim.opt.winbar = '%=%m %f'
-- lua vim.diagnostic.setqflist({open = tru, severity = { min = vim.diagnostic.severity.WARN } })
-- fugitive-gitlab {{{
-- also add our token for private repos
vim.g.fugitive_gitlab_domains = { 'https://git.novadiscovery.net' }
-- }}}
-- set guicursor="n-v-c:block-Cursor/lCursor,ve:ver35-Cursor,o:hor50-Cursor,i-ci:ver25-Cursor/lCursor,r-cr:hor20-Cursor/lCursor,sm:block-Cursor"
vim.opt.guicursor =
'n-v-c:block-blinkon250-Cursor/lCursor,ve:ver35-Cursor,o:hor50-Cursor,i-ci:ver25-blinkon250-Cursor/lCursor,r-cr:hor20-Cursor/lCursor'
-- highl Cursor ctermfg=16 ctermbg=253 guifg=#000000 guibg=#00FF00
vim.api.nvim_set_hl(0, 'Cursor', { ctermfg = 16, ctermbg = 253, fg = '#000000', bg = '#00FF00' })
vim.api.nvim_set_hl(0, 'CursorLine', { fg = 'None', bg = '#293739' })
vim.api.nvim_set_hl(0, 'NormalFloat', { bg = 'grey' })
-- local my_image = require('hologram.image'):new({
-- source = '/home/teto/doctor.png',
-- row = 11,
-- col = 0,
-- })
-- my_image:transmit() -- send image data to terminal
-- use {
-- -- Display marks for different kinds of decorations across the buffer. Builtin handlers include:
-- -- 'lewis6991/satellite.nvim',
-- config = function()
-- require('satellite').setup()
-- end
-- }
-- installed via nix
-- require('satellite').setup()
-- use {
-- "max397574/colortils.nvim",
-- -- cmd = "Colortils",
-- config = function()
-- require("colortils").setup()
-- end,
-- }
use {'shaunsingh/oxocarbon.nvim', branch = 'fennel'}
-- use '~/neovim/fzf-lua' -- markdown syntax compatible with Github's
use('rhysd/vim-gfm-syntax') -- markdown syntax compatible with Github's
-- use 'symphorien/vim-nixhash' -- use :NixHash
-- use 'vim-denops/denops.vim'
-- use 'ryoppippi/bad-apple.vim' -- needs denops
-- use 'eugen0329/vim-esearch' -- search & replace
-- use 'kshenoy/vim-signature' -- display marks in gutter, love it
-- use '~/pdf-scribe.nvim' -- to annotate pdf files from nvim :PdfScribeInit
-- PdfScribeInit
-- vim.g.pdfscribe_pdf_dir = expand('$HOME').'/Nextcloud/papis_db'
-- vim.g.pdfscribe_notes_dir = expand('$HOME').'/Nextcloud/papis_db'
-- }}}
-- annotations plugins {{{
-- use 'MattesGroeger/vim-bookmarks' -- ruby / :BookmarkAnnotate
-- 'wdicarlo/vim-notebook' -- last update in 2016
-- 'plutonly/vim-annotate-- -- last update in 2015
--}}}
-- use 'norcalli/nvim-terminal.lua' -- to display ANSI colors
-- use '~/neovim/nvim-terminal.lua' -- to display ANSI colors
use('bogado/file-line') -- to open a file at a specific line
-- use 'glacambre/firenvim' -- to use nvim in firefox
-- call :NR on a region than :w . coupled with b:nrrw_aucmd_create,
-- use 'chrisbra/NrrwRgn' -- to help with multi-ft files
use('chrisbra/vim-diff-enhanced') --
use 'uga-rosa/translate.nvim'
-- use ({
-- "jghauser/papis.nvim",
-- after = { "telescope.nvim", "nvim-cmp" },
-- requires = {
-- "kkharji/sqlite.lua",
-- "nvim-lua/plenary.nvim",
-- "MunifTanjim/nui.nvim",
-- "nvim-treesitter/nvim-treesitter",
-- },
-- rocks = {
-- {
-- "lyaml"
-- -- If using macOS or Linux, you may need to install the `libyaml` package.
-- -- If you install libyaml with homebrew you will need to set the YAML_DIR
-- -- to the location of the homebrew installation of libyaml e.g.
-- -- env = { YAML_DIR = '/opt/homebrew/Cellar/libyaml/0.2.5/' },
-- }
-- },
-- config = function()
-- require("papis").setup(
-- -- Your configuration goes here
-- )
-- end,
-- })
-- use { 'ldelossa/gh.nvim',
-- requires = { { 'ldelossa/litee.nvim' } },
-- config = function ()
-- require('litee.lib').setup({
-- -- this is where you configure details about your panel, such as
-- -- whether it toggles on the left, right, top, or bottom.
-- -- leaving this blank will use the defaults.
-- -- reminder: gh.nvim uses litee.lib to implement core portions of its UI.
-- })
-- require('litee.gh').setup({
-- -- this is where you configure details about gh.nvim directly relating
-- -- to GitHub integration.
-- })
-- end
-- }
-- use 'rhysd/git-messenger.vim' -- to show git message :GitMessenger
-- use 'tweekmonster/nvim-api-viewer', {'on': 'NvimAPI'} -- see nvim api
-- provider
-- REPL (Read Execute Present Loop) {{{
-- use 'metakirby5/codi.vim', {'on': 'Codi'} -- repl
-- careful it maps cl by default
-- use 'jalvesaq/vimcmdline' -- no help files, mappings clunky
-- github mirror of use 'http://gitlab.com/HiPhish/repl.nvim'
-- use 'http://gitlab.com/HiPhish/repl.nvim' -- no commit for the past 2 years
--}}}
-- Snippets are separated from the engine. Add this if you want them:
-- " use 'justinmk/vim-gtfo' " gfo to open filemanager in cwd
-- " use 'wannesm/wmgraphviz.vim', {'for': 'dot'} " graphviz syntax highlighting
use('tpope/vim-rhubarb') -- github support in fugitive, use |i_CTRL-X_CTRL-O|
-- use {
-- 'goolord/alpha-nvim',
-- requires = { 'kyazdani42/nvim-web-devicons' },
-- config = function ()
-- require'alpha'.setup(require'alpha.themes.startify'.config)
-- end
-- }
-- diagnostic
-- use { 'neovim/nvimdev.nvim', opt = true }
use({
'jose-elias-alvarez/null-ls.nvim',
config = function()
require('null-ls').setup({
sources = {
-- needs a luacheck in PATH
require('null-ls').builtins.diagnostics.luacheck,
-- require("null-ls").builtins.formatting.stylua,
-- require("null-ls").builtins.diagnostics.eslint,
-- require("null-ls").builtins.completion.spell,
},
})
end,
})
use({
'AckslD/nvim-FeMaco.lua',
config = 'require("femaco").setup()',
})
-- use { 'folke/noice.nvim',
-- event = "VimEnter",
-- requires = { "rcarriga/nvim-notify" },
-- config = function()
-- local fakeColor = { fg='#000000', bg='#00FF00' }
-- vim.api.nvim_set_hl(0, 'NoiceCmdlinePopupBorder', fakeColor)
-- vim.api.nvim_set_hl(0, 'NoiceCmdlinePopupBorderCmdline', fakeColor)
-- -- https://github.com/folke/noice.nvim/wiki/Configuration-Recipes#show-recording-messages
-- require("noice").setup({
-- cmdline = {
-- view = "cmdline_popup", -- view for rendering the cmdline. Change to `cmdline` to get a classic cmdline at the bottom
-- opts = {
-- buf_options = {
-- -- filetype = "vim"
-- }
-- }, -- enable syntax highlighting in the cmdline
-- icons = {
-- ["/"] = { icon = " ", hl_group = "Normal" },
-- ["?"] = { icon = " ", hl_group = "DiagnosticWarn" },
-- [":"] = { icon = " ", hl_group = "DiagnosticInfo", firstc = false },
-- },
-- },
-- lsp_progress ={
-- enabled = true
-- },
-- popupmenu = {
-- enabled = false;
-- },
-- history = {
-- -- options for the message history that you get with `:Noice`
-- view = "split",
-- opts = { enter = true },
-- filter = { event = "msg_show", ["not"] = { kind = { "search_count", "echo" } } },
-- },
-- -- how frequently does Noice need to check for ui updates? This has no effect when in blocking mode.
-- throttle = 1000 / 30,
-- views = {
-- -- cmdline = {
-- -- }
-- -- @see the section on views below
-- cmdline_popup = {
-- border = {
-- -- style = "none",
-- padding = { 2, 3 },
-- },
-- -- filter_options = {},
-- win_options = {
-- winhighlight = {
-- -- Normal = "NormalFloat",
-- -- FloatBorder = "NormalFloat",
-- -- Normal = "NoicePopupmenu", -- change to NormalFloat to make it look like other floats
-- -- FloatBorder = "NoicePopupmenuBorder", -- border highlight
-- -- CursorLine = "NoicePopupmenuSelected", -- used for highlighting the selected item
-- -- PmenuMatch = "NoicePopupmenuMatch", -- used to highlight the part of the item that matches the input
-- },
-- },
-- position = {
-- -- row = 5,
-- col = "50%",
-- },
-- size = {
-- width = 210,
-- -- height = "auto",
-- height = 3
-- },
-- },
-- popupmenu = {
-- relative = "editor",
-- position = {
-- row = 8,
-- col = "50%",
-- },
-- size = {
-- width = 60,
-- height = 10,
-- },
-- border = {
-- style = "rounded",
-- padding = { 0, 1 },
-- },
-- win_options = {
-- winhighlight = { Normal = "Normal", FloatBorder = "DiagnosticInfo" },
-- },
-- },
-- },
-- routes = {
-- -- skip search_count messages instead of showing them as virtual text
-- -- filter = { event = "msg_show", kind = "search_count" },
-- -- opts = { skip = true },
-- { -- shows @Recording message
-- view = "notify",
-- filter = { event = "msg_showmode" },
-- },
-- {
-- filter = {
-- event = "cmdline",
-- find = "^%s*[/?]",
-- },
-- view = "cmdline",
-- },
-- {
-- filter = {
-- event = "msg_show",
-- kind = "",
-- find = "written",
-- },
-- opts = { skip = true },
-- },
-- }, -- @see the section on routes below
-- })
-- end,
-- }
use({ 'seandewar/nvimesweeper', opt = true })
use({ 'voldikss/vim-translator', opt = true })
use('calvinchengx/vim-aftercolors') -- load after/colors
use('bfredl/nvim-luadev') -- lua repl :Luadev
use('alok/notational-fzf-vim') -- to take notes, :NV
-- use {
-- 'hkupty/iron.nvim',
-- config = function ()
-- local iron = require("iron.core")
-- iron.setup {
-- config = {
-- -- If iron should expose `<plug>(...)` mappings for the plugins
-- should_map_plug = false,
-- -- Whether a repl should be discarded or not
-- scratch_repl = true,
-- -- Your repl definitions come here
-- repl_definition = {
-- sh = { command = {"zsh"} },
-- nix = { command = {"nix", "repl", "/home/teto/nixpkgs"} },
-- -- copied from the nix wrapper :/
-- lua = { command = "/nix/store/snzm30m56ps3wkn24van553336a4yylh-luajit-2.1.0-2022-04-05-env/bin/lua"}
-- },
-- repl_open_cmd = require('iron.view').curry.bottom(40),
-- -- how the REPL window will be opened, the default is opening
-- -- a float window of height 40 at the bottom.
-- },
-- -- Iron doesn't set keymaps by default anymore. Set them here
-- -- or use `should_map_plug = true` and map from you vim files
-- keymaps = {
-- send_motion = "<space>sc",
-- visual_send = "<space>sc",
-- send_file = "<space>sf",
-- send_line = "<space>sl",
-- send_mark = "<space>sm",
-- mark_motion = "<space>mc",
-- mark_visual = "<space>mc",
-- remove_mark = "<space>md",
-- cr = "<space>s<cr>",
-- interrupt = "<space>s<space>",
-- exit = "<space>sq",
-- clear = "<space>cl",
-- },
-- -- If the highlight is on, you can change how it looks
-- -- For the available options, check nvim_set_hl
-- highlight = {
-- italic = true
-- }
-- }
-- end
-- }
-- use 'neovimhaskell/nvim-hs.vim' -- to help with nvim-hs
use('teto/vim-listchars') -- to cycle between different list/listchars configurations
use('chrisbra/csv.vim')
use('teto/Modeliner') -- <leader>ml to setup buffer modeline
-- " use 'antoinemadec/openrgb.nvim' " to take into account RGB stuff
-- prefix commands :Files become :FzfFiles, etc.
vim.g.fzf_command_prefix = 'Fzf'
-- disable statusline overwriting
vim.g.fzf_nvim_statusline = 0
-- This is the default extra key bindings
vim.g.fzf_action = { ['ctrl-t'] = 'tab split', ['ctrl-x'] = 'split', ['ctrl-v'] = 'vsplit' }
vim.g.fzf_history_dir = vim.fn.stdpath('cache') .. '/fzf-history'
vim.g.fzf_buffers_jump = 1
-- Empty value to disable preview window altogether
vim.g.fzf_preview_window = 'right:30%'
-- Default fzf layout - down / up / left / right - window (nvim only)
-- vim.g.fzf_layout = { 'down': '~40%' }
-- For Commits and BCommits to customize the options used by 'git log':
vim.g.fzf_commits_log_options = '--graph --color=always --format="%C(auto)%h%d %s %C(black)%C(bold)%cr"'
-- " use 'vhakulinen/gnvim-lsp' " load it only for gnvim
-- " use 'Rykka/riv.vim', {'for': 'rst'}
-- " use 'Rykka/InstantRst', {'for': 'rst'} " rst live preview with :InstantRst,
-- " use 'dhruvasagar/vim-table-mode', {'for': 'txt'}
-- " use 'mhinz/vim-rfc', { 'on': 'RFC' } " requires nokigiri gem
-- " careful maps F4 by default
-- use 'tpope/vim-unimpaired' " [<space> [e [n ]n pour gerer les conflits etc...
-- use 'tpope/vim-scriptease' " Adds command such as :Messages
-- use 'tpope/vim-eunuch' " {provides SudoEdit, SudoWrite , Unlink, Rename etc...
-- " use 'ludovicchabant/vim-gutentags' " automatic tag generation, very good
-- " use 'junegunn/limelight.vim' " focus writing :Limelight, works with goyo
-- " leader
-- " use 'bronson/vim-trailing-whitespace' " :FixWhitespace
vim.api.nvim_set_hl(0, 'DiagnosticVirtualTextError', { fg = 'red' })
vim.api.nvim_set_hl(0, 'DiagnosticVirtualTextDebug', { fg = 'green' })
-- http://stackoverflow.com/questions/28613190/exclude-quickfix-buffer-from-bnext-bprevious
vim.keymap.set('n', '<Leader><Leader>', '<Cmd>b#<CR>')
vim.keymap.set('n', '<Leader>ev', '<Cmd>e $MYVIMRC<CR>')
vim.keymap.set('n', '<Leader>sv', '<Cmd>source $MYVIMRC<CR>')
vim.keymap.set('n', '<Leader>el', '<Cmd>e ~/.config/nvim/lua/init-manual.lua<CR>')
vim.keymap.set('n', '<Leader>em', '<Cmd>e ~/.config/nvim/lua/init-manual.vim<CR>')
vim.keymap.set('n', '<F6>', '<Cmd>ASToggle<CR>')
-- " set vim's cwd to current file's
-- nnoremap ,cd :cd %:p:h<CR>:pwd<CR>
-- " when launching term
-- tnoremap <Esc> <C-\><C-n>
-- nnoremap <Leader>el <Cmd>e ~/.config/nvim/lua/init-manual.lua<CR>
-- nnoremap <Leader>em <Cmd>e ~/.config/nvim/init.manual.vim<CR>
-- -- pb c'est qu'il l'autofocus
-- autocmd User LspDiagnosticsChanged lua vim.lsp.diagnostic.set_loclist( { open = false, open_loclist = false})
-- command! LspStopAllClients lua vim.lsp.stop_client(vim.lsp.get_active_clients())
vim.api.nvim_set_hl(0, 'SignifySignChange', {
cterm = { bold = true },
ctermbg = 237,
ctermfg = 227,
bg = 'NONE',
fg = '#F08A1F',
})
vim.api.nvim_set_hl(
0,
'SignifySignAdd',
{ cterm = { bold = true }, ctermbg = 237, ctermfg = 227, bg = 'NONE', fg = 'green' }
)
vim.api.nvim_set_hl(
0,
'SignifySignDelete',
{ cterm = { bold = true }, ctermbg = 237, ctermfg = 227, bg = 'NONE', fg = 'red' }
)
-- This is the default extra key bindings
-- vim.g.fzf_action = { ['ctrl-t']: 'tab split', 'ctrl-x': 'split', 'ctrl-v': 'vsplit' }
-- Default fzf layout - down / up / left / right - window (nvim only)
vim.g.fzf_layout = { ['down'] = '~40%' }
-- For Commits and BCommits to customize the options used by 'git log':
vim.g.fzf_commits_log_options = '--graph --color=always --format="%C(auto)%h%d %s %C(black)%C(bold)%cr"'
vim.api.nvim_create_autocmd('TextYankPost', {
callback = function()
vim.highlight.on_yank({ higroup = 'IncSearch', timeout = 1000 })
end,
})
nnoremap('n', '<leader>ml', '<Cmd>Modeliner<Enter>')
vim.g.Modeliner_format = 'et ff= fenc= sts= sw= ts= fdm='
-- " auto reload vim config on save
-- " Watch for changes to vimrc
-- " augroup myvimrc
-- " au!
-- " au BufWritePost $MYVIMRC,.vimrc,_vimrc,vimrc,.gvimrc,_gvimrc,gvimrc,init.vim so $MYVIMRC | if has('gui_running') | so $MYGVIMRC | endif
-- " augroup END
vim.cmd([[sign define DiagnosticSignError text=✘ texthl=LspDiagnosticsSignError linehl= numhl=]])
vim.cmd([[sign define DiagnosticSignWarning text=! texthl=LspDiagnosticsSignWarning linehl= numhl=CustomLineWarn]])
vim.cmd(
[[sign define DiagnosticSignInformation text=I texthl=LspDiagnosticsSignInformation linehl= numhl=CustomLineWarn]]
)
vim.cmd([[sign define DiagnosticSignHint text=H texthl=LspDiagnosticsSignHint linehl= numhl=]])
-- autocmd ColorScheme *
-- \ highlight Comment gui=italic
-- \ | highlight Search gui=underline
-- \ | highlight MatchParen guibg=NONE guifg=NONE gui=underline
-- \ | highlight NeomakePerso cterm=underline ctermbg=Red ctermfg=227 gui=underline
-- netrw config {{{
vim.g.netrw_browsex_viewer = 'xdg-open'
vim.g.netrw_home = vim.env.XDG_CACHE_HOME .. '/nvim'
vim.g.netrw_liststyle = 1 -- long listing with timestamp
--}}}
vim.keymap.set('n', '<leader>rg', '<Cmd>Grepper -tool rg -open -switch<CR>')
-- rgb
-- vim.keymap.set("n", "<leader>rgb", "<Cmd>Grepper -tool rgb -open -switch -buffer<CR>")
-- vim.api.nvim_create_augroup('bufcheck', {clear = true})
-- autocmd BufReadPost *.pdf silent %!pdftotext -nopgbrk -layout -q -eol unix "%" - | fmt -w78
-- " convert all kinds of files (but pdf) to plain text
-- autocmd BufReadPost *.doc,*.docx,*.rtf,*.odp,*.odt silent %!pandoc "%" -tplain -o /dev/stdout
vim.api.nvim_create_autocmd('BufReadPost', {
pattern = '*.pdf',
callback = function()
vim.cmd([[%!pdftotext -nopgbrk -layout -q -eol unix "%" - | fmt -w78]])
vim.highlight.on_yank({ higroup = 'IncSearch', timeout = 1000 })
end,
})
-- display buffer name top-right
-- use {
-- "b0o/incline.nvim",
-- config = function ()
-- require('incline').setup()
-- end
-- }
-- use {
-- 'norcalli/nvim-colorizer.lua',
-- config = function ()
-- require('colorizer').setup()
-- end
-- }
-- use {
-- -- a zenity picker for several stuff (colors etc)
-- 'DougBeney/pickachu'
-- }
use('/home/teto/neovim/rest.nvim')
-- provides 'NvimTree'
use('kyazdani42/nvim-tree.lua')
use 'rhysd/committia.vim'
-- TODO package in nvim
use({
'MrcJkb/haskell-tools.nvim',
config = function()
local ht = require('haskell-tools')
ht.setup({
tools = { -- haskell-tools options
codeLens = {
-- Whether to automatically display/refresh codeLenses
autoRefresh = true,
},
hoogle = {
-- 'auto': Choose a mode automatically, based on what is available.
-- 'telescope-local': Force use of a local installation.
-- 'telescope-web': The online version (depends on curl).
-- 'browser': Open hoogle search in the default browser.
mode = 'auto',
},
repl = {
-- 'builtin': Use the simple builtin repl
-- 'toggleterm': Use akinsho/toggleterm.nvim
handler = 'builtin',
builtin = {
create_repl_window = function(view)
-- create_repl_split | create_repl_vsplit | create_repl_tabnew | create_repl_cur_win
return view.create_repl_split { size = vim.o.lines / 3 }
end
},
},
},
hls = { -- LSP client options
on_attach = function(client, bufnr)
local attach_cb = require('on_attach')
attach_cb.on_attach(client, bufnr)
-- haskell-language-server relies heavily on codeLenses,
-- so auto-refresh (see advanced configuration) is enabled by default
vim.keymap.set('n', '<leader>ca', vim.lsp.codelens.run, opts)
vim.keymap.set('n', '<leader>cl', vim.lsp.codelens.run, opts)
vim.keymap.set('n', '<leader>hs', ht.hoogle.hoogle_signature, opts)
-- default_on_attach(client, bufnr) -- if defined, see nvim-lspconfig
end,
-- ...
settings = { -- haskell-language-server options
haskell = {
formattingProvider = 'ormolu',
checkProject = true, -- Setting this to true could have a performance impact on large mono repos.
-- ...
plugin = {
refineImports = {
codeActionsOn = true,
codeLensOn = false,
},
},
},
},
},
})
end,
})
-- defaults
-- use {
-- "~/telescope-frecency.nvim",
-- config = function ()
-- nnoremap ( "n", "<Leader>f", function () require('telescope').extensions.frecency.frecency({
-- query = "toto"
-- }) end )
-- end
-- }
-- use {
-- 'VonHeikemen/fine-cmdline.nvim',
-- config = function ()
-- require('fine-cmdline').setup()
-- end
-- -- requires = {
-- -- {'MunifTanjim/nui.nvim'}
-- -- }
-- }
-- use {'kevinhwang91/nvim-ufo', requires = 'kevinhwang91/promise-async'}
-- for quickreading: use :FSToggle to Toggle flow state
use({'nullchilly/fsread.nvim', config = function ()
-- vim.g.flow_strength = 0.7 -- low: 0.3, middle: 0.5, high: 0.7 (default)
-- vim.g.skip_flow_default_hl = true -- If you want to override default highlights
-- vim.api.nvim_set_hl(0, "FSPrefix", { fg = "#cdd6f4" })
-- vim.api.nvim_set_hl(0, "FSSuffix", { fg = "#6C7086" })
end})
-- overrides vim.ui / vim.select with the backend of my choice
use({
'stevearc/dressing.nvim',
config = function()
require('dressing').setup({
input = {
-- Default prompt string
default_prompt = '➤ ',
-- When true, <Esc> will close the modal
insert_only = true,
-- These are passed to nvim_open_win
anchor = 'SW',
relative = 'cursor',
border = 'rounded',
-- These can be integers or a float between 0 and 1 (e.g. 0.4 for 40%)
prefer_width = 40,
width = nil,
-- min_width and max_width can be a list of mixed types.
-- min_width = {20, 0.2} means "the greater of 20 columns or 20% of total"
max_width = { 140, 0.9 },
min_width = { 20, 0.2 },
-- see :help dressing_get_config
get_config = nil,
},
mappings = {
['<C-c>'] = 'Close',
},
select = {
-- Priority list of preferred vim.select implementations
backend = { 'telescope', 'fzf', 'builtin', 'nui' },
-- Options for fzf selector
fzf = {
window = {
width = 0.5,
height = 0.4,
},
},
telescope = {
window = {
width = 0.5,
height = 0.4,
},
},
-- Options for nui Menu
-- nui = {
-- position = "50%",
-- size = nil,
-- relative = "editor",
-- border = {
-- style = "rounded",
-- },
-- max_width = 80,
-- max_height = 40,
-- },
-- Options for built-in selector
builtin = {
-- These are passed to nvim_open_win
anchor = 'NW',
relative = 'cursor',
border = 'rounded',
-- Window options
winblend = 10,
-- These can be integers or a float between 0 and 1 (e.g. 0.4 for 40%)
-- the min_ and max_ options can be a list of mixed types.
-- max_width = {140, 0.8} means "the lesser of 140 columns or 80% of total"
width = nil,
max_width = { 140, 0.8 },
min_width = { 40, 0.2 },
height = nil,
max_height = 0.9,
min_height = { 10, 0.2 },
},
-- see :help dressing_get_config
get_config = nil,
},
})
end,
})
-- use 'https://git.sr.ht/~whynothugo/lsp_lines.nvim'
-- use({
-- "https://git.sr.ht/~whynothugo/lsp_lines.nvim",
-- as = "lsp_lines",
-- config = function()
-- require("lsp_lines").register_lsp_virtual_lines()
-- end,
-- })
-- use 'mfussenegger/nvim-dap'
-- use {
-- "rcarriga/nvim-dap-ui"
-- , requires = {"mfussenegger/nvim-dap"}
-- }
-- use 'nvim-telescope/telescope-dap.nvim'
--
-- use {
-- -- set virtualedit=all, select an area then call :VBox
-- 'jbyuki/venn.nvim'
-- }
-- use {
-- 'rose-pine/neovim'
-- }
use({
'rose-pine/neovim',
as = 'rose-pine',
tag = 'v1.*',
-- config = function()
-- end
})
-- use { 'protex/better-digraphs.nvim' }
use({
'rcarriga/nvim-notify',
config = function()
require('notify').setup({
-- Animation style (see below for details)
stages = 'fade_in_slide_out',
-- Function called when a new window is opened, use for changing win settings/config
-- on_open = nil,
-- Function called when a window is closed
-- on_close = nil,
-- Render function for notifications. See notify-render()
-- render = "default",
-- Default timeout for notifications
timeout = 5000,
-- Max number of columns for messages
max_width = 300,
-- Max number of lines for a message
-- max_height = 50,
-- For stages that change opacity this is treated as the highlight behind the window
-- Set this to either a highlight group, an RGB hex value e.g. "#000000" or a function returning an RGB code for dynamic values
background_colour = 'Normal',
-- Minimum width for notification windows
minimum_width = 50,
})
vim.notify = require('notify')
end,
})
-- terminal image viewer in neovim see https://github.com/edluffy/hologram.nvim#usage for usage
-- use 'edluffy/hologram.nvim' -- hologram-nvim
-- use 'ellisonleao/glow.nvim' -- markdown preview, run :Glow
-- use {
-- -- Show where your cursor moves
-- 'edluffy/specs.nvim',
-- config = function ()
-- local specs = require 'specs'
-- specs.setup{
-- show_jumps = true,
-- min_jump = 20,
-- popup = {
-- delay_ms = 0, -- delay before popup displays
-- inc_ms = 10, -- time increments used for fade/resize effects
-- blend = 10, -- starting blend, between 0-100 (fully transparent), see :h winblend
-- width = 30,
-- winhl = "PMenu",
-- fader = specs.linear_fader,
-- resizer = specs.shrink_resizer
-- },
-- ignore_filetypes = {},
-- ignore_buftypes = {
-- nofile = true,
-- },
-- }
-- end
-- }
-- use {
-- 'code-biscuits/nvim-biscuits',
-- config = function ()
-- require('nvim-biscuits').setup({
-- on_events = { 'InsertLeave', 'CursorHoldI' },
-- cursor_line_only = true,
-- default_config = {
-- max_length = 12,
-- min_distance = 50,
-- prefix_string = " 📎 "
-- },
-- language_config = {
-- html = { prefix_string = " 🌐 " },
-- javascript = {
-- prefix_string = " ✨ ",
-- max_length = 80
-- },
-- python = { disabled = true },
-- -- nix = { disabled = true }
-- }
-- })
-- end
-- }
-- use { 'nvim-lua/popup.nvim' } -- mimic vim's popupapi for neovim
use({
'lukas-reineke/indent-blankline.nvim',
config = function()
require('indent_blankline').setup({
char = '│',
buftype_exclude = { 'terminal' },
filetype_exclude = { 'help' },
space_char_blankline = ' ',
show_end_of_line = true,
char_highlight_list = {
'IndentBlanklineIndent1',
'IndentBlanklineIndent2',
'IndentBlanklineIndent3',
'IndentBlanklineIndent4',
'IndentBlanklineIndent5',
'IndentBlanklineIndent6',
},
max_indent_increase = 1,
indent_level = 2,
show_first_indent_level = false,
-- blankline_use_treesitter,
char_list = { '.', '|', '-' },
show_trailing_blankline_indent = false,
show_current_context = false,
show_current_context_start = true,
enabled = false,
})
end,
})
-- use {
-- -- shows type annotations for functions in virtual text using built-in LSP client
-- 'jubnzv/virtual-types.nvim'
-- }
-- telescope plugins {{{
use({
'~/telescope.nvim',
requires = {
'nvim-telescope/telescope-github.nvim',
'nvim-telescope/telescope-symbols.nvim',
'nvim-telescope/telescope-fzy-native.nvim',
'nvim-telescope/telescope-media-files.nvim',
'nvim-telescope/telescope-packer.nvim', -- :Telescope pack,e
'MrcJkb/telescope-manix', -- :Telescope manix
'luc-tielen/telescope_hoogle'
-- psiska/telescope-hoogle.nvim looks less advanced
},
})
--}}}
-- use "terrortylor/nvim-comment"
-- shows a lightbulb where a codeAction is available
-- use { 'kosayoda/nvim-lightbulb',
-- config = function ()
-- vim.cmd [[autocmd CursorHold,CursorHoldI * lua require'nvim-lightbulb'.update_lightbulb()]]
-- end
-- }
-- using packer.nvim
use {'akinsho/bufferline.nvim', requires = 'kyazdani42/nvim-web-devicons'}
-- compete with registers.nvim
-- https://github.com/gelguy/wilder.nvim
-- use { 'gelguy/wilder.nvim' }
-- use { 'gennaro-tedesco/nvim-peekup' }
--use { 'TimUntersberger/neogit',
-- config = function ()
-- vim.defer_fn (
-- function ()
-- require 'neogit'.setup {
-- disable_signs = false,
-- disable_context_highlighting = false,
-- disable_commit_confirmation = false,
-- -- customize displayed signs
-- signs = {
-- -- { CLOSED, OPENED }
-- section = { ">", "v" },
-- item = { ">", "v" },
-- hunk = { "", "" },
-- },
-- integrations = {
-- -- Neogit only provides inline diffs. If you want a more traditional way to look at diffs you can use `sindrets/diffview.nvim`.
-- -- The diffview integration enables the diff popup, which is a wrapper around `sindrets/diffview.nvim`.
-- --
-- -- Requires you to have `sindrets/diffview.nvim` installed.
-- -- use {
-- -- 'TimUntersberger/neogit',
-- -- requires = {
-- -- 'nvim-lua/plenary.nvim',
-- -- 'sindrets/diffview.nvim'
-- -- }
-- -- }
-- --
-- diffview = false
-- },
-- -- override/add mappings
-- mappings = {
-- -- modify status buffer mappings
-- status = {
-- -- Adds a mapping with "B" as key that does the "BranchPopup" command
-- ["B"] = "BranchPopup",
-- -- Removes the default mapping of "s"
-- ["s"] = "",
-- }
-- }
-- }
--end)
--end
--}
-- use { 'notomo/gesture.nvim' , opt = true; }
-- using teto instead to test packer luarocks support
-- use { "rktjmp/lush.nvim" }
use({
'rktjmp/hotpot.nvim',
config = function()
require('hotpot').setup({
-- allows you to call `(require :fennel)`.
-- recommended you enable this unless you have another fennel in your path.
-- you can always call `(require :hotpot.fennel)`.
provide_require_fennel = false,
-- show fennel compiler results in when editing fennel files
enable_hotpot_diagnostics = true,
-- compiler options are passed directly to the fennel compiler, see
-- fennels own documentation for details.
compiler = {
-- options passed to fennel.compile for modules, defaults to {}
modules = {
-- not default but recommended, align lua lines with fnl source
-- for more debuggable errors, but less readable lua.
-- correlate = true
},
-- options passed to fennel.compile for macros, defaults as shown
macros = {
env = '_COMPILER', -- MUST be set along with any other options
},
},
})
end,
})
use({ 'alec-gibson/nvim-tetris', opt = true })
-- use { 'mfussenegger/nvim-dap'} -- debug adapter protocol
-- use {
-- -- a plugin for interacting with bazel :Bazel build //some/package:sometarget
-- -- supports autocompletion
-- 'bazelbuild/vim-bazel' , requires = { 'google/vim-maktaba' }
-- }
use('bazelbuild/vim-ft-bzl')
use('PotatoesMaster/i3-vim-syntax')
-- colorschemes {{{
use('Matsuuu/pinkmare')
use('flrnd/candid.vim')
use('adlawson/vim-sorcerer')
use('whatyouhide/vim-gotham')
use('vim-scripts/Solarized')
-- use 'npxbr/gruvbox.nvim' " requires lush
use('romainl/flattened')
use('NLKNguyen/papercolor-theme')
use('marko-cerovac/material.nvim')
-- }}}
-- use 'anuvyklack/hydra.nvim' -- to create submodes
use('skywind3000/vim-quickui') -- to design cool uis
use('neovim/nvim-lspconfig') -- while fuzzing details out
-- use '~/neovim/nvim-lspconfig' -- while fuzzing details out
-- use 'vim-scripts/rfc-syntax' -- optional syntax highlighting for RFC files
-- use 'vim-scripts/coq-syntax'
use({ 'tweekmonster/startuptime.vim', opt = true }) -- {'on': 'StartupTime'} " see startup time per script
-- TODO upstream
--use {
-- 'chipsenkbeil/distant.nvim'
-- , opt = true
-- , config = function()
-- require('distant').setup {
-- -- Applies Chip's personal settings to every machine you connect to
-- --
-- -- 1. Ensures that distant servers terminate with no connections
-- -- 2. Provides navigation bindings for remote directories
-- -- 3. Provides keybinding to jump into a remote file's parent directory
-- ['*'] = require('distant.settings').chip_default()
-- }
-- end
--}
-- use {
-- 'matbme/JABS.nvim',
-- config = function ()
-- require 'jabs'.setup {
-- position = 'center', -- center, corner
-- width = 50,
-- height = 10,
-- border = 'shadow', -- none, single, double, rounded, solid, shadow, (or an array or chars)
-- -- the options below are ignored when position = 'center'
-- col = 0,
-- row = 0,
-- anchor = 'NW', -- NW, NE, SW, SE
-- relative = 'win', -- editor, win, cursor
-- }
-- end
-- }
-- use {
-- 'ggandor/lightspeed.nvim',
-- config = function ()
-- require'lightspeed'.setup {
-- -- This can get _really_ slow if the window has a lot of content,
-- -- turn it on only if your machine can always cope with it.
-- jump_to_unique_chars = false,
-- match_only_the_start_of_same_char_seqs = true,
-- limit_ft_matches = 5,
-- -- x_mode_prefix_key = '<c-x>',
-- substitute_chars = { ['\r'] = '¬' },
-- instant_repeat_fwd_key = nil,
-- instant_repeat_bwd_key = nil,
-- -- If no values are given, these will be set at runtime,
-- -- based on `jump_to_first_match`.
-- labels = nil,
-- cycle_group_fwd_key = nil,
-- cycle_group_bwd_key = nil,
-- }
-- end
-- }
-- use 'mrjones2014/dash.nvim' -- only for dash it seems
-- Trouble {{{
--use {
-- "folke/trouble.nvim",
---- requires = "kyazdani42/nvim-web-devicons",
-- config = function ()
-- end
--}
-- }}}
-- use {
-- 'kdheepak/tabline.nvim',
-- config = function()
-- require'tabline'.setup {
-- -- Defaults configuration options
-- enable = true,
-- show_filename_only = true,
-- show_devicons = false,
-- }
-- vim.cmd[[
-- set guioptions-=e " Use showtabline in gui vim
-- set sessionoptions+=tabpages,globals " store tabpages and globals in session
-- ]]
-- end,
-- requires = { { 'hoob3rt/lualine.nvim', opt=true }, 'kyazdani42/nvim-web-devicons' }
-- }
use('MunifTanjim/nui.nvim') -- to create UIs
use('honza/vim-snippets')
-- use 'sjl/gundo.vim' " :GundoShow/Toggle to redo changes
-- use {
-- 'hrsh7th/nvim-cmp',
-- -- use 'hrsh7th/cmp-nvim-lsp' -- LSP source for nvim-cmp
-- -- use 'saadparwaiz1/cmp_luasnip' -- Snippets source for nvim-cmp
-- requires = {
-- -- "quangnguyen30192/cmp-nvim-ultisnips",
-- 'hrsh7th/cmp-buffer',
-- 'hrsh7th/cmp-vsnip',
-- 'hrsh7th/cmp-nvim-lsp',
-- 'hrsh7th/vim-vsnip',
-- 'hrsh7th/vim-vsnip-integ',
-- 'rafamadriz/friendly-snippets'
-- },
-- config = function ()
local has_cmp, cmp = pcall(require, 'cmp')
if has_cmp then
use('michaeladler/cmp-notmuch')
-- nvim-cmp autocompletion plugin{{{
cmp.setup({
snippet = {
expand = function(args)
-- For `vsnip` user.
vim.fn['vsnip#anonymous'](args.body)
-- For `luasnip` user.
-- require('luasnip').lsp_expand(args.body)
-- For `ultisnips` user.
-- vim.fn["UltiSnips#Anon"](args.body)
end,
},
mapping = cmp.mapping.preset.insert({
['<C-d>'] = cmp.mapping.scroll_docs(-4),
['<C-f>'] = cmp.mapping.scroll_docs(4),
-- ['<C-Space>'] = cmp.mapping.complete(),
-- ['<C-e>'] = cmp.mapping.close(),
['<CR>'] = cmp.mapping.confirm({ select = true }),
}),
-- view = {
-- entries = 'native'
-- },
sources = {
{ name = 'nvim_lsp' },
-- For vsnip user.
{ name = 'vsnip' },
-- For luasnip user.
-- { name = 'luasnip' },
-- For ultisnips user.
-- { name = 'ultisnips' },
{ name = 'buffer' },
-- { name = 'neorg' },
-- { name = 'orgmode' },
},
})
-- }}}
-- cmp.setup.cmdline {
-- mapping = cmp.mapping.preset.cmdline({
-- -- Your configuration here.
-- })
-- }
-- end
-- }
end
vim.api.nvim_create_autocmd('MenuPopup', {
callback = function()
-- vim.highlight.on_yank({ higroup = 'IncSearch', timeout = 1000 })
print("hello")
end,
})
-- Load custom tree-sitter grammar for org filetype
-- orgmode depends on treesitter
local has_orgmode, orgmode = pcall(require, 'orgmode')
if has_orgmode then
orgmode.setup_ts_grammar()
end
-- use {
-- "nvim-neorg/neorg",
-- config = function()
-- require('neorg').setup {
-- -- Tell Neorg what modules to load
-- load = {
-- ["core.defaults"] = {}, -- Load all the default modules
-- ["core.keybinds"] = { -- Configure core.keybinds
-- config = {
-- default_keybinds = true, -- Generate the default keybinds
-- neorg_leader = "<Leader>n" -- This is the default if unspecified
-- }
-- },
-- ["core.norg.concealer"] = {}, -- Allows for use of icons
-- ["core.norg.completion"] = {
-- config = {
-- engine = "nvim-cmp"
-- }
-- }, -- Allows for use of icons
-- ["core.norg.dirman"] = { -- Manage your directories with Neorg
-- config = {
-- workspaces = {
-- my_workspace = "~/neorg"
-- }
-- }
-- }
-- },
-- }
-- end,
-- requires = "nvim-lua/plenary.nvim"
-- }
use('ray-x/lsp_signature.nvim') -- display function signature in insert mode
-- use({
-- 'Pocco81/AutoSave.nvim' -- :ASToggle /AsOn / AsOff
-- , config = function ()
-- local autosave = require("autosave")
-- autosave.setup({
-- enabled = true,
-- execution_message = "AutoSave: saved at " .. vim.fn.strftime("%H:%M:%S"),
-- events = { "FocusLost"}, -- "InsertLeave"
-- conditions = {
-- exists = true,
-- filetype_is_not = {},
-- modifiable = true
-- },
-- write_all_buffers = false,
-- on_off_commands = true,
-- clean_command_line_interval = 2500
-- }
-- )
-- end
-- })
-- use 'sindrets/diffview.nvim' -- :DiffviewOpen
-- lua require('github-notifications.menu').notifications()
-- use 'rlch/github-notifications.nvim'
use({
'nvim-lualine/lualine.nvim', -- fork of hoob3rt/lualine
requires = { 'arkav/lualine-lsp-progress' },
config = function()
require 'teto.lualine'
end,
})
-- Inserts a component in lualine_c at left section
-- local function ins_left(component)
-- table.insert(config.sections.lualine_c, component)
-- end
-- -- Inserts a component in lualine_x ot right section
-- local function ins_right(component)
-- table.insert(config.sections.lualine_x, component)
-- end
-- shade currently broken
--local has_shade, shade = pcall(require, "shade")
--if has_shade then
-- shade.setup({
-- overlay_opacity = 70,
-- opacity_step = 1,
-- -- keys = {
-- -- brightness_up = '<C-Up>',
-- -- brightness_down = '<C-Down>',
-- -- toggle = '<Leader>s',
-- -- }
-- })
--end
-- use fzf to search through diagnostics
-- use { 'ojroques/nvim-lspfuzzy'}
-- for live editing
-- use { 'jbyuki/instant.nvim' }
-- use { 'jbyuki/nabla.nvim' } -- write latex equations in ASCII
-- use { 'jbyuki/monolithic.nvim' } -- write latex equations in ASCII
-- vim.g.sonokai_style = 'atlantis'
-- vim.cmd([[colorscheme sonokai]])
vim.cmd([[colorscheme janah]])
-- vim.cmd([[colorscheme pywal]])
--require'sniprun'.setup({
-- -- selected_interpreters = {'Python3_fifo'}, --" use those instead of the default for the current filetype
-- -- repl_enable = {'Python3_fifo', 'R_original'}, --" enable REPL-like behavior for the given interpreters
-- -- repl_disable = {}, --" disable REPL-like behavior for the given interpreters
-- -- possible values are 'none', 'single', 'double', or 'shadow'
-- borders = 'single',
-- --" you can combo different display modes as desired
-- display = {
-- "Classic", -- "display results in the command-line area
-- "VirtualTextOk", -- "display ok results as virtual text (multiline is shortened)
-- },
--})
vim.g.indicator_errors = ''
vim.g.indicator_warnings = ''
vim.g.indicator_info = '🛈'
vim.g.indicator_hint = '❗'
vim.g.indicator_ok = '✅'
-- ✓
vim.g.spinner_frames = { '⣾', '⣽', '⣻', '⢿', '⡿', '⣟', '⣯', '⣷' }
vim.g.should_show_diagnostics_in_statusline = true
-- code to toggle diagnostic display
local diagnostics_active = true
vim.keymap.set('n', '<leader>d', function()
diagnostics_active = not diagnostics_active
if diagnostics_active then
vim.diagnostic.show()
else
vim.diagnostic.hide()
end
end)
if has_fzf_lua then
require('teto.fzf-lua').register_keymaps()
local fzf_history_dir = vim.fn.expand('~/.local/share/fzf-history')
require('fzf-lua').setup({
-- [...]
fzf_opts = {
-- [...]
['--history'] = fzf_history_dir,
-- to get the prompt at the top
['--layout'] = 'reverse',
},
winopts = {
preview = {
-- default = 'builtin'
hidden = 'hidden',
},
},
})
elseif has_telescope then
require('teto.telescope').telescope_create_keymaps()
end
-- nnoremap ( "n", "<Leader>ca", function () vim.lsp.buf.code_action{} end )
nnoremap('n', '<Leader>ca', function()
vim.cmd([[ FzfLua lsp_code_actions]])
end)
-- nnoremap ( "n", "<leader>S", function() require('spectre').open() end )
-- replace with telescope
-- nnoremap { "<Leader>t", function () vim.cmd("FzfTags") end}
-- nnoremap <Leader>h <Cmd>FzfHistory<CR>
-- nnoremap <Leader>c <Cmd>FzfCommits<CR>
-- nnoremap <Leader>C <Cmd>FzfColors<CR>
-- use 'folke/which-key.nvim' -- :WhichKey
local has_whichkey, wk = pcall(require, 'which-key')
if has_whichkey then
wk.setup({
-- plugins = {
-- marks = true, -- shows a list of your marks on ' and `
-- registers = true, -- shows your registers on " in NORMAL or <C-r> in INSERT mode
-- -- the presets plugin, adds help for a bunch of default keybindings in Neovim
-- -- No actual key bindings are created
-- presets = {
-- operators = true, -- adds help for operators like d, y, ... and registers them for motion / text object completion
-- motions = true, -- adds help for motions
-- text_objects = true, -- help for text objects triggered after entering an operator
-- windows = true, -- default bindings on <c-w>
-- nav = true, -- misc bindings to work with windows
-- z = true, -- bindings for folds, spelling and others prefixed with z
-- g = true, -- bindings for prefixed with g
-- },
-- },
-- add operators that will trigger motion and text object completion
-- to enable all native operators, set the preset / operators plugin above
-- operators = { gc = "Comments" },
-- icons = {
-- breadcrumb = "»", -- symbol used in the command line area that shows your active key combo
-- separator = "➜", -- symbol used between a key and it's label
-- group = "+", -- symbol prepended to a group
-- },
-- window = {
-- border = "none", -- none, single, double, shadow
-- position = "bottom", -- bottom, top
-- margin = { 1, 0, 1, 0 }, -- extra window margin [top, right, bottom, left]
-- padding = { 2, 2, 2, 2 }, -- extra window padding [top, right, bottom, left]
-- },
-- layout = {
-- height = { min = 4, max = 25 }, -- min and max height of the columns
-- width = { min = 20, max = 50 }, -- min and max width of the columns
-- spacing = 3, -- spacing between columns
-- },
-- hidden = { "<silent>", "<cmd>", "<Cmd>", "<CR>", "call", "lua", "^:", "^ "}, -- hide mapping boilerplate
-- show_help = true, -- show help message on the command line when the popup is visible
-- triggers = "auto", -- automatically setup triggers
-- triggers = {"<leader>"} -- or specifiy a list manually
})
end
-- set tagfunc=v:lua.vim.lsp.tagfunc
-- since it was not merge yet
--vim.ui.pick = function(entries, opts)
-- acceptable_files = vim.tbl_values(entries)
-- local pickers = require('telescope.pickers')
-- local finders = require('telescope.finders')
-- local actions = require('telescope.actions')
-- local action_state = require('telescope.actions.state')
-- print('use my custom function')
-- local prompt = 'default prompt'
-- if opts ~= nil then
-- prompt = opts.prompt
-- end
-- local selection = pickers
-- .new({
-- prompt_title = prompt,
-- finder = finders.new_table({
-- results = acceptable_files,
-- entry_maker = function(line)
-- return {
-- value = line,
-- ordinal = line,
-- display = line,
-- -- filename = base_directory .. "/data/memes/planets/" .. line,
-- }
-- end,
-- attach_mappings = function(prompt_bufnr)
-- actions.select_default:replace(function()
-- selection = action_state.get_selected_entry()
-- actions.close(prompt_bufnr)
-- print('Selected', selection)
-- return selection
-- end)
-- return true
-- end,
-- }),
-- })
-- :find()
-- -- print("Selected", selection)
-- return selection
--end
-- review locally github PRs
local has_octo, octo = pcall(require, 'octo')
if has_octo then
octo.setup({
default_remote = { 'upstream', 'origin' }, -- order to try remotes
reaction_viewer_hint_icon = '', -- marker for user reactions
user_icon = ' ', -- user icon
timeline_marker = '', -- timeline marker
timeline_indent = '2', -- timeline indentation
right_bubble_delimiter = '', -- Bubble delimiter
left_bubble_delimiter = '', -- Bubble delimiter
github_hostname = '', -- GitHub Enterprise host
snippet_context_lines = 4, -- number or lines around commented lines
file_panel = {
size = 10, -- changed files panel rows
use_icons = true, -- use web-devicons in file panel
},
mappings = { --{{{
issue = { --{{{
close_issue = '<space>ic', -- close issue
reopen_issue = '<space>io', -- reopen issue
list_issues = '<space>il', -- list open issues on same repo
reload = '<C-r>', -- reload issue
open_in_browser = '<C-b>', -- open issue in browser
copy_url = '<C-y>', -- copy url to system clipboard
add_assignee = '<space>aa', -- add assignee
remove_assignee = '<space>ad', -- remove assignee
create_label = '<space>lc', -- create label
add_label = '<space>la', -- add label
remove_label = '<space>ld', -- remove label
goto_issue = '<space>gi', -- navigate to a local repo issue
add_comment = '<space>ca', -- add comment
delete_comment = '<space>cd', -- delete comment
next_comment = ']c', -- go to next comment
prev_comment = '[c', -- go to previous comment
react_hooray = '<space>rp', -- add/remove 🎉 reaction
react_heart = '<space>rh', -- add/remove ❤️ reaction
react_eyes = '<space>re', -- add/remove 👀 reaction
react_thumbs_up = '<space>r+', -- add/remove 👍 reaction
react_thumbs_down = '<space>r-', -- add/remove 👎 reaction
react_rocket = '<space>rr', -- add/remove 🚀 reaction
react_laugh = '<space>rl', -- add/remove 😄 reaction
react_confused = '<space>rc', -- add/remove 😕 reaction
}, --}}}
pull_request = { --{{{
checkout_pr = '<space>po', -- checkout PR
merge_pr = '<space>pm', -- merge PR
list_commits = '<space>pc', -- list PR commits
list_changed_files = '<space>pf', -- list PR changed files
show_pr_diff = '<space>pd', -- show PR diff
add_reviewer = '<space>va', -- add reviewer
remove_reviewer = '<space>vd', -- remove reviewer request
close_issue = '<space>ic', -- close PR
reopen_issue = '<space>io', -- reopen PR
list_issues = '<space>il', -- list open issues on same repo
reload = '<C-r>', -- reload PR
open_in_browser = '<C-b>', -- open PR in browser
copy_url = '<C-y>', -- copy url to system clipboard
add_assignee = '<space>aa', -- add assignee
remove_assignee = '<space>ad', -- remove assignee
create_label = '<space>lc', -- create label
add_label = '<space>la', -- add label
remove_label = '<space>ld', -- remove label
goto_issue = '<space>gi', -- navigate to a local repo issue
add_comment = '<space>ca', -- add comment
delete_comment = '<space>cd', -- delete comment
next_comment = ']c', -- go to next comment
prev_comment = '[c', -- go to previous comment
react_hooray = '<space>rp', -- add/remove 🎉 reaction
react_heart = '<space>rh', -- add/remove ❤️ reaction
react_eyes = '<space>re', -- add/remove 👀 reaction
react_thumbs_up = '<space>r+', -- add/remove 👍 reaction
react_thumbs_down = '<space>r-', -- add/remove 👎 reaction
react_rocket = '<space>rr', -- add/remove 🚀 reaction
react_laugh = '<space>rl', -- add/remove 😄 reaction
react_confused = '<space>rc', -- add/remove 😕 reaction
}, --}}}
review_thread = { --{{{
goto_issue = '<space>gi', -- navigate to a local repo issue
add_comment = '<space>ca', -- add comment
add_suggestion = '<space>sa', -- add suggestion
delete_comment = '<space>cd', -- delete comment
next_comment = ']c', -- go to next comment
prev_comment = '[c', -- go to previous comment
select_next_entry = ']q', -- move to previous changed file
select_prev_entry = '[q', -- move to next changed file
close_review_tab = '<C-c>', -- close review tab
react_hooray = '<space>rp', -- add/remove 🎉 reaction
react_heart = '<space>rh', -- add/remove ❤️ reaction
react_eyes = '<space>re', -- add/remove 👀 reaction
react_thumbs_up = '<space>r+', -- add/remove 👍 reaction
react_thumbs_down = '<space>r-', -- add/remove 👎 reaction
react_rocket = '<space>rr', -- add/remove 🚀 reaction
react_laugh = '<space>rl', -- add/remove 😄 reaction
react_confused = '<space>rc', -- add/remove 😕 reaction
}, --}}}
submit_win = { --{{{
approve_review = '<C-a>', -- approve review
comment_review = '<C-m>', -- comment review
request_changes = '<C-r>', -- request changes review
close_review_tab = '<C-c>', -- close review tab
}, --}}}
review_diff = { --{{{
add_review_comment = '<space>ca', -- add a new review comment
add_review_suggestion = '<space>sa', -- add a new review suggestion
focus_files = '<leader>e', -- move focus to changed file panel
toggle_files = '<leader>b', -- hide/show changed files panel
next_thread = ']t', -- move to next thread
prev_thread = '[t', -- move to previous thread
select_next_entry = ']q', -- move to previous changed file
select_prev_entry = '[q', -- move to next changed file
close_review_tab = '<C-c>', -- close review tab
toggle_viewed = '<leader><space>', -- toggle viewer viewed state
}, --}}}
file_panel = { --{{{
next_entry = 'j', -- move to next changed file
prev_entry = 'k', -- move to previous changed file
select_entry = '<cr>', -- show selected changed file diffs
refresh_files = 'R', -- refresh changed files panel
focus_files = '<leader>e', -- move focus to changed file panel
toggle_files = '<leader>b', -- hide/show changed files panel
select_next_entry = ']q', -- move to previous changed file
select_prev_entry = '[q', -- move to next changed file
close_review_tab = '<C-c>', -- close review tab
toggle_viewed = '<leader><space>', -- toggle viewer viewed state
},--}}}
},--}}}
})
end
-- inoremap <C-k><C-k> <Cmd>lua require'betterdigraphs'.digraphs("i")<CR>
-- nnoremap { "n", "r<C-k><C-k>" , function () require'betterdigraphs'.digraphs("r") end}
-- vnoremap r<C-k><C-k> <ESC><Cmd>lua require'betterdigraphs'.digraphs("gvr")<CR>
-- local orig_ref_handler = vim.lsp.handlers['textDocument/references']
-- vim.lsp.handlers['textDocument/references'] = function(...)
-- orig_ref_handler(...)
-- vim.cmd([[ wincmd p ]])
-- end
-- require("urlview").setup({
-- picker = "default", -- "default" (vim.ui.select), "telescope" (telescope.nvim)
-- title = "URLs: ", -- prompt title
-- debug = true, -- logs user errors
-- })
local has_bufferline, bufferline = pcall(require, 'bufferline')
if has_bufferline then
bufferline.setup{
options = {
view = "default",
numbers = "buffer_id",
-- number_style = "superscript" | "",
-- mappings = true,
modified_icon = '●',
close_icon = '',
left_trunc_marker = '',
right_trunc_marker = '',
-- max_name_length = 18,
-- max_prefix_length = 15, -- prefix used when a buffer is deduplicated
-- tab_size = 18,
show_buffer_close_icons = false,
persist_buffer_sort = true, -- whether or not custom sorted buffers should persist
-- -- can also be a table containing 2 custom separators
-- -- [focused and unfocused]. eg: { '|', '|' }
-- separator_style = "slant" | "thick" | "thin" | { 'any', 'any' },
separator_style = "slant",
-- enforce_regular_tabs = false | true,
always_show_bufferline = false,
-- sort_by = 'extension' | 'relative_directory' | 'directory' | function(buffer_a, buffer_b)
-- -- add custom logic
-- return buffer_a.modified > buffer_b.modified
-- end
hover = {
enabled = true,
delay = 200,
reveal = {'close'}
},
}
}
end
for i=1,9 do
vim.keymap.set('n', '<leader>'..tostring(i) , "<cmd>BufferLineGoToBuffer "..tostring(i).."<CR>", { silent = true})
end
-- nvim-colorizer {{{
require('terminal').setup()
-- }}}
use({
'ethanholz/nvim-lastplace',
config = function()
require('nvim-lastplace').setup({
lastplace_ignore_buftype = { 'quickfix', 'nofile', 'help' },
lastplace_ignore_filetype = { 'gitcommit', 'gitrebase', 'svn', 'hgcommit' },
lastplace_open_folds = true,
})
end,
})
vim.g.UltiSnipsSnippetDirectories = { vim.fn.stdpath('config') .. '/snippets' }
vim.g.tex_flavor = 'latex'
-- Treesitter config {{{
-- 'nvim-treesitter/completion-treesitter' " extension of completion-nvim,
-- use { 'nvim-treesitter/nvim-treesitter' }
local enable_treesitter = false
if enable_treesitter then
-- use { 'nvim-treesitter/nvim-treesitter' }
use({
'nvim-treesitter/playground',
requires = { 'nvim-treesitter/nvim-treesitter' },
})
-- use {
-- 'p00f/nvim-ts-rainbow',
-- requires = { 'nvim-treesitter/nvim-treesitter' }
-- }
use({ 'nvim-treesitter/nvim-treesitter-textobjects' })
end
--}}}
-- my treesitter config
require('teto.treesitter')
-- telescope {{{
-- TODO check for telescope github extension too
if has_telescope then
-- telescope.load_extension('ghcli')
local actions = require('telescope.actions')
local trouble = require('trouble')
-- telescope.setup{}
telescope.setup({
defaults = {
layout_config = {
vertical = { width = 0.7 },
-- other layout configuration here
},
mappings = {
i = {
['<c-t>'] = trouble.open_with_trouble,
-- -- -- To disable a keymap, put [map] = false
-- -- -- So, to not map "<C-n>", just put
-- -- ["<c-x>"] = false,
-- -- -- Otherwise, just set the mapping to the function that you want it to be.
-- -- ["<C-i>"] = actions.goto_file_selection_split,
-- -- -- Add up multiple actions
-- -- ["<CR>"] = actions.goto_file_selection_edit + actions.center,
-- -- -- You can perform as many actions in a row as you like
-- -- ["<CR>"] = actions.goto_file_selection_edit + actions.center + my_cool_custom_action,
['<esc>'] = actions.close,
},
n = {
['<C-t>'] = function(prompt_bufnr, _mode)
require('trouble.providers.telescope').open_with_trouble(prompt_bufnr, _mode)
end,
-- ["<c-t>"] = trouble.open_with_trouble,
['<esc>'] = actions.close,
},
},
-- vimgrep_arguments = {
-- 'rg',
-- '--color=never',
-- '--no-heading',
-- '--with-filename',
-- '--line-number',
-- '--column',
-- '--smart-case'
-- },
-- prompt_prefix = ">",
-- scroll_strategy = "limit", -- or cycle
-- selection_strategy = "reset",
-- sorting_strategy = "descending",
-- -- horizontal, vertical, center, flex
-- layout_strategy = "horizontal",
-- layout = {
-- width = 0.75,
-- prompt_position = "bottom",
-- },
-- file_ignore_patterns = {},
-- -- get_generic_fuzzy_sorter not very good, doesn't select an exact match
-- -- get_fzy_sorter
-- -- https://github.com/nvim-telescope/telescope.nvim#sorters
-- -- generic_sorter = require'telescope.sorters'.get_levenshtein_sorter,
-- generic_sorter = require'telescope.sorters'.get_generic_fuzzy_sorter,
-- file_sorter = require'telescope.sorters'.get_fuzzy_file,
-- shorten_path = false,
-- path_display='smart',
-- winblend = 0,
-- -- preview_cutoff = 120,
-- border = true,
-- -- borderchars = { '─', '│', '─', '│', '╭', '╮', '╯', '╰'},
-- color_devicons = true,
-- -- use_less = true,
-- -- file_previewer = require'telescope.previewers'.cat.new, -- For buffer previewer use `require'telescope.previewers'.vim_buffer_cat.new`
-- -- grep_previewer = require'telescope.previewers'.vimgrep.new, -- For buffer previewer use `require'telescope.previewers'.vim_buffer_vimgrep.new`
-- -- qflist_previewer = require'telescope.previewers'.qflist.new, -- For buffer previewer use `require'telescope.previewers'.vim_buffer_qflist.new`
-- -- Developer configurations: Not meant for general override
-- -- buffer_previewer_maker = require'telescope.previewers'.buffer_previewer_maker
},
extensions = {
-- fzf = {
-- fuzzy = true, -- false will only do exact matching
-- override_generic_sorter = true, -- override the generic sorter
-- override_file_sorter = true, -- override the file sorter
-- case_mode = "smart_case", -- or "ignore_case" or "respect_case"
-- -- the default case_mode is "smart_case"
-- },
-- fzy_native = {
-- override_generic_sorter = false,
-- override_file_sorter = false,
-- },
frecency = {
-- -- workspaces = {
-- -- ["home"] = "/home/teto/home",
-- -- ["data"] = "/home/teto/neovim",
-- -- ["jinko"] = "/home/teto/jinko",
-- -- -- ["wiki"] = "/home/my_username/wiki"
-- },
-- show_scores = true,
-- show_unindexed = true,
-- ignore_patterns = {"*.git/*", "*/tmp/*"},
db_safe_mode = true,
auto_validate = false,
-- devicons_disabled = true
},
},
})
-- This will load fzy_native and have it override the default file sorter
-- telescope.load_extension('fzf')
--jghauser/papis.nvim telescope.load_extension('fzy_native')
-- telescope.load_extension("notify")
telescope.load_extension('hoogle')
telescope.load_extension('frecency')
telescope.load_extension('manix')
-- TODO add autocmd
-- User TelescopePreviewerLoaded
end
--}}}
function contextMenu()
local choices = { 'choice 1', 'choice 2' }
require('contextmenu').open(choices, {
callback = function(chosen)
print('Final choice ' .. choices[chosen])
end,
})
end
-- Disable virtual_text since it's redundant due to lsp_lines.
vim.diagnostic.config({
-- disabled because too big in haskell
virtual_lines = false,
virtual_text = true,
-- {
-- severity = { min = vim.diagnostic.severity.WARN }
-- },
signs = true,
severity_sort = true,
})
require('teto.lsp')
-- logs are written to /home/teto/.cache/vim-lsp.log
vim.lsp.set_log_level('info')
-- hack
local _, notifs = pcall(require, 'notifications')
vim.lsp.notifier = notifs
-- showLineDiagnostic is a wrapper around show_line_diagnostics
-- show_line_diagnostics calls open_floating_preview
-- local popup_bufnr, winnr = util.open_floating_preview(lines, 'plaintext')
-- seems like there is no way to pass options from show_line_diagnostics to open_floating_preview
-- the floating popup has "ownsyntax markdown"
function showLineDiagnostic()
-- local opts = {
-- enable_popup = true;
-- -- options of
-- popup_opts = {
-- };
-- }
-- return vim.lsp.diagnostic.show_line_diagnostics()
vim.diagnostic.goto_prev({ wrap = true })
-- return require'lspsaga.diagnostic'.show_line_diagnostics()
end
-- to disable virtualtext check
-- follow https://www.reddit.com/r/neovim/comments/f8u6fz/lsp_query/fip91ww/?utm_source=share&utm_medium=web2x
-- vim.cmd [[autocmd CursorHold <buffer> lua showLineDiagnostic()]]
-- vim.cmd [[autocmd CursorMoved <buffer> lua showLineDiagnostic()]]
-- function lsp_show_all_diagnostics()
-- local all_diagnostics = vim.lsp.diagnostic.get_all()
-- vim.lsp.util.set_qflist(all_diagnostics)
-- end
vim.opt.background = 'light' -- or "light" for light mode
vim.opt.showbreak = '↳ ' -- displayed in front of wrapped lines
-- TODO add a command to select a ref (from telescope ?) and call Gitsigns change_base
-- afterwards
vim.cmd([[highlight IndentBlanklineIndent1 guifg=#E06C75 gui=nocombine]])
vim.cmd([[highlight IndentBlanklineIndent2 guifg=#E5C07B gui=nocombine]])
vim.cmd([[highlight IndentBlanklineIndent3 guifg=#98C379 gui=nocombine]])
vim.cmd([[highlight IndentBlanklineIndent4 guifg=#56B6C2 gui=nocombine]])
vim.cmd([[highlight IndentBlanklineIndent5 guifg=#61AFEF gui=nocombine]])
vim.cmd([[highlight IndentBlanklineIndent6 guifg=#C678DD gui=nocombine]])
local menu_add, menu_add_cmd = myMenu.menu_add, myMenu.menu_add_cmd
menu_add('LSP.Declaration', '<cmd>lua vim.lsp.buf.declaration()<cr>')
menu_add('LSP.Definition', '<cmd>lua vim.lsp.buf.definition()<cr>')
menu_add('LSP.Hover', '<cmd>lua vim.lsp.buf.references()<cr>')
menu_add('LSP.Rename', '<cmd>lua vim.lsp.buf.rename()<cr>')
menu_add('LSP.Format', '<cmd>lua vim.lsp.buf.format()<cr>')
menu_add('Toggle.Minimap', '<cmd>MinimapToggle<cr>')
menu_add('Toggle.Obsession', '<cmd>Obsession<cr>')
menu_add('Toggle.Blanklines', '<cmd>IndentBlanklineToggle<cr>')
-- menu_add("Toggle.Biscuits", 'lua require("nvim-biscuits").toggle_biscuits()')
menu_add('REPL.Send line', [[<cmd>lua require'luadev'.exec(vim.api.nvim_get_current_line())<cr>]])
-- menu_add('REPL.Send selection ', 'call <SID>luadev_run_operator(v:true)')
menu_add ("PopUp.Lsp_declaration", "<Cmd>lua vim.lsp.buf.declaration()<CR>")
menu_add ("PopUp.Lsp_definition", "<Cmd>lua vim.lsp.buf.definition()<CR>")
menu_add('PopUp.LSP_Rename', '<cmd>lua vim.lsp.buf.rename()<cr>')
menu_add('PopUp.LSP_Format', '<cmd>lua vim.lsp.buf.format()<cr>')
menu_add(
'Diagnostic.Display_in_QF',
'<cmd>lua vim.diagnostic.setqflist({open = true, severity = { min = vim.diagnostic.severity.WARN } })<cr>'
)
menu_add(
'Diagnostic.Set_severity_to_warning',
'<cmd>lua vim.diagnostic.config({virtual_text = { severity = { min = vim.diagnostic.severity.WARN } }})<cr>'
)
menu_add('Diagnostic.Set_severity_to_all', '<cmd>lua vim.diagnostic.config({virtual_text = { severity = nil }})<cr>')
menu_add_cmd('Search.Search_and_replace', "lua require('spectre').open()")
menu_add('Search.Test', 'let a=3')
menu_add('Rest.RunRequest', "<cmd>lua require('rest-nvim').run(true)<cr>")
-- menu_add("Search.Search\ in\ current\ Buffer", :Grepper -switch -buffer")
-- menu_add("Search.Search\ across\ Buffers :Grepper -switch -buffers")
-- menu_add("Search.Search\ across\ directory :Grepper")
-- menu_add("Search.Autoopen\ results :let g:grepper.open=1<CR>")
-- menu_add("Tabs.S2 :set tabstop=2 softtabstop=2 sw=2<CR>")
-- menu_add("Tabs.S4 :set ts=4 sts=4 sw=4<CR>")
-- menu_add("Tabs.S6 :set ts=6 sts=6 sw=6<CR>")
-- menu_add("Tabs.S8 :set ts=8 sts=8 sw=8<CR>")
-- menu_add("Tabs.SwitchExpandTabs :set expandtab!")
-- menu_add("DAP.Add breakpoint", 'lua require"dap".toggle_breakpoint()')
-- menu_add("DAP.Continue", 'lua require"dap".continue()')
-- menu_add("DAP.Open repl", 'lua require"dap".repl.open()')
local function open_contextual_menu()
-- getcurpos() Get the position of the cursor. This is like getpos('.'), but
-- includes an extra "curswant" in the list:
-- [0, lnum, col, off, curswant] ~
-- The "curswant" number is the preferred column when moving the
-- cursor vertically. Also see |getpos()|.
-- The first "bufnum" item is always zero.
local curpos = vim.fn.getcurpos()
menu_opts = {
kind = 'menu',
prompt = 'Main menu',
experimental_mouse = true,
position = {
screenrow = curpos[2],
screencol = curpos[3],
},
-- ignored
-- width = 200,
-- height = 300,
}
-- print('### ' ..res)
require('stylish').ui_menu(vim.fn.menu_get(''), menu_opts, function(res)
vim.cmd(res)
end)
end
vim.opt.listchars = 'tab:•·,trail:·,extends:❯,precedes:❮,nbsp:×'
-- set listchars+=conceal:X
-- conceal is used by deefault if cchar does not exit
vim.opt.listchars:append('conceal:❯')
-- "set shada=!,'50,<1000,s100,:0,n$XDG_CACHE_HOME/nvim/shada
vim.g.netrw_home = vim.fn.stdpath('data') .. '/nvim'
-- quickui {{{
-- https://github.com/skywind3000/vim-quickui
-- TODO should be printed only if available
vim.g.quickui_border_style = 1
-- content = {
-- \ ['LSP -'],
-- \ ["Goto &Definition\t\\cd", 'lua vim.lsp.buf.definition()'],
-- \ ["Goto &Declaration\t\\cd", 'lua vim.lsp.buf.declaration()'],
-- \ ["Goto I&mplementation\t\\cd", 'lua vim.lsp.buf.implementation()'],
-- \ ["Hover\t\\ch", 'lua vim.lsp.buf.references()'],
-- \ ["Search &References\t\\cr", 'lua vim.lsp.buf.references()'],
-- \ ["Document &Symbols\t\\cr", 'lua vim.lsp.buf.document_symbol()'],
-- \ ["Format", 'lua vim.lsp.buf.formatting_sync(nil, 1000)'],
-- \ ["&Execute Command\\ce", 'lua vim.lsp.buf.execute_command()'],
-- \ ["&Incoming calls\\ci", 'lua vim.lsp.buf.incoming_calls()'],
-- \ ["&Outgoing calls\\ci", 'lua vim.lsp.buf.outgoing_calls()'],
-- \ ["&Signature help\\ci", 'lua vim.lsp.buf.signature_help()'],
-- \ ["&Workspace symbol\\cw", 'lua vim.lsp.buf.workspace_symbol()'],
-- \ ["&Rename\\cw", 'lua vim.lsp.buf.rename()'],
-- \ ["&Code action\\cw", 'lua vim.lsp.buf.code_action()'],
-- \ ['- Diagnostic '],
-- \ ['Display in QF', 'lua vim.diagnostic.setqflist({open = true, severity = { min = vim.diagnostic.severity.WARN } })'],
-- \ ['Set severity to warning', 'lua vim.diagnostic.config({virtual_text = { severity = { min = vim.diagnostic.severity.WARN } }})'],
-- \ ['Set severity to all', 'lua vim.diagnostic.config({virtual_text = { severity = nil }})'],
-- \ ['- Misc '],
-- \ ['Toggle indentlines', 'IndentBlanklineToggle!'],
-- \ ['Start search and replace', 'lua require("spectre").open()'],
-- \ ['Toggle obsession', 'Obsession'],
-- \ ['Toggle minimap', 'MinimapToggle'],
-- \ ['Toggle biscuits', 'lua require("nvim-biscuits").toggle_biscuits()'],
-- \ ['REPL - '],
-- \ ['Send line ', 'lua require''luadev''.exec(vim.api.nvim_get_current_line())'],
-- \ ['Send selection ', 'call <SID>luadev_run_operator(v:true)'],
-- \ ['DAP -'],
-- \ ['Add breakpoint', 'lua require"dap".toggle_breakpoint()'],
-- \ ["Continue", 'lua require"dap".continue()'],
-- \ ['Open REPL', 'lua require"dap".repl.open()']
-- \ }
-- " formatting_sync
-- " set cursor to the last position
-- let quick_opts = {'index':g:quickui#context#cursor}
-- " TODO map to lua create_menu()
-- map <RightMouse> <Cmd>call quickui#context#open(content, quick_opts)<CR>
-- vim.keymap.set('n', '<RightMouse>', '<Cmd>lua open_contextual_menu()<CR>' )
-- " can't click on it plus it disappears
-- " map <RightMouse> <Cmd>lua create_menu()<CR>
-- }}}
vim.keymap.set('n', '<F11>', '<Plug>(ToggleListchars)')
vim.keymap.set('n', '<leader>pi', '<cmd>PackerInstall<CR>')
vim.keymap.set('n', '<leader>pu', '<cmd>PackerSync<CR>')
vim.keymap.set('n', '<leader>q', '<Cmd>Sayonara!<cr>', { silent = true })
vim.keymap.set('n', '<leader>Q', '<Cmd>Sayonara<cr>', { silent = true })
vim.keymap.set('n', '<leader>rr', '<Plug>RestNvim<cr>', { remap = true, desc = 'Run an http request' })
vim.keymap.set('n', '<leader>rp', '<Plug>RestNvimPreview', { remap = true, desc = 'Preview an http request' })
-- vim.keymap.set('n', '<C-j>' , "<use>RestNvimPreview")
-- nnoremap <use>RestNvimPreview :lua require('rest-nvim').run(true)<CR>
-- nnoremap <use>RestNvimLast :lua require('rest-nvim').last()<CR>
-- repl.nvim (from hiphish) {{{
-- vim.g.repl['lua'] = {
-- \ 'bin': 'lua',
-- \ 'args': [],
-- \ 'syntax': '',
-- \ 'title': 'Lua REPL'
-- \ }
-- Send the text of a motion to the REPL
-- nmap <leader>rs <Plug>(ReplSend)
-- -- Send the current line to the REPL
-- nmap <leader>rss <Plug>(ReplSendLine)
-- nmap <leader>rs_ <Plug>(ReplSendLine)
-- -- Send the selected text to the REPL
-- vmap <leader>rs <Plug>(ReplSend)
-- }}}
-- alok/notational-fzf-vim {{{
-- use c-x to create the note
-- vim.g.nv_search_paths = []
vim.g.nv_search_paths = { '~/Nextcloud/Notes' }
vim.g.nv_default_extension = '.md'
vim.g.nv_show_preview = 1
vim.g.nv_create_note_key = 'ctrl-x'
-- String. Default is first directory found in `g:nv_search_paths`. Error thrown
--if no directory found and g:nv_main_directory is not specified
--vim.g.nv_main_directory = g:nv_main_directory or (first directory in g:nv_search_paths)
--}}}
vim.g.vsnip_snippet_dir = vim.fn.stdpath('config') .. '/vsnip'
map('n', '<Leader>$', '<Cmd>Obsession<CR>')
-- nvimdev {{{
-- call nvimdev#init(--path/to/neovim--)
vim.g.nvimdev_auto_init = 1
vim.g.nvimdev_auto_cd = 1
-- vim.g.nvimdev_auto_ctags=1
vim.g.nvimdev_auto_lint = 1
vim.g.nvimdev_build_readonly = 1
--}}}
-- nvim will load any .nvimrc in the cwd; useful for per-project settings
vim.opt.exrc = true
-- hi CustomLineWarn guifg=#FD971F
-- command! JsonPretty %!jq '.'
vim.api.nvim_create_user_command('Htags', '!hasktags .', {})
vim.api.nvim_create_user_command('JsonPretty', "%!jq '.'", {})
-- taken from justinmk's config
vim.api.nvim_create_user_command(
'Tags',
[[
!ctags -R --exclude='build*' --exclude='.vim-src/**' --exclude='venv/**' --exclude='**/site-packages/**' --exclude='data/**' --exclude='dist/**' --exclude='notebooks/**' --exclude='Notebooks/**' --exclude='*graphhopper_data/*.json' --exclude='*graphhopper/*.json' --exclude='*.json' --exclude='qgis/**' *]],
{}
)
-- " Bye bye ex mode
-- noremap Q <NOP>
vim.api.nvim_set_keymap('n', '<F1>', '<Cmd>lua open_contextual_menu()<CR>', { noremap = true, silent = false })
vim.cmd([[
map f <Plug>Sneak_f
map F <Plug>Sneak_F
map t <Plug>Sneak_t
map T <Plug>Sneak_T
]])
-- dadbod UI sql connections
-- let g:db_ui_winwidth = 30
-- dadbod is controllable via DBUI
vim.g.dbs = {
dev = 'sqlite:///home/teto/nova/jinko3/core-platform-db/db.sqlite',
}
-- luadev mappings
-- https://github.com/bfredl/nvim-luadev
-- for i=1,2 do
-- print("hello: "..tostring(i))
-- end
vim.api.nvim_set_keymap('n', ',a', '<Plug>(Luadev-Run)', { noremap = false, silent = false })
vim.api.nvim_set_keymap('v', ',,', '<Plug>(Luadev-Run)', { noremap = false, silent = false })
vim.api.nvim_set_keymap('n', ',,', '<Plug>(Luadev-RunLine)', { noremap = false, silent = false })
map('n', '<leader>rg', '<Cmd>Grepper -tool git -open -switch<CR>', { remap = true })
map('n', '<leader>rgb', '<Cmd>Grepper -tool rg -open -switch -buffer<CR>', { remap = true })
map('n', '<leader>rg', '<Cmd>Grepper -tool rg -open -switch<CR>', { remap = true })
-- vim.api.nvim_set_keymap(
-- 'n',
-- '<F1>',
-- "<Cmd>lua require'stylish'.ui_menu(vim.fn.menu_get(''), {kind=menu, prompt = 'Main Menu', experimental_mouse = true}, function(res) print('### ' ..res) end)<CR>",
-- { noremap = true, silent = true }
-- )
vim.o.grepprg = 'rg --vimgrep --no-heading --smart-case'
| gpl-2.0 |
lemonkit/VisualCocos | frameworks/cocos2d-x/cocos/scripting/lua-bindings/auto/api/CameraBackgroundColorBrush.lua | 9 | 1583 |
--------------------------------
-- @module CameraBackgroundColorBrush
-- @extend CameraBackgroundDepthBrush
-- @parent_module cc
--------------------------------
-- Set clear color<br>
-- param color Color used to clear the color buffer
-- @function [parent=#CameraBackgroundColorBrush] setColor
-- @param self
-- @param #color4f_table color
-- @return CameraBackgroundColorBrush#CameraBackgroundColorBrush self (return value: cc.CameraBackgroundColorBrush)
--------------------------------
-- Create a color brush<br>
-- param color Color used to clear the color buffer<br>
-- param depth Depth used to clear the depth buffer<br>
-- return Created brush
-- @function [parent=#CameraBackgroundColorBrush] create
-- @param self
-- @param #color4f_table color
-- @param #float depth
-- @return CameraBackgroundColorBrush#CameraBackgroundColorBrush ret (return value: cc.CameraBackgroundColorBrush)
--------------------------------
-- Get brush type. Should be BrushType::COLOR<br>
-- return brush type
-- @function [parent=#CameraBackgroundColorBrush] getBrushType
-- @param self
-- @return int#int ret (return value: int)
--------------------------------
--
-- @function [parent=#CameraBackgroundColorBrush] init
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
--
-- @function [parent=#CameraBackgroundColorBrush] CameraBackgroundColorBrush
-- @param self
-- @return CameraBackgroundColorBrush#CameraBackgroundColorBrush self (return value: cc.CameraBackgroundColorBrush)
return nil
| mit |
ddumont/darkstar | scripts/zones/RaKaznar_Inner_Court/Zone.lua | 33 | 1290 | -----------------------------------
--
-- Zone: Ra’Kanzar Inner Court (276)
--
-----------------------------------
package.loaded["scripts/zones/RaKaznar_Inner_Court/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/RaKaznar_Inner_Court/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
player:setPos(-476,-520.5,20,0);
end
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
Squeakz/darkstar | scripts/zones/RuLude_Gardens/npcs/Perisa-Neburusa.lua | 13 | 1063 | -----------------------------------
-- Area: Ru'Lude Gardens
-- NPC: Perisa-Neburusa
-- Type: Residence Renter
-- @zone: 243
-- @pos 54.651 8.999 -74.372
--
-- Auto-Script: Requires Verification (Verfied by Brawndo)
-----------------------------------
package.loaded["scripts/zones/RuLude_Gardens/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x004c);
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 |
ddumont/darkstar | scripts/zones/Port_San_dOria/npcs/Coullave.lua | 17 | 1986 | -----------------------------------
-- Area: Port San d'Oria
-- NPC: Coullave
-- Standard Merchant NPC
-----------------------------------
package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Port_San_dOria/TextIDs");
require("scripts/globals/quests");
require("scripts/globals/shop");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
local FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE);
if (FlyerForRegine == 1) then
local count = trade:getItemCount();
local MagicFlyer = trade:hasItemQty(532,1);
if (MagicFlyer == true and count == 1) then
player:messageSpecial(FLYER_REFUSED);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,COULLAVE_SHOP_DIALOG);
stock = {0x1020,4445,1, --Ether
0x43a1,1107,1, --Grenade
0x30a8,552,1, --Hachimaki
0x3128,833,1, --Kenpogi
0x32a8,424,1, --Kyahan
0x1010,837,1, --Potion
0x31a8,458,1, --Tekko
0x3228,666,1, --Sitabaki
0x02c0,96,2, --Bamboo Stick
0x1037,736,2, --Echo Drops
0x1034,290,3, --Antidote
0x1036,2387,3, --Eye Drops
0x349d,1150,3} --Leather Ring
showNationShop(player, NATION_SANDORIA, 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 |
Squeakz/darkstar | scripts/globals/spells/burn.lua | 17 | 1851 | -----------------------------------------
-- Spell: Burn
-- Deals fire damage that lowers an enemy's intelligence and gradually reduces its HP.
-----------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
if (target:getStatusEffect(EFFECT_DROWN) ~= nil) then
spell:setMsg(75); -- no effect
else
local dINT = caster:getStat(MOD_INT)-target:getStat(MOD_INT);
local resist = applyResistance(caster,spell,target,dINT,36,0);
if (resist <= 0.125) then
spell:setMsg(85);
else
if (target:getStatusEffect(EFFECT_FROST) ~= nil) then
target:delStatusEffect(EFFECT_FROST);
end;
local sINT = caster:getStat(MOD_INT);
local DOT = getElementalDebuffDOT(sINT);
local effect = target:getStatusEffect(EFFECT_BURN);
local noeffect = false;
if (effect ~= nil) then
if (effect:getPower() >= DOT) then
noeffect = true;
end;
end;
if (noeffect) then
spell:setMsg(75); -- no effect
else
if (effect ~= nil) then
target:delStatusEffect(EFFECT_BURN);
end;
spell:setMsg(237);
local duration = math.floor(ELEMENTAL_DEBUFF_DURATION * resist);
target:addStatusEffect(EFFECT_BURN,DOT, 3, ELEMENTAL_DEBUFF_DURATION,FLAG_ERASBLE);
end;
end;
end;
return EFFECT_BURN;
end; | gpl-3.0 |
pvpgn/pvpgn-server | lua/extend/enum/messagebox.lua | 6 | 1435 | --[[
Copyright (C) 2014 HarpyWar (harpywar@gmail.com)
This file is a part of the PvPGN Project http://pvpgn.pro
Licensed under the same terms as Lua itself.
]]--
-- https://github.com/pvpgn/pvpgn-server/issues/15
-- http://msdn.microsoft.com/en-us/library/windows/desktop/ms645505(v=vs.85).aspx
--
-- use math_or(mb_type1, mb_type2) to combine two messagebox types
--[[ Example code to display Windows MessageBox:
local mb_type = math_or(MB_DEFBUTTON2, math_or(MB_ABORTRETRYIGNORE, MB_ICONEXCLAMATION) )
api.messagebox_show(account.name, "aaaaaaaaaaaaaaaaaaaaaaaaawwadwwadawdawdawdwadawdaaw", "MessageBox from " .. config.servername, mb_type)
]]--
MB_ABORTRETRYIGNORE,
MB_CANCELTRYCONTINUE,
MB_HELP,
MB_OK,
MB_OKCANCEL,
MB_RETRYCANCEL,
MB_YESNO,
MB_YESNOCANCEL,
MB_ICONEXCLAMATION,
MB_ICONWARNING,
MB_ICONINFORMATION,
MB_ICONASTERISK,
MB_ICONQUESTION,
MB_ICONSTOP,
MB_ICONERROR,
MB_ICONHAND,
MB_DEFBUTTON1,
MB_DEFBUTTON2,
MB_DEFBUTTON3,
MB_DEFBUTTON4,
MB_APPLMODAL,
MB_SYSTEMMODAL,
MB_TASKMODAL,
MB_DEFAULT_DESKTOP_ONLY,
MB_RIGHT,
MB_RTLREADING,
MB_SETFOREGROUND,
MB_TOPMOST,
MB_SERVICE_NOTIFICATION
= 0x00000002,0x00000006,0x00004000,0x00000000,0x00000001,0x00000005,0x00000004,0x00000003,0x00000030,0x00000030,0x00000040,0x00000040,0x00000020,0x00000010,0x00000010,0x00000010,0x00000000,0x00000100,0x00000200,0x00000300,0x00000000,0x00001000,0x00002000,0x00020000,0x00080000,0x00100000,0x00010000,0x00040000,0x00200000
| gpl-2.0 |
bjornbytes/graphql-lua | graphql/rules.lua | 1 | 18019 | local path = (...):gsub('%.[^%.]+$', '')
local types = require(path .. '.types')
local util = require(path .. '.util')
local schema = require(path .. '.schema')
local introspection = require(path .. '.introspection')
local function getParentField(context, name, count)
if introspection.fieldMap[name] then return introspection.fieldMap[name] end
count = count or 1
local parent = context.objects[#context.objects - count]
-- Unwrap lists and non-null types
while parent.ofType do
parent = parent.ofType
end
return parent.fields[name]
end
local rules = {}
function rules.uniqueOperationNames(node, context)
local name = node.name and node.name.value
if name then
if context.operationNames[name] then
error('Multiple operations exist named "' .. name .. '"')
end
context.operationNames[name] = true
end
end
function rules.loneAnonymousOperation(node, context)
local name = node.name and node.name.value
if context.hasAnonymousOperation or (not name and next(context.operationNames)) then
error('Cannot have more than one operation when using anonymous operations')
end
if not name then
context.hasAnonymousOperation = true
end
end
function rules.fieldsDefinedOnType(node, context)
if context.objects[#context.objects] == false then
local parent = context.objects[#context.objects - 1]
while parent.ofType do parent = parent.ofType end
error('Field "' .. node.name.value .. '" is not defined on type "' .. parent.name .. '"')
end
end
function rules.argumentsDefinedOnType(node, context)
if node.arguments then
local parentField = getParentField(context, node.name.value)
for _, argument in pairs(node.arguments) do
local name = argument.name.value
if not parentField.arguments[name] then
error('Non-existent argument "' .. name .. '"')
end
end
end
end
function rules.scalarFieldsAreLeaves(node, context)
if context.objects[#context.objects].__type == 'Scalar' and node.selectionSet then
error('Scalar values cannot have subselections')
end
end
function rules.compositeFieldsAreNotLeaves(node, context)
local _type = context.objects[#context.objects].__type
local isCompositeType = _type == 'Object' or _type == 'Interface' or _type == 'Union'
if isCompositeType and not node.selectionSet then
error('Composite types must have subselections')
end
end
function rules.unambiguousSelections(node, context)
local selectionMap = {}
local seen = {}
local function findConflict(entryA, entryB)
-- Parent types can't overlap if they're different objects.
-- Interface and union types may overlap.
if entryA.parent ~= entryB.parent and entryA.__type == 'Object' and entryB.__type == 'Object' then
return
end
-- Error if there are aliases that map two different fields to the same name.
if entryA.field.name.value ~= entryB.field.name.value then
return 'Type name mismatch'
end
-- Error if there are fields with the same name that have different return types.
if entryA.definition and entryB.definition and entryA.definition ~= entryB.definition then
return 'Return type mismatch'
end
-- Error if arguments are not identical for two fields with the same name.
local argsA = entryA.field.arguments or {}
local argsB = entryB.field.arguments or {}
if #argsA ~= #argsB then
return 'Argument mismatch'
end
local argMap = {}
for i = 1, #argsA do
argMap[argsA[i].name.value] = argsA[i].value
end
for i = 1, #argsB do
local name = argsB[i].name.value
if not argMap[name] then
return 'Argument mismatch'
elseif argMap[name].kind ~= argsB[i].value.kind then
return 'Argument mismatch'
elseif argMap[name].value ~= argsB[i].value.value then
return 'Argument mismatch'
end
end
end
local function validateField(key, entry)
if selectionMap[key] then
for i = 1, #selectionMap[key] do
local conflict = findConflict(selectionMap[key][i], entry)
if conflict then
error(conflict)
end
end
table.insert(selectionMap[key], entry)
else
selectionMap[key] = { entry }
end
end
-- Recursively make sure that there are no ambiguous selections with the same name.
local function validateSelectionSet(selectionSet, parentType)
for _, selection in ipairs(selectionSet.selections) do
if selection.kind == 'field' then
if not parentType or not parentType.fields or not parentType.fields[selection.name.value] then return end
local key = selection.alias and selection.alias.name.value or selection.name.value
local definition = parentType.fields[selection.name.value].kind
local fieldEntry = {
parent = parentType,
field = selection,
definition = definition
}
validateField(key, fieldEntry)
elseif selection.kind == 'inlineFragment' then
local parentType = selection.typeCondition and context.schema:getType(selection.typeCondition.name.value) or parentType
validateSelectionSet(selection.selectionSet, parentType)
elseif selection.kind == 'fragmentSpread' then
local fragmentDefinition = context.fragmentMap[selection.name.value]
if fragmentDefinition and not seen[fragmentDefinition] then
seen[fragmentDefinition] = true
if fragmentDefinition and fragmentDefinition.typeCondition then
local parentType = context.schema:getType(fragmentDefinition.typeCondition.name.value)
validateSelectionSet(fragmentDefinition.selectionSet, parentType)
end
end
end
end
end
validateSelectionSet(node, context.objects[#context.objects])
end
function rules.uniqueArgumentNames(node, context)
if node.arguments then
local arguments = {}
for _, argument in ipairs(node.arguments) do
local name = argument.name.value
if arguments[name] then
error('Encountered multiple arguments named "' .. name .. '"')
end
arguments[name] = true
end
end
end
function rules.argumentsOfCorrectType(node, context)
if node.arguments then
local parentField = getParentField(context, node.name.value)
for _, argument in pairs(node.arguments) do
local name = argument.name.value
local argumentType = parentField.arguments[name]
util.coerceValue(argument.value, argumentType.kind or argumentType)
end
end
end
function rules.requiredArgumentsPresent(node, context)
local arguments = node.arguments or {}
local parentField = getParentField(context, node.name.value)
for name, argument in pairs(parentField.arguments) do
if argument.__type == 'NonNull' then
local present = util.find(arguments, function(argument)
return argument.name.value == name
end)
if not present then
error('Required argument "' .. name .. '" was not supplied.')
end
end
end
end
function rules.uniqueFragmentNames(node, context)
local fragments = {}
for _, definition in ipairs(node.definitions) do
if definition.kind == 'fragmentDefinition' then
local name = definition.name.value
if fragments[name] then
error('Encountered multiple fragments named "' .. name .. '"')
end
fragments[name] = true
end
end
end
function rules.fragmentHasValidType(node, context)
if not node.typeCondition then return end
local name = node.typeCondition.name.value
local kind = context.schema:getType(name)
if not kind then
error('Fragment refers to non-existent type "' .. name .. '"')
end
if kind.__type ~= 'Object' and kind.__type ~= 'Interface' and kind.__type ~= 'Union' then
error('Fragment type must be an Object, Interface, or Union, got ' .. kind.__type)
end
end
function rules.noUnusedFragments(node, context)
for _, definition in ipairs(node.definitions) do
if definition.kind == 'fragmentDefinition' then
local name = definition.name.value
if not context.usedFragments[name] then
error('Fragment "' .. name .. '" was not used.')
end
end
end
end
function rules.fragmentSpreadTargetDefined(node, context)
if not context.fragmentMap[node.name.value] then
error('Fragment spread refers to non-existent fragment "' .. node.name.value .. '"')
end
end
function rules.fragmentDefinitionHasNoCycles(node, context)
local seen = { [node.name.value] = true }
local function detectCycles(selectionSet)
for _, selection in ipairs(selectionSet.selections) do
if selection.kind == 'inlineFragment' then
detectCycles(selection.selectionSet)
elseif selection.kind == 'fragmentSpread' then
if seen[selection.name.value] then
error('Fragment definition has cycles')
end
seen[selection.name.value] = true
local fragmentDefinition = context.fragmentMap[selection.name.value]
if fragmentDefinition and fragmentDefinition.typeCondition then
detectCycles(fragmentDefinition.selectionSet)
end
end
end
end
detectCycles(node.selectionSet)
end
function rules.fragmentSpreadIsPossible(node, context)
local fragment = node.kind == 'inlineFragment' and node or context.fragmentMap[node.name.value]
local parentType = context.objects[#context.objects - 1]
while parentType.ofType do parentType = parentType.ofType end
local fragmentType
if node.kind == 'inlineFragment' then
fragmentType = node.typeCondition and context.schema:getType(node.typeCondition.name.value) or parentType
else
fragmentType = context.schema:getType(fragment.typeCondition.name.value)
end
-- Some types are not present in the schema. Let other rules handle this.
if not parentType or not fragmentType then return end
local function getTypes(kind)
if kind.__type == 'Object' then
return { [kind] = kind }
elseif kind.__type == 'Interface' then
return context.schema:getImplementors(kind.name)
elseif kind.__type == 'Union' then
local types = {}
for i = 1, #kind.types do
types[kind.types[i]] = kind.types[i]
end
return types
else
return {}
end
end
local parentTypes = getTypes(parentType)
local fragmentTypes = getTypes(fragmentType)
local valid = util.find(parentTypes, function(kind)
return fragmentTypes[kind]
end)
if not valid then
error('Fragment type condition is not possible for given type')
end
end
function rules.uniqueInputObjectFields(node, context)
local function validateValue(value)
if value.kind == 'listType' or value.kind == 'nonNullType' then
return validateValue(value.type)
elseif value.kind == 'inputObject' then
local fieldMap = {}
for _, field in ipairs(value.values) do
if fieldMap[field.name] then
error('Multiple input object fields named "' .. field.name .. '"')
end
fieldMap[field.name] = true
validateValue(field.value)
end
end
end
validateValue(node.value)
end
function rules.directivesAreDefined(node, context)
if not node.directives then return end
for _, directive in pairs(node.directives) do
if not context.schema:getDirective(directive.name.value) then
error('Unknown directive "' .. directive.name.value .. '"')
end
end
end
function rules.variablesHaveCorrectType(node, context)
local function validateType(type)
if type.kind == 'listType' or type.kind == 'nonNullType' then
validateType(type.type)
elseif type.kind == 'namedType' then
local schemaType = context.schema:getType(type.name.value)
if not schemaType then
error('Variable specifies unknown type "' .. tostring(type.name.value) .. '"')
elseif schemaType.__type ~= 'Scalar' and schemaType.__type ~= 'Enum' and schemaType.__type ~= 'InputObject' then
error('Variable types must be scalars, enums, or input objects, got "' .. schemaType.__type .. '"')
end
end
end
if node.variableDefinitions then
for _, definition in ipairs(node.variableDefinitions) do
validateType(definition.type)
end
end
end
function rules.variableDefaultValuesHaveCorrectType(node, context)
if node.variableDefinitions then
for _, definition in ipairs(node.variableDefinitions) do
if definition.type.kind == 'nonNullType' and definition.defaultValue then
error('Non-null variables can not have default values')
elseif definition.defaultValue then
util.coerceValue(definition.defaultValue, context.schema:getType(definition.type.name.value))
end
end
end
end
function rules.variablesAreUsed(node, context)
if node.variableDefinitions then
for _, definition in ipairs(node.variableDefinitions) do
local variableName = definition.variable.name.value
if not context.variableReferences[variableName] then
error('Unused variable "' .. variableName .. '"')
end
end
end
end
function rules.variablesAreDefined(node, context)
if context.variableReferences then
local variableMap = {}
for _, definition in ipairs(node.variableDefinitions or {}) do
variableMap[definition.variable.name.value] = true
end
for variable in pairs(context.variableReferences) do
if not variableMap[variable] then
error('Unknown variable "' .. variable .. '"')
end
end
end
end
function rules.variableUsageAllowed(node, context)
if context.currentOperation then
local variableMap = {}
for _, definition in ipairs(context.currentOperation.variableDefinitions or {}) do
variableMap[definition.variable.name.value] = definition
end
local arguments
if node.kind == 'field' then
arguments = { [node.name.value] = node.arguments }
elseif node.kind == 'fragmentSpread' then
local seen = {}
local function collectArguments(referencedNode)
if referencedNode.kind == 'selectionSet' then
for _, selection in ipairs(referencedNode.selections) do
if not seen[selection] then
seen[selection] = true
collectArguments(selection)
end
end
elseif referencedNode.kind == 'field' and referencedNode.arguments then
local fieldName = referencedNode.name.value
arguments[fieldName] = arguments[fieldName] or {}
for _, argument in ipairs(referencedNode.arguments) do
table.insert(arguments[fieldName], argument)
end
elseif referencedNode.kind == 'inlineFragment' then
return collectArguments(referencedNode.selectionSet)
elseif referencedNode.kind == 'fragmentSpread' then
local fragment = context.fragmentMap[referencedNode.name.value]
return fragment and collectArguments(fragment.selectionSet)
end
end
local fragment = context.fragmentMap[node.name.value]
if fragment then
arguments = {}
collectArguments(fragment.selectionSet)
end
end
if not arguments then return end
for field in pairs(arguments) do
local parentField = getParentField(context, field)
for i = 1, #arguments[field] do
local argument = arguments[field][i]
if argument.value.kind == 'variable' then
local argumentType = parentField.arguments[argument.name.value]
local variableName = argument.value.name.value
local variableDefinition = variableMap[variableName]
local hasDefault = variableDefinition.defaultValue ~= nil
local function typeFromAST(variable)
local innerType
if variable.kind == 'listType' then
innerType = typeFromAST(variable.type)
return innerType and types.list(innerType)
elseif variable.kind == 'nonNullType' then
innerType = typeFromAST(variable.type)
return innerType and types.nonNull(innerType)
else
assert(variable.kind == 'namedType', 'Variable must be a named type')
return context.schema:getType(variable.name.value)
end
end
local variableType = typeFromAST(variableDefinition.type)
if hasDefault and variableType.__type ~= 'NonNull' then
variableType = types.nonNull(variableType)
end
local function isTypeSubTypeOf(subType, superType)
if subType == superType then return true end
if superType.__type == 'NonNull' then
if subType.__type == 'NonNull' then
return isTypeSubTypeOf(subType.ofType, superType.ofType)
end
return false
elseif subType.__type == 'NonNull' then
return isTypeSubTypeOf(subType.ofType, superType)
end
if superType.__type == 'List' then
if subType.__type == 'List' then
return isTypeSubTypeOf(subType.ofType, superType.ofType)
end
return false
elseif subType.__type == 'List' then
return false
end
if subType.__type ~= 'Object' then return false end
if superType.__type == 'Interface' then
local implementors = context.schema:getImplementors(superType.name)
return implementors and implementors[context.schema:getType(subType.name)]
elseif superType.__type == 'Union' then
local types = superType.types
for i = 1, #types do
if types[i] == subType then
return true
end
end
return false
end
return false
end
if not isTypeSubTypeOf(variableType, argumentType) then
error('Variable type mismatch')
end
end
end
end
end
end
return rules
| mit |
ddumont/darkstar | scripts/zones/La_Theine_Plateau/mobs/Bloodtear_Baldurf.lua | 13 | 1668 | -----------------------------------
-- Area: La Theine Plateau
-- MOB: Bloodtear_Baldurf
-----------------------------------
require("scripts/globals/titles");
require("scripts/zones/La_Theine_Plateau/MobIDs");
-----------------------------------
-- onMobInitialize Action
-----------------------------------
function onMobInitialize(mob)
mob:setMobMod(MOBMOD_ALWAYS_AGGRO, 1);
mob:setMobMod(MOBMOD_MAIN_2HOUR, 1);
mob:setMobMod(MOBMOD_2HOUR_MULTI, 1);
mob:setMobMod(MOBMOD_DRAW_IN, 1);
end;
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, player, isKiller)
player:addTitle(THE_HORNSPLITTER);
end;
-----------------------------------
-- onMobDespawn
-----------------------------------
function onMobDespawn(mob)
local mobID = mob:getID();
local chanceForLambert = 0;
if (GetServerVariable("[POP]Lumbering_Lambert") <= os.time(t)) then
chanceForLambert = math.random(1,100);
end
if (chanceForLambert > 95 and GetMobAction(Battering_Ram) == ACTION_NONE and GetMobAction(Lumbering_Lambert) == ACTION_NONE) then
UpdateNMSpawnPoint(Lumbering_Lambert);
GetMobByID(Lumbering_Lambert):setRespawnTime(GetMobRespawnTime(Battering_Ram));
DeterMob(mobID, true);
else
GetMobByID(Battering_Ram):setRespawnTime(GetMobRespawnTime(Battering_Ram));
DeterMob(mobID, true);
end
SetServerVariable("[POP]Bloodtear_Baldurf", os.time(t) + math.random(75600, 86400)); -- 21-24hours repop
end;
| gpl-3.0 |
Squeakz/darkstar | scripts/zones/Meriphataud_Mountains/npcs/Beastmen_s_Banner.lua | 13 | 1028 | -----------------------------------
-- Area: Meriphataud_Mountains
-- NPC: Beastmen_s_Banner
-- @pos 592.850 -16.765 -518.802 119
-----------------------------------
package.loaded["scripts/zones/Meriphataud_Mountains/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Meriphataud_Mountains/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(BEASTMEN_BANNER);
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);
end; | gpl-3.0 |
ddumont/darkstar | scripts/zones/Port_Bastok/npcs/Numa.lua | 17 | 1786 | -----------------------------------
-- Area: Port Bastok
-- NPC: Numa
-- Standard Merchant NPC
-- Confirmed shop stock, August 2013
-----------------------------------
require("scripts/globals/shop");
package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil;
require("scripts/zones/Port_Bastok/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,NUMA_SHOP_DIALOG);
stock = {
0x30A9, 5079,1, --Cotton Hachimaki
0x3129, 7654,1, --Cotton Dogi
0x31A9, 4212,1, --Cotton Tekko
0x3229, 6133,1, --Cotton Sitabaki
0x32A9, 3924,1, --Cotton Kyahan
0x3395, 3825,1, --Silver Obi
0x30A8, 759,2, --Hachimaki
0x3128, 1145,2, --Kenpogi
0x31A8, 630,2, --Tekko
0x3228, 915,2, --Sitabaki
0x32A8, 584,2, --Kyahan
0x02C0, 132,2, --Bamboo Stick
0x025D, 180,3, --Pickaxe
0x16EB, 13500,3, --Toolbag (Ino)
0x16EC, 18000,3, --Toolbag (Shika)
0x16ED, 18000,3 --Toolbag (Cho)
}
showNationShop(player, NATION_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 |
ddumont/darkstar | scripts/zones/PsoXja/npcs/_097.lua | 14 | 2875 | -----------------------------------
-- Area: Pso'Xja
-- NPC: _097 (Stone Gate)
-- Notes: Spawns Gargoyle when triggered
-- @pos 290.000 -1.925 -81.600 9
-----------------------------------
package.loaded["scripts/zones/PsoXja/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/status");
require("scripts/zones/PsoXja/TextIDs");
require("scripts/globals/keyitems");
-----------------------------------
-- onTrade
-----------------------------------
function onTrade(player,npc,trade)
if ((trade:hasItemQty(1115,1) or trade:hasItemQty(1023,1) or trade:hasItemQty(1022,1)) and trade:getItemCount() == 1 and player:getMainJob() == JOBS.THF) then
local Z=player:getZPos();
if (npc:getAnimation() == 9) then
if (Z <= -82) then
if (GetMobAction(16814088) == 0) then
local Rand = math.random(1,2); -- estimated 50% success as per the wiki
if (Rand == 1) then -- Spawn Gargoyle
player:messageSpecial(DISCOVER_DISARM_FAIL + 0x8000, 0, 0, 0, 0, true);
SpawnMob(16814088):updateClaim(player); -- Gargoyle
else
player:messageSpecial(DISCOVER_DISARM_SUCCESS + 0x8000, 0, 0, 0, 0, true);
npc:openDoor(30);
end
player:tradeComplete();
else
player:messageSpecial(DOOR_LOCKED);
end
end
end
end
end;
-----------------------------------
-- onTrigger
-----------------------------------
function onTrigger(player,npc)
local Z=player:getZPos();
if (npc:getAnimation() == 9) then
if (Z <= -82) then
if (GetMobAction(16814088) == 0) then
local Rand = math.random(1,10);
if (Rand <=9) then -- Spawn Gargoyle
player:messageSpecial(TRAP_ACTIVATED + 0x8000, 0, 0, 0, 0, true);
SpawnMob(16814088):updateClaim(player); -- Gargoyle
else
player:messageSpecial(TRAP_FAILS + 0x8000, 0, 0, 0, 0, true);
npc:openDoor(30);
end
else
player:messageSpecial(DOOR_LOCKED);
end
elseif (Z >= -81) then
player:startEvent(0x001A);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
if (csid == 0x001A and option == 1) then
player:setPos(260,-0.25,-20,254,111);
end
end; | gpl-3.0 |
ddumont/darkstar | scripts/zones/Windurst_Walls/npcs/Hiwon-Biwon.lua | 17 | 3908 | -----------------------------------
-- Area: Windurst Walls
-- NPC: Hiwon-Biwon
-- Involved In Quest: Making Headlines, Curses, Foiled...Again!?
-- Working 100%
-----------------------------------
package.loaded["scripts/zones/Windurst_Walls/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/zones/Windurst_Walls/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
function testflag(set,flag)
return (set % (2*flag) >= flag)
end
local MakingHeadlines = player:getQuestStatus(WINDURST,MAKING_HEADLINES);
local CFA2 = player:getQuestStatus(WINDURST,CURSES_FOILED_AGAIN_2);
-- Curses,Foiled ... Again!?
if (CFA2 == QUEST_ACCEPTED and player:hasItem(552) == false) then
player:startEvent(0x00B6); -- get Hiwon's hair
elseif (CFA2 == QUEST_COMPLETED and MakingHeadlines ~= QUEST_ACCEPTED) then
player:startEvent(0x00B9); -- New Dialog after CFA2
-- Making Headlines
elseif (MakingHeadlines == 1) then
prog = player:getVar("QuestMakingHeadlines_var");
-- Variable to track if player has talked to 4 NPCs and a door
-- 1 = Kyume
-- 2 = Yujuju
-- 4 = Hiwom
-- 8 = Umumu
-- 16 = Mahogany Door
if (testflag(tonumber(prog),4) == false) then
if (player:getQuestStatus(WINDURST,CURSES_FOILED_AGAIN_1) == 1) then
if (math.random(1,2) == 1) then
player:startEvent(0x011b); -- Give scoop while sick
else
player:startEvent(0x011c); -- Give scoop while sick
end
else
player:startEvent(0x0119); -- Give scoop
end
else
player:startEvent(0x011a); -- "Getting back to the maater at hand-wand..."
end
else
local rand = math.random(1,5);
if (rand == 1) then
print (rand);
player:startEvent(0x0131); -- Standard Conversation
elseif (rand == 2) then
print (rand);
player:startEvent(0x0132); -- Standard Conversation
elseif (rand == 3) then
print (rand);
player:startEvent(0x00a8); -- Standard Conversation
elseif (rand == 4) then
print (rand);
player:startEvent(0x00aa); -- Standard Conversation
elseif (rand == 5) then
print (rand);
player:startEvent(0x00a9); -- 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);
-- Making Headlines
if (csid == 0x0119 or csid == 0x011b or csid == 0x011c) then
prog = player:getVar("QuestMakingHeadlines_var");
player:addKeyItem(WINDURST_WALLS_SCOOP);
player:messageSpecial(KEYITEM_OBTAINED,WINDURST_WALLS_SCOOP);
player:setVar("QuestMakingHeadlines_var",prog+4);
-- Curses,Foiled...Again!?
elseif (csid == 0x00B6) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,552); -- Hiwon's hair
else
player:addItem(552);
player:messageSpecial(ITEM_OBTAINED,552); -- Hiwon's hair
end
end
end;
| gpl-3.0 |
ddumont/darkstar | scripts/zones/Crawlers_Nest/npcs/qm10.lua | 57 | 2127 | -----------------------------------
-- Area: Crawlers' Nest
-- NPC: qm10 (??? - Exoray Mold Crumbs)
-- Involved in Quest: In Defiant Challenge
-- @pos -83.391 -8.222 79.065 197
-----------------------------------
package.loaded["scripts/zones/Crawlers_Nest/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/keyitems");
require("scripts/globals/settings");
require("scripts/zones/Crawlers_Nest/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (OldSchoolG1 == false) then
if (player:hasItem(1089) == false and player:hasKeyItem(EXORAY_MOLD_CRUMB1) == false
and player:getQuestStatus(JEUNO,IN_DEFIANT_CHALLENGE) == QUEST_ACCEPTED) then
player:addKeyItem(EXORAY_MOLD_CRUMB1);
player:messageSpecial(KEYITEM_OBTAINED,EXORAY_MOLD_CRUMB1);
end
if (player:hasKeyItem(EXORAY_MOLD_CRUMB1) and player:hasKeyItem(EXORAY_MOLD_CRUMB2) and player:hasKeyItem(EXORAY_MOLD_CRUMB3)) then
if (player:getFreeSlotsCount() >= 1) then
player:addItem(1089, 1);
player:messageSpecial(ITEM_OBTAINED, 1089);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, 1089);
end
end
if (player:hasItem(1089)) then
player:delKeyItem(EXORAY_MOLD_CRUMB1);
player:delKeyItem(EXORAY_MOLD_CRUMB2);
player:delKeyItem(EXORAY_MOLD_CRUMB3);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID2: %u",csid);
-- printf("RESULT2: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
Squeakz/darkstar | scripts/zones/Crawlers_Nest/npcs/qm10.lua | 57 | 2127 | -----------------------------------
-- Area: Crawlers' Nest
-- NPC: qm10 (??? - Exoray Mold Crumbs)
-- Involved in Quest: In Defiant Challenge
-- @pos -83.391 -8.222 79.065 197
-----------------------------------
package.loaded["scripts/zones/Crawlers_Nest/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/keyitems");
require("scripts/globals/settings");
require("scripts/zones/Crawlers_Nest/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (OldSchoolG1 == false) then
if (player:hasItem(1089) == false and player:hasKeyItem(EXORAY_MOLD_CRUMB1) == false
and player:getQuestStatus(JEUNO,IN_DEFIANT_CHALLENGE) == QUEST_ACCEPTED) then
player:addKeyItem(EXORAY_MOLD_CRUMB1);
player:messageSpecial(KEYITEM_OBTAINED,EXORAY_MOLD_CRUMB1);
end
if (player:hasKeyItem(EXORAY_MOLD_CRUMB1) and player:hasKeyItem(EXORAY_MOLD_CRUMB2) and player:hasKeyItem(EXORAY_MOLD_CRUMB3)) then
if (player:getFreeSlotsCount() >= 1) then
player:addItem(1089, 1);
player:messageSpecial(ITEM_OBTAINED, 1089);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, 1089);
end
end
if (player:hasItem(1089)) then
player:delKeyItem(EXORAY_MOLD_CRUMB1);
player:delKeyItem(EXORAY_MOLD_CRUMB2);
player:delKeyItem(EXORAY_MOLD_CRUMB3);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID2: %u",csid);
-- printf("RESULT2: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
ddumont/darkstar | scripts/zones/Kamihr_Drifts/Zone.lua | 17 | 1219 | -----------------------------------
--
-- Zone: Kamihr Drifts
--
-----------------------------------
require("scripts/globals/settings");
package.loaded["scripts/zones/Kamihr_Drifts/TextIDs"] = nil;
require("scripts/zones/Kamihr_Drifts/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
player:setPos(500,72,-479,191);
end
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
Squeakz/darkstar | scripts/globals/spells/chocobo_mazurka.lua | 27 | 1162 | -----------------------------------------
-- Spell: Chocobo Mazurka
-- Gives party members enhanced movement
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
local power = 24;
local iBoost = caster:getMod(MOD_MAZURKA_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT);
local duration = 120;
duration = duration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1);
if (caster:hasStatusEffect(EFFECT_SOUL_VOICE)) then
duration = duration * 2;
elseif (caster:hasStatusEffect(EFFECT_MARCATO)) then
duration = duration * 1.5;
end
caster:delStatusEffect(EFFECT_MARCATO);
if (caster:hasStatusEffect(EFFECT_TROUBADOUR)) then
duration = duration * 2;
end
if not (target:addBardSong(caster,EFFECT_MAZURKA,power,0,duration,caster:getID(), 0, 1)) then
spell:setMsg(75);
end
return EFFECT_MAZURKA;
end;
| gpl-3.0 |
ddumont/darkstar | scripts/zones/Selbina/npcs/Gabwaleid.lua | 14 | 1534 | -----------------------------------
-- Area: Selbina
-- NPC: Gabwaleid
-- Involved in Quest: Riding on the Clouds
-- @pos -17 -7 11 248
-----------------------------------
package.loaded["scripts/zones/Selbina/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Selbina/TextIDs");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(JEUNO,RIDING_ON_THE_CLOUDS) == QUEST_ACCEPTED and player:getVar("ridingOnTheClouds_3") == 4) then
if (trade:hasItemQty(1127,1) and trade:getItemCount() == 1) then -- Trade Kindred seal
player:setVar("ridingOnTheClouds_3",0);
player:tradeComplete();
player:addKeyItem(SOMBER_STONE);
player:messageSpecial(KEYITEM_OBTAINED,SOMBER_STONE);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0258);
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 |
ddumont/darkstar | scripts/zones/Gustav_Tunnel/Zone.lua | 11 | 1655 | -----------------------------------
--
-- Zone: Gustav Tunnel (212)
--
-----------------------------------
package.loaded["scripts/zones/Gustav_Tunnel/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Gustav_Tunnel/TextIDs");
require("scripts/globals/settings");
require("scripts/globals/zone");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
-- Bune
SetRespawnTime(17645578, 900, 10800);
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then
player:setPos(-260.013,-21.802,-276.352,205);
end
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
Squeakz/darkstar | scripts/globals/weaponskills/shadow_of_death.lua | 2 | 1254 | -----------------------------------
-- Shadow of Death
-- Scythe weapon skill
-- Skill Level: 70
-- Delivers a dark elemental attack. Damage varies with TP.
-- Aligned with the Snow Gorget & Aqua Gorget.
-- Aligned with the Snow Belt & Aqua Belt.
-- Element: Dark
-- Modifiers: STR:40% ; INT:40%
-- 100%TP 200%TP 300%TP
-- 1.00 2.50 3.00
-----------------------------------
require("scripts/globals/magic");
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary)
local params = {};
params.ftp100 = 1; params.ftp200 = 2.5; params.ftp300 = 3;
params.str_wsc = 0.3; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.3; params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
params.ele = ELE_DARK;
params.skill = SKILL_SYH;
params.includemab = true;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.str_wsc = 0.4; params.int_wsc = 0.4;
end
local damage, criticalHit, tpHits, extraHits = doMagicWeaponskill(player, target, wsID, params, tp, primary);
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
jlcvp/otxserver | data/monster/quests/cults_of_tibia/bosses/summons/voidshard.lua | 2 | 2358 | local mType = Game.createMonsterType("Voidshard")
local monster = {}
monster.description = "a voidshard"
monster.experience = 0
monster.outfit = {
lookType = 878,
lookHead = 0,
lookBody = 0,
lookLegs = 0,
lookFeet = 0,
lookAddons = 0,
lookMount = 0
}
monster.health = 3500
monster.maxHealth = 3500
monster.race = "venom"
monster.corpse = 23553
monster.speed = 200
monster.manaCost = 0
monster.changeTarget = {
interval = 4000,
chance = 10
}
monster.strategiesTarget = {
nearest = 70,
health = 10,
damage = 10,
random = 10,
}
monster.flags = {
summonable = false,
attackable = true,
hostile = true,
convinceable = false,
pushable = false,
rewardBoss = false,
illusionable = false,
canPushItems = true,
canPushCreatures = true,
staticAttackChance = 90,
targetDistance = 1,
runHealth = 0,
healthHidden = false,
isBlockable = false,
canWalkOnEnergy = false,
canWalkOnFire = false,
canWalkOnPoison = false
}
monster.light = {
level = 0,
color = 0
}
monster.voices = {
interval = 5000,
chance = 10,
}
monster.loot = {
}
monster.attacks = {
{name ="melee", interval = 2000, chance = 100, minDamage = 0, maxDamage = -350},
{name ="combat", interval = 2000, chance = 20, type = COMBAT_ENERGYDAMAGE, minDamage = -168, maxDamage = -400, range = 6, radius = 4, shootEffect = CONST_ANI_ENERGY, effect = CONST_ME_PURPLEENERGY, target = true},
{name ="energy strike", interval = 2000, chance = 30, minDamage = -50, maxDamage = -180, range = 1, target = false},
-- energy damage
{name ="condition", type = CONDITION_ENERGY, interval = 1000, chance = 15, radius = 3, effect = CONST_ME_YELLOWENERGY, target = false}
}
monster.defenses = {
defense = 40,
armor = 40
}
monster.elements = {
{type = COMBAT_PHYSICALDAMAGE, percent = 0},
{type = COMBAT_ENERGYDAMAGE, percent = 0},
{type = COMBAT_EARTHDAMAGE, percent = 0},
{type = COMBAT_FIREDAMAGE, percent = 0},
{type = COMBAT_LIFEDRAIN, percent = 0},
{type = COMBAT_MANADRAIN, percent = 0},
{type = COMBAT_DROWNDAMAGE, percent = 0},
{type = COMBAT_ICEDAMAGE, percent = 0},
{type = COMBAT_HOLYDAMAGE , percent = 0},
{type = COMBAT_DEATHDAMAGE , percent = 0}
}
monster.immunities = {
{type = "paralyze", condition = true},
{type = "outfit", condition = false},
{type = "invisible", condition = true},
{type = "bleed", condition = false}
}
mType:register(monster)
| gpl-2.0 |
smartdevicelink/sdl_atf_test_scripts | test_scripts/API/KeyboardEnhancements/Capabilities/002_HMI_provides_valid_value_for_one_parameter_in_KeyboardCapabilities.lua | 1 | 2460 | ----------------------------------------------------------------------------------------------------
-- Proposal:
-- https://github.com/smartdevicelink/sdl_evolution/blob/master/proposals/0238-Keyboard-Enhancements.md
----------------------------------------------------------------------------------------------------
-- Description: Check SDL is able to receive 'KeyboardCapabilities' from HMI and transfer them to App
-- in case one parameter is defined with valid values (edge scenarios)
--
-- Steps:
-- 1. App is registered
-- 2. HMI provides 'KeyboardCapabilities' within 'OnSystemCapabilityUpdated' notification
-- 3. App requests 'DISPLAYS' system capabilities through 'GetSystemCapability'
-- SDL does:
-- - Provide 'KeyboardCapabilities' to App
----------------------------------------------------------------------------------------------------
--[[ Required Shared libraries ]]
local common = require('test_scripts/API/KeyboardEnhancements/common')
--[[ Local Variables ]]
local tcs = {
[01] = { maskInputCharactersSupported = false },
[02] = { maskInputCharactersSupported = true },
[03] = { supportedKeyboards = common.getArrayValue({ { keyboardLayout = "QWERTY", numConfigurableKeys = 1 }}, 1) },
[04] = { supportedKeyboards = common.getArrayValue({ { keyboardLayout = "QWERTY", numConfigurableKeys = 0 }}, 5) },
[05] = { supportedKeyboards = common.getArrayValue({ { keyboardLayout = "QWERTY", numConfigurableKeys = 5 }}, 1000) },
[06] = { supportedKeyboards = common.getArrayValue({ { keyboardLayout = "QWERTY", numConfigurableKeys = 10 }}, 5) }
}
--[[ Local Functions ]]
local function getDispCaps(pTC)
local dispCaps = common.getDispCaps()
dispCaps.systemCapability.displayCapabilities[1].windowCapabilities[1].keyboardCapabilities = pTC
return dispCaps
end
--[[ Scenario ]]
common.Title("Preconditions")
common.Step("Clean environment", common.preconditions)
common.Step("Start SDL, HMI, connect Mobile, start Session", common.start)
common.Step("Register App", common.registerApp)
common.Title("Test")
for tc, data in common.spairs(tcs) do
common.Title("TC[" .. string.format("%03d", tc) .. "]")
local dispCaps = getDispCaps(data)
common.Step("HMI sends OnSystemCapabilityUpdated", common.sendOnSystemCapabilityUpdated, { dispCaps })
common.Step("App sends GetSystemCapability", common.sendGetSystemCapability, { dispCaps })
end
common.Title("Postconditions")
common.Step("Stop SDL", common.postconditions)
| bsd-3-clause |
Squeakz/darkstar | scripts/globals/mobskills/Sweeping_Flail.lua | 39 | 1067 | ---------------------------------------------------
-- Sweeping Flail
-- Family: Bahamut
-- Description: Spins around to deal physical damage to enemies behind user. Additional effect: Knockback
-- Type: Physical
-- Utsusemi/Blink absorb: 2-3 shadows
-- Range: 20' cone
-- Notes: Used when someone pulls hate from behind Bahamut.
---------------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------------
function onMobSkillCheck(target,mob,skill)
if (target:isBehind(mob, 55) == false) then
return 1;
else
return 0;
end;
end;
function onMobWeaponSkill(target, mob, skill)
local numhits = 1;
local accmod = 1;
local dmgmod = 2;
local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_SLASH,MOBPARAM_3_SHADOW);
target:delHP(dmg);
return dmg;
end;
| gpl-3.0 |
ff-kbu/fff-luci | applications/luci-ahcp/luasrc/model/cbi/ahcp.lua | 36 | 3895 | --[[
LuCI - Lua Configuration Interface
Copyright 2011 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: init.lua 5764 2010-03-08 19:05:34Z jow $
]]--
m = Map("ahcpd", translate("AHCP Server"), translate("AHCP is an autoconfiguration protocol " ..
"for IPv6 and dual-stack IPv6/IPv4 networks designed to be used in place of router " ..
"discovery or DHCP on networks where it is difficult or impossible to configure a " ..
"server within every link-layer broadcast domain, for example mobile ad-hoc networks."))
m:section(SimpleSection).template = "ahcp_status"
s = m:section(TypedSection, "ahcpd")
s:tab("general", translate("General Setup"))
s:tab("advanced", translate("Advanced Settings"))
s.addremove = false
s.anonymous = true
mode = s:taboption("general", ListValue, "mode", translate("Operation mode"))
mode:value("server", translate("Server"))
mode:value("forwarder", translate("Forwarder"))
net = s:taboption("general", Value, "interface", translate("Served interfaces"))
net.template = "cbi/network_netlist"
net.widget = "checkbox"
net.nocreate = true
function net.cfgvalue(self, section)
return m.uci:get("ahcpd", section, "interface")
end
pfx = s:taboption("general", DynamicList, "prefix", translate("Announced prefixes"),
translate("Specifies the announced IPv4 and IPv6 network prefixes in CIDR notation"))
pfx.optional = true
pfx.datatype = "ipaddr"
pfx:depends("mode", "server")
nss = s:taboption("general", DynamicList, "name_server", translate("Announced DNS servers"),
translate("Specifies the announced IPv4 and IPv6 name servers"))
nss.optional = true
nss.datatype = "ipaddr"
nss:depends("mode", "server")
ntp = s:taboption("general", DynamicList, "ntp_server", translate("Announced NTP servers"),
translate("Specifies the announced IPv4 and IPv6 NTP servers"))
ntp.optional = true
ntp.datatype = "ipaddr"
ntp:depends("mode", "server")
mca = s:taboption("general", Value, "multicast_address", translate("Multicast address"))
mca.optional = true
mca.placeholder = "ff02::cca6:c0f9:e182:5359"
mca.datatype = "ip6addr"
port = s:taboption("general", Value, "port", translate("Port"))
port.optional = true
port.placeholder = 5359
port.datatype = "port"
fam = s:taboption("general", ListValue, "_family", translate("Protocol family"))
fam:value("", translate("IPv4 and IPv6"))
fam:value("ipv4", translate("IPv4 only"))
fam:value("ipv6", translate("IPv6 only"))
function fam.cfgvalue(self, section)
local v4 = m.uci:get_bool("ahcpd", section, "ipv4_only")
local v6 = m.uci:get_bool("ahcpd", section, "ipv6_only")
if v4 then
return "ipv4"
elseif v6 then
return "ipv6"
end
return ""
end
function fam.write(self, section, value)
if value == "ipv4" then
m.uci:set("ahcpd", section, "ipv4_only", "true")
m.uci:delete("ahcpd", section, "ipv6_only")
elseif value == "ipv6" then
m.uci:set("ahcpd", section, "ipv6_only", "true")
m.uci:delete("ahcpd", section, "ipv4_only")
end
end
function fam.remove(self, section)
m.uci:delete("ahcpd", section, "ipv4_only")
m.uci:delete("ahcpd", section, "ipv6_only")
end
ltime = s:taboption("general", Value, "lease_time", translate("Lease validity time"))
ltime.optional = true
ltime.placeholder = 3666
ltime.datatype = "uinteger"
ld = s:taboption("advanced", Value, "lease_dir", translate("Lease directory"))
ld.datatype = "directory"
ld.placeholder = "/var/lib/leases"
id = s:taboption("advanced", Value, "id_file", translate("Unique ID file"))
--id.datatype = "file"
id.placeholder = "/var/lib/ahcpd-unique-id"
log = s:taboption("advanced", Value, "log_file", translate("Log file"))
--log.datatype = "file"
log.placeholder = "/var/log/ahcpd.log"
return m
| apache-2.0 |
ddumont/darkstar | scripts/globals/items/serving_of_bison_steak.lua | 12 | 1781 | -----------------------------------------
-- ID: 5142
-- Item: serving_of_bison_steak
-- Food Effect: 180Min, All Races
-----------------------------------------
-- Strength 6
-- Agility 1
-- Intelligence -3
-- Attack % 18
-- Attack Cap 90
-- Ranged ATT % 18
-- Ranged ATT Cap 90
-- Lizard Killer 5
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,10800,5142);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_STR, 6);
target:addMod(MOD_AGI, 1);
target:addMod(MOD_INT, -3);
target:addMod(MOD_FOOD_ATTP, 18);
target:addMod(MOD_FOOD_ATT_CAP, 90);
target:addMod(MOD_FOOD_RATTP, 18);
target:addMod(MOD_FOOD_RATT_CAP, 90);
target:addMod(MOD_LIZARD_KILLER, 5);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_STR, 6);
target:delMod(MOD_AGI, 1);
target:delMod(MOD_INT, -3);
target:delMod(MOD_FOOD_ATTP, 18);
target:delMod(MOD_FOOD_ATT_CAP, 90);
target:delMod(MOD_FOOD_RATTP, 18);
target:delMod(MOD_FOOD_RATT_CAP, 90);
target:delMod(MOD_LIZARD_KILLER, 5);
end;
| gpl-3.0 |
jlcvp/otxserver | data/monster/quests/kilmaresh/xogixath.lua | 2 | 3395 | local mType = Game.createMonsterType("Xogixath")
local monster = {}
monster.description = "xogixath"
monster.experience = 22000
monster.outfit = {
lookType = 842,
lookHead = 3,
lookBody = 16,
lookLegs = 75,
lookFeet = 79,
lookAddons = 2,
lookMount = 0
}
monster.health = 28000
monster.maxHealth = 28000
monster.race = "fire"
monster.corpse = 12838
monster.speed = 190
monster.manaCost = 0
monster.changeTarget = {
interval = 4000,
chance = 10
}
monster.strategiesTarget = {
nearest = 70,
health = 10,
damage = 10,
random = 10,
}
monster.flags = {
summonable = false,
attackable = true,
hostile = true,
convinceable = false,
pushable = false,
rewardBoss = true,
illusionable = false,
canPushItems = true,
canPushCreatures = true,
staticAttackChance = 90,
targetDistance = 1,
runHealth = 0,
healthHidden = false,
isBlockable = false,
canWalkOnEnergy = true,
canWalkOnFire = true,
canWalkOnPoison = true
}
monster.light = {
level = 0,
color = 0
}
monster.voices = {
interval = 5000,
chance = 10,
}
monster.loot = {
{name = "platinum coin", chance = 100000, maxCount = 9},
{id= 3039, chance = 65000, maxCount = 2}, -- red gem
{name = "green crystal shard", chance = 16000},
{name = "sea horse figurine", chance = 2400},
{name = "winged boots", chance = 120},
{name = "small sapphire", chance = 48000, maxCount = 3},
{name = "stone skin amulet", chance = 54000},
{id = 31369, chance = 6500}, -- gryphon mask
{name = "fire axe", chance = 34000},
{id = 31557, chance = 520} -- blister ring
}
monster.attacks = {
{name ="melee", interval = 2000, chance = 100, minDamage = 0, maxDamage = -650},
{name ="sudden death rune", interval = 2000, chance = 16, minDamage = -450, maxDamage = -550, range = 5, target = true},
{name ="combat", interval = 2000, chance = 14, type = COMBAT_FIREDAMAGE, minDamage = -400, maxDamage = -480, range = 5, radius = 3, shootEffect = CONST_ANI_FIRE, effect = CONST_ME_FIREAREA, target = true},
{name ="combat", interval = 2000, chance = 10, type = COMBAT_FIREDAMAGE, minDamage = -400, maxDamage = -550, radius = 4, effect = CONST_ME_EXPLOSIONHIT, target = false},
{name ="combat", interval = 2000, chance = 12, type = COMBAT_FIREDAMAGE, minDamage = -420, maxDamage = -600, length = 5, spread = 3, effect = CONST_ME_HITBYFIRE, target = false}
}
monster.defenses = {
defense = 86,
armor = 86
}
monster.elements = {
{type = COMBAT_PHYSICALDAMAGE, percent = 0},
{type = COMBAT_ENERGYDAMAGE, percent = 0},
{type = COMBAT_EARTHDAMAGE, percent = 0},
{type = COMBAT_FIREDAMAGE, percent = 0},
{type = COMBAT_LIFEDRAIN, percent = 0},
{type = COMBAT_MANADRAIN, percent = 0},
{type = COMBAT_DROWNDAMAGE, percent = 0},
{type = COMBAT_ICEDAMAGE, percent = -10},
{type = COMBAT_HOLYDAMAGE , percent = 0},
{type = COMBAT_DEATHDAMAGE , percent = 50}
}
monster.immunities = {
{type = "paralyze", condition = true},
{type = "outfit", condition = false},
{type = "invisible", condition = true},
{type = "bleed", condition = false}
}
mType.onThink = function(monster, interval)
end
mType.onAppear = function(monster, creature)
if monster:getType():isRewardBoss() then
monster:setReward(true)
end
end
mType.onDisappear = function(monster, creature)
end
mType.onMove = function(monster, creature, fromPosition, toPosition)
end
mType.onSay = function(monster, creature, type, message)
end
mType:register(monster)
| gpl-2.0 |
ddumont/darkstar | scripts/zones/Inner_Horutoto_Ruins/npcs/_5ci.lua | 14 | 1496 | -----------------------------------
-- Area: Inner Horutoto Ruins
-- NPC: _5ci (Gate of Light)
-- Involved In Mission: 3-2
-- @pos -331 0 139 192
-----------------------------------
package.loaded["scripts/zones/Inner_Horutoto_Ruins/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/missions");
require("scripts/zones/Inner_Horutoto_Ruins/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getCurrentMission(WINDURST) == WRITTEN_IN_THE_STARS and player:getVar("MissionStatus") == 1) then
player:startEvent(0x0029,0,CHARM_OF_LIGHT);
else
player:messageSpecial(DOOR_FIRMLY_CLOSED);
end
return 1;
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0029) then
player:setVar("MissionStatus",2);
player:delKeyItem(CHARM_OF_LIGHT);
end
end; | gpl-3.0 |
Squeakz/darkstar | scripts/zones/Nashmau/Zone.lua | 10 | 1803 | -----------------------------------
--
-- Zone: Nashmau (53)
--
-----------------------------------
package.loaded["scripts/zones/Nashmau/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Nashmau/TextIDs");
require("scripts/globals/settings");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
if (prevZone == 58) then
cs = 0x00C9;
player:setPos(11,2,-102,128);
else
player:setPos(40.658,-7.527,-24.001,128);
end
end
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onRegionLeave
-----------------------------------
function onRegionLeave(player,region)
end;
-----------------------------------
-- onTransportEvent
-----------------------------------
function onTransportEvent(player,transport)
if (transport == 59) then
player:startEvent(200);
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 == 200) then
player:setPos(0,-2,0,0,59);
end
end;
| gpl-3.0 |
smartdevicelink/sdl_atf_test_scripts | test_scripts/Policies/App_Permissions/022_ATF_No_Permission_Notification_To_HMI_In_First_App_Registration.lua | 1 | 5174 | ---------------------------------------------------------------------------------------------
-- Requirement summary:
-- Registering the app the 1st time initiate promting the User about the event
-- [RegisterAppInterface] Order of request/response/notifications on registering an application
--
-- Description:
-- When the application is registered for the first time (no records in PT) PoliciesManager should not initiate promting the User about the event.
-- 1. Used preconditions:
-- a) Stop SDL and set SDL to first life cycle state.
-- 2. Performed steps:
-- a) Register Application
--
-- Expected result:
-- No prompts or notification are observed on HMI
-- Note: Requirement under clarification! Assumed that OnAppPermissionChanged and OnSDLConsentNeeded should not come
---------------------------------------------------------------------------------------------
require('user_modules/script_runner').isTestApplicable({ { extendedPolicy = { "EXTERNAL_PROPRIETARY" } } })
--[[ General configuration parameters ]]
--ToDo: shall be removed when issue: "ATF does not stop HB timers by closing session and connection" is fixed
config.defaultProtocolVersion = 2
--[[ Required Shared libraries ]]
local commonFunctions = require ('user_modules/shared_testcases/commonFunctions')
local commonSteps = require ('user_modules/shared_testcases/commonSteps')
local commonPreconditions = require ('user_modules/shared_testcases/commonPreconditions')
local commonTestCases = require ('user_modules/shared_testcases/commonTestCases')
local utils = require ('user_modules/utils')
--[[ General Preconditions before ATF starts ]]
commonSteps:DeleteLogsFileAndPolicyTable()
commonPreconditions:Connecttest_without_ExitBySDLDisconnect_WithoutOpenConnectionRegisterApp("connecttest_ConnectMobile.lua")
--[[ General Settings for configuration ]]
Test = require('user_modules/connecttest_ConnectMobile')
require('cardinalities')
require('user_modules/AppTypes')
local mobile_session = require('mobile_session')
--[[ Preconditions ]]
function Test:Precondition_ConnectMobile_FirstLifeCycle()
self:connectMobile()
end
function Test:Precondition_StartSession()
self.mobileSession = mobile_session.MobileSession(self, self.mobileConnection)
self.mobileSession:StartService(7)
end
function Test:TestStep_Firs_Time_Register_App_And_Check_That_No_Permission_Notification_To_HMI()
local is_test_fail = false
local order_communication = 1
local CorIdRAI = self.mobileSession:SendRPC("RegisterAppInterface",
{
syncMsgVersion =
{
majorVersion = 3,
minorVersion = 0
},
appName = "SPT",
isMediaApplication = true,
languageDesired = "EN-US",
hmiDisplayLanguageDesired = "EN-US",
appID = "1234567",
deviceInfo =
{
os = "Android",
carrier = "Megafon",
firmwareRev = "Name: Linux, Version: 3.4.0-perf",
osVersion = "4.4.2",
maxNumberRFCOMMPorts = 1
}
})
EXPECT_HMINOTIFICATION("BasicCommunication.OnAppRegistered",
{
application =
{
appName = "SPT",
policyAppID = "1234567",
isMediaApplication = true,
hmiDisplayLanguageDesired = "EN-US",
deviceInfo =
{
name = utils.getDeviceName(),
id = utils.getDeviceMAC(),
transportType = utils.getDeviceTransportType(),
isSDLAllowed = false
}
}
})
:Do(function(_,data)
self.hmiConnection:SendResponse(data.id,"BasicCommunication.ActivateApp", "SUCCESS", {})
end)
EXPECT_HMINOTIFICATION("SDL.OnAppPermissionChanged", {}):Times(0)
EXPECT_HMINOTIFICATION("SDL.OnSDLConsentNeeded", {}) :Times(0)
EXPECT_RESPONSE(CorIdRAI, { success = true, resultCode = "SUCCESS"})
:Do(function(_,_)
if(order_communication ~= 1) then
commonFunctions:printError("RAI response is not received 1 in message order. Real: received number: "..order_communication)
is_test_fail = true
end
order_communication = order_communication + 1
end)
EXPECT_NOTIFICATION("OnHMIStatus", {hmiLevel = "NONE", audioStreamingState = "NOT_AUDIBLE", systemContext = "MAIN"})
:Do(function(_,_)
if(order_communication ~= 2) then
commonFunctions:printError("OnHMIStatus is not received 2 in message order. Real: received number: "..order_communication)
is_test_fail = true
end
order_communication = order_communication + 1
end)
EXPECT_NOTIFICATION("OnPermissionsChange", {})
:Do(function(_,_)
if(order_communication ~= 3) then
commonFunctions:printError("OnPermissionsChange is not received 3 in message order. Real: received number: "..order_communication)
is_test_fail = true
end
order_communication = order_communication + 1
end)
local function verify_test_result()
if(is_test_fail == true) then
self:FailTestCase("Test is FAILED. See prints.")
end
end
RUN_AFTER(verify_test_result,10000)
commonTestCases:DelayedExp(11000)
end
--[[ Postconditions ]]
commonFunctions:newTestCasesGroup("Postconditions")
function Test.Postcondition_StopSDL()
StopSDL()
end
return Test
| bsd-3-clause |
lukego/snabb | src/lib/protocol/ipv4.lua | 7 | 5967 | module(..., package.seeall)
local ffi = require("ffi")
local C = ffi.C
local lib = require("core.lib")
local header = require("lib.protocol.header")
local ipsum = require("lib.checksum").ipsum
local htons, ntohs, htonl, ntohl =
lib.htons, lib.ntohs, lib.htonl, lib.ntohl
-- TODO: generalize
local AF_INET = 2
local INET_ADDRSTRLEN = 16
local ipv4hdr_pseudo_t = ffi.typeof[[
struct {
uint8_t src_ip[4];
uint8_t dst_ip[4];
uint8_t ulp_zero;
uint8_t ulp_protocol;
uint16_t ulp_length;
} __attribute__((packed))
]]
local ipv4_addr_t = ffi.typeof("uint8_t[4]")
local ipv4_addr_t_size = ffi.sizeof(ipv4_addr_t)
local ipv4 = subClass(header)
-- Class variables
ipv4._name = "ipv4"
ipv4._ulp = {
class_map = {
[6] = "lib.protocol.tcp",
[17] = "lib.protocol.udp",
[47] = "lib.protocol.gre",
[58] = "lib.protocol.icmp.header",
},
method = 'protocol' }
ipv4:init(
{
[1] = ffi.typeof[[
struct {
uint16_t ihl_v_tos; // ihl:4, version:4, tos(dscp:6 + ecn:2)
uint16_t total_length;
uint16_t id;
uint16_t frag_off; // flags:3, fragmen_offset:13
uint8_t ttl;
uint8_t protocol;
uint16_t checksum;
uint8_t src_ip[4];
uint8_t dst_ip[4];
} __attribute__((packed))
]],
})
-- Class methods
function ipv4:new (config)
local o = ipv4:superClass().new(self)
o:header().ihl_v_tos = htons(0x4000) -- v4
o:ihl(o:sizeof() / 4)
o:dscp(config.dscp or 0)
o:ecn(config.ecn or 0)
o:total_length(o:sizeof()) -- default to header only
o:id(config.id or 0)
o:flags(config.flags or 0)
o:frag_off(config.frag_off or 0)
o:ttl(config.ttl or 0)
o:protocol(config.protocol or 0xff)
o:src(config.src)
o:dst(config.dst)
o:checksum()
return o
end
function ipv4:pton (p)
local in_addr = ffi.new("uint8_t[4]")
local result = C.inet_pton(AF_INET, p, in_addr)
if result ~= 1 then
return false, "malformed IPv4 address: " .. address
end
return in_addr
end
function ipv4:ntop (n)
local p = ffi.new("char[?]", INET_ADDRSTRLEN)
local c_str = C.inet_ntop(AF_INET, n, p, INET_ADDRSTRLEN)
return ffi.string(c_str)
end
-- Instance methods
function ipv4:version (v)
return lib.bitfield(16, self:header(), 'ihl_v_tos', 0, 4, v)
end
function ipv4:ihl (ihl)
return lib.bitfield(16, self:header(), 'ihl_v_tos', 4, 4, ihl)
end
function ipv4:dscp (dscp)
return lib.bitfield(16, self:header(), 'ihl_v_tos', 8, 6, dscp)
end
function ipv4:ecn (ecn)
return lib.bitfield(16, self:header(), 'ihl_v_tos', 14, 2, ecn)
end
function ipv4:total_length (length)
if length ~= nil then
self:header().total_length = htons(length)
else
return(ntohs(self:header().total_length))
end
end
function ipv4:id (id)
if id ~= nil then
self:header().id = htons(id)
else
return(ntohs(self:header().id))
end
end
function ipv4:flags (flags)
return lib.bitfield(16, self:header(), 'frag_off', 0, 3, flags)
end
function ipv4:frag_off (frag_off)
return lib.bitfield(16, self:header(), 'frag_off', 3, 13, frag_off)
end
function ipv4:ttl (ttl)
if ttl ~= nil then
self:header().ttl = ttl
else
return self:header().ttl
end
end
function ipv4:protocol (protocol)
if protocol ~= nil then
self:header().protocol = protocol
else
return self:header().protocol
end
end
function ipv4:checksum ()
self:header().checksum = htons(ipsum(ffi.cast("uint8_t *", self:header()),
self:sizeof(), 0))
return ntohs(self:header().checksum)
end
function ipv4:src (ip)
if ip ~= nil then
ffi.copy(self:header().src_ip, ip, ipv4_addr_t_size)
else
return self:header().src_ip
end
end
function ipv4:src_eq (ip)
return C.memcmp(ip, self:header().src_ip, ipv4_addr_t_size) == 0
end
function ipv4:dst (ip)
if ip ~= nil then
ffi.copy(self:header().dst_ip, ip, ipv4_addr_t_size)
else
return self:header().dst_ip
end
end
function ipv4:dst_eq (ip)
return C.memcmp(ip, self:header().dst_ip, ipv4_addr_t_size) == 0
end
-- override the default equality method
function ipv4:eq (other)
--compare significant fields
return (self:ihl() == other:ihl()) and
(self:id() == other:id()) and
(self:protocol() == other:protocol()) and
self:src_eq(other:src()) and self:dst_eq(other:dst())
end
-- Return a pseudo header for checksum calculation in a upper-layer
-- protocol (e.g. icmp). Note that the payload length and next-header
-- values in the pseudo-header refer to the effective upper-layer
-- protocol. They differ from the respective values of the ipv6
-- header if extension headers are present.
function ipv4:pseudo_header (ulplen, proto)
local ph = ipv4hdr_pseudo_t()
local h = self:header()
ffi.copy(ph, h.src_ip, 2*ipv4_addr_t_size) -- Copy source and destination
ph.ulp_length = htons(ulplen)
ph.ulp_protocol = proto
return(ph)
end
local function test_ipv4_checksum ()
local IP_BASE = 14
local IP_HDR_SIZE = 20
local p = packet.from_string(lib.hexundump([[
52:54:00:02:02:02 52:54:00:01:01:01 08 00 45 00
00 34 59 1a 40 00 40 06 00 00 c0 a8 14 a9 6b 15
f0 b4 de 0b 01 bb e7 db 57 bc 91 cd 18 32 80 10
05 9f 00 00 00 00 01 01 08 0a 06 0c 5c bd fa 4a
e1 65
]], 66))
local ip_hdr = ipv4:new_from_mem(p.data + IP_BASE, IP_HDR_SIZE)
local csum = ip_hdr:checksum()
assert(csum == 0xb08e, "Wrong IPv4 checksum")
end
function selftest()
local ipv4_address = "192.168.1.1"
assert(ipv4_address == ipv4:ntop(ipv4:pton(ipv4_address)),
'ipv4 text to binary conversion failed.')
test_ipv4_checksum()
local ipv4hdr = ipv4:new({})
assert(C.ntohs(ipv4hdr:header().ihl_v_tos) == 0x4500,
'ipv4 header field ihl_v_tos not initialized correctly.')
end
ipv4.selftest = selftest
return ipv4
| apache-2.0 |
PlexChat/premake-core | tests/config/test_targetinfo.lua | 9 | 5055 | --
-- tests/config/test_targetinfo.lua
-- Test the config object's build target accessor.
-- Copyright (c) 2011-2013 Jason Perkins and the Premake project
--
local suite = test.declare("config_targetinfo")
local config = premake.config
--
-- Setup and teardown
--
local wks, prj
function suite.setup()
_ACTION = "test"
wks, prj = test.createWorkspace()
system "macosx"
end
local function prepare()
local cfg = test.getconfig(prj, "Debug")
return config.gettargetinfo(cfg)
end
--
-- Directory uses targetdir() value if present.
--
function suite.directoryIsTargetDir_onTargetDir()
targetdir "../bin"
i = prepare()
test.isequal("../bin", path.getrelative(os.getcwd(), i.directory))
end
--
-- Base name should use the project name by default.
--
function suite.basenameIsProjectName_onNoTargetName()
i = prepare()
test.isequal("MyProject", i.basename)
end
--
-- Base name should use targetname() if present.
--
function suite.basenameIsTargetName_onTargetName()
targetname "MyTarget"
i = prepare()
test.isequal("MyTarget", i.basename)
end
--
-- Base name should use suffix if present.
--
function suite.basenameUsesSuffix_onTargetSuffix()
targetsuffix "-d"
i = prepare()
test.isequal("MyProject-d", i.basename)
end
--
-- Name should not have an extension for Posix executables.
--
function suite.nameHasNoExtension_onMacOSXConsoleApp()
system "MacOSX"
i = prepare()
test.isequal("MyProject", i.name)
end
function suite.nameHasNoExtension_onLinuxConsoleApp()
system "Linux"
i = prepare()
test.isequal("MyProject", i.name)
end
function suite.nameHasNoExtension_onBSDConsoleApp()
system "BSD"
i = prepare()
test.isequal("MyProject", i.name)
end
--
-- Name should use ".exe" for Windows executables.
--
function suite.nameUsesExe_onWindowsConsoleApp()
kind "ConsoleApp"
system "Windows"
i = prepare()
test.isequal("MyProject.exe", i.name)
end
function suite.nameUsesExe_onWindowsWindowedApp()
kind "WindowedApp"
system "Windows"
i = prepare()
test.isequal("MyProject.exe", i.name)
end
--
-- Name should use ".dll" for Windows shared libraries.
--
function suite.nameUsesDll_onWindowsSharedLib()
kind "SharedLib"
system "Windows"
i = prepare()
test.isequal("MyProject.dll", i.name)
end
--
-- Name should use ".lib" for Windows static libraries.
--
function suite.nameUsesLib_onWindowsStaticLib()
kind "StaticLib"
system "Windows"
i = prepare()
test.isequal("MyProject.lib", i.name)
end
--
-- Name should use "lib and ".dylib" for Mac shared libraries.
--
function suite.nameUsesLib_onMacSharedLib()
kind "SharedLib"
system "MacOSX"
i = prepare()
test.isequal("libMyProject.dylib", i.name)
end
--
-- Name should use "lib and ".a" for Mac static libraries.
--
function suite.nameUsesLib_onMacStaticLib()
kind "StaticLib"
system "MacOSX"
i = prepare()
test.isequal("libMyProject.a", i.name)
end
--
-- Name should use "lib" and ".so" for Linux shared libraries.
--
function suite.nameUsesLib_onLinuxSharedLib()
kind "SharedLib"
system "Linux"
i = prepare()
test.isequal("libMyProject.so", i.name)
end
--
-- Name should use "lib" and ".a" for Linux shared libraries.
--
function suite.nameUsesLib_onLinuxStaticLib()
kind "StaticLib"
system "Linux"
i = prepare()
test.isequal("libMyProject.a", i.name)
end
--
-- Name should use ".exe" for Xbox360 executables.
--
function suite.nameUsesExe_onWindowsConsoleApp()
kind "ConsoleApp"
system "Xbox360"
i = prepare()
test.isequal("MyProject.exe", i.name)
end
function suite.nameUsesLib_onXbox360StaticLib()
kind "StaticLib"
system "Xbox360"
i = prepare()
test.isequal("MyProject.lib", i.name)
end
--
-- Name should use a prefix if set.
--
function suite.nameUsesPrefix_onTargetPrefix()
targetprefix "sys"
i = prepare()
test.isequal("sysMyProject", i.name)
end
--
-- Bundle name should be set and use ".app" for Mac windowed applications.
--
function suite.bundlenameUsesApp_onMacWindowedApp()
kind "WindowedApp"
system "MacOSX"
i = prepare()
test.isequal("MyProject.app", i.bundlename)
end
--
-- Bundle path should be set for Mac windowed applications.
--
function suite.bundlepathSet_onMacWindowedApp()
kind "WindowedApp"
system "MacOSX"
i = prepare()
test.isequal("bin/Debug/MyProject.app/Contents/MacOS", path.getrelative(os.getcwd(), i.bundlepath))
end
--
-- Target extension is used if set.
--
function suite.extensionSet_onTargetExtension()
targetextension ".self"
i = prepare()
test.isequal("MyProject.self", i.name)
end
--
-- .NET executables should always default to ".exe" extensions.
--
function suite.appUsesExe_onDotNet()
_OS = "macosx"
language "C#"
i = prepare()
test.isequal("MyProject.exe", i.name)
end
--
-- .NET libraries should always default to ".dll" extensions.
--
function suite.appUsesExe_onDotNet()
_OS = "macosx"
language "C#"
kind "SharedLib"
i = prepare()
test.isequal("MyProject.dll", i.name)
end
| bsd-3-clause |
morteza1378/SHIELD_POWER | plugins/ingroup.lua | 371 | 44212 | do
-- Check Member
local function check_member_autorealm(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
group_type = 'Realm',
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes'
}
}
save_data(_config.moderation.data, data)
local realms = 'realms'
if not data[tostring(realms)] then
data[tostring(realms)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(realms)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Welcome to your new realm !')
end
end
end
local function check_member_realm_add(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
group_type = 'Realm',
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes'
}
}
save_data(_config.moderation.data, data)
local realms = 'realms'
if not data[tostring(realms)] then
data[tostring(realms)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(realms)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Realm has been added!')
end
end
end
function check_member_group(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
group_type = 'Group',
moderators = {},
set_owner = member_id ,
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes',
}
}
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'You have been promoted as the owner.')
end
end
end
local function check_member_modadd(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
group_type = 'Group',
moderators = {},
set_owner = member_id ,
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes',
}
}
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Group is added and you have been promoted as the owner ')
end
end
end
local function automodadd(msg)
local data = load_data(_config.moderation.data)
if msg.action.type == 'chat_created' then
receiver = get_receiver(msg)
chat_info(receiver, check_member_group,{receiver=receiver, data=data, msg = msg})
end
end
local function autorealmadd(msg)
local data = load_data(_config.moderation.data)
if msg.action.type == 'chat_created' then
receiver = get_receiver(msg)
chat_info(receiver, check_member_autorealm,{receiver=receiver, data=data, msg = msg})
end
end
local function check_member_realmrem(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Realm configuration removal
data[tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
local realms = 'realms'
if not data[tostring(realms)] then
data[tostring(realms)] = nil
save_data(_config.moderation.data, data)
end
data[tostring(realms)][tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Realm has been removed!')
end
end
end
local function check_member_modrem(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration removal
data[tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = nil
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Group has been removed')
end
end
end
--End Check Member
local function show_group_settingsmod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
local bots_protection = "Yes"
if data[tostring(msg.to.id)]['settings']['lock_bots'] then
bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots']
end
local leave_ban = "no"
if data[tostring(msg.to.id)]['settings']['leave_ban'] then
leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban']
end
local settings = data[tostring(target)]['settings']
local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nLock group leave : "..leave_ban.."\nflood sensitivity : "..NUM_MSG_MAX.."\nBot protection : "..bots_protection--"\nPublic: "..public
return text
end
local function set_descriptionmod(msg, data, target, about)
if not is_momod(msg) then
return "For moderators only!"
end
local data_cat = 'description'
data[tostring(target)][data_cat] = about
save_data(_config.moderation.data, data)
return 'Set group description to:\n'..about
end
local function get_description(msg, data)
local data_cat = 'description'
if not data[tostring(msg.to.id)][data_cat] then
return 'No description available.'
end
local about = data[tostring(msg.to.id)][data_cat]
local about = string.gsub(msg.to.print_name, "_", " ")..':\n\n'..about
return 'About '..about
end
local function lock_group_arabic(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'yes' then
return 'Arabic is already locked'
else
data[tostring(target)]['settings']['lock_arabic'] = 'yes'
save_data(_config.moderation.data, data)
return 'Arabic has been locked'
end
end
local function unlock_group_arabic(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'no' then
return 'Arabic is already unlocked'
else
data[tostring(target)]['settings']['lock_arabic'] = 'no'
save_data(_config.moderation.data, data)
return 'Arabic has been unlocked'
end
end
local function lock_group_bots(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_bots_lock = data[tostring(target)]['settings']['lock_bots']
if group_bots_lock == 'yes' then
return 'Bots protection is already enabled'
else
data[tostring(target)]['settings']['lock_bots'] = 'yes'
save_data(_config.moderation.data, data)
return 'Bots protection has been enabled'
end
end
local function unlock_group_bots(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_bots_lock = data[tostring(target)]['settings']['lock_bots']
if group_bots_lock == 'no' then
return 'Bots protection is already disabled'
else
data[tostring(target)]['settings']['lock_bots'] = 'no'
save_data(_config.moderation.data, data)
return 'Bots protection has been disabled'
end
end
local function lock_group_namemod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'yes' then
return 'Group name is already locked'
else
data[tostring(target)]['settings']['lock_name'] = 'yes'
save_data(_config.moderation.data, data)
rename_chat('chat#id'..target, group_name_set, ok_cb, false)
return 'Group name has been locked'
end
end
local function unlock_group_namemod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'no' then
return 'Group name is already unlocked'
else
data[tostring(target)]['settings']['lock_name'] = 'no'
save_data(_config.moderation.data, data)
return 'Group name has been unlocked'
end
end
local function lock_group_floodmod(msg, data, target)
if not is_owner(msg) then
return "Only admins can do it for now"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'yes' then
return 'Group flood is locked'
else
data[tostring(target)]['settings']['flood'] = 'yes'
save_data(_config.moderation.data, data)
return 'Group flood has been locked'
end
end
local function unlock_group_floodmod(msg, data, target)
if not is_owner(msg) then
return "Only admins can do it for now"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'no' then
return 'Group flood is not locked'
else
data[tostring(target)]['settings']['flood'] = 'no'
save_data(_config.moderation.data, data)
return 'Group flood has been unlocked'
end
end
local function lock_group_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'Group members are already locked'
else
data[tostring(target)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group members has been locked'
end
local function unlock_group_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'Group members are not locked'
else
data[tostring(target)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'Group members has been unlocked'
end
end
local function set_public_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['public']
if group_member_lock == 'yes' then
return 'Group is already public'
else
data[tostring(target)]['settings']['public'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group is now: public'
end
local function unset_public_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['public']
if group_member_lock == 'no' then
return 'Group is not public'
else
data[tostring(target)]['settings']['public'] = 'no'
save_data(_config.moderation.data, data)
return 'Group is now: not public'
end
end
local function lock_group_leave(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban']
if leave_ban == 'yes' then
return 'Leaving users will be banned'
else
data[tostring(msg.to.id)]['settings']['leave_ban'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Leaving users will be banned'
end
local function unlock_group_leave(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban']
if leave_ban == 'no' then
return 'Leaving users will not be banned'
else
data[tostring(msg.to.id)]['settings']['leave_ban'] = 'no'
save_data(_config.moderation.data, data)
return 'Leaving users will not be banned'
end
end
local function unlock_group_photomod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'no' then
return 'Group photo is not locked'
else
data[tostring(target)]['settings']['lock_photo'] = 'no'
save_data(_config.moderation.data, data)
return 'Group photo has been unlocked'
end
end
local function set_rulesmod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local data_cat = 'rules'
data[tostring(target)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'Set group rules to:\n'..rules
end
local function modadd(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
if is_group(msg) then
return 'Group is already added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_modadd,{receiver=receiver, data=data, msg = msg})
end
local function realmadd(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
if is_realm(msg) then
return 'Realm is already added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_realm_add,{receiver=receiver, data=data, msg = msg})
end
-- Global functions
function modrem(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
if not is_group(msg) then
return 'Group is not added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_modrem,{receiver=receiver, data=data, msg = msg})
end
function realmrem(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
if not is_realm(msg) then
return 'Realm is not added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_realmrem,{receiver=receiver, data=data, msg = msg})
end
local function get_rules(msg, data)
local data_cat = 'rules'
if not data[tostring(msg.to.id)][data_cat] then
return 'No rules available.'
end
local rules = data[tostring(msg.to.id)][data_cat]
local rules = 'Chat rules:\n'..rules
return rules
end
local function set_group_photo(msg, success, result)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if success then
local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg'
print('File downloaded to:', result)
os.rename(result, file)
print('File moved to:', file)
chat_set_photo (receiver, file, ok_cb, false)
data[tostring(msg.to.id)]['settings']['set_photo'] = file
save_data(_config.moderation.data, data)
data[tostring(msg.to.id)]['settings']['lock_photo'] = 'yes'
save_data(_config.moderation.data, data)
send_large_msg(receiver, 'Photo saved!', ok_cb, false)
else
print('Error downloading: '..msg.id)
send_large_msg(receiver, 'Failed, please try again!', ok_cb, false)
end
end
local function promote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'chat#id', '')
if not data[group] then
return send_large_msg(receiver, 'Group is not added.')
end
if data[group]['moderators'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is already a moderator.')
end
data[group]['moderators'][tostring(member_id)] = member_username
save_data(_config.moderation.data, data)
return send_large_msg(receiver, member_username..' has been promoted.')
end
local function promote_by_reply(extra, success, result)
local msg = result
local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '')
if msg.from.username then
member_username = '@'.. msg.from.username
else
member_username = full_name
end
local member_id = msg.from.id
if msg.to.type == 'chat' then
return promote(get_receiver(msg), member_username, member_id)
end
end
local function demote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'chat#id', '')
if not data[group] then
return send_large_msg(receiver, 'Group is not added.')
end
if not data[group]['moderators'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is not a moderator.')
end
data[group]['moderators'][tostring(member_id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, member_username..' has been demoted.')
end
local function demote_by_reply(extra, success, result)
local msg = result
local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '')
if msg.from.username then
member_username = '@'..msg.from.username
else
member_username = full_name
end
local member_id = msg.from.id
if msg.to.type == 'chat' then
return demote(get_receiver(msg), member_username, member_id)
end
end
local function setowner_by_reply(extra, success, result)
local msg = result
local receiver = get_receiver(msg)
local data = load_data(_config.moderation.data)
local name_log = msg.from.print_name:gsub("_", " ")
data[tostring(msg.to.id)]['set_owner'] = tostring(msg.from.id)
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] setted ["..msg.from.id.."] as owner")
local text = msg.from.print_name:gsub("_", " ").." is the owner now"
return send_large_msg(receiver, text)
end
local function promote_demote_res(extra, success, result)
--vardump(result)
--vardump(extra)
local member_id = result.id
local member_username = "@"..result.username
local chat_id = extra.chat_id
local mod_cmd = extra.mod_cmd
local receiver = "chat#id"..chat_id
if mod_cmd == 'promote' then
return promote(receiver, member_username, member_id)
elseif mod_cmd == 'demote' then
return demote(receiver, member_username, member_id)
end
end
local function modlist(msg)
local data = load_data(_config.moderation.data)
local groups = "groups"
if not data[tostring(groups)][tostring(msg.to.id)] then
return 'Group is not added.'
end
-- determine if table is empty
if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way
return 'No moderator in this group.'
end
local i = 1
local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n'
for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do
message = message ..i..' - '..v..' [' ..k.. '] \n'
i = i + 1
end
return message
end
local function callbackres(extra, success, result)
--vardump(result)
local user = result.id
local name = string.gsub(result.print_name, "_", " ")
local chat = 'chat#id'..extra.chatid
send_large_msg(chat, user..'\n'..name)
return user
end
local function help()
local help_text = tostring(_config.help_text)
return help_text
end
local function cleanmember(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user(v.id, result.id)
end
end
local function killchat(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.id, result.id)
end
end
local function killrealm(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.id, result.id)
end
end
local function user_msgs(user_id, chat_id)
local user_info
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info = tonumber(redis:get(um_hash) or 0)
return user_info
end
local function kick_zero(cb_extra, success, result)
local chat_id = cb_extra.chat_id
local chat = "chat#id"..chat_id
local ci_user
local re_user
for k,v in pairs(result.members) do
local si = false
ci_user = v.id
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
for i = 1, #users do
re_user = users[i]
if tonumber(ci_user) == tonumber(re_user) then
si = true
end
end
if not si then
if ci_user ~= our_id then
if not is_momod2(ci_user, chat_id) then
chat_del_user(chat, 'user#id'..ci_user, ok_cb, true)
end
end
end
end
end
local function kick_inactive(chat_id, num, receiver)
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
-- Get user info
for i = 1, #users do
local user_id = users[i]
local user_info = user_msgs(user_id, chat_id)
local nmsg = user_info
if tonumber(nmsg) < tonumber(num) then
if not is_momod2(user_id, chat_id) then
chat_del_user('chat#id'..chat_id, 'user#id'..user_id, ok_cb, true)
end
end
end
return chat_info(receiver, kick_zero, {chat_id = chat_id})
end
local function run(msg, matches)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
local name_log = user_print_name(msg.from)
local group = msg.to.id
if msg.media then
if msg.media.type == 'photo' and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_chat_msg(msg) and is_momod(msg) then
load_photo(msg.id, set_group_photo, msg)
end
end
if matches[1] == 'add' and not matches[2] then
if is_realm(msg) then
return 'Error: Already a realm.'
end
print("group "..msg.to.print_name.."("..msg.to.id..") added")
return modadd(msg)
end
if matches[1] == 'add' and matches[2] == 'realm' then
if is_group(msg) then
return 'Error: Already a group.'
end
print("group "..msg.to.print_name.."("..msg.to.id..") added as a realm")
return realmadd(msg)
end
if matches[1] == 'rem' and not matches[2] then
print("group "..msg.to.print_name.."("..msg.to.id..") removed")
return modrem(msg)
end
if matches[1] == 'rem' and matches[2] == 'realm' then
print("group "..msg.to.print_name.."("..msg.to.id..") removed as a realm")
return realmrem(msg)
end
if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "group" then
return automodadd(msg)
end
if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "realm" then
return autorealmadd(msg)
end
if msg.to.id and data[tostring(msg.to.id)] then
local settings = data[tostring(msg.to.id)]['settings']
if matches[1] == 'chat_add_user' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_member_lock = settings.lock_member
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
if group_member_lock == 'yes' and not is_owner2(msg.action.user.id, msg.to.id) then
chat_del_user(chat, user, ok_cb, true)
elseif group_member_lock == 'yes' and tonumber(msg.from.id) == tonumber(our_id) then
return nil
elseif group_member_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_del_user' then
if not msg.service then
-- return "Are you trying to troll me?"
end
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..user)
end
if matches[1] == 'chat_delete_photo' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_photo_lock = settings.lock_photo
if group_photo_lock == 'yes' then
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:incr(picturehash)
---
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
local picprotectionredis = redis:get(picturehash)
if picprotectionredis then
if tonumber(picprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(picprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:set(picturehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to deleted picture but failed ")
chat_set_photo(receiver, settings.set_photo, ok_cb, false)
elseif group_photo_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then
if not msg.service then
return "Are you trying to troll me?"
end
local group_photo_lock = settings.lock_photo
if group_photo_lock == 'yes' then
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:incr(picturehash)
---
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
local picprotectionredis = redis:get(picturehash)
if picprotectionredis then
if tonumber(picprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(picprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:set(picturehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change picture but failed ")
chat_set_photo(receiver, settings.set_photo, ok_cb, false)
elseif group_photo_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_rename' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_name_set = settings.set_name
local group_name_lock = settings.lock_name
local to_rename = 'chat#id'..msg.to.id
if group_name_lock == 'yes' then
if group_name_set ~= tostring(msg.to.print_name) then
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
redis:incr(namehash)
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
local nameprotectionredis = redis:get(namehash)
if nameprotectionredis then
if tonumber(nameprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(nameprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
redis:set(namehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change name but failed ")
rename_chat(to_rename, group_name_set, ok_cb, false)
end
elseif group_name_lock == 'no' then
return nil
end
end
if matches[1] == 'setname' and is_momod(msg) then
local new_name = string.gsub(matches[2], '_', ' ')
data[tostring(msg.to.id)]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local to_rename = 'chat#id'..msg.to.id
rename_chat(to_rename, group_name_set, ok_cb, false)
savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]")
end
if matches[1] == 'setphoto' and is_momod(msg) then
data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
return 'Please send me new group photo now'
end
if matches[1] == 'promote' and not matches[2] then
if not is_owner(msg) then
return "Only the owner can prmote new moderators"
end
if type(msg.reply_id)~="nil" then
msgr = get_message(msg.reply_id, promote_by_reply, false)
end
end
if matches[1] == 'promote' and matches[2] then
if not is_momod(msg) then
return
end
if not is_owner(msg) then
return "Only owner can promote"
end
local member = matches[2]
savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @".. member)
local cbres_extra = {
chat_id = msg.to.id,
mod_cmd = 'promote',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
return res_user(username, promote_demote_res, cbres_extra)
end
if matches[1] == 'demote' and not matches[2] then
if not is_owner(msg) then
return "Only the owner can demote moderators"
end
if type(msg.reply_id)~="nil" then
msgr = get_message(msg.reply_id, demote_by_reply, false)
end
end
if matches[1] == 'demote' and matches[2] then
if not is_momod(msg) then
return
end
if not is_owner(msg) then
return "Only owner can demote"
end
if string.gsub(matches[2], "@", "") == msg.from.username and not is_owner(msg) then
return "You can't demote yourself"
end
local member = matches[2]
savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @".. member)
local cbres_extra = {
chat_id = msg.to.id,
mod_cmd = 'demote',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
return res_user(username, promote_demote_res, cbres_extra)
end
if matches[1] == 'modlist' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group modlist")
return modlist(msg)
end
if matches[1] == 'about' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group description")
return get_description(msg, data)
end
if matches[1] == 'rules' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group rules")
return get_rules(msg, data)
end
if matches[1] == 'set' then
if matches[2] == 'rules' then
rules = matches[3]
local target = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]")
return set_rulesmod(msg, data, target)
end
if matches[2] == 'about' then
local data = load_data(_config.moderation.data)
local target = msg.to.id
local about = matches[3]
savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]")
return set_descriptionmod(msg, data, target, about)
end
end
if matches[1] == 'lock' then
local target = msg.to.id
if matches[2] == 'name' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked name ")
return lock_group_namemod(msg, data, target)
end
if matches[2] == 'member' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked member ")
return lock_group_membermod(msg, data, target)
end
if matches[2] == 'flood' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked flood ")
return lock_group_floodmod(msg, data, target)
end
if matches[2] == 'arabic' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked arabic ")
return lock_group_arabic(msg, data, target)
end
if matches[2] == 'bots' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked bots ")
return lock_group_bots(msg, data, target)
end
if matches[2] == 'leave' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked leaving ")
return lock_group_leave(msg, data, target)
end
end
if matches[1] == 'unlock' then
local target = msg.to.id
if matches[2] == 'name' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked name ")
return unlock_group_namemod(msg, data, target)
end
if matches[2] == 'member' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked member ")
return unlock_group_membermod(msg, data, target)
end
if matches[2] == 'photo' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked photo ")
return unlock_group_photomod(msg, data, target)
end
if matches[2] == 'flood' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked flood ")
return unlock_group_floodmod(msg, data, target)
end
if matches[2] == 'arabic' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked arabic ")
return unlock_group_arabic(msg, data, target)
end
if matches[2] == 'bots' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked bots ")
return unlock_group_bots(msg, data, target)
end
if matches[2] == 'leave' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked leaving ")
return unlock_group_leave(msg, data, target)
end
end
if matches[1] == 'settings' then
local target = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group settings ")
return show_group_settingsmod(msg, data, target)
end
--[[if matches[1] == 'public' then
local target = msg.to.id
if matches[2] == 'yes' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: public")
return set_public_membermod(msg, data, target)
end
if matches[2] == 'no' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: not public")
return unset_public_membermod(msg, data, target)
end
end]]
if matches[1] == 'newlink' and not is_realm(msg) then
if not is_momod(msg) then
return "For moderators only!"
end
local function callback (extra , success, result)
local receiver = 'chat#'..msg.to.id
if success == 0 then
return send_large_msg(receiver, '*Error: Invite link failed* \nReason: Not creator.')
end
send_large_msg(receiver, "Created a new link")
data[tostring(msg.to.id)]['settings']['set_link'] = result
save_data(_config.moderation.data, data)
end
local receiver = 'chat#'..msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] revoked group link ")
return export_chat_link(receiver, callback, true)
end
if matches[1] == 'link' then
if not is_momod(msg) then
return "For moderators only!"
end
local group_link = data[tostring(msg.to.id)]['settings']['set_link']
if not group_link then
return "Create a link using /newlink first !"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]")
return "Group link:\n"..group_link
end
if matches[1] == 'setowner' and matches[2] then
if not is_owner(msg) then
return "For owner only!"
end
data[tostring(msg.to.id)]['set_owner'] = matches[2]
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set ["..matches[2].."] as owner")
local text = matches[2].." added as owner"
return text
end
if matches[1] == 'setowner' and not matches[2] then
if not is_owner(msg) then
return "only for the owner!"
end
if type(msg.reply_id)~="nil" then
msgr = get_message(msg.reply_id, setowner_by_reply, false)
end
end
if matches[1] == 'owner' then
local group_owner = data[tostring(msg.to.id)]['set_owner']
local user_info = redis:hgetall('user:'..group_owner)
if not group_owner then
return "no owner,ask admins in support groups to set owner for your group"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /owner")
if user_info.username then
return "Group onwer is @"..user_info.username.." ["..group_owner.."]"
else
return "Group owner is ["..group_owner..']'
end
end
if matches[1] == 'setgpowner' then
local receiver = "chat#id"..matches[2]
if not is_admin(msg) then
return "For admins only!"
end
data[tostring(matches[2])]['set_owner'] = matches[3]
save_data(_config.moderation.data, data)
local text = matches[3].." added as owner"
send_large_msg(receiver, text)
return
end
if matches[1] == 'setflood' then
if not is_momod(msg) then
return "For moderators only!"
end
if tonumber(matches[2]) < 5 or tonumber(matches[2]) > 20 then
return "Wrong number,range is [5-20]"
end
local flood_max = matches[2]
data[tostring(msg.to.id)]['settings']['flood_msg_max'] = flood_max
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set flood to ["..matches[2].."]")
return 'Group flood has been set to '..matches[2]
end
if matches[1] == 'clean' then
if not is_owner(msg) then
return "Only owner can clean"
end
if matches[2] == 'member' then
if not is_owner(msg) then
return "Only admins can clean members"
end
local receiver = get_receiver(msg)
chat_info(receiver, cleanmember, {receiver=receiver})
end
if matches[2] == 'modlist' then
if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way
return 'No moderator in this group.'
end
local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n'
for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do
data[tostring(msg.to.id)]['moderators'][tostring(k)] = nil
save_data(_config.moderation.data, data)
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned modlist")
end
if matches[2] == 'rules' then
local data_cat = 'rules'
data[tostring(msg.to.id)][data_cat] = nil
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned rules")
end
if matches[2] == 'about' then
local data_cat = 'description'
data[tostring(msg.to.id)][data_cat] = nil
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned about")
end
end
if matches[1] == 'kill' and matches[2] == 'chat' then
if not is_admin(msg) then
return nil
end
if not is_realm(msg) then
local receiver = get_receiver(msg)
return modrem(msg),
print("Closing Group..."),
chat_info(receiver, killchat, {receiver=receiver})
else
return 'This is a realm'
end
end
if matches[1] == 'kill' and matches[2] == 'realm' then
if not is_admin(msg) then
return nil
end
if not is_group(msg) then
local receiver = get_receiver(msg)
return realmrem(msg),
print("Closing Realm..."),
chat_info(receiver, killrealm, {receiver=receiver})
else
return 'This is a group'
end
end
if matches[1] == 'help' then
if not is_momod(msg) or is_realm(msg) then
return
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help")
return help()
end
if matches[1] == 'res' and is_momod(msg) then
local cbres_extra = {
chatid = msg.to.id
}
local username = matches[2]
local username = username:gsub("@","")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username)
return res_user(username, callbackres, cbres_extra)
end
if matches[1] == 'kickinactive' then
--send_large_msg('chat#id'..msg.to.id, 'I\'m in matches[1]')
if not is_momod(msg) then
return 'Only a moderator can kick inactive users'
end
local num = 1
if matches[2] then
num = matches[2]
end
local chat_id = msg.to.id
local receiver = get_receiver(msg)
return kick_inactive(chat_id, num, receiver)
end
end
end
return {
patterns = {
"^[!/](add)$",
"^[!/](add) (realm)$",
"^[!/](rem)$",
"^[!/](rem) (realm)$",
"^[!/](rules)$",
"^[!/](about)$",
"^[!/](setname) (.*)$",
"^[!/](setphoto)$",
"^[!/](promote) (.*)$",
"^[!/](promote)",
"^[!/](help)$",
"^[!/](clean) (.*)$",
"^[!/](kill) (chat)$",
"^[!/](kill) (realm)$",
"^[!/](demote) (.*)$",
"^[!/](demote)",
"^[!/](set) ([^%s]+) (.*)$",
"^[!/](lock) (.*)$",
"^[!/](setowner) (%d+)$",
"^[!/](setowner)",
"^[!/](owner)$",
"^[!/](res) (.*)$",
"^[!/](setgpowner) (%d+) (%d+)$",-- (group id) (owner id)
"^[!/](unlock) (.*)$",
"^[!/](setflood) (%d+)$",
"^[!/](settings)$",
-- "^[!/](public) (.*)$",
"^[!/](modlist)$",
"^[!/](newlink)$",
"^[!/](link)$",
"^[!/](kickinactive)$",
"^[!/](kickinactive) (%d+)$",
"%[(photo)%]",
"^!!tgservice (.+)$",
},
run = run
}
end
| gpl-2.0 |
xdemolish/darkstar | scripts/zones/Port_Bastok/npcs/Zoby_Quhyo.lua | 36 | 1693 | -----------------------------------
-- Area: Port Bastok
-- NPC: Zoby Quhyo
-- Only sells when Bastok controlls Elshimo Lowlands
-- Confirmed shop stock, August 2013
-----------------------------------
require("scripts/globals/shop");
require("scripts/globals/conquest");
package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil;
require("scripts/zones/Port_Bastok/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
RegionOwner = GetRegionOwner(ELSHIMOLOWLANDS);
if (RegionOwner ~= BASTOK) then
player:showText(npc,ZOBYQUHYO_CLOSED_DIALOG);
else
player:showText(npc,ZOBYQUHYO_OPEN_DIALOG);
stock = {
0x0272, 234, --Black Pepper
0x0264, 55, --Kazham Peppers
0x1150, 55, --Kazham Pineapple
0x0278, 110, --Kukuru Bean
0x1126, 36, --Mithran Tomato
0x0276, 88, --Ogre Pumpkin
0x0583, 1656 --Phalaenopsis
}
showShop(player,BASTOK,stock);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
xdemolish/darkstar | scripts/zones/Bastok_Mines/npcs/Explorer_Moogle.lua | 1 | 1647 | -----------------------------------
-- Area: Bastok Mines
-- NPC: Explorer Moogle
--
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/teleports");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
accept = 0;
event = 0x0249;
if (player:getGil() < 300)then
accept = 1;
end
if (player:getMainLvl() < EXPLORER_MOOGLE_LEVELCAP) then
event = event + 1;
end
player:startEvent(event,player:getZone():getID(),0,accept);
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);
local price = 300;
if (csid == 0x0249) then
if (option == 1 and player:delGil(price)) then
toExplorerMoogle(player,231);
elseif (option == 2 and player:delGil(price)) then
toExplorerMoogle(player,234);
elseif (option == 3 and player:delGil(price)) then
toExplorerMoogle(player,240);
elseif (option == 4 and player:delGil(price)) then
toExplorerMoogle(player,248);
elseif (option == 5 and player:delGil(price)) then
toExplorerMoogle(player,249);
end
end
end; | gpl-3.0 |
PlexChat/premake-core | tests/project/test_config_maps.lua | 32 | 3971 | --
-- tests/project/test_config_maps.lua
-- Test mapping from workspace to project configurations.
-- Copyright (c) 2012-2014 Jason Perkins and the Premake project
--
local suite = test.declare("project_config_maps")
--
-- Setup and teardown
--
local wks, prj, cfg
function suite.setup()
wks = workspace("MyWorkspace")
configurations { "Debug", "Release" }
end
local function prepare(buildcfg, platform)
prj = wks.projects[1]
cfg = test.getconfig(prj, buildcfg or "Debug", platform)
end
--
-- When no configuration is specified in the project, the workspace
-- settings should map directly to a configuration object.
--
function suite.workspaceConfig_onNoProjectConfigs()
project ("MyProject")
prepare()
test.isequal("Debug", cfg.buildcfg)
end
--
-- If a project configuration mapping exists, it should be taken into
-- account when fetching the configuration object.
--
function suite.appliesCfgMapping_onBuildCfgMap()
project ("MyProject")
configmap { ["Debug"] = "Development" }
prepare()
test.isequal("Development", cfg.buildcfg)
end
function suite.appliesCfgMapping_onPlatformMap()
platforms { "Shared", "Static" }
project ("MyProject")
configmap { ["Shared"] = "DLL" }
prepare("Debug", "Shared")
test.isequal("DLL", cfg.platform)
end
--
-- If a configuration mapping exists, can also use the mapped value
-- to fetch the configuration.
--
function suite.fetchesMappedCfg_onBuildCfgMap()
project ("MyProject")
configmap { ["Debug"] = "Development" }
prepare("Development")
test.isequal("Development", cfg.buildcfg)
end
function suite.fetchesMappedCfg_onPlatformMap()
platforms { "Shared", "Static" }
project ("MyProject")
configmap { ["Shared"] = "DLL" }
prepare("Debug", "DLL")
test.isequal("DLL", cfg.platform)
end
--
-- If the specified configuration has been removed from the project,
-- then nil should be returned.
--
function suite.returnsNil_onRemovedBuildCfg()
project ("MyProject")
removeconfigurations { "Debug" }
prepare()
test.isnil(cfg)
end
function suite.returnsNil_onRemovedPlatform()
platforms { "Shared", "Static" }
project ("MyProject")
removeplatforms { "Shared" }
prepare("Debug", "Shared")
test.isnil(cfg)
end
--
-- Check mapping from a buildcfg-platform tuple to a simple single
-- value platform configuration.
--
function suite.canMap_tupleToSingle()
platforms { "Win32", "Linux" }
project ("MyProject")
removeconfigurations "*"
removeplatforms "*"
configurations { "Debug Win32", "Release Win32", "Debug Linux", "Release Linux" }
configmap {
[{"Debug", "Win32"}] = "Debug Win32",
[{"Debug", "Linux"}] = "Debug Linux",
[{"Release", "Win32"}] = "Release Win32",
[{"Release", "Linux"}] = "Release Linux"
}
prepare("Debug", "Linux")
test.isequal("Debug Linux", cfg.buildcfg)
end
--
-- Check mapping from a buildcfg-platform tuple to new project
-- configuration tuple.
--
function suite.canMap_tupleToTuple()
platforms { "Win32", "Linux" }
project ("MyProject")
removeconfigurations "*"
removeplatforms "*"
configurations { "Development", "Production" }
platforms { "x86", "x86_64" }
configmap {
[{"Debug", "Win32"}] = { "Development", "x86" },
[{"Debug", "Linux"}] = { "Development", "x86_64" },
[{"Release", "Win32"}] = { "Production", "x86" },
[{"Release", "Linux"}] = { "Production", "x86_64" },
}
prepare("Debug", "Linux")
test.isequal({ "Development", "x86_64" }, { cfg.buildcfg, cfg.platform })
end
--
-- To allow some measure of global configuration, config maps that are contained
-- in configuration blocks are allowed to bubble up to the project level.
--
function suite.canBubbleUp_onConfiguration()
platforms { "XCUA", "XCUB" }
filter { "platforms:CCU" }
configmap { XCUA = "CCU", XCUB = "CCU" }
project "MyProject"
platforms { "CCU" }
prepare("Debug", "XCUA")
test.isequal({"Debug", "CCU"}, {cfg.buildcfg, cfg.platform})
end
| bsd-3-clause |
yylangchen/Sample_Lua | frameworks/cocos2d-x/templates/lua-template-runtime/src/main.lua | 5 | 1398 |
cc.FileUtils:getInstance():addSearchPath("src")
cc.FileUtils:getInstance():addSearchPath("res")
-- CC_USE_DEPRECATED_API = true
require "cocos.init"
-- cclog
local cclog = function(...)
print(string.format(...))
end
-- for CCLuaEngine traceback
function __G__TRACKBACK__(msg)
cclog("----------------------------------------")
cclog("LUA ERROR: " .. tostring(msg) .. "\n")
cclog(debug.traceback())
cclog("----------------------------------------")
return msg
end
local function main()
collectgarbage("collect")
-- avoid memory leak
collectgarbage("setpause", 100)
collectgarbage("setstepmul", 5000)
-- initialize director
local director = cc.Director:getInstance()
--turn on display FPS
director:setDisplayStats(true)
--set FPS. the default value is 1.0/60 if you don't call this
director:setAnimationInterval(1.0 / 60)
cc.Director:getInstance():getOpenGLView():setDesignResolutionSize(480, 320, 0)
--create scene
local scene = require("GameScene")
local gameScene = scene.create()
gameScene:playBgMusic()
if cc.Director:getInstance():getRunningScene() then
cc.Director:getInstance():replaceScene(gameScene)
else
cc.Director:getInstance():runWithScene(gameScene)
end
end
local status, msg = xpcall(main, __G__TRACKBACK__)
if not status then
error(msg)
end
| mit |
yylangchen/Sample_Lua | frameworks/cocos2d-x/tests/lua-tests/src/PerformanceTest/PerformanceSpriteTest.lua | 14 | 16145 | local kMaxNodes = 50000
local kBasicZOrder = 10
local kNodesIncrease = 250
local TEST_COUNT = 7
local s = cc.Director:getInstance():getWinSize()
-----------------------------------
-- For test functions
-----------------------------------
local function performanceActions(sprite)
sprite:setPosition(cc.p(math.mod(math.random(1, 99999999), s.width), math.mod(math.random(1, 99999999), s.height)))
local period = 0.5 + math.mod(math.random(1, 99999999), 1000) / 500.0
local rot = cc.RotateBy:create(period, 360.0 * math.random())
local rot = cc.RotateBy:create(period, 360.0 * math.random())
local permanentRotation = cc.RepeatForever:create(cc.Sequence:createWithTwoActions(rot, rot:reverse()))
sprite:runAction(permanentRotation)
local growDuration = 0.5 + math.mod(math.random(1, 99999999), 1000) / 500.0
local grow = cc.ScaleBy:create(growDuration, 0.5, 0.5)
local permanentScaleLoop = cc.RepeatForever:create(cc.Sequence:createWithTwoActions(grow, grow:reverse()))
sprite:runAction(permanentScaleLoop)
end
local function performanceActions20(sprite)
if math.random() < 0.2 then
sprite:setPosition(cc.p(math.mod(math.random(1, 99999999), s.width), math.mod(math.random(1, 99999999), s.height)))
else
sprite:setPosition(cc.p(-1000, -1000))
end
local period = 0.5 + math.mod(math.random(1, 99999999), 1000) / 500.0
local rot = cc.RotateBy:create(period, 360.0 * math.random())
local permanentRotation = cc.RepeatForever:create(cc.Sequence:createWithTwoActions(rot, rot:reverse()))
sprite:runAction(permanentRotation)
local growDuration = 0.5 + math.mod(math.random(1, 99999999), 1000) / 500.0
local grow = cc.ScaleBy:create(growDuration, 0.5, 0.5)
local permanentScaleLoop = cc.RepeatForever:create(cc.Sequence:createWithTwoActions(grow, grow:reverse()))
sprite:runAction(permanentScaleLoop)
end
local function performanceRotationScale(sprite)
sprite:setPosition(cc.p(math.mod(math.random(1, 99999999), s.width), math.mod(math.random(1, 99999999), s.height)))
sprite:setRotation(math.random() * 360)
sprite:setScale(math.random() * 2)
end
local function performancePosition(sprite)
sprite:setPosition(cc.p(math.mod(math.random(1, 99999999), s.width), math.mod(math.random(1, 99999999), s.height)))
end
local function performanceout20(sprite)
if math.random() < 0.2 then
sprite:setPosition(cc.p(math.mod(math.random(1, 99999999), s.width), math.mod(math.random(1, 99999999), s.height)))
else
sprite:setPosition(cc.p(-1000, -1000))
end
end
local function performanceOut100(sprite)
sprite:setPosition(cc.p( -1000, -1000))
end
local function performanceScale(sprite)
sprite:setPosition(cc.p(math.mod(math.random(1, 99999999), s.width), math.mod(math.random(1, 99999999), s.height)))
sprite:setScale(math.random() * 100 / 50)
end
-----------------------------------
-- Subtest
-----------------------------------
local subtestNumber = 1
local batchNode = nil -- cc.SpriteBatchNode
local parent = nil -- cc.Node
local function initWithSubTest(nSubTest, p)
subtestNumber = nSubTest
parent = p
batchNode = nil
local mgr = cc.Director:getInstance():getTextureCache()
-- remove all texture
mgr:removeTexture(mgr:addImage("Images/grossinis_sister1.png"))
mgr:removeTexture(mgr:addImage("Images/grossini_dance_atlas.png"))
mgr:removeTexture(mgr:addImage("Images/spritesheet1.png"))
if subtestNumber == 2 then
cc.Texture2D:setDefaultAlphaPixelFormat(cc.TEXTURE2_D_PIXEL_FORMAT_RGB_A8888)
batchNode = cc.SpriteBatchNode:create("Images/grossinis_sister1.png", 100)
p:addChild(batchNode, 0)
elseif subtestNumber == 3 then
cc.Texture2D:setDefaultAlphaPixelFormat(cc.TEXTURE2_D_PIXEL_FORMAT_RGB_A4444)
batchNode = cc.SpriteBatchNode:create("Images/grossinis_sister1.png", 100)
p:addChild(batchNode, 0)
elseif subtestNumber == 5 then
cc.Texture2D:setDefaultAlphaPixelFormat(cc.TEXTURE2_D_PIXEL_FORMAT_RGB_A8888)
batchNode = cc.SpriteBatchNode:create("Images/grossini_dance_atlas.png", 100)
p:addChild(batchNode, 0)
elseif subtestNumber == 6 then
cc.Texture2D:setDefaultAlphaPixelFormat(cc.TEXTURE2_D_PIXEL_FORMAT_RGB_A4444)
batchNode = cc.SpriteBatchNode:create("Images/grossini_dance_atlas.png", 100)
p:addChild(batchNode, 0)
elseif subtestNumber == 8 then
cc.Texture2D:setDefaultAlphaPixelFormat(cc.TEXTURE2_D_PIXEL_FORMAT_RGB_A8888)
batchNode = cc.SpriteBatchNode:create("Images/spritesheet1.png", 100)
p:addChild(batchNode, 0)
elseif subtestNumber == 9 then
cc.Texture2D:setDefaultAlphaPixelFormat(cc.TEXTURE2_D_PIXEL_FORMAT_RGB_A4444)
batchNode = cc.SpriteBatchNode:create("Images/spritesheet1.png", 100)
p:addChild(batchNode, 0)
end
-- todo
if batchNode ~= nil then
batchNode:retain()
end
cc.Texture2D:setDefaultAlphaPixelFormat(cc.TEXTURE_PIXELFORMAT_DEFAULT)
end
local function createSpriteWithTag(tag)
cc.Texture2D:setDefaultAlphaPixelFormat(cc.TEXTURE2_D_PIXEL_FORMAT_RGB_A8888)
local sprite = nil
if subtestNumber == 1 then
sprite = cc.Sprite:create("Images/grossinis_sister1.png")
parent:addChild(sprite, -1, tag + 100)
elseif subtestNumber == 2 then
sprite = cc.Sprite:createWithTexture(batchNode:getTexture(), cc.rect(0, 0, 52, 139))
batchNode:addChild(sprite, 0, tag + 100)
elseif subtestNumber == 3 then
sprite = cc.Sprite:createWithTexture(batchNode:getTexture(), cc.rect(0, 0, 52, 139))
batchNode:addChild(sprite, 0, tag + 100)
elseif subtestNumber == 4 then
local idx = math.floor((math.random() * 1400 / 100)) + 1
local num
if idx < 10 then
num = "0" .. idx
else
num = idx
end
local str = "Images/grossini_dance_" .. num .. ".png"
sprite = cc.Sprite:create(str)
parent:addChild(sprite, -1, tag + 100)
elseif subtestNumber == 5 then
local y, x
local r = math.floor(math.random() * 1400 / 100)
y = math.floor(r / 5)
x = math.mod(r, 5)
x = x * 85
y = y * 121
sprite = cc.Sprite:createWithTexture(batchNode:getTexture(), cc.rect(x, y, 85, 121))
batchNode:addChild(sprite, 0, tag + 100)
elseif subtestNumber == 6 then
local y, x
local r = math.floor(math.random() * 1400 / 100)
y = math.floor(r / 5)
x = math.mod(r, 5)
x = x * 85
y = y * 121
sprite = cc.Sprite:createWithTexture(batchNode:getTexture(), cc.rect(x, y, 85, 121))
batchNode:addChild(sprite, 0, tag + 100)
elseif subtestNumber == 7 then
local y, x
local r = math.floor(math.random() * 6400 / 100)
y = math.floor(r / 8)
x = math.mod(r, 8)
local str = "Images/sprites_test/sprite-"..x.."-"..y..".png"
sprite = cc.Sprite:create(str)
parent:addChild(sprite, -1, tag + 100)
elseif subtestNumber == 8 then
local y, x
local r = math.floor(math.random() * 6400 / 100)
y = math.floor(r / 8)
x = math.mod(r, 8)
x = x * 32
y = y * 32
sprite = cc.Sprite:createWithTexture(batchNode:getTexture(), cc.rect(x, y, 32, 32))
batchNode:addChild(sprite, 0, tag + 100)
elseif subtestNumber == 9 then
local y, x
local r = math.floor(math.random() * 6400 / 100)
y = math.floor(r / 8)
x = math.mod(r, 8)
x = x * 32
y = y * 32
sprite = cc.Sprite:createWithTexture(batchNode:getTexture(), cc.rect(x, y, 32, 32))
batchNode:addChild(sprite, 0, tag + 100)
end
cc.Texture2D:setDefaultAlphaPixelFormat(cc.TEXTURE_PIXELFORMAT_DEFAULT)
return sprite
end
local function removeByTag(tag)
if subtestNumber == 1 then
parent:removeChildByTag(tag + 100, true)
elseif subtestNumber == 4 then
parent:removeChildByTag(tag + 100, true)
elseif subtestNumber == 7 then
parent:removeChildByTag(tag + 100, true)
else
batchNode:removeChildAtIndex(tag, true)
end
end
-----------------------------------
-- PerformBasicLayer
-----------------------------------
local curCase = 0
local maxCases = 7
local function showThisTest()
local scene = CreateSpriteTestScene()
cc.Director:getInstance():replaceScene(scene)
end
local function backCallback(sender)
subtestNumber = 1
curCase = curCase - 1
if curCase < 0 then
curCase = curCase + maxCases
end
showThisTest()
end
local function restartCallback(sender)
subtestNumber = 1
showThisTest()
end
local function nextCallback(sender)
subtestNumber = 1
curCase = curCase + 1
curCase = math.mod(curCase, maxCases)
showThisTest()
end
local function toPerformanceMainLayer(sender)
cc.Director:getInstance():replaceScene(PerformanceTest())
end
local function initWithLayer(layer, controlMenuVisible)
cc.MenuItemFont:setFontName("Arial")
cc.MenuItemFont:setFontSize(24)
local mainItem = cc.MenuItemFont:create("Back")
mainItem:registerScriptTapHandler(toPerformanceMainLayer)
mainItem:setPosition(s.width - 50, 25)
local menu = cc.Menu:create()
menu:addChild(mainItem)
menu:setPosition(cc.p(0, 0))
if controlMenuVisible == true then
local item1 = cc.MenuItemImage:create(s_pPathB1, s_pPathB2)
local item2 = cc.MenuItemImage:create(s_pPathR1, s_pPathR2)
local item3 = cc.MenuItemImage:create(s_pPathF1, s_pPathF2)
item1:registerScriptTapHandler(backCallback)
item2:registerScriptTapHandler(restartCallback)
item3:registerScriptTapHandler(nextCallback)
item1:setPosition(s.width / 2 - 100, 30)
item2:setPosition(s.width / 2, 30)
item3:setPosition(s.width / 2 + 100, 30)
menu:addChild(item1, kItemTagBasic)
menu:addChild(item2, kItemTagBasic)
menu:addChild(item3, kItemTagBasic)
end
layer:addChild(menu)
end
-----------------------------------
-- SpriteMainScene
-----------------------------------
local lastRenderedCount = nil
local quantityNodes = nil
local infoLabel = nil
local titleLabel = nil
local function testNCallback(tag)
subtestNumber = tag - kBasicZOrder
showThisTest()
end
local function updateNodes()
if quantityNodes ~= lastRenderedCount then
local str = quantityNodes .. " nodes"
infoLabel:setString(str)
lastRenderedCount = quantityNodes
end
end
local function onDecrease(sender)
if quantityNodes <= 0 then
return
end
for i = 0, kNodesIncrease - 1 do
quantityNodes = quantityNodes - 1
removeByTag(quantityNodes)
end
updateNodes()
end
local function onIncrease(sender)
if quantityNodes >= kMaxNodes then
return
end
for i = 0, kNodesIncrease - 1 do
local sprite = createSpriteWithTag(quantityNodes)
if curCase == 0 then
doPerformSpriteTest1(sprite)
elseif curCase == 1 then
doPerformSpriteTest2(sprite)
elseif curCase == 2 then
doPerformSpriteTest3(sprite)
elseif curCase == 3 then
doPerformSpriteTest4(sprite)
elseif curCase == 4 then
doPerformSpriteTest5(sprite)
elseif curCase == 5 then
doPerformSpriteTest6(sprite)
elseif curCase == 6 then
doPerformSpriteTest7(sprite)
end
quantityNodes = quantityNodes + 1
end
updateNodes()
end
local function initWithMainTest(scene, asubtest, nNodes)
subtestNumber = asubtest
initWithSubTest(asubtest, scene)
lastRenderedCount = 0
quantityNodes = 0
cc.MenuItemFont:setFontSize(65)
local decrease = cc.MenuItemFont:create(" - ")
decrease:registerScriptTapHandler(onDecrease)
decrease:setColor(cc.c3b(0, 200, 20))
local increase = cc.MenuItemFont:create(" + ")
increase:registerScriptTapHandler(onIncrease)
increase:setColor(cc.c3b(0, 200, 20))
local menu = cc.Menu:create()
menu:addChild(decrease)
menu:addChild(increase)
menu:alignItemsHorizontally()
menu:setPosition(s.width / 2, s.height - 65)
scene:addChild(menu, 1)
infoLabel = cc.Label:createWithTTF("0 nodes", s_markerFeltFontPath, 30)
infoLabel:setColor(cc.c3b(0, 200, 20))
infoLabel:setAnchorPoint(cc.p(0.5, 0.5))
infoLabel:setPosition(s.width / 2, s.height - 90)
scene:addChild(infoLabel, 1)
maxCases = TEST_COUNT
-- Sub Tests
cc.MenuItemFont:setFontSize(32)
subMenu = cc.Menu:create()
for i = 1, 9 do
local str = i .. " "
local itemFont = cc.MenuItemFont:create(str)
itemFont:registerScriptTapHandler(testNCallback)
--itemFont:setTag(i)
subMenu:addChild(itemFont, kBasicZOrder + i, kBasicZOrder + i)
if i <= 3 then
itemFont:setColor(cc.c3b(200, 20, 20))
elseif i <= 6 then
itemFont:setColor(cc.c3b(0, 200, 20))
else
itemFont:setColor(cc.c3b(0, 20, 200))
end
end
subMenu:alignItemsHorizontally()
subMenu:setPosition(cc.p(s.width / 2, 80))
scene:addChild(subMenu, 1)
-- add title label
titleLabel = cc.Label:createWithTTF("No title", s_arialPath, 40)
scene:addChild(titleLabel, 1)
titleLabel:setAnchorPoint(cc.p(0.5, 0.5))
titleLabel:setPosition(s.width / 2, s.height - 32)
titleLabel:setColor(cc.c3b(255, 255, 40))
while quantityNodes < nNodes do
onIncrease()
end
end
-----------------------------------
-- SpritePerformTest1
-----------------------------------
function doPerformSpriteTest1(sprite)
performancePosition(sprite)
end
local function SpriteTestLayer1()
local layer = cc.Layer:create()
initWithLayer(layer, true)
local str = "A (" .. subtestNumber .. ") position"
titleLabel:setString(str)
return layer
end
-----------------------------------
-- SpritePerformTest2
-----------------------------------
function doPerformSpriteTest2(sprite)
performanceScale(sprite)
end
local function SpriteTestLayer2()
local layer = cc.Layer:create()
initWithLayer(layer, true)
local str = "B (" .. subtestNumber .. ") scale"
titleLabel:setString(str)
return layer
end
-----------------------------------
-- SpritePerformTest3
-----------------------------------
function doPerformSpriteTest3(sprite)
performanceRotationScale(sprite)
end
local function SpriteTestLayer3()
local layer = cc.Layer:create()
initWithLayer(layer, true)
local str = "C (" .. subtestNumber .. ") scale + rot"
titleLabel:setString(str)
return layer
end
-----------------------------------
-- SpritePerformTest4
-----------------------------------
function doPerformSpriteTest4(sprite)
performanceOut100(sprite)
end
local function SpriteTestLayer4()
local layer = cc.Layer:create()
initWithLayer(layer, true)
local str = "D (" .. subtestNumber .. ") 100% out"
titleLabel:setString(str)
return layer
end
-----------------------------------
-- SpritePerformTest5
-----------------------------------
function doPerformSpriteTest5(sprite)
performanceout20(sprite)
end
local function SpriteTestLayer5()
local layer = cc.Layer:create()
initWithLayer(layer, true)
local str = "E (" .. subtestNumber .. ") 80% out"
titleLabel:setString(str)
return layer
end
-----------------------------------
-- SpritePerformTest6
-----------------------------------
function doPerformSpriteTest6(sprite)
performanceActions(sprite)
end
local function SpriteTestLayer6()
local layer = cc.Layer:create()
initWithLayer(layer, true)
local str = "F (" .. subtestNumber .. ") actions"
titleLabel:setString(str)
return layer
end
-----------------------------------
-- SpritePerformTest7
-----------------------------------
function doPerformSpriteTest7(sprite)
performanceActions20(sprite)
end
local function SpriteTestLayer7()
local layer = cc.Layer:create()
initWithLayer(layer, true)
local str = "G (" .. subtestNumber .. ") actions 80% out"
titleLabel:setString(str)
return layer
end
-----------------------------------
-- PerformanceSpriteTest
-----------------------------------
function CreateSpriteTestScene()
local scene = cc.Scene:create()
initWithMainTest(scene, subtestNumber, kNodesIncrease)
if curCase == 0 then
scene:addChild(SpriteTestLayer1())
elseif curCase == 1 then
scene:addChild(SpriteTestLayer2())
elseif curCase == 2 then
scene:addChild(SpriteTestLayer3())
elseif curCase == 3 then
scene:addChild(SpriteTestLayer4())
elseif curCase == 4 then
scene:addChild(SpriteTestLayer5())
elseif curCase == 5 then
scene:addChild(SpriteTestLayer6())
elseif curCase == 6 then
scene:addChild(SpriteTestLayer7())
end
return scene
end
function PerformanceSpriteTest()
curCase = 0
return CreateSpriteTestScene()
end
| mit |
xdemolish/darkstar | scripts/zones/Cape_Teriggan/npcs/Voranbo-Natanbo_WW.lua | 6 | 3025 | -----------------------------------
-- Area: Cape Teriggan
-- NPC: Voranbo-Natanbo, W.W.
-- Type: Outpost Conquest Guards
-- @pos -185 7 -63 113
-----------------------------------
package.loaded["scripts/zones/Cape_Teriggan/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/conquest");
require("scripts/zones/Cape_Teriggan/TextIDs");
local guardnation = WINDURST; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno
local guardtype = 3; -- 1: city, 2: foreign, 3: outpost, 4: border
local region = VOLLBOW;
local csid = 0x7ff7;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
tradeConquestGuard(player,npc,trade,guardnation,guardtype);
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if(player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then
if(supplyRunFresh(player) == 1) then
player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies !
else
player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use."
player:delKeyItem(getSupplyKey(region));
player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region));
player:setVar("supplyQuest_region",0);
end
else
local arg1 = getArg1(guardnation, player) - 1;
if(arg1 >= 1792) then -- foreign, non-allied
player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0);
else -- citizen or allied
player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("OPTION: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("OPTION: %u",option);
if(option == 1) then
local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600;
player:delStatusEffect(EFFECT_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 |
emmericp/libmoon | lua/lib/StackTracePlus/init.lua | 44 | 12501 | -- tables
local _G = _G
local string, io, debug, coroutine = string, io, debug, coroutine
-- functions
local tostring, print, require = tostring, print, require
local next, assert = next, assert
local pcall, type, pairs, ipairs = pcall, type, pairs, ipairs
local error = error
assert(debug, "debug table must be available at this point")
local io_open = io.open
local string_gmatch = string.gmatch
local string_sub = string.sub
local table_concat = table.concat
local _M = {
max_tb_output_len = 70 -- controls the maximum length of the 'stringified' table before cutting with ' (more...)'
}
-- this tables should be weak so the elements in them won't become uncollectable
local m_known_tables = { [_G] = "_G (global table)" }
local function add_known_module(name, desc)
local ok, mod = pcall(require, name)
if ok then
m_known_tables[mod] = desc
end
end
add_known_module("string", "string module")
add_known_module("io", "io module")
add_known_module("os", "os module")
add_known_module("table", "table module")
add_known_module("math", "math module")
add_known_module("package", "package module")
add_known_module("debug", "debug module")
add_known_module("coroutine", "coroutine module")
-- lua5.2
add_known_module("bit32", "bit32 module")
-- luajit
add_known_module("bit", "bit module")
add_known_module("jit", "jit module")
local m_user_known_tables = {}
local m_known_functions = {}
for _, name in ipairs{
-- Lua 5.2, 5.1
"assert",
"collectgarbage",
"dofile",
"error",
"getmetatable",
"ipairs",
"load",
"loadfile",
"next",
"pairs",
"pcall",
"print",
"rawequal",
"rawget",
"rawlen",
"rawset",
"require",
"select",
"setmetatable",
"tonumber",
"tostring",
"type",
"xpcall",
-- Lua 5.1
"gcinfo",
"getfenv",
"loadstring",
"module",
"newproxy",
"setfenv",
"unpack",
-- TODO: add table.* etc functions
} do
if _G[name] then
m_known_functions[_G[name]] = name
end
end
local m_user_known_functions = {}
local function safe_tostring (value)
local ok, err = pcall(tostring, value)
if ok then return err else return ("<failed to get printable value>: '%s'"):format(err) end
end
-- Private:
-- Parses a line, looking for possible function definitions (in a very naïve way)
-- Returns '(anonymous)' if no function name was found in the line
local function ParseLine(line)
assert(type(line) == "string")
--print(line)
local match = line:match("^%s*function%s+(%w+)")
if match then
--print("+++++++++++++function", match)
return match
end
match = line:match("^%s*local%s+function%s+(%w+)")
if match then
--print("++++++++++++local", match)
return match
end
match = line:match("^%s*local%s+(%w+)%s+=%s+function")
if match then
--print("++++++++++++local func", match)
return match
end
match = line:match("%s*function%s*%(") -- this is an anonymous function
if match then
--print("+++++++++++++function2", match)
return "(anonymous)"
end
return "(anonymous)"
end
-- Private:
-- Tries to guess a function's name when the debug info structure does not have it.
-- It parses either the file or the string where the function is defined.
-- Returns '?' if the line where the function is defined is not found
local function GuessFunctionName(info)
--print("guessing function name")
if type(info.source) == "string" and info.source:sub(1,1) == "@" then
local file, err = io_open(info.source:sub(2), "r")
if not file then
print("file not found: "..tostring(err)) -- whoops!
return "?"
end
local line
for i = 1, info.linedefined do
line = file:read("*l")
end
if not line then
print("line not found") -- whoops!
return "?"
end
return ParseLine(line)
else
local line
local lineNumber = 0
for l in string_gmatch(info.source, "([^\n]+)\n-") do
lineNumber = lineNumber + 1
if lineNumber == info.linedefined then
line = l
break
end
end
if not line then
print("line not found") -- whoops!
return "?"
end
return ParseLine(line)
end
end
---
-- Dumper instances are used to analyze stacks and collect its information.
--
local Dumper = {}
Dumper.new = function(thread)
local t = { lines = {} }
for k,v in pairs(Dumper) do t[k] = v end
t.dumping_same_thread = (thread == coroutine.running())
-- if a thread was supplied, bind it to debug.info and debug.get
-- we also need to skip this additional level we are introducing in the callstack (only if we are running
-- in the same thread we're inspecting)
if type(thread) == "thread" then
t.getinfo = function(level, what)
if t.dumping_same_thread and type(level) == "number" then
level = level + 1
end
return debug.getinfo(thread, level, what)
end
t.getlocal = function(level, loc)
if t.dumping_same_thread then
level = level + 1
end
return debug.getlocal(thread, level, loc)
end
else
t.getinfo = debug.getinfo
t.getlocal = debug.getlocal
end
return t
end
-- helpers for collecting strings to be used when assembling the final trace
function Dumper:add (text)
self.lines[#self.lines + 1] = text
end
function Dumper:add_f (fmt, ...)
self:add(fmt:format(...))
end
function Dumper:concat_lines ()
return table_concat(self.lines)
end
---
-- Private:
-- Iterates over the local variables of a given function.
--
-- @param level The stack level where the function is.
--
function Dumper:DumpLocals (level)
local prefix = "\t "
local i = 1
if self.dumping_same_thread then
level = level + 1
end
local name, value = self.getlocal(level, i)
if not name then
return
end
self:add("\tLocal variables:\r\n")
while name do
if type(value) == "number" then
self:add_f("%s%s = number: %g\r\n", prefix, name, value)
elseif type(value) == "boolean" then
self:add_f("%s%s = boolean: %s\r\n", prefix, name, tostring(value))
elseif type(value) == "string" then
self:add_f("%s%s = string: %q\r\n", prefix, name, value)
elseif type(value) == "userdata" then
self:add_f("%s%s = %s\r\n", prefix, name, safe_tostring(value))
elseif type(value) == "nil" then
self:add_f("%s%s = nil\r\n", prefix, name)
elseif type(value) == "table" then
if m_known_tables[value] then
self:add_f("%s%s = %s\r\n", prefix, name, m_known_tables[value])
elseif m_user_known_tables[value] then
self:add_f("%s%s = %s\r\n", prefix, name, m_user_known_tables[value])
else
local txt = "{"
for k,v in pairs(value) do
txt = txt..safe_tostring(k)..":"..safe_tostring(v)
if #txt > _M.max_tb_output_len then
txt = txt.." (more...)"
break
end
if next(value, k) then txt = txt..", " end
end
self:add_f("%s%s = %s %s\r\n", prefix, name, safe_tostring(value), txt.."}")
end
elseif type(value) == "function" then
local info = self.getinfo(value, "nS")
local fun_name = info.name or m_known_functions[value] or m_user_known_functions[value]
if info.what == "C" then
self:add_f("%s%s = C %s\r\n", prefix, name, (fun_name and ("function: " .. fun_name) or tostring(value)))
else
local source = info.short_src
if source:sub(2,7) == "string" then
source = source:sub(9) -- uno más, por el espacio que viene (string "Baragent.Main", por ejemplo)
end
--for k,v in pairs(info) do print(k,v) end
fun_name = fun_name or GuessFunctionName(info)
self:add_f("%s%s = Lua function '%s' (defined at line %d of chunk %s)\r\n", prefix, name, fun_name, info.linedefined, source)
end
elseif type(value) == "thread" then
self:add_f("%sthread %q = %s\r\n", prefix, name, tostring(value))
end
i = i + 1
name, value = self.getlocal(level, i)
end
end
---
-- Public:
-- Collects a detailed stack trace, dumping locals, resolving function names when they're not available, etc.
-- This function is suitable to be used as an error handler with pcall or xpcall
--
-- @param thread An optional thread whose stack is to be inspected (defaul is the current thread)
-- @param message An optional error string or object.
-- @param level An optional number telling at which level to start the traceback (default is 1)
--
-- Returns a string with the stack trace and a string with the original error.
--
function _M.stacktrace(thread, message, level)
if type(thread) ~= "thread" then
-- shift parameters left
thread, message, level = nil, thread, message
end
thread = thread or coroutine.running()
level = level or 1
local dumper = Dumper.new(thread)
local original_error
if type(message) == "table" then
dumper:add("an error object {\r\n")
local first = true
for k,v in pairs(message) do
if first then
dumper:add(" ")
first = false
else
dumper:add(",\r\n ")
end
dumper:add(safe_tostring(k))
dumper:add(": ")
dumper:add(safe_tostring(v))
end
dumper:add("\r\n}")
original_error = dumper:concat_lines()
elseif type(message) == "string" then
dumper:add(message)
original_error = message
end
dumper:add("\r\n")
dumper:add[[
Stack Traceback
===============
]]
--print(error_message)
local level_to_show = level
if dumper.dumping_same_thread then level = level + 1 end
local info = dumper.getinfo(level, "nSlf")
while info do
if info.what == "main" then
if string_sub(info.source, 1, 1) == "@" then
dumper:add_f("(%d) main chunk of file '%s' at line %d\r\n", level_to_show, string_sub(info.source, 2), info.currentline)
else
dumper:add_f("(%d) main chunk of %s at line %d\r\n", level_to_show, info.short_src, info.currentline)
end
elseif info.what == "C" then
--print(info.namewhat, info.name)
--for k,v in pairs(info) do print(k,v, type(v)) end
local function_name = m_user_known_functions[info.func] or m_known_functions[info.func] or info.name or tostring(info.func)
dumper:add_f("(%d) %s C function '%s'\r\n", level_to_show, info.namewhat, function_name)
--dumper:add_f("%s%s = C %s\r\n", prefix, name, (m_known_functions[value] and ("function: " .. m_known_functions[value]) or tostring(value)))
elseif info.what == "tail" then
--print("tail")
--for k,v in pairs(info) do print(k,v, type(v)) end--print(info.namewhat, info.name)
dumper:add_f("(%d) tail call\r\n", level_to_show)
dumper:DumpLocals(level)
elseif info.what == "Lua" then
local source = info.short_src
local function_name = m_user_known_functions[info.func] or m_known_functions[info.func] or info.name
if source:sub(2, 7) == "string" then
source = source:sub(9)
end
local was_guessed = false
if not function_name or function_name == "?" then
--for k,v in pairs(info) do print(k,v, type(v)) end
function_name = GuessFunctionName(info)
was_guessed = true
end
-- test if we have a file name
local function_type = (info.namewhat == "") and "function" or info.namewhat
if info.source and info.source:sub(1, 1) == "@" then
dumper:add_f("(%d) Lua %s '%s' at file '%s:%d'%s\r\n", level_to_show, function_type, function_name, info.source:sub(2), info.currentline, was_guessed and " (best guess)" or "")
elseif info.source and info.source:sub(1,1) == '#' then
dumper:add_f("(%d) Lua %s '%s' at template '%s:%d'%s\r\n", level_to_show, function_type, function_name, info.source:sub(2), info.currentline, was_guessed and " (best guess)" or "")
else
dumper:add_f("(%d) Lua %s '%s' at line %d of chunk '%s'\r\n", level_to_show, function_type, function_name, info.currentline, source)
end
dumper:DumpLocals(level)
else
dumper:add_f("(%d) unknown frame %s\r\n", level_to_show, info.what)
end
level = level + 1
level_to_show = level_to_show + 1
info = dumper.getinfo(level, "nSlf")
end
return dumper:concat_lines(), original_error
end
--
-- Adds a table to the list of known tables
function _M.add_known_table(tab, description)
if m_known_tables[tab] then
error("Cannot override an already known table")
end
m_user_known_tables[tab] = description
end
--
-- Adds a function to the list of known functions
function _M.add_known_function(fun, description)
if m_known_functions[fun] then
error("Cannot override an already known function")
end
m_user_known_functions[fun] = description
end
return _M
| mit |
xdemolish/darkstar | scripts/zones/The_Garden_of_RuHmet/mobs/Ix_aern_drg.lua | 2 | 2468 | -----------------------------------
-- Area: The Garden of Ru'Hmet
-- NPC: Ix'aern (drg)
-----------------------------------
require("scripts/zones/The_Garden_of_RuHmet/MobIDs");
require( "scripts/globals/status" );
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function OnMobSpawn(mob)
end;
-----------------------------------
-- onMobFight Action
-----------------------------------
function onMobFight( mob, target )
--[[ local drga = mob:getLocalVar("drga");
local drgb = mob:getLocalVar("drgb");
local drgc = mob:getLocalVar("drgc");
if (drga == 1 and drgb == 1 and drgc == 1) then
return;
end
-- Pick a pet to spawn at random..
local ChosenPet = nil;
local newVar = nil;
repeat
local rand = math.random( 0, 2 );
ChosenPet = 16921023 + rand;
switch (ChosenPet): caseof {
[16921023] = function (x) if (drga == 1) then ChosenPet = 0; else newVar = "drga"; end end, -- drga
[16921024] = function (x) if (drgb == 1) then ChosenPet = 0; else newVar = "drgb"; end end, -- drgb
[16921025] = function (x) if (drgc == 1) then ChosenPet = 0; else newVar = "drgc"; end end, -- drgc
}
until (ChosenPet ~= 0 and ChosenPet ~= nil)
-- Spawn the pet..
local pet = SpawnMob( ChosenPet );
pet:updateEnmity( target );
pet:setPos( mob:getXPos(), mob:getYPos(), mob:getZPos() );
-- Update Ix'aern (drg) extra vars
mob:setLocalVar(newVar, 1);
-- Ensure all spawned pets are doing stuff..
for pets = 16921023, 16921025 do
if (GetMobAction( pets ) == 16) then
-- Send pet after current target..
GetMobByID( pets ):updateEnmity( target );
end
end]]--
end
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, killer)
-- Despawn pets..
DespawnMob(16921023);
DespawnMob(16921024);
DespawnMob(16921025);
end;
-----------------------------------
-- OnMobDespawn
-----------------------------------
function onMobDespawn( mob )
-- Despawn pets..
DespawnMob( 16921023 );
DespawnMob( 16921024 );
DespawnMob( 16921025 );
-- Reset popped var..
SetServerVariable("[PH]Ix_aern_drg",0);
end
| gpl-3.0 |
xdemolish/darkstar | scripts/globals/spells/utsusemi_ni.lua | 31 | 1528 | -----------------------------------------
-- Spell: Utsusemi: Ni
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
local effect = target:getStatusEffect(EFFECT_COPY_IMAGE);
-- Get extras shadows
local bonusShadow = 0;
if caster:getEquipID(SLOT_FEET) == 11156 then
bonusShadow = 1;
end
if (effect == nil) then
if caster:getMainJob() == 13 then
target:addStatusEffectEx(EFFECT_COPY_IMAGE,EFFECT_COPY_IMAGE_4, 4 + bonusShadow,0,900);
target:setMod(MOD_UTSUSEMI, 4 + bonusShadow);
spell:setMsg(230);
else
target:addStatusEffectEx(EFFECT_COPY_IMAGE,EFFECT_COPY_IMAGE_3, 3 + bonusShadow,0,900);
target:setMod(MOD_UTSUSEMI, 3 + bonusShadow);
spell:setMsg(230);
end
elseif caster:getMainJob() == 13 then
if (effect:getPower() <= 4) then
spell:setMsg(230);
effect:setPower(4);
effect:setIcon(EFFECT_COPY_IMAGE_4);
effect:resetStartTime();
target:setMod(MOD_UTSUSEMI, 4 + bonusShadow);
else
spell:setMsg(75);
end
else
if (effect:getPower() <= 3) then
spell:setMsg(230);
effect:setPower(3);
effect:setIcon(EFFECT_COPY_IMAGE_3);
effect:resetStartTime();
target:setMod(MOD_UTSUSEMI, 3 + bonusShadow);
else
spell:setMsg(75);
end
end
return EFFECT_COPY_IMAGE;
end; | gpl-3.0 |
xdemolish/darkstar | scripts/zones/Aht_Urhgan_Whitegate/npcs/Kubhe_Ijyuhla.lua | 17 | 2421 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Kubhe Ijyuhla
-- Standard Info NPC
-- @pos 23.257 0.000 21.532 50
-----------------------------------
package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/settings");
require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local threeMenProg = player:getVar("threemenandaclosetCS");
local threeMenQuest = player:getQuestStatus(AHT_URHGAN,THREE_MEN_AND_A_CLOSET);
if(player:getQuestStatus(AHT_URHGAN,GOT_IT_ALL) == QUEST_COMPLETED and threeMenQuest == QUEST_AVAILABLE) then
player:startEvent(0x0344);
elseif(threeMenProg == 2) then
player:startEvent(0x0345);
elseif(threeMenProg == 3) then
player:startEvent(0x0346);
elseif(threeMenProg == 4) then
player:startEvent(0x0347);
elseif(threeMenProg == 5) then
player:startEvent(0x034a);
elseif(threeMenProg == 6) then
player:startEvent(0x034d);
elseif(threeMenQuest == QUEST_COMPLETED) then
player:startEvent(0x034e);
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 == 0x0344)then
player:addQuest(AHT_URHGAN,THREE_MEN_AND_A_CLOSET);
player:setVar("threemenandaclosetCS",2);
elseif(csid == 0x0346) then
player:setVar("threemenandaclosetCS",4);
elseif(csid == 0x034d) then
if(player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,2184);
else
player:setVar("threemenandaclosetCS",0);
player:addItem(2184,1);
player:messageSpecial(ITEM_OBTAINEDX,2184,1);
player:completeQuest(AHT_URHGAN,THREE_MEN_AND_A_CLOSET);
end
end
end;
| gpl-3.0 |
hsiaoyi/Melo | cocos2d/tests/lua-tests/src/TerrainTest/TerrainTest.lua | 6 | 13924 | require "cocos.3d.3dConstants"
----------------------------------------
----TerrainSimple
----------------------------------------
local TerrainSimple = class("TerrainSimple", function ()
local layer = cc.Layer:create()
return layer
end)
function TerrainSimple:ctor()
-- body
self:init()
end
function TerrainSimple:init()
local visibleSize = cc.Director:getInstance():getVisibleSize()
--use custom camera
self._camera = cc.Camera:createPerspective(60, visibleSize.width/visibleSize.height, 0.1, 800)
self._camera:setCameraFlag(cc.CameraFlag.USER1)
self._camera:setPosition3D(cc.vec3(-1, 1.6, 4))
self:addChild(self._camera)
Helper.initWithLayer(self)
Helper.titleLabel:setString(self:title())
Helper.subtitleLabel:setString(self:subtitle())
local detailMapR = { _detailMapSrc = "TerrainTest/dirt.jpg", _detailMapSize = 35}
local detailMapG = { _detailMapSrc = "TerrainTest/Grass2.jpg", _detailMapSize = 35}
local detailMapB = { _detailMapSrc = "TerrainTest/road.jpg", _detailMapSize = 35}
local detailMapA = { _detailMapSrc = "TerrainTest/GreenSkin.jpg", _detailMapSize = 35}
local terrainData = { _heightMapSrc = "TerrainTest/heightmap16.jpg", _alphaMapSrc = "TerrainTest/alphamap.png" , _detailMaps = {detailMapR, detailMapG, detailMapB, detailMapA}, _detailMapAmount = 4 }
self._terrain = cc.Terrain:create(terrainData,cc.Terrain.CrackFixedType.SKIRT)
self._terrain:setLODDistance(3.2, 6.4, 9.6)
self._terrain:setMaxDetailMapAmount(4)
self:addChild(self._terrain)
self._terrain:setCameraMask(2)
self._terrain:setDrawWire(false)
local listener = cc.EventListenerTouchAllAtOnce:create()
listener:registerScriptHandler(function (touches, event)
local delta = cc.Director:getInstance():getDeltaTime()
local touch = touches[1]
local location = touch:getLocation()
local previousLocation = touch:getPreviousLocation()
local newPos = {x=previousLocation.x - location.x, y=previousLocation.y - location.y}
local matTransform = self:getNodeToWorldTransform()
local cameraDir = {x = -matTransform[9], y = -matTransform[10], z = -matTransform[11]}
cameraDir = cc.vec3normalize(cameraDir)
cameraDir.y = 0
local cameraRightDir = {x = matTransform[1], y = matTransform[2], z = matTransform[3]}
cameraRightDir = cc.vec3normalize(cameraRightDir)
cameraRightDir.y = 0
local cameraPos = self._camera:getPosition3D()
cameraPos = { x = cameraPos.x + cameraDir.x * newPos.y * 0.5 * delta, y = cameraPos.y + cameraDir.y * newPos.y * 0.5 * delta, z = cameraPos.z + cameraDir.z * newPos.y * 0.5 * delta }
cameraPos = { x = cameraPos.x + cameraRightDir.x * newPos.x * 0.5 * delta, y = cameraPos.y + cameraRightDir.y * newPos.x * 0.5 * delta, z = cameraPos.z + cameraRightDir.z * newPos.x * 0.5 * delta }
self._camera:setPosition3D(cameraPos)
end,cc.Handler.EVENT_TOUCHES_MOVED)
local eventDispatcher = self:getEventDispatcher()
eventDispatcher:addEventListenerWithSceneGraphPriority(listener, self)
--add Particle3D for test blend
local rootps = cc.PUParticleSystem3D:create("Particle3D/scripts/mp_torch.pu")
rootps:setCameraMask(cc.CameraFlag.USER1)
rootps:startParticleSystem()
self:addChild(rootps, 0, 0)
end
function TerrainSimple:title()
return "Terrain with skirt"
end
function TerrainSimple:subtitle()
return "Drag to walkThru"
end
----------------------------------------
----TerrainWalkThru
----------------------------------------
local PLAER_STATE =
{
LEFT = 0,
RIGHT = 1,
IDLE = 2,
FORWARD = 3,
BACKWARD = 4,
}
local PLAYER_HEIGHT = 0
local camera_offset = cc.vec3(0, 45, 60)
local Player = class("Player", function(file, cam, terrain)
local sprite = cc.Sprite3D:create(file)
if nil ~= sprite then
sprite._headingAngle = 0
sprite._playerState = PLAER_STATE.IDLE
sprite._cam = cam
sprite._terrain = terrain
end
return sprite
end)
function Player:ctor()
-- body
self:init()
end
function Player:init()
self._headingAxis = cc.vec3(0.0, 0.0, 0.0)
self:scheduleUpdateWithPriorityLua(function(dt)
local curPos = self:getPosition3D()
if self._playerState == PLAER_STATE.IDLE then
elseif self._playerState == PLAER_STATE.FORWARD then
local newFaceDir = cc.vec3( self._targetPos.x - curPos.x, self._targetPos.y - curPos.y, self._targetPos.z - curPos.z)
newFaceDir.y = 0.0
newFaceDir = cc.vec3normalize(newFaceDir)
local offset = cc.vec3(newFaceDir.x * 25.0 * dt, newFaceDir.y * 25.0 * dt, newFaceDir.z * 25.0 * dt)
curPos = cc.vec3(curPos.x + offset.x, curPos.y + offset.y, curPos.z + offset.z)
self:setPosition3D(curPos)
elseif self._playerState == PLAER_STATE.BACKWARD then
local transform = self:getNodeToWorldTransform()
local forward_vec = cc.vec3(-transform[9], -transform[10], -transform[11])
forward_vec = cc.vec3normalize(forward_vec)
self:setPosition3D(cc.vec3(curPos.x - forward_vec.x * 15 * dt, curPos.y - forward_vec.y * 15 * dt, curPos.z - forward_vec.z * 15 *dt))
elseif self._playerState == PLAER_STATE.LEFT then
player:setRotation3D(cc.vec3(curPos.x, curPos.y + 25 * dt, curPos.z))
elseif self._playerState == PLAER_STATE.RIGHT then
player:setRotation3D(cc.vec3(curPos.x, curPos.y - 25 * dt, curPos.z))
end
local normal = cc.vec3(0.0, 0.0, 0.0)
local player_h, normal = self._terrain:getHeight(self:getPositionX(), self:getPositionZ(), normal)
self:setPositionY(player_h + PLAYER_HEIGHT)
--need to scriptfile
local q2 = cc.quaternion_createFromAxisAngle(cc.vec3(0, 1, 0), -math.pi)
local headingQ = cc.quaternion_createFromAxisAngle(self._headingAxis, self._headingAngle)
local x = headingQ.w * q2.x + headingQ.x * q2.w + headingQ.y * q2.z - headingQ.z * q2.y
local y = headingQ.w * q2.y - headingQ.x * q2.z + headingQ.y * q2.w + headingQ.z * q2.x
local z = headingQ.w * q2.z + headingQ.x * q2.y - headingQ.y * q2.x + headingQ.z * q2.w
local w = headingQ.w * q2.w - headingQ.x * q2.x - headingQ.y * q2.y - headingQ.z * q2.z
headingQ = cc.quaternion(x, y, z, w)
self:setRotationQuat(headingQ)
local vec_offset = cc.vec4(camera_offset.x, camera_offset.y, camera_offset.z, 1)
local transform = self:getNodeToWorldTransform()
local dst = cc.vec4(0.0, 0.0, 0.0, 0.0)
vec_offset = mat4_transformVector(transform, vec_offset, dst)
local playerPos = self:getPosition3D()
self._cam:setPosition3D(cc.vec3(playerPos.x + camera_offset.x, playerPos.y + camera_offset.y, playerPos.z + camera_offset.z))
self:updateState()
end, 0)
self:registerScriptHandler(function (event)
-- body
if "exit" == event then
self:unscheduleUpdate()
end
end)
end
function Player:updateState()
if self._playerState == PLAER_STATE.FORWARD then
local player_pos = cc.p(self:getPositionX(),self:getPositionZ())
local targetPos = cc.p(self._targetPos.x, self._targetPos.z)
local dist = cc.pGetDistance(player_pos, targetPos)
if dist < 1 then
self._playerState = PLAER_STATE.IDLE
end
end
end
local TerrainWalkThru = class("TerrainWalkThru", function ()
local layer = cc.Layer:create()
Helper.initWithLayer(layer)
return layer
end)
function TerrainWalkThru:ctor()
-- body
self:init()
end
function TerrainWalkThru:init()
Helper.titleLabel:setString(self:title())
Helper.subtitleLabel:setString(self:subtitle())
local listener = cc.EventListenerTouchAllAtOnce:create()
listener:registerScriptHandler(function (touches, event)
end,cc.Handler.EVENT_TOUCHES_BEGAN)
listener:registerScriptHandler(function (touches, event)
local touch = touches[1]
local location = touch:getLocationInView()
if self._camera ~= nil then
if self._player ~= nil then
local nearP = cc.vec3(location.x, location.y, 0.0)
local farP = cc.vec3(location.x, location.y, 1.0)
local size = cc.Director:getInstance():getWinSize()
nearP = self._camera:unproject(size, nearP, nearP)
farP = self._camera:unproject(size, farP, farP)
local dir = cc.vec3(farP.x - nearP.x, farP.y - nearP.y, farP.z - nearP.z)
dir = cc.vec3normalize(dir)
local rayStep = cc.vec3(15 * dir.x, 15 * dir.y, 15 * dir.z)
local rayPos = nearP
local rayStartPosition = nearP
local lastRayPosition = rayPos
rayPos = cc.vec3(rayPos.x + rayStep.x, rayPos.y + rayStep.y, rayPos.z + rayStep.z)
-- Linear search - Loop until find a point inside and outside the terrain Vector3
local height = self._terrain:getHeight(rayPos.x, rayPos.z)
while rayPos.y > height do
lastRayPosition = rayPos
rayPos = cc.vec3(rayPos.x + rayStep.x, rayPos.y + rayStep.y, rayPos.z + rayStep.z)
height = self._terrain:getHeight(rayPos.x,rayPos.z)
end
local startPosition = lastRayPosition
local endPosition = rayPos
for i = 1, 32 do
-- Binary search pass
local middlePoint = cc.vec3(0.5 * (startPosition.x + endPosition.x), 0.5 * (startPosition.y + endPosition.y), 0.5 * (startPosition.z + endPosition.z))
if (middlePoint.y < height) then
endPosition = middlePoint
else
startPosition = middlePoint
end
end
local collisionPoint = cc.vec3(0.5 * (startPosition.x + endPosition.x), 0.5 * (startPosition.y + endPosition.y), 0.5 * (startPosition.z + endPosition.z))
local playerPos = self._player:getPosition3D()
dir = cc.vec3(collisionPoint.x - playerPos.x, collisionPoint.y - playerPos.y, collisionPoint.z - playerPos.z)
dir.y = 0
dir = cc.vec3normalize(dir)
self._player._headingAngle = -1 * math.acos(-dir.z)
self._player._headingAxis = vec3_cross(dir, cc.vec3(0, 0, -1), self._player._headingAxis)
self._player._targetPos = collisionPoint
-- self._player:forward()
self._player._playerState = PLAER_STATE.FORWARD
end
end
end,cc.Handler.EVENT_TOUCHES_ENDED)
local eventDispatcher = self:getEventDispatcher()
eventDispatcher:addEventListenerWithSceneGraphPriority(listener, self)
local visibleSize = cc.Director:getInstance():getVisibleSize()
self._camera = cc.Camera:createPerspective(60, visibleSize.width/visibleSize.height, 0.1, 200)
self._camera:setCameraFlag(cc.CameraFlag.USER1)
self:addChild(self._camera)
local detailMapR = { _detailMapSrc = "TerrainTest/dirt.jpg", _detailMapSize = 35}
local detailMapG = { _detailMapSrc = "TerrainTest/Grass2.jpg", _detailMapSize = 10}
local detailMapB = { _detailMapSrc = "TerrainTest/road.jpg", _detailMapSize = 35}
local detailMapA = { _detailMapSrc = "TerrainTest/GreenSkin.jpg", _detailMapSize = 20}
local terrainData = { _heightMapSrc = "TerrainTest/heightmap16.jpg", _alphaMapSrc = "TerrainTest/alphamap.png" , _detailMaps = {detailMapR, detailMapG, detailMapB, detailMapA}, _detailMapAmount = 4, _mapHeight = 40.0, _mapScale = 2.0 }
self._terrain = cc.Terrain:create(terrainData,cc.Terrain.CrackFixedType.SKIRT)
self._terrain:setMaxDetailMapAmount(4)
self._terrain:setCameraMask(2)
self._terrain:setDrawWire(false)
self._terrain:setSkirtHeightRatio(3)
self._terrain:setLODDistance(64,128,192)
self._player = Player:create("Sprite3DTest/girl.c3b", self._camera, self._terrain)
self._player:setCameraMask(2)
self._player:setScale(0.08)
self._player:setPositionY(self._terrain:getHeight(self._player:getPositionX(), self._player:getPositionZ()) + PLAYER_HEIGHT)
--add Particle3D for test blend
local rootps = cc.PUParticleSystem3D:create("Particle3D/scripts/mp_torch.pu")
rootps:setCameraMask(cc.CameraFlag.USER1)
rootps:setScale(30.0)
rootps:startParticleSystem()
self._player:addChild(rootps)
--add BillBoard for test blend
local billboard = cc.BillBoard:create("Images/btn-play-normal.png")
billboard:setPosition3D(cc.vec3(0,180,0))
billboard:setCameraMask(cc.CameraFlag.USER1)
self._player:addChild(billboard)
local animation = cc.Animation3D:create("Sprite3DTest/girl.c3b","Take 001")
if nil ~= animation then
local animate = cc.Animate3D:create(animation)
self._player:runAction(cc.RepeatForever:create(animate))
end
local playerPos = self._player:getPosition3D()
self._camera:setPosition3D(cc.vec3(playerPos.x + camera_offset.x, playerPos.y + camera_offset.y, playerPos.z + camera_offset.z))
self._camera:setRotation3D(cc.vec3(-45,0,0))
self:addChild(self._player)
self:addChild(self._terrain)
end
function TerrainWalkThru:title()
return "Player walk around in terrain"
end
function TerrainWalkThru:subtitle()
return "touch to move"
end
function TerrainTest()
local scene = cc.Scene:create()
Helper.createFunctionTable =
{
TerrainSimple.create,
TerrainWalkThru.create,
}
scene:addChild(TerrainSimple.create())
scene:addChild(CreateBackMenuItem())
return scene
end | apache-2.0 |
jarvissso3/jokerblue | system/bot.lua | 1 | 7728 | package.path = package.path .. ';.luarocks/share/lua/5.2/?.lua'
..';.luarocks/share/lua/5.2/?/init.lua'
package.cpath = package.cpath .. ';.luarocks/lib/lua/5.2/?.so'
require("./system/commands")
local f = assert(io.popen('/usr/bin/git describe --tags', 'r'))
VERSION = assert(f:read('*a'))
f:close()
-- This function is called when tg receive a msg
function on_msg_receive (msg)
if not started then
return
end
msg = backward_msg_format(msg)
local receiver = get_receiver(msg)
print(receiver)
--vardump(msg)
--vardump(msg)
msg = pre_process_service_msg(msg)
if msg_valid(msg) then
msg = pre_process_msg(msg)
if msg then
match_plugins(msg)
if redis:get("bot:markread") then
if redis:get("bot:markread") == "on" then
mark_read(receiver, ok_cb, false)
end
end
end
end
end
function ok_cb(extra, success, result)
end
function on_binlog_replay_end()
started = true
postpone (cron_plugins, false, 60*5.0)
-- See plugins/isup.lua as an example for cron
_config = load_config()
-- load plugins
plugins = {}
load_plugins()
end
function msg_valid(msg)
-- Don't process outgoing messages
if msg.out then
print('\27[36mNot valid: msg from us\27[39m')
return false
end
-- Before bot was started
if msg.date < os.time() - 5 then
print('\27[36mNot valid: old msg\27[39m')
return false
end
if msg.unread == 0 then
print('\27[36mNot valid: readed\27[39m')
return false
end
if not msg.to.id then
print('\27[36mNot valid: To id not provided\27[39m')
return false
end
if not msg.from.id then
print('\27[36mNot valid: From id not provided\27[39m')
return false
end
if msg.from.id == our_id then
print('\27[36mNot valid: Msg from our id\27[39m')
return false
end
if msg.to.type == 'encr_chat' then
print('\27[36mNot valid: Encrypted chat\27[39m')
return false
end
if msg.from.id == 777000 then
--send_large_msg(*group id*, msg.text) *login code will be sent to GroupID*
return false
end
return true
end
--
function pre_process_service_msg(msg)
if msg.service then
local action = msg.action or {type=""}
-- Double ! to discriminate of normal actions
msg.text = "!!tgservice " .. action.type
-- wipe the data to allow the bot to read service messages
if msg.out then
msg.out = false
end
if msg.from.id == our_id then
msg.from.id = 0
end
end
return msg
end
-- Apply plugin.pre_process function
function pre_process_msg(msg)
for name,plugin in pairs(plugins) do
if plugin.pre_process and msg then
--print('Preprocess: ', name)
msg = plugin.pre_process(msg)
end
end
return msg
end
-- Go over enabled plugins patterns.
function match_plugins(msg)
for name, plugin in pairs(plugins) do
match_plugin(plugin, name, msg)
end
end
-- Check if plugin is on _config.disabled_plugin_on_chat table
local function is_plugin_disabled_on_chat(plugin_name, receiver)
local disabled_chats = _config.disabled_plugin_on_chat
-- Table exists and chat has disabled plugins
if disabled_chats and disabled_chats[receiver] then
-- Checks if plugin is disabled on this chat
for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do
if disabled_plugin == plugin_name and disabled then
local warning = 'Plugin '..disabled_plugin..' is disabled on this chat'
print(warning)
send_msg(receiver, warning, ok_cb, false)
return true
end
end
end
return false
end
function match_plugin(plugin, plugin_name, msg)
local receiver = get_receiver(msg)
-- Go over patterns. If one matches it's enough.
for k, pattern in pairs(plugin.patterns) do
local matches = match_pattern(pattern, msg.text)
if matches then
--print("Msg pattern: ", pattern)
if is_plugin_disabled_on_chat(plugin_name, receiver) then
return nil
end
-- Function exists
if plugin.run then
-- If plugin is for privileged users only
if not warns_user_not_allowed(plugin, msg) then
local result = plugin.run(msg, matches)
if result then
send_large_msg(receiver, result)
end
end
end
-- One patterns matches
return
end
end
end
-- DEPRECATED, use send_large_msg(destination, text)
function _send_msg(destination, text)
send_large_msg(destination, text)
end
-- Save the content of _config to config.lua
function save_config( )
serialize_to_file(_config, './data/config.lua')
print ('saved config into ./data/config.lua')
end
-- Returns the config from config.lua file.
-- If file doesn't exist, create it.
function load_config( )
local f = io.open('./data/config.lua', "r")
-- If config.lua doesn't exist
if not f then
print ("Created new config file: data/config.lua")
create_config()
else
f:close()
end
local config = loadfile ("./data/config.lua")()
for v,user in pairs(config.sudo_users) do
print("Sudo: " .. user)
end
for v,VIP in pairs(config.vip_users) do
print("VIP: " .. VIP)
end
return config
end
-- Create a basic config.json file and saves it.
function create_config( )
-- A simple config with basic plugins and ourselves as privileged user
config = {
enabled_plugins = {
"all",
"anti_spam",
"banhammer",
"Groups",
"help",
"info",
"ingroup",
"invite",
"security",
"plugins",
"sudo",
"supergroup",
"language",
"whitelist",
"tools"
},
vip_users = {}, --vip users
sudo_users = {111984481,204876190,67647823,tonumber(our_id)},--Sudo users
support_gp = {},--Support id
moderation = {data = 'data/adv.json'},
about_text = [[*IN THE NAME OF ALLAH*
This is an original bot and based on (joker).
Copyright all right reserved and you must respect all laws.
Source: https://github.com/jarvissso3/jokerblue
Channel: @jarvis_joker
Messenger: @joker_hr
Creator: @joker_hr
Site: http://StoreVps.net
Version: [4.1]
]],
--Start rate:
Group_rate = [[]],
Supergroup_rate = [[]]
--Finish rate.
}
serialize_to_file(config, './data/config.lua')
print('saved config into ./data/config.lua')
end
function on_our_id (id)
our_id = id
end
function on_user_update (user, what)
--vardump (user)
end
function on_chat_update (chat, what)
--vardump (chat)
end
function on_secret_chat_update (schat, what)
--vardump (schat)
end
function on_get_difference_end ()
end
-- Enable plugins in config.json
function load_plugins()
for k, v in pairs(_config.enabled_plugins) do
print("Loading plugin", v)
local ok, err = pcall(function()
local t = loadfile("plugins/"..v..'.lua')()
plugins[v] = t
end)
if not ok then
print('\27[31mError loading plugin '..v..'\27[39m')
print(tostring(io.popen("lua plugins/"..v..".lua"):read('*all')))
print('\27[31m'..err..'\27[39m')
end
end
end
-- custom add
function load_data(filename)
local f = io.open(filename)
if not f then
return {}
end
local s = f:read('*all')
f:close()
local data = JSON.decode(s)
return data
end
function save_data(filename, data)
local s = JSON.encode(data)
local f = io.open(filename, 'w')
f:write(s)
f:close()
end
-- Call and postpone execution for cron plugins
function cron_plugins()
for name, plugin in pairs(plugins) do
-- Only plugins with cron function
if plugin.cron ~= nil then
plugin.cron()
end
end
-- Called again in 2 mins
postpone (cron_plugins, false, 120)
end
-- Start and load values
our_id = 0
now = os.time()
math.randomseed(now)
started = false
| gpl-2.0 |
mrbangi/mrbangi | plugins/Boobs.lua | 150 | 1613 | do
-- Recursive function
local function getRandomButts(attempt)
attempt = attempt or 0
attempt = attempt + 1
local res,status = http.request("http://api.obutts.ru/noise/1")
if status ~= 200 then return nil end
local data = json:decode(res)[1]
-- The OpenBoobs API sometimes returns an empty array
if not data and attempt <= 3 then
print('Cannot get that butts, trying another one...')
return getRandomButts(attempt)
end
return 'http://media.obutts.ru/' .. data.preview
end
local function getRandomBoobs(attempt)
attempt = attempt or 0
attempt = attempt + 1
local res,status = http.request("http://api.oboobs.ru/noise/1")
if status ~= 200 then return nil end
local data = json:decode(res)[1]
-- The OpenBoobs API sometimes returns an empty array
if not data and attempt < 10 then
print('Cannot get that boobs, trying another one...')
return getRandomBoobs(attempt)
end
return 'http://media.oboobs.ru/' .. data.preview
end
local function run(msg, matches)
local url = nil
if matches[1] == "!boobs" then
url = getRandomBoobs()
end
if matches[1] == "!butts" then
url = getRandomButts()
end
if url ~= nil then
local receiver = get_receiver(msg)
send_photo_from_url(receiver, url)
else
return 'Error getting boobs/butts for you, please try again later.'
end
end
return {
description = "Gets a random boobs or butts pic",
usage = {
"!boobs: Get a boobs NSFW image. ًں”",
"!butts: Get a butts NSFW image. ًں”"
},
patterns = {
"^!boobs$",
"^!butts$"
},
run = run
}
end
| gpl-2.0 |
hsiaoyi/Melo | cocos2d/tests/lua-tests/src/LightTest/LightTest.lua | 11 | 8467 | local LightTest = class("LightTest",function()
return cc.Layer:create()
end)
function LightTest:ctor()
local function onNodeEvent(event)
if event == "enter" then
self:init()
elseif event == "exit" then
self:unscheduleUpdate()
end
end
self:registerScriptHandler(onNodeEvent)
end
function LightTest:init()
self:addSprite()
self:addLights()
local s = cc.Director:getInstance():getWinSize()
local camera = cc.Camera:createPerspective(60, s.width/s.height, 1.0, 1000.0)
camera:setCameraFlag(cc.CameraFlag.USER1)
camera:setPosition3D(cc.vec3(0.0, 100, 100))
camera:lookAt(cc.vec3(0.0, 0.0, 0.0), cc.vec3(0.0, 1.0, 0.0))
self:addChild(camera)
local ttfConfig = {}
ttfConfig.fontFilePath = "fonts/arial.ttf"
ttfConfig.fontSize = 15
local ambientLightLabel = cc.Label:createWithTTF(ttfConfig,"Ambient Light ON")
local menuItem0 = cc.MenuItemLabel:create(ambientLightLabel)
menuItem0:registerScriptTapHandler(function (tag, sender)
local str = nil
local isON = not self._ambientLight:isEnabled()
if isON then
str = "Ambient Light ON"
else
str = "Ambient Light OFF"
end
self._ambientLight:setEnabled(isON)
menuItem0:setString(str)
end)
local directionalLightLabel = cc.Label:createWithTTF(ttfConfig,"Directional Light OFF")
local menuItem1 = cc.MenuItemLabel:create(directionalLightLabel)
menuItem1:registerScriptTapHandler(function (tag, sender)
local str = nil
local isON = not self._directionalLight:isEnabled()
if isON then
str = "Directional Light ON"
else
str = "Directional Light OFF"
end
self._directionalLight:setEnabled(isON)
menuItem1:setString(str)
end)
local pointLightLabel = cc.Label:createWithTTF(ttfConfig,"Point Light OFF")
local menuItem2 = cc.MenuItemLabel:create(pointLightLabel)
menuItem2:registerScriptTapHandler(function (tag, sender)
local str = nil
local isON = not self._pointLight:isEnabled()
if isON then
str = "Point Light ON"
else
str = "Point Light OFF"
end
self._pointLight:setEnabled(isON)
menuItem2:setString(str)
end)
local spotLightLabel = cc.Label:createWithTTF(ttfConfig,"Spot Light OFF")
local menuItem3 = cc.MenuItemLabel:create(spotLightLabel)
menuItem3:registerScriptTapHandler(function (tag, sender)
local str = nil
local isON = not self._spotLight:isEnabled()
if isON then
str = "Spot Light ON"
else
str = "Spot Light OFF"
end
self._spotLight:setEnabled(isON)
menuItem3:setString(str)
end)
local menu = cc.Menu:create(menuItem0, menuItem1, menuItem2, menuItem3)
menu:setPosition(cc.p(0, 0))
menuItem0:setAnchorPoint(cc.p(0.0 ,1.0))
menuItem0:setPosition( cc.p(VisibleRect:left().x, VisibleRect:top().y-50) )
menuItem1:setAnchorPoint(cc.p(0.0, 1.0))
menuItem1:setPosition( cc.p(VisibleRect:left().x, VisibleRect:top().y-100) )
menuItem2:setAnchorPoint(cc.p(0.0, 1.0))
menuItem2:setPosition( cc.p(VisibleRect:left().x, VisibleRect:top().y -150))
menuItem3:setAnchorPoint(cc.p(0.0, 1.0))
menuItem3:setPosition( cc.p(VisibleRect:left().x, VisibleRect:top().y -200))
self:addChild(menu)
local angleDelta = 0.0
local function update(delta)
if nil ~= self._directionalLight then
self._directionalLight:setRotation3D(cc.vec3(-45.0, -angleDelta * 57.29577951, 0.0))
end
if nil ~= self._pointLight then
self._pointLight:setPositionX(100.0 * math.cos(angleDelta + 2.0 * delta))
self._pointLight:setPositionY(100.0)
self._pointLight:setPositionZ(100.0 * math.sin(angleDelta + 2.0 * delta))
end
if nil ~= self._spotLight then
self._spotLight:setPositionX(100.0 * math.cos(angleDelta + 4.0 * delta))
self._spotLight:setPositionY(100.0)
self._spotLight:setPositionZ(100.0 * math.sin(angleDelta + 4.0 * delta))
self._spotLight:setDirection(cc.vec3(-math.cos(angleDelta + 4.0 * delta), -1.0, -math.sin(angleDelta + 4.0 * delta)))
end
angleDelta = angleDelta + delta
end
self:scheduleUpdateWithPriorityLua(update,0)
end
function LightTest:addSprite()
local s = cc.Director:getInstance():getWinSize()
local fileName = "Sprite3DTest/orc.c3b"
local sprite1 = cc.Sprite3D:create(fileName)
sprite1:setRotation3D(cc.vec3(0.0, 180.0, 0.0))
sprite1:setPosition(cc.p(0.0, 0.0))
sprite1:setScale(2.0)
local sp = cc.Sprite3D:create("Sprite3DTest/axe.c3b")
sprite1:getAttachNode("Bip001 R Hand"):addChild(sp)
local animation = cc.Animation3D:create(fileName)
if nil ~=animation then
local animate = cc.Animate3D:create(animation)
sprite1:runAction(cc.RepeatForever:create(animate))
end
self:addChild(sprite1)
sprite1:setCameraMask(2)
local fileName = "Sprite3DTest/sphere.c3b"
local sprite2 = cc.Sprite3D:create(fileName)
sprite2:setPosition(cc.p(30.0, 0.0))
self:addChild(sprite2)
sprite2:setCameraMask(2)
local fileName = "Sprite3DTest/sphere.c3b"
local sprite3 = cc.Sprite3D:create(fileName)
sprite3:setScale(0.5)
sprite3:setPosition(cc.p(-50.0, 0.0))
self:addChild(sprite3)
sprite3:setCameraMask(2)
local fileName = "Sprite3DTest/sphere.c3b"
local sprite4 = cc.Sprite3D:create(fileName)
sprite4:setScale(0.5)
sprite4:setPosition(cc.p(-30.0, 10.0))
self:addChild(sprite4)
sprite4:setCameraMask(2)
end
function LightTest:addLights()
local s = cc.Director:getInstance():getWinSize()
self._ambientLight = cc.AmbientLight:create(cc.c3b(200, 200, 200))
self._ambientLight:setEnabled(true)
self:addChild(self._ambientLight)
self._ambientLight:setCameraMask(2)
self._directionalLight = cc.DirectionLight:create(cc.vec3(-1.0, -1.0, 0.0), cc.c3b(200, 200, 200))
self._directionalLight:setEnabled(false)
self:addChild(self._directionalLight)
self._directionalLight:setCameraMask(2)
self._pointLight = cc.PointLight:create(cc.vec3(0.0, 0.0, 0.0), cc.c3b(200, 200, 200), 10000.0)
self._pointLight:setEnabled(false)
self:addChild(self._pointLight)
self._pointLight:setCameraMask(2)
self._spotLight = cc.SpotLight:create(cc.vec3(-1.0, -1.0, 0.0), cc.vec3(0.0, 0.0, 0.0), cc.c3b(200, 200, 200), 0.0, 0.5, 10000.0)
self._spotLight:setEnabled(false)
self:addChild(self._spotLight)
self._spotLight:setCameraMask(2)
local tintto1 = cc.TintTo:create(4, 0, 0, 255)
local tintto2 = cc.TintTo:create(4, 0, 255, 0)
local tintto3 = cc.TintTo:create(4, 255, 0, 0)
local tintto4 = cc.TintTo:create(4, 255, 255, 255)
local seq = cc.Sequence:create(tintto1,tintto2, tintto3, tintto4)
self._ambientLight:runAction(cc.RepeatForever:create(seq))
tintto1 = cc.TintTo:create(4, 255, 0, 0)
tintto2 = cc.TintTo:create(4, 0, 255, 0)
tintto3 = cc.TintTo:create(4, 0, 0, 255)
tintto4 = cc.TintTo:create(4, 255, 255, 255)
seq = cc.Sequence:create(tintto1,tintto2, tintto3, tintto4)
self._directionalLight:runAction(cc.RepeatForever:create(seq))
tintto1 = cc.TintTo:create(4, 255, 0, 0)
tintto2 = cc.TintTo:create(4, 0, 255, 0)
tintto3 = cc.TintTo:create(4, 0, 0, 255)
tintto4 = cc.TintTo:create(4, 255, 255, 255)
seq = cc.Sequence:create(tintto2, tintto1, tintto3, tintto4)
self._pointLight:runAction(cc.RepeatForever:create(seq))
tintto1 = cc.TintTo:create(4, 255, 0, 0)
tintto2 = cc.TintTo:create(4, 0, 255, 0)
tintto3 = cc.TintTo:create(4, 0, 0, 255)
tintto4 = cc.TintTo:create(4, 255, 255, 255)
seq = cc.Sequence:create(tintto3, tintto2, tintto1, tintto4)
self._spotLight:runAction(cc.RepeatForever:create(seq))
end
function LightTest.create( ... )
local layer = LightTest.new()
Helper.initWithLayer(layer)
Helper.titleLabel:setString("Light Test")
return layer
end
function LightTestMain()
cclog("LightTestMain")
local scene = cc.Scene:create()
Helper.createFunctionTable =
{
LightTest.create,
}
scene:addChild(LightTest.create(), 0)
scene:addChild(CreateBackMenuItem())
return scene
end
| apache-2.0 |
yylangchen/Sample_Lua | frameworks/cocos2d-x/cocos/scripting/lua-bindings/auto/api/ActionManagerEx.lua | 10 | 1494 |
--------------------------------
-- @module ActionManagerEx
-- @extend Ref
-- @parent_module ccs
--------------------------------
-- @overload self, char, char, cc.CallFunc
-- @overload self, char, char
-- @function [parent=#ActionManagerEx] playActionByName
-- @param self
-- @param #char jsonName
-- @param #char actionName
-- @param #cc.CallFunc func
-- @return ActionObject#ActionObject ret (return value: ccs.ActionObject)
--------------------------------
-- Gets an ActionObject with a name.<br>
-- param jsonName UI file name<br>
-- param actionName action name in the UI file.<br>
-- return ActionObject which named as the param name
-- @function [parent=#ActionManagerEx] getActionByName
-- @param self
-- @param #char jsonName
-- @param #char actionName
-- @return ActionObject#ActionObject ret (return value: ccs.ActionObject)
--------------------------------
-- Release all actions.
-- @function [parent=#ActionManagerEx] releaseActions
-- @param self
--------------------------------
-- Purges ActionManager point.<br>
-- js purge<br>
-- lua destroyActionManager
-- @function [parent=#ActionManagerEx] destroyInstance
-- @param self
--------------------------------
-- Gets the static instance of ActionManager.<br>
-- js getInstance<br>
-- lua getInstance
-- @function [parent=#ActionManagerEx] getInstance
-- @param self
-- @return ActionManagerEx#ActionManagerEx ret (return value: ccs.ActionManagerEx)
return nil
| mit |
adventure-collective/lanterns | hardware/src/init.setup.lua | 1 | 3645 | print 'Entering setup mode'
dofile("config.lua")
CHIP_ID = string.format('%X', node.chipid())
cfg={}
cfg.ssid="bunch-setup-" .. CHIP_ID
cfg.pwd="password"
wifi.setmode(wifi.SOFTAP, false)
wifi.ap.config(cfg)
tmr.create():alarm(1000, tmr.ALARM_AUTO, function(cb_timer)
if wifi.ap.getip() == nil then
print("Connecting")
else
cb_timer:unregister()
print("Connected, IP address: " .. wifi.ap.getip())
end
end)
-- wifi.setmode(wifi.STATION)
-- wifi.sta.config('DEBUG', 'CREDENTIALS')
-- tmr.create():alarm(1000, tmr.ALARM_AUTO, function(cb_timer)
-- if wifi.sta.getip() == nil then
-- print("Connecting")
-- else
-- cb_timer:unregister()
-- print("Connected, IP address: " .. wifi.sta.getip())
-- end
-- end)
SITE_FLASH = ''
-- a simple HTTP server
srv = net.createServer(net.TCP)
srv:listen(80, function(conn)
conn:on("receive", function(sck, payload)
SITE_FLASH = ''
print("PAYLOAD:" .. payload)
if (payload:sub(0,4) == 'POST') then
local body = payload:match('[^%c]*$')
print("Post body: ".. body)
parts = {}
body:gsub('&?(.-)=([^&]*)', function(key, value)
parts[key] = value
end)
config_str = template(config)
print("WRITING" .. template(config))
if file.open("config.lua", "w") then
file.write(config_str)
file.close()
end
SITE_FLASH = 'SAVED'
-- reload config
dofile("config.lua")
end
-- and send response with variables filled
sck:send(template(html))
end)
conn:on("sent", function(sck) sck:close() end)
end)
port, ip = srv:getaddr()
print(string.format("local HTTP server / port: %s:%d", ip, port))
-- dumb dumb dumb "templating"
function template(str)
return str:gsub("(${.-})", function(a)
return loadstring("return " .. a:sub(3, -2))()
end)
end
html = [[HTTP/1.0 200 OK
Content-Type: text/html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>config</title>
<style media="screen">
body {font-family: AvenirNext-bold, Arial, sans-serif;color:#222;background:#eee; background: #a3c4ff linear-gradient(135deg, #e2ffc1 0%,#a3c4ff 100%); min-height: 100vh}
label {display: flex;}
span, input {flex: 1; margin: .5em;}
span {flex: .5; text-align: right;}
form {max-width: 30em; margin: 0 auto; padding: 5em 0}
header {text-align: right;margin:.5em;font-size: 1.5em; position: fixed; transition: .3s;opacity: 1; color: #000}
[type=submit] {float:right}
input { background: rgba(255,255,255,0.4); border: none; padding: .5em; box-shadow: rgba(119, 119, 119, 0.17) 2px 2px 4px; }
</style>
</head>
<body>
<header>${SITE_FLASH}<script>setTimeout(n=>n.style.opacity=0,1500,document.currentScript.parentNode)</script></header>
<form method="post">
<h1>${CHIP_ID}</h1>
<label><span>ssid</span><input name="SSID" value="${SSID}" required></label>
<label><span>password</span><input name="PASSWORD" value="${PASSWORD}" pattern=".{0}|.{8,64}" required title="Either 0 OR (8 to 64 chars)"></label>
<label><span>bunch id</span><input name="BUNCH_ID" value="${BUNCH_ID}" required></label>
<label><span>led count</span><input name="NUM_PIXELS" value="${NUM_PIXELS}" type="number" required min="0" max="200"></label>
<input type="submit" value="save">
</form>
</body>
</html>]]
config = [[
-- Settings generated by setup:
SSID = "${parts.SSID}"
PASSWORD = "${parts.PASSWORD}"
BUNCH_ID = "${parts.BUNCH_ID}"
NUM_PIXELS = ${parts.NUM_PIXELS}
]]
| mit |
xdemolish/darkstar | scripts/zones/Kazham/npcs/Gatih_Mijurabi.lua | 21 | 1030 | -----------------------------------
-- Area: Kazham
-- NPC: Gatih Mijurabi
-- Type: Standard NPC
-- @zone: 250
-- @pos 58.249 -13.086 -49.084
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Kazham/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x00c4);
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 |
xdemolish/darkstar | scripts/globals/items/plate_of_barnacle_paella.lua | 36 | 1576 | -----------------------------------------
-- ID: 5974
-- Item: Plate of Barnacle Paella
-- Food Effect: 3 Hrs, All Races
-----------------------------------------
-- HP 40
-- Vitality 5
-- Mind -1
-- Charisma -1
-- Defense % 25 Cap 150
-- Undead Killer 5
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,10800,5974);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 40);
target:addMod(MOD_VIT, 5);
target:addMod(MOD_MND, -1);
target:addMod(MOD_CHR, -1);
target:addMod(MOD_FOOD_DEFP, 25);
target:addMod(MOD_FOOD_DEF_CAP, 150);
target:addMod(MOD_UNDEAD_KILLER, 5);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 40);
target:delMod(MOD_VIT, 5);
target:delMod(MOD_MND, -1);
target:delMod(MOD_CHR, -1);
target:delMod(MOD_FOOD_DEFP, 25);
target:delMod(MOD_FOOD_DEF_CAP, 150);
target:delMod(MOD_UNDEAD_KILLER, 5);
end;
| gpl-3.0 |
samael65535/quick-ng | cocos/scripting/lua-bindings/auto/api/SpriteBatchNode.lua | 7 | 8618 |
--------------------------------
-- @module SpriteBatchNode
-- @extend Node,TextureProtocol
-- @parent_module cc
--------------------------------
-- Append the child. <br>
-- param sprite A Sprite.
-- @function [parent=#SpriteBatchNode] appendChild
-- @param self
-- @param #cc.Sprite sprite
-- @return SpriteBatchNode#SpriteBatchNode self (return value: cc.SpriteBatchNode)
--------------------------------
--
-- @function [parent=#SpriteBatchNode] addSpriteWithoutQuad
-- @param self
-- @param #cc.Sprite child
-- @param #int z
-- @param #int aTag
-- @return SpriteBatchNode#SpriteBatchNode ret (return value: cc.SpriteBatchNode)
--------------------------------
--
-- @function [parent=#SpriteBatchNode] reorderBatch
-- @param self
-- @param #bool reorder
-- @return SpriteBatchNode#SpriteBatchNode self (return value: cc.SpriteBatchNode)
--------------------------------
-- js NA
-- @function [parent=#SpriteBatchNode] removeAllChildrenWithCleanup
-- @param self
-- @param #bool cleanup
-- @return SpriteBatchNode#SpriteBatchNode self (return value: cc.SpriteBatchNode)
--------------------------------
-- lua NA
-- @function [parent=#SpriteBatchNode] getBlendFunc
-- @param self
-- @return BlendFunc#BlendFunc ret (return value: cc.BlendFunc)
--------------------------------
-- Get the Min image block index,in all child. <br>
-- param sprite The parent sprite.<br>
-- return Index.
-- @function [parent=#SpriteBatchNode] lowestAtlasIndexInChild
-- @param self
-- @param #cc.Sprite sprite
-- @return long#long ret (return value: long)
--------------------------------
-- Get the nearest index from the sprite in z.<br>
-- param sprite The parent sprite.<br>
-- param z Z order for drawing priority.<br>
-- return Index.
-- @function [parent=#SpriteBatchNode] atlasIndexForChild
-- @param self
-- @param #cc.Sprite sprite
-- @param #int z
-- @return long#long ret (return value: long)
--------------------------------
-- Sets the TextureAtlas object. <br>
-- param textureAtlas The TextureAtlas object.
-- @function [parent=#SpriteBatchNode] setTextureAtlas
-- @param self
-- @param #cc.TextureAtlas textureAtlas
-- @return SpriteBatchNode#SpriteBatchNode self (return value: cc.SpriteBatchNode)
--------------------------------
--
-- @function [parent=#SpriteBatchNode] getTexture
-- @param self
-- @return Texture2D#Texture2D ret (return value: cc.Texture2D)
--------------------------------
-- Increase the Atlas Capacity.
-- @function [parent=#SpriteBatchNode] increaseAtlasCapacity
-- @param self
-- @return SpriteBatchNode#SpriteBatchNode self (return value: cc.SpriteBatchNode)
--------------------------------
-- Returns the TextureAtlas object. <br>
-- return The TextureAtlas object.
-- @function [parent=#SpriteBatchNode] getTextureAtlas
-- @param self
-- @return TextureAtlas#TextureAtlas ret (return value: cc.TextureAtlas)
--------------------------------
-- Inserts a quad at a certain index into the texture atlas. The Sprite won't be added into the children array.<br>
-- This method should be called only when you are dealing with very big AtlasSrite and when most of the Sprite won't be updated.<br>
-- For example: a tile map (TMXMap) or a label with lots of characters (LabelBMFont).
-- @function [parent=#SpriteBatchNode] insertQuadFromSprite
-- @param self
-- @param #cc.Sprite sprite
-- @param #long index
-- @return SpriteBatchNode#SpriteBatchNode self (return value: cc.SpriteBatchNode)
--------------------------------
--
-- @function [parent=#SpriteBatchNode] setTexture
-- @param self
-- @param #cc.Texture2D texture
-- @return SpriteBatchNode#SpriteBatchNode self (return value: cc.SpriteBatchNode)
--------------------------------
-- Rebuild index with a sprite all child. <br>
-- param parent The parent sprite.<br>
-- param index The child index.<br>
-- return Index.
-- @function [parent=#SpriteBatchNode] rebuildIndexInOrder
-- @param self
-- @param #cc.Sprite parent
-- @param #long index
-- @return long#long ret (return value: long)
--------------------------------
-- Get the Max image block index,in all child.<br>
-- param sprite The parent sprite.<br>
-- return Index.
-- @function [parent=#SpriteBatchNode] highestAtlasIndexInChild
-- @param self
-- @param #cc.Sprite sprite
-- @return long#long ret (return value: long)
--------------------------------
-- Removes a child given a certain index. It will also cleanup the running actions depending on the cleanup parameter.<br>
-- param index A certain index.<br>
-- param doCleanup Whether or not to cleanup the running actions.<br>
-- warning Removing a child from a SpriteBatchNode is very slow.
-- @function [parent=#SpriteBatchNode] removeChildAtIndex
-- @param self
-- @param #long index
-- @param #bool doCleanup
-- @return SpriteBatchNode#SpriteBatchNode self (return value: cc.SpriteBatchNode)
--------------------------------
-- Remove a sprite from Atlas. <br>
-- param sprite A Sprite.
-- @function [parent=#SpriteBatchNode] removeSpriteFromAtlas
-- @param self
-- @param #cc.Sprite sprite
-- @return SpriteBatchNode#SpriteBatchNode self (return value: cc.SpriteBatchNode)
--------------------------------
-- code<br>
-- When this function bound into js or lua,the parameter will be changed.<br>
-- In js: var setBlendFunc(var src, var dst).<br>
-- endcode<br>
-- lua NA
-- @function [parent=#SpriteBatchNode] setBlendFunc
-- @param self
-- @param #cc.BlendFunc blendFunc
-- @return SpriteBatchNode#SpriteBatchNode self (return value: cc.SpriteBatchNode)
--------------------------------
-- Creates a SpriteBatchNode with a file image (.png, .jpeg, .pvr, etc) and capacity of children.<br>
-- The capacity will be increased in 33% in runtime if it runs out of space.<br>
-- The file will be loaded using the TextureMgr.<br>
-- param fileImage A file image (.png, .jpeg, .pvr, etc).<br>
-- param capacity The capacity of children.<br>
-- return Return an autorelease object.
-- @function [parent=#SpriteBatchNode] create
-- @param self
-- @param #string fileImage
-- @param #long capacity
-- @return SpriteBatchNode#SpriteBatchNode ret (return value: cc.SpriteBatchNode)
--------------------------------
-- Creates a SpriteBatchNode with a texture2d and capacity of children.<br>
-- The capacity will be increased in 33% in runtime if it runs out of space.<br>
-- param tex A texture2d.<br>
-- param capacity The capacity of children.<br>
-- return Return an autorelease object.
-- @function [parent=#SpriteBatchNode] createWithTexture
-- @param self
-- @param #cc.Texture2D tex
-- @param #long capacity
-- @return SpriteBatchNode#SpriteBatchNode ret (return value: cc.SpriteBatchNode)
--------------------------------
-- @overload self, cc.Node, int, string
-- @overload self, cc.Node, int, int
-- @function [parent=#SpriteBatchNode] addChild
-- @param self
-- @param #cc.Node child
-- @param #int zOrder
-- @param #int tag
-- @return SpriteBatchNode#SpriteBatchNode self (return value: cc.SpriteBatchNode)
--------------------------------
-- js NA
-- @function [parent=#SpriteBatchNode] draw
-- @param self
-- @param #cc.Renderer renderer
-- @param #mat4_table transform
-- @param #unsigned int flags
-- @return SpriteBatchNode#SpriteBatchNode self (return value: cc.SpriteBatchNode)
--------------------------------
-- js NA
-- @function [parent=#SpriteBatchNode] getDescription
-- @param self
-- @return string#string ret (return value: string)
--------------------------------
-- js NA
-- @function [parent=#SpriteBatchNode] visit
-- @param self
-- @param #cc.Renderer renderer
-- @param #mat4_table parentTransform
-- @param #unsigned int parentFlags
-- @return SpriteBatchNode#SpriteBatchNode self (return value: cc.SpriteBatchNode)
--------------------------------
--
-- @function [parent=#SpriteBatchNode] sortAllChildren
-- @param self
-- @return SpriteBatchNode#SpriteBatchNode self (return value: cc.SpriteBatchNode)
--------------------------------
--
-- @function [parent=#SpriteBatchNode] removeChild
-- @param self
-- @param #cc.Node child
-- @param #bool cleanup
-- @return SpriteBatchNode#SpriteBatchNode self (return value: cc.SpriteBatchNode)
--------------------------------
--
-- @function [parent=#SpriteBatchNode] reorderChild
-- @param self
-- @param #cc.Node child
-- @param #int zOrder
-- @return SpriteBatchNode#SpriteBatchNode self (return value: cc.SpriteBatchNode)
return nil
| mit |
Zarakichi/ObEngine | engine/Lib/Extlibs/pl/compat.lua | 5 | 5040 | ----------------
--- Lua 5.1/5.2/5.3 compatibility.
-- Ensures that `table.pack` and `package.searchpath` are available
-- for Lua 5.1 and LuaJIT.
-- The exported function `load` is Lua 5.2 compatible.
-- `compat.setfenv` and `compat.getfenv` are available for Lua 5.2, although
-- they are not always guaranteed to work.
-- @module pl.compat
local compat = {}
compat.lua51 = _VERSION == 'Lua 5.1'
local isJit = (tostring(assert):match('builtin') ~= nil)
if isJit then
-- 'goto' is a keyword when 52 compatibility is enabled in LuaJit
compat.jit52 = not loadstring("local goto = 1")
end
compat.dir_separator = _G.package.config:sub(1,1)
compat.is_windows = compat.dir_separator == '\\'
--- execute a shell command.
-- This is a compatibility function that returns the same for Lua 5.1 and Lua 5.2
-- @param cmd a shell command
-- @return true if successful
-- @return actual return code
function compat.execute (cmd)
local res1,_,res3 = os.execute(cmd)
if compat.lua51 and not compat.jit52 then
if compat.is_windows then
res1 = res1 > 255 and res1 % 256 or res1
return res1==0,res1
else
res1 = res1 > 255 and res1 / 256 or res1
return res1==0,res1
end
else
if compat.is_windows then
res3 = res3 > 255 and res3 % 256 or res3
return res3==0,res3
else
return not not res1,res3
end
end
end
----------------
-- Load Lua code as a text or binary chunk.
-- @param ld code string or loader
-- @param[opt] source name of chunk for errors
-- @param[opt] mode 'b', 't' or 'bt'
-- @param[opt] env environment to load the chunk in
-- @function compat.load
---------------
-- Get environment of a function.
-- With Lua 5.2, may return nil for a function with no global references!
-- Based on code by [Sergey Rozhenko](http://lua-users.org/lists/lua-l/2010-06/msg00313.html)
-- @param f a function or a call stack reference
-- @function compat.getfenv
---------------
-- Set environment of a function
-- @param f a function or a call stack reference
-- @param env a table that becomes the new environment of `f`
-- @function compat.setfenv
if compat.lua51 then -- define Lua 5.2 style load()
if not isJit then -- but LuaJIT's load _is_ compatible
local lua51_load = load
function compat.load(str,src,mode,env)
local chunk,err
if type(str) == 'string' then
if str:byte(1) == 27 and not (mode or 'bt'):find 'b' then
return nil,"attempt to load a binary chunk"
end
chunk,err = loadstring(str,src)
else
chunk,err = lua51_load(str,src)
end
if chunk and env then setfenv(chunk,env) end
return chunk,err
end
else
compat.load = load
end
compat.setfenv, compat.getfenv = setfenv, getfenv
else
compat.load = load
-- setfenv/getfenv replacements for Lua 5.2
-- by Sergey Rozhenko
-- http://lua-users.org/lists/lua-l/2010-06/msg00313.html
-- Roberto Ierusalimschy notes that it is possible for getfenv to return nil
-- in the case of a function with no globals:
-- http://lua-users.org/lists/lua-l/2010-06/msg00315.html
function compat.setfenv(f, t)
f = (type(f) == 'function' and f or debug.getinfo(f + 1, 'f').func)
local name
local up = 0
repeat
up = up + 1
name = debug.getupvalue(f, up)
until name == '_ENV' or name == nil
if name then
debug.upvaluejoin(f, up, function() return name end, 1) -- use unique upvalue
debug.setupvalue(f, up, t)
end
if f ~= 0 then return f end
end
function compat.getfenv(f)
local f = f or 0
f = (type(f) == 'function' and f or debug.getinfo(f + 1, 'f').func)
local name, val
local up = 0
repeat
up = up + 1
name, val = debug.getupvalue(f, up)
until name == '_ENV' or name == nil
return val
end
end
--- Lua 5.2 Functions Available for 5.1
-- @section lua52
--- pack an argument list into a table.
-- @param ... any arguments
-- @return a table with field n set to the length
-- @return the length
-- @function table.pack
if not table.pack then
function table.pack (...)
return {n=select('#',...); ...}
end
end
------
-- return the full path where a Lua module name would be matched.
-- @param mod module name, possibly dotted
-- @param path a path in the same form as package.path or package.cpath
-- @see path.package_path
-- @function package.searchpath
if not package.searchpath then
local sep = package.config:sub(1,1)
function package.searchpath (mod,path)
mod = mod:gsub('%.',sep)
for m in path:gmatch('[^;]+') do
local nm = m:gsub('?',mod)
local f = io.open(nm,'r')
if f then f:close(); return nm end
end
end
end
return compat
| mit |
xdemolish/darkstar | scripts/zones/Temenos/mobs/Temenos_Weapon.lua | 17 | 1285 | -----------------------------------
-- Area: Temenos Central 1floor
-- NPC: Temenos_Weapon
-----------------------------------
package.loaded["scripts/zones/Temenos/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/limbus");
require("scripts/zones/Temenos/TextIDs");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
if(IsMobDead(16929048)==true)then
mob:addStatusEffect(EFFECT_REGAIN,7,3,0);
mob:addStatusEffect(EFFECT_REGEN,50,3,0);
end
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer)
local mobX = mob:getXPos();
local mobY = mob:getYPos();
local mobZ = mob:getZPos();
if(IsMobDead(16929046)==true and IsMobDead(16929047)==true and IsMobDead(16929048)==true and IsMobDead(16929049)==true and IsMobDead(16929050)==true and IsMobDead(16929051)==true)then
GetNPCByID(16928768+71):setPos(mobX,mobY,mobZ);
GetNPCByID(16928768+71):setStatus(STATUS_NORMAL);
GetNPCByID(16928770+471):setStatus(STATUS_NORMAL);
end
end;
| gpl-3.0 |
Javaxio/BadRotations | System/UI/Elements/Section.lua | 2 | 2798 | local DiesalGUI = LibStub("DiesalGUI-1.0")
function br.ui:createSection(parent, sectionName, tooltip)
local newSection = DiesalGUI:Create('AccordianSection')
local parent = parent
newSection:SetParentObject(parent)
newSection:ClearAllPoints()
-- Calculate Position
if #parent.children == nil then
newSection.settings.position = 1
else
newSection.settings.position = #parent.children + 1
end
newSection.settings.sectionName = sectionName
if br.data.settings[br.selectedSpec][br.selectedProfile] == nil then br.data.settings[br.selectedSpec][br.selectedProfile] = {} end
newSection.settings.expanded = br.data.settings[br.selectedSpec][br.selectedProfile][sectionName.."Section"] or true
-- newSection.settings.contentPadding = {0,0,12,32}
newSection:SetEventListener('OnStateChange', function(this, event)
br.data.settings[br.selectedSpec][br.selectedProfile][sectionName.."Section"] = newSection.settings.expanded
end)
-- Event: Tooltip
if tooltip then
newSection:SetEventListener("OnEnter", function(this, event)
GameTooltip:SetOwner(Minimap, "ANCHOR_CURSOR", 50 , 50)
GameTooltip:SetText(tooltip, 214/255, 25/255, 25/255)
GameTooltip:Show()
end)
newSection:SetEventListener("OnLeave", function(this, event)
GameTooltip:Hide()
end)
end
newSection:ApplySettings()
newSection:UpdateHeight()
parent:AddChild(newSection)
return newSection
end
-- Restore last saved state of section (collapsed or expanded)
function br.ui:checkSectionState(section)
local state = br.data.settings[br.selectedSpec][br.selectedProfile][section.settings.sectionName.."Section"]
--Override UpdateHeight()
local function UpdateHeight(self)
local settings, children = self.settings, self.children
local contentHeight = 0
self.content:SetPoint('TOPLEFT',self.frame,0,settings.button and -settings.buttonHeight or 0)
if settings.expanded then
contentHeight = settings.contentPadding[3] + settings.contentPadding[4]
for i=1 , #children do
-- Print("children[i].type: "..children[i].type)
if children[i].type ~= "Spinner" and children[i].type ~= "Dropdown" then
contentHeight = contentHeight + children[i].frame:GetHeight()*1.2
end
end
end
self.content:SetHeight(contentHeight)
self:SetHeight((settings.button and settings.buttonHeight or 0) + contentHeight)
self:FireEvent("OnHeightChange",contentHeight)
end
if state then
section:Expand()
UpdateHeight(section)
else
section:Collapse()
end
end | gpl-3.0 |
yangchaogit/ABTestingGateway | lib/abtesting/userinfo/ipParser.lua | 25 | 1259 |
local _M = {
_VERSION = '0.01'
}
local ffi = require("ffi")
ffi.cdef[[
struct in_addr {
uint32_t s_addr;
};
int inet_aton(const char *cp, struct in_addr *inp);
uint32_t ntohl(uint32_t netlong);
char *inet_ntoa(struct in_addr in);
uint32_t htonl(uint32_t hostlong);
]]
local C = ffi.C
local ip2long = function(ip)
local inp = ffi.new("struct in_addr[1]")
if C.inet_aton(ip, inp) ~= 0 then
return tonumber(C.ntohl(inp[0].s_addr))
end
return nil
end
local long2ip = function(long)
if type(long) ~= "number" then
return nil
end
local addr = ffi.new("struct in_addr")
addr.s_addr = C.htonl(long)
return ffi.string(C.inet_ntoa(addr))
end
_M.get = function()
local ClientIP = ngx.req.get_headers()["X-Real-IP"]
if ClientIP == nil then
ClientIP = ngx.req.get_headers()["X-Forwarded-For"]
if ClientIP then
local colonPos = string.find(ClientIP, ' ')
if colonPos then
ClientIP = string.sub(ClientIP, 1, colonPos - 1)
end
end
end
if ClientIP == nil then
ClientIP = ngx.var.remote_addr
end
if ClientIP then
ClientIP = ip2long(ClientIP)
end
return ClientIP
end
return _M
| mit |
xdemolish/darkstar | scripts/globals/items/dish_of_spaghetti_marinara.lua | 35 | 1471 | -----------------------------------------
-- ID: 5719
-- Item: dish_of_spaghetti_marinara
-- Food Effect: 30Min, All Races
-----------------------------------------
-- HP % 15 (cap 120)
-- Vitality 2
-- Defense 5
-- Store TP 7
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,1800,5719);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_FOOD_HPP, 15);
target:addMod(MOD_FOOD_HP_CAP, 120);
target:addMod(MOD_VIT, 2);
target:addMod(MOD_DEF, 5);
target:addMod(MOD_STORETP, 7);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_FOOD_HPP, 15);
target:delMod(MOD_FOOD_HP_CAP, 120);
target:delMod(MOD_VIT, 2);
target:delMod(MOD_DEF, 5);
target:delMod(MOD_STORETP, 7);
end;
| gpl-3.0 |
lighter-cd/premake4-mobile | tests/actions/codeblocks/codeblocks_files.lua | 21 | 1664 | --
-- tests/actions/codeblocks/codeblocks_files.lua
-- Validate generation of files block in CodeLite C/C++ projects.
-- Copyright (c) 2011 Jason Perkins and the Premake project
--
T.codeblocks_files = { }
local suite = T.codeblocks_files
local codeblocks = premake.codeblocks
--
-- Setup
--
local sln, prj
function suite.setup()
sln = test.createsolution()
end
local function prepare()
premake.bake.buildconfigs()
prj = premake.solution.getproject(sln, 1)
codeblocks.files(prj)
end
--
-- Test grouping and nesting
--
function suite.SimpleSourceFile()
files { "hello.cpp" }
prepare()
test.capture [[
<Unit filename="hello.cpp">
</Unit>
]]
end
function suite.SingleFolderLevel()
files { "src/hello.cpp" }
prepare()
test.capture [[
<Unit filename="src/hello.cpp">
</Unit>
]]
end
function suite.MultipleFolderLevels()
files { "src/greetings/hello.cpp" }
prepare()
test.capture [[
<Unit filename="src/greetings/hello.cpp">
</Unit>
]]
end
--
-- Test source file type handling
--
function suite.CFileInCppProject()
files { "hello.c" }
prepare()
test.capture [[
<Unit filename="hello.c">
<Option compilerVar="CC" />
</Unit>
]]
end
function suite.WindowsResourceFile()
files { "hello.rc" }
prepare()
test.capture [[
<Unit filename="hello.rc">
<Option compilerVar="WINDRES" />
</Unit>
]]
end
function suite.PchFile()
files { "hello.h" }
pchheader "hello.h"
prepare()
test.capture [[
<Unit filename="hello.h">
<Option compilerVar="CPP" />
<Option compile="1" />
<Option weight="0" />
<Add option="-x c++-header" />
</Unit>
]]
end
| mit |
xdemolish/darkstar | scripts/zones/Kazham/npcs/Hari_Pakhroib.lua | 19 | 2828 | -----------------------------------
-- Area: Kazham
-- NPC: Hari Pakhroib
-- Starts and Finishes Quest: Greetings to the Guardian
-----------------------------------
package.loaded["scripts/zones/Kazham/TextIDs"] = nil;
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/globals/titles");
require("scripts/zones/Kazham/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
Guardian = player:getQuestStatus(OUTLANDS,GREETINGS_TO_THE_GUARDIAN);
Pamamas = player:getVar("PamamaVar");
pfame = player:getFameLevel(KAZHAM)
needToZone = player:needToZone();
if(Guardian == QUEST_ACCEPTED) then
if(Pamamas == 1) then
player:startEvent(0x0047); --Finish Quest
else
player:startEvent(0x0045,0,4596); --Reminder Dialogue
end
elseif(Guardian == QUEST_AVAILABLE and pfame >= 7) then
player:startEvent(0x0044,4596,4596,4596); --Start Quest
elseif(Guardian == QUEST_COMPLETED and needToZone == false) then
if(Pamamas == 2) then
player:startEvent(0x0047); --Finish quest dialogue (no different csid between initial and repeats)
else
player:startEvent(0x0048); --Dialogue for after completion of quest
end
elseif(Guardian == QUEST_COMPLETED and needToZone == true) then
player:startEvent(0x0048);
else
player:startEvent(0x0054); --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 == 0x0044 and option == 1) then
player:addQuest(OUTLANDS,GREETINGS_TO_THE_GUARDIAN);
player:setVar("PamamaVar",0);
elseif(csid == 0x0047) then
if(Pamamas == 1) then --First completion of quest; set title, complete quest, and give higher fame
player:addGil(GIL_RATE*5000);
player:messageSpecial(GIL_OBTAINED, 5000);
player:completeQuest(OUTLANDS,GREETINGS_TO_THE_GUARDIAN);
player:addFame(WINDURST,WIN_FAME*100);
player:addTitle(KAZHAM_CALLER);
player:setVar("PamamaVar",0);
player:needToZone(true);
elseif(Pamamas == 2) then --Repeats of quest; give only gil and less fame
player:addGil(GIL_RATE*5000);
player:messageSpecial(GIL_OBTAINED, 5000);
player:addFame(WINDURST,WIN_FAME*30);
player:setVar("PamamaVar",0);
player:needToZone(true);
end
end
end;
| gpl-3.0 |
PlexChat/premake-core | tests/api/test_list_kind.lua | 9 | 1617 | --
-- tests/api/test_list_kind.lua
-- Tests the list API value type.
-- Copyright (c) 2012 Jason Perkins and the Premake project
--
T.api_list_kind = {}
local suite = T.api_list_kind
local api = premake.api
--
-- Setup and teardown
--
function suite.setup()
api.register {
name = "testapi",
kind = "string",
list = true,
scope = "project",
allowed = { "first", "second", "third" }
}
test.createWorkspace()
end
function suite.teardown()
testapi = nil
end
--
-- Table values should be stored as-is.
--
function suite.storesTable_onArrayValue()
testapi { "first", "second" }
test.isequal({ "first", "second" }, api.scope.project.testapi)
end
--
-- String values should be converted into a table.
--
function suite.storesTable_onStringValue()
testapi "first"
test.isequal({ "first" }, api.scope.project.testapi)
end
--
-- New values should be appended to any previous values.
--
function suite.overwrites_onNewValue()
testapi "first"
testapi "second"
test.isequal({ "first", "second" }, api.scope.project.testapi)
end
--
-- Nested lists should be flattened.
--
function suite.flattensValues_onNestedLists()
testapi { { "first" }, { "second" } }
test.isequal({ "first", "second" }, api.scope.project.testapi)
end
--
-- If an allowed values list is present, make sure it gets applied.
--
function suite.raisesError_onDisallowedValue()
ok, err = pcall(function ()
testapi "NotAllowed"
end)
test.isfalse(ok)
end
function suite.convertsCase_onAllowedValue()
testapi "seCOnd"
test.isequal({ "second" }, api.scope.project.testapi)
end
| bsd-3-clause |
lukego/snabb | lib/luajit/dynasm/dasm_arm.lua | 15 | 34598 | ------------------------------------------------------------------------------
-- DynASM ARM module.
--
-- Copyright (C) 2005-2015 Mike Pall. All rights reserved.
-- See dynasm.lua for full copyright notice.
------------------------------------------------------------------------------
-- Module information:
local _info = {
arch = "arm",
description = "DynASM ARM module",
version = "1.4.0",
vernum = 10400,
release = "2015-10-18",
author = "Mike Pall",
license = "MIT",
}
-- Exported glue functions for the arch-specific module.
local _M = { _info = _info }
-- Cache library functions.
local type, tonumber, pairs, ipairs = type, tonumber, pairs, ipairs
local assert, setmetatable, rawget = assert, setmetatable, rawget
local _s = string
local sub, format, byte, char = _s.sub, _s.format, _s.byte, _s.char
local match, gmatch, gsub = _s.match, _s.gmatch, _s.gsub
local concat, sort, insert = table.concat, table.sort, table.insert
local bit = bit or require("bit")
local band, shl, shr, sar = bit.band, bit.lshift, bit.rshift, bit.arshift
local ror, tohex = bit.ror, bit.tohex
-- Inherited tables and callbacks.
local g_opt, g_arch
local wline, werror, wfatal, wwarn
-- Action name list.
-- CHECK: Keep this in sync with the C code!
local action_names = {
"STOP", "SECTION", "ESC", "REL_EXT",
"ALIGN", "REL_LG", "LABEL_LG",
"REL_PC", "LABEL_PC", "IMM", "IMM12", "IMM16", "IMML8", "IMML12", "IMMV8",
}
-- Maximum number of section buffer positions for dasm_put().
-- CHECK: Keep this in sync with the C code!
local maxsecpos = 25 -- Keep this low, to avoid excessively long C lines.
-- Action name -> action number.
local map_action = {}
for n,name in ipairs(action_names) do
map_action[name] = n-1
end
-- Action list buffer.
local actlist = {}
-- Argument list for next dasm_put(). Start with offset 0 into action list.
local actargs = { 0 }
-- Current number of section buffer positions for dasm_put().
local secpos = 1
------------------------------------------------------------------------------
-- Dump action names and numbers.
local function dumpactions(out)
out:write("DynASM encoding engine action codes:\n")
for n,name in ipairs(action_names) do
local num = map_action[name]
out:write(format(" %-10s %02X %d\n", name, num, num))
end
out:write("\n")
end
-- Write action list buffer as a huge static C array.
local function writeactions(out, name)
local nn = #actlist
if nn == 0 then nn = 1; actlist[0] = map_action.STOP end
out:write("static const unsigned int ", name, "[", nn, "] = {\n")
for i = 1,nn-1 do
assert(out:write("0x", tohex(actlist[i]), ",\n"))
end
assert(out:write("0x", tohex(actlist[nn]), "\n};\n\n"))
end
------------------------------------------------------------------------------
-- Add word to action list.
local function wputxw(n)
assert(n >= 0 and n <= 0xffffffff and n % 1 == 0, "word out of range")
actlist[#actlist+1] = n
end
-- Add action to list with optional arg. Advance buffer pos, too.
local function waction(action, val, a, num)
local w = assert(map_action[action], "bad action name `"..action.."'")
wputxw(w * 0x10000 + (val or 0))
if a then actargs[#actargs+1] = a end
if a or num then secpos = secpos + (num or 1) end
end
-- Flush action list (intervening C code or buffer pos overflow).
local function wflush(term)
if #actlist == actargs[1] then return end -- Nothing to flush.
if not term then waction("STOP") end -- Terminate action list.
wline(format("dasm_put(Dst, %s);", concat(actargs, ", ")), true)
actargs = { #actlist } -- Actionlist offset is 1st arg to next dasm_put().
secpos = 1 -- The actionlist offset occupies a buffer position, too.
end
-- Put escaped word.
local function wputw(n)
if n <= 0x000fffff then waction("ESC") end
wputxw(n)
end
-- Reserve position for word.
local function wpos()
local pos = #actlist+1
actlist[pos] = ""
return pos
end
-- Store word to reserved position.
local function wputpos(pos, n)
assert(n >= 0 and n <= 0xffffffff and n % 1 == 0, "word out of range")
if n <= 0x000fffff then
insert(actlist, pos+1, n)
n = map_action.ESC * 0x10000
end
actlist[pos] = n
end
------------------------------------------------------------------------------
-- Global label name -> global label number. With auto assignment on 1st use.
local next_global = 20
local map_global = setmetatable({}, { __index = function(t, name)
if not match(name, "^[%a_][%w_]*$") then werror("bad global label") end
local n = next_global
if n > 2047 then werror("too many global labels") end
next_global = n + 1
t[name] = n
return n
end})
-- Dump global labels.
local function dumpglobals(out, lvl)
local t = {}
for name, n in pairs(map_global) do t[n] = name end
out:write("Global labels:\n")
for i=20,next_global-1 do
out:write(format(" %s\n", t[i]))
end
out:write("\n")
end
-- Write global label enum.
local function writeglobals(out, prefix)
local t = {}
for name, n in pairs(map_global) do t[n] = name end
out:write("enum {\n")
for i=20,next_global-1 do
out:write(" ", prefix, t[i], ",\n")
end
out:write(" ", prefix, "_MAX\n};\n")
end
-- Write global label names.
local function writeglobalnames(out, name)
local t = {}
for name, n in pairs(map_global) do t[n] = name end
out:write("static const char *const ", name, "[] = {\n")
for i=20,next_global-1 do
out:write(" \"", t[i], "\",\n")
end
out:write(" (const char *)0\n};\n")
end
------------------------------------------------------------------------------
-- Extern label name -> extern label number. With auto assignment on 1st use.
local next_extern = 0
local map_extern_ = {}
local map_extern = setmetatable({}, { __index = function(t, name)
-- No restrictions on the name for now.
local n = next_extern
if n > 2047 then werror("too many extern labels") end
next_extern = n + 1
t[name] = n
map_extern_[n] = name
return n
end})
-- Dump extern labels.
local function dumpexterns(out, lvl)
out:write("Extern labels:\n")
for i=0,next_extern-1 do
out:write(format(" %s\n", map_extern_[i]))
end
out:write("\n")
end
-- Write extern label names.
local function writeexternnames(out, name)
out:write("static const char *const ", name, "[] = {\n")
for i=0,next_extern-1 do
out:write(" \"", map_extern_[i], "\",\n")
end
out:write(" (const char *)0\n};\n")
end
------------------------------------------------------------------------------
-- Arch-specific maps.
-- Ext. register name -> int. name.
local map_archdef = { sp = "r13", lr = "r14", pc = "r15", }
-- Int. register name -> ext. name.
local map_reg_rev = { r13 = "sp", r14 = "lr", r15 = "pc", }
local map_type = {} -- Type name -> { ctype, reg }
local ctypenum = 0 -- Type number (for Dt... macros).
-- Reverse defines for registers.
function _M.revdef(s)
return map_reg_rev[s] or s
end
local map_shift = { lsl = 0, lsr = 1, asr = 2, ror = 3, }
local map_cond = {
eq = 0, ne = 1, cs = 2, cc = 3, mi = 4, pl = 5, vs = 6, vc = 7,
hi = 8, ls = 9, ge = 10, lt = 11, gt = 12, le = 13, al = 14,
hs = 2, lo = 3,
}
------------------------------------------------------------------------------
-- Template strings for ARM instructions.
local map_op = {
-- Basic data processing instructions.
and_3 = "e0000000DNPs",
eor_3 = "e0200000DNPs",
sub_3 = "e0400000DNPs",
rsb_3 = "e0600000DNPs",
add_3 = "e0800000DNPs",
adc_3 = "e0a00000DNPs",
sbc_3 = "e0c00000DNPs",
rsc_3 = "e0e00000DNPs",
tst_2 = "e1100000NP",
teq_2 = "e1300000NP",
cmp_2 = "e1500000NP",
cmn_2 = "e1700000NP",
orr_3 = "e1800000DNPs",
mov_2 = "e1a00000DPs",
bic_3 = "e1c00000DNPs",
mvn_2 = "e1e00000DPs",
and_4 = "e0000000DNMps",
eor_4 = "e0200000DNMps",
sub_4 = "e0400000DNMps",
rsb_4 = "e0600000DNMps",
add_4 = "e0800000DNMps",
adc_4 = "e0a00000DNMps",
sbc_4 = "e0c00000DNMps",
rsc_4 = "e0e00000DNMps",
tst_3 = "e1100000NMp",
teq_3 = "e1300000NMp",
cmp_3 = "e1500000NMp",
cmn_3 = "e1700000NMp",
orr_4 = "e1800000DNMps",
mov_3 = "e1a00000DMps",
bic_4 = "e1c00000DNMps",
mvn_3 = "e1e00000DMps",
lsl_3 = "e1a00000DMws",
lsr_3 = "e1a00020DMws",
asr_3 = "e1a00040DMws",
ror_3 = "e1a00060DMws",
rrx_2 = "e1a00060DMs",
-- Multiply and multiply-accumulate.
mul_3 = "e0000090NMSs",
mla_4 = "e0200090NMSDs",
umaal_4 = "e0400090DNMSs", -- v6
mls_4 = "e0600090DNMSs", -- v6T2
umull_4 = "e0800090DNMSs",
umlal_4 = "e0a00090DNMSs",
smull_4 = "e0c00090DNMSs",
smlal_4 = "e0e00090DNMSs",
-- Halfword multiply and multiply-accumulate.
smlabb_4 = "e1000080NMSD", -- v5TE
smlatb_4 = "e10000a0NMSD", -- v5TE
smlabt_4 = "e10000c0NMSD", -- v5TE
smlatt_4 = "e10000e0NMSD", -- v5TE
smlawb_4 = "e1200080NMSD", -- v5TE
smulwb_3 = "e12000a0NMS", -- v5TE
smlawt_4 = "e12000c0NMSD", -- v5TE
smulwt_3 = "e12000e0NMS", -- v5TE
smlalbb_4 = "e1400080NMSD", -- v5TE
smlaltb_4 = "e14000a0NMSD", -- v5TE
smlalbt_4 = "e14000c0NMSD", -- v5TE
smlaltt_4 = "e14000e0NMSD", -- v5TE
smulbb_3 = "e1600080NMS", -- v5TE
smultb_3 = "e16000a0NMS", -- v5TE
smulbt_3 = "e16000c0NMS", -- v5TE
smultt_3 = "e16000e0NMS", -- v5TE
-- Miscellaneous data processing instructions.
clz_2 = "e16f0f10DM", -- v5T
rev_2 = "e6bf0f30DM", -- v6
rev16_2 = "e6bf0fb0DM", -- v6
revsh_2 = "e6ff0fb0DM", -- v6
sel_3 = "e6800fb0DNM", -- v6
usad8_3 = "e780f010NMS", -- v6
usada8_4 = "e7800010NMSD", -- v6
rbit_2 = "e6ff0f30DM", -- v6T2
movw_2 = "e3000000DW", -- v6T2
movt_2 = "e3400000DW", -- v6T2
-- Note: the X encodes width-1, not width.
sbfx_4 = "e7a00050DMvX", -- v6T2
ubfx_4 = "e7e00050DMvX", -- v6T2
-- Note: the X encodes the msb field, not the width.
bfc_3 = "e7c0001fDvX", -- v6T2
bfi_4 = "e7c00010DMvX", -- v6T2
-- Packing and unpacking instructions.
pkhbt_3 = "e6800010DNM", pkhbt_4 = "e6800010DNMv", -- v6
pkhtb_3 = "e6800050DNM", pkhtb_4 = "e6800050DNMv", -- v6
sxtab_3 = "e6a00070DNM", sxtab_4 = "e6a00070DNMv", -- v6
sxtab16_3 = "e6800070DNM", sxtab16_4 = "e6800070DNMv", -- v6
sxtah_3 = "e6b00070DNM", sxtah_4 = "e6b00070DNMv", -- v6
sxtb_2 = "e6af0070DM", sxtb_3 = "e6af0070DMv", -- v6
sxtb16_2 = "e68f0070DM", sxtb16_3 = "e68f0070DMv", -- v6
sxth_2 = "e6bf0070DM", sxth_3 = "e6bf0070DMv", -- v6
uxtab_3 = "e6e00070DNM", uxtab_4 = "e6e00070DNMv", -- v6
uxtab16_3 = "e6c00070DNM", uxtab16_4 = "e6c00070DNMv", -- v6
uxtah_3 = "e6f00070DNM", uxtah_4 = "e6f00070DNMv", -- v6
uxtb_2 = "e6ef0070DM", uxtb_3 = "e6ef0070DMv", -- v6
uxtb16_2 = "e6cf0070DM", uxtb16_3 = "e6cf0070DMv", -- v6
uxth_2 = "e6ff0070DM", uxth_3 = "e6ff0070DMv", -- v6
-- Saturating instructions.
qadd_3 = "e1000050DMN", -- v5TE
qsub_3 = "e1200050DMN", -- v5TE
qdadd_3 = "e1400050DMN", -- v5TE
qdsub_3 = "e1600050DMN", -- v5TE
-- Note: the X for ssat* encodes sat_imm-1, not sat_imm.
ssat_3 = "e6a00010DXM", ssat_4 = "e6a00010DXMp", -- v6
usat_3 = "e6e00010DXM", usat_4 = "e6e00010DXMp", -- v6
ssat16_3 = "e6a00f30DXM", -- v6
usat16_3 = "e6e00f30DXM", -- v6
-- Parallel addition and subtraction.
sadd16_3 = "e6100f10DNM", -- v6
sasx_3 = "e6100f30DNM", -- v6
ssax_3 = "e6100f50DNM", -- v6
ssub16_3 = "e6100f70DNM", -- v6
sadd8_3 = "e6100f90DNM", -- v6
ssub8_3 = "e6100ff0DNM", -- v6
qadd16_3 = "e6200f10DNM", -- v6
qasx_3 = "e6200f30DNM", -- v6
qsax_3 = "e6200f50DNM", -- v6
qsub16_3 = "e6200f70DNM", -- v6
qadd8_3 = "e6200f90DNM", -- v6
qsub8_3 = "e6200ff0DNM", -- v6
shadd16_3 = "e6300f10DNM", -- v6
shasx_3 = "e6300f30DNM", -- v6
shsax_3 = "e6300f50DNM", -- v6
shsub16_3 = "e6300f70DNM", -- v6
shadd8_3 = "e6300f90DNM", -- v6
shsub8_3 = "e6300ff0DNM", -- v6
uadd16_3 = "e6500f10DNM", -- v6
uasx_3 = "e6500f30DNM", -- v6
usax_3 = "e6500f50DNM", -- v6
usub16_3 = "e6500f70DNM", -- v6
uadd8_3 = "e6500f90DNM", -- v6
usub8_3 = "e6500ff0DNM", -- v6
uqadd16_3 = "e6600f10DNM", -- v6
uqasx_3 = "e6600f30DNM", -- v6
uqsax_3 = "e6600f50DNM", -- v6
uqsub16_3 = "e6600f70DNM", -- v6
uqadd8_3 = "e6600f90DNM", -- v6
uqsub8_3 = "e6600ff0DNM", -- v6
uhadd16_3 = "e6700f10DNM", -- v6
uhasx_3 = "e6700f30DNM", -- v6
uhsax_3 = "e6700f50DNM", -- v6
uhsub16_3 = "e6700f70DNM", -- v6
uhadd8_3 = "e6700f90DNM", -- v6
uhsub8_3 = "e6700ff0DNM", -- v6
-- Load/store instructions.
str_2 = "e4000000DL", str_3 = "e4000000DL", str_4 = "e4000000DL",
strb_2 = "e4400000DL", strb_3 = "e4400000DL", strb_4 = "e4400000DL",
ldr_2 = "e4100000DL", ldr_3 = "e4100000DL", ldr_4 = "e4100000DL",
ldrb_2 = "e4500000DL", ldrb_3 = "e4500000DL", ldrb_4 = "e4500000DL",
strh_2 = "e00000b0DL", strh_3 = "e00000b0DL",
ldrh_2 = "e01000b0DL", ldrh_3 = "e01000b0DL",
ldrd_2 = "e00000d0DL", ldrd_3 = "e00000d0DL", -- v5TE
ldrsb_2 = "e01000d0DL", ldrsb_3 = "e01000d0DL",
strd_2 = "e00000f0DL", strd_3 = "e00000f0DL", -- v5TE
ldrsh_2 = "e01000f0DL", ldrsh_3 = "e01000f0DL",
ldm_2 = "e8900000oR", ldmia_2 = "e8900000oR", ldmfd_2 = "e8900000oR",
ldmda_2 = "e8100000oR", ldmfa_2 = "e8100000oR",
ldmdb_2 = "e9100000oR", ldmea_2 = "e9100000oR",
ldmib_2 = "e9900000oR", ldmed_2 = "e9900000oR",
stm_2 = "e8800000oR", stmia_2 = "e8800000oR", stmfd_2 = "e8800000oR",
stmda_2 = "e8000000oR", stmfa_2 = "e8000000oR",
stmdb_2 = "e9000000oR", stmea_2 = "e9000000oR",
stmib_2 = "e9800000oR", stmed_2 = "e9800000oR",
pop_1 = "e8bd0000R", push_1 = "e92d0000R",
-- Branch instructions.
b_1 = "ea000000B",
bl_1 = "eb000000B",
blx_1 = "e12fff30C",
bx_1 = "e12fff10M",
-- Miscellaneous instructions.
nop_0 = "e1a00000",
mrs_1 = "e10f0000D",
bkpt_1 = "e1200070K", -- v5T
svc_1 = "ef000000T", swi_1 = "ef000000T",
ud_0 = "e7f001f0",
-- VFP instructions.
["vadd.f32_3"] = "ee300a00dnm",
["vadd.f64_3"] = "ee300b00Gdnm",
["vsub.f32_3"] = "ee300a40dnm",
["vsub.f64_3"] = "ee300b40Gdnm",
["vmul.f32_3"] = "ee200a00dnm",
["vmul.f64_3"] = "ee200b00Gdnm",
["vnmul.f32_3"] = "ee200a40dnm",
["vnmul.f64_3"] = "ee200b40Gdnm",
["vmla.f32_3"] = "ee000a00dnm",
["vmla.f64_3"] = "ee000b00Gdnm",
["vmls.f32_3"] = "ee000a40dnm",
["vmls.f64_3"] = "ee000b40Gdnm",
["vnmla.f32_3"] = "ee100a40dnm",
["vnmla.f64_3"] = "ee100b40Gdnm",
["vnmls.f32_3"] = "ee100a00dnm",
["vnmls.f64_3"] = "ee100b00Gdnm",
["vdiv.f32_3"] = "ee800a00dnm",
["vdiv.f64_3"] = "ee800b00Gdnm",
["vabs.f32_2"] = "eeb00ac0dm",
["vabs.f64_2"] = "eeb00bc0Gdm",
["vneg.f32_2"] = "eeb10a40dm",
["vneg.f64_2"] = "eeb10b40Gdm",
["vsqrt.f32_2"] = "eeb10ac0dm",
["vsqrt.f64_2"] = "eeb10bc0Gdm",
["vcmp.f32_2"] = "eeb40a40dm",
["vcmp.f64_2"] = "eeb40b40Gdm",
["vcmpe.f32_2"] = "eeb40ac0dm",
["vcmpe.f64_2"] = "eeb40bc0Gdm",
["vcmpz.f32_1"] = "eeb50a40d",
["vcmpz.f64_1"] = "eeb50b40Gd",
["vcmpze.f32_1"] = "eeb50ac0d",
["vcmpze.f64_1"] = "eeb50bc0Gd",
vldr_2 = "ed100a00dl|ed100b00Gdl",
vstr_2 = "ed000a00dl|ed000b00Gdl",
vldm_2 = "ec900a00or",
vldmia_2 = "ec900a00or",
vldmdb_2 = "ed100a00or",
vpop_1 = "ecbd0a00r",
vstm_2 = "ec800a00or",
vstmia_2 = "ec800a00or",
vstmdb_2 = "ed000a00or",
vpush_1 = "ed2d0a00r",
["vmov.f32_2"] = "eeb00a40dm|eeb00a00dY", -- #imm is VFPv3 only
["vmov.f64_2"] = "eeb00b40Gdm|eeb00b00GdY", -- #imm is VFPv3 only
vmov_2 = "ee100a10Dn|ee000a10nD",
vmov_3 = "ec500a10DNm|ec400a10mDN|ec500b10GDNm|ec400b10GmDN",
vmrs_0 = "eef1fa10",
vmrs_1 = "eef10a10D",
vmsr_1 = "eee10a10D",
["vcvt.s32.f32_2"] = "eebd0ac0dm",
["vcvt.s32.f64_2"] = "eebd0bc0dGm",
["vcvt.u32.f32_2"] = "eebc0ac0dm",
["vcvt.u32.f64_2"] = "eebc0bc0dGm",
["vcvtr.s32.f32_2"] = "eebd0a40dm",
["vcvtr.s32.f64_2"] = "eebd0b40dGm",
["vcvtr.u32.f32_2"] = "eebc0a40dm",
["vcvtr.u32.f64_2"] = "eebc0b40dGm",
["vcvt.f32.s32_2"] = "eeb80ac0dm",
["vcvt.f64.s32_2"] = "eeb80bc0GdFm",
["vcvt.f32.u32_2"] = "eeb80a40dm",
["vcvt.f64.u32_2"] = "eeb80b40GdFm",
["vcvt.f32.f64_2"] = "eeb70bc0dGm",
["vcvt.f64.f32_2"] = "eeb70ac0GdFm",
-- VFPv4 only:
["vfma.f32_3"] = "eea00a00dnm",
["vfma.f64_3"] = "eea00b00Gdnm",
["vfms.f32_3"] = "eea00a40dnm",
["vfms.f64_3"] = "eea00b40Gdnm",
["vfnma.f32_3"] = "ee900a40dnm",
["vfnma.f64_3"] = "ee900b40Gdnm",
["vfnms.f32_3"] = "ee900a00dnm",
["vfnms.f64_3"] = "ee900b00Gdnm",
-- NYI: Advanced SIMD instructions.
-- NYI: I have no need for these instructions right now:
-- swp, swpb, strex, ldrex, strexd, ldrexd, strexb, ldrexb, strexh, ldrexh
-- msr, nopv6, yield, wfe, wfi, sev, dbg, bxj, smc, srs, rfe
-- cps, setend, pli, pld, pldw, clrex, dsb, dmb, isb
-- stc, ldc, mcr, mcr2, mrc, mrc2, mcrr, mcrr2, mrrc, mrrc2, cdp, cdp2
}
-- Add mnemonics for "s" variants.
do
local t = {}
for k,v in pairs(map_op) do
if sub(v, -1) == "s" then
local v2 = sub(v, 1, 2)..char(byte(v, 3)+1)..sub(v, 4, -2)
t[sub(k, 1, -3).."s"..sub(k, -2)] = v2
end
end
for k,v in pairs(t) do
map_op[k] = v
end
end
------------------------------------------------------------------------------
local function parse_gpr(expr)
local tname, ovreg = match(expr, "^([%w_]+):(r1?[0-9])$")
local tp = map_type[tname or expr]
if tp then
local reg = ovreg or tp.reg
if not reg then
werror("type `"..(tname or expr).."' needs a register override")
end
expr = reg
end
local r = match(expr, "^r(1?[0-9])$")
if r then
r = tonumber(r)
if r <= 15 then return r, tp end
end
werror("bad register name `"..expr.."'")
end
local function parse_gpr_pm(expr)
local pm, expr2 = match(expr, "^([+-]?)(.*)$")
return parse_gpr(expr2), (pm == "-")
end
local function parse_vr(expr, tp)
local t, r = match(expr, "^([sd])([0-9]+)$")
if t == tp then
r = tonumber(r)
if r <= 31 then
if t == "s" then return shr(r, 1), band(r, 1) end
return band(r, 15), shr(r, 4)
end
end
werror("bad register name `"..expr.."'")
end
local function parse_reglist(reglist)
reglist = match(reglist, "^{%s*([^}]*)}$")
if not reglist then werror("register list expected") end
local rr = 0
for p in gmatch(reglist..",", "%s*([^,]*),") do
local rbit = shl(1, parse_gpr(gsub(p, "%s+$", "")))
if band(rr, rbit) ~= 0 then
werror("duplicate register `"..p.."'")
end
rr = rr + rbit
end
return rr
end
local function parse_vrlist(reglist)
local ta, ra, tb, rb = match(reglist,
"^{%s*([sd])([0-9]+)%s*%-%s*([sd])([0-9]+)%s*}$")
ra, rb = tonumber(ra), tonumber(rb)
if ta and ta == tb and ra and rb and ra <= 31 and rb <= 31 and ra <= rb then
local nr = rb+1 - ra
if ta == "s" then
return shl(shr(ra,1),12)+shl(band(ra,1),22) + nr
else
return shl(band(ra,15),12)+shl(shr(ra,4),22) + nr*2 + 0x100
end
end
werror("register list expected")
end
local function parse_imm(imm, bits, shift, scale, signed)
imm = match(imm, "^#(.*)$")
if not imm then werror("expected immediate operand") end
local n = tonumber(imm)
if n then
local m = sar(n, scale)
if shl(m, scale) == n then
if signed then
local s = sar(m, bits-1)
if s == 0 then return shl(m, shift)
elseif s == -1 then return shl(m + shl(1, bits), shift) end
else
if sar(m, bits) == 0 then return shl(m, shift) end
end
end
werror("out of range immediate `"..imm.."'")
else
waction("IMM", (signed and 32768 or 0)+scale*1024+bits*32+shift, imm)
return 0
end
end
local function parse_imm12(imm)
local n = tonumber(imm)
if n then
local m = band(n)
for i=0,-15,-1 do
if shr(m, 8) == 0 then return m + shl(band(i, 15), 8) end
m = ror(m, 2)
end
werror("out of range immediate `"..imm.."'")
else
waction("IMM12", 0, imm)
return 0
end
end
local function parse_imm16(imm)
imm = match(imm, "^#(.*)$")
if not imm then werror("expected immediate operand") end
local n = tonumber(imm)
if n then
if shr(n, 16) == 0 then return band(n, 0x0fff) + shl(band(n, 0xf000), 4) end
werror("out of range immediate `"..imm.."'")
else
waction("IMM16", 32*16, imm)
return 0
end
end
local function parse_imm_load(imm, ext)
local n = tonumber(imm)
if n then
if ext then
if n >= -255 and n <= 255 then
local up = 0x00800000
if n < 0 then n = -n; up = 0 end
return shl(band(n, 0xf0), 4) + band(n, 0x0f) + up
end
else
if n >= -4095 and n <= 4095 then
if n >= 0 then return n+0x00800000 end
return -n
end
end
werror("out of range immediate `"..imm.."'")
else
waction(ext and "IMML8" or "IMML12", 32768 + shl(ext and 8 or 12, 5), imm)
return 0
end
end
local function parse_shift(shift, gprok)
if shift == "rrx" then
return 3 * 32
else
local s, s2 = match(shift, "^(%S+)%s*(.*)$")
s = map_shift[s]
if not s then werror("expected shift operand") end
if sub(s2, 1, 1) == "#" then
return parse_imm(s2, 5, 7, 0, false) + shl(s, 5)
else
if not gprok then werror("expected immediate shift operand") end
return shl(parse_gpr(s2), 8) + shl(s, 5) + 16
end
end
end
local function parse_label(label, def)
local prefix = sub(label, 1, 2)
-- =>label (pc label reference)
if prefix == "=>" then
return "PC", 0, sub(label, 3)
end
-- ->name (global label reference)
if prefix == "->" then
return "LG", map_global[sub(label, 3)]
end
if def then
-- [1-9] (local label definition)
if match(label, "^[1-9]$") then
return "LG", 10+tonumber(label)
end
else
-- [<>][1-9] (local label reference)
local dir, lnum = match(label, "^([<>])([1-9])$")
if dir then -- Fwd: 1-9, Bkwd: 11-19.
return "LG", lnum + (dir == ">" and 0 or 10)
end
-- extern label (extern label reference)
local extname = match(label, "^extern%s+(%S+)$")
if extname then
return "EXT", map_extern[extname]
end
end
werror("bad label `"..label.."'")
end
local function parse_load(params, nparams, n, op)
local oplo = band(op, 255)
local ext, ldrd = (oplo ~= 0), (oplo == 208)
local d
if (ldrd or oplo == 240) then
d = band(shr(op, 12), 15)
if band(d, 1) ~= 0 then werror("odd destination register") end
end
local pn = params[n]
local p1, wb = match(pn, "^%[%s*(.-)%s*%](!?)$")
local p2 = params[n+1]
if not p1 then
if not p2 then
if match(pn, "^[<>=%-]") or match(pn, "^extern%s+") then
local mode, n, s = parse_label(pn, false)
waction("REL_"..mode, n + (ext and 0x1800 or 0x0800), s, 1)
return op + 15 * 65536 + 0x01000000 + (ext and 0x00400000 or 0)
end
local reg, tailr = match(pn, "^([%w_:]+)%s*(.*)$")
if reg and tailr ~= "" then
local d, tp = parse_gpr(reg)
if tp then
waction(ext and "IMML8" or "IMML12", 32768 + 32*(ext and 8 or 12),
format(tp.ctypefmt, tailr))
return op + shl(d, 16) + 0x01000000 + (ext and 0x00400000 or 0)
end
end
end
werror("expected address operand")
end
if wb == "!" then op = op + 0x00200000 end
if p2 then
if wb == "!" then werror("bad use of '!'") end
local p3 = params[n+2]
op = op + shl(parse_gpr(p1), 16)
local imm = match(p2, "^#(.*)$")
if imm then
local m = parse_imm_load(imm, ext)
if p3 then werror("too many parameters") end
op = op + m + (ext and 0x00400000 or 0)
else
local m, neg = parse_gpr_pm(p2)
if ldrd and (m == d or m-1 == d) then werror("register conflict") end
op = op + m + (neg and 0 or 0x00800000) + (ext and 0 or 0x02000000)
if p3 then op = op + parse_shift(p3) end
end
else
local p1a, p2 = match(p1, "^([^,%s]*)%s*(.*)$")
op = op + shl(parse_gpr(p1a), 16) + 0x01000000
if p2 ~= "" then
local imm = match(p2, "^,%s*#(.*)$")
if imm then
local m = parse_imm_load(imm, ext)
op = op + m + (ext and 0x00400000 or 0)
else
local p2a, p3 = match(p2, "^,%s*([^,%s]*)%s*,?%s*(.*)$")
local m, neg = parse_gpr_pm(p2a)
if ldrd and (m == d or m-1 == d) then werror("register conflict") end
op = op + m + (neg and 0 or 0x00800000) + (ext and 0 or 0x02000000)
if p3 ~= "" then
if ext then werror("too many parameters") end
op = op + parse_shift(p3)
end
end
else
if wb == "!" then werror("bad use of '!'") end
op = op + (ext and 0x00c00000 or 0x00800000)
end
end
return op
end
local function parse_vload(q)
local reg, imm = match(q, "^%[%s*([^,%s]*)%s*(.*)%]$")
if reg then
local d = shl(parse_gpr(reg), 16)
if imm == "" then return d end
imm = match(imm, "^,%s*#(.*)$")
if imm then
local n = tonumber(imm)
if n then
if n >= -1020 and n <= 1020 and n%4 == 0 then
return d + (n >= 0 and n/4+0x00800000 or -n/4)
end
werror("out of range immediate `"..imm.."'")
else
waction("IMMV8", 32768 + 32*8, imm)
return d
end
end
else
if match(q, "^[<>=%-]") or match(q, "^extern%s+") then
local mode, n, s = parse_label(q, false)
waction("REL_"..mode, n + 0x2800, s, 1)
return 15 * 65536
end
local reg, tailr = match(q, "^([%w_:]+)%s*(.*)$")
if reg and tailr ~= "" then
local d, tp = parse_gpr(reg)
if tp then
waction("IMMV8", 32768 + 32*8, format(tp.ctypefmt, tailr))
return shl(d, 16)
end
end
end
werror("expected address operand")
end
------------------------------------------------------------------------------
-- Handle opcodes defined with template strings.
local function parse_template(params, template, nparams, pos)
local op = tonumber(sub(template, 1, 8), 16)
local n = 1
local vr = "s"
-- Process each character.
for p in gmatch(sub(template, 9), ".") do
local q = params[n]
if p == "D" then
op = op + shl(parse_gpr(q), 12); n = n + 1
elseif p == "N" then
op = op + shl(parse_gpr(q), 16); n = n + 1
elseif p == "S" then
op = op + shl(parse_gpr(q), 8); n = n + 1
elseif p == "M" then
op = op + parse_gpr(q); n = n + 1
elseif p == "d" then
local r,h = parse_vr(q, vr); op = op+shl(r,12)+shl(h,22); n = n + 1
elseif p == "n" then
local r,h = parse_vr(q, vr); op = op+shl(r,16)+shl(h,7); n = n + 1
elseif p == "m" then
local r,h = parse_vr(q, vr); op = op+r+shl(h,5); n = n + 1
elseif p == "P" then
local imm = match(q, "^#(.*)$")
if imm then
op = op + parse_imm12(imm) + 0x02000000
else
op = op + parse_gpr(q)
end
n = n + 1
elseif p == "p" then
op = op + parse_shift(q, true); n = n + 1
elseif p == "L" then
op = parse_load(params, nparams, n, op)
elseif p == "l" then
op = op + parse_vload(q)
elseif p == "B" then
local mode, n, s = parse_label(q, false)
waction("REL_"..mode, n, s, 1)
elseif p == "C" then -- blx gpr vs. blx label.
if match(q, "^([%w_]+):(r1?[0-9])$") or match(q, "^r(1?[0-9])$") then
op = op + parse_gpr(q)
else
if op < 0xe0000000 then werror("unconditional instruction") end
local mode, n, s = parse_label(q, false)
waction("REL_"..mode, n, s, 1)
op = 0xfa000000
end
elseif p == "F" then
vr = "s"
elseif p == "G" then
vr = "d"
elseif p == "o" then
local r, wb = match(q, "^([^!]*)(!?)$")
op = op + shl(parse_gpr(r), 16) + (wb == "!" and 0x00200000 or 0)
n = n + 1
elseif p == "R" then
op = op + parse_reglist(q); n = n + 1
elseif p == "r" then
op = op + parse_vrlist(q); n = n + 1
elseif p == "W" then
op = op + parse_imm16(q); n = n + 1
elseif p == "v" then
op = op + parse_imm(q, 5, 7, 0, false); n = n + 1
elseif p == "w" then
local imm = match(q, "^#(.*)$")
if imm then
op = op + parse_imm(q, 5, 7, 0, false); n = n + 1
else
op = op + shl(parse_gpr(q), 8) + 16
end
elseif p == "X" then
op = op + parse_imm(q, 5, 16, 0, false); n = n + 1
elseif p == "Y" then
local imm = tonumber(match(q, "^#(.*)$")); n = n + 1
if not imm or shr(imm, 8) ~= 0 then
werror("bad immediate operand")
end
op = op + shl(band(imm, 0xf0), 12) + band(imm, 0x0f)
elseif p == "K" then
local imm = tonumber(match(q, "^#(.*)$")); n = n + 1
if not imm or shr(imm, 16) ~= 0 then
werror("bad immediate operand")
end
op = op + shl(band(imm, 0xfff0), 4) + band(imm, 0x000f)
elseif p == "T" then
op = op + parse_imm(q, 24, 0, 0, false); n = n + 1
elseif p == "s" then
-- Ignored.
else
assert(false)
end
end
wputpos(pos, op)
end
map_op[".template__"] = function(params, template, nparams)
if not params then return template:gsub("%x%x%x%x%x%x%x%x", "") end
-- Limit number of section buffer positions used by a single dasm_put().
-- A single opcode needs a maximum of 3 positions.
if secpos+3 > maxsecpos then wflush() end
local pos = wpos()
local lpos, apos, spos = #actlist, #actargs, secpos
local ok, err
for t in gmatch(template, "[^|]+") do
ok, err = pcall(parse_template, params, t, nparams, pos)
if ok then return end
secpos = spos
actlist[lpos+1] = nil
actlist[lpos+2] = nil
actlist[lpos+3] = nil
actargs[apos+1] = nil
actargs[apos+2] = nil
actargs[apos+3] = nil
end
error(err, 0)
end
------------------------------------------------------------------------------
-- Pseudo-opcode to mark the position where the action list is to be emitted.
map_op[".actionlist_1"] = function(params)
if not params then return "cvar" end
local name = params[1] -- No syntax check. You get to keep the pieces.
wline(function(out) writeactions(out, name) end)
end
-- Pseudo-opcode to mark the position where the global enum is to be emitted.
map_op[".globals_1"] = function(params)
if not params then return "prefix" end
local prefix = params[1] -- No syntax check. You get to keep the pieces.
wline(function(out) writeglobals(out, prefix) end)
end
-- Pseudo-opcode to mark the position where the global names are to be emitted.
map_op[".globalnames_1"] = function(params)
if not params then return "cvar" end
local name = params[1] -- No syntax check. You get to keep the pieces.
wline(function(out) writeglobalnames(out, name) end)
end
-- Pseudo-opcode to mark the position where the extern names are to be emitted.
map_op[".externnames_1"] = function(params)
if not params then return "cvar" end
local name = params[1] -- No syntax check. You get to keep the pieces.
wline(function(out) writeexternnames(out, name) end)
end
------------------------------------------------------------------------------
-- Label pseudo-opcode (converted from trailing colon form).
map_op[".label_1"] = function(params)
if not params then return "[1-9] | ->global | =>pcexpr" end
if secpos+1 > maxsecpos then wflush() end
local mode, n, s = parse_label(params[1], true)
if mode == "EXT" then werror("bad label definition") end
waction("LABEL_"..mode, n, s, 1)
end
------------------------------------------------------------------------------
-- Pseudo-opcodes for data storage.
map_op[".long_*"] = function(params)
if not params then return "imm..." end
for _,p in ipairs(params) do
local n = tonumber(p)
if not n then werror("bad immediate `"..p.."'") end
if n < 0 then n = n + 2^32 end
wputw(n)
if secpos+2 > maxsecpos then wflush() end
end
end
-- Alignment pseudo-opcode.
map_op[".align_1"] = function(params)
if not params then return "numpow2" end
if secpos+1 > maxsecpos then wflush() end
local align = tonumber(params[1])
if align then
local x = align
-- Must be a power of 2 in the range (2 ... 256).
for i=1,8 do
x = x / 2
if x == 1 then
waction("ALIGN", align-1, nil, 1) -- Action byte is 2**n-1.
return
end
end
end
werror("bad alignment")
end
------------------------------------------------------------------------------
-- Pseudo-opcode for (primitive) type definitions (map to C types).
map_op[".type_3"] = function(params, nparams)
if not params then
return nparams == 2 and "name, ctype" or "name, ctype, reg"
end
local name, ctype, reg = params[1], params[2], params[3]
if not match(name, "^[%a_][%w_]*$") then
werror("bad type name `"..name.."'")
end
local tp = map_type[name]
if tp then
werror("duplicate type `"..name.."'")
end
-- Add #type to defines. A bit unclean to put it in map_archdef.
map_archdef["#"..name] = "sizeof("..ctype..")"
-- Add new type and emit shortcut define.
local num = ctypenum + 1
map_type[name] = {
ctype = ctype,
ctypefmt = format("Dt%X(%%s)", num),
reg = reg,
}
wline(format("#define Dt%X(_V) (int)(ptrdiff_t)&(((%s *)0)_V)", num, ctype))
ctypenum = num
end
map_op[".type_2"] = map_op[".type_3"]
-- Dump type definitions.
local function dumptypes(out, lvl)
local t = {}
for name in pairs(map_type) do t[#t+1] = name end
sort(t)
out:write("Type definitions:\n")
for _,name in ipairs(t) do
local tp = map_type[name]
local reg = tp.reg or ""
out:write(format(" %-20s %-20s %s\n", name, tp.ctype, reg))
end
out:write("\n")
end
------------------------------------------------------------------------------
-- Set the current section.
function _M.section(num)
waction("SECTION", num)
wflush(true) -- SECTION is a terminal action.
end
------------------------------------------------------------------------------
-- Dump architecture description.
function _M.dumparch(out)
out:write(format("DynASM %s version %s, released %s\n\n",
_info.arch, _info.version, _info.release))
dumpactions(out)
end
-- Dump all user defined elements.
function _M.dumpdef(out, lvl)
dumptypes(out, lvl)
dumpglobals(out, lvl)
dumpexterns(out, lvl)
end
------------------------------------------------------------------------------
-- Pass callbacks from/to the DynASM core.
function _M.passcb(wl, we, wf, ww)
wline, werror, wfatal, wwarn = wl, we, wf, ww
return wflush
end
-- Setup the arch-specific module.
function _M.setup(arch, opt)
g_arch, g_opt = arch, opt
end
-- Merge the core maps and the arch-specific maps.
function _M.mergemaps(map_coreop, map_def)
setmetatable(map_op, { __index = function(t, k)
local v = map_coreop[k]
if v then return v end
local k1, cc, k2 = match(k, "^(.-)(..)([._].*)$")
local cv = map_cond[cc]
if cv then
local v = rawget(t, k1..k2)
if type(v) == "string" then
local scv = format("%x", cv)
return gsub(scv..sub(v, 2), "|e", "|"..scv)
end
end
end })
setmetatable(map_def, { __index = map_archdef })
return map_op, map_def
end
return _M
------------------------------------------------------------------------------
| apache-2.0 |
sdgdsffdsfff/redis-storage | deps/lua/dynasm/dynasm.lua | 15 | 30945 | ------------------------------------------------------------------------------
-- DynASM. A dynamic assembler for code generation engines.
-- Originally designed and implemented for LuaJIT.
--
-- Copyright (C) 2005-2012 Mike Pall. All rights reserved.
-- See below for full copyright notice.
------------------------------------------------------------------------------
-- Application information.
local _info = {
name = "DynASM",
description = "A dynamic assembler for code generation engines",
version = "1.3.0",
vernum = 10300,
release = "2011-05-05",
author = "Mike Pall",
url = "http://luajit.org/dynasm.html",
license = "MIT",
copyright = [[
Copyright (C) 2005-2012 Mike Pall. All rights reserved.
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.
[ MIT license: http://www.opensource.org/licenses/mit-license.php ]
]],
}
-- Cache library functions.
local type, pairs, ipairs = type, pairs, ipairs
local pcall, error, assert = pcall, error, assert
local _s = string
local sub, match, gmatch, gsub = _s.sub, _s.match, _s.gmatch, _s.gsub
local format, rep, upper = _s.format, _s.rep, _s.upper
local _t = table
local insert, remove, concat, sort = _t.insert, _t.remove, _t.concat, _t.sort
local exit = os.exit
local io = io
local stdin, stdout, stderr = io.stdin, io.stdout, io.stderr
------------------------------------------------------------------------------
-- Program options.
local g_opt = {}
-- Global state for current file.
local g_fname, g_curline, g_indent, g_lineno, g_synclineno, g_arch
local g_errcount = 0
-- Write buffer for output file.
local g_wbuffer, g_capbuffer
------------------------------------------------------------------------------
-- Write an output line (or callback function) to the buffer.
local function wline(line, needindent)
local buf = g_capbuffer or g_wbuffer
buf[#buf+1] = needindent and g_indent..line or line
g_synclineno = g_synclineno + 1
end
-- Write assembler line as a comment, if requestd.
local function wcomment(aline)
if g_opt.comment then
wline(g_opt.comment..aline..g_opt.endcomment, true)
end
end
-- Resync CPP line numbers.
local function wsync()
if g_synclineno ~= g_lineno and g_opt.cpp then
wline("# "..g_lineno..' "'..g_fname..'"')
g_synclineno = g_lineno
end
end
-- Dummy action flush function. Replaced with arch-specific function later.
local function wflush(term)
end
-- Dump all buffered output lines.
local function wdumplines(out, buf)
for _,line in ipairs(buf) do
if type(line) == "string" then
assert(out:write(line, "\n"))
else
-- Special callback to dynamically insert lines after end of processing.
line(out)
end
end
end
------------------------------------------------------------------------------
-- Emit an error. Processing continues with next statement.
local function werror(msg)
error(format("%s:%s: error: %s:\n%s", g_fname, g_lineno, msg, g_curline), 0)
end
-- Emit a fatal error. Processing stops.
local function wfatal(msg)
g_errcount = "fatal"
werror(msg)
end
-- Print a warning. Processing continues.
local function wwarn(msg)
stderr:write(format("%s:%s: warning: %s:\n%s\n",
g_fname, g_lineno, msg, g_curline))
end
-- Print caught error message. But suppress excessive errors.
local function wprinterr(...)
if type(g_errcount) == "number" then
-- Regular error.
g_errcount = g_errcount + 1
if g_errcount < 21 then -- Seems to be a reasonable limit.
stderr:write(...)
elseif g_errcount == 21 then
stderr:write(g_fname,
":*: warning: too many errors (suppressed further messages).\n")
end
else
-- Fatal error.
stderr:write(...)
return true -- Stop processing.
end
end
------------------------------------------------------------------------------
-- Map holding all option handlers.
local opt_map = {}
local opt_current
-- Print error and exit with error status.
local function opterror(...)
stderr:write("dynasm.lua: ERROR: ", ...)
stderr:write("\n")
exit(1)
end
-- Get option parameter.
local function optparam(args)
local argn = args.argn
local p = args[argn]
if not p then
opterror("missing parameter for option `", opt_current, "'.")
end
args.argn = argn + 1
return p
end
------------------------------------------------------------------------------
-- Core pseudo-opcodes.
local map_coreop = {}
-- Dummy opcode map. Replaced by arch-specific map.
local map_op = {}
-- Forward declarations.
local dostmt
local readfile
------------------------------------------------------------------------------
-- Map for defines (initially empty, chains to arch-specific map).
local map_def = {}
-- Pseudo-opcode to define a substitution.
map_coreop[".define_2"] = function(params, nparams)
if not params then return nparams == 1 and "name" or "name, subst" end
local name, def = params[1], params[2] or "1"
if not match(name, "^[%a_][%w_]*$") then werror("bad or duplicate define") end
map_def[name] = def
end
map_coreop[".define_1"] = map_coreop[".define_2"]
-- Define a substitution on the command line.
function opt_map.D(args)
local namesubst = optparam(args)
local name, subst = match(namesubst, "^([%a_][%w_]*)=(.*)$")
if name then
map_def[name] = subst
elseif match(namesubst, "^[%a_][%w_]*$") then
map_def[namesubst] = "1"
else
opterror("bad define")
end
end
-- Undefine a substitution on the command line.
function opt_map.U(args)
local name = optparam(args)
if match(name, "^[%a_][%w_]*$") then
map_def[name] = nil
else
opterror("bad define")
end
end
-- Helper for definesubst.
local gotsubst
local function definesubst_one(word)
local subst = map_def[word]
if subst then gotsubst = word; return subst else return word end
end
-- Iteratively substitute defines.
local function definesubst(stmt)
-- Limit number of iterations.
for i=1,100 do
gotsubst = false
stmt = gsub(stmt, "#?[%w_]+", definesubst_one)
if not gotsubst then break end
end
if gotsubst then wfatal("recursive define involving `"..gotsubst.."'") end
return stmt
end
-- Dump all defines.
local function dumpdefines(out, lvl)
local t = {}
for name in pairs(map_def) do
t[#t+1] = name
end
sort(t)
out:write("Defines:\n")
for _,name in ipairs(t) do
local subst = map_def[name]
if g_arch then subst = g_arch.revdef(subst) end
out:write(format(" %-20s %s\n", name, subst))
end
out:write("\n")
end
------------------------------------------------------------------------------
-- Support variables for conditional assembly.
local condlevel = 0
local condstack = {}
-- Evaluate condition with a Lua expression. Substitutions already performed.
local function cond_eval(cond)
local func, err
if setfenv then
func, err = loadstring("return "..cond, "=expr")
else
-- No globals. All unknown identifiers evaluate to nil.
func, err = load("return "..cond, "=expr", "t", {})
end
if func then
if setfenv then
setfenv(func, {}) -- No globals. All unknown identifiers evaluate to nil.
end
local ok, res = pcall(func)
if ok then
if res == 0 then return false end -- Oh well.
return not not res
end
err = res
end
wfatal("bad condition: "..err)
end
-- Skip statements until next conditional pseudo-opcode at the same level.
local function stmtskip()
local dostmt_save = dostmt
local lvl = 0
dostmt = function(stmt)
local op = match(stmt, "^%s*(%S+)")
if op == ".if" then
lvl = lvl + 1
elseif lvl ~= 0 then
if op == ".endif" then lvl = lvl - 1 end
elseif op == ".elif" or op == ".else" or op == ".endif" then
dostmt = dostmt_save
dostmt(stmt)
end
end
end
-- Pseudo-opcodes for conditional assembly.
map_coreop[".if_1"] = function(params)
if not params then return "condition" end
local lvl = condlevel + 1
local res = cond_eval(params[1])
condlevel = lvl
condstack[lvl] = res
if not res then stmtskip() end
end
map_coreop[".elif_1"] = function(params)
if not params then return "condition" end
if condlevel == 0 then wfatal(".elif without .if") end
local lvl = condlevel
local res = condstack[lvl]
if res then
if res == "else" then wfatal(".elif after .else") end
else
res = cond_eval(params[1])
if res then
condstack[lvl] = res
return
end
end
stmtskip()
end
map_coreop[".else_0"] = function(params)
if condlevel == 0 then wfatal(".else without .if") end
local lvl = condlevel
local res = condstack[lvl]
condstack[lvl] = "else"
if res then
if res == "else" then wfatal(".else after .else") end
stmtskip()
end
end
map_coreop[".endif_0"] = function(params)
local lvl = condlevel
if lvl == 0 then wfatal(".endif without .if") end
condlevel = lvl - 1
end
-- Check for unfinished conditionals.
local function checkconds()
if g_errcount ~= "fatal" and condlevel ~= 0 then
wprinterr(g_fname, ":*: error: unbalanced conditional\n")
end
end
------------------------------------------------------------------------------
-- Search for a file in the given path and open it for reading.
local function pathopen(path, name)
local dirsep = package and match(package.path, "\\") and "\\" or "/"
for _,p in ipairs(path) do
local fullname = p == "" and name or p..dirsep..name
local fin = io.open(fullname, "r")
if fin then
g_fname = fullname
return fin
end
end
end
-- Include a file.
map_coreop[".include_1"] = function(params)
if not params then return "filename" end
local name = params[1]
-- Save state. Ugly, I know. but upvalues are fast.
local gf, gl, gcl, gi = g_fname, g_lineno, g_curline, g_indent
-- Read the included file.
local fatal = readfile(pathopen(g_opt.include, name) or
wfatal("include file `"..name.."' not found"))
-- Restore state.
g_synclineno = -1
g_fname, g_lineno, g_curline, g_indent = gf, gl, gcl, gi
if fatal then wfatal("in include file") end
end
-- Make .include and conditionals initially available, too.
map_op[".include_1"] = map_coreop[".include_1"]
map_op[".if_1"] = map_coreop[".if_1"]
map_op[".elif_1"] = map_coreop[".elif_1"]
map_op[".else_0"] = map_coreop[".else_0"]
map_op[".endif_0"] = map_coreop[".endif_0"]
------------------------------------------------------------------------------
-- Support variables for macros.
local mac_capture, mac_lineno, mac_name
local mac_active = {}
local mac_list = {}
-- Pseudo-opcode to define a macro.
map_coreop[".macro_*"] = function(mparams)
if not mparams then return "name [, params...]" end
-- Split off and validate macro name.
local name = remove(mparams, 1)
if not name then werror("missing macro name") end
if not (match(name, "^[%a_][%w_%.]*$") or match(name, "^%.[%w_%.]*$")) then
wfatal("bad macro name `"..name.."'")
end
-- Validate macro parameter names.
local mdup = {}
for _,mp in ipairs(mparams) do
if not match(mp, "^[%a_][%w_]*$") then
wfatal("bad macro parameter name `"..mp.."'")
end
if mdup[mp] then wfatal("duplicate macro parameter name `"..mp.."'") end
mdup[mp] = true
end
-- Check for duplicate or recursive macro definitions.
local opname = name.."_"..#mparams
if map_op[opname] or map_op[name.."_*"] then
wfatal("duplicate macro `"..name.."' ("..#mparams.." parameters)")
end
if mac_capture then wfatal("recursive macro definition") end
-- Enable statement capture.
local lines = {}
mac_lineno = g_lineno
mac_name = name
mac_capture = function(stmt) -- Statement capture function.
-- Stop macro definition with .endmacro pseudo-opcode.
if not match(stmt, "^%s*.endmacro%s*$") then
lines[#lines+1] = stmt
return
end
mac_capture = nil
mac_lineno = nil
mac_name = nil
mac_list[#mac_list+1] = opname
-- Add macro-op definition.
map_op[opname] = function(params)
if not params then return mparams, lines end
-- Protect against recursive macro invocation.
if mac_active[opname] then wfatal("recursive macro invocation") end
mac_active[opname] = true
-- Setup substitution map.
local subst = {}
for i,mp in ipairs(mparams) do subst[mp] = params[i] end
local mcom
if g_opt.maccomment and g_opt.comment then
mcom = " MACRO "..name.." ("..#mparams..")"
wcomment("{"..mcom)
end
-- Loop through all captured statements
for _,stmt in ipairs(lines) do
-- Substitute macro parameters.
local st = gsub(stmt, "[%w_]+", subst)
st = definesubst(st)
st = gsub(st, "%s*%.%.%s*", "") -- Token paste a..b.
if mcom and sub(st, 1, 1) ~= "|" then wcomment(st) end
-- Emit statement. Use a protected call for better diagnostics.
local ok, err = pcall(dostmt, st)
if not ok then
-- Add the captured statement to the error.
wprinterr(err, "\n", g_indent, "| ", stmt,
"\t[MACRO ", name, " (", #mparams, ")]\n")
end
end
if mcom then wcomment("}"..mcom) end
mac_active[opname] = nil
end
end
end
-- An .endmacro pseudo-opcode outside of a macro definition is an error.
map_coreop[".endmacro_0"] = function(params)
wfatal(".endmacro without .macro")
end
-- Dump all macros and their contents (with -PP only).
local function dumpmacros(out, lvl)
sort(mac_list)
out:write("Macros:\n")
for _,opname in ipairs(mac_list) do
local name = sub(opname, 1, -3)
local params, lines = map_op[opname]()
out:write(format(" %-20s %s\n", name, concat(params, ", ")))
if lvl > 1 then
for _,line in ipairs(lines) do
out:write(" |", line, "\n")
end
out:write("\n")
end
end
out:write("\n")
end
-- Check for unfinished macro definitions.
local function checkmacros()
if mac_capture then
wprinterr(g_fname, ":", mac_lineno,
": error: unfinished .macro `", mac_name ,"'\n")
end
end
------------------------------------------------------------------------------
-- Support variables for captures.
local cap_lineno, cap_name
local cap_buffers = {}
local cap_used = {}
-- Start a capture.
map_coreop[".capture_1"] = function(params)
if not params then return "name" end
wflush()
local name = params[1]
if not match(name, "^[%a_][%w_]*$") then
wfatal("bad capture name `"..name.."'")
end
if cap_name then
wfatal("already capturing to `"..cap_name.."' since line "..cap_lineno)
end
cap_name = name
cap_lineno = g_lineno
-- Create or continue a capture buffer and start the output line capture.
local buf = cap_buffers[name]
if not buf then buf = {}; cap_buffers[name] = buf end
g_capbuffer = buf
g_synclineno = 0
end
-- Stop a capture.
map_coreop[".endcapture_0"] = function(params)
wflush()
if not cap_name then wfatal(".endcapture without a valid .capture") end
cap_name = nil
cap_lineno = nil
g_capbuffer = nil
g_synclineno = 0
end
-- Dump a capture buffer.
map_coreop[".dumpcapture_1"] = function(params)
if not params then return "name" end
wflush()
local name = params[1]
if not match(name, "^[%a_][%w_]*$") then
wfatal("bad capture name `"..name.."'")
end
cap_used[name] = true
wline(function(out)
local buf = cap_buffers[name]
if buf then wdumplines(out, buf) end
end)
g_synclineno = 0
end
-- Dump all captures and their buffers (with -PP only).
local function dumpcaptures(out, lvl)
out:write("Captures:\n")
for name,buf in pairs(cap_buffers) do
out:write(format(" %-20s %4s)\n", name, "("..#buf))
if lvl > 1 then
local bar = rep("=", 76)
out:write(" ", bar, "\n")
for _,line in ipairs(buf) do
out:write(" ", line, "\n")
end
out:write(" ", bar, "\n\n")
end
end
out:write("\n")
end
-- Check for unfinished or unused captures.
local function checkcaptures()
if cap_name then
wprinterr(g_fname, ":", cap_lineno,
": error: unfinished .capture `", cap_name,"'\n")
return
end
for name in pairs(cap_buffers) do
if not cap_used[name] then
wprinterr(g_fname, ":*: error: missing .dumpcapture ", name ,"\n")
end
end
end
------------------------------------------------------------------------------
-- Sections names.
local map_sections = {}
-- Pseudo-opcode to define code sections.
-- TODO: Data sections, BSS sections. Needs extra C code and API.
map_coreop[".section_*"] = function(params)
if not params then return "name..." end
if #map_sections > 0 then werror("duplicate section definition") end
wflush()
for sn,name in ipairs(params) do
local opname = "."..name.."_0"
if not match(name, "^[%a][%w_]*$") or
map_op[opname] or map_op["."..name.."_*"] then
werror("bad section name `"..name.."'")
end
map_sections[#map_sections+1] = name
wline(format("#define DASM_SECTION_%s\t%d", upper(name), sn-1))
map_op[opname] = function(params) g_arch.section(sn-1) end
end
wline(format("#define DASM_MAXSECTION\t\t%d", #map_sections))
end
-- Dump all sections.
local function dumpsections(out, lvl)
out:write("Sections:\n")
for _,name in ipairs(map_sections) do
out:write(format(" %s\n", name))
end
out:write("\n")
end
------------------------------------------------------------------------------
-- Replacement for customized Lua, which lacks the package library.
local prefix = ""
if not require then
function require(name)
local fp = assert(io.open(prefix..name..".lua"))
local s = fp:read("*a")
assert(fp:close())
return assert(loadstring(s, "@"..name..".lua"))()
end
end
-- Load architecture-specific module.
local function loadarch(arch)
if not match(arch, "^[%w_]+$") then return "bad arch name" end
local ok, m_arch = pcall(require, "dasm_"..arch)
if not ok then return "cannot load module: "..m_arch end
g_arch = m_arch
wflush = m_arch.passcb(wline, werror, wfatal, wwarn)
m_arch.setup(arch, g_opt)
map_op, map_def = m_arch.mergemaps(map_coreop, map_def)
end
-- Dump architecture description.
function opt_map.dumparch(args)
local name = optparam(args)
if not g_arch then
local err = loadarch(name)
if err then opterror(err) end
end
local t = {}
for name in pairs(map_coreop) do t[#t+1] = name end
for name in pairs(map_op) do t[#t+1] = name end
sort(t)
local out = stdout
local _arch = g_arch._info
out:write(format("%s version %s, released %s, %s\n",
_info.name, _info.version, _info.release, _info.url))
g_arch.dumparch(out)
local pseudo = true
out:write("Pseudo-Opcodes:\n")
for _,sname in ipairs(t) do
local name, nparam = match(sname, "^(.+)_([0-9%*])$")
if name then
if pseudo and sub(name, 1, 1) ~= "." then
out:write("\nOpcodes:\n")
pseudo = false
end
local f = map_op[sname]
local s
if nparam ~= "*" then nparam = nparam + 0 end
if nparam == 0 then
s = ""
elseif type(f) == "string" then
s = map_op[".template__"](nil, f, nparam)
else
s = f(nil, nparam)
end
if type(s) == "table" then
for _,s2 in ipairs(s) do
out:write(format(" %-12s %s\n", name, s2))
end
else
out:write(format(" %-12s %s\n", name, s))
end
end
end
out:write("\n")
exit(0)
end
-- Pseudo-opcode to set the architecture.
-- Only initially available (map_op is replaced when called).
map_op[".arch_1"] = function(params)
if not params then return "name" end
local err = loadarch(params[1])
if err then wfatal(err) end
end
-- Dummy .arch pseudo-opcode to improve the error report.
map_coreop[".arch_1"] = function(params)
if not params then return "name" end
wfatal("duplicate .arch statement")
end
------------------------------------------------------------------------------
-- Dummy pseudo-opcode. Don't confuse '.nop' with 'nop'.
map_coreop[".nop_*"] = function(params)
if not params then return "[ignored...]" end
end
-- Pseudo-opcodes to raise errors.
map_coreop[".error_1"] = function(params)
if not params then return "message" end
werror(params[1])
end
map_coreop[".fatal_1"] = function(params)
if not params then return "message" end
wfatal(params[1])
end
-- Dump all user defined elements.
local function dumpdef(out)
local lvl = g_opt.dumpdef
if lvl == 0 then return end
dumpsections(out, lvl)
dumpdefines(out, lvl)
if g_arch then g_arch.dumpdef(out, lvl) end
dumpmacros(out, lvl)
dumpcaptures(out, lvl)
end
------------------------------------------------------------------------------
-- Helper for splitstmt.
local splitlvl
local function splitstmt_one(c)
if c == "(" then
splitlvl = ")"..splitlvl
elseif c == "[" then
splitlvl = "]"..splitlvl
elseif c == "{" then
splitlvl = "}"..splitlvl
elseif c == ")" or c == "]" or c == "}" then
if sub(splitlvl, 1, 1) ~= c then werror("unbalanced (), [] or {}") end
splitlvl = sub(splitlvl, 2)
elseif splitlvl == "" then
return " \0 "
end
return c
end
-- Split statement into (pseudo-)opcode and params.
local function splitstmt(stmt)
-- Convert label with trailing-colon into .label statement.
local label = match(stmt, "^%s*(.+):%s*$")
if label then return ".label", {label} end
-- Split at commas and equal signs, but obey parentheses and brackets.
splitlvl = ""
stmt = gsub(stmt, "[,%(%)%[%]{}]", splitstmt_one)
if splitlvl ~= "" then werror("unbalanced () or []") end
-- Split off opcode.
local op, other = match(stmt, "^%s*([^%s%z]+)%s*(.*)$")
if not op then werror("bad statement syntax") end
-- Split parameters.
local params = {}
for p in gmatch(other, "%s*(%Z+)%z?") do
params[#params+1] = gsub(p, "%s+$", "")
end
if #params > 16 then werror("too many parameters") end
params.op = op
return op, params
end
-- Process a single statement.
dostmt = function(stmt)
-- Ignore empty statements.
if match(stmt, "^%s*$") then return end
-- Capture macro defs before substitution.
if mac_capture then return mac_capture(stmt) end
stmt = definesubst(stmt)
-- Emit C code without parsing the line.
if sub(stmt, 1, 1) == "|" then
local tail = sub(stmt, 2)
wflush()
if sub(tail, 1, 2) == "//" then wcomment(tail) else wline(tail, true) end
return
end
-- Split into (pseudo-)opcode and params.
local op, params = splitstmt(stmt)
-- Get opcode handler (matching # of parameters or generic handler).
local f = map_op[op.."_"..#params] or map_op[op.."_*"]
if not f then
if not g_arch then wfatal("first statement must be .arch") end
-- Improve error report.
for i=0,9 do
if map_op[op.."_"..i] then
werror("wrong number of parameters for `"..op.."'")
end
end
werror("unknown statement `"..op.."'")
end
-- Call opcode handler or special handler for template strings.
if type(f) == "string" then
map_op[".template__"](params, f)
else
f(params)
end
end
-- Process a single line.
local function doline(line)
if g_opt.flushline then wflush() end
-- Assembler line?
local indent, aline = match(line, "^(%s*)%|(.*)$")
if not aline then
-- No, plain C code line, need to flush first.
wflush()
wsync()
wline(line, false)
return
end
g_indent = indent -- Remember current line indentation.
-- Emit C code (even from macros). Avoids echo and line parsing.
if sub(aline, 1, 1) == "|" then
if not mac_capture then
wsync()
elseif g_opt.comment then
wsync()
wcomment(aline)
end
dostmt(aline)
return
end
-- Echo assembler line as a comment.
if g_opt.comment then
wsync()
wcomment(aline)
end
-- Strip assembler comments.
aline = gsub(aline, "//.*$", "")
-- Split line into statements at semicolons.
if match(aline, ";") then
for stmt in gmatch(aline, "[^;]+") do dostmt(stmt) end
else
dostmt(aline)
end
end
------------------------------------------------------------------------------
-- Write DynASM header.
local function dasmhead(out)
out:write(format([[
/*
** This file has been pre-processed with DynASM.
** %s
** DynASM version %s, DynASM %s version %s
** DO NOT EDIT! The original file is in "%s".
*/
#if DASM_VERSION != %d
#error "Version mismatch between DynASM and included encoding engine"
#endif
]], _info.url,
_info.version, g_arch._info.arch, g_arch._info.version,
g_fname, _info.vernum))
end
-- Read input file.
readfile = function(fin)
g_indent = ""
g_lineno = 0
g_synclineno = -1
-- Process all lines.
for line in fin:lines() do
g_lineno = g_lineno + 1
g_curline = line
local ok, err = pcall(doline, line)
if not ok and wprinterr(err, "\n") then return true end
end
wflush()
-- Close input file.
assert(fin == stdin or fin:close())
end
-- Write output file.
local function writefile(outfile)
local fout
-- Open output file.
if outfile == nil or outfile == "-" then
fout = stdout
else
fout = assert(io.open(outfile, "w"))
end
-- Write all buffered lines
wdumplines(fout, g_wbuffer)
-- Close output file.
assert(fout == stdout or fout:close())
-- Optionally dump definitions.
dumpdef(fout == stdout and stderr or stdout)
end
-- Translate an input file to an output file.
local function translate(infile, outfile)
g_wbuffer = {}
g_indent = ""
g_lineno = 0
g_synclineno = -1
-- Put header.
wline(dasmhead)
-- Read input file.
local fin
if infile == "-" then
g_fname = "(stdin)"
fin = stdin
else
g_fname = infile
fin = assert(io.open(infile, "r"))
end
readfile(fin)
-- Check for errors.
if not g_arch then
wprinterr(g_fname, ":*: error: missing .arch directive\n")
end
checkconds()
checkmacros()
checkcaptures()
if g_errcount ~= 0 then
stderr:write(g_fname, ":*: info: ", g_errcount, " error",
(type(g_errcount) == "number" and g_errcount > 1) and "s" or "",
" in input file -- no output file generated.\n")
dumpdef(stderr)
exit(1)
end
-- Write output file.
writefile(outfile)
end
------------------------------------------------------------------------------
-- Print help text.
function opt_map.help()
stdout:write("DynASM -- ", _info.description, ".\n")
stdout:write("DynASM ", _info.version, " ", _info.release, " ", _info.url, "\n")
stdout:write[[
Usage: dynasm [OPTION]... INFILE.dasc|-
-h, --help Display this help text.
-V, --version Display version and copyright information.
-o, --outfile FILE Output file name (default is stdout).
-I, --include DIR Add directory to the include search path.
-c, --ccomment Use /* */ comments for assembler lines.
-C, --cppcomment Use // comments for assembler lines (default).
-N, --nocomment Suppress assembler lines in output.
-M, --maccomment Show macro expansions as comments (default off).
-L, --nolineno Suppress CPP line number information in output.
-F, --flushline Flush action list for every line.
-D NAME[=SUBST] Define a substitution.
-U NAME Undefine a substitution.
-P, --dumpdef Dump defines, macros, etc. Repeat for more output.
-A, --dumparch ARCH Load architecture ARCH and dump description.
]]
exit(0)
end
-- Print version information.
function opt_map.version()
stdout:write(format("%s version %s, released %s\n%s\n\n%s",
_info.name, _info.version, _info.release, _info.url, _info.copyright))
exit(0)
end
-- Misc. options.
function opt_map.outfile(args) g_opt.outfile = optparam(args) end
function opt_map.include(args) insert(g_opt.include, 1, optparam(args)) end
function opt_map.ccomment() g_opt.comment = "/*|"; g_opt.endcomment = " */" end
function opt_map.cppcomment() g_opt.comment = "//|"; g_opt.endcomment = "" end
function opt_map.nocomment() g_opt.comment = false end
function opt_map.maccomment() g_opt.maccomment = true end
function opt_map.nolineno() g_opt.cpp = false end
function opt_map.flushline() g_opt.flushline = true end
function opt_map.dumpdef() g_opt.dumpdef = g_opt.dumpdef + 1 end
------------------------------------------------------------------------------
-- Short aliases for long options.
local opt_alias = {
h = "help", ["?"] = "help", V = "version",
o = "outfile", I = "include",
c = "ccomment", C = "cppcomment", N = "nocomment", M = "maccomment",
L = "nolineno", F = "flushline",
P = "dumpdef", A = "dumparch",
}
-- Parse single option.
local function parseopt(opt, args)
opt_current = #opt == 1 and "-"..opt or "--"..opt
local f = opt_map[opt] or opt_map[opt_alias[opt]]
if not f then
opterror("unrecognized option `", opt_current, "'. Try `--help'.\n")
end
f(args)
end
-- Parse arguments.
local function parseargs(args)
-- Default options.
g_opt.comment = "//|"
g_opt.endcomment = ""
g_opt.cpp = true
g_opt.dumpdef = 0
g_opt.include = { "" }
-- Process all option arguments.
args.argn = 1
repeat
local a = args[args.argn]
if not a then break end
local lopt, opt = match(a, "^%-(%-?)(.+)")
if not opt then break end
args.argn = args.argn + 1
if lopt == "" then
-- Loop through short options.
for o in gmatch(opt, ".") do parseopt(o, args) end
else
-- Long option.
parseopt(opt, args)
end
until false
-- Check for proper number of arguments.
local nargs = #args - args.argn + 1
if nargs ~= 1 then
if nargs == 0 then
if g_opt.dumpdef > 0 then return dumpdef(stdout) end
end
opt_map.help()
end
-- Translate a single input file to a single output file
-- TODO: Handle multiple files?
translate(args[args.argn], g_opt.outfile)
end
------------------------------------------------------------------------------
-- Add the directory dynasm.lua resides in to the Lua module search path.
local arg = arg
if arg and arg[0] then
prefix = match(arg[0], "^(.*[/\\])")
if package and prefix then package.path = prefix.."?.lua;"..package.path end
end
-- Start DynASM.
parseargs{...}
------------------------------------------------------------------------------
| bsd-3-clause |
bitdewy/cegui | cegui/src/ScriptModules/Lua/support/tolua++bin/lua/function.lua | 14 | 20809 | -- tolua: function class
-- Written by Waldemar Celes
-- TeCGraf/PUC-Rio
-- Jul 1998
-- $Id$
-- This code is free software; you can redistribute it and/or modify it.
-- The software provided hereunder is on an "as is" basis, and
-- the author has no obligation to provide maintenance, support, updates,
-- enhancements, or modifications.
-- CEGUILua mod
-- exception handling
-- patch from Tov
-- modded by Lindquist
exceptionDefs = exceptionDefs or {}
exceptionDefs["std::exception"] = {}
exceptionDefs["std::exception"]["var"] = "&e"
exceptionDefs["std::exception"]["c_str"] = "e.what()"
exceptionDefs["any"] = {}
exceptionDefs["any"]["var"] = ""
exceptionDefs["any"]["c_str"] = '"Unknown"'
exceptionMessageBufferSize = 512
function outputExceptionError(f,e,errBuf)
-- if the exception is not "..." then use the "c_str" info the get a real exception message
local messageC_str = true
if e.name == "any" then
messageC_str = false
end
-- make a default e.ret if empty
if not e.ret or e.ret == "" then
e.ret = "nil,message"
end
-- create a default exceptionDef if we dont have one
if not exceptionDefs[e.name] then
exceptionDefs[e.name] = {}
exceptionDefs[e.name].var = "&e"
exceptionDefs[e.name].c_str = '"Unknown"'
end
-- print catch header
local nameToEcho = e.name
if nameToEcho == "any" then
nameToEcho = "..."
end
if e.ret == "nil" then
output("catch(",nameToEcho," CEGUIDeadException(",exceptionDefs[e.name].var,"))\n{\n")
else
output("catch(",nameToEcho,exceptionDefs[e.name].var,")\n{\n")
end
-- if just a nil
if e.ret == "nil" then
output("return 0;\n")
-- if error should be raised
elseif string.find(e.ret,"error") then
if messageC_str then
output("snprintf(errorBuffer,"..exceptionMessageBufferSize..",\"Exception of type '"..e.name.."' was thrown by function '"..f.."'\\nMessage: %s\","..exceptionDefs[e.name].c_str..");\n")
else
output("snprintf(errorBuffer,"..exceptionMessageBufferSize..",\"Unknown exception thrown by function '"..f.."'\");\n")
end
output("errorDoIt = true;\n")
-- else go through the returns
else
-- buffer for message
if string.find(e.ret,"message") and messageC_str and errBuf == false then
output("char errorBuffer["..exceptionMessageBufferSize.."];\n")
end
local numrets = 0
local retpat = "(%w+),?"
local i,j,retval = string.find(e.ret,retpat)
while i do
local code = ""
-- NIL
if retval == "nil" then
code = "tolua_pushnil(tolua_S);\n"
-- MESSAGE
elseif retval == "message" then
if messageC_str then
code = "snprintf(errorBuffer,"..exceptionMessageBufferSize..",\"Exception of type '"..e.name.."' was thrown by function '"..f.."'\\nMessage: %s\","..exceptionDefs[e.name].c_str..");\ntolua_pushstring(tolua_S,errorBuffer);\n"
else
code = "tolua_pushstring(tolua_S,\"Unknown exception thrown by function '"..f.."'\");\n"
end
-- TRUE
elseif retval == "true" then
code = "tolua_pushboolean(tolua_S, 1);\n"
-- FALSE
elseif retval == "false" then
code = "tolua_pushboolean(tolua_S, 0);\n"
end
-- print code for this return value
if code ~= "" then
output(code)
numrets = numrets + 1
end
-- next return value
i,j,retval = string.find(e.ret,retpat,j+1)
end
output("return ",numrets,";\n")
end
-- print catch footer
output("}\n")
end
function outputExceptionCatchBlocks(func,throws,err)
for i=1,table.getn(throws) do
outputExceptionError(func, throws[i], err)
end
-- if an error should be raised, we do it here
if err then
output("if (errorDoIt) {\n")
output("luaL_error(tolua_S,errorBuffer);\n")
output("}\n")
end
end
-- Function class
-- Represents a function or a class method.
-- The following fields are stored:
-- mod = type modifiers
-- type = type
-- ptr = "*" or "&", if representing a pointer or a reference
-- name = name
-- lname = lua name
-- args = list of argument declarations
-- const = if it is a method receiving a const "this".
classFunction = {
mod = '',
type = '',
ptr = '',
name = '',
args = {n=0},
const = '',
}
classFunction.__index = classFunction
setmetatable(classFunction,classFeature)
-- declare tags
function classFunction:decltype ()
self.type = typevar(self.type)
if strfind(self.mod,'const') then
self.type = 'const '..self.type
self.mod = gsub(self.mod,'const','')
end
local i=1
while self.args[i] do
self.args[i]:decltype()
i = i+1
end
end
-- Write binding function
-- Outputs C/C++ binding function.
function classFunction:supcode (local_constructor)
local overload = strsub(self.cname,-2,-1) - 1 -- indicate overloaded func
local nret = 0 -- number of returned values
local class = self:inclass()
local _,_,static = strfind(self.mod,'^%s*(static)')
if class then
if self.name == 'new' and self.parent.flags.pure_virtual then
-- no constructor for classes with pure virtual methods
return
end
if local_constructor then
output("/* method: new_local of class ",class," */")
else
output("/* method:",self.name," of class ",class," */")
end
else
output("/* function:",self.name," */")
end
if local_constructor then
output("#ifndef TOLUA_DISABLE_"..self.cname.."_local")
output("\nstatic int",self.cname.."_local","(lua_State* tolua_S)")
else
output("#ifndef TOLUA_DISABLE_"..self.cname)
output("\nstatic int",self.cname,"(lua_State* tolua_S)")
end
output("{")
-- check types
if overload < 0 then
output('#ifndef TOLUA_RELEASE\n')
end
output(' tolua_Error tolua_err;')
output(' if (\n')
-- check self
local narg
if class then narg=2 else narg=1 end
if class then
local func = 'tolua_isusertype'
local type = self.parent.type
if self.name=='new' or static~=nil then
func = 'tolua_isusertable'
type = self.parent.type
end
if self.const ~= '' then
type = "const "..type
end
output(' !'..func..'(tolua_S,1,"'..type..'",0,&tolua_err) ||\n')
end
-- check args
if self.args[1].type ~= 'void' then
local i=1
while self.args[i] do
local btype = isbasic(self.args[i].type)
if btype ~= 'value' and btype ~= 'state' then
output(' !'..self.args[i]:outchecktype(narg)..' ||\n')
end
if btype ~= 'state' then
narg = narg+1
end
i = i+1
end
end
-- check end of list
output(' !tolua_isnoobj(tolua_S,'..narg..',&tolua_err)\n )')
output(' goto tolua_lerror;')
output(' else\n')
if overload < 0 then
output('#endif\n')
end
output(' {')
-- declare self, if the case
local narg
if class then narg=2 else narg=1 end
if class and self.name~='new' and static==nil then
output(' ',self.const,self.parent.type,'*','self = ')
output('(',self.const,self.parent.type,'*) ')
output('tolua_tousertype(tolua_S,1,0);')
elseif static then
_,_,self.mod = strfind(self.mod,'^%s*static%s%s*(.*)')
end
-- declare parameters
if self.args[1].type ~= 'void' then
local i=1
while self.args[i] do
self.args[i]:declare(narg)
if isbasic(self.args[i].type) ~= "state" then
narg = narg+1
end
i = i+1
end
end
-- check self
if class and self.name~='new' and static==nil then
output('#ifndef TOLUA_RELEASE\n')
output(' if (!self) tolua_error(tolua_S,"invalid \'self\' in function \''..self.name..'\'",NULL);');
output('#endif\n')
end
-- get array element values
if class then narg=2 else narg=1 end
if self.args[1].type ~= 'void' then
local i=1
while self.args[i] do
self.args[i]:getarray(narg)
narg = narg+1
i = i+1
end
end
--------------------------------------------------
-- CEGUILua mod
-- init exception handling
local throws = false
do
local pattern = "tolua_throws|.*|"
local i,j = string.find(self.mod, pattern)
if i then
throws = {}
-- ensure table is empty. Used to be: table.setn(throws,0)
for x in pairs(throws) do
throws[x] = nil
end
local excepts = string.sub(self.mod, i+12,j)
local epattern = "|.-|"
local i,j = string.find(excepts, epattern)
while i do
local e = string.sub(excepts,i+1,j-1)
local _,_,name,rest = string.find(e, "([%w:_]+),?(.*)")
table.insert(throws,{name=name, ret=rest})
i,j = string.find(excepts, epattern, j)
end
self.mod = string.gsub(self.mod, pattern, "")
end
end
local exRaiseError = false
--------------------------------------------------
local out = string.find(self.mod, "tolua_outside")
---------------
-- CEGUILua mod
-- remove "tolua_outside" from self.mod
if out then
self.mod = string.gsub(self.mod, "tolua_outside", "")
end
-- call function
if class and self.name=='delete' then
output(' delete self;')
elseif class and self.name == 'operator&[]' then
if flags['1'] then -- for compatibility with tolua5 ?
output(' self->operator[](',self.args[1].name,'-1) = ',self.args[2].name,';')
else
output(' self->operator[](',self.args[1].name,') = ',self.args[2].name,';')
end
else
-- CEGUILua mod begin- throws
if throws then
for i=1,table.getn(throws) do
if string.find(throws[i].ret, "error") then
output("char errorBuffer["..exceptionMessageBufferSize.."];\n")
output("bool errorDoIt = false;\n")
exRaiseError = true
break
end
end
output("try\n")
end
-- CEGUILua mod end - throws
output(' {')
if self.type ~= '' and self.type ~= 'void' then
output(' ',self.mod,self.type,self.ptr,'tolua_ret = ')
output('(',self.mod,self.type,self.ptr,') ')
else
output(' ')
end
if class and self.name=='new' then
output('new',self.type,'(')
elseif class and static then
if out then
output(self.name,'(')
else
output(class..'::'..self.name,'(')
end
elseif class then
if out then
output(self.name,'(')
else
if self.cast_operator then
output('static_cast<',self.mod,self.type,self.ptr,'>(*self')
else
output('self->'..self.name,'(')
end
end
else
output(self.name,'(')
end
if out and not static then
output('self')
if self.args[1] and self.args[1].name ~= '' then
output(',')
end
end
-- write parameters
local i=1
while self.args[i] do
self.args[i]:passpar()
i = i+1
if self.args[i] then
output(',')
end
end
if class and self.name == 'operator[]' and flags['1'] then
output('-1);')
else
output(');')
end
-- return values
if self.type ~= '' and self.type ~= 'void' then
nret = nret + 1
local t,ct = isbasic(self.type)
if t then
if self.cast_operator and _basic_raw_push[t] then
output(' ',_basic_raw_push[t],'(tolua_S,(',ct,')tolua_ret);')
else
output(' tolua_push'..t..'(tolua_S,(',ct,')tolua_ret);')
end
else
t = self.type
new_t = string.gsub(t, "const%s+", "")
if self.ptr == '' then
output(' {')
output('#ifdef __cplusplus\n')
output(' void* tolua_obj = new',new_t,'(tolua_ret);')
output(' tolua_pushusertype_and_takeownership(tolua_S,tolua_obj,"',t,'");')
output('#else\n')
output(' void* tolua_obj = tolua_copy(tolua_S,(void*)&tolua_ret,sizeof(',t,'));')
output(' tolua_pushusertype_and_takeownership(tolua_S,tolua_obj,"',t,'");')
output('#endif\n')
output(' }')
elseif self.ptr == '&' then
output(' tolua_pushusertype(tolua_S,(void*)&tolua_ret,"',t,'");')
else
if local_constructor then
output(' tolua_pushusertype_and_takeownership(tolua_S,(void *)tolua_ret,"',t,'");')
else
output(' tolua_pushusertype(tolua_S,(void*)tolua_ret,"',t,'");')
end
end
end
end
local i=1
while self.args[i] do
nret = nret + self.args[i]:retvalue()
i = i+1
end
output(' }')
------------------------------------------
-- CEGUILua mod
-- finish exception handling
-- catch
if throws then
outputExceptionCatchBlocks(self.name, throws, exRaiseError)
end
------------------------------------------
-- set array element values
if class then narg=2 else narg=1 end
if self.args[1].type ~= 'void' then
local i=1
while self.args[i] do
self.args[i]:setarray(narg)
narg = narg+1
i = i+1
end
end
-- free dynamically allocated array
if self.args[1].type ~= 'void' then
local i=1
while self.args[i] do
self.args[i]:freearray()
i = i+1
end
end
end
output(' }')
output(' return '..nret..';')
-- call overloaded function or generate error
if overload < 0 then
output('#ifndef TOLUA_RELEASE\n')
output('tolua_lerror:\n')
output(' tolua_error(tolua_S,"#ferror in function \''..self.lname..'\'.",&tolua_err);')
output(' return 0;')
output('#endif\n')
else
local _local = ""
if local_constructor then
_local = "_local"
end
output('tolua_lerror:\n')
output(' return '..strsub(self.cname,1,-3)..format("%02d",overload).._local..'(tolua_S);')
end
output('}')
output('#endif //#ifndef TOLUA_DISABLE\n')
output('\n')
-- recursive call to write local constructor
if class and self.name=='new' and not local_constructor then
self:supcode(1)
end
end
-- register function
function classFunction:register (pre)
if not self:check_public_access() then
return
end
if self.name == 'new' and self.parent.flags.pure_virtual then
-- no constructor for classes with pure virtual methods
return
end
output(pre..'tolua_function(tolua_S,"'..self.lname..'",'..self.cname..');')
if self.name == 'new' then
output(pre..'tolua_function(tolua_S,"new_local",'..self.cname..'_local);')
output(pre..'tolua_function(tolua_S,".call",'..self.cname..'_local);')
--output(' tolua_set_call_event(tolua_S,'..self.cname..'_local, "'..self.parent.type..'");')
end
end
---
-- LuaDoc Patch
-- outputs an empty(without documentation) LuaDoc interface
-- by klapeto (http://cegui.org.uk/forum/viewtopic.php?f=7&t=6784)
function classFunction:output_luadoc()
if not self:check_public_access() then
return
end
if self.name == 'new' and self.parent.flags.pure_virtual then
-- no constructor for classes with pure virtual methods
return
end
output('---\n')
output('-- '..self.lname..'\n')
output('-- @function [parent=#'..cleanseType(self.parent.name)..'] '..self.lname..'\n')
output('-- @param self'..'\n')
local i=1
while self.args[i] do
local pType = cleanseType(self.args[i].type)
if (pType~=nil) then
output('-- @param #'..pType..' '..self.args[i].name..'\n')
end
i = i+1
end
local rType = cleanseType(self.type)
if (rType~=nil) then
output('-- @return #'..rType..'\n')
end
if self.name == 'new' then
output('\n---\n')
output('-- new_local \n')
output('-- @function [parent=#'..cleanseType(self.parent.name)..'] new_local\n')
output('-- @param self'..'\n')
local i=1
while self.args[i] do
local pType = cleanseType(self.args[i].type)
if (pType~=nil) then
output('-- @param #'..pType..' '..self.args[i].name..'\n')
end
i = i+1
end
output('-- @return #'..cleanseType(self.parent.name)..'\n')
output('\n')
output('---\n')
output('-- .call\n')
output('-- Construct on the Lua Memory.\n')
output('-- @callof #'..cleanseType(self.parent.name)..'\n')
output('-- @param self'..'\n')
output('-- @return #'..cleanseType(self.parent.name)..'\n')
end
output('\n')
end
-- Print method
function classFunction:print (ident,close)
print(ident.."Function{")
print(ident.." mod = '"..self.mod.."',")
print(ident.." type = '"..self.type.."',")
print(ident.." ptr = '"..self.ptr.."',")
print(ident.." name = '"..self.name.."',")
print(ident.." lname = '"..self.lname.."',")
print(ident.." const = '"..self.const.."',")
print(ident.." cname = '"..self.cname.."',")
print(ident.." lname = '"..self.lname.."',")
print(ident.." args = {")
local i=1
while self.args[i] do
self.args[i]:print(ident.." ",",")
i = i+1
end
print(ident.." }")
print(ident.."}"..close)
end
-- check if it returns an object by value
function classFunction:requirecollection (t)
local r = false
if self.type ~= '' and not isbasic(self.type) and self.ptr=='' then
local type = gsub(self.type,"%s*const%s+","")
t[type] = "tolua_collect_" .. clean_template(type)
r = true
end
local i=1
while self.args[i] do
r = self.args[i]:requirecollection(t) or r
i = i+1
end
return r
end
-- determine lua function name overload
function classFunction:overload ()
return self.parent:overload(self.lname)
end
function param_object(par) -- returns true if the parameter has an object as its default value
if not string.find(par, '=') then return false end -- it has no default value
local _,_,def = string.find(par, "=(.*)$")
if string.find(par, "|") then -- a list of flags
return true
end
if string.find(par, "%*") then -- it's a pointer with a default value
if string.find(par, '=%s*new') then -- it's a pointer with an instance as default parameter.. is that valid?
return true
end
return false -- default value is 'NULL' or something
end
if string.find(par, "[%(&]") then
return true
end -- default value is a constructor call (most likely for a const reference)
--if string.find(par, "&") then
-- if string.find(def, ":") or string.find(def, "^%s*new%s+") then
-- -- it's a reference with default to something like Class::member, or 'new Class'
-- return true
-- end
--end
return false -- ?
end
function strip_last_arg(all_args, last_arg) -- strips the default value from the last argument
local _,_,s_arg = string.find(last_arg, "^([^=]+)")
last_arg = string.gsub(last_arg, "([%%%(%)])", "%%%1");
all_args = string.gsub(all_args, "%s*,%s*"..last_arg.."%s*%)%s*$", ")")
return all_args, s_arg
end
-- Internal constructor
function _Function (t)
setmetatable(t,classFunction)
if t.const ~= 'const' and t.const ~= '' then
error("#invalid 'const' specification")
end
append(t)
if t:inclass() then
--print ('t.name is '..t.name..', parent.name is '..t.parent.name)
if string.gsub(t.name, "%b<>", "") == string.gsub(t.parent.original_name or t.parent.name, "%b<>", "") then
t.name = 'new'
t.lname = 'new'
t.parent._new = true
t.type = t.parent.name
t.ptr = '*'
elseif string.gsub(t.name, "%b<>", "") == '~'..string.gsub(t.parent.original_name or t.parent.name, "%b<>", "") then
t.name = 'delete'
t.lname = 'delete'
t.parent._delete = true
end
end
t.cname = t:cfuncname("tolua")..t:overload(t)
return t
end
-- Constructor
-- Expects three strings: one representing the function declaration,
-- another representing the argument list, and the third representing
-- the "const" or empty string.
function Function (d,a,c)
--local t = split(strsub(a,2,-2),',') -- eliminate braces
--local t = split_params(strsub(a,2,-2))
if not flags['W'] and string.find(a, "%.%.%.%s*%)") then
warning("Functions with variable arguments (`...') are not supported. Ignoring "..d..a..c)
return nil
end
local i=1
local l = {n=0}
a = string.gsub(a, "%s*([%(%)])%s*", "%1")
local t,strip,last = strip_pars(strsub(a,2,-2));
if strip then
--local ns = string.sub(strsub(a,1,-2), 1, -(string.len(last)+1))
local ns = join(t, ",", 1, last-1)
ns = "("..string.gsub(ns, "%s*,%s*$", "")..')'
--ns = strip_defaults(ns)
Function(d, ns, c)
for i=1,last do
t[i] = string.gsub(t[i], "=.*$", "")
end
end
while t[i] do
l.n = l.n+1
l[l.n] = Declaration(t[i],'var',true)
i = i+1
end
local f = Declaration(d,'func')
f.args = l
f.const = c
return _Function(f)
end
function join(t, sep, first, last)
first = first or 1
last = last or table.getn(t)
local lsep = ""
local ret = ""
local loop = false
for i = first,last do
ret = ret..lsep..t[i]
lsep = sep
loop = true
end
if not loop then
return ""
end
return ret
end
function strip_pars(s)
local t = split_c_tokens(s, ',')
local strip = false
local last
for i=t.n,1,-1 do
if not strip and param_object(t[i]) then
last = i
strip = true
end
--if strip then
-- t[i] = string.gsub(t[i], "=.*$", "")
--end
end
return t,strip,last
end
function strip_defaults(s)
s = string.gsub(s, "^%(", "")
s = string.gsub(s, "%)$", "")
local t = split_c_tokens(s, ",")
local sep, ret = "",""
for i=1,t.n do
t[i] = string.gsub(t[i], "=.*$", "")
ret = ret..sep..t[i]
sep = ","
end
return "("..ret..")"
end
| mit |
kaadmy/pixture | mods/welcome/init.lua | 1 | 2233 | --
-- Welcome mod
-- By Kaadmy, for Pixture
--
welcome = {}
welcome.rules = {
"Welcome!",
"",
"Rules:",
"1. No swearing.",
"2. No griefing.",
"3. No spamming."
}
function welcome.get_formspec(name)
if not minetest.settings:get_bool("welcome_enable") then
minetest.chat_send_player(name, "Welcoming is disabled")
return ""
end
local form = default.ui.get_page("default:notabs")
local rules = ""
for _, t in ipairs(welcome.rules) do
if rules ~= "" then rules = rules .. "," end
rules = rules .. minetest.formspec_escape(t)
end
form = form .. "textlist[0.25,0.75;7.75,6.75;rules;" .. rules .. "]"
if not minetest.check_player_privs(name, {interact = true}) then
form = form .. default.ui.button_exit(1.25, 7.75, 3, 1, "decline_rules", "Nope")
form = form .. default.ui.button_exit(4.25, 7.75, 3, 1, "accept_rules", "Okay")
else
form = form .. default.ui.button_exit(2.9, 7.75, 3, 1, "", "Okay")
end
return form
end
function welcome.show_rules(name)
local f = welcome.get_formspec(name)
if f ~= "" then
minetest.show_formspec(name, "welcome:welcome", f)
end
end
minetest.register_on_player_receive_fields(
function(player, form_name, fields)
local name = player:get_player_name()
local privs = minetest.get_player_privs(name)
if privs.interact or fields.rules then
return
end
if fields.accept_rules then
privs.interact = true
minetest.set_player_privs(name, privs)
minetest.chat_send_player(name, "You now have interact, follow the rules and have fun!")
else
minetest.chat_send_player(name, "If you want to interact, please read and accept the rules. Type /welcome to show rules.")
end
end)
minetest.register_chatcommand(
"welcome",
{
description = "Show rules",
func = function(name, param)
welcome.show_rules(name)
end
})
minetest.register_on_joinplayer(
function(player)
local name = player:get_player_name()
if not minetest.check_player_privs(name, {interact = true}) and minetest.settings:get_bool("welcome_enable") then
welcome.show_rules(name)
end
end)
default.log("mod:welcome", "loaded")
| lgpl-2.1 |
xdemolish/darkstar | scripts/zones/Port_Windurst/npcs/Chipmy-Popmy.lua | 17 | 1291 | -----------------------------------
-- Area: Port Windurst
-- NPC: Chipmy-Popmy
-- Working 100%
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/missions");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local currentday = tonumber(os.date("%j"));
if(player:getCurrentMission(COP) == DAWN and player:getVar("PromathiaStatus")==3 and player:getVar("Promathia_kill_day") ~= currentday and player:getVar("COP_3-taru_story")== 0 )then
player:startEvent(0x026B);
else
player:startEvent(0xca);
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 == 0x026B)then
player:setVar("COP_3-taru_story",1);
end
end;
| gpl-3.0 |
7khat/7khat | plugins/inpm.lua | 1114 | 3008 | do
local function pairsByKeys (t, f)
local a = {}
for n in pairs(t) do table.insert(a, n) end
table.sort(a, f)
local i = 0 -- iterator variable
local iter = function () -- iterator function
i = i + 1
if a[i] == nil then return nil
else return a[i], t[a[i]]
end
end
return iter
end
local function chat_list(msg)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] then
return 'No groups at the moment'
end
local message = 'List of Groups:\n*Use /join (ID) to join*\n\n '
for k,v in pairs(data[tostring(groups)]) do
local settings = data[tostring(v)]['settings']
for m,n in pairsByKeys(settings) do
if m == 'set_name' then
name = n
end
end
message = message .. '👥 '.. name .. ' (ID: ' .. v .. ')\n\n '
end
local file = io.open("./groups/lists/listed_groups.txt", "w")
file:write(message)
file:flush()
file:close()
return message
end
local function run(msg, matches)
if msg.to.type ~= 'chat' or is_sudo(msg) or is_admin(msg) and is_realm(msg) then
local data = load_data(_config.moderation.data)
if matches[1] == 'join' and data[tostring(matches[2])] then
if is_banned(msg.from.id, matches[2]) then
return 'You are banned.'
end
if is_gbanned(msg.from.id) then
return 'You are globally banned.'
end
if data[tostring(matches[2])]['settings']['lock_member'] == 'yes' and not is_owner2(msg.from.id, matches[2]) then
return 'Group is private.'
end
local chat_id = "chat#id"..matches[2]
local user_id = "user#id"..msg.from.id
chat_add_user(chat_id, user_id, ok_cb, false)
local group_name = data[tostring(matches[2])]['settings']['set_name']
return "Added you to chat:\n\n👥"..group_name.." (ID:"..matches[2]..")"
elseif matches[1] == 'join' and not data[tostring(matches[2])] then
return "Chat not found."
end
if matches[1] == 'chats'then
if is_admin(msg) and msg.to.type == 'chat' then
return chat_list(msg)
elseif msg.to.type ~= 'chat' then
return chat_list(msg)
end
end
if matches[1] == 'chatlist'then
if is_admin(msg) and msg.to.type == 'chat' then
send_document("chat#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false)
elseif msg.to.type ~= 'chat' then
send_document("user#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false)
end
end
end
end
return {
patterns = {
"^[/!](chats)$",
"^[/!](chatlist)$",
"^[/!](join) (.*)$",
"^[/!](kickme) (.*)$",
"^!!tgservice (chat_add_user)$"
},
run = run,
}
end
| gpl-2.0 |
midelic/DIY-Multiprotocol-TX-Module | Lua_scripts/Graupner HoTT.lua | 2 | 5771 | ---- #########################################################################
---- # #
---- # Copyright (C) OpenTX #
-----# #
---- # License GPLv2: http://www.gnu.org/licenses/gpl-2.0.html #
---- # #
---- # This program is free software; you can redistribute it and/or modify #
---- # it under the terms of the GNU General Public License version 2 as #
---- # published by the Free Software Foundation. #
---- # #
---- # 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. #
---- # #
---- #########################################################################
--###############################################################################
-- Multi buffer for HoTT description
-- To start operation:
-- Write "HoTT" at address 0..3
-- Write 0xFF at address 4 will request the buffer to be cleared
-- Write 0x0F at address 5
-- Read buffer from address 6 access the RX text for 168 bytes, 21 caracters
-- by 8 lines
-- Write at address 5 sends an order to the RX: 0xXF=start, 0xX7=prev page,
-- 0xXE=next page, 0xX9=enter, 0xXD=next or 0xXB=prev with X being the sensor
-- to request data from 8=RX only, 9=Vario, A=GPS, B=Cust, C=ESC, D=GAM, E=EAM
-- Write at address 4 the value 0xFF will request the buffer to be cleared
-- !! Before exiting the script must write 0 at address 0 for normal operation !!
--###############################################################################
HoTT_Sensor = 0
Timer_128 = 100
local function HoTT_Release()
multiBuffer( 0, 0 )
end
local function HoTT_Send(button)
multiBuffer( 5, 0x80+(HoTT_Sensor*16) + button)
end
local function HoTT_Sensor_Inc()
local detected_sensors=multiBuffer( 4 )
local a
if detected_sensors ~= 0xFF then
repeat
HoTT_Sensor=(HoTT_Sensor+1)%7 -- Switch to next sensor
if HoTT_Sensor ~= 0 then
a = math.floor(detected_sensors/ (2^(HoTT_Sensor-1))) -- shift right
end
until HoTT_Sensor==0 or a % 2 == 1
HoTT_Send( 0x0F )
end
end
local function HoTT_Draw_LCD()
local i
local value
local line
local result
local offset=0
local sensor_name = { "", "+Vario", "+GPS", "+Cust", "+ESC", "+GAM", "+EAM" }
lcd.clear()
if LCD_W == 480 then
--Draw title
lcd.drawFilledRectangle(0, 0, LCD_W, 30, TITLE_BGCOLOR)
lcd.drawText(1, 5, "Graupner HoTT: config RX" .. sensor_name[HoTT_Sensor+1] .. " - Menu cycle Sensors", MENU_TITLE_COLOR)
--Draw RX Menu
if multiBuffer( 4 ) == 0xFF then
lcd.drawText(10,50,"No HoTT telemetry...", BLINK)
else
for line = 0, 7, 1 do
for i = 0, 21-1, 1 do
value=multiBuffer( line*21+6+i )
if value > 0x80 then
value = value - 0x80
lcd.drawText(10+i*16,32+20*line,string.char(value).." ",INVERS)
else
lcd.drawText(10+i*16,32+20*line,string.char(value))
end
end
end
end
else
--Draw RX Menu on LCD_W=128
if multiBuffer( 4 ) == 0xFF then
lcd.drawText(2,17,"No HoTT telemetry...",SMLSIZE)
else
if Timer_128 ~= 0 then
--Intro page
Timer_128 = Timer_128 - 1
lcd.drawScreenTitle("Graupner Hott",0,0)
lcd.drawText(2,17,"Configuration of RX" .. sensor_name[HoTT_Sensor+1] ,SMLSIZE)
lcd.drawText(2,37,"Press menu to cycle Sensors" ,SMLSIZE)
else
--Menu page
for line = 0, 7, 1 do
for i = 0, 21-1, 1 do
value=multiBuffer( line*21+6+i )
if value > 0x80 then
value = value - 0x80
lcd.drawText(2+i*6,1+8*line,string.char(value).." ",SMLSIZE+INVERS)
else
lcd.drawText(2+i*6,1+8*line,string.char(value),SMLSIZE)
end
end
end
end
end
end
end
-- Init
local function HoTT_Init()
--Set protocol to talk to
multiBuffer( 0, string.byte('H') )
--test if value has been written
if multiBuffer( 0 ) ~= string.byte('H') then
error("Not enough memory!")
return 2
end
multiBuffer( 1, string.byte('o') )
multiBuffer( 2, string.byte('T') )
multiBuffer( 3, string.byte('T') )
--Request init of the RX buffer
multiBuffer( 4, 0xFF )
--Request RX to send the config menu
HoTT_Send( 0x0F )
HoTT_Sensor = 0;
HoTT_Detected_Sensors=0;
Timer_128 = 100
end
-- Main
local function HoTT_Run(event)
if event == nil then
error("Cannot be run as a model script!")
return 2
elseif event == EVT_VIRTUAL_EXIT then
HoTT_Release()
return 2
else
if event == EVT_VIRTUAL_PREV_PAGE then
killEvents(event)
HoTT_Send( 0x07 )
elseif event == EVT_VIRTUAL_ENTER then
HoTT_Send( 0x09 )
elseif event == EVT_VIRTUAL_PREV then
HoTT_Send( 0x0B )
elseif event == EVT_VIRTUAL_NEXT then
HoTT_Send( 0x0D )
elseif event == EVT_VIRTUAL_NEXT_PAGE then
HoTT_Send( 0x0E )
elseif event == EVT_VIRTUAL_MENU then
Timer_128 = 100
HoTT_Sensor_Inc()
else
HoTT_Send( 0x0F )
end
HoTT_Draw_LCD()
return 0
end
end
return { init=HoTT_Init, run=HoTT_Run }
| gpl-3.0 |
lukego/snabb | lib/ljsyscall/syscall/freebsd/c.lua | 24 | 1298 | -- This sets up the table of C functions
local require, error, assert, tonumber, tostring,
setmetatable, pairs, ipairs, unpack, rawget, rawset,
pcall, type, table, string =
require, error, assert, tonumber, tostring,
setmetatable, pairs, ipairs, unpack, rawget, rawset,
pcall, type, table, string
local abi = require "syscall.abi"
local ffi = require "ffi"
require "syscall.freebsd.ffi"
local voidp = ffi.typeof("void *")
local function void(x)
return ffi.cast(voidp, x)
end
-- basically all types passed to syscalls are int or long, so we do not need to use nicely named types, so we can avoid importing t.
local int, long = ffi.typeof("int"), ffi.typeof("long")
local uint, ulong = ffi.typeof("unsigned int"), ffi.typeof("unsigned long")
local function inlibc_fn(k) return ffi.C[k] end
local C = setmetatable({}, {
__index = function(C, k)
if pcall(inlibc_fn, k) then
C[k] = ffi.C[k] -- add to table, so no need for this slow path again
return C[k]
else
return nil
end
end
})
-- quite a few FreeBSD functions are weak aliases to __sys_ prefixed versions, some seem to resolve but others do not, odd.
C.futimes = C.__sys_futimes
C.lutimes = C.__sys_lutimes
C.utimes = C.__sys_utimes
C.wait4 = C.__sys_wait4
C.sigaction = C.__sys_sigaction
return C
| apache-2.0 |
Zarakichi/ObEngine | engine/Lib/Toolkit/Functions/package.lua | 5 | 4096 | local Color = require("Lib/StdLib/ConsoleColor");
local Route = require("Lib/Toolkit/Route");
local Style = require("Lib/Toolkit/Stylesheet");
local Package = obe.Package;
local Functions = {};
function getPackageList()
local parser = Vili.ViliParser.new();
parser:parseFile("Package/Packages.vili");
local allPackages = {};
for _, key in pairs(parser:root():getAll(Vili.NodeType.ComplexNode)) do
table.insert(allPackages, key:getId());
end
return allPackages;
end
function getUninstalledPackageList()
local fileList = obe.Filesystem.getFileList("Package/");
local opaqueFiles = {};
local extension = ".opaque";
for _, file in pairs(fileList) do
if file:sub(-extension:len()) == extension then
table.insert(opaqueFiles, file:sub(1, #file - #extension));
end
end
return opaqueFiles;
end
function Functions.install(packageName)
Color.print({
{ text = "Installing Package '", color = Style.Execute},
{ text = packageName, color = Style.Package},
{ text = "' ...", color = Style.Execute},
}, 1)
if Package.Install(packageName) then
Color.print({
{ text = "Package '", color = Style.Success},
{ text = packageName, color = Style.Package},
{ text = "' has been successfully installed", color = Style.Success}
}, 2);
local parser = Vili.ViliParser.new();
parser:parseFile("Package/Opaque.vili");
local tPackageName = parser:root():at("Meta"):getDataNode("name"):getString();
if parser:hasFlag("Mount") then
obe.Filesystem.copy(Package.GetPackageLocation(tPackageName) .. "/Mount.vili", "Mount.vili");
end
else
Color.print({
{ text = "Package '", color = Style.Error},
{ text = packageName, color = Style.Package},
{ text = "' has not been installed (Already installed ?)", color = Style.Error}
}, 2);
end
end
function Functions.mount(packageName)
Color.print({
{ text = "Mounting Package '", color = Style.Execute},
{ text = packageName, color = Style.Package},
{ text = "' ...", color = Style.Execute},
}, 1)
if Package.PackageExists(packageName) then
obe.Filesystem.copy(Package.GetPackageLocation(packageName) .. "/Mount.vili", "Mount.vili");
Color.print({
{ text = "Package '", color = Style.Success},
{ text = packageName, color = Style.Package},
{ text = "' has been successfully mounted", color = Style.Success}
}, 2);
obe.MountPaths();
else
Color.print({
{ text = "Package '", color = Style.Error},
{ text = packageName, color = Style.Package},
{ text = "' does not exists", color = Style.Error}
}, 2);
end
end
function Functions.list()
local allPackages = getPackageList();
Color.print({
{ text = "All Registered Packages : ", color = Style.Execute}
}, 1);
for _, key in pairs(allPackages) do
Color.print({
{ text = "- Package : ", color = Style.Default},
{ text = key, color = Style.Package}
}, 2);
end
end
return {
Functions = Functions,
Routes = {
Route.Help("Commands to work with Packages");
install = Route.Node {
Route.Help("Installs a Package");
packageName = Route.Arg {
Route.Help("Name of the .opaque package file you want to install");
Route.Call("install");
Route.Autocomplete(getUninstalledPackageList);
};
};
mount = Route.Node {
Route.Help("Mount a Package");
packageName = Route.Arg {
Route.Help("Name of the package you want to mount");
Route.Call("mount");
};
Route.Autocomplete(getPackageList)
};
list = Route.Node {
Route.Help("Lists all Packages");
Route.Call("list");
}
}
}; | mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.