content stringlengths 5 1.05M |
|---|
concommand.Add( "mute_player", function( ply, cmd, args, argStr )
if ply:IsAdmin() then
local target
for _, v in ipairs( player.GetHumans() ) do
if v:Nick() == argStr then
target = v
end
end
if IsValid( target ) then
target.muted = true
print( "Player muted!" )
else
print( "Couldn't find player " .. argStr .. "!" )
end
end
end )
|
local skynet = require "skynet"
local log = require "chestnut.skynet.log"
local servicecode = require "enum.servicecode"
local traceback = debug.traceback
local CMD = {}
local SUB = {}
------------------------------------------
-- 服务协议
function CMD:start(channel_id, ... )
-- body
-- return self:start(channel_id, ... )
return true
end
function CMD:sayhi(reload)
-- body
return self:sayhi(reload)
end
function CMD:close()
-- body
return self:close()
end
function CMD:kill()
-- body
assert(false)
skynet.exit()
return servicecode.NORET
end
------------------------------------------
-- called by gated
function CMD:login(gate, uid, subid, secret)
-- body
local ok, err = xpcall(self.login, traceback, self, gate, uid, subid, secret)
if not ok then
log.error(err)
skynet.call(".AGENT_MGR", "lua", "exit_at_once", uid)
return servicecode.LOGIN_AGENT_ERR
end
if err ~= servicecode.SUCCESS then
ok = skynet.call(".AGENT_MGR", "lua", "exit_at_once", uid)
if not ok then
log.error("call AGENT_MGR exit_at_once failture.")
end
return err
end
return err
end
-- prohibit mult landing
function CMD:logout()
-- body
return self:logout()
end
-- begain to wait for client
function CMD:auth(conf)
return self:auth(conf)
end
-- others serverce disconnect
function CMD:afk()
-- body
return self:afk()
end
function CMD:save_data()
-- body
local ok, err = pcall(self.save_data, self)
if not ok then
log.error(err)
end
end
------------------------------------------
-- called by room
function CMD:test()
-- body
assert(self)
end
function CMD:info()
-- body
assert(self)
return { name="xiaomiao"}
end
function CMD:alter_rcard(args)
-- body
if self.systems.package:consume(4, 1) then
return true
else
return false
end
end
function CMD:roomover()
-- body
return self.systems.room:roomover()
end
function CMD:record(recordid, names)
-- body
local r = self._recordmgr:create(recordid, names)
self._recordmgr:add(r)
r:insert_db()
end
function CMD:room_leave()
-- body
log.info('room_leave')
return self.systems.room:leave()
end
------------------------------------------
-- 协议代理
------------------------------------------
-- 麻将协议代理,广播消息
function CMD:join(args, ... )
-- body
self:send_request("join", args)
return servicecode.NORET
end
function CMD:rejoin(args)
-- body
self:send_request("rejoin", args)
return servicecode.NORET
end
function CMD:offline(args)
-- body
self:send_request("offline", args)
return servicecode.NORET
end
function CMD:leave(args, ... )
-- body
self:send_request("leave", args)
return servicecode.NORET
end
function CMD:take_ready(args)
self:send_request("take_ready", args)
return servicecode.NORET
end
function CMD:ready(args, ... )
-- body
self:send_request("ready", args)
return servicecode.NORET
end
function CMD:deal(args, ... )
-- body
self:send_request("deal", args)
return servicecode.NORET
end
function CMD:take_turn(args)
-- body
self:send_request("take_turn", args)
return servicecode.NORET
end
function CMD:peng(args)
-- body
self:send_request("peng", args)
return servicecode.NORET
end
function CMD:gang(args)
-- body
self:send_request("gang", args)
return servicecode.NORET
end
function CMD:hu(args)
-- body
self:send_request("hu", args)
return servicecode.NORET
end
function CMD:ocall(args)
-- body
self:send_request("ocall", args)
return servicecode.NORET
end
function CMD:shuffle(args)
-- body
self:send_request("shuffle", args)
return servicecode.NORET
end
function CMD:dice(args)
-- body
self:send_request("dice", args)
return servicecode.NORET
end
function CMD:lead(args)
-- body
self:send_request("lead", args)
return servicecode.NORET
end
function CMD:over(args)
-- body
self:send_request("over", args)
return servicecode.NORET
end
function CMD:restart(args)
-- body
self:send_request("restart", args)
return servicecode.NORET
end
function CMD:take_restart(args)
-- body
self:send_request("take_restart", args)
return servicecode.NORET
end
-- function CMD:rchat(args)
-- -- body
-- self:send_request("rchat", args)
-- return servicecode.NORET
-- end
function CMD:take_xuanpao(args)
-- body
self:send_request("take_xuanpao", args)
return servicecode.NORET
end
function CMD:xuanpao(args)
-- body
self:send_request("xuanpao", args)
return servicecode.NORET
end
function CMD:take_xuanque(args)
-- body
self:send_request("take_xuanque", args)
return servicecode.NORET
end
function CMD:xuanque(args)
-- body
self:send_request("xuanque", args)
return servicecode.NORET
end
function CMD:settle(args)
-- body
self:send_request("settle", args)
return servicecode.NORET
end
function CMD:final_settle(args)
-- body
self:send_request("final_settle", args)
return servicecode.NORET
end
function CMD:mcall(args)
-- body
self:send_request("mcall", args)
return servicecode.NORET
end
function CMD:take_card(args)
-- body
end
function CMD:roomover(args)
-- body
self:send_request("roomover", args)
return servicecode.NORET
end
------------------------------------------
-- 大佬2协议发送代理
function CMD:big2take_turn(args)
-- body
self:send_request_gate("big2take_turn", args)
return servicecode.NORET
end
function CMD:big2call(args)
-- body
self:send_request_gate("big2call", args)
return servicecode.NORET
end
function CMD:big2shuffle(args)
-- body
self:send_request_gate("big2shuffle", args)
return servicecode.NORET
end
function CMD:big2lead(args)
-- body
self:send_request_gate("big2lead", args)
return servicecode.NORET
end
function CMD:big2deal(args)
-- body
self:send_request_gate("big2deal", args)
return servicecode.NORET
end
function CMD:big2ready(args)
-- body
self:send_request_gate("big2ready", args)
return servicecode.NORET
end
function CMD:big2over(args)
-- body
self:send_request_gate("big2ready", args)
return servicecode.NORET
end
function CMD:big2restart(args)
-- body
self:send_request_gate("big2restart", args)
return servicecode.NORET
end
function CMD:big2take_restart(args)
-- body
self:send_request_gate("big2take_restart", args)
return servicecode.NORET
end
function CMD:big2settle(args)
-- body
self:send_request_gate("big2settle", args)
return servicecode.NORET
end
function CMD:big2final_settle(args)
-- body
self:send_request_gate("big2final_settle", args)
return servicecode.NORET
end
function CMD:big2match(args)
-- body
self:send_request_gate("big2match", args)
return servicecode.NORET
end
function CMD:big2rejoin(args)
-- body
self:send_request_gate("big2rejoin", args)
return servicecode.NORET
end
function CMD:big2join(args)
-- body
self:send_request_gate("big2rejoin", args)
return servicecode.NORET
end
function CMD:big2leave(args)
-- body
self:send_request_gate("big2rejoin", args)
return servicecode.NORET
end
function CMD:big2take_ready(args)
-- body
self:send_request_gate("big2rejoin", args)
return servicecode.NORET
end
-- 大佬2协议发送代理
------------------------------------------
------------------------------------------
-- 德扑发送代理
function CMD:pokertake_turn(args)
-- body
self:send_request_gate("pokertake_turn", args)
return servicecode.NORET
end
function CMD:pokercall(args)
-- body
self:send_request_gate("pokercall", args)
return servicecode.NORET
end
function CMD:pokershuffle(args)
-- body
self:send_request_gate("pokershuffle", args)
return servicecode.NORET
end
function CMD:pokerdeal(args)
-- body
self:send_request_gate("pokerdeal", args)
return servicecode.NORET
end
function CMD:pokertake_ready(args)
-- body
self:send_request_gate("pokerrejoin", args)
return servicecode.NORET
end
function CMD:pokerready(args)
-- body
self:send_request_gate("pokerready", args)
return servicecode.NORET
end
function CMD:pokerover(args)
-- body
self:send_request_gate("pokerready", args)
return servicecode.NORET
end
function CMD:pokertake_restart(args)
-- body
self:send_request_gate("big2take_restart", args)
return servicecode.NORET
end
function CMD:pokerrestart(args)
-- body
self:send_request_gate("pokerrestart", args)
return servicecode.NORET
end
function CMD:pokersettle(args)
-- body
self:send_request_gate("pokersettle", args)
return servicecode.NORET
end
function CMD:pokerfinal_settle(args)
-- body
self:send_request_gate("pokerfinal_settle", args)
return servicecode.NORET
end
function CMD:pokermatch(args)
-- body
self:send_request_gate("pokermatch", args)
return servicecode.NORET
end
function CMD:pokerrejoin(args)
-- body
self:send_request_gate("pokerrejoin", args)
return servicecode.NORET
end
function CMD:pokerjoin(args)
-- body
self:send_request_gate("pokerjoin", args)
return servicecode.NORET
end
function CMD:pokerleave(args)
-- body
self:send_request_gate("pokerleave", args)
return servicecode.NORET
end
-- 德扑发送代理
------------------------------------------
return CMD |
character_2:UseSkill(1)
character_4:UseSkill(1)
Summon(1) |
--game.player[1] = Allways Admin
function isEmpty(value)
return value == nil or value == ''
end
function getRandomSign()
if (math.random() < 0.5) then
return -1
else
return 1
end
end
function getNewPositionRelativeTotalPlayers()
local randomLimit = global.preferredSpawnDistances * global.totalPlayers
local randomDistanceX = math.random(randomLimit, randomLimit + global.preferredSpawnDistances) * getRandomSign()
local randomDistanceY = math.random(randomLimit, randomLimit + global.preferredSpawnDistances) * getRandomSign()
local x = {}
x.x = randomDistanceX
x.y = randomDistanceY
return x
end
function getPlayersTotal()
local count = 0
for index, value in pairs(game.players) do
count = count + 1
end
return count
end
function getPlayersTotalOnline()
local count = 0
for index, value in pairs(game.players) do
if (value.connected) then
count = count + 1
end
end
return count
end
function getPlayersOnlineNames()
local names
local count = 0
for index, value in pairs(game.players) do
if (value.connected) then
count = count + 1
if (count == 1) then
names = value.name
else
names = names .. "," .. value.name
end
end
end
return names
end
function tryNewSpawnPoint(player)
--Setea un lugar nuevo de spawn
local randomPosition = getNewPositionRelativeTotalPlayers()
player.teleport{
randomPosition.x,
randomPosition.y
}
while ((game.surfaces[player.surface.name].get_tile(player.position.x, player.position.y).collides_with("water-tile")) == true)
do
goodPosition = game.surfaces[1].find_non_colliding_position("player", randomPosition, 0, 1)
player.teleport{
goodPosition.x,
goodPosition.y
}
player.force.set_spawn_position({
goodPosition.x,
goodPosition.y
}, game.surfaces[1])
end
end
script.on_event(defines.events.on_player_created, function(event)
--Called after the player was created.Just the first time in multiplayer games.
local player = game.players[event.player_index]
global.totalPlayers = global.totalPlayers + 1
local newForce = game.create_force("force" .. event.player_index)
player.force = newForce
resetPlayerData(event.player_index)
game.forces["enemy"].set_cease_fire(newForce, true)
game.forces["player"].set_cease_fire(newForce, false)
game.forces["neutral"].set_cease_fire(newForce, false)
tryNewSpawnPoint(player)
initGui(player)
player.print({"server-messages.welcome"})
printHelp(player)
end)
function initGui(player)
player.gui.left.add{
type = "frame", caption = {"gui-colonies.main"}, name = "main", direction = "vertical", style = "side_menu_frame_style"
}
end
script.on_event(defines.events.on_gui_click, function(event)
local player = game.players[event.player_index]
if (event.element.name == "main") then
if (isEmpty(player.gui.left.main.main_restartPlayer)) then
player.gui.left.main.add{
type = "button", caption = {"gui-colonies.main_restartPlayer"}, name = "main_restartPlayer"
}
else
player.gui.left.main.main_restartPlayer.destroy()
end
--[[ if (isEmpty(player.gui.left.main.main_playersList)) then
player.gui.left.main.add{
type = "button", caption = {"gui-colonies.main_playersList"}, name = "main_playersList"
}
else
player.gui.left.main.main_playersList.destroy()
end]]
if (isEmpty(player.gui.left.main.main_showHelp)) then
player.gui.left.main.add{
type = "button", caption = {"gui-colonies.main_showHelp"}, name = "main_showHelp"
}
else
player.gui.left.main.main_showHelp.destroy()
end
return
end
if (event.element.name=="main_showHelp") then
printHelp(player)
return
end
if (event.element.name == "main_restartPlayer") then
if (isEmpty(player.gui.center.main_restartPlayer_confirmRestart)) then
player.gui.center.add{
type = "frame", caption = {"gui-colonies.main_restartPlayer_confirmRestart"}, name = "main_restartPlayer_confirmRestart", direction = "vertical"
}
player.gui.center.main_restartPlayer_confirmRestart.add{
type = "button", caption = {"gui-colonies.main_restartPlayer_confirmRestart_yes"}, name = "main_restartPlayer_confirmRestart_yes"
}
player.gui.center.main_restartPlayer_confirmRestart.add{
type = "button", caption = {"gui-colonies.main_restartPlayer_confirmRestart_no"}, name = "main_restartPlayer_confirmRestart_no"
}
end
return
end
if (event.element.name == "main_playersList") then
if (isEmpty(player.gui.center.main_playerList)) then
player.gui.center.add{
type = "frame", caption = {"gui-colonies.main_playerList"}, name = "main_playerList", direction = "vertical"
}
for index, value in pairs(game.players) do
player.gui.center.main_playerList.add{
type = "label", caption = value.name, name = "guiCOLONIES" .. index
}
game.print("x1")
for index2, value2 in pairs(global.forcesData[value.force.name].totalKills) do
game.print("x2.1" .. index2)
game.print("x2.2 " .. "main_playerList_totalKills" .. value2)
player.gui.center.main_playerList["main" .. index].add{
type = "label", caption = value2 .. "-" .. index2, name = "main_playerList_totalKills" .. value2
}
end
game.print("x3")
-- global.forcesData[killers.name].totalKills[recentlyDeceasedEntity.name]
end
else
player.gui.center.main_playerList.destroy()
end
return
end
if (event.element.name == "main_restartPlayer_confirmRestart_yes") then
player.gui.center.main_restartPlayer_confirmRestart.destroy()
global.playersToRemove = {}
global.playersToRemove[1] = player
global.totalPlayers = global.totalPlayers - 1
player.gui.center.add{
type = "frame", caption = {"gui-colonies.main_restartPlayer_confirmedMessage"}, name = "main_restartPlayer_confirmedMessage", direction = "vertical"
}
player.gui.center.main_restartPlayer_confirmedMessage.add{
type = "button", caption = {"gui-colonies.main_restartPlayer_confirmedMessage_ok"}, name = "main_restartPlayer_confirmedMessage_ok"
}
return
end
if (event.element.name == "main_restartPlayer_confirmedMessage_yes") then
player.gui.center.main_restartPlayer_confirmRestart.destroy()
return
end
if (event.element.name == "main_restartPlayer_confirmRestart_no") then
player.gui.center.main_restartPlayer_confirmRestart.destroy()
return
end
if (event.element.name == "main_restartPlayer_confirmedMessage_ok") then
player.gui.center.main_restartPlayer_confirmedMessage.destroy()
return
end
--[[
if (event.element.name == "notificationMessage_ok") then
player.gui.center.notificationMessage.destroy()
return
end
]]
end)
--Garbage
function showNotificationMessage(playerIndex, messageId)
if (isEmpty(game.players[playerIndex].gui.center.notificationMessage)) then
local frame = game.players[playerIndex].gui.center.add{name = "notificationMessage", type = "frame", direction = "horizontal", style="scenario_message_dialog_style"}
frame.add{
type = "label", caption = {"gui-colonies.notificationMessage_" .. messageId}, name = "notificationMessage",style="entity_info_label_style"
}
game.players[playerIndex].gui.center.notificationMessage.add{
type = "button", caption = {"gui-colonies.notificationMessage_" .. messageId .. "_ok"}, name = "notificationMessage_ok"
}
end
return
end
function printCurrentServerStatus()
if (isEmpty(getPlayersOnlineNames())) then
log("****** Players Online/Total " .. getPlayersTotalOnline() .. "/" .. getPlayersTotal() .. " - Online now: none")
game.print("****** Players Online/Total " .. getPlayersTotalOnline() .. "/" .. getPlayersTotal() .. " - Online now: none")
else
log("****** Players Online/Total " .. getPlayersTotalOnline() .. "/" .. getPlayersTotal() .. " - Online now: " .. getPlayersOnlineNames())
game.print("****** Players Online/Total " .. getPlayersTotalOnline() .. "/" .. getPlayersTotal() .. " - Online now: " .. getPlayersOnlineNames())
end
end
script.on_event(defines.events.on_player_left_game, function(event)
log("****** Player " .. game.players[event.player_index].name .. " leave")
printCurrentServerStatus()
checkPlayerToRemove()
end)
script.on_event(defines.events.on_player_joined_game, function(event)
log("****** Player " .. game.players[event.player_index].name .. " joined")
printCurrentServerStatus()
end)
function resetPlayerData(playerIndex)
game.print("****** Player " .. game.players[playerIndex].name .. " initialized")
global.playersData[playerIndex] = {}
global.forcesData[game.players[playerIndex].force.name] = {}
global.forcesData[game.players[playerIndex].force.name].totalKills = {}
end
function checkPlayerToRemove()
if (global.playersToRemove == nil) then
return
else
log("****** Reseting player " .. global.playersToRemove[1].name)
local playersToRemove = global.playersToRemove
global.playersToRemove = nil
game.merge_forces(playersToRemove[1].force.name, game.forces["player"].name)
game.remove_offline_players(playersToRemove)
return
end
end
function printHelp(player)
player.print({"briefing-messages.help"})
player.print({"briefing-messages.reset"})
player.print({"briefing-messages.natives"})
player.print({"briefing-messages.humans"})
player.print({"briefing-messages.victory"})
end
script.on_event(defines.events.on_entity_died, function(event)
local recentlyDeceasedEntity = event.entity
local killers = event.force
log("on_entity_died X1: killers.name: " .. killers.name)
log("on_entity_died X2: recentlyDeceasedEntity.name: " .. recentlyDeceasedEntity.name)
if (killers.name=="enemy") then
return
end
if recentlyDeceasedEntity.name == "player" then
else
game.forces["enemy"].set_cease_fire(killers, false)
end
--Increment kind total kills
if (isEmpty(global.gameData[recentlyDeceasedEntity.name])) then
global.gameData.totalKills[recentlyDeceasedEntity.name] = 0
end
global.gameData.totalKills[recentlyDeceasedEntity.name] = global.gameData.totalKills[recentlyDeceasedEntity.name] + 1
if (isEmpty(global.forcesData[killers.name].totalKills[recentlyDeceasedEntity.name])) then
global.forcesData[killers.name].totalKills[recentlyDeceasedEntity.name] = 0
end
global.forcesData[killers.name].totalKills[recentlyDeceasedEntity.name] = global.forcesData[killers.name].totalKills[recentlyDeceasedEntity.name] + 1
if (isEmpty(global.gameData[recentlyDeceasedEntity.name])) then
global.gameData.totalKills[recentlyDeceasedEntity.name] = 0
end
global.gameData.totalKills[recentlyDeceasedEntity.name] = global.gameData.totalKills[recentlyDeceasedEntity.name] + 1
end)
function coloniesInitData()
log("Colonies 0.0.1 - on init")
if (isEmpty(global.totalPlayers)) then
global.totalPlayers = 0
global.playersData = {}
global.forcesData = {}
global.gameData = {}
global.gameData.totalKills = {}
global.preferredSpawnDistances = 300
end
log("global.totalPlayers: " .. global.totalPlayers)
end
script.on_init(function()
coloniesInitData()
end)
|
--[[ Extension functions for CDOTA_BaseNPC
-HasLearnedAbility(abilityName)
Checks if the unit has at least one point in ability abilityName.
Primarily for checking if talents have been learned.
--]]
function CDOTA_BaseNPC:HasLearnedAbility(abilityName)
local ability = self:FindAbilityByName(abilityName)
if ability then
return ability:GetLevel() > 0
end
return false
end
|
local PLUGIN = PLUGIN;
local Clockwork = Clockwork;
Clockwork.config:AddToSystem("No Noclip Eavesdrop", "no_noclip_eavesdrop", "Disables eavesdropping from players in observer.", 0, 1, 0);
Clockwork.chatBox:RegisterClass("radio_transmit", "ic", function(info)
info.channel = info.data.channel;
if (table.Count(info.data.transmitTable) == 1) then
local targetChannel = table.GetFirstKey(info.data.transmitTable);
local channelNumber = info.data.transmitTable[targetChannel]
if (type(channelNumber) != "boolean") then
info.channel = Clockwork.radio:FormatRadioChannel(targetChannel, channelNumber);
end;
end;
info.sound = info.data.sound;
info.useSound = true;
Clockwork.plugin:Call("AdjustRadioTransmit", info);
Clockwork.chatBox:Add(info.filtered, nil, info.data.color, info.name.." "..info.data.typeText.." on "..info.channel..": \""..info.text.."\"");
if (info.useSound) then
surface.PlaySound(info.sound);
end;
end);
Clockwork.chatBox:RegisterClass("radio_eavesdrop", "ic", function(info)
if (info.shouldHear) then
local color = Color(255, 255, 175, 255);
if (info.focusedOn) then
color = Color(175, 255, 175, 255);
end;
if (info.data.typeText == "radios") then
info.data.typeText = "says";
end;
info.sound = info.data.sound;
info.useSound = false;
Clockwork.plugin:Call("AdjustRadioEavesdrop", info);
Clockwork.chatBox:Add(info.filtered, nil, color, info.name.." "..info.data.typeText.." on radio: \""..info.text.."\"");
if (info.useSound) then
surface.PlaySound(info.sound);
end;
end;
end); |
require "Token"
require "AST"
require "ParserUtils"
require "Utils"
require "DoNotation"
-- parser function : ( buffer, index ) -> ( successful, buffer, index, value )
-- parser function : ( buffer, index ) -> ( failure, index )
mu = unit
function literals( buffer, index )
return choice { match( tokenType.int, function ( v ) return { type = astType.int; value = v.value } end )
, match( tokenType.float,
function ( v )
return { type = astType.float
; exponent = v.exponent
; intValue = v.intValue
; floatValue = v.floatValue
}
end )
, match( tokenType["true"], function ( v ) return { type = astType.bool; value = true } end )
, match( tokenType["false"], function ( v ) return { type = astType.bool; value = false } end )
, match( tokenType.string, function ( v ) return { type = astType.string; value = v.value } end )
} ( buffer, index )
-- TODO array literals
-- TODO function literals?
end
function constDeclaration( buffer, index )
local x = doNotation [[
do( bind, mu )
{
|- check( tokentype.const ) ;
varname <- symbol ;
|- check( tokentype.assign ) ;
|- dothis( function () print( "blarg " .. expr ) end )
exprvalue <- expr ;
|- check( tokentype.semicolon ) ;
unit { type = asttype.constdeclaration, varname = varname, assignment = exprvalue } ;
}
]]
print( x )
constDeclData = load( x )()
return constDeclData( buffer, index )
--[[return bind( check( tokenType.const ), function () return
bind( symbol, function ( varName ) return
bind( check( tokenType.assign ), function () return
bind( expr, function ( exprValue ) return
bind( check( tokenType.semicolon ), function () return
unit( { type = astType.constDeclaration; varName = varName; assignment = exprValue } ) end ) end ) end ) end ) end )( buffer, index )
--]]
end
function varDeclaration( buffer, index )
return bind( check( tokenType.var ), function () return
bind( symbol, function ( varName ) return
bind( check( tokenType.assign ), function () return
bind( expr, function ( exprValue ) return
bind( check( tokenType.semicolon ), function () return
unit( { type = astType.varDeclaration; varName = varName; assignment = exprValue } ) end ) end ) end ) end ) end )( buffer, index )
end
function symbol( buffer, index )
return match( tokenType.symbol, function ( s ) return s.value end )( buffer, index )
end
function indexedTypeSymbol( buffer, index )
return bind( symbol, function ( name ) return
bind( check( tokenType.openAngle ), function () return
bind( typeSig, function ( indexSig ) return
bind( check( tokenType.closeAngle ), function () return
unit( { type = astType.indexedType ; outer = name ; inner = indexSig } ) end ) end ) end ) end )( buffer, index )
end
function typeSymbol( buffer, index )
return choice { indexedTypeSymbol
, map( symbol, function ( s ) return { type = astType.simpleType ; value = s } end )
} ( buffer, index )
end
function arrowType( buffer, index )
return bind( allButArrowType, function ( t ) return
bind( check( tokenType.sub ), function () return
bind( check( tokenType.closeAngle ), function () return
bind( typeSig, function ( rest ) return
unit( { type = astType.arrowType ; first = t ; rest = rest } ) end ) end ) end ) end )( buffer, index )
end
function typeListTail( buffer, index )
return bind( check( tokenType.comma ), function () return
bind( typeSig, function ( t ) return
bind( typeList, function ( rest ) return
unit( insert( rest, 1, t ) ) end ) end ) end )( buffer, index )
end
function typeList( buffer, index )
return choice { typeListTail
, map( nothing, function () return {} end )
} ( buffer, index )
end
function tupleType( buffer, index )
return bind( check( tokenType.openParen ), function () return
bind( typeSig, function ( t ) return
bind( typeList, function ( rest ) return
bind( check( tokenType.closeParen ), function () return
unit( { type = astType.tupleType; typeList = insert( rest, 1, t ) } ) end ) end ) end ) end )( buffer, index )
end
function voidType( buffer, index )
return bind( check( tokenType.openParen ), function () return
bind( check( tokenType.closeParen ), function () return
unit( { type = astType.voidType } ) end ) end )( buffer, index )
end
function allButArrowType( buffer, index )
return choice { voidType
, tupleType
, typeSymbol
} ( buffer, index )
end
function typeSig( buffer, index )
return choice { voidType
, arrowType
, tupleType
, typeSymbol
} ( buffer, index )
end
function typeDefinition( buffer, index )
return bind( check( tokenType.type ), function () return
bind( symbol, function ( name ) return
bind( check( tokenType.colon ), function () return
bind( typeSig, function ( typeOfName ) return
bind( check( tokenType.semicolon ), function () return
unit( { type = astType.typeDefinition; name = name; typeOfName = typeOfName } ) end ) end ) end ) end ) end )( buffer, index )
end
function functionDefinitionParamVar( buffer, index )
return bind( symbol, function ( name ) return
bind( check( tokenType.colon ), function () return
bind( check( tokenType.var ), function () return
unit( { type = astType.paramVar, name = name } ) end ) end ) end )( buffer, index )
end
function functionDefinitionParamConst( buffer, index )
return bind( symbol, function ( name ) return
bind( check( tokenType.colon ), function () return
bind( check( tokenType.const ), function () return
unit( { type = astType.paramConst, name = name } ) end ) end ) end )( buffer, index )
end
function functionDefinitionParam( buffer, index )
return choice { functionDefinitionParamVar
, functionDefinitionParamConst
, map( symbol, function ( s ) return { type = astType.paramConst, name = s } end )
} ( buffer, index )
end
function functionParamListTail( buffer, index )
return bind( check( tokenType.comma ), function () return
bind( functionDefinitionParam, function ( param ) return
bind( functionParamList, function ( rest ) return
unit( insert( rest, 1, param ) ) end ) end ) end )( buffer, index )
end
function functionParamList( buffer, index )
return choice { functionParamListTail
, map( nothing, function () return {} end )
} ( buffer, index )
end
function functionDefinitionParameters( buffer, index )
return bind( check( tokenType.openParen ), function () return
bind( functionDefinitionParam, function ( param ) return
bind( functionParamList, function ( rest ) return
bind( check( tokenType.closeParen ), function () return
unit( { type = astType.paramList; paramList = insert( rest, 1, param ) } ) end ) end ) end ) end )( buffer, index )
end
function functionDefinitionEmptyParameter( buffer, index )
return bind( check( tokenType.openParen ), function () return
bind( check( tokenType.closeParen ), function () return
unit( { type = astType.paramList; paramList = {} } ) end ) end )( buffer, index )
end
function functionDefinition( buffer, index )
funcDefData = funcDefData or load( doNotation [[
do ( bind, mu )
{
|- check( tokenType.func ) ;
|- doThis( function () print( "one" ) end ) ;
funcName <- symbol ;
|- doThis( function () print( "two" ) end ) ;
params <- choice { functionDefinitionEmptyParameter, functionDefinitionParameters } ;
|- doThis( function () print( "three" ) end ) ;
|- check( tokenType.openCurly ) ;
|- doThis( function () print( "four - 1" ) end ) ;
stms <- stmList ;
|- doThis( function () print( "five" ) end ) ;
|- check( tokenType.closeCurly ) ;
|- doThis( function () print( "six" ) end ) ;
unit { type = astType.functionDefinition, name = funcName, parameters = params, statements = stms } ;
}
]] )()
return funcDefData( buffer, index )
end
function expr( buffer, index )
return choice { literals
,
} ( buffer, index )
end
function stm( buffer, index )
return choice { constDefinition
, varDefinition
} ( buffer, index )
end
function stmList( buffer, index )
return choice { stmListTail
, map( nothing, function () return {} end )
} ( buffer, index )
end
function stmListTail( buffer, index )
stmListTailData = stmdListTailData or load( doNotation [[
do ( bind, mu )
{
|- doThis( function() print( "stm 1" ) end ) ;
state <- stm ;
|- doThis( function() print( "stm 2" ) end ) ;
rest <- stmList ;
|- doThis( function() print( "stm 3" ) end ) ;
unit insert( rest, 1, state ) ;
}
]] )()
return stmListTailData( buffer, index )
end
|
local server = {}
return server
|
-- Copyright (c) 2017-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the license found in the LICENSE file in
-- the root directory of this source tree. An additional grant of patent rights
-- can be found in the PATENTS file in the same directory.
--
--[[
--
-- A helper script to convert a CUDA model into a CPU variant.
--
--]]
require 'fairseq'
local utils = require 'fairseq.utils'
local cuda = utils.loadCuda()
assert(cuda.cutorch)
local cmd = torch.CmdLine()
cmd:option('-input_model', 'cuda_model.th7',
'a th7 file that contains a CUDA model')
cmd:option('-output_model', 'float_model.th7',
'an output file that will contain the CPU verion of the model')
local config = cmd:parse(arg)
local model = torch.load(config.input_model)
model:float()
model.module:getParameters()
torch.save(config.output_model, model)
|
cc = cc or {}
---AnimationFrame object
---@class AnimationFrame : Ref
local AnimationFrame = {}
cc.AnimationFrame = AnimationFrame
--------------------------------
--- Set the SpriteFrame.<br>
---param frame A SpriteFrame will be used.
---@param frame SpriteFrame
---@return AnimationFrame
function AnimationFrame:setSpriteFrame(frame) end
--------------------------------
---@overload fun():map_table
---@overload fun():map_table
---@return map_table
function AnimationFrame:getUserInfo() end
--------------------------------
--- Sets the units of time the frame takes.<br>
---param delayUnits The units of time the frame takes.
---@param delayUnits float
---@return AnimationFrame
function AnimationFrame:setDelayUnits(delayUnits) end
--------------------------------
--
---@return AnimationFrame
function AnimationFrame:clone() end
--------------------------------
--- Return a SpriteFrameName to be used.<br>
---return a SpriteFrameName to be used.
---@return SpriteFrame
function AnimationFrame:getSpriteFrame() end
--------------------------------
--- Gets the units of time the frame takes.<br>
---return The units of time the frame takes.
---@return float
function AnimationFrame:getDelayUnits() end
--------------------------------
--- Sets user information.<br>
---param userInfo A dictionary as UserInfo.
---@param userInfo map_table
---@return AnimationFrame
function AnimationFrame:setUserInfo(userInfo) end
--------------------------------
--- initializes the animation frame with a spriteframe, number of delay units and a notification user info
---@param spriteFrame SpriteFrame
---@param delayUnits float
---@param userInfo map_table
---@return bool
function AnimationFrame:initWithSpriteFrame(spriteFrame, delayUnits, userInfo) end
--------------------------------
---Creates the animation frame with a spriteframe, number of delay units and a notification user info.<br>
---param spriteFrame The animation frame with a spriteframe.<br>
---param delayUnits Number of delay units.<br>
---param userInfo A notification user info.<br>
---since 3.0
---@param spriteFrame SpriteFrame
---@param delayUnits float
---@param userInfo map_table
---@return AnimationFrame
function AnimationFrame:create(spriteFrame, delayUnits, userInfo) end
--------------------------------
---js ctor
---@return AnimationFrame
function AnimationFrame:AnimationFrame() end
return AnimationFrame |
local core = require 'core.hover'
local files = require 'files'
rawset(_G, 'TEST', true)
function TEST(script)
return function (expect)
files.removeAll()
local start = script:find('<?', 1, true)
local finish = script:find('?>', 1, true)
local pos = (start + finish) // 2 + 1
local new_script = script:gsub('<[!?]', ' '):gsub('[!?]>', ' ')
files.setText('', new_script)
local hover = core.byUri('', pos)
assert(hover)
expect = expect:gsub('^[\r\n]*(.-)[\r\n]*$', '%1'):gsub('\r\n', '\n')
local label = hover.label:gsub('^[\r\n]*(.-)[\r\n]*$', '%1'):gsub('\r\n', '\n')
assert(expect == label)
end
end
TEST [[
local function <?x?>(a, b)
end
]]
"function x(a: any, b: any)"
TEST [[
local function x(a, b)
end
<?x?>()
]]
"function x(a: any, b: any)"
TEST [[
local mt = {}
mt.__index = mt
function mt:init(a, b, c)
return
end
local obj = setmetatable({}, mt)
obj:<?init?>(1, '测试')
]]
[[
function mt:init(a: any, b: any, c: any)
]]
TEST [[
local mt = {}
mt.__index = mt
mt.type = 'Class'
function mt:init(a, b, c)
return
end
local obj = setmetatable({}, mt)
obj:<?init?>(1, '测试')
]]
[[
function Class:init(a: any, b: any, c: any)
]]
TEST [[
local mt = {}
mt.__index = mt
mt.__name = 'Class'
function mt:init(a, b, c)
return
end
local obj = setmetatable({}, mt)
obj:<?init?>(1, '测试')
]]
[[
function Class:init(a: any, b: any, c: any)
]]
TEST [[
local mt = {}
mt.__index = mt
function mt:init(a, b, c)
return {}
end
local obj = setmetatable({}, mt)
obj:<?init?>(1, '测试')
]]
[[
function mt:init(a: any, b: any, c: any)
-> table
]]
TEST [[
local mt = {}
mt.__index = mt
function mt:init(a, b, c)
return {}
end
local obj = setmetatable({}, mt)
obj:init(1, '测试')
obj.<?init?>(obj, 1, '测试')
]]
[[
function mt:init(a: any, b: any, c: any)
-> table
]]
TEST [[
function obj.xxx()
end
obj.<?xxx?>()
]]
"function obj.xxx()"
TEST [[
obj.<?xxx?>()
]]
[[global obj.xxx: any]]
TEST [[
local <?x?> = 1
]]
"local x: integer = 1"
TEST [[
<?x?> = 1
]]
"global x: integer = 1"
TEST [[
local t = {}
t.<?x?> = 1
]]
"field t.x: integer = 1"
TEST [[
t = {}
t.<?x?> = 1
]]
"global t.x: integer = 1"
TEST [[
t = {
<?x?> = 1
}
]]
"field x: integer = 1"
TEST [[
local <?obj?> = {}
]]
"local obj: {}"
TEST [[
local mt = {}
mt.__name = 'class'
local <?obj?> = setmetatable({}, mt)
]]
"local obj: class {}"
TEST [[
local mt = {}
mt.name = 'class'
mt.__index = mt
local <?obj?> = setmetatable({}, mt)
]]
[[
local obj: class {
__index: table,
name: string = "class",
}
]]
TEST [[
local mt = {}
mt.TYPE = 'class'
mt.__index = mt
local <?obj?> = setmetatable({}, mt)
]]
[[
local obj: class {
TYPE: string = "class",
__index: table,
}
]]
TEST [[
local mt = {}
mt.Class = 'class'
mt.__index = mt
local <?obj?> = setmetatable({}, mt)
]]
[[
local obj: class {
Class: string = "class",
__index: table,
}
]]
-- TODO 支持自定义的函数库
--TEST[[
--local fs = require 'bee.filesystem'
--local <?root?> = fs.current_path()
--]]
--"local root: bee::filesystem"
TEST [[
<?print?>()
]]
[[
function print(...)
]]
TEST [[
string.<?sub?>()
]]
[[
function string.sub(s: string, i: integer, j?: integer)
-> string
]]
TEST[[
('xx'):<?sub?>()
]]
[[function string:sub(i: integer, j?: integer)
-> string]]
TEST [[
local <?v?> = collectgarbage()
]]
"local v: any"
TEST [[
local type
w2l:get_default()[<?type?>]
]]
"local type: any"
-- TODO 可选参数(或多原型)
TEST [[
<?load?>()
]]
[=[
function load(chunk: string|function, chunkname?: string, mode?: "b"|"t"|"bt", env?: table)
-> function
2. error_message: string
]=]
TEST [[
string.<?lower?>()
]]
[[
function string.lower(s: string)
-> string
]]
-- 不根据传入值推测参数类型
TEST [[
local function x(a, ...)
end
<?x?>(1, 2, 3, 4, 5, 6, 7)
]]
[[
function x(a: any, ...)
]]
TEST [[
local function x()
return y()
end
<?x?>()
]]
[[
function x()
-> any
]]
TEST [[
local mt = {}
function mt:add(a, b)
end
local function init()
return mt
end
local t = init()
t:<?add?>()
]]
[[
function mt:add(a: any, b: any)
]]
TEST [[
local mt = {}
mt.__index = mt
function mt:add(a, b)
end
local function init()
return setmetatable({}, mt)
end
local t = init()
t:<?add?>()
]]
[[
function mt:add(a: any, b: any)
]]
TEST [[
local <?t?> = - 1000
]]
[[local t: integer = -1000]]
-- TODO 暂不支持
--TEST [[
--for <?c?> in io.lines() do
--end
--]]
--[[local c: string]]
TEST [[
local function f()
return ...
end
local <?n?> = f()
]]
[[local n: any]]
TEST [[
local <?n?> = table.unpack(t)
]]
[[local n: any]]
TEST [[
local <?n?>
table.pack(n)
]]
[[
local n: any
]]
TEST [[
local s = <?'abc中文'?>
]]
[[9 个字节,5 个字符]]
TEST [[
local n = <?0xff?>
]]
[[255]]
TEST [[
local <?t?> = {
a = 1,
b = 2,
c = 3,
}
]]
[[
local t: {
a: integer = 1,
b: integer = 2,
c: integer = 3,
}
]]
TEST [[
local <?t?> = {}
t.a = 1
t.a = true
]]
[[
local t: {
a: boolean|integer = 1|true,
}
]]
TEST [[
local <?t?> = {
a = 1,
[1] = 2,
[true] = 3,
[5.5] = 4,
[{}] = 5,
[function () end] = 6,
["b"] = 7,
["012"] = 8,
}
]]
[[
local t: {
a: integer = 1,
[1]: integer = 2,
[true]: integer = 3,
[5.5]: integer = 4,
[table]: integer = 5,
[function]: integer = 6,
b: integer = 7,
["012"]: integer = 8,
}
]]
TEST [[
local <?t?> = {}
t[#t+1] = 1
t[#t+1] = 1
local any = collectgarbage()
t[any] = any
]]
[[
local t: {
[integer]: integer = 1,
}
]]
TEST[[
local x = 1
local y = x
print(<?y?>)
]]
[[
local y: integer = 1
]]
TEST[[
local mt = {}
mt.a = 1
mt.b = 2
mt.c = 3
local <?obj?> = setmetatable({}, {__index = mt})
]]
[[
local obj: {
a: integer = 1,
b: integer = 2,
c: integer = 3,
}
]]
TEST[[
local mt = {}
mt.__index = {}
function mt:test(a, b)
self:<?test?>()
end
]]
[[
function mt:test(a: any, b: any)
]]
TEST[[
local mt = {}
mt.__index = mt
mt.__name = 'obj'
function mt:remove()
end
local <?self?> = setmetatable({
id = 1,
}, mt)
]]
[[
local self: obj {
__index: table,
__name: string = "obj",
id: integer = 1,
remove: function,
}
]]
TEST [[
print(<?utf8?>)
]]
[[
global utf8: utf8* {
char: function,
charpattern: string,
codepoint: function,
codes: function,
len: function,
offset: function,
}
]]
TEST [[
print(io.<?stderr?>)
]]
[[
global io.stderr: file* {
close: function,
flush: function,
lines: function,
read: function,
seek: function,
setvbuf: function,
write: function,
}
]]
TEST [[
print(<?io?>)
]]
[[
global io: io* {
close: function,
flush: function,
input: function,
lines: function,
open: function,
output: function,
popen: function,
read: function,
stderr: file*,
stdin: file*,
stdout: file*,
tmpfile: function,
type: function,
write: function,
}
]]
TEST [[
local <?sssss?> = require 'utf8'
]]
[[
local sssss: utf8* {
char: function,
charpattern: string,
codepoint: function,
codes: function,
len: function,
offset: function,
}
]]
TEST [[
function F(a)
end
function F(b)
end
function F(a)
end
<?F?>()
]]
[[
(3 个定义,2 个原型)
(2) function F(a: any)
(1) function F(b: any)
]]
-- 不根据参数推断
--TEST[[
--function a(v)
-- print(<?v?>)
--end
--a(1)
--]]
--[[
--local v: number = 1
--]]
--
--TEST[[
--function a(v)
-- print(<?v?>)
--end
--pcall(a, 1)
--]]
--[[
--local v: number = 1
--]]
--TEST[[
--function a(v)
-- print(<?v?>)
--end
--xpcall(a, log.error, 1)
--]]
--[[
--local v: number = 1
--]]
TEST[[
function a(v)
return 'a'
end
local <?r?> = a(1)
]]
[[
local r: string = "a"
]]
TEST[[
function a(v)
return 'a'
end
local _, <?r?> = pcall(a, 1)
]]
[[
local r: string = "a"
]]
TEST[[
local <?n?> = rawlen()
]]
[[
local n: integer
]]
TEST[[
<?next?>()
]]
[[
function next(table: table, index?: any)
-> key: any
2. value: any
]]
-- TODO 暂未实现
--TEST[[
--local <?n?> = pairs()
--]]
--[[
--function n<next>(table: table [, index: any])
-- -> key: any, value: any
--]]
TEST[[
local <?x?> = '\a'
]]
[[local x: string = "\007"]]
TEST [[
local <?t?> = {
b = 1,
c = 2,
d = 3,
a = 4,
s = 5,
y = 6,
z = 7,
q = 8,
g = 9,
p = 10,
l = 11,
}
]]
[[
local t: {
b: integer = 1,
c: integer = 2,
d: integer = 3,
a: integer = 4,
s: integer = 5,
y: integer = 6,
z: integer = 7,
q: integer = 8,
g: integer = 9,
p: integer = 10,
l: integer = 11,
}
]]
TEST [[
local function <?f?>()
return nil, nil
end
]]
[[
function f()
-> nil
2. nil
]]
TEST [[
local function f()
return nil
end
local <?x?> = f()
]]
[[
local x: nil
]]
TEST [[
local function <?f?>()
return 1
return nil
end
]]
[[
function f()
-> integer|nil
]]
TEST [[
local <?t?> = {
b = 1,
c = 2,
d = 3,
}
local e = t.b
]]
[[
local t: {
b: integer = 1,
c: integer = 2,
d: integer = 3,
}
]]
TEST [[
local <?t?> = {
b = 1,
c = 2,
d = 3,
}
g.e = t.b
]]
[[
local t: {
b: integer = 1,
c: integer = 2,
d: integer = 3,
}
]]
TEST [[
local t = {
v = {
b = 1,
c = 2,
d = 3,
}
}
print(t.<?v?>)
]]
[[
field t.v: {
b: integer = 1,
c: integer = 2,
d: integer = 3,
}
]]
TEST [[
local <?t?> = {
f = io.open(),
}
]]
[[
local t: {
f: file*,
}
]]
TEST [[
io.<?popen?>()
]]
[[
function io.popen(prog: string, mode?: "r"|"w")
-> file*?
2. errmsg?: string
]]
TEST [[
<?_G?>
]]
[[
global _G: _G {
_G: _G,
_VERSION: string = "Lua 5.4",
arg: table,
assert: function,
bit32: bit32*,
collectgarbage: function,
coroutine: coroutine*,
debug: debug*,
dofile: function,
error: function,
getfenv: function,
getmetatable: function,
io: io*,
ipairs: function,
load: function,
loadfile: function,
loadstring: function,
math: math*,
module: function,
next: function,
os: os*,
package: table,
pairs: function,
pcall: function,
print: function,
rawequal: function,
rawget: function,
rawlen: function,
rawset: function,
require: function,
select: function,
setfenv: function,
setmetatable: function,
string: string*,
table: table*,
tonumber: function,
tostring: function,
type: function,
unpack: function,
utf8: utf8*,
warn: function,
xpcall: function,
}
]]
TEST [[
local x
x = 1
x = 1.0
print(<?x?>)
]]
[[
local x: number = 1
]]
TEST [[
local <?x?> <close> = 1
]]
[[
local x <close>: integer = 1
]]
TEST [[
local function <?a?>(b)
return (b.c and a(b.c) or b)
end
]]
[[
function a(b: table)
-> any
]]
TEST [[
local <?t?> = {
a = true
}
local t2 = {
[t.a] = function () end,
}
]]
[[
local t: {
a: boolean = true,
}
]]
TEST[[
---@class Class
local <?x?> = class()
]]
[[
local x: Class
]]
TEST[[
---@class Class
<?x?> = class()
]]
[[
global x: Class
]]
TEST[[
local t = {
---@class Class
<?x?> = class()
}
]]
[[
field x: Class
]]
TEST[[
---@type Class
local <?x?> = class()
]]
[[
local x: Class
]]
TEST[[
---@type Class
<?x?> = class()
]]
[[
global x: Class
]]
TEST[[
local t = {
---@type Class
<?x?> = class()
}
]]
[[
field x: Class
]]
TEST[[
---@type A|B|C
local <?x?> = class()
]]
[[
local x: A|B|C
]]
TEST[[
---@class Class
local <?x?> = {
b = 1
}
]]
[[
local x: Class {
b: integer = 1,
}
]]
TEST [[
---@class Class
local mt = {}
---@param t Class
function f(<?t?>)
end
]]
[[
local t: Class
]]
TEST [[
---@class Class
local mt = {}
---@param t Class
function f(t)
print(<?t?>)
end
]]
[[
local t: Class {}
]]
TEST [[
---@class Class
---@param k Class
for <?k?> in pairs(t) do
end
]]
[[
local k: Class
]]
TEST [[
---@class Class
---@param v Class
for k, <?v?> in pairs(t) do
end
]]
[[
local v: Class
]]
TEST [[
---@return A|B
---@return C
local function <?f?>()
end
]]
[[
function f()
-> A|B
2. C
]]
TEST [[
---@generic T
---@param x T
---@return T
local function <?f?>(x)
end
]]
[[
function f(x: <T>)
-> <T>
]]
TEST [[
---@return number
local function f()
end
local <?r?> = f()
]]
[[
local r: number
]]
TEST [[
---@generic T
---@param x T
---@return T
local function f(x)
end
local <?r?> = f(1)
]]
[[
local r: integer = 1
]]
TEST [[
---@param x number
---@param y boolean
local function <?f?>(x, y)
end
]]
[[
function f(x: number, y: boolean)
]]
TEST [[
---@vararg Class
local function f(...)
local _, <?x?> = ...
end
f(1, 2, 3)
]]
[[
local x: Class
]]
TEST [[
---@vararg Class
local function f(...)
local <?t?> = {...}
end
f(1, 2, 3)
]]
[[
local t: Class[]
]]
TEST [[
---@type string[]
local <?x?>
]]
[[
local x: string[]
]]
TEST [[
---@type string[]|boolean
local <?x?>
]]
[[
local x: boolean|string[]
]]
TEST [[
---@type string[]
local t
local <?x?> = t[1]
]]
[[
local x: string
]]
-- TODO
--TEST [[
-----@type string[]
--local t
--for _, <?x?> in ipairs(t) do
--end
--]]
--[[
--local x: string
--]]
--TEST [[
-----@type string[]
--local t
--for _, <?x?> in pairs(t) do
--end
--]]
--[[
--local x: string
--]]
--TEST [[
-----@type string[]
--local t
--for <?k?>, v in pairs(t) do
--end
--]]
--[[
--local k: integer
--]]
TEST [[
---@type table<ClassA, ClassB>
local <?x?>
]]
[[
local x: table<ClassA, ClassB>
]]
--TEST [[
-----@type table<ClassA, ClassB>
--local t
--for _, <?x?> in pairs(t) do
--end
--]]
--[[
--local x: *ClassB
--]]
--TEST [[
-----@type table<ClassA, ClassB>
--local t
--for <?k?>, v in pairs(t) do
--end
--]]
--[[
--local k: *ClassA
--]]
TEST [[
---@type fun(x: number, y: number):boolean
local <?f?>
]]
[[
function f(x: number, y: number)
-> boolean
]]
TEST [[
---@type fun(x: number, y: number):boolean
local f
local <?r?> = f()
]]
[[
local r: boolean
]]
TEST [[
---@param f fun():void
function t(<?f?>) end
]]
[[
function ()
-> void
]]
TEST [[
---@type fun(a:any, b:any)
local f
local t = {f = f}
t:<?f?>()
]]
[[
function f(a: any, b: any)
]]
TEST [[
---@param names string[]
local function f(<?names?>)
end
]]
[[
local names: string[]
]]
TEST [[
---@return any
function <?f?>()
---@type integer
local a
return a
end
]]
[[
function f()
-> any
]]
TEST [[
---@return any
function f()
---@type integer
local a
return a
end
local <?x?> = f()
]]
[[
local x: integer
]]
TEST [[
---@overload fun(y: boolean)
---@param x number
---@param y boolean
---@param z string
function f(x, y, z) end
print(<?f?>)
]]
[[
(2 个定义,2 个原型)
(1) function f(x: number, y: boolean, z: string)
(1) function f(y: boolean)
]]
TEST [[
---@type fun(x?: boolean):boolean?
local <?f?>
]]
[[
function f(x?: boolean)
-> boolean?
]]
TEST [[
---@param x? number
---@param y? boolean
---@return table?, string?
local function <?f?>(x, y)
end
]]
[[
function f(x?: number, y?: boolean)
-> table?
2. string?
]]
TEST [[
---@return table first, string? second
local function <?f?>(x, y)
end
]]
[[
function f(x: any, y: any)
-> first: table
2. second?: string
]]
TEST [[
---@class Class
---@field x number
---@field y number
---@field z string
local <?t?>
]]
[[
local t: Class {
x: number,
y: number,
z: string,
}
]]
TEST [[
---@class A
---@type <?A?>
]]
[[
class A
]]
TEST [[
---@type string | "'enum1'" | "'enum2'"
local <?t?>
]]
[[
local t: string|'enum1'|'enum2'
]]
TEST [[
---@alias A string | "'enum1'" | "'enum2'"
---@type <?A?>
]]
[[
展开为 string|'enum1'|'enum2'
]]
TEST [[
---@alias A string | "'enum1'" | "'enum2'"
---@type A
local <?t?>
]]
[[
local t: string|'enum1'|'enum2'
]]
TEST [[
---@type string
---| "'enum1'"
---| "'enum2'"
local <?t?>
]]
[[
local t: string|'enum1'|'enum2'
]]
TEST [[
---@class c
t = {}
---@overload fun()
function <?t?>.f() end
]]
[[
global t: c {
f: function,
}
]]
TEST [[
---@class c
local t = {}
---@overload fun()
function t.<?f?>() end
]]
[[
(2 个定义,1 个原型)
(2) function c.f()
]]
TEST [[
---@class c
t = {}
---@overload fun()
function t.<?f?>() end
]]
[[
(2 个定义,1 个原型)
(2) function t.f()
]]
TEST [[
---@class C
---@field field any
---@type C
local <?c?>
]]
[[
local c: C {
field: any,
}
]]
TEST [[
---@class C
---@field field any
---@return C
local function f() end
local <?c?> = f()
]]
[[
local c: C {
field: any,
}
]]
|
PLUGIN.name = "Stamina"
PLUGIN.author = "Chessnut, AleXXX_007"
PLUGIN.desc = "Adds a stamina system to limit running and jumping."
if (SERVER) then
function PLUGIN:SetupMove(player, movedata)
if player:getChar() then
local stamina = player:getLocalVar("stm", 100)
player:SetJumpPower(player:getChar():getAttrib("stm", 0) * 1.5 + 150)
end
end
function PLUGIN:PostPlayerLoadout(client)
client:SetWalkSpeed(nut.config.get("walkSpeed"))
local skill = client:getChar():getAttrib("end", 0)
client:setLocalVar("stm", math.Round(100 + skill))
local uniqueID = "nutStam"..client:SteamID()
local offset = 0
local velocity
local length2D = 0
local runSpeed = client:GetRunSpeed() - 5
timer.Create(uniqueID, 0.05, 0, function()
if (IsValid(client)) then
client:setLocalVar("maxStm", math.Round(100 + skill))
local character = client:getChar()
if (client:GetMoveType() != MOVETYPE_NOCLIP and character) then
velocity = client:GetVelocity()
length2D = velocity:Length2D()
runSpeed = nut.config.get("runSpeed")
local armor = 0
if client:getChar():getData("ArmorType", 0) == 3 then
armor = -0.5
elseif client:getChar():getData("ArmorType", 0) == 2 then
armor = -0.25
end
local buff = 0
if client:getLocalVar("stmBuff", 0) > 0 then
buff = client:getLocalVar("stmBuff")
end
offset = armor + buff
if (client:WaterLevel() > 1) then
runSpeed = runSpeed * 0.775
end
if (client:KeyDown(IN_SPEED) and length2D >= (runSpeed - 55)) then
offset = offset - 0.5 + math.floor(character:getAttrib("end", 0) / 200)
character:updateAttrib("end", 0.00025)
character:updateAttrib("stm", 0.00005)
if math.random(1, 30) == 1 then
character:setData("thirst", math.max(character:getData("thirst", 100) - 0.25, 0))
elseif math.random(1, 30) == 1 then
character:setData("hunger", math.max(character:getData("hunger", 100) - 0.25, 0))
elseif math.random(1, 30) == 1 then
character:setData("fatigue", math.max(character:getData("fatigue", 100) - 0.25, 0))
end
else
offset = offset + 0.6
end
local current = client:getLocalVar("stm", 0)
local value = math.Clamp(current + offset, 0, 100 + skill)
if (current != value) then
client:setLocalVar("stm", value, 2)
client:setLocalVar("maxStm", 100 + skill, 2)
if (client:getLocalVar("stm", 0) == 0 and !client.nutBreathing) then
client:SetRunSpeed(nut.config.get("walkSpeed"))
client.nutBreathing = true
hook.Run("PlayerStaminaLost", client)
elseif (value >= 50 and client.nutBreathing) then
client:SetRunSpeed(runSpeed)
client.nutBreathing = false
end
end
end
else
timer.Remove(uniqueID)
end
end)
end
local playerMeta = FindMetaTable("Player")
function playerMeta:restoreStamina(amount)
local skill = self:getChar():getAttrib("end", 0)
local current = self:getLocalVar("stm", 0)
local value = math.Clamp(current + amount, 0, 100 + skill)
self:setLocalVar("stm", value)
end
end |
-- Created by jogag
-- Part of the Digiline Stuff pack
-- Mod: Plastic from homedecor, if homedecor is not installed :)
-- + Also checks for pipeworks!
-- Texture license: from VanessaE, WTFPL
if not minetest.get_modpath("homedecor") and not minetest.get_modpath("pipeworks") then
minetest.register_craftitem(":homedecor:oil_extract", {
description = "Oil extract",
inventory_image = "homedecor_oil_extract.png",
})
minetest.register_craftitem(":homedecor:paraffin", {
description = "Unprocessed paraffin",
inventory_image = "homedecor_paraffin.png",
})
minetest.register_alias("homedecor:plastic_base", "homedecor:paraffin")
minetest.register_craftitem(":homedecor:plastic_sheeting", {
description = "Plastic sheet",
inventory_image = "homedecor_plastic_sheeting.png",
})
minetest.register_craft({
type = "shapeless",
output = "homedecor:oil_extract 6",
recipe = { "default:junglegrass",
"default:junglegrass",
"default:junglegrass"
}
})
minetest.register_craft({
type = "shapeless",
output = "homedecor:oil_extract 3",
recipe = { "default:dry_shrub",
"default:dry_shrub",
"default:dry_shrub"
},
})
minetest.register_craft({
type = "shapeless",
output = "homedecor:oil_extract 4",
recipe = { "default:leaves",
"default:leaves",
"default:leaves",
"default:leaves",
"default:leaves",
"default:leaves"
}
})
minetest.register_craft({
type = "cooking",
output = "homedecor:paraffin",
recipe = "homedecor:oil_extract",
})
minetest.register_craft({
type = "fuel",
recipe = "homedecor:paraffin",
burntime = 30,
})
minetest.register_craft({
type = "fuel",
recipe = "homedecor:plastic_sheeting",
burntime = 30,
})
minetest.register_alias("pipeworks:oil_extract", "homedecor:oil_extract")
minetest.register_alias("pipeworks:paraffin", "homedecor:paraffin")
minetest.register_alias("pipeworks:plastic_sheeting", "homedecor:plastic_sheeting")
end
|
local http = require "resty.http"
local lock = require "resty.lock"
local ocsp = require "ngx.ocsp"
local ssl = require "ngx.ssl"
local ssl_provider = require "resty.auto-ssl.ssl_providers.lets_encrypt"
local function convert_to_der_and_cache(domain, cert)
-- Convert certificate from PEM to DER format.
local fullchain_der, fullchain_der_err = ssl.cert_pem_to_der(cert["fullchain_pem"])
if not fullchain_der or fullchain_der_err then
return nil, "failed to convert certificate chain from PEM to DER: " .. (fullchain_der_err or "")
end
-- Convert private key from PEM to DER format.
local privkey_der, privkey_der_err = ssl.priv_key_pem_to_der(cert["privkey_pem"])
if not privkey_der or privkey_der_err then
return nil, "failed to convert private key from PEM to DER: " .. (privkey_der_err or "")
end
-- Cache DER formats in memory for 1 hour (so renewals will get picked up
-- across multiple servers).
local _, set_fullchain_err, set_fullchain_forcible = ngx.shared.auto_ssl:set("domain:fullchain_der:" .. domain, fullchain_der, 3600)
if set_fullchain_err then
ngx.log(ngx.ERR, "auto-ssl: failed to set shdict cache of certificate chain for " .. domain .. ": ", set_fullchain_err)
elseif set_fullchain_forcible then
ngx.log(ngx.ERR, "auto-ssl: 'lua_shared_dict auto_ssl' might be too small - consider increasing its configured size (old entries were removed while adding certificate chain for " .. domain .. ")")
end
local _, set_privkey_err, set_privkey_forcible = ngx.shared.auto_ssl:set("domain:privkey_der:" .. domain, privkey_der, 3600)
if set_privkey_err then
ngx.log(ngx.ERR, "auto-ssl: failed to set shdict cache of private key for " .. domain .. ": ", set_privkey_err)
elseif set_privkey_forcible then
ngx.log(ngx.ERR, "auto-ssl: 'lua_shared_dict auto_ssl' might be too small - consider increasing its configured size (old entries were removed while adding private key for " .. domain .. ")")
end
return {
fullchain_der = fullchain_der,
privkey_der = privkey_der,
}
end
local function issue_cert_unlock(domain, storage, local_lock, distributed_lock_value)
if local_lock then
local _, local_unlock_err = local_lock:unlock()
if local_unlock_err then
ngx.log(ngx.ERR, "auto-ssl: failed to unlock: ", local_unlock_err)
end
end
if distributed_lock_value then
local _, distributed_unlock_err = storage:issue_cert_unlock(domain, distributed_lock_value)
if distributed_unlock_err then
ngx.log(ngx.ERR, "auto-ssl: failed to unlock: ", distributed_unlock_err)
end
end
end
local function issue_cert(auto_ssl_instance, storage, domain)
-- Before issuing a cert, create a local lock to ensure multiple workers
-- don't simultaneously try to register the same cert.
local local_lock, new_local_lock_err = lock:new("auto_ssl", { exptime = 30, timeout = 30 })
if new_local_lock_err then
ngx.log(ngx.ERR, "auto-ssl: failed to create lock: ", new_local_lock_err)
return
end
local _, local_lock_err = local_lock:lock("issue_cert:" .. domain)
if local_lock_err then
ngx.log(ngx.ERR, "auto-ssl: failed to obtain lock: ", local_lock_err)
return
end
-- Also add a lock to the configured storage adapter, which allows for a
-- distributed lock across multiple servers (depending on the storage
-- adapter).
local distributed_lock_value, distributed_lock_err = storage:issue_cert_lock(domain)
if distributed_lock_err then
ngx.log(ngx.ERR, "auto-ssl: failed to obtain lock: ", distributed_lock_err)
issue_cert_unlock(domain, storage, local_lock, nil)
return
end
-- After obtaining the local and distributed lock, see if the certificate
-- has already been registered.
local cert, err = storage:get_cert(domain)
if err then
ngx.log(ngx.ERR, "auto-ssl: error fetching certificate from storage for ", domain, ": ", err)
end
if cert and cert["fullchain_pem"] and cert["privkey_pem"] then
issue_cert_unlock(domain, storage, local_lock, distributed_lock_value)
return cert
end
ngx.log(ngx.NOTICE, "auto-ssl: issuing new certificate for ", domain)
cert, err = ssl_provider.issue_cert(auto_ssl_instance, domain)
if err then
ngx.log(ngx.ERR, "auto-ssl: issuing new certificate failed: ", err)
end
issue_cert_unlock(domain, storage, local_lock, distributed_lock_value)
return cert, err
end
local function get_cert_der(auto_ssl_instance, domain, ssl_options)
-- Look for the certificate in shared memory first.
local fullchain_der = ngx.shared.auto_ssl:get("domain:fullchain_der:" .. domain)
local privkey_der = ngx.shared.auto_ssl:get("domain:privkey_der:" .. domain)
if fullchain_der and privkey_der then
return {
fullchain_der = fullchain_der,
privkey_der = privkey_der,
newly_issued = false,
}
end
-- Check to ensure the domain is one we allow for handling SSL.
--
-- Note: We perform this after the memory lookup, so more costly
-- "allow_domain" lookups can be avoided for cached certs. However, we will
-- perform this before the storage lookup, since the storage lookup could
-- also be more costly (or blocking in the case of the file storage adapter).
-- We may want to consider caching the results of allow_domain lookups
-- (including negative caching or disallowed domains).
local allow_domain = auto_ssl_instance:get("allow_domain")
if not allow_domain(domain, auto_ssl_instance) then
return nil, "domain not allowed"
end
-- Next, look for the certificate in permanent storage (which can be shared
-- across servers depending on the storage).
local storage = auto_ssl_instance.storage
local cert, get_cert_err = storage:get_cert(domain)
if get_cert_err then
ngx.log(ngx.ERR, "auto-ssl: error fetching certificate from storage for ", domain, ": ", get_cert_err)
end
if cert and cert["fullchain_pem"] and cert["privkey_pem"] then
local cert_der = convert_to_der_and_cache(domain, cert)
cert_der["newly_issued"] = false
return cert_der
end
-- Finally, issue a new certificate if one hasn't been found yet.
if not ssl_options or ssl_options["generate_certs"] ~= false then
cert = issue_cert(auto_ssl_instance, storage, domain)
if cert and cert["fullchain_pem"] and cert["privkey_pem"] then
local cert_der = convert_to_der_and_cache(domain, cert)
cert_der["newly_issued"] = true
return cert_der
end
else
return nil, "did not issue certificate, because the generate_certs setting is false"
end
-- Return an error if issuing the certificate failed.
return nil, "failed to get or issue certificate"
end
local function get_ocsp_response(fullchain_der)
-- Pull the OCSP URL to hit out of the certificate chain.
local ocsp_url, ocsp_responder_err = ocsp.get_ocsp_responder_from_der_chain(fullchain_der)
if not ocsp_url then
return nil, "failed to get OCSP responder: " .. (ocsp_responder_err or "")
end
-- Generate the OCSP request body.
local ocsp_req, ocsp_request_err = ocsp.create_ocsp_request(fullchain_der)
if not ocsp_req then
return nil, "failed to create OCSP request: " .. (ocsp_request_err or "")
end
-- Make the OCSP request against the OCSP server.
local httpc = http.new()
httpc:set_timeout(10000)
local res, req_err = httpc:request_uri(ocsp_url, {
method = "POST",
body = ocsp_req,
headers = {
["Content-Type"] = "application/ocsp-request",
}
})
-- Perform various checks to ensure we have a valid OCSP response.
if not res then
return nil, "OCSP responder query failed (" .. (ocsp_url or "") .. "): " .. (req_err or "")
end
if res.status ~= 200 then
return nil, "OCSP responder returns bad HTTP status code (" .. (ocsp_url or "") .. "): " .. (res.status or "")
end
local ocsp_resp = res.body
if not ocsp_resp or ocsp_resp == "" then
return nil, "OCSP responder returns bad response body (" .. (ocsp_url or "") .. "): " .. (ocsp_resp or "")
end
local ok, ocsp_validate_err = ocsp.validate_ocsp_response(ocsp_resp, fullchain_der)
if not ok then
return nil, "failed to validate OCSP response (" .. (ocsp_url or "") .. "): " .. (ocsp_validate_err or "")
end
return ocsp_resp
end
local function set_ocsp_stapling(domain, cert_der)
-- Fetch the OCSP stapling response from the cache, or make the request to
-- fetch it.
local ocsp_resp = ngx.shared.auto_ssl:get("domain:ocsp:" .. domain)
if not ocsp_resp then
-- If the certificate was just issued on the current request, wait 1 second
-- before making the initial OCSP request. Otherwise Let's Encrypt seems to
-- return an Unauthorized response.
if cert_der["newly_issued"] then
ngx.sleep(1)
end
local ocsp_response_err
ocsp_resp, ocsp_response_err = get_ocsp_response(cert_der["fullchain_der"])
if ocsp_response_err then
return false, "failed to get ocsp response: " .. (ocsp_response_err or "")
end
-- Cache the OCSP stapling response for 1 hour (this is what nginx does by
-- default).
local _, set_ocsp_err, set_ocsp_forcible = ngx.shared.auto_ssl:set("domain:ocsp:" .. domain, ocsp_resp, 3600)
if set_ocsp_err then
ngx.log(ngx.ERR, "auto-ssl: failed to set shdict cache of OCSP response for " .. domain .. ": ", set_ocsp_err)
elseif set_ocsp_forcible then
ngx.log(ngx.ERR, "auto-ssl: 'lua_shared_dict auto_ssl' might be too small - consider increasing its configured size (old entries were removed while adding OCSP response for " .. domain .. ")")
end
end
-- Set the OCSP stapling response.
local ok, ocsp_status_err = ocsp.set_ocsp_status_resp(ocsp_resp)
if not ok then
return false, "failed to set ocsp status resp: " .. (ocsp_status_err or "")
end
return true
end
local function set_response_cert(auto_ssl_instance, domain, cert_der)
local ok, err
-- Clear the default fallback certificates (defined in the hard-coded nginx
-- config).
ok, err = ssl.clear_certs()
if not ok then
return nil, "failed to clear existing (fallback) certificates - " .. (err or "")
end
-- Set OCSP stapling.
ok, err = set_ocsp_stapling(domain, cert_der)
if not ok then
ngx.log(auto_ssl_instance:get("ocsp_stapling_error_level"), "auto-ssl: failed to set ocsp stapling for ", domain, " - continuing anyway - ", err)
end
-- Set the public certificate chain.
ok, err = ssl.set_der_cert(cert_der["fullchain_der"])
if not ok then
return nil, "failed to set certificate - " .. (err or "")
end
-- Set the private key.
ok, err = ssl.set_der_priv_key(cert_der["privkey_der"])
if not ok then
return nil, "failed to set private key - " .. (err or "")
end
end
local function do_ssl(auto_ssl_instance, ssl_options)
-- Determine the domain making the SSL request with SNI.
local request_domain = auto_ssl_instance:get("request_domain")
local domain, domain_err = request_domain(ssl, ssl_options)
if not domain or domain_err then
ngx.log(ngx.WARN, "auto-ssl: could not determine domain for request (SNI not supported?) - using fallback - " .. (domain_err or ""))
return
end
-- Get or issue the certificate for this domain.
local cert_der, get_cert_der_err = get_cert_der(auto_ssl_instance, domain, ssl_options)
if get_cert_der_err then
if get_cert_der_err == "domain not allowed" then
ngx.log(ngx.NOTICE, "auto-ssl: domain not allowed - using fallback - ", domain)
else
ngx.log(ngx.ERR, "auto-ssl: could not get certificate for ", domain, " - using fallback - ", get_cert_der_err)
end
return
elseif not cert_der or not cert_der["fullchain_der"] or not cert_der["privkey_der"] then
ngx.log(ngx.ERR, "auto-ssl: certificate data unexpectedly missing for ", domain, " - using fallback")
return
end
-- Set the certificate on the response.
local _, set_response_cert_err = set_response_cert(auto_ssl_instance, domain, cert_der)
if set_response_cert_err then
ngx.log(ngx.ERR, "auto-ssl: failed to set certificate for ", domain, " - using fallback - ", set_response_cert_err)
return
end
end
return function(auto_ssl_instance, ssl_options)
local ok, err = pcall(do_ssl, auto_ssl_instance, ssl_options)
if not ok then
ngx.log(ngx.ERR, "auto-ssl: failed to run do_ssl: ", err)
end
end
|
minetest.register_alias("extractor", "technic:lv_extractor")
minetest.register_craft({
output = 'technic:lv_extractor',
recipe = {
{'technic:treetap', 'basic_materials:motor', 'technic:treetap'},
{'technic:treetap', 'technic:machine_casing', 'technic:treetap'},
{'', 'technic:lv_cable', ''},
}
})
technic.register_extractor({tier = "LV", demand = {300}, speed = 1})
|
function displayData()
if (not exports.UCDaccounts:isPlayerLoggedIn(localPlayer)) then return end
localPlayer:setData("dxscoreboard_money", exports.UCDutil:tocomma(getPlayerMoney(localPlayer)), true)
localPlayer:setData("dxscoreboard_city", exports.UCDutil:getPlayerCityZone(localPlayer), true)
--localPlayer:setData("dxscoreboard_playtime", localPlayer:getData("playtime"), true) -- Set in UCDplaytime
end
--addEventHandler("onClientPreRender", root, displayData)
Timer(displayData, 1000, 0) |
includeFile("custom_content/intangible/saga_system/sage_intangible_holocron.lua")
|
module(..., package.seeall)
jester.conf.debug = false
require "jester.support.string"
require "jester.support.table"
-- The CLI version assumes it's being run from the FreeSWITCH scripts
-- directory, but when run from FreeSWITCH the full path must be specified.
local script_path = "./"
if jester.is_freeswitch then
script_path = jester.conf.scripts_dir .. "/"
end
--[[
Initialize the help system.
]]
function init_module_help()
local help_file
-- Create a map of all module help that can be called.
jester.help_map = {}
for _, mod in ipairs(jester.conf.modules) do
help_file = "jester.modules." .. mod .. ".help"
if require(help_file) then
jester.debug_log("Loaded module help '%s'", help_file)
else
jester.debug_log("Failed loading module help '%s'!", help_file)
end
end
end
--[[
Get help for the passed subtopics.
]]
function get_help(...)
local output = ""
local help_path, output
local arguments = {...}
local arg_string = table.concat(arguments, " ")
-- Check for special topics first.
if arguments[1] == "modules" or arguments[1] == "module" or arguments[1] == "actions" or arguments[1] == "action" then
init_module_help()
local help_type = "action"
-- Module help.
if arguments[1] == "modules" or arguments[1] == "module" then
help_type = "module"
if arguments[2] then
output = module_help_detail(arguments[2])
else
output = module_help()
end
-- Action help.
else
if arguments[2] then
output = action_help_detail(arguments[2])
else
output = action_help()
end
end
-- Module and action details might return nothing if the arguments were
-- bad, catch that here.
if not output then
output = string.format("No %s help available for '%s'", help_type, arg_string)
end
-- General topic help.
else
-- Initialize the map.
jester.help_map = {}
-- Load all general topics.
require "lfs"
local error_message = {}
local path = script_path .. jester.conf.help_path
local file_list = {}
for file in lfs.dir(path) do
-- Exclude directory references and hidden files.
if not string.match(file, "^%..*") then
table.insert(file_list, file)
end
end
-- Since help files are nested tables, we want to enforce an alphabetical
-- loading order so that help topics nested more deeply can be loaded
-- after higher topics.
table.sort(file_list)
local f, e
for _, file in ipairs(file_list) do
f, e = loadfile(path .. "/" .. file)
if f then
jester.debug_log("Loaded help file '%s'", file)
f()
else
table.insert(error_message, e)
end
end
if #error_message == 0 then
-- Navigate into the help tree, and see if the requested subtopic is
-- available.
help_path = jester.help_map
if #arguments > 0 then
for a = 1, #arguments do
help_path = help_path[arguments[a]]
if not help_path then break end
end
end
-- No subtopics passed, start at main help.
if #arguments == 0 then
output = topic_help(jester.help_map, true)
-- Subtopic help found.
elseif help_path then
output = topic_help(help_path)
-- Help subtopic not found.
else
output = string.format("No help available for '%s'", arg_string)
end
else
output = string.format("Error loading help files: %s", table.concat(error_message, "; "))
end
end
help_output(output)
end
--[[
Output help to the appropriate location.
]]
function help_output(help)
if jester.is_freeswitch then
stream:write("\n" .. tostring(help) .. "\n")
else
print("\n" .. help .. "\n")
end
end
--[[
Build topical help.
]]
function topic_help(topic, main)
local output = {}
local description
-- Main help page must be caught and generated specially.
if main then
description = welcome()
else
description = topic.description_long or topic.description_short
end
if description then
table.insert(output, description:wrap(79))
end
-- Grab subtopics for the topic requested.
local subtopics = {}
for _, sub in ipairs(table.orderkeys(topic)) do
if type(topic[sub]) == "table" then
table.insert(subtopics, sub .. ":")
if topic[sub].description_short then
description = topic[sub].description_short:wrap(79, " ")
else
description = ""
end
table.insert(subtopics, description)
end
end
if #subtopics > 0 then
subtopic_list = string.format("SUBTOPICS:\n\n%s", table.concat(subtopics, "\n"))
table.insert(output, subtopic_list)
end
return table.concat(output, "\n\n")
end
--[[
Main help page text.
]]
function welcome()
return [[Welcome to Jester help!
Here you'll find extensive information on all the important areas of Jester. Start by reviewing the topic list below for an area of interest. The general format for accessing help is 'help [sub-topic] [sub-sub-topic] [...]', and this is how you'll see it referenced internally.]]
end
--[[
Get a list of all modules in the help system.
]]
function get_modules()
local module_list = {}
for _, module_name in ipairs(table.ordervalues(jester.conf.modules)) do
module_list[module_name] = jester.help_map[module_name]
end
return module_list
end
--[[
Build summary help for all modules.
]]
function module_help()
local module_list = {}
local help, description
-- Build an alphabetical summary of all modules enabled in the global config.
for _, name in ipairs(table.ordervalues(jester.conf.modules)) do
help = jester.help_map[name]
table.insert(module_list, name .. ":")
if help.description_short then
description = help.description_short:wrap(79, " ")
else
description = ""
end
table.insert(module_list, description)
end
return string.format("Run 'help module [name]' to get more help on a specific module.\n\nCurrently installed modules:\n\n%s", table.concat(module_list, "\n"))
end
--[[
Build detailed help for a module.
]]
function module_help_detail(module_name)
local description, actions
-- Loop through all modules looking for the passed one.
for name_to_check, data in pairs(jester.help_map) do
if name_to_check == module_name then
if data.description_long then
description = data.description_long:wrap(79)
elseif data.description_short then
description = data.description_short:wrap(79)
end
break
end
end
-- Found the module.
if description then
local list = {}
module_data = jester.help_map[module_name]
action_data = jester.help_map[module_name].actions
table.insert(list, description)
-- Found actions for the module.
if action_data then
table.insert(list, "\nACTIONS:")
-- Build an ordered list of actions.
for _, action in ipairs(table.orderkeys(action_data)) do
table.insert(list, " " .. action .. ":")
if action_data[action].description_short then
description = action_data[action].description_short:wrap(79, " ")
else
description = ""
end
table.insert(list, description)
end
end
-- Display all handlers for the module.
if module_data.handlers then
list = build_handlers(module_data, list)
end
return table.concat(list, "\n")
end
end
--[[
Build handler help.
]]
function build_handlers(module_data, list)
local handlers = module_data.handlers
table.insert(list, "\nHANDLERS:")
for _, handler in ipairs(table.orderkeys(handlers)) do
table.insert(list, " " .. handler .. ":")
table.insert(list, handlers[handler]:wrap(79, " "))
end
return list
end
--[[
Get a list of all actions in the help system.
]]
function get_actions()
local action_list = {}
local actions
for _, module_name in ipairs(table.ordervalues(jester.conf.modules)) do
actions = jester.help_map[module_name].actions
for action, data in pairs(actions) do
action_list[action] = data
end
end
return action_list
end
--[[
Build summary help for all actions.
]]
function action_help()
local action_list = {}
local actions, description
-- Loop through an alphabetically ordered list of modules.
for _, module_name in ipairs(table.ordervalues(jester.conf.modules)) do
actions = jester.help_map[module_name].actions
table.insert(action_list, "\nModule: " .. module_name)
-- Build and alphabetical list of actions for the module.
for _, action in ipairs(table.orderkeys(actions)) do
table.insert(action_list, " " .. action .. ":")
if actions[action].description_short then
description = actions[action].description_short:wrap(79, " ")
else
description = ""
end
table.insert(action_list, description)
end
end
return string.format("Run 'help action [name]' to get more help on a specific action.\n\nCurrently installed actions:\n%s", table.concat(action_list, "\n"))
end
--[[
Build detailed help for an action.
]]
function action_help_detail(action)
-- Loop through the modules looking for the passed action.
for _, module_data in pairs(jester.help_map) do
for action_to_check, action_data in pairs(module_data.actions) do
-- Found the action.
if action_to_check == action then
local list = {}
local description
if action_data.description_long then
description = action_data.description_long:wrap(79)
elseif action_data.description_short then
description = action_data.description_short:wrap(79)
else
description = ""
end
table.insert(list, description)
-- Look for parameters for the action.
local params = action_data.params
if params then
table.insert(list, "\nPARAMETERS:")
-- Build an ordered list of parameters.
for _, param in ipairs(table.orderkeys(params)) do
table.insert(list, " " .. param .. ":")
table.insert(list, params[param]:wrap(79, " "))
end
end
-- Display available handlers for the action.
if module_data.handlers then
list = build_handlers(module_data, list)
end
return table.concat(list, "\n")
end
end
end
end
|
function create_boss(keys)
-- 随机刷boss
local vec = Entities:FindByName(nil, "corner_" .. RandomInt(1, 7))
:GetOrigin()
local boss = Utils:create_unit_simple(
_G.load_boss["boss_" ..
RandomInt(1, tonumber(_G.load_boss["boss_count"]))],
vec, true, DOTA_TEAM_CUSTOM_1)
if keys.ability.boss_lvl ~= nil then
keys.ability.boss_lvl = keys.ability.boss_lvl + 5
-- boss最高24级
if keys.ability.boss_lvl >= 23 then keys.ability.boss_lvl = 23 end
boss:CreatureLevelUp(keys.ability.boss_lvl)
else
keys.ability.boss_lvl = -1
end
local level = boss:GetLevel()
for i = 0, boss:GetAbilityCount() - 1 do
abi = boss:GetAbilityByIndex(i)
if abi and abi:GetMaxLevel() == 4 then
abi:SetLevel(math.ceil(level / 8))
end
end
end
|
data:extend(
{
--fluid-craft*************************************************************************************************************************************************************
{
type = "recipe",
name = "fc-advanced-circuit",
category = "fluid-craft",
energy_required = 8,
enabled = false,
ingredients =
{
{type="fluid", name="electronic-circuit-fluid", amount=2},
{type="fluid", name="electronic-circuit-fluid", amount=2},
{type="fluid", name="copper-cable-fluid", amount=4}
},
results=
{
{"advanced-circuit", 1}
}
},
--battery
{
type = "recipe",
name = "fc-battery",
category = "fluid-craft",
energy_required = 5,
enabled = false,
ingredients =
{
{type="fluid", name="sulfuric-acid", amount=2},
{type="fluid", name="iron-plate-fluid", amount=1},
{type="fluid", name="copper-plate-fluid", amount=1}
},
results=
{
{"battery", 1},
}
},
--copper cable
{
type = "recipe",
name = "fc-copper-cable",
enabled = false,
category = "fluid-craft",
ingredients =
{
{type="fluid", name="copper-plate-fluid", amount=1}
},
results=
{
{"copper-cable", 3},
}
},
--concrete
{
type = "recipe",
name = "fc-concrete",
enabled = false,
category = "fluid-craft",
ingredients =
{
{type="fluid", name="stone-brick-fluid", amount=5},
{type="fluid", name="iron-ore-fluid", amount=1},
{type="fluid", name="water", amount=10}
},
results=
{
{"concrete", 10},
}
},
--effectivity module 1
{
type = "recipe",
name = "fc-effectivity-module",
category = "fluid-craft",
energy_required = 15,
enabled = false,
ingredients =
{
{type="fluid", name="advanced-circuit-fluid", amount=5},
{type="fluid", name="electronic-circuit-fluid", amount=5}
},
results=
{
{"effectivity-module", 1},
}
},
--eff mod 2
{
type = "recipe",
name = "fc-effectivity-module-2",
category = "fluid-craft",
energy_required = 30,
enabled = false,
ingredients =
{
{type="fluid", name="effectivity-module-fluid", amount=4},
{type="fluid", name="advanced-circuit-fluid", amount=5},
{type="fluid", name="processing-unit-fluid", amount=5}
},
results=
{
{"effectivity-module-2", 1},
}
},
--eff mod 3
{
type = "recipe",
name = "fc-effectivity-module-3",
category = "fluid-craft",
energy_required = 60,
enabled = false,
ingredients =
{
{type="fluid", name="effectivity-module-2-fluid", amount=5},
{type="fluid", name="advanced-circuit-fluid", amount=5},
{type="fluid", name="processing-unit-fluid", amount=5},
{type="fluid", name="alien-artifact-fluid", amount=1}
},
results=
{
{"effectivity-module-3", 1}
}
},
--electronic circuit
{
type = "recipe",
name = "fc-electronic-circuit",
enabled = false,
category = "fluid-craft",
ingredients =
{
{type="fluid", name="copper-cable-fluid", amount=3},
{type="fluid", name="iron-plate-fluid", amount=1}
},
results=
{
{"electronic-circuit", 1}
}
},
--engine unit
{
type = "recipe",
name = "fc-engine-unit",
category = "fluid-craft",
energy_required = 20,
enabled = false,
ingredients =
{
{type="fluid", name="iron-gear-wheel-fluid", amount=1},
{type="fluid", name="pipe-fluid", amount=2},
{type="fluid", name="steel-plate-fluid", amount=1}
},
results=
{
{"engine-unit", 1}
}
},
--electronic engine unit
{
type = "recipe",
name = "fc-electric-engine-unit",
category = "fluid-craft",
energy_required = 20,
enabled = false,
ingredients =
{
{type="fluid", name="engine-unit-fluid", amount=1},
{type="fluid", name="lubricant", amount=2},
{type="fluid", name="electronic-circuit-fluid", amount=2}
},
results=
{
{"electric-engine-unit", 1},
}
},
--explosives
{
type = "recipe",
name = "fc-explosive",
category = "fluid-craft",
energy_required = 5,
enabled = false,
ingredients =
{
{type="fluid", name="sulfur-fluid", amount=1},
{type="fluid", name="coal-fluid", amount=1},
{type="fluid", name="water", amount=1}
},
results=
{
{"explosives", 1},
}
},
--iron gear
{
type = "recipe",
name = "fc-iron-gear-wheel",
enabled = false,
category = "fluid-craft",
ingredients =
{
{type="fluid", name="iron-plate-fluid", amount=2}
},
results=
{
{"iron-gear-wheel", 1},
}
},
--iron stick
{
type = "recipe",
name = "fc-iron-stick",
enabled = false,
category = "fluid-craft",
ingredients =
{
{type="fluid", name="iron-plate-fluid", amount=1}
},
results=
{
{"iron-stick", 2},
}
},
--pipe
{
type = "recipe",
name = "fc-pipe",
category = "fluid-craft",
enabled = false,
ingredients =
{
{type="fluid", name="iron-plate-fluid", amount=1}
},
results=
{
{"pipe", 1},
}
},
--plastic bar
{
type = "recipe",
name = "fc-plastic-bar",
category = "fluid-craft",
energy_required = 1,
enabled = false,
ingredients =
{
{type="fluid", name="petroleum-gas", amount=3},
{type="fluid", name="coal-fluid", amount=1}
},
results=
{
{"plastic-bar", 1},
}
},
--processing unit
{
type = "recipe",
name = "fc-processing-unit",
category = "fluid-craft",
energy_required = 15,
enabled = false,
ingredients =
{
{type="fluid", name="electronic-circuit-fluid", amount=20},
{type="fluid", name="advanced-circuit-fluid", amount=2},
{type="fluid", name="sulfuric-acid", amount=0.5}
},
results=
{
{"processing-unit", 1},
}
},
--productivity module 1
{
type = "recipe",
name = "fc-productivity-module",
category = "fluid-craft",
energy_required = 15,
enabled = false,
ingredients =
{
{type="fluid", name="advanced-circuit-fluid", amount=5},
{type="fluid", name="electronic-circuit-fluid", amount=5}
},
results=
{
{"productivity-module", 1},
}
},
--prod mod 2
{
type = "recipe",
name = "fc-productivity-module-2",
category = "fluid-craft",
energy_required = 30,
enabled = false,
ingredients =
{
{type="fluid", name="productivity-module-fluid", amount=4},
{type="fluid", name="advanced-circuit-fluid", amount=5},
{type="fluid", name="processing-unit-fluid", amount=5}
},
results=
{
{"productivity-module-2", 1},
}
},
--prod mod 3
{
type = "recipe",
name = "fc-productivity-module-3",
category = "fluid-craft",
energy_required = 60,
enabled = false,
ingredients =
{
{type="fluid", name="productivity-module-2-fluid", amount=5},
{type="fluid", name="advanced-circuit-fluid", amount=5},
{type="fluid", name="processing-unit-fluid", amount=5},
{type="fluid", name="alien-artifact-fluid", amount=1}
},
results=
{
{"productivity-module-3", 1},
}
},
--robot frame
{
type = "recipe",
name = "fc-flying-robot-frame",
category = "fluid-craft",
energy_required = 20,
enabled = false,
ingredients =
{
{type="fluid", name="electric-engine-unit-fluid", amount=1},
{type="fluid", name="battery-fluid", amount=2},
{type="fluid", name="steel-plate-fluid", amount=1},
{type="fluid", name="electronic-circuit-fluid", amount=3}
},
results=
{
{"flying-robot-frame", 1},
}
},
--rocket control unit
{
type = "recipe",
name = "fc-rocket-control-unit",
category = "fluid-craft",
energy_required = 30,
enabled = false,
ingredients =
{
{type="fluid", name="processing-unit-fluid", amount=1},
{type="fluid", name="speed-module-fluid", amount=1}
},
results=
{
{"rocket-control-unit", 1},
}
},
--rocket fuel
{
type = "recipe",
name = "fc-rocket-fuel",
category = "fluid-craft",
energy_required = 30,
enabled = false,
ingredients =
{
{type="fluid", name="solid-fuel-fluid", amount=10}
},
results=
{
{"rocket-fuel", 1},
}
},
--low density structure fluid
{
type = "recipe",
name = "fc-low-density-structure",
category = "fluid-craft",
energy_required = 30,
enabled = false,
ingredients =
{
{type="fluid", name="steel-plate-fluid", amount=10},
{type="fluid", name="copper-plate-fluid", amount=5},
{type="fluid", name="plastic-bar-fluid", amount=5}
},
results=
{
{"low-density-structure", 1},
}
},
--science pack 1
{
type = "recipe",
name = "fc-science-pack-1",
enabled = false,
energy_required = 5,
category = "fluid-craft",
ingredients =
{
{type="fluid", name="copper-plate-fluid", amount=1},
{type="fluid", name="iron-gear-wheel-fluid", amount=1}
},
results=
{
{"science-pack-1", 1},
}
},
--alien science pack
{
type = "recipe",
name = "fc-alien-science-pack",
category = "fluid-craft",
enabled = false,
ingredients =
{
{type="fluid", name="alien-artifact-fluid", amount=1}
},
results=
{
{"alien-science-pack", 10},
}
},
--speed module 1
{
type = "recipe",
name = "fc-speed-module",
category = "fluid-craft",
energy_required = 15,
enabled = false,
ingredients =
{
{type="fluid", name="electronic-circuit-fluid", amount=5},
{type="fluid", name="advanced-circuit-fluid", amount=5}
},
results=
{
{"speed-module", 1},
}
},
--spd mod 2
{
type = "recipe",
name = "fc-speed-module-2",
category = "fluid-craft",
energy_required = 30,
enabled = false,
ingredients =
{
{type="fluid", name="speed-module-fluid", amount=4},
{type="fluid", name="advanced-circuit-fluid", amount=5},
{type="fluid", name="processing-unit-fluid", amount=5}
},
results=
{
{"speed-module-2", 1},
}
},
--spd mod 3
{
type = "recipe",
name = "fc-speed-module-3",
category = "fluid-craft",
energy_required = 60,
enabled = false,
ingredients =
{
{type="fluid", name="speed-module-2-fluid", amount=5},
{type="fluid", name="advanced-circuit-fluid", amount=5},
{type="fluid", name="processing-unit-fluid", amount=5},
{type="fluid", name="alien-artifact-fluid", amount=1}
},
results=
{
{"speed-module-3", 1},
}
},
}
) |
--------------------------------------------------------------------------------
-- Module Declaration
--
local mod, CL = BigWigs:NewBoss("Underrot Trash", 1841)
if not mod then return end
mod.displayName = CL.trash
mod:RegisterEnableMob(
133685, -- Befouled Spirit
131492, -- Devout Blood Priest
130909, -- Fetid Maggot
131436, -- Chosen Blood Matron
133870, -- Diseased Lasher
133835, -- Feral Bloodswarmer
133852, -- Living Rot
134284, -- Fallen Deathspeaker
133912, -- Bloodsworn Defiler
138281 -- Faceless Corruptor
)
--------------------------------------------------------------------------------
-- Localization
--
local L = mod:GetLocale()
if L then
L.spirit = "Befouled Spirit"
L.priest = "Devout Blood Priest"
L.maggot = "Fetid Maggot"
L.matron = "Chosen Blood Matron"
L.lasher = "Diseased Lasher"
L.bloodswarmer = "Feral Bloodswarmer"
L.rot = "Living Rot"
L.deathspeaker = "Fallen Deathspeaker"
L.defiler = "Bloodsworn Defiler"
L.corruptor = "Faceless Corruptor"
end
--------------------------------------------------------------------------------
-- Initialization
--
function mod:GetOptions()
return {
-- Befouled Spirit
{265568, "SAY"}, -- Dark Omen
-- Devout Blood Priest
265089, -- Dark Reconstitution
265091, -- Gift of G'huun
-- Fetid Maggot
265540, -- Rotten Bile
-- Chosen Blood Matron
265019, -- Savage Cleave
265081, -- Warcry
-- Diseased Lasher
278961, -- Decaying Mind
-- Feral Bloodswarmer
266107, -- Thirst For Blood
266106, -- Sonic Screech
-- Living Rot
265668, -- Wave of Decay
-- Fallen Deathspeaker
272183, -- Raise Dead
266209, -- Wicked Frenzy
-- Bloodsworn Defiler
265487, -- Shadow Bolt Volley
265433, -- Withering Curse
265523, -- Summon Spirit Drain Totem
-- Faceless Corruptor
272592, -- Abyssal Reach
272609, -- Maddening Gaze
}, {
[265568] = L.spirit,
[265089] = L.priest,
[265540] = L.maggot,
[265019] = L.matron,
[278961] = L.lasher,
[266107] = L.bloodswarmer,
[265668] = L.rot,
[272183] = L.deathspeaker,
[265487] = L.defiler,
[272592] = L.corruptor,
}
end
function mod:OnBossEnable()
self:RegisterMessage("BigWigs_OnBossEngage", "Disable")
-- Befouled Spirit
self:Log("SPELL_CAST_START", "DarkOmen", 265568)
self:Log("SPELL_AURA_APPLIED", "DarkOmenApplied", 265568)
-- Devout Blood Priest
self:Log("SPELL_CAST_START", "DarkReconstitution", 265089)
self:Log("SPELL_CAST_START", "GiftOfGhuun", 265091)
self:Log("SPELL_AURA_APPLIED", "GiftOfGhuunApplied", 265091)
-- Fetid Maggot
self:Log("SPELL_CAST_START", "RottenBile", 265540)
-- Chosen Blood Matron
self:Log("SPELL_CAST_SUCCESS", "BloodHarvest", 265016) -- charge that Matron does right before casting Savage Cleave
self:Log("SPELL_CAST_START", "SavageCleave", 265019)
self:Log("SPELL_AURA_APPLIED", "SavageCleaveApplied", 265019)
self:Log("SPELL_CAST_START", "Warcry", 265081)
-- Diseased Lasher
self:Log("SPELL_CAST_START", "DecayingMind", 278961)
self:Log("SPELL_AURA_APPLIED", "DecayingMindApplied", 278961)
self:Log("SPELL_AURA_REMOVED", "DecayingMindRemoved", 278961)
-- Feral Bloodswarmer
self:Log("SPELL_AURA_APPLIED", "ThirstForBloodApplied", 266107)
self:Log("SPELL_CAST_START", "SonicScreech", 266106)
-- Fallen Deathspeaker
self:Log("SPELL_CAST_START", "RaiseDead", 272183)
self:Log("SPELL_CAST_START", "WickedFrenzy", 266209)
-- Bloodsworn Defiler
self:Log("SPELL_CAST_START", "ShadowBoltVolley", 265487)
self:Log("SPELL_CAST_START", "WitheringCurse", 265433)
self:Log("SPELL_CAST_START", "SummonSpiritDrainTotem", 265523)
-- Faceless Corruptor
self:Log("SPELL_CAST_START", "AbyssalReach", 272592)
self:Log("SPELL_CAST_START", "MaddeningGaze", 272609)
self:Log("SPELL_AURA_APPLIED", "WaveOfDecayDamage", 278789)
self:Log("SPELL_PERIODIC_DAMAGE", "WaveOfDecayDamage", 278789)
self:Log("SPELL_PERIODIC_MISSED", "WaveOfDecayDamage", 278789)
end
--------------------------------------------------------------------------------
-- Event Handlers
--
-- Befouled Spirit
function mod:DarkOmen(args)
self:Message2(args.spellId, "cyan")
self:PlaySound(args.spellId, "alert")
end
function mod:DarkOmenApplied(args)
if self:Me(args.destGUID) then
self:PersonalMessage(args.spellId)
self:PlaySound(args.spellId, "alarm")
self:Say(args.spellId)
end
end
-- Devout Blood Priest
function mod:DarkReconstitution(args)
self:Message2(args.spellId, "orange")
self:PlaySound(args.spellId, "warning")
end
function mod:GiftOfGhuun(args)
self:Message2(args.spellId, "yellow", CL.casting:format(args.spellName))
self:PlaySound(args.spellId, "alert")
end
function mod:GiftOfGhuunApplied(args)
if self:MobId(args.sourceGUID) ~= 131492 then return end -- filter out Spellsteal
self:Message2(args.spellId, "red", CL.other:format(args.spellName, args.destName))
if self:Dispeller("magic", true) then
self:PlaySound(args.spellId, "alarm")
end
end
-- Fetid Maggot
function mod:RottenBile(args)
self:Message2(args.spellId, "yellow")
self:PlaySound(args.spellId, "alarm")
end
-- Chosen Blood Matron
do
local lastChargeTarget = nil
function mod:BloodHarvest(args)
lastChargeTarget = args.destName
end
function mod:SavageCleave(args)
if IsItemInRange(33278, lastChargeTarget) then -- 11 yards
self:Message2(args.spellId, "red", CL.near:format(args.spellName))
self:PlaySound(args.spellId, "warning")
else
self:Message2(args.spellId, "yellow", CL.casting:format(args.spellName))
end
end
end
function mod:SavageCleaveApplied(args)
if self:Me(args.destGUID) then
self:PersonalMessage(args.spellId)
self:PlaySound(args.spellId, "info")
end
end
function mod:Warcry(args)
self:Message2(args.spellId, "red")
self:PlaySound(args.spellId, "long")
end
-- Diseased Lasher
function mod:DecayingMind(args)
self:Message2(args.spellId, "orange", CL.casting:format(args.spellName))
self:PlaySound(args.spellId, "alert")
end
function mod:DecayingMindApplied(args)
if self:Me(args.destGUID) or self:Healer() or self:Dispeller("disease") then
self:TargetMessage2(args.spellId, "yellow", args.destName)
self:PlaySound(args.spellId, "info", nil, args.destName)
self:TargetBar(args.spellId, 30, args.destName)
end
end
function mod:DecayingMindRemoved(args)
self:StopBar(args.spellName, args.destName)
end
-- Feral Bloodswarmer
function mod:ThirstForBloodApplied(args)
if self:Me(args.destGUID) then
self:PersonalMessage(args.spellId)
self:PlaySound(args.spellId, "alarm")
end
end
function mod:SonicScreech(args)
self:Message2(args.spellId, "red", CL.casting:format(args.spellName))
self:PlaySound(args.spellId, "warning")
end
-- Fallen Deathspeaker
function mod:RaiseDead(args)
self:Message2(args.spellId, "yellow")
self:PlaySound(args.spellId, "alert")
end
function mod:WickedFrenzy(args)
self:Message2(args.spellId, "cyan")
self:PlaySound(args.spellId, "info")
end
-- Bloodsworn Defiler
function mod:ShadowBoltVolley(args)
self:Message2(args.spellId, "red")
self:PlaySound(args.spellId, "warning")
end
function mod:WitheringCurse(args)
self:Message2(args.spellId, "orange")
self:PlaySound(args.spellId, "alert")
end
function mod:SummonSpiritDrainTotem(args)
self:Message2(args.spellId, "yellow")
self:PlaySound(args.spellId, "alarm")
end
-- Faceless Corruptor
do
local prev = 0
function mod:AbyssalReach(args)
local t = args.time
if t-prev > 1.5 then
prev = t
self:Message2(args.spellId, "cyan")
self:PlaySound(args.spellId, "long")
end
end
end
do
local prev = 0
function mod:MaddeningGaze(args)
local t = args.time
if t-prev > 1.5 then
prev = t
self:Message2(args.spellId, "orange")
self:PlaySound(args.spellId, "alarm")
end
end
end
do
local prev = 0
function mod:WaveOfDecayDamage(args)
if self:Me(args.destGUID) then
local t = args.time
if t-prev > 1.5 then
prev = t
self:PersonalMessage(265668, "underyou")
self:PlaySound(265668, "alarm", "gtfo")
end
end
end
end
|
--[[
LuaOOP
Version 0.1.0
Developed by Pyutaro
Repository: lua-oop
]]
local LuaOOP = {}
--[[
Method: Class
Turns the classDefinition into a class.
To do this, it creates 2 methods:
1. .New (...)
If a .New method already exists, the old one is called *after* the new object inherits all of the class methods from the class definition.
Then returns the end result.
2. .Inherit (obj = nil)
If obj isn't specified, returns a new table containing all of the class methods.
Otherwise, all of the class methods are added to obj. (Will override if it already exists, however, so run this method *first*)
Arguments:
(ClassDefinition) classDefinition
Returns: (Class) class
]]
function LuaOOP.Class (classDefinition)
local base_constructor = classDefinition.New
function classDefinition.New (...)
local newObject = {}
newObject.class = classDefinition
for key, value in pairs(classDefinition) do
if type(value) == "function" then
newObject[key] = value
end
end
if base_constructor ~= nil then
base_constructor(newObject, ...)
end
return newObject
end
function classDefinition.Inherit (obj)
local newObject = obj or {}
for key, value in pairs(classDefinition) do
if type(value) == "function" then
newObject[key] = value
end
end
if obj == nil then
return newObject
end
end
return classDefinition
end
|
local self = {}
GLib.Net.Layer1.Channel = GLib.MakeConstructor (self, GLib.Net.IChannel) |
fx_version 'cerulean'
games { 'gta5' }
description 'NPC-Fuel-Stations'
version '1.0.0'
client_script "@npc-scripts/client/errorlog.lua"
ui_page 'html/ui.html'
files {
'html/*',
}
client_script 'client/client.lua'
exports {
'SetFuel',
'GetFuel'
}
|
local allowCountdown = false
local startedFirstDialogue = false
local startedEndDialogue = false
function onStartCountdown()
makeAnimatedLuaSprite('ts1', 'ts1', 0, 175);
setLuaSpriteScrollFactor('ts1', 0.9, 0.9);
addLuaSprite('ts1', false);
if not allowCountdown and isStoryMode and not startedFirstDialogue then
setProperty('inCutscene', true);
runTimer('startDialogue', 0.8);
startedFirstDialogue = true;
return Function_Stop;
end
return Function_Continue;
end
function onEndSong()
if not allowCountdown and isStoryMode and not startedEndDialogue then
setProperty('inCutscene', true);
runTimer('startDialogueEnd', 0.8);
startedEndDialogue = true;
return Function_Stop;
end
return Function_Continue;
end
function onTimerCompleted(tag, loops, loopsLeft)
if tag == 'startDialogue' then
startDialogue('dialogue', 'silence');
elseif tag == 'startDialogueEnd' then
startDialogue('dialogueEnd', 'silence');
makeAnimatedLuaSprite('lyrabon', 'lyrabon', 750, 150);
setLuaSpriteScrollFactor('lyrabon', 0.9, 0.9);
addLuaSprite('lyrabon', false);
makeAnimatedLuaSprite('derp', 'derp', 1250, 150);
setLuaSpriteScrollFactor('derp', 0.9, 0.9);
addLuaSprite('derp', false);
makeAnimatedLuaSprite('ts1', 'ts1', 0, 175);
setLuaSpriteScrollFactor('ts1', 0.9, 0.9);
addLuaSprite('ts1', false);
end
end
function onSongStart()
luaSpriteAddAnimationByPrefix('lyrabon', 'lyrabon', 'lyrabon', 24, true);
luaSpriteAddAnimationByPrefix('derp', 'derp', 'derp', 24, true);
luaSpriteAddAnimationByPrefix('ts1', 'ts1', 'ts1', 24, true);
end
function opponentNoteHit()
health = getProperty('health')
if getProperty('health') > 0.05 then
setProperty('health', health - 0.015);
end
end |
ENT.Contact = "https://space.bilibili.com/3761568/"
ENT.Base = "npc_vj_human_base"
ENT.Type = "ai"
ENT.Author = "Tamill"
ENT.Category = "Anime Bodyguard"
ENT.Purpose = ""
ENT.Instructions = ""
ENT.PrintName = "Renri Yamine"
ENT.AssetName = "npc_ab_renri_yamine"
ENT.ChineseName = "暗音"
ENT.Web = "http://steamcommunity.com/sharedfiles/filedetails/?id=1257751694"
ENT.Model = {"models/npc/renri_yamine_npc.mdl"}
ENT.IsUnavailable = false
|
local TestLayer = require("graphic.test.TestLayer")
local TestBitmapLayer = class("TestBitmapLayer", TestLayer)
function TestBitmapLayer:ctor()
TestLayer.ctor(self)
end
function TestBitmapLayer:init()
TestLayer.init(self)
self:customLayout()
end
function TestBitmapLayer:customLayout()
self._ui = {}
local go = self:loadUiPrefab("Sandbox/Prefabs/UI/Test/testBitmap.prefab")
self._ui.root = {}
self._ui.root.transform = go.transform
local tempGo = go.transform:Find("name").gameObject
self._ui.name = {}
self._ui.name.gameObject = tempGo
self._ui.name.text = tempGo:GetComponent(typeof(UI.Text))
local tempGo = go.transform:Find("BMFont").gameObject
self._ui.bmFont = {}
self._ui.bmFont.gameObject = tempGo
local txtGo = g_2dTools:createText("custom font: 0000", "Sandbox/Fonts/ttf/Hack_Regular.ttf", 30, self:assetGroup() )
txtGo.transform:SetParent(self._ui.root.transform, false)
txtGo:GetComponent(typeof(RectTransform)).anchorMin = Vector2(0.5,0.5)
txtGo:GetComponent(typeof(RectTransform)).anchorMax = Vector2(0.5,0.5)
txtGo:GetComponent(typeof(RectTransform)).sizeDelta = Vector2(500,62)
txtGo:GetComponent(typeof(RectTransform)).anchoredPosition = Vector2(0,10)
txtGo:GetComponent(typeof(UI.Text)).color = Color(1,1,1,1)
txtGo:GetComponent(typeof(UI.Text)).alignment = TextAnchor.MiddleCenter
local cmp = require("graphic.component.CScrollNumber").create()
cmp:init(txtGo, {
srcValue=0,
dstValue=9999,
duration=3,
-- format="custom font: %04d",
})
local cmp = require("graphic.component.CCountDown").create()
cmp:init(self._ui.name.gameObject, {
remainTime=10,
callback=function()
self._ui.name.text.text = "cd is over"
end})
local cmp = require("graphic.component.CCountDown").create()
cmp:init(self._ui.bmFont.gameObject, {
remainTime=65,
formats={"%02d-%02d-%02d","%02d-%02d","%d"},
type=typeof(TextMesh)
})
end
return TestBitmapLayer
|
nssm:register_mob("nssm:kraken", "Kraken", {
type = "monster",
hp_max = 350,
hp_min = 350,
collisionbox = {-2, 0, -2, 2, 4, 2},
visual = "mesh",
mesh = "kraken.x",
textures = {{"kraken.png"}, {"kraken2.png"}},
visual_size = {x=15, y=15},
lifetimer=500,
inker = false,
view_range = 50,
fly = true,
fly_in = {"default:water_source", "default:water_flowing"},
fall_speed = -1,
walk_velocity = 3.5,
run_velocity = 4.5,
damage = 14,
rotate = 270,
jump = false,
jump_chance = 0,
jump_height = 0,
sounds = {
random = "kraken",
},
drops = {
{name = "nssm:life_energy",
chance = 1,
min = 6,
max = 7,},
{name = "nssm:tentacle",
chance = 1,
min = 30,
max = 40,},
{name = "nssm:tentacle_curly",
chance = 1,
min = 1,
max = 1,},
},
armor = 50,
drawtype = "front",
water_damage = 0,
lava_damage = 10,
light_damage = 0,
blood_texture="nssm_blood_blue.png",
blood_amount=100,
knock_back=0,
on_rightclick = nil,
attack_type = "dogfight",
reach=8,
animation = {
speed_normal = 20,
speed_run = 30,
stand_start = 1,
stand_end = 40,
walk_start = 60,
walk_end = 100,
run_start = 60,
run_end = 100,
punch_start = 120,
punch_end = 150,
},
})
|
assert(math.ldexp)
assert(math.ldexp(5,5) == 160)
assert(math.ldexp(1.2345678,2) == 4.9382712)
|
--[[
Collectable Group - Server
v1.0
Created by Chris
Server-side implementation for collectable groups.
Keeps track of what collectables have been picked up, and informs
clients of what the "official" state is. Also validates
pickups and awards resources.
See the Readme for a more detailed breakdown of the architecture.
]]
local prop_Bitfields = script:GetCustomProperty("_Bitfields")
local propClientRoot = script:GetCustomProperty("ClientRoot"):WaitForObject()
local propResource = script.parent:GetCustomProperty("Resource")
local propResourceAmount = script.parent:GetCustomProperty("ResourceAmount")
if propResourceAmount == nil then propResourceAmount = 1 end
local SERVER_DATA_PROPERTY = "Contents"
local BF = require(prop_Bitfields)
local collectableData = nil
function InitContents(player, itemCount)
if collectableData ~= nil then return end
print(string.format("Initting %s with %d items!", propClientRoot.name, itemCount))
collectableData = BF.New(itemCount)
collectableData:Reset(true)
UpdateCurrentStringData()
end
function UpdateContents(player, bits, dataString)
local collected = BF.New(bits, dataString)
local needToUpdate = false
for i = 0, collectableData.bits - 1 do
if collected:Get(i) then
if collectableData:Get(i) then
collectableData:Set(i, false)
if propResource ~= nil then
player:AddResource(propResource, propResourceAmount)
end
needToUpdate = true
else
warn("!!!! Tried to collect an id that wasn't there:" .. tostring(i) .. ":" .. player.name)
end
end
end
if needToUpdate then
UpdateCurrentStringData()
end
end
-- Updates the custom network property with the "official" game state data.
function UpdateCurrentStringData()
if collectableData ~= nil then
propClientRoot:SetNetworkedCustomProperty(SERVER_DATA_PROPERTY, collectableData.raw)
else
warn("Somehow got to update string data without any data?")
end
end
-- Reenables all the collectables
function ResetCollectables(group)
if group ~= nil and group ~= propClientRoot then return end
collectableData:Reset(true)
UpdateCurrentStringData()
end
Events.ConnectForPlayer(propClientRoot:GetReference().id .. ":UpdateContents", UpdateContents)
Events.ConnectForPlayer(propClientRoot:GetReference().id .. ":Init", InitContents)
Events.Connect("ResetCollectables", ResetCollectables)
|
local mod = DBM:NewMod(1468, "DBM-Party-Legion", 10, 707)
local L = mod:GetLocalizedStrings()
mod:SetRevision(("$Revision: 17095 $"):sub(12, -3))
mod:SetCreatureID(95886)
mod:SetEncounterID(1816)
mod:SetZone()
mod:RegisterCombat("combat")
mod:RegisterEventsInCombat(
"SPELL_CAST_START 192522 192631 192621",
"SPELL_PERIODIC_DAMAGE",
"SPELL_PERIODIC_MISSED"
)
local warnVolcano = mod:NewSpellAnnounce(192621, 3, nil, nil, nil, nil, nil, 2)
local specWarnLavaWreath = mod:NewSpecialWarningDodge(192631, nil, nil, nil, 2, 2)
local specWarnFissure = mod:NewSpecialWarningSpell(192522, "Tank", nil, nil, 1, 2)--Not dogable, just so we aim it correctly
local timerVolcanoCD = mod:NewCDTimer(20, 192621, nil, nil, nil, 1)--20-22 unless delayed by brittle
local timerLavaWreathCD = mod:NewCDTimer(42.5, 192631, nil, nil, nil, 3)--42 unless delayed by brittle
local timerFissureCD = mod:NewCDTimer(42.5, 192522, nil, nil, nil, 5, nil, DBM_CORE_TANK_ICON)--42 unless delayed by brittle
function mod:OnCombatStart(delay)
timerVolcanoCD:Start(10-delay)
timerLavaWreathCD:Start(25-delay)
timerFissureCD:Start(40-delay)
end
function mod:SPELL_CAST_START(args)
local spellId = args.spellId
if spellId == 192522 then
specWarnFissure:Show()
specWarnFissure:Play("shockwave")
timerFissureCD:Start()
elseif spellId == 192631 then
specWarnLavaWreath:Show()
specWarnLavaWreath:Play("watchstep")
timerLavaWreathCD:Start()
elseif spellId == 192621 then
warnVolcano:Show()
warnVolcano:Play("mobsoon")
timerVolcanoCD:Start()
end
end
|
-------------------------------------------------------------------------------
-- Mob Framework Mod by Sapier
--
-- You may copy, use, modify or do nearly anything except removing this
-- copyright notice.
-- And of course you are NOT allow to pretend you have written it.
--
--! @file run_and_jump_low.lua
--! @brief movementpattern running arround ad doing random low jumps
--! @copyright Sapier
--! @author Sapier
--! @date 2012-08-10
--
--! @addtogroup mpatterns
--! @{
-- Contact sapier a t gmx net
-------------------------------------------------------------------------------
--! @struct run_and_jump_low_prototype
--! @brief a movement pattern used for quick moving and direction changing mobs
--! that jump every now and then
local run_and_jump_low_prototype = {
name ="run_and_jump_low",
jump_up =0.2,
random_jump_chance =0.3,
random_jump_initial_speed =3.5,
random_jump_delay =2,
random_acceleration_change =0.6,
}
--!~@}
table.insert(mov_patterns_defined,run_and_jump_low_prototype) |
--[[
Functions below: Ped spawning / clothing attachment
Description: function spawns and skins the peds acourding to the players chars , this is also where the start of the train spawn takes place
along with fetching players char data from DB , clothing data is done before this function.
This also determains the model for the spawning peds be it the one based on char clothing or a empty ped slot
]]
function Login.CreatePlayerCharacterPeds(characterModelData,isReset)
if Login.actionsBlocked and not isReset then return end
Login.actionsBlocked = true
if not isReset then
Wait(1000)
Login.LoadFinished = false
Login.ClearSpawnedPeds()
CleanUpArea()
Wait(1000)
CleanUpArea()
while Login.isTrainMoving do
Wait(10)
end
while Login.HasTransistionFinished do
Wait(10)
end
end
Login.CurrentClothing = characterModelData
local data = RPC.execute("caue-char:fetchCharacters")
if data.err then
return
end
local pedCoords = GetEntityCoords(PlayerPedId())
if isReset then
Login.ClearSpawnedPeds()
end
Login.CreatedPeds = {}
local PlusOneEmpty = false
local noCharacters = true
for _=1,#Login.spawnLoc do
local isCustom = false
local character = nil
local cid = 0
local cModelHash = GetHashKey("NP_M_Character_Select")
if data[_] ~= nil then
character = data[_]
local gender = `mp_male`
if character.gender == 1 then
cModelHash = GetHashKey("mp_f_freemode_01")
gender = `mp_female`
else
cModelHash = GetHashKey("mp_m_freemode_01")
end
cid = character.id
if characterModelData[cid] ~= nil then cModelHash = tonumber(characterModelData[cid].model) end
noCharacters = false
else
if math.random(2) == 1 then
cModelHash = GetHashKey("NP_F_Character_Select")
end
end
-- for i,v in ipairs(Login.custompeds) do
-- if cModelHash == GetHashKey(v) then
-- cModelHash = GetHashKey("np_m_character_select")
-- isCustom = true
-- end
-- end
if character == nil and not PlusOneEmpty then
PlusOneEmpty = _
end
local function CreatePedPCall(pHash, pX, pY, pZ)
local ped = CreatePed(3, pHash, pX, pY, pZ, 0.72, false, false)
return ped
end
Login.RequestModel(cModelHash, function(loaded, model, modelHash)
if loaded then
local newPed = nil
if character ~= nil then
local success, rData = pcall(CreatePedPCall, modelHash, Login.spawnLoc[_].x, Login.spawnLoc[_].y, Login.spawnLoc[_].z)
if success then
newPed = rData
else
newPed = CreatePed(3, `np_m_character_select`, Login.spawnLoc[_].x, Login.spawnLoc[_].y, Login.spawnLoc[_].z, 0.72, false, false)
print("MODEL FAILED TO LOAD IN SPAWN: " .. modelHash)
end
else
if PlusOneEmpty == _ then
local success, rData = pcall(CreatePedPCall, modelHash, Login.spawnLoc[_].x, Login.spawnLoc[_].y, Login.spawnLoc[_].z)
if success then
newPed = rData
else
newPed = CreatePed(3, `np_m_character_select`, Login.spawnLoc[_].x, Login.spawnLoc[_].y, Login.spawnLoc[_].z, 0.72, false, false)
print("MODEL FAILED TO LOAD IN SPAWN: " .. modelHash)
end
end
end
FreezeEntityPosition(newPed, true)
if newPed == nil then
goto skip_to_next
end
SetEntityHeading(newPed, Login.spawnLoc[_].w)
if character ~= nil and characterModelData[cid] ~= nil and characterModelData[cid] ~= {} and not isCustom then
Login.LoadPed(newPed, characterModelData[cid], modelHash)
end
if not isCustom then
if modelHash == GetHashKey("NP_F_Character_Select") or modelHash == GetHashKey("NP_M_Character_Select") then
if character ~= nil then
SetEntityAlpha(newPed,200,false)
else
SetEntityAlpha(newPed,0.9,false)
end
end
end
TaskLookAtCoord(newPed, vector3(-3968.05, 2015.41, 502.3 ),-1, 0, 2)
FreezeEntityPosition(newPed, true)
SetEntityInvincible(newPed, true)
SetBlockingOfNonTemporaryEvents(newPed, true)
Login.currentProtected[newPed] = true
if character ~= nil then
Login.CreatedPeds[_] = {
pedObject = newPed,
charId = cid,
posId = _
}
else
Login.CreatedPeds[_] = {
pedObject = newPed,
charId = 0,
posId = _
}
end
::skip_to_next::
end
end)
end
Wait(600)
SetNuiFocus(true, true)
SendNUIMessage({
open = true,
chars = data
})
--If no characters, open Creation menu
if noCharacters then
SendNUIMessage({ firstOpen = true })
end
Login.actionsBlocked = false
end
RegisterNetEvent("login:CreatePlayerCharacterPeds")
AddEventHandler("login:CreatePlayerCharacterPeds", Login.CreatePlayerCharacterPeds)
--[[
Functions below: base attachment
Description: set/get the correct information for chars
]]
function Login.getCharacters(isReset)
if not isReset then
TransitionFromBlurred(500)
local data = RPC.execute("caue-login:fetchData")
if data.err then
print(data.err)
return
end
end
local data = RPC.execute("caue-char:fetchCharacters")
if data.err then
print(data.err)
return
end
local charIds = "0"
local first = true
for k,v in ipairs(data) do
charIds = charIds .. "," .. v.id
end
TriggerServerEvent("login:getCharModels", charIds, isReset)
end
--[[
Functions below: character handlers
Description: dealing with finding information about characters
]]
function Login.SelectedChar(data)
Login.ClearSpawnedPeds()
TriggerEvent("character:PlayerSelectedCharacter")
local returnData = RPC.execute("caue-char:selectCharacter", data.actionData)
if not returnData then
print("There was a problem logging in as that character, if the problem persists, contact an administrator")
return
end
exports["caue-base"]:setVar("char", returnData)
if Login.CurrentClothing[data.actionData] == nil then
Login.setClothingForChar()
else
spawnChar()
end
end
--[[
Functions below: Clothing handlers
Description: Attachted to raid_clothes this deals with new chars or chars without clothes being selected and giveing the clothes
]]
function Login.setClothingForChar()
Login.actionsBlocked = true
SendNUIMessage({
close = true
})
SetEntityVisible(PlayerPedId(), true)
SetEntityCoords(PlayerPedId(),-3963.54,2013.95, 499.92)
SetEntityHeading(PlayerPedId(),64.71)
SetGameplayCamRelativeHeading(180.0)
SetGameplayCamRelativePitch(1.0, 1.0)
Wait(800)
for i=1,25 do
local posoffset = GetCamCoord(LoginSafe.Cam)
local setpos = VecLerp(posoffset.x,posoffset.y,posoffset.z, -3965.88,2014.55, 501.6, i/30, true)
SetCamCoord(LoginSafe.Cam, setpos)
Wait(15)
end
Login.Open = false
local gender = exports["caue-base"]:getChar("gender")
if gender ~= 0 then
SetSkin(GetHashKey("mp_f_freemode_01"), true)
else
SetSkin(GetHashKey("mp_m_freemode_01"), true)
end
TriggerEvent("raid_clothes:openClothing")
TriggerEvent("raid_clothes:inSpawn", true)
SetEntityHeading(PlayerPedId(),64.71)
SetGameplayCamRelativeHeading(180.0)
SetGameplayCamRelativePitch(4.0, 1.0)
end
RegisterNetEvent("caue-login:finishedClothing")
AddEventHandler("caue-login:finishedClothing", function(endType)
local playerped = PlayerPedId()
local playerCoords = GetEntityCoords(playerped)
local pos = vector3(-3965.88,2014.55, 501.6)
local distance = #(playerCoords - pos)
TriggerEvent("raid_clothes:inSpawn", false)
if distance <= 10 then
SetEntityVisible(PlayerPedId(), false)
if endType == "Finished" then
DoScreenFadeOut(2)
spawnChar()
else
backToMenu()
end
end
end)
function backToMenu()
Login.actionsBlocked = false
SetCamActive(LoginSafe.Cam, true)
RenderScriptCams(true, false, 0, true, true)
Login.nativeStart(true)
end
function spawnChar()
Login.actionsBlocked = false
deleteTrain()
SetNuiFocus(false, false)
SetPlayerInvincible(PlayerPedId(), true)
TriggerServerEvent("caue-login:spawnCharacter")
SendNUIMessage({
default = true
})
Login.Selected = false
Login.CurrentPedInfo = nil
Login.CurrentPed = nil
Login.CreatedPeds = {}
end |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- gameView.lua
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
local composer = require( "composer" )
local scene = composer.newScene()
--> MISCELLANEOUS
require ("math")
system.activate( "multitouch" )
-- include Corona's "widget" library
local widget = require "widget"
-- include global variables custom lua
local global = require( "variables" )
-- include Corona's "physics" library
local physics = require "physics"
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--> VARIABLES AND CONSTANTS
local halfpost = 36
local longside = 140
local a = 120
local b = 100
local strokeWidth = 10
local X, Y, X1, Y1, X2, Y2
local ball
local ballDim = 30
local player1
local player2
local player1Score
local player1Score
local score = 0
local pdim = 10
local background
local bluLine
local redLine
local bluTableL = {}
local bluTableR = {}
local redTableL = {}
local redTableR = {}
local upBoundL
local upBoundR
local lowBoundL
local lowBoundR
local title
local text
local text2
local porta1
local porta2
local v = 0.16
local netTimeK = 1.2
local bluX = {}
local bluY = {}
local redX = {}
local redY = {}
local timeTable = {}
local LowerNetCollisionFilter = {categoryBits = 1, maskBits = 16}
local upperNetCollisionFilter = {categoryBits = 2, maskBits = 32}
local lowerBoundCollisionFilter = {categoryBits = 4, maskBits = 80}
local upperBoundCollisionFilter = {categoryBits = 8, maskBits = 96}
local bluPlayerCollisionFilter = {categoryBits = 16, maskBits = 101}
local redPlayerCollisionFilter = {categoryBits = 32, maskBits = 90}
local ballCollisionFilter = {categoryBits = 64, maskBits = 60}
local LowerNetCollisionFilter_1 = {categoryBits = 1, maskBits = 0}
local upperNetCollisionFilter_1 = {categoryBits = 2, maskBits = 0}
local lowerBoundCollisionFilter_1 = {categoryBits = 4, maskBits = 64}
local upperBoundCollisionFilter_1 = {categoryBits = 8, maskBits = 64}
local bluPlayerCollisionFilter_1 = {categoryBits = 16, maskBits = 64}
local redPlayerCollisionFilter_1 = {categoryBits = 32, maskBits = 64}
local ballCollisionFilter_1 = {categoryBits = 64, maskBits = 60}
local LowerNetCollisionFilter_2 = {categoryBits = 1, maskBits = 16}
local upperNetCollisionFilter_2 = {categoryBits = 2, maskBits = 16}
local lowerBoundCollisionFilter_2 = {categoryBits = 4, maskBits = 80}
local upperBoundCollisionFilter_2 = {categoryBits = 8, maskBits = 80}
local bluPlayerCollisionFilter_2 = {categoryBits = 16, maskBits = 79}
local redPlayerCollisionFilter_2 = {categoryBits = 32, maskBits = 64}
local ballCollisionFilter_2 = {categoryBits = 64, maskBits = 60}
local i = 0
local j = 0
local segmentTransition
local delta = 1
local goal
local shootPowerDefault=0.01
local bluInPitch = false
local redInPitch = false
local lenBluX
local power_button_red
local staging_powerup
local loading
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--> GAME
function scene:create( event )
physics.start()
physics.setGravity(0,0)
local sceneGroup = self.view
--> SOUND
local goalSound = audio.loadSound('sounds/goal.wav')
--> FUNCTIONS
-- calcola il numero totale di elementi contenuti in un array
local function tableSize(table)
local i = 0
while table[i+1] do
i = i + 1
end
return i
end
--calcola la lunghezza di un segmento dati gli estremi
local function segmentLenght( x1, y1, x2, y2 )
local xFactor = x2 - x1
local yFactor = y2 - y1
local dist = math.sqrt( (xFactor*xFactor) + (yFactor*yFactor) )
return dist
end
--calcola l'intervallo di tempo per percorrere un segmento con una certa velocità
local function segmentTime(S, V)
local timeInterval = S / V
return timeInterval
end
--calcola l'angolo tra due oggetti
local function angleBetween ( srcObj, dstObj )
local xDist = dstObj.x-srcObj.x ; local yDist = dstObj.y-srcObj.y
local angleBetween = math.deg( math.atan( yDist/xDist ) )
if srcObj.x < dstObj.x then
angleBetween = angleBetween+90
else
angleBetween = angleBetween-90
end
return angleBetween
end
local function menuView()
composer.gotoScene( "menuView", "fade", 300 ) -- event listener function
playSound2()
return true
end
--muove player2 lungo la bluLine
local function onCompleteMove()
i = i + delta
if timeTable[i] then
segmentTransition = transition.to(player2, {
time=timeTable[i],
x=bluX[i+delta+j],
y=bluY[i+delta+j],
onComplete=onCompleteMove
})
else
if j==0 then
j = 1
else
j = 0
end
delta = delta*(-1)
i = i + delta
segmentTransition = transition.to(player2, {
time=timeTable[i],
x=bluX[i+delta+j],
y=bluY[i+delta+j],
onComplete=onCompleteMove
})
end
end
--ferma player2
local function bluStop()
transition.pause(segmentTransition)
end
--inverte il verso del moto di player2
local function invert()
bluStop()
if player2.x <= display.contentCenterX - halfpost or player2.x >= display.contentCenterX + halfpost then
print("I:", i)
print("J:", j)
print("D:", delta)
delta = delta * (-1)
if j==0 then
j = 1
else
j = 0
end
segmentTransition = transition.to(player2, {
time = segmentTime( segmentLenght( player2.x, player2.y, bluX[i+delta+j], bluY[i+delta+j]), v),
x = bluX[i+delta+j],
y = bluY[i+delta+j],
onComplete = onCompleteMove
})
else
transition.resume(segmentTransition)
end
end
--spara player2 nel campo con direzione normale alla bluLine
local function shoot()
if not bluInPitch then
if player2.x == display.contentCenterX - a - halfpost then
bluStop()
player2:applyLinearImpulse( shootPowerDefault, 0, player2.x, player2.y)
elseif player2.x > display.contentCenterX - a - halfpost and player2.x < display.contentCenterX-halfpost then
local centerAS = display.newCircle(a, display.contentHeight/2-140, 0.1)
centerAS:setFillColor( 0, 0, 0, 0)
local angleAS = angleBetween(centerAS, player2)*math.pi/180
local shootAngle = math.atan(b*math.sin(angleAS)/(a*math.cos(angleAS))) + math.pi/2
print("ANGLE: ".. tostring(shootAngle*180/math.pi))
local shootPowerComp_x = shootPowerDefault * math.cos(shootAngle)
local shootPowerComp_y = shootPowerDefault * math.sin(shootAngle)
bluStop()
player2:applyLinearImpulse(shootPowerComp_x, shootPowerComp_y, player2.x, player2.y)
elseif player2.x >= display.contentCenterX - halfpost and player2.x <= display.contentCenterX + halfpost then
bluStop()
player2:applyLinearImpulse( 0, shootPowerDefault, player2.x, player2.y)
elseif player2.x > display.contentCenterX + halfpost and player2.x < display.contentCenterX + a + halfpost then
local centerAD = display.newCircle(display.contentCenterX + halfpost, display.contentHeight/2-140, 0.1)
centerAD:setFillColor( 0, 0, 0, 0)
local angleAD = angleBetween(centerAD, player2)*math.pi/180
local shootAngle = math.atan(b*math.sin(angleAD)/(a*math.cos(angleAD))) - math.pi/2
local shootPowerComp_x = -shootPowerDefault * math.cos(shootAngle)
local shootPowerComp_y = -shootPowerDefault * math.sin(shootAngle)
bluStop()
player2:applyLinearImpulse(shootPowerComp_x, shootPowerComp_y, player2.x, player2.y)
elseif player2.x == display.contentCenterX + a + halfpost then
bluStop()
player2:applyLinearImpulse( -shootPowerDefault, 0, player2.x, player2.y)
end
bluInPitch = true
end
end
local function startMoving()
i = 1
if player2.x < display.contentCenterX then
while bluX[i] < player2.x do
i = i + 1
end
delta = 1
j = 0
else
i = lenBluX
while bluX[i] > player2.x do
i = i - 1
end
delta = -1
j = 1
end
segmentTransition = transition.to(player2, {
time = segmentTime( segmentLenght( player2.x, player2.y, bluX[i], bluY[i]), v),
x = bluX[i],
y = bluY[i],
onComplete = onCompleteMove
})
end
local function EllipseY(X)
return display.contentCenterY - math.sqrt((1-(X^2)/(a^2))*b^2) - longside
end
local leftX = display.contentCenterX - a - halfpost
local leftPostX = display.contentCenterX - halfpost
local rightPostX = display.contentCenterX + halfpost
local rightX = display.contentCenterX + a + halfpost
local highY = display.contentCenterY - longside - b
local bluHooking = function(event)
if bluInPitch and player2.y <= display.contentCenterY then
if player2.x - leftX <= 3 or rightX - player2.x <= 3 or player2.y - highY <= 2 then
player2.isAwake = false
startMoving()
bluInPitch = false
elseif player2.x < leftPostX and player2.y - EllipseY(player2.x-display.contentCenterX+halfpost) <= 3 then
player2.isAwake = false
startMoving()
bluInPitch = false
elseif player2.x >rightPostX and player2.y - EllipseY(player2.x-display.contentCenterX-halfpost) <= 3 then
player2.isAwake = false
startMoving()
bluInPitch = false
end
end
end
Runtime:addEventListener( "enterFrame", bluHooking)
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--> POWERUPS
local used_red = true
local ready_to_randomize = true
local counter = -1
local function restorePower()--ripristina potenza di tiro
shootPowerDefault=0.01
end
local function restoreDim()--ripristina dimensioni(?)
pdim=10
end
local function red_powerup_usage()
-- power_button_red.fill.effect = "filter.grayscale"
power_button_red.alpha=0
used_red=true
print ("X")
if current==1 then
print ("a")
local powerup1_sound = audio.loadSound( "sounds/powerup1_sound.wav")
audio.play(powerup1_sound, {channel=6})
ball.isAwake=false
elseif current==2 then
print ("b")
local powerup2_sound = audio.loadSound( "sounds/powerup2_sound.wav" )
audio.play(powerup2_sound, {channel=6})
elseif current==3 then
print ("c")
local powerup3_sound = audio.loadSound( "sounds/powerup3_sound.wav" )
audio.play(powerup3_sound, {channel=6})
shootPowerDefault=0.1
timer.performWithDelay(1500, restorePower)
elseif current==4 then
print ("d")
local powerup4_sound = audio.loadSound( "sounds/powerup4_sound.wav" )
audio.play(powerup4_sound, {channel=6})
pdim=30
timer.performWithDelay(1500, restoreDim)
end
print ("Y")
end
local function powerup()
if counter~=-1 then
loading.alpha=0
else
counter=0
end
if used_red and ready_to_randomize then
print("A libero B libero")
rand_red=math.random(5)
if rand_red==1 then
loading=display.newImageRect("powerups/powerup1.png", 30, 30 )
loading.alpha=1
print("B1")
elseif rand_red==2 then
loading=display.newImageRect("powerups/powerup2.png", 30, 30 )
loading.alpha=1
print("B2")
elseif rand_red==3 then
loading=display.newImageRect("powerups/powerup3.png", 30, 30 )
loading.alpha=1
print("B3")
elseif rand_red==4 then
loading=display.newImageRect("powerups/powerup4.png", 30, 30 )
loading.alpha=1
print("B4")
elseif rand_red==5 then
loading=display.newImageRect("powerups/powerup5.png", 30, 30 )
loading.alpha=1
print("B5")
end
loading.x = display.contentCenterX + 115
loading.y = display.contentCenterY-45
counter=counter+1
if counter ~= 5 then
timer.performWithDelay(700, powerup)
print("rieseguo")
else
print("counter=5")
if rand_red==1 then
power_button_red=display.newImageRect("powerups/powerup1.png", 30, 30 )
elseif rand_red==2 then
power_button_red=display.newImageRect("powerups/powerup2.png", 30, 30 )
elseif rand_red==3 then
power_button_red=display.newImageRect("powerups/powerup3.png", 30, 30 )
elseif rand_red==4 then
power_button_red=display.newImageRect("powerups/powerup4.png", 30, 30 )
elseif rand_red==5 then
power_button_red=display.newImageRect("powerups/powerup5.png", 30, 30 )
end
power_button_red.x = display.contentCenterX + 78
power_button_red.y = display.contentCenterY - 65
current=rand_red
power_button_red:addEventListener("tap", red_powerup_usage)
used_red=false
counter=0
timer.performWithDelay(700, powerup)
end
elseif not used_red and ready_to_randomize then
print("A pieno B libero")
loading.alpha=0
rand_red=math.random(5)
if rand_red==1 then
loading=display.newImageRect("powerups/powerup1.png", 30, 30 )
loading.alpha=1
print("B1")
elseif rand_red==2 then
loading=display.newImageRect("powerups/powerup2.png", 30, 30 )
loading.alpha=1
print("B1")
elseif rand_red==3 then
loading=display.newImageRect("powerups/powerup3.png", 30, 30 )
loading.alpha=1
print("B1")
elseif rand_red==4 then
loading=display.newImageRect("powerups/powerup4.png", 30, 30 )
loading.alpha=1
print("B1")
elseif rand_red==5 then
loading=display.newImageRect("powerups/powerup5.png", 30, 30 )
loading.alpha=1
print("B1")
end
loading.x = display.contentCenterX + 115
loading.y = display.contentCenterY-45
counter=counter+1
if counter ~= 5 then
print("rieseguo")
timer.performWithDelay(700, powerup)
else
print("counter=5")
staging_powerup=rand_red
ready_to_randomize=false
timer.performWithDelay(700, powerup)
end
elseif used_red and not ready_to_randomize then
print("A libero, B pieno")
power_button_red.alpha=0
rand_red = staging_powerup
if rand_red==1 then
power_button_red=display.newImageRect("powerups/powerup1.png", 30, 30 )
elseif rand_red==2 then
power_button_red=display.newImageRect("powerups/powerup2.png", 30, 30 )
elseif rand_red==3 then
power_button_red=display.newImageRect("powerups/powerup3.png", 30, 30 )
elseif rand_red==4 then
power_button_red=display.newImageRect("powerups/powerup4.png", 30, 30 )
elseif rand_red==5 then
power_button_red=display.newImageRect("powerups/powerup5.png", 30, 30 )
end
power_button_red.x = display.contentCenterX + 78
power_button_red.y = display.contentCenterY-65
current=rand_red
power_button_red:addEventListener("tap", red_powerup_usage)
used_red=false
ready_to_randomize=true
counter=0
timer.performWithDelay(700, powerup)
elseif not used_red and not ready_to_randomize then
loading.alpha=1
print("A pieno, B pieno")
timer.performWithDelay(700, powerup)
end
end
timer.performWithDelay(700, powerup)
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--> BACKGROUND
if (global.fieldType==1) then
background = display.newImageRect( "fields/field1.png", display.contentWidth, display.contentHeight*119/100 )
background.x = display.contentCenterX
background.y = display.contentCenterY
elseif (global.fieldType==2) then
background = display.newImageRect( "fields/field2.png", display.contentWidth, display.contentHeight*119/100 )
background.x = display.contentCenterX
background.y = display.contentCenterY
elseif (global.fieldType==3) then
background = display.newImageRect( "fields/field3.png", display.contentWidth, display.contentHeight*119/100 )
background.x = display.contentCenterX
background.y = display.contentCenterY
else
background = display.newImageRect( "fields/field0.png", display.contentWidth, display.contentHeight*119/100 )
background.x = display.contentCenterX
background.y = display.contentCenterY
end
--> GOALS
if (global.fieldType==0) then
porta1 = display.newImageRect("fields/porta100.png", 80, 80)
porta1.x = display.contentCenterX
porta1.y = display.contentHeight*3.6/100
porta2 = display.newImageRect("fields/porta200.png", 80, 80)
porta2.x = display.contentCenterX
porta2.y = display.contentHeight*96.4/100
end
--[[ lasciate commentato plz
if (global.fieldType==0) then
porta1 = display.newImageRect(".png", 80, 80)
porta1.x = display.contentCenterX
porta1.y = display.contentHeight*3.6/100
porta2 = display.newImageRect(".png", 80, 80)
porta2.x = display.contentCenterX
porta2.y = display.contentHeight*96.4/100
elseif (global.fieldType==1) then
porta1 = display.newImageRect(".png", 80, 80)
porta1.x = display.contentCenterX
porta1.y = display.contentHeight*3.6/100
porta2 = display.newImageRect(".png", 80, 80)
porta2.x = display.contentCenterX
porta2.y = display.contentHeight*96.4/100
end
]]
--> ARENA
--player paths
--bluX and bluY tables, creation of timeTable
X1 = display.contentCenterX - a - halfpost
Y1 = display.contentCenterY
X2 = display.contentCenterX - a - halfpost
Y2 = display.contentCenterY - longside
table.insert(bluX, X1)
table.insert(bluX, X2)
table.insert(bluY, Y1)
table.insert(bluY, Y2)
table.insert(timeTable, segmentTime(segmentLenght(X1, Y1, X2, Y2), v))
X1 = X2
Y1 = Y2
for x = -a + 4, 0, 4 do
X2 = display.contentCenterX + x - halfpost
Y2 = display.contentCenterY - math.sqrt((1-(x^2)/(a^2))*b^2) - longside
table.insert(bluX, X2)
table.insert(bluY, Y2)
table.insert(timeTable, segmentTime(segmentLenght(X1, Y1, X2, Y2), v))
X1 = X2
Y1 = Y2
end
X2 = display.contentCenterX + halfpost
Y2 = display.contentCenterY - longside - b
table.insert(bluX, X2)
table.insert(bluY, Y2)
table.insert(timeTable, segmentTime(segmentLenght(X1, Y1, X2, Y2), v)*netTimeK)
X1 = X2
Y1 = Y2
for x = 4, a, 4 do
X2 = display.contentCenterX + x + halfpost
Y2 = display.contentCenterY - math.sqrt((1-(x^2)/(a^2))*b^2) - longside
table.insert(bluX, X2)
table.insert(bluY, Y2)
table.insert(timeTable, segmentTime(segmentLenght(X1, Y1, X2, Y2), v))
X1 = X2
Y1 = Y2
end
X2 = display.contentCenterX + a + halfpost
Y2 = display.contentCenterY
table.insert(bluX, X2)
table.insert(bluY, Y2)
table.insert(timeTable, segmentTime(segmentLenght(X1, Y1, X2, Y2), v))
lenBluX = tableSize(bluX)--lasciami qui
print(bluX[lenBluX])
--redX and redY tables
redX = {display.contentCenterX - a - halfpost, display.contentCenterX - a - halfpost}
redY = {display.contentCenterY, display.contentCenterY + longside}
for x = - a + 4, 0, 4 do
X = display.contentCenterX + x - halfpost
Y = display.contentCenterY + math.sqrt((1-(x^2)/(a^2))*b^2) + longside
table.insert(redX, X)
table.insert(redY, Y)
end
for x = 0, a, 4 do
X = display.contentCenterX + x + halfpost
Y = display.contentCenterY + math.sqrt((1-(x^2)/(a^2))*b^2) + longside
table.insert(redX, X)
table.insert(redY, Y)
end
table.insert(redX, display.contentCenterX + a + halfpost)
table.insert(redY, display.contentCenterY)
--bluLine, bluTable and upBound physics
local bluLine = display.newLine(display.contentCenterX - a - halfpost, display.contentCenterY, display.contentCenterX - a - halfpost, display.contentCenterY - longside)
bluLine.strokeWidth = strokeWidth
if (global.fieldType==2) then
bluLine:setStrokeColor(0, 1, 0, 0.6)
else
--bluLine:setStrokeColor(0, 0, 1, 0.4)
bluLine.alpha=0
end
bluTableL = {display.contentCenterX - a - halfpost, display.contentCenterY, display.contentCenterX - a - halfpost, display.contentCenterY - longside}
for x = -a + 1, 0 do
X = display.contentCenterX + x - halfpost
Y = display.contentCenterY - math.sqrt((1-(x^2)/(a^2))*b^2) - longside
bluLine:append(X,Y)
table.insert(bluTableL, X)
table.insert(bluTableL, Y)
end
for x = 0, a do
X = display.contentCenterX + x + halfpost
Y = display.contentCenterY - math.sqrt((1-(x^2)/(a^2))*b^2) - longside
bluLine:append(X,Y)
table.insert(bluTableR, X)
table.insert(bluTableR, Y)
end
bluLine:append(display.contentCenterX + a + halfpost, display.contentCenterY)
table.insert(bluTableR, display.contentCenterX + a + halfpost)
table.insert(bluTableR, display.contentCenterY)
upBoundL = display.newRect(0,0,21,21)
upBoundL.alpha = 0
physics.addBody(upBoundL, "static", {chain = bluTableL, filter = upperBoundCollisionFilter})
upBoundR = display.newRect(0,0,21,21)
upBoundR.alpha = 0
physics.addBody(upBoundR, "static", {chain = bluTableR, filter = upperBoundCollisionFilter})
--redLine, redTable and lowBound physics
local redLine = display.newLine(display.contentCenterX - a - halfpost, display.contentCenterY, display.contentCenterX - a - halfpost, display.contentCenterY + longside)
redLine.strokeWidth = strokeWidth
if (global.fieldType==3) then
redLine:setStrokeColor(153, 0, 153, 0.4)
elseif (global.fieldType==2) then
redLine:setStrokeColor(1, 0, 0, 0.6)
else
--redLine:setStrokeColor(1, 0, 0, 0.4)
redLine.alpha=0
end
redTableL = {display.contentCenterX - a - halfpost, display.contentCenterY, display.contentCenterX - a - halfpost, display.contentCenterY + longside}
for x = -a + 1, 0 do
X = display.contentCenterX + x - halfpost
Y = display.contentCenterY + math.sqrt((1-(x^2)/(a^2))*b^2) + longside
redLine:append(X,Y)
table.insert(redTableL, X)
table.insert(redTableL, Y)
end
for x = 0, a do
X = display.contentCenterX + x + halfpost
Y = display.contentCenterY + math.sqrt((1-(x^2)/(a^2))*b^2) + longside
redLine:append(X,Y)
table.insert(redTableR, X)
table.insert(redTableR, Y)
end
redLine:append(display.contentCenterX + a + halfpost, display.contentCenterY)
table.insert(redTableR, display.contentCenterX + a + halfpost)
table.insert(redTableR, display.contentCenterY)
lowBoundL = display.newRect(0,0,21,21)
lowBoundL.alpha = 0
physics.addBody(lowBoundL, "static", {chain = redTableL, filter = lowerBoundCollisionFilter})
lowBoundR = display.newRect(0,0,21,21)
lowBoundR.alpha = 0
physics.addBody(lowBoundR, "static", {chain = redTableR, filter = lowerBoundCollisionFilter})
--nets physics rectangles
local upperNet = display.newRect(display.contentCenterX, display.contentCenterY - b - longside, 2*halfpost, strokeWidth)
local lowerNet = display.newRect(display.contentCenterX, display.contentCenterY + b + longside, 2*halfpost, strokeWidth)
upperNet.alpha = 0
lowerNet.alpha = 0
physics.addBody(upperNet, "static", {filter = upperNetCollisionFilter})
physics.addBody(lowerNet, "static", {filter = LowerNetCollisionFilter})
--> SCORES
if (global.fieldType==3) then
player1Score = display.newText('0',display.contentCenterX, display.contentHeight*80/100, 'Courier-Bold',display.contentHeight*20/100)
player1Score:setTextColor(153, 0, 153, 0.4)
else
player1Score = display.newText('0',display.contentCenterX, display.contentHeight*80/100, 'Courier-Bold',display.contentHeight*20/100)
player1Score:setTextColor(1, 0, 0, 0.4)
end
if (global.fieldType==2) then
player2Score = display.newText('0', display.contentCenterX, display.contentHeight*18/100, 'Courier-Bold', display.contentHeight*20/100)
player2Score:setTextColor(0, 1, 0, 0.4)
else
player2Score = display.newText('0', display.contentCenterX, display.contentHeight*18/100, 'Courier-Bold', display.contentHeight*20/100)
player2Score:setTextColor(0, 0, 1, 0.4)
end
--> BALL
if(global.ballType==1) then
ball = display.newImageRect( "balls/ball1.png", ballDim, ballDim)
ball.x = display.contentCenterX
ball.y = display.contentCenterY
physics.addBody( ball, "dynamic", {radius=ballDim/2, bounce=1, filter = ballCollisionFilter})
elseif(global.ballType==2) then
ball = display.newImageRect( "balls/ball2.png", ballDim, ballDim)
ball.x = display.contentCenterX
ball.y = display.contentCenterY
physics.addBody( ball, "dynamic", {radius=ballDim/2, bounce=1, filter = ballCollisionFilter})
elseif(global.ballType==3) then
ball = display.newImageRect( "balls/ball3.png", ballDim, ballDim)
ball.x = display.contentCenterX
ball.y = display.contentCenterY
physics.addBody( ball, "dynamic", {radius=ballDim/2, bounce=1, filter = ballCollisionFilter})
elseif(global.ballType==4) then
ball = display.newImageRect( "balls/ball4.png", ballDim, ballDim)
ball.x = display.contentCenterX
ball.y = display.contentCenterY
physics.addBody( ball, "dynamic", {radius=ballDim/2, bounce=1, filter = ballCollisionFilter})
elseif(global.ballType==5) then
ball = display.newImageRect( "balls/ball5.png", ballDim, ballDim)
ball.x = display.contentCenterX
ball.y = display.contentCenterY
physics.addBody( ball, "dynamic", {radius=ballDim/2, bounce=1, filter = ballCollisionFilter})
else
ball = display.newCircle(display.contentCenterX, display.contentCenterY, ballDim/2)
ball:setFillColor(1)
physics.addBody(ball, "dynamic", {radius=ballDim/2, bounce=1, filter = ballCollisionFilter})
end
--> PLAYERS
player1 = display.newCircle(display.contentCenterX, display.contentCenterY + b + longside, pdim)
player1:setFillColor(1, 0, 0, 1)
physics.addBody(player1, "dynamic", {radius=pdim/2, bounce=1, filter = redPlayerCollisionFilter})
player2 = display.newCircle(display.contentCenterX - a - halfpost, display.contentCenterY, pdim)
player2:setFillColor(0, 0, 1, 1)
physics.addBody(player2, "dynamic", {radius=pdim/2, bounce=1, filter = bluPlayerCollisionFilter})
onCompleteMove(i) -- start moving
--> BUTTONS
button2 = display.newImageRect( "buttons/bottone1_prova.png", 150, 150 )
button2.x = display.contentWidth*90/100
button2.y = display.contentHeight*103/100
button1 = display.newImageRect( "buttons/bottone2_prova.png", 150, 150 )
button1.x = display.contentWidth*10/100
button1.y = display.contentHeight*103/100
restartBtn = display.newImageRect( "buttons/restart_round.png", display.contentWidth*20/100, display.contentWidth*20/100)
restartBtn.x = display.contentWidth*92/100
restartBtn.y = display.contentWidth*0,05/100
menuBtn=display.newImageRect('buttons/menu_round.png', display.contentWidth*20/100, display.contentWidth*20/100)
menuBtn.x = display.contentWidth*8/100
menuBtn.y = display.contentWidth*0,05/100
menuBtn:addEventListener('tap', menuView)
--button functions
local function reset()
ball.x = display.contentCenterX
ball.y = display.contentCenterY
ball.isAwake = false
end
local function removeGoal()
display.remove(goal)
end
local flag=1
local function check()
if(flag==1) then
if(ball.y > display.contentHeight) then
goal = display.newImageRect("goal.png", 300, 200)
goal.x = display.contentCenterX
goal.y = display.contentCenterY
if (global.soundFlag==0) then
audio.play(goalSound, {channel=5})
end
timer.performWithDelay (1000, removeGoal)
player2Score.text = tostring(tonumber(player2Score.text) + 1)
ball.x = display.contentCenterX
ball.y = display.contentCenterY
ball.isAwake = false
score = score+1
return score
elseif(ball.y < -5) then
goal = display.newImageRect("goal.png", display.contentWidth, display.contentHeight)
goal.x = display.contentCenterX
goal.y = display.contentCenterY
if (global.soundFlag==0) then
audio.play(goalSound, {channel=5})
end
timer.performWithDelay (1000, removeGoal)
player1Score.text = tostring(tonumber(player1Score.text) + 1)
ball.x = display.contentCenterX
ball.y = display.contentCenterY
ball.isAwake = false
score = score+1
return score
end
end
end
--> EVENT LISTENERS
--event listeners for powerup4_sound
--timer.performWithDelay(9000, powerup, 0)
--event listerner for goal check function
Runtime:addEventListener("enterFrame", check)
--event listeners for buttons
button2:addEventListener( "tap", shoot)
button1:addEventListener( "tap", invert)
restartBtn:addEventListener( "tap", reset)
-- all display objects must be inserted into group
sceneGroup:insert( background )
if (porta1) then
sceneGroup:insert( porta1 )
end
if (porta2) then
sceneGroup:insert( porta2 )
end
sceneGroup:insert( redLine )
sceneGroup:insert( bluLine )
sceneGroup:insert( upperNet )
sceneGroup:insert( lowerNet )
sceneGroup:insert( player1Score )
sceneGroup:insert( player2Score )
sceneGroup:insert( ball )
sceneGroup:insert( player1 )
sceneGroup:insert( player2 )
sceneGroup:insert( button1 )
sceneGroup:insert( button2 )
sceneGroup:insert( restartBtn )
sceneGroup:insert( menuBtn )
end
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--[[
function scene:show( event )
local sceneGroup = self.view
local phase = event.phase
if phase == "will" then
-- Called when the scene is still off screen and is about to move on screen
elseif phase == "did" then
-- Called when the scene is now on screen
physics.start()
end
end
]]
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
function scene:hide( event )
local sceneGroup = self.view
local phase = event.phase
if event.phase == "will" then
-- Called when the scene is on screen and is about to move off screen
-- INSERT code here to pause the scene
physics.stop()
composer.removeScene("gameView") -- rimuove completamente la scena
elseif phase == "did" then
-- Called when the scene is now off screen
end
end
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
function scene:destroy( event )
local sceneGroup = self.view
package.loaded[physics] = nil
physics = nil
end
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--> Listener setup
scene:addEventListener( "create", scene )
scene:addEventListener( "show", scene )
scene:addEventListener( "hide", scene )
scene:addEventListener( "destroy", scene )
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
return scene
|
local nvim_command = vim.api.nvim_command
local fn = vim.fn
local stdpath = fn.stdpath
local empty = fn.empty
local glob = fn.glob
local system = fn.system
-- Bootstrap here.
local install_path = stdpath('data')..'/site/pack/packer/start/packer.nvim'
local packer_bootstrap
-- 0 if it is empty, 1 if it's not. Why not booleans? Compatability?
if empty(glob(install_path)) > 0 then
-- When run with a list it doesn't run it inside a shell.
packer_bootstrap = system({'git', 'clone', '--depth', '1', 'https://github.com/wbthomason/packer.nvim', install_path})
nvim_command('packadd packer.nvim')
end
nvim_command('packadd packer.nvim')
local packer = require 'packer'
-- 'use' and 'use_rocks' are not actually injected here, packer is inserting
-- them into the environment.
return packer.startup(function(use)
use('wbthomason/packer.nvim')
use {
'mhinz/vim-startify',
config = function()
require('drhayes.startify').setup()
end,
}
-- Telescope.
use {
'nvim-telescope/telescope.nvim',
requires = {{'nvim-lua/popup.nvim'}, {'nvim-lua/plenary.nvim'}},
config = function()
require 'drhayes.telescope'
end,
}
use('nvim-telescope/telescope-fzy-native.nvim')
use('nvim-telescope/telescope-fzf-writer.nvim')
use('nvim-telescope/telescope-packer.nvim')
use('nvim-telescope/telescope-github.nvim')
use('nvim-telescope/telescope-symbols.nvim')
use 'nvim-telescope/telescope-dap.nvim'
use('cwebster2/github-coauthors.nvim')
-- fzf.
use {'junegunn/fzf', run = './install --all'}
use 'junegunn/fzf.vim'
-- Treesitter.
use {
'nvim-treesitter/nvim-treesitter',
run = ':TSUpdate',
config = function()
require('drhayes.treesitter').setup()
end,
}
use 'nvim-treesitter/nvim-treesitter-textobjects'
use 'nvim-treesitter/nvim-treesitter-refactor'
use {
'romgrk/nvim-treesitter-context',
requires = {'nvim-treesitter/nvim-treesitter'}
}
use 'p00f/nvim-ts-rainbow'
use 'windwp/nvim-ts-autotag'
use {
'SmiteshP/nvim-gps',
requires = {'nvim-treesitter/nvim-treesitter'},
config = function()
require('drhayes.nvimgps').setup()
end,
}
--------------
-- THEME CHURN
--------------
-- use({
-- 'catppuccin/nvim',
-- as = 'catppuccin',
-- config = function()
-- vim.cmd[[colorscheme catppuccin]]
-- end,
-- })
-- use({
-- 'lalitmee/cobalt2.nvim',
-- requires = 'tjdevries/colorbuddy.nvim',
-- })
-- vim.g.monokaipro_filter = 'machine'
-- use({
-- 'https://gitlab.com/__tpb/monokai-pro.nvim',
-- -- 'mhartington/oceanic-next',
-- config = function()
-- vim.cmd[[syntax enable]]
-- vim.cmd[[colorscheme monokaipro]]
-- end,
-- })
vim.g.tokyonight_style = 'storm'
vim.g.tokyonight_colors = {
comment = '#8080a0',
}
use({
'folke/tokyonight.nvim',
config = function()
require('drhayes.colors').setup()
end
})
-- 'mhartington/oceanic-next',
--'rmehri01/onenord.nvim',
--'nanotech/jellybeans.vim',
--'Pocco81/Catppuccino.nvim',
-- 'GertjanReynaert/cobalt2-vim-theme',
-- 'GlennLeo/cobalt2',
-- requires = {'sheerun/vim-polyglot'},
-- config = function()
-- vim.cmd[[colorscheme tokyonight]]
--vim.cmd[[colorscheme onenord]]
-- vim.cmd[[syntax enable]]
-- vim.cmd[[let g:oceanic_next_terminal_bold = 1]]
-- vim.cmd[[let g:oceanic_next_terminal_italic = 1]]
-- vim.cmd[[colorscheme OceanicNext]]
-- require('drhayes.theme').setup()
-- end
-- })
-- https://github.com/phanviet/vim-monokai-pro
-- https://github.com/haishanh/night-owl.vim
-- https://github.com/dracula/vim
-- Golang.
use 'fatih/vim-go'
-- Github issue stuff.
use 'pwntester/octo.nvim'
-- debugging
use 'mfussenegger/nvim-dap'
use 'theHamsta/nvim-dap-virtual-text'
use { 'rcarriga/nvim-dap-ui', requires = {'mfussenegger/nvim-dap'} }
-- LSP.
use {
'neovim/nvim-lspconfig',
'williamboman/nvim-lsp-installer',
}
use { "folke/lua-dev.nvim" }
-- use { "kosayoda/nvim-lightbulb" }
use { "tami5/lspsaga.nvim" }
use { "nvim-lua/lsp-status.nvim" }
use { "ray-x/lsp_signature.nvim" }
use { "jose-elias-alvarez/null-ls.nvim" }
use { "folke/lsp-trouble.nvim",
requires = "kyazdani42/nvim-web-devicons",
config = "require('drhayes.trouble').setup()",
}
-- What keys am I pressing?
use {
'folke/which-key.nvim',
config = function()
require('drhayes.whichkey').setup()
end,
}
use 'sheerun/vim-polyglot'
-- Tabs at the top.
use {
'akinsho/nvim-bufferline.lua',
requires = {'kyazdani42/nvim-web-devicons'},
config = "require('drhayes.bufferline').setup()",
}
-- Things at the bottom.
use {
'NTBBloodbath/galaxyline.nvim',
branch='main',
requires = {'kyazdani42/nvim-web-devicons'}
}
-- Things on the left side.
use {
'lewis6991/gitsigns.nvim',
requires = {'nvim-lua/plenary.nvim'},
config = "require('drhayes.gitsigns').setup()",
}
-- Trailing whitespace generally sucks.
use {
'ntpeters/vim-better-whitespace',
config = function ()
local g = vim.g
g.better_whitespace_enabled = 1
g.strip_whitespace_on_save = 1
g.strip_whitespace_confirm = 0
end
}
-- Git in neovim?
-- use {
-- 'TimUntersberger/neogit',
-- requires = { 'nvim-lua/plenary.nvim', 'sindrets/diffview.nvim'},
-- config = "require('drhayes.neogit').setup()",
-- }
-- Completion
use {
'hrsh7th/nvim-cmp',
config = function()
require('drhayes.lsp').setup()
require('drhayes.completion').setup()
end,
requires = {
-- 'L3MON4D3/LuaSnip',
-- 'saadparwaiz1/cmp_luasnip',
'hrsh7th/cmp-buffer',
'hrsh7th/cmp-nvim-lsp',
'hrsh7th/cmp-path',
'hrsh7th/cmp-nvim-lua',
'hrsh7th/vim-vsnip',
'hrsh7th/vim-vsnip-integ',
'hrsh7th/cmp-vsnip',
-- 'Saecki/crates.nvim',
'f3fora/cmp-spell',
},
}
use {
'windwp/nvim-autopairs',
config = function ()
require('nvim-autopairs').setup()
end
}
-- Set path searching options.
use 'tpope/vim-apathy'
-- Automatically insert end structures.
-- use 'tpope/vim-endwise'
-- Comments happen a lot.
use 'tpope/vim-commentary'
-- I often surround things with things.
use 'tpope/vim-surround'
-- Who doesn't want a tree view of their filesystem?
-- use { 'kyazdani42/nvim-tree.lua',
-- commit = "f1f1488",
-- config = function()
-- require('drhayes.nvim-tree').setup()
-- end,
--cmd = {"NvimTreeFindFile", "NvimTreeToggle"},
--opt = true
-- }
use 'editorconfig/editorconfig-vim'
use {
'phaazon/hop.nvim',
branch = 'v1', -- optional but strongly recommended
config = function()
-- you can configure Hop the way you like here; see :h hop-config
require('hop').setup({ keys = 'asdghklqwertyuiopzxcvbnmf' })
end
}
use 'fladson/vim-kitty'
use({
'earthly/earthly.vim',
branch = 'main'
})
use 'andymass/vim-matchup'
use 'tpope/vim-unimpaired'
use {
"folke/todo-comments.nvim",
requires = "nvim-lua/plenary.nvim",
config = function()
require("todo-comments").setup {
-- your configuration comes here
-- or leave it empty to use the default settings
-- refer to the configuration section below
}
end
}
use('nathom/filetype.nvim')
use('lepture/vim-jinja')
-- Bootstrap if we don't already have it.
if packer_bootstrap then
require('packer').sync()
end
end)
|
return {
cornecro = {
acceleration = 0.2,
brakerate = 0.75,
buildcostenergy = 1514,
buildcostmetal = 108,
builddistance = 145,
builder = true,
buildpic = "cornecro.dds",
buildtime = 2400,
canassist = false,
canmove = true,
canpatrol = true,
canreclamate = 1,
canresurrect = true,
canstop = 1,
category = "ALL MOBILE SMALL SURFACE UNDERWATER",
collisionvolumeoffsets = "0 -2 1",
collisionvolumescales = "30.5 36 30.5",
collisionvolumetype = "CylY",
corpse = "dead",
defaultmissiontype = "Standby",
description = "Rez Kbot",
explodeas = "BIG_UNITEX",
footprintx = 2,
footprintz = 2,
idleautoheal = 5,
idletime = 60,
losemitheight = 36,
maneuverleashlength = 640,
mass = 109,
maxdamage = 200,
maxslope = 14,
maxvelocity = 2.6,
maxwaterdepth = 22,
mobilestandorders = 1,
movementclass = "KBOT2",
name = "Necro",
noautofire = false,
objectname = "CORNECRO",
radardistance = 50,
radaremitheight = 36,
resurrect = 1,
seismicsignature = 0,
selfdestructas = "BIG_UNIT",
shownanospray = false,
sightdistance = 430,
standingmoveorder = 1,
steeringmode = 2,
turninplaceanglelimit = 140,
turninplacespeedlimit = 1.716,
turnrate = 1118,
unitname = "cornecro",
upright = true,
workertime = 200,
customparams = {
buildpic = "cornecro.dds",
faction = "CORE",
},
featuredefs = {
dead = {
blocking = true,
collisionvolumeoffsets = "0.248977661133 -1.21184884033 0.586555480957",
collisionvolumescales = "33.9485473633 23.5305023193 36.0355987549",
collisionvolumetype = "Box",
damage = 357,
description = "Necro Wreckage",
featuredead = "heap",
footprintx = 2,
footprintz = 2,
metal = 81,
object = "CORNECRO_DEAD",
reclaimable = true,
customparams = {
fromunit = 1,
},
},
heap = {
blocking = false,
damage = 447,
description = "Necro Debris",
footprintx = 2,
footprintz = 2,
metal = 43,
object = "2X2D",
reclaimable = true,
customparams = {
fromunit = 1,
},
},
},
nanocolor = {
[1] = 0.16,
[2] = 0.51,
[3] = 0.51,
},
sfxtypes = {
pieceexplosiongenerators = {
[1] = "piecetrail0",
[2] = "piecetrail1",
[3] = "piecetrail2",
[4] = "piecetrail3",
[5] = "piecetrail4",
[6] = "piecetrail6",
},
},
sounds = {
canceldestruct = "cancel2",
underattack = "warning1",
cant = {
[1] = "cantdo4",
},
count = {
[1] = "count6",
[2] = "count5",
[3] = "count4",
[4] = "count3",
[5] = "count2",
[6] = "count1",
},
ok = {
[1] = "necrok2",
},
select = {
[1] = "necrsel2",
},
},
},
}
|
local draw = require 'lx.draw'
local sys = require 'lx.sys'
local tk = {}
--[[
Widgets:
window manager widget
Window manager
Widows are any widget which determine their own size
box widget
A box that can be:
- scrollable (H/V)
- resizable (H/V)
Has a single child. Can either:
a. constrain the size of the child to the size of the box
b. let the child widget determine its size
Can have a margin (outer margin) with associated outer background color,
a padding (inner margin) with associated background color,
a border with its color
Can have onclick events to implement buttons.
grid widget
A grid widget, organizes its children in a grid, which can make a table or any kind of layout. It:
- resizes its childs and repositions them to make a grid
- accepts when its childs are resized and changes the width of columns
or the height of lines accordingly
- draws borders/spacing between elements
text widget
image widget
border widget
centered widget
text input
text box
text_layout_widget
Positions text widgets and images widgets in a subtle and intelligent manner (lol)
How to make a table:
widget = tk.grid({},
{ { tk.box({h_resizable = true, width = 200}, tk.text("name")),
tk.box({h_resizable = true, width = 100}, tk.text("actions")) },
{ tk.box({padding = 4}, tk.text("file A")),
tk.grid({}, {{ tk.box({padding = 4, border = 1, border_color = red,
on_click = function() do something end}, tk.text("open")) }}) } }
--]]
-- UTIL
function region_operation(reg1, reg2, sel_fun)
local xs = {reg1.x, reg1.x + reg1.w, reg2.x, reg2.x + reg2.w}
local ys = {reg1.y, reg1.y + reg1.h, reg2.y, reg2.y + reg2.h}
table.sort(xs)
table.sort(ys)
local pieces = {}
local function add_region(x, y, w, h)
for i, r in pairs(pieces) do
if r.y == y and r.h == h and r.x + r.w == x then
table.remove(pieces, i)
add_region(r.x, r.y, r.w + w, r.h)
return
elseif r.x == x and r.w == w and r.y + r.h == y then
table.remove(pieces, i)
add_region(r.x, r.y, r.w, r.h + h)
return
end
end
table.insert(pieces, {x = x, y = y, w = w, h = h})
end
for i = 1, 3 do
for j = 1, 3 do
local x0, x1, y0, y1 = xs[i], xs[i+1], ys[j], ys[j+1]
if x1 > x0 and y1 > y0 then
if sel_fun(x0, x1, y0, y1) then
add_region(x0, y0, x1 - x0, y1 - y0)
end
end
end
end
return pieces
end
function region_diff(reg1, reg2)
return region_operation(reg1, reg2,
function(x0, x1, y0, y1)
return (x0 >= reg1.x and x0 < reg1.x + reg1.w and y0 >= reg1.y and y0 < reg1.y + reg1.h)
and not (x0 >= reg2.x and x0 < reg2.x + reg2.w and y0 >= reg2.y and y0 < reg2.y + reg2.h)
end
)
end
function region_inter(reg1, reg2)
return region_operation(reg1, reg2,
function(x0, x1, y0, y1)
return (x0 >= reg1.x and x0 < reg1.x + reg1.w and y0 >= reg1.y and y0 < reg1.y + reg1.h)
and (x0 >= reg2.x and x0 < reg2.x + reg2.w and y0 >= reg2.y and y0 < reg2.y + reg2.h)
end
)
end
function region_union(reg1, reg2)
return region_operation(reg1, reg2,
function(x0, x1, y0, y1)
return (x0 >= reg1.x and x0 < reg1.x + reg1.w and y0 >= reg1.y and y0 < reg1.y + reg1.h)
or (x0 >= reg2.x and x0 < reg2.x + reg2.w and y0 >= reg2.y and y0 < reg2.y + reg2.h)
end
)
end
-- ACTUAL TK STUFF
function tk.widget(width, height, opts)
local w = {
x = 0,
y = 0,
width = width,
height = height,
}
if opts then
for k, v in pairs(opts) do
w[k] = v
end
end
function w:resize(width, height)
if width then w.width = width end
if width then w.height = height end
end
function w:get_draw_buffer(x0, y0, w, h)
-- Replaced by parent by a function that returns the buffer for
return nil
end
function w:finalize_draw_buffer()
if self.parent ~= nil then
self.parent:finalize_draw_buffer()
end
end
function w:redraw(x0, y0, buf)
-- Replaced by widget code by a function that does the actual drawing
end
function w:redraw_sub(x0, y0, buf, subwidget)
local region = {x = x0, y = y0, w = buf:width(), h = buf:height()}
local subregion = {x = subwidget.x, y = subwidget.y, w = subwidget.width, h = subwidget.height}
local inter = region_inter(region, subregion)
for _, z in pairs(inter) do
subwidget:redraw(z.x - subwidget.x, z.y - subwidget.y, buf:sub(z.x - x0, z.y - y0, z.w, z.h))
end
end
function w:on_mouse_down(x, y, lb, rb, mb)
if lb then
-- Handler for mouse down event
self.left_click_valid = true
end
end
function w:on_mouse_up(x, y, lb, rb, mb)
-- Handler for mouse up event
if lb and self.left_click_valid then
self:on_click()
end
end
function w:on_mouse_move(prev_x, prev_y, new_x, new_y)
-- Handler for mouse move event
self.left_click_valid = false
end
function w:on_click()
end
function w:on_text_input(char)
-- Handler for text input
end
function w:on_key_down(key)
-- Handler for key press
end
function w:on_key_up(key)
-- Handler for key release
end
return w
end
function tk.init(gui, root_widget)
if tk.root_widget ~= nil then return end
tk.root_widget = root_widget
if root_widget.parent ~= nil then return end
root_widget.parent = gui
tk.fonts = {
["vera.ttf"] = draw.load_ttf_font("sys:/fonts/vera.ttf"),
["veraserif.ttf"] = draw.load_ttf_font("sys:/fonts/veraserif.ttf"),
["veramono.ttf"] = draw.load_ttf_font("sys:/fonts/veramono.ttf"),
}
tk.fonts.default = tk.fonts["vera.ttf"]
function tk.rgb(r, g, b)
return gui.surface:rgb(r, g, b)
end
root_widget:resize(gui.surface:width(), gui.surface:height())
gui.on_key_down = function(key) root_widget:on_key_down(key) end
gui.on_key_up = function(key) root_widget:on_key_up(key) end
gui.on_text_input = function(key) root_widget:on_text_input(char) end
gui.on_mouse_move = function(ox, oy, nx, ny) root_widget:on_mouse_move(ox, oy, nx, ny) end
gui.on_mouse_down = function(lb, rb, mb) root_widget:on_mouse_down(gui.mouse_x, gui.mouse_y, lb, rb, mb) end
gui.on_mouse_up = function(lb, rb, mb) root_widget:on_mouse_up(gui.mouse_x, gui.mouse_y, lb, rb, mb) end
function root_widget:get_draw_buffer(x0, y0, w, h)
if gui.cursor_visible and #region_inter({x=x0, y=y0, w=w, h=h},
{x=gui.mouse_x, y=gui.mouse_y, w=gui.cursor:width(), h=gui.cursor:height()})>0
then
tk.must_reshow_cursor_on_finalize = true
gui.hide_cursor()
end
return gui.surface:sub(x0, y0, w, h)
end
function root_widget:finalize_draw_buffer()
if tk.must_reshow_cursor_on_finalize then
tk.must_reshow_cursor_on_finalize = false
gui.show_cursor()
end
end
root_widget:redraw(0, 0, root_widget:get_draw_buffer(0, 0, root_widget.width, root_widget.height))
root_widget:finalize_draw_buffer()
end
-- #### #### STANDARD WIDGETS #### ####
function tk.image(a, b)
local img = b or a
local opts = b and a or {}
local image = tk.widget(img:width(), img:height(), opts)
image.img = img
function image:resize(width, height)
if width then
self.width = width
if self.width < self.img:width() then self.width = self.img:width() end
end
if height then
self.height = height
if self.height < self.img:height() then self.height = self.img:height() end
end
end
function image:redraw(x0, y0, buf)
local step = 20
local halfstep = 10
for x = x0 - (x0 % step), x0 + buf:width(), step do
for y = y0 - (y0 % step), y0 + buf:height(), step do
buf:fillrect(x - x0, y - y0, halfstep, halfstep, buf:rgb(150, 150, 150))
buf:fillrect(x - x0 + halfstep, y - y0 + halfstep, halfstep, halfstep, buf:rgb(150, 150, 150))
buf:fillrect(x - x0 + halfstep, y - y0, halfstep, halfstep, buf:rgb(170, 170, 170))
buf:fillrect(x - x0, y - y0 + halfstep, halfstep, halfstep, buf:rgb(170, 170, 170))
end
end
if x0 < self.img:width() and y0 < self.img:height() then
buf:blit(0, 0, self.img:sub(x0, y0, self.img:width(), self.img:height()))
end
end
return image
end
function tk.text(a, b)
local text = b or a
local opts = b and a or {}
-- Some defaults
opts.text_size = opts.text_size or 16
opts.padding = opts.padding or 2
opts.background = opts.background or tk.rgb(255, 255, 255)
opts.color = opts.color or tk.rgb(0, 0, 0)
opts.line_spacing = opts.line_spacing or 1
if opts.word_wrap == nil then opts.word_wrap = true end
opts.font = opts.font or tk.fonts.default
opts.dy = opts.dy or -(opts.text_size//8)
local txt = tk.widget(100, #string.split(text, "\n")*(opts.text_size + opts.line_spacing) - opts.line_spacing + 2*opts.padding, opts)
txt.text = text
function txt:redraw(x0, y0, buf)
local lines = string.split(self.text, "\n")
buf:fillrect(0, 0, buf:width(), buf:height(), self.background)
local acceptable_surface = region_inter({x = x0, y = y0, w = buf:width(), h = buf:height()},
{x = self.padding, y = self.padding, w = self.width - 2*self.padding, h = self.height - 2*self.padding})
for _, s in pairs(acceptable_surface) do
local buf2 = buf:sub(s.x - x0, s.y - y0, s.w, s.h)
for i = 1, #lines do
-- TODO word wrap
buf2:write(self.padding - s.x, (i-1) * (self.text_size + self.line_spacing) + self.padding - s.y + self.dy,
lines[i], self.font, self.text_size, self.color)
end
end
end
return txt
end
function tk.box(a, b)
local content = b or a
local opts = b and a or {}
-- Some defaults
opts.hresize = opts.hresize or false
opts.vresize = opts.vresize or false
opts.hscroll = opts.hscroll or false
opts.vscroll = opts.vscroll or false
opts.center_content = opts.center_content or false
opts.constrain_size = opts.constrain_size or nil
opts.background_color = opts.background_color or tk.rgb(190, 190, 190)
opts.control_size = 12
local box = tk.widget(content.width, content.height, opts)
box.content = content
if box.center_content then
if box.width > box.content.width then
box.content.x = (box.width - box.content.width) // 2
else
box.content.x = 0
end
if box.height > box.content.height then
box.content.y = (box.height - box.content.height) // 2
else
box.content.y = 0
end
else
box.content.x = 0
box.content.y = 0
end
function box:resize(width, height)
local ow, oh = self.width, self.height
if self.constrain_size then
self.content:resize(width, height)
self.width = content.width
self.height = content.height
else
if width then self.width = width end
if height then self.height = height end
if self.center_content then
if self.width > self.content.width then
self.content.x = (self.width - self.content.width) // 2
else
self.content.x = math.min(0, math.max(-(self.content.width - self.width), self.content.x))
end
if self.height > self.content.height then
self.content.y = (self.height - self.content.height) // 2
else
self.content.y = math.min(0, math.max(-(self.content.height - self.height), self.content.y))
end
end
end
if self.parent and (self.width ~= ow or self.height ~= oh) then
self.parent:child_resized(self)
end
end
function box:move_content(x, y)
local ox, oy = self.content.x, self.content.y
if x then self.content.x = math.min(0, math.max(-(self.content.width - self.width), x)) end
if y then self.content.y = math.min(0, math.max(-(self.content.height - self.height), y)) end
if self.parent and (self.content.x ~= ox or self.content.y ~= oy) then
self.parent:child_resized(self)
end
end
function box:barcalc(pos, insize, outsize)
local csz = self.control_size
local barsize = (outsize - csz) * outsize // insize
local baravail = outsize - csz - barsize
local barpos = -pos * baravail // (insize - outsize)
return barsize, barpos, baravail
end
function box:redraw(x0, y0, buf)
local csz = self.control_size
local acceptable_surface = region_inter({x = x0, y = y0, w = buf:width(), h = buf:height()},
{x = self.content.x, y = self.content.y,
w = self.content.width, h = self.content.height})
for _, s in pairs(acceptable_surface) do
local buf2 = buf:sub(s.x - x0, s.y - y0, s.w, s.h)
self.content:redraw(s.x - self.content.x, s.y - self.content.y, buf2)
end
local background_surface = region_diff({x = x0, y = y0, w = buf:width(), h = buf:height()},
{x = self.content.x, y = self.content.y,
w = self.content.width, h = self.content.height})
for _, s in pairs(background_surface) do
buf:fillrect(s.x - x0, s.y - y0, s.w, s.h, self.background_color)
end
if self.vresize or self.hresize then
buf:rect(self.width - csz - x0, self.height - csz - y0, csz, csz, buf:rgb(0, 0, 0))
buf:fillrect(self.width - csz + 1 - x0, self.height - csz + 1 - y0, csz - 2, csz - 2, buf:rgb(255, 255, 255))
end
if self.hscroll and self.width < self.content.width then
local barsize, barpos = self:barcalc(self.content.x, self.content.width, self.width)
buf:fillrect(barpos + 4 - x0, self.height - csz + 2 - y0, barsize - 8, csz - 4, buf:rgb(0, 0, 0))
end
if self.vscroll and self.height < self.content.height then
local barsize, barpos = self:barcalc(self.content.y, self.content.height, self.height)
buf:fillrect(self.width - csz + 2 - x0, barpos + 4 - y0, csz - 4, barsize - 8, buf:rgb(0, 0, 0))
end
end
function box:on_mouse_down(x, y, lb, mb, rb)
local csz = self.control_size
if lb and (self.vresize or self.hresize) and x >= self.width - csz and y >= self.height - csz then
self.resizing = true
self.resize_initw = self.width
self.resize_inith = self.height
self.resize_initmx = x
self.resize_initmy = y
elseif lb and self.vscroll and x >= self.width - csz and self.height < self.content.height then
local barsize, barpos = self:barcalc(self.content.y, self.content.height, self.height)
if y < barpos then
self:move_content(nil, self.content.y + self.height * 2 // 3)
elseif y >= barpos + barsize then
self:move_content(nil, self.content.y - self.height * 2 // 3)
else
self.vscrolling = true
self.vscrolling_inity = self.content.y
self.vscrolling_initmy = y
end
elseif lb and self.hscroll and y >= self.height - csz and self.width < self.content.width then
local barsize, barpos = self:barcalc(self.content.x, self.content.width, self.width)
if x < barpos then
self:move_content(self.content.x + self.width * 2 // 3, nil)
elseif x >= barpos + barsize then
self:move_content(self.content.x - self.width * 2 // 3, nil)
else
self.hscrolling = true
self.hscrolling_initx = self.content.x
self.hscrolling_initmx = x
end
else
self.content:on_mouse_down(x - self.content.x, y - self.content.y, lb, mb, rb)
end
end
function box:on_mouse_up(x, y, lb, mb, rb)
if lb and self.resizing then
self.resizing = false
elseif lb and self.vscrolling then
self.vscrolling = false
elseif lb and self.hscrolling then
self.hscrolling = false
else
self.content:on_mouse_up(x - self.content.x, y - self.content.y, lb, mb, rb)
end
end
function box:on_mouse_move(px, py, nx, ny)
if self.resizing then
local w = self.hresize and self.resize_initw + nx - self.resize_initmx
local h = self.vresize and self.resize_inith + ny - self.resize_initmy
self:resize(w, h)
elseif self.vscrolling then
local barsize, barpos, baravail = self:barcalc(self.content.y, self.content.height, self.height)
self:move_content(nil, self.vscrolling_inity - (ny - self.vscrolling_initmy) * (self.content.height - self.height) // baravail)
elseif self.hscrolling then
local barsize, barpos, baravail = self:barcalc(self.content.x, self.content.width, self.width)
self:move_content(self.hscrolling_initx - (nx - self.hscrolling_initmx) * (self.content.width - self.width) // baravail)
else
self.content:on_mouse_move(px - self.content.x, py - self.content.y, nx - self.content.x, ny - self.content.y)
end
end
return box
end
-- #### #### WINDOW MANAGER WIDGET #### ####
function tk.window_manager()
local wm = tk.widget(100, 100)
wm.windows = {} -- Last = on top
wm.window_pos = {}
wm.mouse_lb = false
wm.mouse_rb = false
wm.mouse_mb = false
wm.mouse_win = nil
function wm:add(content, title, x, y)
local win = tk.widget(content.width + 2, content.height + 22)
win.parent = self
win.x = x or 24
win.y = y or 24
win.title = title
win.visible = true
table.insert(self.windows, win)
self.window_pos[win] = {x = win.x, y = win.y, h = win.height, w = win.width}
win.content = content
content.parent = win
content.x = 1
content.y = 21
function content:get_draw_buffer(x0, y0, w, h)
if x0 + w > self.width then w = self.width - x0 end
if y0 + h > self.height then h = self.height - y0 end
return win:get_draw_buffer(x0 + 1, y0 + 21, w, h)
end
function win:get_draw_buffer(x0, y0, w, h)
-- TODO clipping etc
end
function win:child_resized(c)
assert(c == self.content)
local reg1 = wm.window_pos[self]
self.width = c.width + 2
self.height = c.height + 22
wm.window_pos[self] = {x = self.x, y = self.y, w = self.width, h = self.height}
local reg2 = wm.window_pos[self]
local pieces = region_union(reg1, reg2)
for _, p in pairs(pieces) do
wm:redraw_region(p.x, p.y, p.w, p.h)
end
end
function win:redraw(x0, y0, buf)
self:redraw_sub(x0, y0, buf, self.content)
buf:rect(-x0, -y0, self.width, self.height, buf:rgb(255, 128, 0))
buf:fillrect(-x0+1, -y0+1, win.width-2, 20, buf:rgb(200, 200, 200))
if win.title then
buf:write(-x0+2, -y0+2, win.title, tk.fonts.default, 16, buf:rgb(0, 0, 0))
end
end
function win:on_mouse_down(x, y, lb, rb, mb)
if y < 22 and lb then
self.moving = true
else
self.content:on_mouse_down(x-1, y-21, lb, rb, mb)
end
end
function win:on_mouse_up(x, y, lb, rb, mb)
if self.moving then
self.moving = false
else
self.content:on_mouse_up(x-1, y-21, lb, rb, mb)
end
end
function win:on_mouse_move(px, py, nx, ny)
if self.moving then
local reg1 = wm.window_pos[self]
self.x = self.x + nx - px
self.y = self.y + ny - py
wm.window_pos[self] = {x = self.x, y = self.y, w = self.width, h = self.height}
local reg2 = wm.window_pos[self]
local pieces = region_union(reg1, reg2)
for _, p in pairs(pieces) do
wm:redraw_region(p.x, p.y, p.w, p.h)
end
else
self.content:on_mouse_move(px-1, py-21, nx-1, ny-21)
end
end
self:redraw_win(win)
end
function wm:remove(win)
if win.parent ~= self then return end
win.parent = nil
win.get_draw_buffer = function() return nil end
win.content.parent = nil
win.content.get_draw_buffer = function() return nil end
for i, w2 in pairs(self.windows) do
if w2 == win then
table.remove(self.windows, i)
return
end
end
end
function wm:redraw_region(x, y, w, h)
local ok = region_inter({x = 0, y = 0, w = self.width, h = self.height},
{x = x, y = y, w = w, h = h})
for _, r in pairs(ok) do
self:redraw(r.x, r.y, self:get_draw_buffer(r.x, r.y, r.w, r.h))
self:finalize_draw_buffer()
end
end
function wm:redraw_win(win)
self:redraw_region(win.x, win.y, win.width, win.height)
end
function wm:redraw(x0, y0, buf)
local remaining = { {x = x0, y = y0, w = buf:width(), h = buf:height()} }
-- TODO do this in inverse order and clip regions of hidden windows
-- so that less redrawing is done
for i = #self.windows, 1, -1 do
win = self.windows[i]
if win.visible then
local remaining2 = {}
local win_reg = {x = win.x, y = win.y, w = win.width, h = win.height}
for _, reg in pairs(remaining) do
local draw_to = region_inter(reg, win_reg)
for _, reg2 in pairs(draw_to) do
win:redraw(reg2.x - win.x, reg2.y - win.y, buf:sub(reg2.x - x0, reg2.y - y0, reg2.w, reg2.h))
end
local remain_to = region_diff(reg, win_reg)
for _, reg2 in pairs(remain_to) do
table.insert(remaining2, reg2)
end
end
remaining = remaining2
end
end
-- Draw background
function draw_background(x0, y0, buf)
local step = 32
local halfstep = 16
for x = x0 - (x0 % step), x0 + buf:width(), step do
for y = y0 - (y0 % step), y0 + buf:height(), step do
buf:fillrect(x - x0, y - y0, halfstep, halfstep, buf:rgb(110, 110, 140))
buf:fillrect(x - x0 + halfstep, y - y0 + halfstep, halfstep, halfstep, buf:rgb(110, 110, 140))
buf:fillrect(x - x0 + halfstep, y - y0, halfstep, halfstep, buf:rgb(110, 140, 110))
buf:fillrect(x - x0, y - y0 + halfstep, halfstep, halfstep, buf:rgb(110, 140, 110))
end
end
end
for _, reg in pairs(remaining) do
draw_background(reg.x, reg.y, buf:sub(reg.x - x0, reg.y - y0, reg.w, reg.h))
end
end
function wm:find_win(x, y)
for i = #self.windows, 1, -1 do
local win = self.windows[i]
if win.visible and x >= win.x and y >= win.y and x < win.x + win.width and y < win.y + win.height then
return win
end
end
return nil
end
function wm:on_mouse_down(x, y, lb, rb, mb)
self.mouse_lb = self.mouse_lb or lb
self.mouse_rb = self.mouse_rb or rb
self.mouse_mb = self.mouse_mb or mb
local on_win = self:find_win(x, y)
if self.mouse_win then
on_win = self.mouse_win
else
self.mouse_win = on_win
end
if on_win then
sys.dbg_print(string.format("Mouse down on window %s\n", on_win.title))
if self.windows[#self.windows] ~= on_win then
for i, w in pairs(self.windows) do
if w == on_win then
table.remove(self.windows, i)
break
end
end
table.insert(self.windows, on_win)
self:redraw_win(on_win)
end
on_win:on_mouse_down(x - on_win.x, y - on_win.y, lb, rb, mb)
end
end
function wm:on_mouse_up(x, y, lb, rb, mb)
local on_win = self.mouse_win or self:find_win(x, y)
if on_win then
on_win:on_mouse_up(x - on_win.x, y - on_win.y, lb, rb, mb)
end
self.mouse_lb = self.mouse_lb and not lb
self.mouse_rb = self.mouse_rb and not rb
self.mouse_mb = self.mouse_mb and not mb
if not (self.mouse_lb or self.mouse_mb or self.mouse_rb) then
self.mouse_win = nil
end
end
function wm:on_mouse_move(prev_x, prev_y, new_x, new_y)
local on_win = self.mouse_win or self:find_win(prev_x, prev_y)
if on_win then
on_win:on_mouse_move(prev_x - on_win.x, prev_y - on_win.y, new_x - on_win.x, new_y - on_win.y)
end
end
return wm
end
return tk
|
-- copy all globals into locals, some locals are prefixed with a G to reduce name clashes
local coroutine,package,string,table,math,io,os,debug,assert,dofile,error,_G,getfenv,getmetatable,ipairs,Gload,loadfile,loadstring,next,pairs,pcall,print,rawequal,rawget,rawset,select,setfenv,setmetatable,tonumber,tostring,type,unpack,_VERSION,xpcall,module,require=coroutine,package,string,table,math,io,os,debug,assert,dofile,error,_G,getfenv,getmetatable,ipairs,load,loadfile,loadstring,next,pairs,pcall,print,rawequal,rawget,rawset,select,setfenv,setmetatable,tonumber,tostring,type,unpack,_VERSION,xpcall,module,require
local sys=require("wetgenes.www.any.sys")
local wet_html=require("wetgenes.html")
local replace=wet_html.replace
local url_esc=wet_html.url_esc
local html=require("base.html")
-- replacement version of module that does not global
local module=function(modname, ...)
local ns={ _NAME = modname , _PACKAGE = string.gsub (modname, "[^.]*$", "") }
ns._M = ns
package.loaded[modname] = ns
setfenv (2, ns)
for _,f in ipairs({...}) do f(ns) end
end
module("profile.html")
setmetatable(_M,{__index=html}) -- use a meta table to also return html base
-----------------------------------------------------------------------------
--
-- table layout, grab all the previously built bits and spit them out
-- into some sort of layout
--
-----------------------------------------------------------------------------
profile_layout=function(d)
-- the 4 main components, may be arrays of strings just join them if they are
for i,v in ipairs{"head","wide","side","foot"} do
if type(d[v])=="table" then
d[v]=table.concat(d[v]) -- turn any tables to strings
end
end
local p=[[
<div class="profile_layout">
<div class="profile_layout_head">
{head}
</div>
<div class="profile_layout_body">
<div class="profile_layout_wide">
{wide}
</div>
<div class="profile_layout_side">
{side}
</div>
</div>
<div class="profile_layout_foot">
{foot}
</div>
</div>
]]
return replace(p,d)
end
|
gl.setup(1390, 545)
local font = resource.load_font("OpenSans-Regular.ttf")
function node.render()
local bus = resource.render_child("bus")
bus:draw(0, 0, 690, 545)
local tram = resource.render_child("tram")
tram:draw(695, 0, 1390, 545)
end
|
function GenerateQuads(atlas, tilewidth, tileheight)
local sheetWidth = atlas:getWidth() / tilewidth
local sheetHeight = atlas:getHeight() / tileheight
local sheetCounter = 1
local spritesheet = {}
for y = 0, sheetHeight - 1 do
for x = 0, sheetWidth - 1 do
spritesheet[sheetCounter] =
love.graphics.newQuad(x * tilewidth, y * tileheight, tilewidth, tileheight, atlas:getDimensions())
sheetCounter = sheetCounter + 1
end
end
return spritesheet
end
function GenerateTileSets(quads, setsX, setsY, sizeX, sizeY)
local tilesets = {}
local tableCounter = 0
local sheetWidth = setsX * sizeX
for tilesetY = 1, setsY do
for tilesetX = 1, setsX do
table.insert(tilesets, {})
tableCounter = tableCounter + 1
for y = (sizeY * (tilesetY - 1)) + 1, (sizeY * (tilesetY - 1)) + 1 + sizeY do
for x = (sizeX * (tilesetX - 1)) + 1, (sizeX * (tilesetX - 1)) + 1 + sizeX do
table.insert(tilesets[tableCounter], quads[(sheetWidth * (y - 1)) + x])
end
end
end
end
return tilesets
end
|
--[[
Moves job from active to delayed set.
Input:
KEYS[1] delayed key
KEYS[2] job key
KEYS[3] events stream
KEYS[4] delayed stream
ARGV[1] delayedTimestamp
ARGV[2] the id of the job
ARGV[3] queue token
Output:
0 - OK
-1 - Missing job.
-1 - Job not in delayed set.
Events:
- delayed key.
]]
local rcall = redis.call
if rcall("EXISTS", KEYS[2]) == 1 then
local jobId = ARGV[2]
local score = tonumber(ARGV[1])
local delayedTimestamp = (score / 0x1000)
if redis.call("ZSCORE", KEYS[1], jobId) ~= false then
return -3
end
rcall("XADD", KEYS[3], "*", "event", "delayed", "jobId", jobId, "delay", delayedTimestamp);
rcall("XADD", KEYS[4], "*", "nextTimestamp", delayedTimestamp);
return 0
else
return -1
end
|
local Commands = require("commands")
local Permissions = require("permissions")
local Get = require("get")
local name = "blockperms" -- Name of the command.
local permissions = {
bot_owner = false, -- Whether only the bot owner can use this command.
manage_server = true, -- Whether you must have `Manage Server` to use this command.
moderator = false, -- Whether you must be manually given permission to use this command.
}
local run_perms = { } -- List of permissions that are required to run the command
local signature = "blockperms [thing] <command>" -- Type signature of the command for help files.
-- Array of information about arguments for help files.
--eg: {false, "arg", "This is an argument."}, {true, "optionalArg", "This argument is optional"}
local args = {
{true, "thing", "The object to block permissions for"},
{false, "command", "What command, if any, to block the `thing` from using"},
}
-- Description of each command for help files.
local description = [[
Blocks a specific user or role from using moderator commands or optionally from using a specific command.
If `thing` is a user, that user is blocked from using moderator commands. If `thing` is a role, anyone with that role will automatically be blocked from using moderator commands.
If `command` is given, the block will only apply to that specific command. This will block non-moderator commands, so it can be used to effectively disable certain commands.
Blocking someone won't prevent them from using commands that require `Manage Server`, like `blockperms`.
Additionally, if someone has any blocks in place (either on their user or a role they have), it will override any permissions given with `giveperm`.]]
-- The code block that gets executed when the command is ran.
---@param guild Guild
---@param author User
---@param message Message
---@param args string[]
local function command(guild, author, message, args)
if #args == 0 then
message:reply("No user/role provided. See this command's help text for more information.")
return
end
local mention = args[1]
local gotMember, member = Get.member(guild, mention, false)
local gotRole, role = Get.role(guild, mention, false)
if gotMember and gotRole then
message:reply("Found both a user and a role by that name. Try using a mention or the ID of the thing you want to reference.")
return
elseif not (gotMember or gotRole) then
message:reply("Couldn't find a user or role by that name/id. Try using a mention or the ID of the thing you want to reference.")
return
end
local commandData
local cmdName = args[2]
if cmdName then
cmdName = string.lower(cmdName)
commandData = Commands.getCommandData(cmdName)
if not commandData or not Permissions.canUseCommand(guild, author, commandData) then
message:reply(string.format("Command `%s` doesn't exist or is inaccessible to you.", cmdName))
return
end
end
if gotMember then
local user = member.user
local saved = Permissions.setNegativeMemberOverride(guild, user, commandData)
if saved then
if commandData then
message:reply(string.format("Successfully blocked user `%s` from being able to use command `%s`!", user.tag, cmdName))
else
message:reply(string.format("Successfully blocked user `%s` from being able to use moderator commands!", user.tag))
end
else
message:reply(string.format("Failed to update the permissions for user `%s`. Please try again later.", user.tag))
end
return
else
local saved = Permissions.setNegativeRoleOverride(guild, role, commandData)
if saved then
if commandData then
message:reply(string.format("Successfully blocked role `%s` from being able to use command `%s`!", role.name, cmdName))
else
message:reply(string.format("Successfully blocked role `%s` from being able to use use moderator commands!", role.name))
end
else
message:reply(string.format("Failed to update the permissions for role `%s`. Please try again later.", role.name))
end
return
end
end
return {
name = name,
permissions = permissions,
run_perms = run_perms,
signature = signature,
args = args,
description = description,
command = command
} |
-- Example: Getting the x- and y-position of the mouse
function love.load()
love.graphics.setFont(14)
end
function love.draw()
-- Draws the position on screen.
love.graphics.print("The mouse is at:",50,50)
love.graphics.print(love.mouse.getX(),50,64)
love.graphics.print(love.mouse.getY(),50,78)
end
|
-- These are the default settings. Don't mind changing these.
FPP = FPP or {}
-- Don't reset the settings when they're already there
if FPP.Settings then
return
end
FPP.Settings = {}
FPP.Settings.FPP_PHYSGUN1 = {
toggle = 1,
adminall = 1,
worldprops = 0,
adminworldprops = 1,
canblocked = 0,
admincanblocked = 0,
shownocross = 1,
checkconstrained = 1,
reloadprotection = 1,
iswhitelist = 0}
FPP.Settings.FPP_GRAVGUN1 = {
toggle = 1,
adminall = 1,
worldprops = 1,
adminworldprops = 1,
canblocked = 0,
admincanblocked = 0,
shownocross = 1,
checkconstrained = 1,
noshooting = 1,
iswhitelist = 0}
FPP.Settings.FPP_TOOLGUN1 = {
toggle = 1,
adminall = 1,
worldprops = 1,
adminworldprops = 1,
canblocked = 0,
admincanblocked = 0,
shownocross = 1,
checkconstrained = 1,
iswhitelist = 0,
duplicatorprotect = 1,
duplicatenoweapons = 1,
spawniswhitelist = 0,
spawnadmincanweapon = 0,
spawnadmincanblocked = 0}
FPP.Settings.FPP_PLAYERUSE1 = {
toggle = 0,
adminall = 1,
worldprops = 1,
adminworldprops = 1,
canblocked = 0,
admincanblocked = 1,
shownocross = 1,
checkconstrained = 0,
iswhitelist = 0}
FPP.Settings.FPP_ENTITYDAMAGE1 = {
toggle = 1,
protectpropdamage = 1,
adminall = 1,
worldprops = 1,
adminworldprops = 1,
canblocked = 0,
admincanblocked = 0,
shownocross = 1,
checkconstrained = 0,
iswhitelist = 0}
FPP.Settings.FPP_GLOBALSETTINGS1 = {
cleanupdisconnected = 1,
cleanupdisconnectedtime = 120,
cleanupadmin = 1,
antie2minge = 1}
FPP.Settings.FPP_ANTISPAM1 = {
toggle = 1,
antispawninprop = 0,
bigpropsize = 5.85,
bigpropwait = 1.5,
smallpropdowngradecount = 3,
smallpropghostlimit = 2,
smallpropdenylimit = 6,
duplicatorlimit = 3
}
FPP.Settings.FPP_BLOCKMODELSETTINGS1 = {
toggle = 1,
propsonly = 0,
iswhitelist = 0
}
for Protection, Settings in pairs(FPP.Settings) do
for Option, value in pairs(Settings) do
CreateConVar("_"..Protection.."_"..Option, value, {FCVAR_REPLICATED, FCVAR_SERVER_CAN_EXECUTE})
end
end
|
function arithmetic(a, b)
print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a // b)
print(a % b)
print(a ^ b)
print(-b)
end
function bitwise(a, b)
print(a & b)
print(a | b)
print(a ~ b)
print(a >> 4)
print(a << 4)
print(~a)
end
function relational(a, b)
print(a == b)
print(a ~= b)
print(a < b)
print(a > b)
print(a <= b)
print(a >= b)
end
function logical(a, b)
print(a or b)
print(a and b)
print(not a)
end
function concatenation(a, b)
print(a .. b)
end
function length(a)
print(#a)
end
arithmetic(11, 2)
bitwise(0x0F, 0xF0)
relational(1, 2)
logical(true, false)
concatenation('foo', 'bar')
length('foo')
|
--- Main methods directly available in your addon
-- @classmod lib
-- @author Alar of Runetotem
-- @release 51
-- @set sort=true
-- @usage
-- -- Create a new addon this way:
-- local me,ns=... -- Wow engine passes you your addon name and a private table to use
-- addon=LibStub("LibInit"):newAddon(ns,me)
-- -- Since now, all LibInit methods are available on self
local me, ns = ...
local __FILE__=tostring(debugstack(1,2,0):match("(.*):12:")) -- Always check line number in regexp and file
local MAJOR_VERSION = "LibInit"
local MINOR_VERSION = 51
local LibStub=LibStub
local dprint=function() end
local encapsulate = function ()
if LibDebug and AlarDbg then
LibDebug()
dprint=print
end
end
encapsulate()
local obj,old=LibStub:NewLibrary(MAJOR_VERSION,MINOR_VERSION)
if obj then
dprint(strconcat("Loading ",MAJOR_VERSION,'.',MINOR_VERSION,' from ',__FILE__))
if old then
dprint(strconcat("Upgrading ",MAJOR_VERSION,'.',old))
end
-- obj.loadedFrom=__FILE__
else
dprint(strconcat("Already loaded ",MAJOR_VERSION,'.',MINOR_VERSION," checked from ", __FILE__))
return
end
local off=(_G.RED_FONT_COLOR_CODE or '|cffff0000') .. (_G.VIDEO_OPTIONS_DISABLED or 'Off') .. ( _G.FONT_COLOR_CODE_CLOSE or '|r')
local on=(_G.GREEN_FONT_COLOR_CODE or '|cff00ff00') .. (_G.VIDEO_OPTIONS_ENABLED or 'On') .. ( _G.FONT_COLOR_CODE_CLOSE or '|r')
local nop=function() end
local pp=print -- Keeping a handy plain print around
local assert=assert
local strconcat=strconcat
local tostring=tostring
local tremove=tremove
local _G=_G -- Unmodified env
--@debug@
-- Checking packager behaviour
--@end-debug@
local lib=obj --#Lib
function lib:Info()
print(MAJOR_VERSION,MINOR_VERSION,' loaded from ',__FILE__)
end
-- A default dictionary, in case something went wrong with localization
local L=setmetatable({},{
__index=function(t,k) return k end
})
local C
local F
function lib:_SetLocalization(localization)
L=localization
end
function lib:_SetColorize(colorize)
C=colorize
end
function lib:_SetFactory(factory)
F=factory
end
local CallbackHandler = LibStub:GetLibrary("CallbackHandler-1.0")
-- Upvalues
local _G=_G
local floor=floor
local abs=abs
local wipe=wipe
local print=print
local next = next
local pairs = pairs
local pcall = pcall
local type = type
local GetTime = GetTime
local gcinfo = gcinfo
local unpack = unpack
local geterrorhandler = geterrorhandler
local GetContainerNumSlots=GetContainerNumSlots
local GetContainerItemID=GetContainerItemID
local GetItemInfo=GetItemInfo
local UnitHealth=UnitHealth
local UnitHealthMax=UnitHealthMax
local setmetatable=setmetatable
local NUM_BAG_SLOTS=NUM_BAG_SLOTS
local InCombatLockdown=InCombatLockdown
local error=error
local tinsert=tinsert
local debugstack=debugstack
local ipairs=ipairs
local GetAddOnMetadata=GetAddOnMetadata
local format=format
local tostringall=tostringall
local tonumber=tonumber
local strconcat=strconcat
local strjoin=strjoin
local strsplit=strsplit
local select=select
local coroutine=coroutine
local cachedGetItemInfo
local toc=select(4,GetBuildInfo())
--]]
-- Help sections
local titles
local RELNOTES
local LIBRARIES
local PROFILE
local HELPSECTIONS
local AceConfig = LibStub("AceConfig-3.0",true)
assert(AceConfig,"LibInit needs AceConfig-3.0")
local AceRegistry = LibStub("AceConfigRegistry-3.0",true)
local AceDBOptions=LibStub("AceDBOptions-3.0",true)
local AceConfigDialog=LibStub("AceConfigDialog-3.0",true)
local AceGUI=LibStub("AceGUI-3.0",true)
local Ace=LibStub("AceAddon-3.0")
local AceLocale=LibStub("AceLocale-3.0",true)
local AceDB = LibStub("AceDB-3.0",true)
-- Persistent tables
lib.mixinTargets=lib.mixinTargets or {}
--- Runtime storage for variables.
--
lib.toggles=lib.toggles or {}
lib.chats=lib.chats or {}
--- Runtime storage for information on LibInit managed addons.
--
lib.options=lib.options or {}
--- Recycling system pool.
--
lib.pool=lib.pool or setmetatable({},{__mode="k",__tostring=function(t) return "Recycle Pool:" end})
--- Mixins list
--
lib.mixins=lib.mixins or {}
wipe(lib.mixins)
-- Recycling function from ACE3
--- Table Recycling System.
--
-- A set of functions to allow for table reusing
-- @section Recycle
-- @usage
-- -- You better upvalue these functions
-- local addon=LibStub("LibInit"):NewAddon("myaddon")
-- local new=addon:Wrap("NewTable")
-- local new=addon:Wrap("DelTable")
--
local new, del, add, recursivedel,copy, cached, stats
do
local meta={__metatable="RECYCLE"}
local pool = lib.pool
--@debug@
local newcount, delcount,createdcount= 0,0,0
--@end-debug@
function new(t)
--@debug@
newcount = newcount + 1
--@end-debug@
if type(t)=="table" then
local rc=pcall(setmetatable,t,meta)
return t
else
t = next(pool)
end
if t then
pool[t] = nil
return t
else
--@debug@
createdcount = createdcount + 1
--@end-debug@
return setmetatable({},meta)
end
end
function copy(t)
local c = new()
for k, v in pairs(t) do
c[k] = v
end
return c
end
function del(t)
--@debug@
delcount = delcount + 1
--@end-debug@
if getmetatable(t)==meta then
wipe(t)
pool[t] = true
end
end
function recursivedel(t,level)
level=level or 0
--@debug@
delcount = delcount + 1
--@end-debug@
for k,v in pairs(t) do
if type(v)=="table" and getmetatable(v) == "RECYCLE" then
if level < 2 then
recursivedel(v,level+1)
end
end
end
if getmetatable(t)=="RECYCLE" then
wipe(t)
pool[t] = true
end
end
function cached()
local n = 0
for k in pairs(pool) do
n = n + 1
end
return n
end
--@debug@
function stats()
print("Created:",createdcount)
print("Aquired:",newcount)
print("Released:",delcount)
print("Cached:",cached())
end
--@end-debug@
--[===[@non-debug@
function stats()
return
end
--@end-non-debug@]===]
end
--- Get a new table from the recycle pool
-- Preferred usage is assigning to a local via wrap function
-- @tparam[opt=nil] table tbl Optional table which will be added to the pool after use. Must NOT have a metatable
-- @treturn table A new table or a recycled one. Table is wiped
-- @usage
-- -- Assuming you upvalued it as new
-- local t=new()
-- -- do something
-- del(t)
-- t=new()
-- t.check=new()
-- del(t,true) -- will recycle both t and t.check
function lib:NewTable(tbl)
if tbl and lib.options[tbl] then
return new()
else
return new(tbl)
end
end
--- Returns a table to the recycle pool
-- Table will be wiped
-- Only manages tables allocated via NewTable
-- Other tables are left intact
-- -- Preferred usage is assigning to a local via wrap function
-- @tparam table tbl table to be recycled
-- @tparam[opt=true] boolean recursive If true, embedded tables added cia new table will be wiped and recycled
--
function lib:DelTable(tbl,recursive)
if type(recursive)=="nil" then recursive=true end
--assert(type(tbl)=="table","Usage: DelTable(table) called as DelTable(" ..tostring(tbl) ..','..tostring(recursive)..")")
return recursive and recursivedel(tbl) or del(tbl)
end
function lib:CachedTableCount()
return cached()
end
function lib:CacheStats()
return stats()
end
--- Addon management.
-- @section addon
--- Create a new AceAddon-3.0 addon.
--
-- Any library you specified will be embeded, and the addon will be scheduled for
-- its OnInitializee and OnEnabled callbacks.
--
-- The final addon object, with all libraries embeded, will be returned.
--
-- Options table format:
--
--* profile: choose the initial profile (if omittete, uses a per character one)
--* noswitch: disables Ace profile managemente, user will not be able to change it
--* nogui: do not generate a gui for configuration
--* nohelp: do not generate help (actually, help generation is not yet implemented)
--* enhancedProfile: adds "Switch all profiles to default" and "Remove unused profiles" do Ace profile gui
--
-- @tparam[opt] table target to use as a base for the addon (optional)
-- @tparam string name Name of the addon object to create
-- @tparam[opt] table options options list
-- @tparam[opt] bool full If true, all available and embeddable Ace3 library are embedded
-- @tparam[opt] string ... List of libraries to embed into the addon
-- @treturn table new addon
--
-- @usage
-- --Create a simple addon object
-- MyAddon = LibStub("LibInit"):NewAddon("MyAddon", "AceEvent-3.0")
--
-- -- Create a Addon object based on the table of a frame
-- local MyFrame = CreateFrame("Frame")
-- MyAddon = LibStub("LibInit"):NewAddon(MyFrame, "MyAddon", "AceEvent-3.0")
-- -- Create an Addon based on the private table provided by Blizzard Code:
-- local myname,addon = ...
-- LibStub("LibInit"):NewAddon(addon,myname)
--
function lib:NewAddon(target,...)
local name
local customOptions
local start=1
if type(target) ~= "table" then
name=target
target={}
else
name=(select(1,...))
start=2
end
assert(Ace,"Could not find Ace3 Library")
assert(type(name)=="string","Name is mandatory")
local appo={}
appo[MAJOR_VERSION]=true
appo["AceConsole-3.0"]=true
for i=start,select('#',...) do
local mix=select(i,...)
if type(mix)=="boolean" and mix then
for n,k in LibStub:IterateLibraries() do
if (n:match("Ace%w*-3%.0") and k.Embed) then appo[n]=true end
end
elseif type(mix)=="string" then
appo[mix]=true
elseif type(mix)=="table" then
customOptions=mix
end
end
local mixins=new()
for i,_ in pairs(appo) do
tinsert(mixins,i)
end
local target=Ace:NewAddon(target,name,unpack(mixins))
del(mixins)
appo=nil
local options={}
options.name=name
options.first=true
options.libstub=__FILE__
options.version=GetAddOnMetadata(name,'Version') or "Internal"
if (options.version:sub(1,1)=='@') then
options.version=GetAddOnMetadata(name,'X-Version') or "Internal"
end
local b,e=options.version:find(" ")
if b and b>1 then
options.version=options.version:sub(1,b-1)
end
options.revision=GetAddOnMetadata(name,'X-revision') or "Alpha"
if (options.revision:sub(1,1)=='@') then
options.revision='Development'
end
options.prettyversion=format("%s (Revision: %s)",tostringall(options.version,options.revision))
options.title=GetAddOnMetadata(name,"title") or 'No title'
options.notes=GetAddOnMetadata(name,"notes") or 'No notes'
options.libinit=MAJOR_VERSION .. ' ' .. MINOR_VERSION
-- Setting sensible default for mandatory fields
options.ID=GetAddOnMetadata(name,"X-ID") or name
options.DATABASE=GetAddOnMetadata(name,"X-Database") or "db" .. options.ID
lib.toggles[target]={}
if customOptions then
for k,v in pairs(customOptions) do
local key=strlower(k)
if key=="enhanceprofile" then key = "enhancedprofile" end
if key=="profile"
or key=="noswitch"
or key=="nogui"
or key=="nohelp"
or key=="enhancedprofile"
then
options[key]=v
else
error("Invalid options: " .. k)
end
end
end
lib.options[target]=options
RELNOTES=L["Release Notes"]
PROFILE=L["Profile"]
HELPSECTIONS={PROFILE,RELNOTES}
titles={
RELNOTES=RELNOTES,
PROFILE=PROFILE
}
return target
end
function lib:NewSubModule(name,...)
local obj=self:NewModule(name,...)
-- To avoid strange interactions
obj.OnInitialized=function()end -- placeholder
obj.OnInitialize=function(self,...) return self:OnInitialized(...) end
obj.OnEnable=nil
obj.OnDisable=nil
return obj
end
function lib:NewSubClass(name)
return self:NewSubModule(name,self)
end
--- Returns a closure to call a method as simple local function
-- @tparam string name Method name
-- @usage local print=self:Wrap("print") ; print("Hello") same as self:print("Hello")
-- @treturn func Wrapper
function lib:Wrap(name)
if (name=="Trace") then
return function(...) lib._Trace(self,1,...) end
end
if (type(self[name])=="function") then
return function(...) return self[name](self,...) end
else
return nop
end
end
function lib:GetAddon(name)
return Ace:GetAddon(name,true)
end
function lib:GetLocale()
return AceLocale:GetLocale(self.name)
end
--- Generic.
-- General utilities
-- @section utils
--- Colors a string.
-- @tparam string stringa A string
-- @tparam string colore Name of a color (red, rare, alliance and so on). If not existent uses yellow
-- @treturn string Colored string
--
function lib:Colorize(stringa,colore)
return C(stringa,colore) .. "|r"
end
function lib:GetTocVersion()
return select(4,GetBuildInfo())
end
-- Combat scheduler done with LibCallbackHandler
if not lib.CombatScheduler then
lib.CombatScheduler = CallbackHandler:New(lib,"_OnLeaveCombat","_CancelCombatAction")
lib.CombatFrame=CreateFrame("Frame")
lib.CombatFrame:SetScript("OnEvent",function()
lib.CombatScheduler:Fire("LIBINIT_END_COMBAT")
if lib.CombatScheduler.insertQueue then
wipe(lib.CombatScheduler.insertQueue) -- hackish, depends on internal callbackhanlder implementation
end
wipe(lib.CombatScheduler.events)
lib.CombatScheduler.recurse=0
for _,c in pairs(lib.coroutines) do
if c.waiting then
c.waiting=false
C_Timer.After(c.interval,c.repeater) -- to avoid hammering client with a shitload of corooutines starting together
end
end
end)
lib.CombatFrame:RegisterEvent("PLAYER_REGEN_ENABLED")
end
local function Run(args) tremove(args,1)(unpack(args)) end
--- Executes an action as soon as combat restrictions lift.
-- Action can be executed immediately if toon is out of combat
-- @tparam string|func action To be executed, Can be a function or a method name
-- @tparam[opt] mixed ... More parameters will be directly passed to action
--
function lib:OnLeaveCombat(action,...)
if type(action)~="string" and type(action)~="function" then
error("Usage: OnLeaveCombat (\"action\", ...): 'action' - string or function expected.", 2)
end
if type(action)=="string" and type(self[action]) ~= "function" then
error("Usage: OnLeaveCombat (\"action\", ...): 'action' - method '"..tostring(action).."' not found on self.", 2)
end
if type(action) =="string" then
lib._OnLeaveCombat(self,"LIBINIT_END_COMBAT",Run,{self[action],self,...})
else
lib._OnLeaveCombat(self,"LIBINIT_END_COMBAT",Run,{action,...})
end
if (not InCombatLockdown()) then
lib.CombatFrame:GetScript("OnEvent")()
end
end
function lib:Gradient(perc)
return self:ColorGradient(perc,0,1,0,1,1,0,1,0,0)
end
function lib:ColorToString(r,g,b)
return format("%02X%02X%02X", 255*r, 255*g, 255*b)
end
function lib:ColorGradient(perc, ...)
if perc >= 1 then
local r, g, b = select(select('#', ...) - 2, ...)
return r, g, b
elseif perc <= 0 then
local r, g, b = ...
return r, g, b
end
local num = select('#', ...) / 3
local segment, relperc = math.modf(perc*(num-1))
local r1, g1, b1, r2, g2, b2 = select((segment*3)+1, ...)
return r1 + (r2-r1)*relperc, g1 + (g2-g1)*relperc, b1 + (b2-b1)*relperc
end
-- Gestione variabili
local varmeta={}
do
local function f1(self,flag,value)
return self:Apply(flag,value)
end
local function f2(self,flag,value)
return self['Apply' .. flag](self,value)
end
varmeta={
__index =
function(table,cmd)
local self=rawget(table,'_handler')
if (type(self["Apply" .. cmd]) =='function') then
rawset(table,cmd,f2)
elseif (type(self.Apply)=='function') then
rawset(table,cmd,f1)
else
rawset(table,cmd,function(...) end)
end
return rawget(table,cmd)
end
}
end
--- Return a named chatframe.
-- Returns nil if chat does not exist
-- @tparam[opt=DEFAULT_CHAT_FRAME] string chat Chat name
-- @treturn frame|nil requested chat frame, can be nil if "chat" does not exist
--
function lib:GetChatFrame(chat)
if (chat) then
if (lib.chats[chat]) then return lib.chats[chat] end
for i=1,NUM_CHAT_WINDOWS do
local frame=_G["ChatFrame" .. i]
if (not frame) then break end
if (frame.name==chat) then lib.chats[chat]=frame return frame end
end
return nil
end
return DEFAULT_CHAT_FRAME
end
local Myclass
---
-- Check if the unit in target hast the requested class
-- @tparam string class Requested Class
-- @tparam string target Requested Unit (default 'player')
-- @return boolean true if target has the requeste class
function lib:Is(class,target)
target=target or "player"
if (target == "player") then
if (not Myclass) then
Myclass=select(2,UnitClass('player'))
end
return Myclass==strupper(class)
else
local rc,_,unitclass=pcall(UnitClass,target)
if (rc) then
return unitclass==strupper(class)
else
return false
end
end
end
---
-- Parses a command from chat or from an table options handjer command
-- Internally calls AceConsole-3.0:GetArgs
-- @tparam string|table msg Can be a string (when called from chat command) or a table (wbe called by Ace3 Options Table Handler)
-- @tparam number n index in command list
-- @return command,subcommand,arg,full string after command
function lib:Parse(msg,n)
if (not msg) then
return nil
end
if (type(msg) == 'table' and msg.input ) then msg=msg.input end
if (type(msg) ~= 'string') then return end
return self:GetArgs(msg,n)
end
---
-- Parses an itemlink and returns itemId without calling API again
-- @tparam string itemlink A standard wow itemlink
-- @treturn number itemId or 0
function lib:GetItemID(itemlink)
if (type(itemlink)=="string") then
local itemid,context=GetItemInfoFromHyperlink(itemlink)
return tonumber(itemid) or 0
--return tonumber(itemlink:match("Hitem:(%d+):")) or 0
else
return 0
end
end
---
-- Return the total numner of bag slots
-- @treturn number Total bag slots
function lib:GetTotalBagSlots()
local i=0
for bag=0,NUM_BAG_SLOTS do
i=i+GetContainerNumSlots(bag)
end
return i
end
---
-- Scans Bags for an item based on different criteria
--
-- All parameters are optional.
--
-- With no parameters ScanBags returns the first empty slot
--
-- Passing starbag and scanslot allows to continue scanning after the first finding
--
-- @tparam[opt=0] number index index in GetItemInfo result. 0 is a special case to match just itemid
-- @tparam[opt=0] number value value against to match. 0 is a special case for empty slot
-- @tparam[opt=0] number startbag Initialbag to start scan from
-- @tparam[opt=1] number startslot Initial slot to start scan from
-- @treturn[1] number ItemId
-- @treturn[1] number bag
-- @treturn[1] number slot
-- @treturn[1] list all return value from GetItemInfo called on _Itemid_
-- @treturn[2] bool false If nothing found
--
function lib:ScanBags(index,value,startbag,startslot)
index=index or 0
value=value or 0
startbag=startbag or 0
startslot=startslot or 1
for bag=startbag,NUM_BAG_SLOTS do
for slot=startslot,GetContainerNumSlots(bag),1 do
local itemlink=GetContainerItemLink(bag,slot)
if (itemlink) then
if (index==0) then
if (self:GetItemID(itemlink)==value) then
return itemlink,bag,slot
end
else
local test=CachedGetItemInfo(itemlink,index)
if (value==test) then
return itemlink,bag,slot
end
end
elseif value==0 then
return bag,slot
end
end
end
return false
end
--- Returns number of free bag slots and total bagt slots.
-- @treturn number Free bag slots
-- @treturn number Total bag slots
function lib:GetBagSlotCount()
local free,total=0,0
for bag=0,NUM_BAG_SLOTS do
free=free+(GetContainerNumFreeSlots(bag) or 0)
total=total+(GetContainerNumSlots(bag) or 0)
end
return free,total
end
--- Returns unit's health as a normalized percent value
-- @tparam string unit A standard unit name
-- @treturn number health as percent value
function lib:Health(unit)
local totale=UnitHealthMax(unit) or 1
local corrente=UnitHealth(unit) or 1
if (corrente == 0) then corrente =1 end
if (totale==0) then totale = corrente end
local life=corrente/totale*100
return math.ceil(life)
end
function lib:Age(secs)
return self:TimeToStr(GetTime() - secs)
end
function lib:Mana(unit)
local totale=UnitManaMax(unit) or 1
local corrente=UnitMana(unit) or 1
if (corrente == 0) then corrente =1 end
if (totale==0) then totale = corrente end
local life=corrente/totale*100
return math.ceil(life)
end
function lib:IsFriend(player)
local i
for i =1,GetNumFriends() do
local name,_,_,_,_ =GetFriendInfo(i)
if (name == player) then
return true
end
end
return false
end
function lib:GetDistanceFromMe(unit)
if not unit then return 99999 end
local x,y=GetPlayerMapPosition(unit)
return self:GetUnitDistance(x,y)
end
function lib:GetUnitDistance(x,y,unit)
unit=unit or "player"
local from={}
local to={}
from.x,from.y=GetPlayerMapPosition(unit)
to.x=x
to.y=y
return self:GetDistance(from,to) * 10000
end
function lib:GetDistance(a,b)
--------------
-- Calculates distance betweeb 2 points given as
-- a.x,a.y and b.x,b.y
local x=b.x - a.x
local y=b.y -a.y
local d=x*x + y* y
local rc,distance=pcall(math.sqrt,d)
if (rc) then
return distance
else
return 99999
end
end
---
-- Returns a numeric representation of version.
-- Can be overridden
-- In default incarnation assumes that version is in the form x,y,z
-- @return z+y*100+x*10000
--
function lib:NumericVersion()
local v=tonumber(self.version)
if (v) then return v end
if (type(self.version) == "string") then
local a,b,c=self.version:match("(%d*)%D?(%d*)%D?(%d*)%D*")
a=tonumber(a) or 0
b=tonumber(b) or 0
c=tonumber(c) or 0
return a*10000+b*100+c
else
return 0
end
end
local function loadOptionsTable(self)
local options=lib.options[self]
self.OptionsTable={
handler=self,
type="group",
childGroups="tab",
name=options.title,
desc=options.notes,
args={
gui = {
name="GUI",
desc=_G.CHAT_CONFIGURATION,
type="execute",
func="Gui",
guiHidden=true,
},
--@debug@
help = {
name="HELP",
desc="Show help",
type="execute",
func="Help",
guiHidden=true,
},
debug = {
name="DBG",
desc="Enable debug",
type="execute",
func="Debug",
guiHidden=true,
cmdHidden=true,
},
--@end-debug@
silent = {
name="SILENT",
desc="Eliminates startup messages",
type="execute",
func=function()
self.db.global.silent=not self.db.global.silent
self:Print("Silent is now",self.db.global.silent and "true" or "false" )
end,
guiHidden=true,
},
on = {
name=strlower(_G.ENABLE),
desc=_G.ENABLE .. ' ' .. options.title,
type="execute",
func="Enable",
guiHidden=true,
},
off = {
name=strlower(_G.DISABLE),
desc=_G.DISABLE .. ' ' .. options.title,
type="execute",
func="Disable",
guiHidden=true,
arg='Active'
},
}
}
end
local function loadDbDefaults(self)
self.DbDefaults={
char={
firstrun=true,
lastversion=0,
},
global={
firstrun=true,
lastversion=0,
lastinterface=60200
},
profile={
toggles={
Active=true,
},
["*"]={},
}
}
self.MenuLevels={"root"}
self.ItemOrder=setmetatable({},{
__index=function(table,key) rawset(table,key,1)
return 1
end
}
)
end
local function BuildHelp(self)
local main=self.name
for _,section in ipairs(HELPSECTIONS) do
if (section == RELNOTES) then
self:HF_Load(section,main..section,' ' .. tostring(self.version) .. ' (r:' .. tostring(self.revision) ..')')
else
self:HF_Load(section,main .. section,'')
end
end
end
function lib:IsFirstRun()
return self.db.global.firstrun
end
function lib:IsNewVersion()
return self.numericversion > self.db.global.lastnumericversion and self.db.global.lastnumericversion or false
end
function lib:IsNewTocVersion()
return self.interface > self.db.global.lastinterface and self.db.global.lastinterface or false
end
function lib:RegisterDatabase(dbname,defaults,profile)
return AceDB:New(dbname,defaults,profile)
end
local function SetCommonProfile(info,...)
local db=info.handler.db
for k,v in pairs(db.sv.profileKeys) do
db.sv.profileKeys[k]="Default"
end
db:SetProfile("Default")
end
local function PurgeProfiles(info,...)
local profiles=new()
local used=new()
local db=info.handler.db
db:GetProfiles(profiles)
for k,v in pairs(db.sv.profileKeys) do
used[v]=true
end
for _,v in ipairs(profiles) do
if not used[v] then
db:DeleteProfile(v)
end
end
del(used)
del(profiles)
end
local function SetupProfileSwitcher(tbl,addon)
local profiles=tbl.handler:ListProfiles({args="both"})
local default=profiles.Default or "Default"
wipe(profiles)
tbl.args.UseDefault_Desc={
order=900,
type='description',
name="\n"..format(L['UseDefault_Desc'],default)
}
tbl.args.UseDefault={
order=910,
type='execute',
func=SetCommonProfile,
name=format(L['UseDefault1'],default),
desc=format(L['UseDefault2'],default),
width="double",
}
tbl.args.Purge_Desc={
order=920,
type='description',
--name="forcedescname",
name="\n"..L['Purge_Desc'],
}
tbl.args.Purge={
order=930,
type='execute',
func=PurgeProfiles,
name=L['Purge1'],
desc=L['Purge2'],
width="double",
}
end
function lib:OnInitialize(...)
self.numericversion=self:NumericVersion() -- Initialized now becaus NumericVersion could be overrided
--CachedGetItemInfo=self:GetCachingGetItemInfo()
loadOptionsTable(self)
loadDbDefaults(self)
self:SetOptionsTable(self.OptionsTable) --hook
self:SetDbDefaults(self.DbDefaults) -- hook
local options=lib.options[self]
self.version=self.version or options.version
self.prettyversion=self.prettyversion or options.prettyversion
self.revision=self.revision or options.revision
if (AceDB and not self.db) then
self.db=AceDB:New(options.DATABASE,nil,options.profile)
end
if self.db then
self.db:RegisterDefaults(self.DbDefaults)
if (not self.db.global.silent) then
self:Print(format("Version %s %s loaded (%s)",
self:Colorize(options.version,'green'),
self:Colorize(format("(Revision: %s)",options.revision),"silver"),
"Disable message with /" .. strlower(options.ID) .. " silent")
)
self:Print("Using profile ",self.db:GetCurrentProfile())
end
self:SetEnabledState(self:GetBoolean("Active"))
else
self.db=setmetatable({},{
__index=function(t,l)
assert(false,"You need AceDB-3.0 in order to use database")
end
}
)
self:SetEnabledState(true)
end
-- I have for sure some library that needs to be intialized Before the addon
for _,library in self:IterateEmbeds(self) do
local lib=LibStub(library)
if (lib.OnEmbedPreInitialize) then
lib:OnEmbedPreInitialize(self)
end
end
self.help=setmetatable(
{},
{__index=function(table,key)
rawset(table,key,"")
return rawget(table,key)
end
}
)
--===============================================================================
-- Calls initialization Callback
local ignoreProfile=self:OnInitialized(...)
--===============================================================================
if (not self.OnDisabled) then
self.OptionsTable.args.on=nil
self.OptionsTable.args.off=nil
self.OptionsTable.args.standby=nil
end
if (type(self.LoadHelp)=="function") then self:LoadHelp() end
local main=options.name
BuildHelp(self)
if AceConfig and not options.nogui then
AceConfig:RegisterOptionsTable(main,self.OptionsTable,{main,strlower(options.ID)})
self.CfgDlg=AceConfigDialog:AddToBlizOptions(main,main )
if (not ignoreProfile and not options.noswitch) then
if (AceDBOptions) then
local profileOpts=AceDBOptions:GetOptionsTable(self.db)
self.ProfileOpts={} -- We dont want to propagate this change to all ace3 addons
for k,v in pairs(profileOpts) do
if k=='args' then
self.ProfileOpts.args={}
for k2,v2 in pairs(v) do
self.ProfileOpts.args[k2]=v2
end
else
self.ProfileOpts[k]=v
end
end
titles.PROFILE=self.ProfileOpts.name
self.ProfileOpts.name=self.name
if options.enhancedprofile then
SetupProfileSwitcher(self.ProfileOpts,self)
end
local profile=main..PROFILE
end
AceConfig:RegisterOptionsTable(main .. PROFILE,self.ProfileOpts)
AceConfigDialog:AddToBlizOptions(main .. PROFILE,titles.PROFILE,main)
end
else
self.OptionsTable.args.gui=nil
end
if (self.help[RELNOTES]~='') then
self.CfgRel=AceConfigDialog:AddToBlizOptions(main..RELNOTES,titles.RELNOTES,main)
end
if AceDB then
self:UpdateVersion()
end
end
function lib:UpdateVersion()
if (type(self.db.char) == "table") then
self.db.char.lastversion=self.numericversion
self.db.char.firstun=false
end
if (type(self.db.global)=="table") then
self.db.global.lastversion=self.numericversion
self.db.global.firstrun=false
self.db.global.lastinterface=self.interface
end
end
--- Help system.
-- @section help
function lib:HF_Push(section,text)
if section then section=titles[section] end
section=section or self.lastsection or RELNOTES
self.lastsection=section
self.help[section]=self.help[section] .. '\n' .. text
end
local getlibs
do
local libs={}
function lib:HF_Lib(libname)
local o,minor=LibStub(libname,true)
if (o and libs) then
if (not libs[o] or libs[o] <minor) then
libs[libname]=minor
end
end
end
function getlibs(l)
local appo={}
if (not libs) then return end
for i,_ in pairs(libs) do
table.insert(appo,i)
end
table.sort(appo)
for _,libname in pairs(appo) do
local minor=libs[libname]
l:HF_Pre(format("%s release: %s",l:Colorize(libname,'green'),l:Colorize(minor,'orange')),LIBRARIES)
end
libs=nil
end
end
function lib:HF_Toggle(flag,description)
flag=C(format("/%s toggle %s: ",strlower(lib.options[self].ID),flag),'orange') ..C(description,'white')
self:HF_Push(TOGGLES,"\n" .. C(flag,'orange'))
end
function lib:HF_Title(text,section)
self:HF_Push(section,C(text or '','yellow') .. "\n")
end
function lib:HF_Command(text,description,section)
self:HF_Push(section,C(text or '','orange') .. ':' .. C(description or '','yellow') .. "\n")
end
function lib:HF_Paragraph(text,section)
self:HF_Push(section,"\n"..C(text,'green'))
end
function lib:HF_CmdA(command,description,tooltip)
self:HF_Push(nil,
C('/' .. command,'orange') .. ' : ' .. (description or '') .. '\n' .. C(tooltip or '','yellow'))
end
function lib:HF_Cmd(command,description,tooltip)
command=lib.options[self].ID .. ' ' .. command
self:HF_CmdA(command,description,tooltip)
end
function lib:HF_Pre(testo,section)
self:HF_Push(section,testo)
end
function lib:Wiki(testo,section)
section=section or self.lastsection or RELNOTES
self.lastsection=section
local fmtbullet=" * %s\n"
local progressive=1
local fmtnum=" %2d. %s\n"
local fmthead1="|cff" .. C.Orange .."%s|r\n \n \n"
local fmthead2="|cff" .. C.Yellow .."%s|r\n \n"
local text=''
for line in testo:gmatch("(%C*)%c+") do
line=line:gsub("^ *","")
line=line:gsub(" *$","")
local i,j= line:find('^%=+')
if (i) then
if (j==1) then
text=text .. fmthead1:format(line:sub(j+1,-j-1))
else
text=text .. fmthead2:format(line:sub(j+1,-j-1))
end
else
local i,j= line:find('^%*+')
if (i) then
text=text.. fmtbullet:format(line:sub(j+1))
else
local i,j= line:find('^#+')
if (i) then
text=text .. fmtnum:format(progressive,line:sub(j+1))
progressive=progressive + 1
else
text=text .. line.."\n"
end
end
end
end
self.help[section]=self.help[section] .. '\n' .. text
end
function lib:RelNotes(major,minor,revision,t)
local fmt=self:Colorize("Release note for %d.%d.%s",'Yellow') .."\n%s"
local lines={}
local spacer=""
local maxpanlen=70
lines={strsplit("\n",t)}
local max=5
for i,tt in ipairs(lines) do
local prefix,text=tt:match("^(%a+):(.*)")
if (prefix == "Fixed" or prefix=="Fix") then
prefix=self:Colorize("Fix: ",'Red')
spacer=" "
elseif (prefix == "Feature") then
prefix=self:Colorize("Feature: ",'Green')
spacer= " "
else
text=tt
prefix=spacer
end
local tta=""
tt=text
while (tt:len() > maxpanlen) do
local p=tt:find("[%s%p]",maxpanlen -10) or maxpanlen
tta=tta..prefix..tt:sub(1,p) .. "\n"
prefix=spacer
tt=tt:sub(p+1)
end
tta=tta..prefix..tt
tta=tta:gsub("Upgrade:",self:Colorize("Upgrade:",'Azure'))
lines[i]=tta:gsub("Example:",self:Colorize("Example:",'Orange'))
max=max-1
if (max<1) then
break
end
end
self:HF_Push(RELNOTES,fmt:format(major,minor,revision,strjoin("\n",unpack(lines))))
end
function lib:HF_Load(section,optionname,versione)
-- Creazione pannello di help
-- Livello due del
if (section == LIBRARIES) then
getlibs(self)
end
local testo =self.help[section]
--debug(section)
--debug(optionname)
--debug(self.title)
if (testo ~= '') then
AceConfig:RegisterOptionsTable(optionname, {
name = lib.options[self].title .. (versione or ""),
type = "group",
args = {
help = {
type = "description",
name = testo,
fontSize='medium',
},
},
})
AceConfigDialog:SetDefaultSize(optionname, 600, 400)
end
end
-- var area
local function getgroup(self)
local group=self.OptionsTable
local m=self.MenuLevels
for i=2,#m do
group=group.args[self.MenuLevels[i]]
end
if (type(group) ~= "table") then
group={}
end
return group
end
local function getorder(self,group)
local i=self.ItemOrder[group.name]+1
self.ItemOrder[group.name]=i
return i
end
local function toflag(...)
local appo=''
for i=1,select("#",...) do
appo=appo .. tostring(select(i,...))
end
return appo:gsub("%W",'')
end
function lib:EndLabel()
local m=self.MenuLevels
if (#m > 1) then
table.remove(m)
end
end
--- Configuration panel.
-- These functions allow to build a ACE option table which will be fed to
-- AceConfigDialog:AddToBlizOptions
-- @section add
--self:AddLabel("General","General Options",C.Green)
---@section Variables management
--- Create a tab (ace type "header")
-- @tparam string title
-- @tparam string description
-- @tparam string stringcolor esadecimal color string without "|cff"
-- @treturn table Pointer to option table fragment added
function lib:AddLabel(title,description,stringcolor)
self:EndLabel()
description=description or title
stringcolor=stringcolor or C.yellow
local t=self:AddSubLabel(title,description,stringcolor)
t.childGroups="tab"
self:AddSeparator(description)
return t
end
--self:AddSubLabel("Local","Local Options",C.Green)
--- Create a label (ace type "group")
-- @tparam string title
-- @tparam string description
-- @tparam string stringcolor esadecimal color string without "|cff"
-- @treturn table Pointer to option table fragment added
function lib:AddSubLabel(title,description,stringcolor)
local m=self.MenuLevels
description=description or title
stringcolor=stringcolor or C.orange
local group=getgroup(self)
local flag=toflag(group.name,title)
group.args[flag]={
name="|cff" .. stringcolor .. title .. "|r",
desc=description,
type="group",
cmdHidden=true,
args={},
order=getorder(self,group),
}
table.insert(m,flag)
return group.args[flag]
end
--self:AddText("Testo"[,texture[,height[,width[,texcoords]]]])
--- Create a description (ace type "description")
-- @tparam string text
-- @tparam[opt] string image
-- @tparam[opt] number imageHeight
-- @tparam[opt] string imageWidth
-- @tparam[opt] table imageCoords
-- @treturn table Pointer to option table fragment added
function lib:AddText(text,image,imageHeight,imageWidth,imageCoords)
local group=getgroup(self)
local flag=toflag(group.name,text)
local t={
name=text,
type="description",
image=image,
imageHeight=imageHeight,
imageWidth=imageWidth,
imageCoords=imageCoords,
desc=text,
order=getorder(self,group),
}
group.args[flag]=t
return t
end
--self:AddToggle("AUTOLEAVE",true,"Quick Battlefield Leave","Alt-Click on hide button in battlefield alert leaves the queue")
function lib:AddBoolean(...) return self:AddToggle(...) end
--- Create a boolean configuration var
-- @tparam string flag variable name
-- @tparam any defaultvalue
-- @tparam string name public name (appears in gui)
-- @tparam[opt=name] string description long description (appears in tooltip)
-- @tparam[opt] string icon icon reference
-- @treturn table A reference to the newly create item inside Ace OptionTable
function lib:AddToggle(flag,defaultvalue,name,description,icon)
description=description or name
local group=getgroup(self)
local t={
name=name,
type="toggle",
get="OptToggleGet",
set="OptToggleSet",
desc=description,
width='full',
arg=flag,
cmdHidden=true,
icon=icon,
order=getorder(self,group),
}
lib.toggles[self][flag]=t
group.args[flag]=t
if (self.db.profile.toggles[flag]== nil) then
self.db.profile.toggles[flag]=defaultvalue
end
return t
end
-- self:AddEdit("REFLECTTO",1,{a=1,b=2},"Whisper reflection receiver:","All your whispers will be forwarded to this guy")
function lib:AddSelect(flag,defaultvalue,values,name,description)
description=description or name
local group=getgroup(self)
local t={
name=name,
type="select",
get="OptToggleGet",
set="OptToggleSet",
desc=description,
width="full",
values=values,
arg=flag,
cmdHidden=true,
order=getorder(self,group)
}
group.args[flag]=t
if (self.db.profile.toggles[flag]== nil) then
self.db.profile.toggles[flag]=defaultvalue
end
lib.toggles[self][flag]=t
return t
end
function lib:AddMultiSelect(flag,defaultvalue,...)
local t=self:AddSelect(flag,defaultvalue,...)
t.type="multiselect"
if type(self.db.profile.toggles[flag])~="table" then
self.db.profile.toggles[flag]={}
end
if type(self.db.profile.toggles[flag]._default)=="nil" then
self.db.profile.toggles[flag]=defaultvalue
self.db.profile.toggles[flag]._default=true
end
return t
end
--self:AddSlider("RESTIMER",5,1,10,"Enable res timer","Shows a timer for battlefield resser",1)
function lib:AddRange(...) return self:AddSlider(...) end
function lib:AddSlider(flag,defaultvalue,min,max,name,description,step)
description=description or name
min=min or 0
max=max or 100
local group=getgroup(self)
local isPercent=nil
if (type(step)=="boolean") then
isPercent=step
step=nil
else
step=tonumber(step) or 1
end
local t={
name=name,
type="range",
get="OptToggleGet",
set="OptToggleSet",
desc=description,
width="full",
arg=flag,
step=step,
isPercent=isPercent,
min=min,
max=max,
order=getorder(self,group),
}
group.args[flag]=t
if (self.db.profile.toggles[flag]== nil) then
self.db.profile.toggles[flag]=defaultvalue
end
lib.toggles[self][flag]=t
return t
end
-- self:AddEdit("REFLECTTO","","Whisper reflection receiver:","All your whispers will be forwarded to this guy","How to use it")
function lib:AddEdit(flag,defaultvalue,name,description,usage)
description=description or name
usage = usage or description
local group=getgroup(self)
local t={
name=name,
type="input",
get="OptToggleGet",
set="OptToggleSet",
desc=description,
arg=flag,
usage=usage,
order=getorder(self,group),
}
group.args[flag]=t
if (self.db.profile.toggles[flag]== nil) then
self.db.profile.toggles[flag]=defaultvalue
end
lib.toggles[self][flag]=t
return t
end
-- self:AddAction("openSpells","Opens spell panel","You can choose yoru spells in spell panel")
function lib:AddAction(method,label,description,private)
label=label or method
description=description or label
local group=getgroup(self)
local t={
func=method,
name=label,
type="execute",
desc=description,
confirm=false,
cmdHidden=true,
order=getorder(self,group)
}
if (private) then t.hidden=true end
group.args[strlower(label)]=t
lib.toggles[self][method]=t
return t
end
function lib:AddPrivateAction(method,name,description)
return self:AddAction(method,name,description,true)
end
function lib:AddKeyBinding(flag,name,description)
name=name or strlower(name)
description=description or name
local group=getgroup(self)
local t={
name=name,
type="keybinding",
get="OptToggleGet",
set="OptToggleSet",
desc=description,
arg=flag,
order=getorder(self,group)
}
group.args[flag]=t
lib.toggles[self][flag]=t
return t
end
function lib:AddTable(flag,table)
local group=getgroup(self)
group.args[flag]=table
lib.toggles[self][flag]=table
end
local function OpenCmd(self,info,args)
return self[info.arg](self,args,strsplit(' ',args))
end
function lib:AddOpenCmd(command,method,description,arguments,private)
method=method or command
description=description or command
local group=getgroup(self)
if (not private) then
local command=C('/' .. lib.options[self].ID .. ' ' .. command .. " (" .. description .. ")" ,'orange')
local t={
name=command,
type="description",
order=getorder(self,group),
fontSize='medium',
width='full'
}
group.args[command .. 'title']=t
end
local t={
name=command,
type="input",
arg=method,
get=function(...) end,
set=function(...) return OpenCmd(self,...) end,
desc=description,
order=getorder(self,group),
guiHidden=true,
hidden=private
}
if (type(arguments)=="table") then
local validate={}
for _,v in pairs(arguments) do
validate[v]=v
end
t.values=validate
t.type="select"
end
self.OptionsTable.args[command]=t
return t
end
function lib:AddPrivateOpenCmd(command,method,description,arguments)
return self:AddOpenCmd(command,method,description,arguments,true)
end
function lib:GetVarInfo(flag)
return lib.toggles[self][flag]
end
--self:AddSubCmd(flagname,method,label,description)
function lib:AddSubCmd(flag,method,name,description,input)
method=method or flag
name=name or flag
description=description or name
local group=getgroup(self)
debug("AddSubCmd " .. flag .. " for " .. method)
local t={
func=method,
name=name,
type="execute",
input=input,
desc=description,
confirm=true,
order=getorder(self,group),
guiHidden=true,
}
group.args[flag]=t
return t
end
--self:AddChatCmd(method,label,description)
function lib:AddChatCmd(method,label,description)
if (not self.RegisterChatCommand) then
LibStub("AceConsole-3.0"):Embed(self)
end
label=label or method
self:RegisterChatCommand(label,method)
description=description or label
local group=getgroup(self)
local t={
name=C('/' .. label .. " (" .. description .. ")",'orange'),
type="description",
order=getorder(self,group),
fontSize="medium",
width="full"
}
group.args[label .. 'title']=t
return t
end
--self:AddSeparator(text)
function lib:AddSeparator(text)
local group=getgroup(self)
local i=getorder(self,group)
local flag=group.name .. i
flag=flag:gsub('%W','')
local t={
name=text,
type="header",
order=i,
}
group.args[flag]=t
return t
end
function lib:Toggle()
if (self:IsEnabled()) then
self:Disable()
else
self:Enable()
end
end
function lib:Vars()
return pairs(self.db.profile.toggles)
end
function lib:SetBoolean(flag,value)
if (value) then
value=true
else
value=false
end
self.db.profile.toggles[flag]=value
return not value
end
function lib:GetBoolean(flag)
if (self.db.profile.toggles[flag]) then
return true
else
return false
end
end
lib.GetToggle=lib.GetBoolean -- alias
function lib:GetNumber(flag,default)
return tonumber(self:GetSet(flag) or default or 0)
end
function lib:GetString(flag,default)
return tostring(self:GetSet(flag) or default or '')
end
function lib:PrintBoolean(flag)
if (type(flag) == "string") then
flag=self:GetBoolean(flag)
end
if (flag) then
return on
else
return off
end
end
function lib:GetSet(...)
local flag,value=select(1,...)
if (select('#',...) == 2) then
self.db.profile.toggles[flag]=value
else
return self.db.profile.toggles[flag]
end
end
function lib:GetIndexedVar(flag,index)
local rc=GetVar(flag)
if index and type(rc)=="table" then
return rc[index]
else
return rc
end
end
function lib:GetVar(flag)
return self:GetSet(flag)
end
function lib:SetVar(flag,value)
return self:GetSet(flag,value)
end
--- Simulates a configuration variable change.
--
-- Generates Apply* events if needed
-- @tparam string flag Variable name
function lib:Trigger(flag)
local info=self:GetVarInfo(flag)
if (info) then
local value=info.type=="toggle" and self:GetBoolean(flag) or self:GetVar(flag)
self._Apply[flag](self,flag,value)
end
end
function lib:OptToggleSet(info,value,extra)
return self:ToggleSet(info.option.arg,info.option.type,value,extra)
end
function lib:ToggleSet(flag,tipo,value,extra)
if (tipo=="toggle") then
self:SetBoolean(flag,value)
elseif (tipo=="multiselect") then
self.db.profile.toggles[flag][value]=extra
else
self:GetSet(flag,value)
end
if (self:IsEnabled()) then
self._Apply[flag](self,flag,value)
end
end
function lib:OptToggleGet(info,extra)
return self:ToggleGet(info.option.arg,info.option.type,extra)
end
function lib:ToggleGet(flag,tipo,extra)
if (tipo=="toggle") then
return self:GetBoolean(flag)
elseif (tipo=="multiselect") then
if type(self.db.profile.toggles[flag])~="table" then
self.db.profile.toggles[flag]={}
end
return self.db.profile.toggles[flag][extra]
else
return self:GetSet(flag)
end
end
function lib:ApplySettings()
if (type(self.ApplyAll)=="function") then
self:ApplyAll()
else
for i,v in self:Vars() do
self._Apply[i](self,i,v)
end
end
end
--- Hooks.
-- Stub function you can (and should) overrid in your addon
-- @section hooks
--- Called When the embedding addon is enabled
--
function lib:OnEmbedEnable(first)
end
--- Called when the wmbedding addon is disabled
--
function lib:OnEmbedDisable()
end
--- Called after VARIABLES_LOADED event, by OnInitialize Ace Hook
--
function lib:OnInitialized()
print("|cff33ff99"..tostring( self ).."|r:",format(ITEM_MISSING,"OnInitialized"))
end
--- Called to fill the help system
--
function lib:LoadHelp()
end
--- Called with the db default table as argument
--
-- You can customize defaults here
--
-- @tparam table tbl ACE DB default table
function lib:SetDbDefaults(tbl)
end
--- Called with the current option table
--
-- You can change the default options table here
-- @tparam table tbl ACE Options Table
--
function lib:SetOptionsTable(tbl)
end
--- Called from the OnEnable ACE event
-- @function lib:OnEnabled
-- @tparam[opt] bool first True on the first activation
function lib:OnEnable()
if (self.OnEnabled) then
if (not self.db.global.silent) then
self:Print(C(VIDEO_OPTIONS_ENABLED,"green"))
end
pcall(self.OnEnabled,self,lib.options[self].first)
lib.options[self].first=nil
end
end
--- Called from the OnDisable ACE event
-- @function lib:OnDisabled
--
function lib:OnDisable(...)
if (self.OnDisabled) then
if (not self.db.global.silent) then
self.print(C(VIDEO_OPTIONS_DISABLED,'red'))
end
pcall(self.OnDisabled,self,...)
end
end
local function _GetMethod(target,prefix,func)
if (func == 'Start' or func == 'Stop') then return end
local method=prefix .. func
if (type(target[method])== "function") then
return method
elseif (type(target["_" .. prefix])) then
return "_" .. prefix
end
end
local neveropened=true
function lib:Gui(info)
if (AceConfigDialog and AceGUI) then
if (neveropened) then
InterfaceAddOnsList_Update()
neveropened=false
end
InterfaceOptionsFrame_OpenToCategory(self.CfgDlg)
else
self:Print("No GUI available")
end
end
function lib:Help(info)
if (AceConfigDialog and AceGUI) then
if (neveropened) then
InterfaceAddOnsList_Update()
neveropened=false
end
InterfaceOptionsFrame_OpenToCategory(self.CfgRel)
else
self:Print("No GUI available")
end
end
function lib:Long(msg) C:OnScreen('Yellow',msg,20) end
function lib:Onscreen_Orange(msg) C:OnScreen('Orange',msg,2) end
function lib:Onscreen_Purple(msg) C:OnScreen('Purple',msg,8) end
function lib:Onscreen_Yellow(msg) C:OnScreen('Yellow',msg,1) end
function lib:Onscreen_Azure(msg) C:OnScreen('Azure',msg,1) end
function lib:Onscreen_Red(msg) C:OnScreen('Red',msg,1) end
function lib:Onscreen_Green(msg) C:OnScreen('Green',msg,1) end
function lib:OnScreen(color,...) C:OnScreen(color,strjoin(' ',tostringall(...))) end
function lib:TimeToStr(time) -- Converts time data to a string format
local p,s,m,h;
if (not time) then
return ("0:00")
end
if (time < 0) then
time=abs(time)
p='-'
else
p=''
end
s = floor(mod(time, 60));
m = floor(time/ 60);
if (m > 59) then
h=floor(m/60)
m=floor(mod(m,60))
end
if (h) then
return format("%s%d:%02d:%02d",p,h,m,s)
else
return format("%s%d:%02d",p,m,s)
end
end
---
-- Returns a crayon like object
-- @usage
-- local C=LibStub("LibInit"):GetColorTable()
-- C.Azure.c --returns a string "rrggbb"
-- C.Azure.r --returns red value as a number
-- C.Azure.g --returns green value as a number
-- C.Azure.b --returns blue value as a number
-- tostring(C.Azure) -- returns a string "rrggbb"
-- "aa" .. C.Azure -- returns "aarrggbb"
-- C.Azure() -- returns r,g,b as float list
-- C.Azure.r -- returns r as float
-- C("testo","azure") -- returns "|cff" .. >color code for azure> .. "test" .. "|r"
-- -- For a list of available color check Colors
-- -- Each color became the name of a meth
function lib:GetColorTable()
return C
end
--- Returns a factory for lightweight widgets
-- @see factory
function lib:GetFactory()
return F
end
-- In case of upgrade, we need to redo embed for ALL Addons
-- This function get called on addon creation
-- Anything I define here is immediately available to newAddon method and in addon right after creation
function lib:Embed(target)
-- All methods are pulled in via metatable in order to not pollute addon table
local mt=getmetatable(target)
if not mt then mt={__tostring=function(me) return me.name end} end
mt.__index=lib.mixins
setmetatable(target,mt)
target._Apply=target._Apply or {}
target._Apply._handler=target
for k,v in pairs(self) do
if type(v)=="string" or type(v)=="number" then pp (self,k,v) end
end
setmetatable(target._Apply,varmeta)
lib.mixinTargets[target] = true
if type(lib.options[target])=="table" then -- Updating library version if needed
lib.options[target].libinit=MAJOR_VERSION .. ' ' .. MINOR_VERSION
end
end
local function fsort(a,b)
if type(a)=="number" then
a=format("%07d",a)
end
if type(b)=="number" then
b=format("%07d",b)
end
return b>a
end
local function kpairs(t,f)
local a = new()
f=f or fsort
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
del(a)
return nil
else
local k=a[i]
a[i]=nil -- Should optimize memory usage
return k, t[k]
end
end
return iter
end
function lib:Kpairs(t,f)
return kpairs(t,f)
end
--- Returns kpairs implementation
-- Deprecated in favour of Wrap("Kpairs")
--
function lib:GetKpairs()
return kpairs
end
lib.getKpairs=lib.GetKpairs
--- Implements PHP empty function.
-- @tparam any obj variable to be tested
-- @treturn boolean
function lib:Empty(obj)
if not obj then return true end -- Simplest case, obj evaluates to false in boolean context
local t=type(obj)
if t=="number" then
return obj==0
elseif t=="bool" then
return t
elseif t=="string" then
return obj=='' or obj==tostring(nil) or obj=="0"
elseif t=="table" then
return not next(obj)
end
return false -- Userdata and threads can never be empty
end
-- This metatable is used to generate a sorted proxy to an hashed table.
-- It should not used directly
lib.mt={__metatable=true,__version=MINOR_VERSION}
local mt=lib.mt
function mt:__index(k)
if k=="n" then
return #mt.keys[self.__source]
end
return self.__source[k]
end
function mt:__len()
return #self.__keys
end
function mt:__newindex(k,v)
local pos=#self.__keys+1
for i,x in ipairs(self.__keys) do
if x>k then
pos=i
break;
end
end
if (k:sub(1,2)~="__") then
table.insert(self.__keys,pos,k)
end
self.__source[k]=v -- We want to trigger metamethods on original table
end
function mt:__call()
do
local current=0
return function(unsorted,i)
current=current+1
local k=self.__keys[current]
if k then return k,self.__source[k] end
end,self,0
end
end
function lib:GetSortedProxy(table)
local proxy=setmetatable({__keys={},__source=table,__metatable=true},mt)
for k,v in pairs(table) do
proxy[k]=v
end
return proxy
end
function lib:ScheduleLeaveCombatAction(method, ...)
return self:OnLeaveCombat(method,...)
end
if not lib.secureframe then
lib.secureframe=CreateFrame("Button",nil,nil,"StaticPopupButtonTemplate,SecureActionButtonTemplate")
lib.secureframe:Hide()
end
local function StopSpellCasting(this)
local b2=_G[this:GetName().."Button2"]
local AC=lib.secureframe
AC:SetParent(b2)
AC:SetAllPoints()
AC:SetText(b2:GetText())
AC:SetAttribute("type","stop")
AC:SetScript("PostClick",function() b2:Click() end)
AC:Show()
end
local function StopSpellCastingCleanup(this)
local AC=lib.secureframe
AC:SetParent(nil)
AC:Hide()
end
local StaticPopupDialogs=StaticPopupDialogs
local StaticPopup_Show=StaticPopup_Show
--- Show a popup
-- Display a popup message with Accept and optionally Cancel button
-- @tparam string msg Message to be shown
-- @tparam[opt=60] number timeout In seconds, if omitted assumes 60
-- @tparam[opt] func OnAccept Executed when clicked on Accept
-- @tparam[opt] func OnCancel Executed when clicked on Cancel (if nill, Cancel button is not shown)
-- @tparam[opt] mixed data Passed to the callback function
-- @tparam[opt] bool StopCasting If true, when the popup appear will stop any running casting.
-- Useful to ask confirmation before performing a programmatic initiated spellcasting
function lib:Popup(msg,timeout,OnAccept,OnCancel,data,StopCasting)
if InCombatLockdown() then
return self:ScheduleLeaveCombatAction("Popup",msg,timeout,OnAccept,OnCancel,data,StopCasting)
end
msg=msg or "Something strange happened"
if type(timeout)=="function" then
StopCasting=data
data=OnCancel
OnAccept=timeout
timeout=60
end
StaticPopupDialogs["LIBINIT_POPUP"] = StaticPopupDialogs["LIBINIT_POPUP"] or
{
text = msg,
showAlert = true,
timeout = timeout or 60,
exclusive = true,
whileDead = true,
interruptCinematic = true
};
local popup=StaticPopupDialogs["LIBINIT_POPUP"]
if StopCasting then
popup.OnShow=StopSpellCasting
popup.OnHide=StopSpellCastingCleanup
else
popup.OnShow=nil
popup.OnHide=nil
end
popup.timeout=timeout
popup.text=msg
popup.OnCancel=nil
popup.OnAccept=OnAccept
popup.button1=ACCEPT
popup.button2=nil
if (OnCancel) then
if (type(OnCancel)=="function") then
popup.OnCancel=OnCancel
end
popup.button2=CANCEL
else
popup.button1=OKAY
end
return StaticPopup_Show("LIBINIT_POPUP",timeout,SECONDS,data);
end
--- Coroutines.
-- Methods to manage coroutines
-- @section coroutine
lib.coroutines=lib.coroutines or setmetatable({},{__index=function(t,k) rawset(t,k,{}) return t[k] end})
if not lib.CoroutineScheduler then
lib.CoroutineScheduler = CallbackHandler:New(lib,"_OnCoroutineEnd","_CancelOnCoroutine")
end
---
local coroutines=lib.coroutines --#Coroutines
--- Executes an action as soon as a coroutine exit
-- Action can be executed immediately if coroutine is already dead
-- @tparam string signature Coroutine indentifier as returined by coroutineExecute
-- @tparam string|function action To be executed, Can be a function or a method name
-- @tparam[opt] mixed ... More parameters will be directly passed to action
--
function lib:coroutineOnEnd(signature,action,...)
if type(action)~="string" and type(action)~="function" then
error("Usage: OnCoroutineEnd (\"action\", ...): 'action' - string or function expected.", 2)
end
if type(action)=="string" and type(self[action]) ~= "function" then
error("Usage: OnCoroutineEnd (\"action\", ...): 'action' - method '"..tostring(action).."' not found on self.", 2)
end
if type(action) =="string" then
dprint("onend",self,signature,action,...)
lib._OnCoroutineEnd(self,signature,Run,{self[action],self,...})
else
lib._OnCoroutineEnd(self,signature,Run,{action,...})
end
end
--- Generates and executes a coroutine with configurable interval and combat status
-- If called for already running coroutine changes the interval and the combat status
-- @tparam number interval between steps
-- @tparam string|function action To be executed, Can be a function or a method name
-- @tparam[opt] bool combatSafe keep running in combat
-- @tparam[opt] mixed more parameter are passed to function
-- @treturn string coroutine handle
function lib:coroutineExecute(interval,action,combatSafe,...)
local signature=strjoin(':',tostringall(self,action,...))
if type(action)=="string" then
action=self[action]
end
assert(type(action) =="function","coroutineExecute arg1 was not convertible to a function " .. tostring(action))
local c=lib.coroutines[signature]
c.signature=signature
c.interval=interval
c.combatSafe=combatSafe
if c.running then
return signature
end
if type(c.co)=="thread" and coroutine.status(c.co)=="suspended" then return signature end
c.co=coroutine.create(action)
c.running=true
c.paused=false
do
local args={...}
local obj=self
local c=c
c.repeater=function()
if not c.combatSafe and InCombatLockdown() then
c.waiting=true
return
end
if c.paused then return end
local rc,res=pcall(coroutine.resume,c.co,obj,unpack(args))
if rc and res then
C_Timer.After(c.interval,c.repeater)
else
if not rc then error(res,2) end
lib.coroutines[signature]=nil
lib.CoroutineScheduler:Fire(c.signature)
end
end
end
c.repeater()
return signature
end
lib.coroutineStart=lib.coroutineExecute -- alias
function lib:coroutineGet(signature)
return coroutines[signature]
end
function lib:coroutinePause(signature)
local co=coroutines[signature]
if co then
co.paused=true
end
end
function lib:coroutineRestart(signature)
local c=coroutines[signature]
if c then
if c.paused then
c.paused=false
local rc,res=pcall(c.repeater)
if not rc then error(res,2) end
end
end
end
function lib:coroutineGetList()
return coroutines
end
local C_Timer=C_Timer
local NDTProto={}
local NDTMeta={
__index=NDTProto,
__metatable=true,
}
function NDTProto:UpdateTimes(seconds)
seconds=seconds or self.delay
self.delay=seconds
self.expire=GetTime()+seconds-0.05
end
function NDTProto:Start(seconds)
self:UpdateTimes(seconds)
return self:Callback()
end
function NDTProto:Callback(reset)
if reset then self.running=false end
if self.expire <=GetTime() then
self.callback()
self=nil
else
if not self.running then
self:UpdateTimes()
C_Timer.After(self.delay,function() return self:Callback(true) end)
self.running=true
end
end
end
function NDTProto:New(callback)
local timer=setmetatable({},NDTMeta)
timer.expire=GetTime()
timer.delay=0.001
timer.callback=callback
return timer
end
--- Delayable timers
-- Create a timer that can be delayed. Useful for example for throttling sliders' events
-- This function just create the timer, to start (or delay) it use the :Start(seconds) method
-- @tparam function callback Function to be called at expire time
-- @treturn object
--
function lib:NewDelayableTimer(callback)
return NDTProto:New(callback)
end
--- Automatic events.
-- You can have automatic events creating methods with the name EvtEVENTNAME
-- For example in order to manage the event ADDON\_LOADED you can just define
-- a EvtADDON\_LOADED method
-- @section event
-- @usage
-- function addon:EvtADDON_LOADED(event,addonname)
-- end
-- function addon:OnEnabled()
-- self:StartAutomaticEvents()
-- end
-- function addon:OnDisabled()
-- self:StopAutomaticEvents()
-- end
---
-- Starts all automatic events.
-- Automatic events are the one for which exists and EvtEVENTNAME method
--
function lib:StartAutomaticEvents()
for k,v in pairs(self) do
if (type(v)=='function') then
if (k:sub(1,3)=='Evt') then
_G.print(self,"Registering",k)
self:Print("Registering",k)
self:RegisterEvent(k:sub(4),k)
end
end
end
end
---
-- Stops all automatic events.
-- Automatic events are the one for which exists and EvtEVENTNAME method
-- @tparam[opt] string ignore Name of an event method not to be stopped
-- @usage
-- self:StopAutomaticEvents("ADDON_LOADED")
-- -- Will stop all events but ADDON_LOADED
--
function lib:StopAutomaticEvents(ignore)
for k,v in pairs(self) do
if (type(v)=='function') then
if (k:sub(1,3)=='Evt') then
if (ignore and k==ignore or k:sub(4)==ignore) then
--a kickstart event not to be disabled
else
self:UnregisterEvent(k:sub(4))
end
end
end
end
end
local meta={__index=_G,
__newindex=function(t,k,v)
assert(type(_G[k]) == 'nil',"Attempting to override global " ..k)
return rawset(t,k,v)
end
}
function lib:SetCustomEnvironment(new_env)
local old_env = getfenv(2)
if old_env==new_env then return end
if getmetatable(new_env)==meta then return end
if not getmetatable(new_env) then
if not new_env.print then new_env.print=dprint end
setmetatable(new_env,meta)
new_env.dprint=dprint
else
assert(false,"new_env already has metatable")
end
setfenv(2, new_env)
end
for name,method in pairs(lib) do
if type(method)=="function" and name~="NewAddon" and name~="GetAddon" and name:sub(1,1)~="_" then
lib.mixins[name] = method
end
end
for target,_ in pairs(lib.mixinTargets) do
lib:Embed(target)
end
|
-----------------------------------------
-- Spell: Sacrifice
--
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/magic")
require("scripts/globals/msg")
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0
end
function onSpellCast(caster,target,spell)
local count = 1
local removables = {tpz.effect.FLASH, tpz.effect.BLINDNESS, tpz.effect.PARALYSIS, tpz.effect.POISON, tpz.effect.CURSE_I, tpz.effect.CURSE_II, tpz.effect.DISEASE, tpz.effect.PLAGUE}
-- remove one effect and add it to me
for i, effect in ipairs(removables) do
if (target:hasStatusEffect(effect)) then
spell:setMsg(tpz.msg.basic.MAGIC_ABSORB_AILMENT)
local statusEffect = target:getStatusEffect(effect)
-- only add it to me if I don't have it
if (caster:hasStatusEffect(effect) == false) then
caster:addStatusEffect(effect, statusEffect:getPower(), statusEffect:getTickCount(), statusEffect:getDuration())
end
target:delStatusEffect(effect)
return 1
end
end
spell:setMsg(tpz.msg.basic.MAGIC_NO_EFFECT) -- no effect
return 0
end
|
-- windwp/nvim-autopairs
local npairs = require 'nvim-autopairs'
local Rule = require 'nvim-autopairs.rule'
require('nvim-autopairs').setup({
disable_filetype = { 'TelescopePrompt' , 'vim' },
})
-- If you want insert `(` after select function or method item
local cmp_autopairs = require('nvim-autopairs.completion.cmp')
local cmp = require('cmp')
cmp.event:on( 'confirm_done', cmp_autopairs.on_confirm_done({ map_char = { tex = '' } }))
|
require "import"
import "android.widget.ArrayAdapter"
import "android.widget.LinearLayout"
import "android.widget.TextView"
import "java.io.File"
import "android.widget.ListView"
import "android.app.AlertDialog"
function ChoiceFile(StartPath)
--创建ListView作为文件列表
lv=ListView(activity).setFastScrollEnabled(true)
--创建路径标签
cp=TextView(activity)
lay=LinearLayout(activity).setOrientation(1).addView(cp).addView(lv)
function SetItem(path)
path=tostring(path)
ls=File(path).listFiles()
if ls~=nil then
ls=luajava.astable(File(path).listFiles()) --全局文件列表变量
table.sort(ls,function(a,b)
return (a.isDirectory()~=b.isDirectory() and a.isDirectory()) or ((a.isDirectory()==b.isDirectory()) and a.Name<b.Name)
end)
else
ls={}
end
QQ={}
for index,c in ipairs(ls) do
if string.find(c.Name,"config.json")~=nil then
QQ[#QQ+1]=c.Name:gsub("config.json","")
end
--print(c.Name)
end
end
SetItem(StartPath)
end
QQ目录= 本地目录.."/tencent/MobileQQ/WebViewCheck/"
ChoiceFile(QQ目录)
TIM目录= 本地目录.."/tencent/Tim/WebViewCheck/"
ChoiceFile(TIM目录)
--print(QQ[2])
function 加载图片(目录,QQ)
qqjpg.setImageBitmap(loadbitmap(目录..QQ[1]..".png"))
end
function 下载png(QQH)
thread(function(QQH,目录,QQ)
require "import"
import "http"
import "java.io.File"
QQ图片="http://q.qlogo.cn/headimg_dl?bs=qq&dst_uin="..QQH.."&src_uin=www.feifeiboke.com&fid=blog&spec=640"
http.download(QQ图片,目录..QQH..".png")
if File(tostring(目录..QQ[1]..".png")).length() > 30 then
call("加载图片",目录,QQ)
end
end,QQH,目录,QQ)
end
--获取图片
import "http"
if QQ[1]~=nil then
if File(目录..QQ[1]..".png").isFile() then
if File(tostring(目录..QQ[1]..".png")).length() > 30 then
qqjpg.setImageBitmap(loadbitmap(目录..QQ[1]..".png"))
else
qqjpg.setImageBitmap(loadbitmap("icon.png"))
下载png(QQ[1])
-- os.remove(目录..QQ[1]..".png")
end
else
if 网络>2 then
下载png(QQ[1])
-- qqjpg.setImageBitmap(loadbitmap(目录..QQ[1]..".png"))
else
qqjpg.setImageBitmap(loadbitmap("icon.png"))
-- os.remove(目录..QQ[1]..".png")
end
end
else
print("没有检测到QQ号,无法加载图片……")
qqjpg.setImageBitmap(loadbitmap("icon.png"))
end
-- then
--搭配图片
--qqjpg.setImageBitmap(loadbitmap("imgs/1.jpg"))
--end
for i=1,#QQ do
缓存("\nQQ"..i..":.-:QQ"..i,"\nQQ"..i..":"..QQ[i]..":QQ"..i.."\n")
end |
RegisterServerEvent('InitialCore:NotifAppelLTD')
AddEventHandler("InitialCore:NotifAppelLTD", function()
TriggerClientEvent('InitialCore:NotifAppelLTDC', -1)
end)
RegisterServerEvent('InitialCore:AppelAcceptedLtd')
AddEventHandler('InitialCore:AppelAcceptedLtd', function()
local PlayerIdentifier = GetPlayerIdentifier(source)
MySQL.Async.fetchAll('SELECT Prenom, Nom FROM playerinfo WHERE SteamID = \'' .. PlayerIdentifier .. '\'', {}, function(result)
TriggerClientEvent('InitialCore:AppelAcceptedLTDC', -1, result[1].Prenom .. " " .. result[1].Nom)
end)
end) |
local fn = require('tmux.lib.fn')
local registry = require('tmux.lib.registry')
local cmds = require('tmux.commands')
return fn.nested(2, function (P, M)
function start_insert()
vim.defer_fn(function ()
P.last.status = -1
if vim.bo.buftype == 'terminal' then
vim.cmd('startinsert!')
end
end, 10)
end
function on_cmdline_leave(event)
if event.cmdtype == ':' then
start_insert()
end
end
registry.auto('BufEnter', start_insert)
registry.auto('CmdlineLeave', 'call ' .. registry.call_for_fn(on_cmdline_leave, 'v:event'))
registry.auto('TermOpen', 'startinsert!')
registry.auto({ 'InsertEnter', 'TermEnter' }, function ()
vim.defer_fn(function ()
if vim.bo.buftype == 'terminal' then
vim.cmd('nohlsearch')
end
end, 10)
end)
function on_terminal_close(event)
P.last.status = event.status
-- if terminal was not killed
if P.last.status ~= -1 then
vim.defer_fn(function ()
cmds.kill_pane({})(P)(M)
end, 10)
end
end
registry.auto('TermClose', 'call ' .. registry.call_for_fn(on_terminal_close, 'v:event'))
function on_tab_leave()
P.last.tabpage = vim.fn.tabpagenr()
end
registry.auto('TabLeave', on_tab_leave)
end)
|
-- Best/Worst Window
return function()
local JudgNames = LoadModule("Options.SmartTapNoteScore.lua")()
table.sort(JudgNames)
-- We need to check what is the worst window available.
local CurPrefTiming = LoadModule("Config.Load.lua")("SmartTimings","Save/OutFoxPrefs.ini")
local LowestWindow = nil
local HighestWindow = nil
local n = LoadModule( "Options.ReturnCurrentTiming.lua" )()
-- Now, calculate the lowest.
for k,v in pairs( JudgNames ) do
-- lua.ReportScriptError( v )
if n.Timings[ "TapNoteScore_"..v ] > 0 then
local ConvertedTime = GetWindowSeconds(n.Timings[ "TapNoteScore_"..v ], 1, 0)
if not HighestWindow then HighestWindow = ConvertedTime end
LowestWindow = ConvertedTime
end
end
return LowestWindow, HighestWindow
end |
------------------------------------
-- XAF Module - Network:REPClient --
------------------------------------
-- [>] This is the client side module of Remote Executor Protocol.
-- [>] It allows requesting for executing remote located scripts.
-- [>] That class implements mechanisms for returning received parameters for performed program.
local client = require("xaf/network/client")
local xafcore = require("xaf/core/xafcore")
local xafcoreText = xafcore:getTextInstance()
local RepClient = {
C_NAME = "Generic REP Client",
C_INSTANCE = true,
C_INHERIT = true,
static = {}
}
function RepClient:initialize()
local parent = client:extend()
local private = (parent) and parent.private or {}
local public = (parent) and parent.public or {}
public.execute = function(self, scriptPath, ...) -- [!] Function: execute(scriptPath, ...) - Sends 'REP_EXECUTE' request type to the REP server.
assert(type(scriptPath) == "string", "[XAF Network] Expected STRING as argument #1") -- [!] Parameter: scriptPath - Relative path of script to be parformed.
-- [!] Parameter: ... - Optional arguments passed to the target program.
local scriptRelativePath = scriptPath -- [!] Return: ... - Boolean flag of request status and optional returned arguments from executed script.
local scriptParameters = {...}
return private:sendRawRequest("REP_EXECUTE", scriptRelativePath, table.unpack(scriptParameters))
end
public.executeAbsolute = function(self, scriptPath, ...) -- [!] Function: executeAbsolute(scriptPath, ...) - Sends 'REP_EXECUTE_ABSOLUTE' request type to the REP server.
assert(type(scriptPath) == "string", "[XAF Network] Expected STRING as argument #1") -- [!] Parameter: scriptPath - Absolute path of the script to be execute, in entire server file tree.
-- [!] Parameter: ... - Optional arguments passed to the targed script.
local scriptAbsolutePath = scriptPath -- [!] Return: ... - Boolean flag of request procession and optional returned values from performed program.
local scriptParameters = {...}
return private:sendRawRequest("REP_EXECUTE_ABSOLUTE", scriptAbsolutePath, table.unpack(scriptParameters))
end
public.executeCommand = function(self, scriptCommand, ...) -- [!] Function: executeCommand(scriptCommand, ...) - Sends 'REP_EXECUTE_COMMAND' request type to REP server.
assert(type(scriptCommand) == "string", "[XAF Network] Expected STRING as argument #1") -- [!] Parameter: scriptCommand - Name of given command to execute on the server.
-- [!] Parameter: ... - Optional arguments passed to the command.
local scriptCommandName = scriptCommand -- [!] Return: ... - Response status and its message - this function does not return any values from execution.
local scriptParameters = {...}
return private:sendRawRequest("REP_EXECUTE_COMMAND", scriptCommandName, table.unpack(scriptParameters))
end
public.executeNoProtect = function(self, scriptPath, ...) -- [!] Function: executeNoProtect(scriptPath, ...) - Sends 'REP_EXECUTE_NO_PROTECT' request to the target REP server.
assert(type(scriptPath) == "string", "[XAF Network] Expected STRING as argument #1") -- [!] Parameter: scriptPath - Relative path of target script to be executed.
-- [!] Parameter: ... - Optional argument list passed to the script.
local scriptRelativePath = scriptPath -- [!] Return: ... - Boolean flag of exeution status and optional returned argument list.
local scriptParameters = {...}
return private:sendRawRequest("REP_EXECUTE_NO_PROTECT", scriptRelativePath, table.unpack(scriptParameters))
end
public.executeNoReturn = function(self, scriptPath, ...) -- [!] Function: executeNoReturn(scriptPath, ...) - Sends 'REP_EXECUTE_NO_RETURN' request to target REP server.
assert(type(scriptPath) == "string", "[XAF Network] Expected STRING as argument #1") -- [!] Parameter: scriptPath - Relative path of script to execute.
-- [!] Parameter: ... - Argument list passed to the target script.
local scriptRelativePath = scriptPath -- [!] Return: ... - Response status and its message - no execution results returned from the response.
local scriptParameters = {...}
return private:sendRawRequest("REP_EXECUTE_NO_RETURN", scriptRelativePath, table.unpack(scriptParameters))
end
public.scriptList = function(self) -- [!] Function: scriptList() - Sends 'REP_SCRIPT_LIST' request type to the target REP server.
local scriptTable = {} -- [!] Return: responseStatus, responseMessage, scriptTable - Response status, message and retrieved full script list as Lua table.
local responseStatus, responseMessage, responseData = private:sendRawRequest("REP_SCRIPT_LIST")
scriptTable = xafcoreText:split(responseData, string.char(0), true)
return responseStatus, responseMessage, scriptTable
end
return {
private = private,
public = public
}
end
function RepClient:extend()
local class = self:initialize()
local private = class.private
local public = class.public
if (self.C_INHERIT == true) then
return {
private = private,
public = public
}
else
error("[XAF Error] Class '" .. tostring(self.C_NAME) .. "' cannot be inherited")
end
end
function RepClient:new(modem)
local class = self:initialize()
local private = class.private
local public = class.public
public:setModem(modem)
if (self.C_INSTANCE == true) then
return public
else
error("[XAF Error] Class '" .. tostring(self.C_NAME) .. "' cannot be instanced")
end
end
return RepClient
|
/*
@library : rlib
@docs : https://docs.rlib.io
IF YOU HAVE NOT DIRECTLY RECEIVED THESE FILES FROM THE DEVELOPER, PLEASE CONTACT THE DEVELOPER
LISTED ABOVE.
THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE COMMONS PUBLIC LICENSE
('CCPL' OR 'LICENSE'). THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF
THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED.
BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE TO BE BOUND BY THE TERMS
OF THIS LICENSE. TO THE EXTENT THIS LICENSE MAY BE CONSIDERED TO BE A CONTRACT, THE LICENSOR GRANTS
YOU THE RIGHTS CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND CONDITIONS.
UNLESS OTHERWISE MUTUALLY AGREED TO BY THE PARTIES IN WRITING, LICENSOR OFFERS THE WORK AS-IS AND
ONLY TO THE EXTENT OF ANY RIGHTS HELD IN THE LICENSED WORK BY THE LICENSOR. THE LICENSOR MAKES NO
REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE WORK, EXPRESS, IMPLIED, STATUTORY OR
OTHERWISE, INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MARKETABILITY, MERCHANTIBILITY,
FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY,
OR THE PRESENCE OF ABSENCE OF ERRORS, WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE
EXCLUSION OF IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU.
*/
/*
library
*/
local base = rlib
local helper = base.h
local access = base.a
local ui = base.i
local tools = base.t
/*
library > localize
*/
local cfg = base.settings
local mf = base.manifest
local pf = mf.prefix
/*
languages
*/
local function ln( ... )
return base:lang( ... )
end
/*
prefix > get id
*/
local function pid( str, suffix )
local state = ( isstring( suffix ) and suffix ) or ( base and pf ) or false
return base.get:pref( str, state )
end
/*
* tools > diag > run
*
* diag interface
*/
function tools.diag:Run( )
if not access:bIsDev( LocalPlayer( ) ) then return end
if ui:ok( tools.diag.pnl ) then
tools.diag.pnl:ActionToggle( )
return
end
tools.diag.pnl = vgui.Create( 'rlib.lo.diag' )
end
rcc.new.gmod( pid( 'diag' ), tools.diag.Run )
/*
* tools > lang > run
*
* language selection interface
*/
function tools.lang:Run( )
if ui:ok( tools.lang.pnl ) then
ui:dispatch( tools.lang.pnl )
return
end
tools.lang.pnl = ui.new( 'rlib.lo.language' )
:title ( ln( 'lang_sel_title' ) )
:actshow ( )
end
rcc.new.gmod( pid( 'lang' ), tools.lang.Run )
/*
* tools > mdlv > run
*
* model viewer interface
*/
function tools.mdlv:Run( )
if ui:visible( tools.mdlv.pnl ) then
ui:dispatch( tools.mdlv.pnl )
end
tools.mdlv.pnl = ui.new( 'rlib.lo.mdlv' )
:title ( ln( 'mdlv_title' ) )
:actshow ( )
end
rcc.new.gmod( pid( 'mview' ), tools.mdlv.Run )
/*
* tools > pco > run
*
* optimization tool which helps adjust a few game vars in order to cut back and save frames.
* should only be used if you actually know what changes this makes
*
* @param : bool bEnable
*/
function tools.pco:Run( bEnable )
bEnable = bEnable or false
for k, v in pairs( helper._pco_cvars ) do
local val = ( bEnable and ( v.on or 1 ) ) or ( v.off or 0 )
rcc.run.gmod( v.id, val )
end
if cfg.pco.hooks then
for k, v in pairs( helper._pco_hooks ) do
if bEnable then
hook.Remove( v.event, v.name )
else
hook.Add( v.event, v.name )
end
end
end
hook.Add( 'OnEntityCreated', 'rlib_widget_entcreated', function( ent )
if ent:IsWidget( ) then
hook.Add( 'PlayerTick', 'rlib_widget_tick', function( pl, mv )
widgets.PlayerTick( pl, mv )
end )
hook.Remove( 'OnEntityCreated', 'rlib_widget_entcreated' )
end
end )
end
/*
* tools > welcome > run
*
* welcome interface for ?setup
*/
function tools.welcome:Run( )
if not access:bIsRoot( LocalPlayer( ) ) then return end
/*
* destroy existing pnl
*/
if ui:ok( tools.welcome.pnl ) then
ui:dispatch( tools.welcome.pnl )
return
end
/*
* about > network update check
*/
net.Start ( 'rlib.welcome' )
net.SendToServer ( )
/*
* create / show parent pnl
*/
tools.welcome.pnl = ui.new( 'rlib.lo.welcome' )
:title ( ln( 'welcome_title' ) )
:actshow ( )
end
rcc.new.gmod( pid( 'welcome' ), tools.welcome.Run, nil, nil, FCVAR_PROTECTED )
/*
* netlib > tools > lang
*
* initializes lang selector ui
*/
local function netlib_lang( )
tools.lang:Run( )
end
net.Receive( 'rlib.tools.lang', netlib_lang )
/*
* netlib > tools > mviewer
*
* net.Receive to open model viewer
*/
local function netlib_mdlv( )
tools.mdlv:Run( )
end
net.Receive( 'rlib.tools.mdlv', netlib_mdlv )
/*
* netlib > tools > pco
*
* player-client-optimizations
*/
local function netlib_pco( )
local b = net.ReadBool( )
tools.pco:Run( b )
end
net.Receive( 'rlib.tools.pco', netlib_pco )
/*
* netlib > tools > diag
*
* initializes diag ui
*/
local function netlib_diag( )
if not access:bIsRoot( LocalPlayer( ) ) then return end
tools.diag:Run( )
end
net.Receive( 'rlib.tools.diag', netlib_diag )
/*
* think > keybinds > diag
*
* checks to see if the assigned keys are being pressed to activate the diag ui
*/
local i_th_diag = 0
local function th_binds_diag( )
if not access:bIsRoot( LocalPlayer( ) ) then
hook.Remove( 'Think', pid( 'keybinds.diag' ) )
return
end
if gui.IsConsoleVisible( ) then return end
local iKey1, iKey2 = cfg.diag.binds.key1, cfg.diag.binds.key2
local b_Keybfocus = vgui.GetKeyboardFocus( )
if LocalPlayer( ):IsTyping( ) or b_Keybfocus then return end
helper.get.keypress( iKey1, iKey2, function( )
if i_th_diag > CurTime( ) then return end
tools.diag:Run( )
i_th_diag = CurTime( ) + 1
end )
end
hook.Add( 'Think', pid( 'keybinds.diag' ), th_binds_diag ) |
function div(a, b) return math.floor(a/b) end
moy = {Jan=1, Feb=2, Mar=3, Apr=4, May=5, Jun=6,
Jul=7, Aug=8, Sep=9, Oct=10, Nov=11, Dec=12}
function month(s)
return 12*(tonumber(s:sub(5, 8))-1990) + moy[s:sub(1, 3)] - 1
end
for line in io.lines(arg[1]) do
local work, w = {}, 0
for i in line:gsub("; ", ";"):gmatch("[^;]+") do
for j = month(i:sub(1, 8)), month(i:sub(10, 17)) do
work[j] = true
end
end
for _, _ in pairs(work) do w = w + 1 end
print(div(w, 12))
end
|
-- Copyright 2015-2017 David B. Lamkins <david@lamkins.net>. See LICENSE.
-- man/roff LPeg lexer.
local l = require('lexer')
local token, word_match = l.token, l.word_match
local P, R, S = lpeg.P, lpeg.R, lpeg.S
local M = {_NAME = 'man'}
-- Whitespace.
local ws = token(l.WHITESPACE, l.space^1)
-- Markup.
local rule1 = token(l.STRING,
P('.') * (P('B') * P('R')^-1 + P('I') * P('PR')^-1) *
l.nonnewline^0)
local rule2 = token(l.NUMBER, P('.') * S('ST') * P('H') * l.nonnewline^0)
local rule3 = token(l.KEYWORD,
P('.br') + P('.DS') + P('.RS') + P('.RE') + P('.PD'))
local rule4 = token(l.LABEL, P('.') * (S('ST') * P('H') + P('.TP')))
local rule5 = token(l.VARIABLE,
P('.B') * P('R')^-1 + P('.I') * S('PR')^-1 + P('.PP'))
local rule6 = token(l.TYPE, P('\\f') * S('BIPR'))
local rule7 = token(l.PREPROCESSOR, l.starts_line('.') * l.alpha^1)
M._rules = {
{'whitespace', ws},
{'rule1', rule1},
{'rule2', rule2},
{'rule3', rule3},
{'rule4', rule4},
{'rule5', rule5},
{'rule6', rule6},
{'rule7', rule7},
}
return M
|
local Area = Object:extend()
function Area:new()
end
function Area:update(dt)
end
function Area:draw()
end
return Area
|
local model_convert = {}
-- ------------------------------------------------------------------------
-- PROPERTY CONVERTIONS
function model_convert.face_2_edges (face)
local x, y, z = face[1], face[2], face[3]
return {{x, y}, {y, z}, {z, x}}
end
function model_convert.faces_2_edges (faces)
local edges = {}
for _i, f in ipairs(faces) do
local f_edges = model_convert.face_2_edges(f)
for _i, e in ipairs(f_edges) do
table.insert(edges, e)
end
end
return edges
end
-- ------------------------------------------------------------------------
return model_convert
|
getglobal game
getfield -1 ReplicatedStorage
getfield -1 Functions
getfield -1 TradeGem
getfield -1 InvokeServer
pushvalue -2
pushstring Blue Gems
pushstring 1000000000
pcall 3 1 0 |
require("engine/test/unittest_helper")
--#if log
local _logging = require("engine/debug/logging")
--#endif
local p8utest = {}
-- unit test framework mimicking some busted features
-- for direct use in pico8 headless
-- busted features supported: "it" as "check" (immediate assert, no collection of test results)
-- unit test manager: registers all utests and runs them
-- utests [utest] registered utests
utest_manager = singleton(function (self)
self.utests = {}
end)
p8utest.utest_manager = utest_manager
function utest_manager:register(utest)
add(self.utests, utest)
end
function utest_manager:run_all_tests()
for utest in all(self.utests) do
-- In general, the assert message will be so long that the previous prints won't be visible
-- so instead, we print to console so in case of failure, we can check the last test
-- that started. This way, no need to give a meaningful assert message in each utest,
-- unless there are some interesting variables to print.
-- Of course, if we apply the suggestion below and track all tests before summing everything
-- up (like pico-test, but storing test state internally rather than streaming to output),
-- we could print all the test results properly to the console.
log("start pico8 utest: "..utest.name)
-- For now, callback should test directly with assert which will stop at the first failure,
-- but it's not convenient to continue running other tests after a failure
-- to sum-up later, so consider making a custom verify function that
-- checks a boolean and if false, will print that the test failed later
utest.callback(utest.name)
end
end
-- unit test class for pico8
local unit_test = new_class()
p8utest.unit_test = unit_test
-- parameters
-- name string test name
-- callback function test callback, containing assertions
function unit_test:_init(name, callback)
self.name = name
self.callback = callback
end
-- busted-like shortcut functions
function check(name, callback)
local utest = unit_test(name, callback)
utest_manager:register(utest)
end
-- helper assert function that will print error message
-- to any registered log (mostly console), and assert
-- with utest name
-- this is useful because assert detailed message is often
-- too long for PICO-8 assert to print, but utest name is not
-- use instead of assert()
function assert_log(utest_name, condition, msg)
if not condition then
log(msg)
assert(false, utest_name)
end
end
return p8utest
|
return {
summary = 'Set the dimensions of the BoxShape.',
description = 'Sets the width, height, and depth of the BoxShape.',
arguments = {
{
name = 'width',
type = 'number',
description = 'The width of the box, in meters.'
},
{
name = 'height',
type = 'number',
description = 'The height of the box, in meters.'
},
{
name = 'depth',
type = 'number',
description = 'The depth of the box, in meters.'
}
},
returns = {}
}
|
local task = require('lua-channels')
local function counter(c)
local i = 2
while true do
c:send(i)
i = i + 1
end
end
local function filter(p, recv_ch, send_ch)
while true do
local i = recv_ch:recv()
if i % p ~= 0 then
send_ch:send(i)
end
end
end
local function sieve(primes_ch)
local c = task.Channel:new()
task.spawn(counter, c)
while true do
local p, newc = c:recv(), task.Channel:new()
primes_ch:send(p)
task.spawn(filter, p, c, newc)
c = newc
end
end
local function main()
local primes = task.Channel:new()
task.spawn(sieve, primes)
for i = 1, 10 do
print(primes:recv())
end
end
task.spawn(main)
task.scheduler()
|
include "./vendor/premake/premake_customization/solution_items.lua"
include "Dependencies.lua"
workspace "Rage"
architecture "x86_64"
startproject "Ragenut"
configurations
{
"Debug",
"Release",
"Dist"
}
solution_items
{
".editorconfig"
}
flags
{
"MultiProcessorCompile"
}
outputdir = "%{cfg.buildcfg}-%{cfg.system}-%{cfg.architecture}"
group "Dependencies"
include "vendor/premake"
include "Rage/vendor/Box2D"
include "Rage/vendor/GLFW"
include "Rage/vendor/Glad"
include "Rage/vendor/imgui"
include "Rage/vendor/yaml-cpp"
group ""
include "Rage"
include "Sandbox"
include "Ragenut"
|
local path = require 'path'
local toml = require 'toml'
local Logs = require 'lib.logs'
local colors = require 'lib.colors'
require 'lib.table'
local Config = {}
local IS_WIN = package.config:sub(1,1) == "\\"
local HOME = IS_WIN and (os.getenv("APPDATA") .. "\\YGOFabrica") or (os.getenv("HOME") .. "/ygofab")
local FIELDS = {
gamedir = { path = true },
picset = { mode = true },
expansion = { recipe = true }
}
local merge, concat = table.merge, table.concat
local function validate(cfg, fields)
for k, f in pairs(fields or FIELDS) do
local c = cfg[k]
if type(f) == 'table' then
if not c or type(c) ~= 'table' then
cfg[k] = {}
end
for ck, c in pairs(cfg[k]) do
if not validate(c, f) then
cfg[k][ck] = nil
end
end
elseif not c then
return false
end
end
return true
end
local function load_file(path)
local cfg = io.open(path, "r")
if not cfg then
return nil
end
local config = toml.parse(cfg:read('*a'))
cfg:close()
validate(config)
return config
end
local function format_list(cfg, title, fmt)
local list = {}
for k, v in pairs(cfg) do
list[#list + 1] = fmt(k, v)
end
if list and #list > 0 then
table.sort(list)
list = concat(list)
list = (" %s%s:%s\n%s")
:format(colors.FG_MAGENTA, title, colors.RESET, list)
else
list = (" %s[!]%s You have no %s configured.\n")
:format(colors.FG_YELLOW, colors.RESET, title:lower())
end
return list
end
local function format(cfg)
local gamedirs = format_list(cfg.gamedir, "Game directories", function(k, v)
return (" %s: %q%s\n"):format(k, v.path, v.default and " (default)" or "")
end)
local picsets = format_list(cfg.picset, "Pic sets", function(k, v)
return (" %s: %s%s%s%s%s\n"):format(k, v.mode,
v.size and " --size " .. v.size or "",
v.ext and " --ext " .. v.ext or "",
v.field and " --field" or "", v.default and " (default)" or "")
end)
local expansions = format_list(cfg.expansion, "Expansions", function(k, v)
local recipe = type(v.recipe) == 'table' and v.recipe or {}
return (" %s: %s%s\n"):format(k, "[" .. concat(recipe, ", ") .. "]",
v.default and " (default)" or "")
end)
return gamedirs .. "\n" .. picsets .. "\n" .. expansions
end
function Config.get(pwd)
local empty = {}
validate(empty)
local global_cfg = load_file(path.join(HOME, "config.toml")) or empty
local local_cfg = load_file(path.join(pwd, "config.toml"))
return local_cfg, global_cfg
end
function Config.get_one(pwd, key, id)
local local_cfg, global_cfg = Config.get(pwd)
local lc = local_cfg and local_cfg[key][id] or nil
local gc = global_cfg[key][id]
return lc or gc
end
function Config.get_default(pwd, key)
local local_cfg, global_cfg = Config.get(pwd)
local function search(t)
for id, c in pairs(t) do
if c.default then return id, c end
end
return nil
end
local id, c = search(local_cfg and local_cfg[key] or {})
if id then
return id, c
else
return search(global_cfg[key])
end
end
function Config.get_defaults(pwd, key)
local local_cfg, global_cfg = Config.get(pwd)
local cfg = {}
merge(cfg, global_cfg)
merge(cfg, local_cfg or {})
local cs = {}
for id, c in pairs(cfg[key]) do
if c.default then
cs[id] = c
end
end
return cs
end
function Config.get_all(pwd, key)
local local_cfg, global_cfg = Config.get(pwd)
local cfg = {}
merge(cfg, global_cfg)
merge(cfg, local_cfg or {})
return cfg[key]
end
setmetatable(Config, { __call = function(_, pwd)
local local_cfg, global_cfg = Config.get(pwd)
local fglobal_cfg, errmsg = format(global_cfg)
Logs.assert(fglobal_cfg, 1, errmsg)
Logs.info(colors.FG_MAGENTA, colors.BOLD, "Global configurations:\n\n",
colors.RESET, fglobal_cfg)
if local_cfg then
local flocal_cfg, errmsg = format(local_cfg)
Logs.assert(flocal_cfg, 1, errmsg)
Logs.info(colors.FG_MAGENTA, colors.BOLD, "Local configurations:\n\n",
colors.RESET, flocal_cfg)
end
end })
return Config
|
local PPM2
PPM2 = _G.PPM2
local ENABLE_FLASHLIGHT_PASS = CreateConVar('ppm2_flashlight_pass', '1', {
FCVAR_ARCHIVE
}, 'Enable flashlight render pass. This kills FPS.')
local ENABLE_LEGS = CreateConVar('ppm2_draw_legs', '1', {
FCVAR_ARCHIVE
}, 'Draw pony legs.')
local USE_RENDER_OVERRIDE = CreateConVar('ppm2_legs_new', '1', {
FCVAR_ARCHIVE
}, 'Use RenderOverride function for legs drawing')
local LEGS_RENDER_TYPE = CreateConVar('ppm2_render_legstype', '0', {
FCVAR_ARCHIVE
}, 'When render legs. 0 - Before Opaque renderables; 1 - after Translucent renderables')
local ENABLE_STARE = CreateConVar('ppm2_render_stare', '1', {
FCVAR_ARCHIVE
}, 'Make eyes follow players and move when idling')
local PonyRenderController
do
local _class_0
local _parent_0 = PPM2.ControllerChildren
local _base_0 = {
CompileTextures = function(self)
if self.GetTextureController and self:GetTextureController() then
return self:GetTextureController():CompileTextures()
end
end,
GetModel = function(self)
return self.controller:GetModel()
end,
GetLegs = function(self)
if not self.isValid then
return NULL
end
if self:GetEntity() ~= LocalPlayer() then
return NULL
end
if not IsValid() then
self:CreateLegs()
end
return self.legsModel
end,
CreateLegs = function(self)
if not self.isValid then
return NULL
end
if self:GetEntity() ~= LocalPlayer() then
return NULL
end
for _, ent in ipairs(ents.GetAll()) do
if ent.isPonyLegsModel then
ent:Remove()
end
end
do
local _with_0 = ClientsideModel(self.modelCached)
self.legsModel = _with_0
_with_0.isPonyLegsModel = true
_with_0.lastRedrawFix = 0
_with_0:SetNoDraw(true)
_with_0.__PPM2_PonyData = self:GetData()
end
self:GetData():GetWeightController():UpdateWeight(self.legsModel)
self.lastLegUpdate = CurTimeL()
self.legClipPlanePos = Vector(0, 0, 0)
self.legBGSetup = CurTimeL()
self.legUpdateFrame = 0
self.legClipDot = 0
self.duckOffsetHack = self.__class.LEG_CLIP_OFFSET_STAND
self.legsClipPlane = self.__class.LEG_CLIP_VECTOR
return self.legsModel
end,
UpdateLegs = function(self)
if not self.isValid then
return
end
if not ENABLE_LEGS:GetBool() then
return
end
if not (IsValid(self.legsModel)) then
return
end
if self.legUpdateFrame == FrameNumberL() then
return
end
self.legUpdateFrame = FrameNumberL()
local ctime = CurTimeL()
local ply = self:GetEntity()
local seq = ply:GetSequence()
local legsModel = self.legsModel
do
local _with_0 = self.legsModel
if ply.__ppmBonesModifiers then
PPM2.EntityBonesModifier.ThinkObject(ply.__ppmBonesModifiers)
end
for boneid = 0, ply:GetBoneCount() - 1 do
_with_0:ManipulateBonePosition(0, ply:GetManipulateBonePosition(0))
_with_0:ManipulateBoneAngles(0, ply:GetManipulateBoneAngles(0))
_with_0:ManipulateBoneScale(0, ply:GetManipulateBoneScale(0))
end
if seq ~= self.legSeq then
self.legSeq = seq
_with_0:ResetSequence(seq)
end
if self.legBGSetup < ctime then
self.legBGSetup = ctime + 1
for _, group in ipairs(ply:GetBodyGroups()) do
_with_0:SetBodygroup(group.id, ply:GetBodygroup(group.id))
end
end
_with_0:FrameAdvance(ctime - self.lastLegUpdate)
_with_0:SetPlaybackRate(self.__class.LEG_ANIM_SPEED_CONST * ply:GetPlaybackRate())
self.lastLegUpdate = ctime
_with_0:SetPoseParameter('move_x', (ply:GetPoseParameter('move_x') * 2) - 1)
_with_0:SetPoseParameter('move_y', (ply:GetPoseParameter('move_y') * 2) - 1)
_with_0:SetPoseParameter('move_yaw', (ply:GetPoseParameter('move_yaw') * 360) - 180)
_with_0:SetPoseParameter('body_yaw', (ply:GetPoseParameter('body_yaw') * 180) - 90)
_with_0:SetPoseParameter('spine_yaw', (ply:GetPoseParameter('spine_yaw') * 180) - 90)
end
if ply:InVehicle() then
local bonePos
do
local bone = self.legsModel:LookupBone('LrigNeck1')
if bone then
do
local boneData = self.legsModel:GetBonePosition(bone)
if boneData then
bonePos = boneData
end
end
end
end
local veh = ply:GetVehicle()
local vehAng = veh:GetAngles()
local eyepos = EyePos()
vehAng:RotateAroundAxis(vehAng:Up(), 90)
local clipAng = Angle(vehAng.p, vehAng.y, vehAng.r)
clipAng:RotateAroundAxis(clipAng:Right(), -90)
self.legsClipPlane = clipAng:Forward()
self.legsModel:SetRenderAngles(vehAng)
local drawPos = Vector(self.__class.LEG_SHIFT_CONST_VEHICLE, 0, self.__class.LEG_Z_CONST_VEHICLE)
drawPos:Rotate(vehAng)
self.legsModel:SetPos(eyepos - drawPos)
self.legsModel:SetRenderOrigin(eyepos - drawPos)
if not bonePos then
local legClipPlanePos = Vector(0, 0, self.__class.LEG_CLIP_OFFSET_VEHICLE)
legClipPlanePos:Rotate(vehAng)
self.legClipPlanePos = eyepos - legClipPlanePos
else
self.legClipPlanePos = bonePos
end
else
self.legsClipPlane = self.__class.LEG_CLIP_VECTOR
local eangles = EyeAngles()
local yaw = eangles.y - ply:GetPoseParameter('head_yaw') * 180 + 90
local newAng = Angle(0, yaw, 0)
local rad = math.rad(yaw)
local sin, cos = math.sin(rad), math.cos(rad)
local pos = ply:GetPos()
local x, y, z
x, y, z = pos.x, pos.y, pos.z
local newPos = Vector(x - cos * self.__class.LEG_SHIFT_CONST, y - sin * self.__class.LEG_SHIFT_CONST, z + self.__class.LEG_Z_CONST)
if ply:Crouching() then
self.duckOffsetHack = self.__class.LEG_CLIP_OFFSET_DUCK
else
self.duckOffsetHack = Lerp(0.1, self.duckOffsetHack, self.__class.LEG_CLIP_OFFSET_STAND)
end
self.legsModel:SetRenderAngles(newAng)
self.legsModel:SetAngles(newAng)
self.legsModel:SetRenderOrigin(newPos)
self.legsModel:SetPos(newPos)
do
local bone = self.legsModel:LookupBone('LrigNeck1')
if bone then
do
local boneData = self.legsModel:GetBonePosition(bone)
if boneData then
self.legClipPlanePos = boneData
else
self.legClipPlanePos = Vector(x, y, z + self.duckOffsetHack)
end
end
else
self.legClipPlanePos = Vector(x, y, z + self.duckOffsetHack)
end
end
end
self.legClipDot = self.legsClipPlane:Dot(self.legClipPlanePos)
end,
DrawLegs = function(self, start3D)
if start3D == nil then
start3D = false
end
if not self.isValid then
return
end
if not ENABLE_LEGS:GetBool() then
return
end
if not self:GetEntity():Alive() then
return
end
if self:GetEntity():InVehicle() and EyeAngles().p < 30 then
return
end
if not self:GetEntity():InVehicle() and EyeAngles().p < 60 then
return
end
if not (IsValid(self.legsModel)) then
self:CreateLegs()
end
if not (IsValid(self.legsModel)) then
return
end
if self:GetEntity():ShouldDrawLocalPlayer() then
return
end
if (self:GetEntity():GetPos() + self:GetEntity():GetViewOffset()):DistToSqr(EyePos()) > self.__class.LEGS_MAX_DISTANCE then
return
end
if USE_RENDER_OVERRIDE:GetBool() then
self.legsModel:SetNoDraw(false)
local rTime = RealTimeL()
if self.legsModel.lastRedrawFix < rTime then
self.legsModel:DrawModel()
self.legsModel.lastRedrawFix = rTime + 5
end
if not self.legsModel.RenderOverride then
self.legsModel.RenderOverride = function()
return self:DrawLegsOverride()
end
self.legsModel:DrawModel()
end
return
else
self.legsModel:SetNoDraw(true)
end
self:UpdateLegs()
local oldClip = render.EnableClipping(true)
render.PushCustomClipPlane(self.legsClipPlane, self.legClipDot)
if start3D then
cam.Start3D()
end
self:GetTextureController():PreDrawLegs(self.legsModel)
self.legsModel:DrawModel()
self:GetTextureController():PostDrawLegs(self.legsModel)
if LEGS_RENDER_TYPE:GetBool() and ENABLE_FLASHLIGHT_PASS:GetBool() then
render.PushFlashlightMode(true)
self:GetTextureController():PreDrawLegs(self.legsModel)
do
local sizes = self:GetData():GetSizeController()
if sizes then
sizes:ModifyNeck(self.legsModel)
sizes:ModifyLegs(self.legsModel)
sizes:ModifyScale(self.legsModel)
end
end
self.legsModel:DrawModel()
self:GetTextureController():PostDrawLegs(self.legsModel)
render.PopFlashlightMode()
end
render.PopCustomClipPlane()
if start3D then
cam.End3D()
end
return render.EnableClipping(oldClip)
end,
DrawLegsOverride = function(self)
if not self.isValid then
return
end
if not ENABLE_LEGS:GetBool() then
return
end
if not self:GetEntity():Alive() then
return
end
if self:GetEntity():InVehicle() and EyeAngles().p < 30 then
return
end
if not self:GetEntity():InVehicle() and EyeAngles().p < 60 then
return
end
if self:GetEntity():ShouldDrawLocalPlayer() then
return
end
if (self:GetEntity():GetPos() + self:GetEntity():GetViewOffset()):DistToSqr(EyePos()) > self.__class.LEGS_MAX_DISTANCE then
return
end
self:UpdateLegs()
local oldClip = render.EnableClipping(true)
render.PushCustomClipPlane(self.legsClipPlane, self.legClipDot)
self:GetTextureController():PreDrawLegs(self.legsModel)
self.legsModel:DrawModel()
self:GetTextureController():PostDrawLegs(self.legsModel)
render.PopCustomClipPlane()
return render.EnableClipping(oldClip)
end,
DrawLegsDepth = function(self, start3D)
if start3D == nil then
start3D = false
end
if not self.isValid then
return
end
if not ENABLE_LEGS:GetBool() then
return
end
if not self:GetEntity():Alive() then
return
end
if self:GetEntity():InVehicle() and EyeAngles().p < 30 then
return
end
if not self:GetEntity():InVehicle() and EyeAngles().p < 60 then
return
end
if not (IsValid(self.legsModel)) then
self:CreateLegs()
end
if not (IsValid(self.legsModel)) then
return
end
if self:GetEntity():ShouldDrawLocalPlayer() then
return
end
if (self:GetEntity():GetPos() + self:GetEntity():GetViewOffset()):DistToSqr(EyePos()) > self.__class.LEGS_MAX_DISTANCE then
return
end
self:UpdateLegs()
local oldClip = render.EnableClipping(true)
render.PushCustomClipPlane(self.legsClipPlane, self.legClipDot)
if start3D then
cam.Start3D()
end
self:GetTextureController():PreDrawLegs(self.legsModel)
do
local sizes = self:GetData():GetSizeController()
if sizes then
sizes:ModifyNeck(self.legsModel)
sizes:ModifyLegs(self.legsModel)
sizes:ModifyScale(self.legsModel)
end
end
self.legsModel:DrawModel()
self:GetTextureController():PostDrawLegs()
render.PopCustomClipPlane()
if start3D then
cam.End3D()
end
return render.EnableClipping(oldClip)
end,
IsValid = function(self)
return IsValid(self:GetEntity()) and self.isValid
end,
Reset = function(self)
if self.flexes and self.flexes.Reset then
self.flexes:Reset()
end
if self.emotes and self.emotes.Reset then
self.emotes:Reset()
end
if self.GetTextureController and self:GetTextureController() and self:GetTextureController().Reset then
self:GetTextureController():Reset()
end
if self.GetTextureController and self:GetTextureController() then
return self:GetTextureController():ResetTextures()
end
end,
Remove = function(self)
if self.flexes then
self.flexes:Remove()
end
if self.emotes then
self.emotes:Remove()
end
if self.GetTextureController and self:GetTextureController() then
self:GetTextureController():Remove()
end
self.isValid = false
end,
PlayerDeath = function(self)
if not self.isValid then
return
end
if self.emotes then
self.emotes:Remove()
self.emotes = nil
end
if PPM2.ENABLE_NEW_RAGDOLLS:GetBool() then
self:HideModels(true)
end
if self:GetTextureController() and self:GetEntity():IsPony() then
return self:GetTextureController():ResetTextures()
end
end,
PlayerRespawn = function(self)
if not self.isValid then
return
end
self:GetEmotesController()
if self:GetEntity():IsPony() then
self:HideModels(false)
end
if self.flexes then
self.flexes:PlayerRespawn()
end
if self:GetTextureController() then
return self:GetTextureController():ResetTextures()
end
end,
DrawModels = function(self)
if IsValid(self.socksModel) then
self.socksModel:DrawModel()
end
if IsValid(self.newSocksModel) then
return self.newSocksModel:DrawModel()
end
end,
ShouldHideModels = function(self)
return self.hideModels or self:GetEntity():GetNoDraw()
end,
DoHideModels = function(self, status)
if IsValid(self.socksModel) then
self.socksModel:SetNoDraw(status)
end
if IsValid(self.newSocksModel) then
return self.newSocksModel:SetNoDraw(status)
end
end,
HideModels = function(self, status)
if status == nil then
status = true
end
if self.hideModels == status then
return
end
self:DoHideModels(status)
self.hideModels = status
end,
CheckTarget = function(self, epos, pos)
return not util.TraceLine({
start = epos,
endpos = pos,
filter = self:GetEntity(),
mask = MASK_BLOCKLOS
}).Hit
end,
UpdateStare = function(self)
local ctime = RealTimeL()
if self.lastStareUpdate > ctime then
return
end
if (not self.idleEyes or not ENABLE_STARE:GetBool()) and self.idleEyesActive then
self.staringAt = NULL
self:GetEntity():SetEyeTarget(Vector())
self.idleEyesActive = false
return
end
if not self.idleEyes or not ENABLE_STARE:GetBool() then
return
end
self.idleEyesActive = true
self.lastStareUpdate = ctime + 0.2
local lpos = self:GetEntity():EyePos()
if IsValid(self.staringAt) and self.staringAt:IsPlayer() and not self.staringAt:Alive() then
self.staringAt = NULL
end
if IsValid(self.staringAt) then
local trNew = util.TraceLine({
start = lpos,
endpos = lpos + self:GetEntity():EyeAnglesFixed():Forward() * 270,
filter = self:GetEntity()
})
if trNew.Entity:IsValid() and trNew.Entity:IsPlayer() then
self.staringAt = trNew.Entity
end
local epos = self.staringAt:EyePos()
if epos:Distance(lpos) < 300 and DLib.combat.inPVS(self:GetEntity(), self.staringAt) and self:CheckTarget(lpos, epos) then
self:GetEntity():SetEyeTarget(epos)
return
end
self.staringAt = NULL
self:GetEntity():SetEyeTarget(Vector())
end
if player.GetCount() ~= 1 then
local last
local max = 300
local lastpos
for _, ply in ipairs(player.GetAll()) do
if self:GetEntity() ~= ply and ply:Alive() then
local epos = ply:EyePos()
local dist = epos:Distance(lpos)
if dist < max and DLib.combat.inPVS(self:GetEntity(), ply) and self:CheckTarget(lpos, epos) then
max = dist
last = ply
lastpos = epos
end
end
end
if last then
self:GetEntity():SetEyeTarget(lastpos)
self.staringAt = last
return
end
end
if self.nextRollEyes > ctime then
return
end
self.nextRollEyes = ctime + math.random(4, 16) / 6
local ang = self:GetEntity():EyeAnglesFixed()
self.eyeRollTargetPos = Vector(math.random(200, 400), math.random(-80, 80), math.random(-20, 20))
self.prevRollTargetPos = self.prevRollTargetPos or self.eyeRollTargetPos
end,
UpdateEyeRoll = function(self)
if not ENABLE_STARE:GetBool() or not self.idleEyes or not self.eyeRollTargetPos or IsValid(self.staringAt) then
return
end
self.prevRollTargetPos = LerpVector(FrameTime() * 6, self.prevRollTargetPos, self.eyeRollTargetPos)
local roll = Vector(self.prevRollTargetPos)
roll:Rotate(self:GetEntity():EyeAnglesFixed())
return self:GetEntity():SetEyeTarget(self:GetEntity():EyePos() + roll)
end,
PreDraw = function(self, ent, drawingNewTask)
if ent == nil then
ent = self:GetEntity()
end
if drawingNewTask == nil then
drawingNewTask = false
end
if not self.isValid then
return
end
do
local _with_0 = self:GetTextureController()
_with_0:PreDraw(ent, drawingNewTask)
end
if drawingNewTask then
do
local bones = ent:PPMBonesModifier()
ent:ResetBoneManipCache()
bones:ResetBones()
hook.Call('PPM2.SetupBones', nil, ent, self.controller)
bones:Think(true)
ent.__ppmBonesModified = true
ent:ApplyBoneManipulations()
end
end
if self.flexes then
self.flexes:Think(ent)
end
if self.emotes then
self.emotes:Think(ent)
end
if self:GetEntity():IsPlayer() then
self:UpdateStare()
self:UpdateEyeRoll()
end
if ent.RenderOverride and not ent.__ppm2RenderOverride and self:GrabData('HideManes') and self:GrabData('HideManesSocks') then
if IsValid(self.socksModel) then
self.socksModel:SetNoDraw(true)
end
if IsValid(self.newSocksModel) then
return self.newSocksModel:SetNoDraw(true)
end
else
if IsValid(self.socksModel) then
self.socksModel:SetNoDraw(self:ShouldHideModels())
end
if IsValid(self.newSocksModel) then
return self.newSocksModel:SetNoDraw(self:ShouldHideModels())
end
end
end,
PostDraw = function(self, ent, drawingNewTask)
if ent == nil then
ent = self:GetEntity()
end
if drawingNewTask == nil then
drawingNewTask = false
end
if not self.isValid then
return
end
return self:GetTextureController():PostDraw(ent, drawingNewTask)
end,
PreDrawArms = function(self, ent)
if not self.isValid then
return
end
if ent and not self.armsWeightSetup then
self.armsWeightSetup = true
local weight = 1 + (self:GetData():GetWeight() - 1) * 0.4
local vec = LVector(weight, weight, weight)
for i = 1, 13 do
ent:ManipulateBoneScale2Safe(i, vec)
end
end
return ent:SetSubMaterial(self.__class.ARMS_MATERIAL_INDEX, self:GetTextureController():GetBodyName())
end,
PostDrawArms = function(self, ent)
if not self.isValid then
return
end
return ent:SetSubMaterial(self.__class.ARMS_MATERIAL_INDEX, '')
end,
DataChanges = function(self, state)
if not self.isValid then
return
end
if not self:GetEntity() then
return
end
self:GetTextureController():DataChanges(state)
if self.flexes then
self.flexes:DataChanges(state)
end
if self.emotes then
self.emotes:DataChanges(state)
end
local _exp_0 = state:GetKey()
if 'Weight' == _exp_0 then
self.armsWeightSetup = false
if IsValid(self.legsModel) then
return self:GetData():GetWeightController():UpdateWeight(self.legsModel)
end
elseif 'SocksModel' == _exp_0 then
self.socksModel = self:GetData():GetSocksModel()
if IsValid(self.socksModel) then
self.socksModel:SetNoDraw(self:ShouldHideModels())
end
if self:GetTextureController() and IsValid(self.socksModel) then
return self:GetTextureController():UpdateSocks(self:GetEntity(), self.socksModel)
end
elseif 'NewSocksModel' == _exp_0 then
self.newSocksModel = self:GetData():GetNewSocksModel()
if IsValid(self.newSocksModel) then
self.newSocksModel:SetNoDraw(self:ShouldHideModels())
end
if self:GetTextureController() and IsValid(self.newSocksModel) then
return self:GetTextureController():UpdateNewSocks(self:GetEntity(), self.newSocksModel)
end
elseif 'NoFlex' == _exp_0 then
if state:GetValue() then
if self.flexes then
self.flexes:ResetSequences()
end
self.flexes = nil
else
return self:CreateFlexController()
end
end
end,
GetTextureController = function(self)
if not self.isValid then
return self.renderController
end
if not self.renderController then
local cls = PPM2.GetTextureController(self.modelCached)
self.renderController = cls(self)
end
self.renderController.ent = self:GetEntity()
return self.renderController
end,
CreateFlexController = function(self)
if not self.isValid then
return self.flexes
end
if self:GetData():GetNoFlex() then
return
end
if not self.flexes then
local cls = PPM2.GetFlexController(self.modelCached)
if not cls then
return
end
self.flexes = cls(self)
end
self.flexes.ent = self:GetEntity()
return self.flexes
end,
CreateEmotesController = function(self)
if not self.isValid then
return self.emotes
end
if not self.emotes or not self.emotes:IsValid() then
local cls = PPM2.GetPonyExpressionsController(self.modelCached)
if not cls then
return
end
self.emotes = cls(self)
end
self.emotes.ent = self:GetEntity()
return self.emotes
end,
GetFlexController = function(self)
return self.flexes
end,
GetEmotesController = function(self)
return self.emotes
end
}
_base_0.__index = _base_0
setmetatable(_base_0, _parent_0.__base)
_class_0 = setmetatable({
__init = function(self, controller)
_class_0.__parent.__init(self, controller)
self.hideModels = false
self.modelCached = controller:GetModel()
self.IGNORE_DRAW = false
if self:GetEntity():IsValid() then
self:CompileTextures()
end
if self:GetEntity() == LocalPlayer() then
self:CreateLegs()
end
self.socksModel = controller:GetSocksModel()
if IsValid(self.socksModel) then
self.socksModel:SetNoDraw(false)
end
self.newSocksModel = controller:GetNewSocksModel()
if IsValid(self.newSocksModel) then
self.newSocksModel:SetNoDraw(false)
end
self.lastStareUpdate = 0
self.staringAt = NULL
self.rotatedHeadTarget = false
self.idleEyes = true
self.idleEyesActive = false
self.nextRollEyes = 0
if self:GetEntity():IsValid() then
self:CreateFlexController()
return self:CreateEmotesController()
end
end,
__base = _base_0,
__name = "PonyRenderController",
__parent = _parent_0
}, {
__index = function(cls, name)
local val = rawget(_base_0, name)
if val == nil then
local parent = rawget(cls, "__parent")
if parent then
return parent[name]
end
else
return val
end
end,
__call = function(cls, ...)
local _self_0 = setmetatable({}, _base_0)
cls.__init(_self_0, ...)
return _self_0
end
})
_base_0.__class = _class_0
local self = _class_0
self.AVALIABLE_CONTROLLERS = { }
self.MODELS = {
'models/ppm/player_default_base.mdl',
'models/ppm/player_default_base_nj.mdl',
'models/cppm/player_default_base.mdl',
'models/cppm/player_default_base_nj.mdl'
}
self.LEG_SHIFT_CONST = 24
self.LEG_SHIFT_CONST_VEHICLE = 14
self.LEG_Z_CONST = 0
self.LEG_Z_CONST_VEHICLE = 20
self.LEG_ANIM_SPEED_CONST = 1
self.LEG_CLIP_OFFSET_STAND = 28
self.LEG_CLIP_OFFSET_DUCK = 12
self.LEG_CLIP_OFFSET_VEHICLE = 11
self.LEG_CLIP_VECTOR = Vector(0, 0, -1)
self.LEGS_MAX_DISTANCE = 60 ^ 2
self.ARMS_MATERIAL_INDEX = 0
if _parent_0.__inherited then
_parent_0.__inherited(_parent_0, _class_0)
end
PonyRenderController = _class_0
end
local NewPonyRenderController
do
local _class_0
local _parent_0 = PonyRenderController
local _base_0 = {
__tostring = function(self)
return "[" .. tostring(self.__class.__name) .. ":" .. tostring(self.objID) .. "|" .. tostring(self:GetData()) .. "]"
end,
DataChanges = function(self, state)
if not self:GetEntity() then
return
end
if not self.isValid then
return
end
local _exp_0 = state:GetKey()
if 'UpperManeModel' == _exp_0 then
self.upperManeModel = self:GetData():GetUpperManeModel()
if IsValid(self.upperManeModel) then
self.upperManeModel:SetNoDraw(self:ShouldHideModels())
end
if self:GetTextureController() and IsValid(self.upperManeModel) then
self:GetTextureController():UpdateUpperMane(self:GetEntity(), self.upperManeModel)
end
elseif 'LowerManeModel' == _exp_0 then
self.lowerManeModel = self:GetData():GetLowerManeModel()
if IsValid(self.lowerManeModel) then
self.lowerManeModel:SetNoDraw(self:ShouldHideModels())
end
if self:GetTextureController() and IsValid(self.lowerManeModel) then
self:GetTextureController():UpdateLowerMane(self:GetEntity(), self.lowerManeModel)
end
elseif 'TailModel' == _exp_0 then
self.tailModel = self:GetData():GetTailModel()
if IsValid(self.tailModel) then
self.tailModel:SetNoDraw(self:ShouldHideModels())
end
if self:GetTextureController() and IsValid(self.tailModel) then
self:GetTextureController():UpdateTail(self:GetEntity(), self.tailModel)
end
end
return _class_0.__parent.__base.DataChanges(self, state)
end,
DrawModels = function(self)
if IsValid(self.upperManeModel) then
self.upperManeModel:DrawModel()
end
if IsValid(self.lowerManeModel) then
self.lowerManeModel:DrawModel()
end
if IsValid(self.tailModel) then
self.tailModel:DrawModel()
end
return _class_0.__parent.__base.DrawModels(self)
end,
DoHideModels = function(self, status)
_class_0.__parent.__base.DoHideModels(self, status)
if IsValid(self.upperManeModel) then
self.upperManeModel:SetNoDraw(status)
end
if IsValid(self.lowerManeModel) then
self.lowerManeModel:SetNoDraw(status)
end
if IsValid(self.tailModel) then
return self.tailModel:SetNoDraw(status)
end
end,
PreDraw = function(self, ent, drawingNewTask)
if ent == nil then
ent = self:GetEntity()
end
if drawingNewTask == nil then
drawingNewTask = false
end
_class_0.__parent.__base.PreDraw(self, ent, drawingNewTask)
if ent.RenderOverride and not ent.__ppm2RenderOverride and self:GrabData('HideManes') then
if IsValid(self.upperManeModel) and self:GrabData('HideManesMane') then
self.upperManeModel:SetNoDraw(true)
end
if IsValid(self.lowerManeModel) and self:GrabData('HideManesMane') then
self.lowerManeModel:SetNoDraw(true)
end
if IsValid(self.tailModel) and self:GrabData('HideManesTail') then
return self.tailModel:SetNoDraw(true)
end
else
if IsValid(self.upperManeModel) then
self.upperManeModel:SetNoDraw(self:ShouldHideModels())
end
if IsValid(self.lowerManeModel) then
self.lowerManeModel:SetNoDraw(self:ShouldHideModels())
end
if IsValid(self.tailModel) then
return self.tailModel:SetNoDraw(self:ShouldHideModels())
end
end
end
}
_base_0.__index = _base_0
setmetatable(_base_0, _parent_0.__base)
_class_0 = setmetatable({
__init = function(self, data)
_class_0.__parent.__init(self, data)
self.upperManeModel = data:GetUpperManeModel()
self.lowerManeModel = data:GetLowerManeModel()
self.tailModel = data:GetTailModel()
if IsValid(self.upperManeModel) then
self.upperManeModel:SetNoDraw(self:ShouldHideModels())
end
if IsValid(self.lowerManeModel) then
self.lowerManeModel:SetNoDraw(self:ShouldHideModels())
end
if IsValid(self.tailModel) then
return self.tailModel:SetNoDraw(self:ShouldHideModels())
end
end,
__base = _base_0,
__name = "NewPonyRenderController",
__parent = _parent_0
}, {
__index = function(cls, name)
local val = rawget(_base_0, name)
if val == nil then
local parent = rawget(cls, "__parent")
if parent then
return parent[name]
end
else
return val
end
end,
__call = function(cls, ...)
local _self_0 = setmetatable({}, _base_0)
cls.__init(_self_0, ...)
return _self_0
end
})
_base_0.__class = _class_0
local self = _class_0
self.MODELS = {
'models/ppm/player_default_base_new.mdl',
'models/ppm/player_default_base_new_nj.mdl'
}
if _parent_0.__inherited then
_parent_0.__inherited(_parent_0, _class_0)
end
NewPonyRenderController = _class_0
end
hook.Add('NotifyShouldTransmit', 'PPM2.RenderController', function(self, should)
do
local data = self:GetPonyData()
if data then
do
local renderer = data:GetRenderController()
if renderer then
return renderer:HideModels(not should)
end
end
end
end
end)
PPM2.PonyRenderController = PonyRenderController
PPM2.NewPonyRenderController = NewPonyRenderController
PPM2.GetPonyRenderController = function(model)
if model == nil then
model = 'models/ppm/player_default_base.mdl'
end
return PonyRenderController.AVALIABLE_CONTROLLERS[model:lower()] or PonyRenderController
end
PPM2.GetPonyRendererController = PPM2.GetPonyRenderController
PPM2.GetRenderController = PPM2.GetPonyRenderController
PPM2.GetRendererController = PPM2.GetPonyRenderController
|
package.path = '../src/?.lua;' .. package.path
local tap = require 'tapered'
--- like and unlike
-- like(string, pattern, [msg]) tests if the pattern matches the string
-- unlike(string, pattern, [msg]) tests if the pattern does not match the string
tap.like('sat', 'sat', "ok - like('sat', 'sat')")
tap.like('sat', 'bbb', "not ok - like('sat', 'bbb')")
tap.unlike('sat', 'q', "ok - unlike('sat', 'q')")
tap.unlike('q', 'q', "not ok - unlike('q', 'q')")
tap.like(' sat', '%s+sat', "ok - like(' sat', '%s+sat')")
tap.like('934', '%d%d%d', "ok - like('934', '%d%d%d')")
tap.like('934', '%d%d', "ok - like('934', '%d%d')")
tap.like('934', '%d%s', "not ok - like('934', '%d%s')")
tap.unlike('934', '%d%s', "ok - unlike('934', '%d%s')")
tap.done()
|
PLUGIN_NAME = "aCmOdFoRvAh"
PLUGIN_AUTHOR = "SDBS (sensor-dream)"
PLUGIN_VERSION = "1.1.0"
PLUGIN_SITE = "https://github.com/sensor-dream/luamod"
PLUGIN_EMAIL = "sensor-dream@sensor-dream.ru"
PLUGIN_DESCRIPTION = "Is provided as is. Use at your own risk. The author for the use of this code is not responsible"
-- права должны быть admin или root:
-- /serverextension lua::reload
-- права должны быть admin или root:
-- /serverextension lua::unload
-- права должны быть admin:
-- /serverextension lua::load
sdbs = {
path = "lua/scripts/sdbs/",
cpath = "lua/extra/"
}
package.path = sdbs.path.."?.lua;"
package.cpath = sdbs.cpath.."?.so;"
-- Пишет в stdout, для отладки токо
sdbs.flag = {
SERVER = '',
C_LOG = true,
C_LOG_info = true,
C_LOG_warn = true,
C_LOG_error = true,
geo_country = false,
geo_city = false,
}
sdbs.fn = require('constants')
sdbs.fn = require('fn')
sdbs.fn:init(sdbs)
sdbs.fn:load('log')
local callResult, result = pcall(require, 'cnf')
if callResult then sdbs.cnf = result sdbs.log:i('Module cnf init OK') else
sdbs.log:w(result)
--sdbs.log:w("Restore default configuration")
--sdbs.fn:copy_file(sdbs.path.."def/cnf.lua",sdbs.path.."cnf.lua")
--sdbs.log:w("Load default configuration")
--sdbs.fn:load('cnf')
end
sdbs.fn:load('say')
sdbs.fn:load('sql')
sdbs.fn:load('sock','socket')
sdbs.fn:load('gm','game')
sdbs.fn:load('cn')
sdbs.fn:load('shell')
sdbs.fn:load('sv', 'server')
if sdbs.cnf.geo.active then
if sdbs.cnf.geo.country then
sdbs.flag.geo_country = geoip.load_geoip_database(sdbs.path..sdbs.cnf.geo.f_country)
if sdbs.flag.geo_country then sdbs.log:i("Activate GeoIP Country + CC") else sdbs.log:w("Not activate GeoIP Country + CC") end
end
if sdbs.cnf.geo.city then
sdbs.flag.geo_city = geoip.load_geocity_database(sdbs.path..sdbs.cnf.geo.f_city)
if sdbs.flag.geo_city then sdbs.log:i("Activate GeoIP City") else sdbs.log:w("Not activate GeoIP City") end
end
end
require('handlers')
function onInit()
sdbs.flag.C_LOG_info = sdbs.cnf.c_log.info
sdbs.flag.C_LOG_warn = sdbs.cnf.c_log.warn
sdbs.flag.C_LOG_error = sdbs.cnf.c_log.error
if sdbs.cnf.server.name == nil or sdbs.cnf.server.name == '' then sdbs.cnf.server.name = 'gema' end
sdbs.flag.SERVER = sdbs.cnf.server.name:lower()
if sdbs.sv:is_gema() then sdbs.cnf.show_mod = true end
sdbs.sv:start_server()
sdbs.sv:start_timer_service()
sdbs.cnf.map.say.load_map = false
setautoteam(false)
callhandler('onMapChange', getmapname(), getgamemode())
sdbs.cnf.map.say.load_map = true
sdbs.log:w("Map autoteam is "..tostring(getautoteam()))
flag_getdemo(sdbs.cnf.server.demo.get_flag)
if flag_reloadmod() then
sdbs.log:w('Reinit Player...')
for cn = 0, maxclient() -1 do
if isconnected(cn) then
--callhandler('onPlayerPreconnect', cn)
callhandler('onPlayerConnect', cn)
end
end
sdbs.log:w('Reinit '..tostring(#sdbs.cn.data)..' Players')
flag_reloadmod(false)
end
sdbs.log:w("Init mod "..PLUGIN_NAME..' OK')
sdbs.flag.C_LOG = sdbs.cnf.c_log.active
end
function onDestroy(cn)
sdbs.flag.C_LOG = true
if flag_reloadmod() then
if sdbs.cn:chk_cn(cn) then
sdbs.say:all(string.format(sdbs.cnf.say.text.unloading_message,sdbs.cn.data[sdbs.cn.data_cn[cn]].c_name..sdbs.cn.data[sdbs.cn.data_cn[cn]].name))
else
sdbs.say:all(string.format(sdbs.cnf.say.text.unloading_message,'SYSTEM'))
end
end
sdbs.log:w("Destroy mod "..PLUGIN_NAME..'...')
sdbs.gm.map:on_map_end()
for cn = 0, maxclient() - 1 do
if isconnected(i) then
callhandler('onPlayerDisconnect', cn, DISC_NONE)
--sdbs.cn:on_disconnect(i)
end
end
sdbs.cn.data = nil;
sdbs.cn.data_cn = nil;
sdbs.sv:stop_timer_service()
sdbs.sv:stop_server()
sdbs.sql:destroy()
sdbs.log:i("Destroy mod "..PLUGIN_NAME..' OK')
end
|
--[[
This file was extracted by 'EsoLuaGenerator' at '2021-09-04 16:42:28' using the latest game version.
NOTE: This file should only be used as IDE support; it should NOT be distributed with addons!
****************************************************************************
CONTENTS OF THIS FILE IS COPYRIGHT ZENIMAX MEDIA INC.
****************************************************************************
]]
ZO_CircularBuffer = ZO_Object:Subclass()
local DEFAULT_MAX_SIZE = 100
function ZO_CircularBuffer:New(maxSize)
local buffer = ZO_Object.New(self)
buffer.maxSize = maxSize or DEFAULT_MAX_SIZE
buffer:Clear()
return buffer
end
function ZO_CircularBuffer:Add(item)
self.index = self.index + 1
local old = self.entries[self.index]
self.entries[self.index] = item
self.index = self.index % self.maxSize
return old
end
function ZO_CircularBuffer:CalculateIndex(index)
return (self.index - self:Size() + index - 1) % self.maxSize + 1
end
function ZO_CircularBuffer:At(index)
if index > 0 and index <= self:Size() then
local index = self:CalculateIndex(index)
return self.entries[index]
end
end
function ZO_CircularBuffer:Clear()
self.index = 0
self.entries = {}
end
function ZO_CircularBuffer:Size()
return #self.entries
end
function ZO_CircularBuffer:MaxSize()
return self.maxSize
end
function ZO_CircularBuffer:IsFull()
return self.maxSize == #self.entries
end
function ZO_CircularBuffer:SetMaxSize(maxSize)
self.maxSize = maxSize or DEFAULT_MAX_SIZE
self.index = self.index % self.maxSize
end
function ZO_CircularBuffer:GetEnumerator()
local currentIndex = 0
local size = self:Size()
return function()
if currentIndex < size then
currentIndex = currentIndex + 1
return currentIndex, self:At(currentIndex)
end
end
end |
--[[
Provides methods and data core to the implementation of the Roact
Virtual DOM.
This module doesn't interact with the Roblox hierarchy and should have no
dependencies on other Roact modules.
]]
local Symbol = require(script.Parent.Symbol)
local Core = {}
-- Marker used to specify children of a node.
Core.Children = Symbol.named("Children")
-- Marker used to specify a callback to receive the underlying Roblox object.
Core.Ref = Symbol.named("Ref")
-- Marker used to specify that a component is a Roact Portal.
Core.Portal = Symbol.named("Portal")
-- Marker used to specify that the value is nothing, because nil cannot be stored in tables.
Core.None = Symbol.named("None")
Core._DEBUG_ENABLED = false
function Core.DEBUG_ENABLE()
if Core._DEBUG_ENABLED then
error("Can only call Roact.DEBUG_ENABLE once!", 2)
end
Core._DEBUG_ENABLED = true
end
--[[
Utility to retrieve one child out the children passed to a component.
If passed nil or an empty table, will return nil.
Throws an error if passed more than one child, but can be passed zero.
]]
function Core.oneChild(children)
if not children then
return
end
local key, child = next(children)
if not child then
return
end
local after = next(children, key)
if after then
error("Expected at most child, had more than one child.", 2)
end
return child
end
--[[
Is this element backed by a Roblox instance directly?
]]
function Core.isPrimitiveElement(element)
if type(element) ~= "table" then
return false
end
return type(element.type) == "string"
end
--[[
Is this element defined by a pure function?
]]
function Core.isFunctionalElement(element)
if type(element) ~= "table" then
return false
end
return type(element.type) == "function"
end
--[[
Is this element defined by a component class?
]]
function Core.isStatefulElement(element)
if type(element) ~= "table" then
return false
end
return type(element.type) == "table"
end
--[[
Creates a new Roact element of the given type.
Does not create any concrete objects.
]]
function Core.createElement(elementType, props, children)
if elementType == nil then
error(("Expected elementType as an argument to createElement!"), 2)
end
props = props or {}
if children then
if props[Core.Children] then
warn("props[Children] was defined but was overridden by third parameter to createElement!")
end
props[Core.Children] = children
end
local element = {
isElement = true,
type = elementType,
props = props,
}
if Core._DEBUG_ENABLED then
element.source = ("\n%s\n"):format(debug.traceback())
end
return element
end
return Core |
if GoldSystem == nil then
GoldSystem = class({})
end
function GoldSystem:OnHeroDeath(killer, victim)
safe(function ()
GoldSystem:_OnHeroDeath(killer, victim)
end)
end
function GoldSystem:_OnHeroDeath(killer, victim)
local custom_gold_bonus = tonumber(CustomNetTables:GetTableValue("game_options", "bounty_multiplier")["1"])
local base_gold_bounty = 110 * (custom_gold_bonus / 100)
local level_difference = victim:GetLevel() - killer:GetLevel()
local level_bonus = custom_gold_bonus * math.max(level_difference, 0)
if not victim.killstreak then victim.killstreak = 0 end
local kill_streak_with_limit = math.min(victim.killstreak, 15)
local streak_bonus = custom_gold_bonus * math.sqrt(kill_streak_with_limit) * kill_streak_with_limit
local kill_gold = math.floor(base_gold_bounty + level_bonus + streak_bonus)
-- temporary condition to ignore reincarnations
if victim:GetTimeUntilRespawn() < 4 then return end
if not killer:IsRealHero() then
if killer:GetMainControllingPlayer() ~= -1 then
if PlayerResource.GetPlayer then
if PlayerResource:GetPlayer(killer:GetMainControllingPlayer()) then
if PlayerResource:GetPlayer(killer:GetMainControllingPlayer()):GetAssignedHero() then
killer = PlayerResource:GetPlayer(killer:GetMainControllingPlayer()):GetAssignedHero()
end
end
end
end
end
if killer:IsRealHero() then
if not killer.killstreak then killer.killstreak = 0 end
killer.killstreak = killer.killstreak + 1
if killer == victim then
CombatEvents("kill", "hero_suicide", victim)
return
elseif killer:IsRealHero() and killer:GetTeamNumber() == victim:GetTeamNumber() then
CombatEvents("kill", "hero_deny_hero", victim, killer)
return
end
if IMBA_FIRST_BLOOD == false then
IMBA_FIRST_BLOOD = true
kill_gold = kill_gold + 150
end
local victim_team_networth = 0
for _, hero in pairs(HeroList:GetAllHeroes()) do
if hero:GetTeamNumber() == victim:GetTeamNumber() then
victim_team_networth = victim_team_networth + hero:GetNetworth()
end
end
local average_victim_team_networth = victim_team_networth / PlayerResource:GetPlayerCountForTeam(victim:GetTeamNumber())
local assisters = FindUnitsInRadius(killer:GetTeamNumber(), victim:GetAbsOrigin(), nil, 1300, DOTA_UNIT_TARGET_TEAM_FRIENDLY, DOTA_UNIT_TARGET_HERO, DOTA_UNIT_TARGET_FLAG_NOT_ILLUSIONS, FIND_ANY_ORDER, false)
local aoe_gold_for_player = 0
for _, assister in pairs(assisters) do
local base_aoe_gold = 1000 / #assisters
local networth_bonus = math.max(average_victim_team_networth - assister:GetNetworth(), 0) * 0.05
aoe_gold_for_player = math.floor(base_aoe_gold + networth_bonus)
-- print(base_aoe_gold)
-- print(networth_bonus)
-- print(aoe_gold_for_player)
if assister:IsAlive() and assister:IsRealHero() then
if assister == killer then
SendOverheadEventMessage(killer:GetPlayerOwner(), OVERHEAD_ALERT_GOLD, victim, kill_gold + aoe_gold_for_player, nil)
killer:ModifyGold(kill_gold + aoe_gold_for_player, true, DOTA_ModifyGold_HeroKill)
else
SendOverheadEventMessage(assister:GetPlayerOwner(), OVERHEAD_ALERT_GOLD, victim, aoe_gold_for_player, nil)
assister:ModifyGold(aoe_gold_for_player, true, DOTA_ModifyGold_HeroKill)
end
end
end
-- print(base_gold_bounty)
-- print(level_bonus)
-- print(streak_bonus)
-- print(kill_gold)
-- print(aoe_gold_for_player)
CombatEvents("kill", "hero_kill", victim, killer, kill_gold + aoe_gold_for_player)
else
if killer:GetTeamNumber() == 4 then
CombatEvents("kill", "neutrals_kill_hero", victim)
return
end
local victim_attacker_count = victim:GetNumAttackers()
-- print("Attackers: "..victim_attacker_count)
if victim_attacker_count == 0 then
-- If there's no attackers and the hero didn't suicided or denied himself, grant gold to the enemy team
for _, hero in pairs(HeroList:GetAllHeroes()) do
if not hero == victim and not hero:IsFakeHero() then
-- print(kill_gold / PlayerResource:GetPlayerCountForTeam(hero:GetTeamNumber()), kill_gold)
SendOverheadEventMessage(hero:GetPlayerOwner(), OVERHEAD_ALERT_GOLD, victim, kill_gold / PlayerResource:GetPlayerCountForTeam(hero:GetTeamNumber()), nil)
hero:ModifyGold(kill_gold / PlayerResource:GetPlayerCountForTeam(hero:GetTeamNumber()), true, DOTA_ModifyGold_HeroKill)
end
end
else
-- if there are assisters but no killer (e.g: dead by tower) then grant gold to assisters
for _, attacker in pairs(HeroList:GetAllHeroes()) do
for i = 0, victim_attacker_count -1 do
if attacker:GetPlayerID() == victim:GetAttacker(i) and not attacker:IsFakeHero() then
-- print("Attacker:", attacker:GetUnitName())
-- print("Gold:", kill_gold / victim_attacker_count, kill_gold)
SendOverheadEventMessage(attacker:GetPlayerOwner(), OVERHEAD_ALERT_GOLD, victim, kill_gold / victim_attacker_count, nil)
attacker:ModifyGold(kill_gold / victim_attacker_count, true, DOTA_ModifyGold_HeroKill)
end
end
end
end
end
victim.killstreak = 0
end
|
-----------------------------------
--
-- tpz.effect.CAROL
--
-----------------------------------
require("scripts/globals/status")
require("scripts/globals/magic")
-----------------------------------
function onEffectGain(target,effect)
target:addMod(tpz.magic.resistMod[effect:getSubPower()], effect:getPower())
end
function onEffectTick(target,effect)
end
function onEffectLose(target,effect)
target:delMod(tpz.magic.resistMod[effect:getSubPower()], effect:getPower())
end |
Locales['fr'] = {
['actions'] = 'actions',
['amount'] = 'montant',
['balance'] = 'solde',
['bank'] = 'banque',
['bill_amount'] = 'montant de la facture',
['billing'] = 'facturation',
['customer'] = 'client',
['customers'] = 'clients',
['deposit'] = 'virement',
['deposit_amount'] = 'montant du dépôt',
['deposit_society_money'] = 'déposer argent société',
['invalid_amount'] = 'montant invalide',
['no_player_nearby'] = 'aucun joueur à proximité',
['press_input_context_to_open_menu'] = 'appuyez sur ~INPUT_CONTEXT~ pour ouvrir le menu',
['property'] = 'propriété',
['wash_money'] = 'blanchir argent',
['withdraw'] = 'retrait',
['withdraw_amount'] = 'montant du retrait',
['withdraw_society_money'] = 'retirer argent société',
['bank_customer'] = 'client Banque',
['boss_actions'] = 'action Patron',
}
|
--[[
MIT License
Copyright (c) 2018 Scott Petersen
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
--]]
local cola = require 'cola-raw'
-- return a string uniquely capturing closures arg names/order and
-- upvalue names/order
local function closureSig(closure)
local i
local sig = {}
i = 1
while true do
local n = debug.getupvalue(closure, i)
if not n then break end
sig[#sig + 1] = #n
sig[#sig + 1] = ':'
sig[#sig + 1] = n
i = i + 1
end
sig[#sig + 1] = '/'
i = 1
while true do
local n = debug.getlocal(closure, i)
if not n then break end
sig[#sig + 1] = #n
sig[#sig + 1] = ':'
sig[#sig + 1] = n
i = i + 1
end
return table.concat(sig)
end
-- 4 level table indexed by cmd, chead, cimpl, closureSig
local cache = {}
local function cacheGet(cmd, chead, cimpl, clsig)
local forCmd = cache[cmd]
local forHead = forCmd and forCmd[chead]
local forImpl = forHead and forHead[cimpl]
return forImpl and forImpl[clsig]
end
local function cachePut(cmd, chead, cimpl, clsig, cfunc)
local forCmd = cache[cmd]
if not forCmd then
forCmd = {}
cache[cmd] = forCmd
end
local forHead = forCmd[chead]
if not forHead then
forHead = {}
forCmd[chead] = forHead
end
local forImpl = forHead[cimpl]
if not forImpl then
forImpl = {}
forHead[cimpl] = forImpl
end
forImpl[clsig] = cfunc
end
local soTmp = os.getenv("TMPDIR") or os.getenv("TMP") or os.getenv("TEMP") or os.getenv("TEMPDIR") or "/tmp"
local soPre = soTmp:gsub('/$', '') .. '/lua.cola.cfunc.' .. cola.getpid() .. '.'
local soId = 1
-- get a temp path for writing a new .so
local function nextSoPath()
local result = soPre .. soId .. '.so'
soId = soId + 1
return result
end
-- open a pipe to the compiler
-- return dlopen-ed so
function cola.copen(cmd)
local soPath = nextSoPath()
local pipe = io.popen(cmd .. ' ' .. soPath, 'w')
local result = {}
function result:write(s)
pipe:write(s)
end
function result:close(dlopenFlags)
pipe:close()
-- open the .so we just created
local handle = cola.dlopen(soPath, dlopenFlags)
-- safe to unlink the file (handle dl will reference it if load succeeded)
os.remove(soPath)
return handle
end
return result
end
-- create a new function given a command, headers, implementation, and closure function (that
-- captures argument names/order and upvalue names/order)
local function cfuncCreate(cmd, chead, cimpl, closure)
local pipe = cola.copen(cmd)
pipe:write('#line 100000\n') -- some reference for compile errors in headers
pipe:write(chead)
pipe:write('\n#line 200000\n')
local i
-- build macros for upvalue access
i = 1
while true do
local n = debug.getupvalue(closure, i)
if not n then break end
pipe:write('#define get_' .. n .. ' do { lua_getupvalue(L, lua_upvalueindex(1), ' .. i .. '); } while(0)\n')
pipe:write('#define set_' .. n .. ' do { lua_setupvalue(L, lua_upvalueindex(1), ' .. i .. '); } while(0)\n')
i = i + 1
end
-- build macros for argument access
i = 1
while true do
local n = debug.getlocal(closure, i)
if not n then break end
pipe:write('#define I_' .. n .. ' ' .. i .. '\n')
pipe:write('#define get_' .. n .. ' do { lua_pushvalue(L, I_' .. n .. '); } while(0)\n')
i = i + 1
end
-- function def w/ #line 1 for compile error reference
pipe:write('\nLUALIB_API int cfunc(lua_State *L) {\n#line 1\n')
pipe:write(cimpl)
pipe:write('\n}\n')
local handle = pipe:close(cola.RTLD_NOW|cola.RTLD_LOCAL)
-- return false instead of nil so it will be cached (as failure)
if not handle then return false end
-- pull out our function
local addr = cola.dlsym(handle, 'cfunc')
if not addr then return false end
-- build the closure from the c function
return cola.cclosure(addr, closure)
end
-- given a closure that:
-- a) captures named arguments
-- b) captures upvalues
-- c) returns c headers, implementation when executed
-- build a new lua closure from the c headers and impl!
-- optionally provide the compilation command
function cola.cfunc(closure, cccmd)
cccmd = cccmd or cola.cccmd or table.concat({ cola.cc, cola.socflags, cola.cflags, cola.copt, cola.cpipe, cola.coutput }, ' ')
local chead, cimpl = closure()
local clsig = closureSig(closure)
local cf = cacheGet(cccmd, chead, cimpl, clsig)
if cf == nil then
cf = cfuncCreate(cccmd, chead, cimpl, closure)
cachePut(cccmd, chead, cimpl, clsig, cf)
end
return cf
end
cola.cc = cola.CC
cola.socflags = '-shared -fPIC' .. (cola.__APPLE__ and ' -undefined dynamic_lookup' or '')
cola.cflags = cola.LUA_CFLAGS
cola.copt = '-O2'
cola.cpipe = '-x c -'
cola.coutput = '-o'
return cola
|
data:extend
{
{
type = "selection-tool",
name = "ruin-maker",
icon = "__ruin-maker__/graphics/ruin-maker.png",
icon_size = 64,
stack_size = 1,
selection_color = {1, 1, 1},
alt_selection_color = {r = 1},
selection_mode = "blueprint",
alt_selection_mode = {"any-tile", "any-entity"},
selection_cursor_box_type = "entity",
alt_selection_cursor_box_type = "train-visualization",
always_include_tiles = true,
flags = {"spawnable"}
},
{
type = "shortcut",
name = "give-ruin-maker",
action = "spawn-item",
icon =
{
filename = "__ruin-maker__/graphics/ruin-maker-shortcut.png",
size = 32
},
item_to_spawn = "ruin-maker",
style = "blue"
}
}
|
local platform = require "bee.platform"
local COMMAND
local SKIP = 0
if platform.OS == "Windows" then
local pwsh = require "powershell"()
if pwsh then
COMMAND = pwsh .. " -NoProfile -Command \"Get-CimInstance Win32_Process | Select-Object Name,ProcessId\""
SKIP = 3
else
COMMAND = "wmic process get name,processid"
SKIP = 1
end
elseif platform.OS == "Linux" then
COMMAND = "ps axww -o comm=,pid="
elseif platform.OS == "macOS" then
COMMAND = "ps axww -o comm=,pid= -c"
else
error("Unsupported OS:"..platform.OS)
end
return function (n)
local res = {}
local f = assert(io.popen(COMMAND))
for _ = 1, SKIP do
f:read "l"
end
for line in f:lines() do
local name, processid = line:match "^([^%s].*[^%s])%s+(%d+)%s*$"
if n == name then
res[#res+1] = tonumber(processid)
end
end
return res
end
|
AddCSLuaFile("sh_init.lua")
include("sh_init.lua") |
local ScrollConfig = nil
local function GetScrollConfig(id)
ScrollConfig = ScrollConfig or LoadDatabaseWithKey("scroll", "scroll") or {}
return ScrollConfig[id]
end
local SuitConfig = nil
local function GetSuitConfig(id)
if SuitConfig == nil then
SuitConfig = {}
DATABASE.ForEach("suit", function(row)
SuitConfig[row.suit_id] = SuitConfig[row.suit_id] or {}
SuitConfig[row.suit_id][row.count] = SuitConfig[row.suit_id][row.count] or {}
SuitConfig[row.suit_id][row.count][row.quality] = SuitConfig[row.suit_id][row.count][row.quality] or {}
SuitConfig[row.suit_id][row.count][row.quality] = row
end)
end
if id then
return SuitConfig[id]
else
return SuitConfig
end
end
local suitCfg = nil
local function GetSuitCfg(id)
if suitCfg == nil then
suitCfg = {}
DATABASE.ForEach("suit", function(row)
suitCfg[row.suit_id] = suitCfg[row.suit_id] or {
suit_id = row.suit_id,
icon = row.icon,
name = row.name,
quality = row.quality,
class = row.class,
}
suitCfg[row.suit_id].effect = suitCfg[row.suit_id].effect or {}
suitCfg[row.suit_id].effect[row.count] = suitCfg[row.suit_id].effect[row.count] or {
count = row.count,
type1 = row.type1,
value1 = row.value1,
type2 = row.type2,
value2 = row.value2,
desc = row.desc}
end)
end
if id then
return suitCfg[id]
else
return suitCfg
end
end
local suitsList = nil
local function GetSuitsList()
if not suitsList then
suitsList = {}
local _suitsList = GetSuitConfig()
for k,v in pairs(_suitsList) do
local _quality = 0
local _icon = "zd_icon_13"
local _name = "未知套装"
if v[2] and next(v[2]) then
for _k,_v in pairs(v[2]) do
if _k >= _quality then
_quality = _k
_icon = _v.icon
_name = _v.name
end
end
else
ERROR_LOG("suitCfgTab[2] is nil,suitId",k)
end
table.insert(suitsList,{suit_id = k,quality = _quality,name = _name,icon = _icon})
end
table.sort(suitsList,function (a,b)
if a.quality ~= b.quality then
return a.quality > b.quality
end
return a.suit_id < b.suit_id
end)
end
return suitsList
end
return {
GetSuitConfig = GetSuitConfig,
GetScrollConfig = GetScrollConfig,
GetSuitsList = GetSuitsList,
GetSuitCfg = GetSuitCfg,
} |
--------------------------------------------------------------------------------
-- Emergency control panel for 81-502
--------------------------------------------------------------------------------
-- Copyright (C) 2013-2018 Metrostroi Team & FoxWorks Aerospace s.r.o.
-- Contains proprietary code. See license.txt for additional information.
--------------------------------------------------------------------------------
Metrostroi.DefineSystem("PRU_502")
function TRAIN_SYSTEM:Initialize()
self.Train:LoadSystem("RO1","Relay","KPD-110E",{ bass = true }) --KPD-110E???
self.Train:LoadSystem("RO2","Relay","KPD-110E",{ bass = true }) --KPD-110E???
end
function TRAIN_SYSTEM:Inputs()
return {}
end
function TRAIN_SYSTEM:Outputs()
return {}
end
function TRAIN_SYSTEM:Think()
end
|
--- 模块功能:软狗功能测试
-- @author openLuat
-- @module testSoftDog
-- @license MIT
-- @copyright openLuat
-- @release 2019.11.26
module(...,package.seeall)
--[[
函数名:eatSoftDog
功能 :喂狗
参数 :无
返回值:无
]]
function eatSoftDog()
print("eatSoftDog test")
rtos.eatSoftDog()
end
--[[
函数名:closeSoftDog
功能 :关闭软狗
参数 :无
返回值:无
]]
function closeSoftDog()
print("closeSoftDog test")
sys.timerStop(eatSoftDog)
rtos.closeSoftDog()
end
--打开并设置软狗超时时间单位MS,超过设置时间没去喂狗,重启模块
rtos.openSoftDog(60*1000)
--定时喂狗
sys.timerLoopStart(eatSoftDog,50*1000)
--关闭软狗
sys.timerStart(closeSoftDog,180*1000)
--打印版本号
sys.timerLoopStart(log.info,2000,rtos.get_version(),_G.VERSION)
|
ID = {}
ID.instances = {}
function ID.CreateFactory()
local o = {
_id_ = 0
}
setmetatable(o, { __index = ID })
table.insert(ID.instances, o)
return o
end
function ID:Obtain()
local id = self._id_
self._id_ = id + 1
return id
end
function ID:Reset()
self._id_ = 0
end
|
local menu = {}
local bg = {}
if not pcall(function () menu.font = love.graphics.newFont("assets/murder.ttf", 150) end) then
print("Could not load 'murder.ttf' font..")
return 2
end
love.graphics.setFont(menu.font)
bg.background = {bg1, bg2, bg3, bg4, bg5, bg5}
for i = 1, 7 do
if not pcall(function () bg.background[i] = love.graphics.newImage("assets/mmenu/background/bg" .. i .. ".png") end) then
print("Could not load background asset.")
return 2
end
end
if not pcall(function () bg.rock = love.graphics.newImage("assets/mmenu/background/rock.png") end) then
print("Could not load background asset.")
return 2
end
bg.rock_scalex = 0.6
bg.rock_scaley = 0.6
bg.rock_x = (love.graphics.getWidth() / 2) - 160
bg.rock_y = (love.graphics.getHeight() / 2) - 300
bg.rock_sizex = bg.rock:getWidth() * bg.rock_scalex
bg.rock_sizey = bg.rock:getHeight() * bg.rock_scaley
bg.scalex = 0.75
bg.scaley = 0.805
bg.x = 0
bg.y = 0
button = {}
table.insert(menu, bg)
if not pcall(function () button.play = love.graphics.newImage("assets/mmenu/buttons/play.png") end) then
print("Could not load play button asset.")
return 2
end
if not pcall(function () button.playwshadow = love.graphics.newImage("assets/mmenu/buttons/playwshadow.png") end) then
print("Could not load play w shadow button asset.")
return 2
end
if not pcall(function () button.settings = love.graphics.newImage("assets/mmenu/buttons/options.png") end) then
print("Could not load options button asset.")
return 2
end
if not pcall(function () button.settingswshadow = love.graphics.newImage("assets/mmenu/buttons/optionswshadow.png") end) then
print("Could not load options w shadow button asset.")
return 2
end
if not pcall(function () button.info = love.graphics.newImage("assets/mmenu/buttons/info.png") end) then
print("Could not load info button asset.")
return 2
end
if not pcall(function () button.infowshadow = love.graphics.newImage("assets/mmenu/buttons/infowshadow.png") end) then
print("Could not load info w shadow button asset.")
return 2
end
if not pcall(function () button.leader = love.graphics.newImage("assets/mmenu/buttons/leader.png") end) then
print("Could not load leader button asset.")
return 2
end
if not pcall(function () button.leaderwshadow = love.graphics.newImage("assets/mmenu/buttons/leaderwshadow.png") end) then
print("Could not load leader w shadow button asset.")
return 2
end
button.playscalex = 0.9
button.playscaley = 0.9
button.settingsscalex = 0.7
button.settingsscaley = 0.7
button.infoscalex = 0.5
button.infoscaley = 0.5
button.leaderscalex = 0.7
button.leaderscaley = 0.7
button.playsizex = button.play:getWidth() * button.playscalex
button.playsizey = button.play:getHeight() * button.playscaley
button.settingssizex = button.play:getWidth() * button.settingsscalex
button.settingssizey = button.play:getHeight() * button.settingsscaley
button.infosizex = button.play:getWidth() * button.infoscalex
button.infosizey = button.play:getHeight() * button.infoscaley
button.leadersizex = button.leader:getWidth() * button.leaderscalex
button.leadersizey = button.leader:getHeight() * button.leaderscaley
button.playx = love.graphics.getWidth() / 2
button.playy = love.graphics.getHeight() * 0.66
button.settingsx = (love.graphics.getWidth() / 2) - button.playsizex - 20
button.settingsy = love.graphics.getHeight() * 0.66
button.infox = button.infosizex - button.infosizex / 2 - 10
button.infoy = love.graphics.getHeight() - 82
button.leaderx = (love.graphics.getWidth() / 2) + button.playsizex - 9
button.leadery = love.graphics.getHeight() * 0.66
button.collision = 0
table.insert(menu, button)
return menu |
--redis-cli -c --eval lock.lua unit1 , resource locker mode value
local r= redis.call('hsetnx',KEYS[1],ARGV[1],ARGV[2])
if r==0 then --锁已存在
local locker=redis.call('hget',KEYS[1],ARGV[1])
local mode=redis.call('hget',KEYS[1],ARGV[1]..'_M')
if ARGV[3]=='S' then --申请共享锁
if (mode~='X') then --当前为共享锁
if locker~=ARGV[2] then --非原始拥有者,计数器增加
redis.call('hincrby',KEYS[1],ARGV[1]..'_M',1)
end
return ARGV[2] --加锁成功
else --当前为排它锁
return ''; --锁冲突,加锁失败
end
else --申请排它锁
if (mode=='X') then --当前为排它锁
return locker --返回原始拥有者,调用方判断是否成功
else --当前为共享锁
return ''; --锁冲突,加锁失败
end
end
else
if (ARGV[3]=='X') then --申请排它锁,锁类型为'X'
redis.call('hmset',KEYS[1], ARGV[1]..'_M', ARGV[3], ARGV[1]..'_V', ARGV[4])
else --申请共享锁,锁类型为计数器
redis.call('hmset',KEYS[1], ARGV[1]..'_M', 1, ARGV[1]..'_V', ARGV[4])
end
return ARGV[2] --加锁成功
end
|
local nmap = require "nmap"
local stdnse = require "stdnse"
local string = require "string"
description = [[
Checks if a target on a local Ethernet has its network card in promiscuous mode.
The techniques used are described at
http://www.securityfriday.com/promiscuous_detection_01.pdf.
]]
---
-- @output
-- Host script results:
-- |_ sniffer-detect: Likely in promiscuous mode (tests: "11111111")
author = "Marek Majkowski"
license = "Same as Nmap--See http://nmap.org/book/man-legal.html"
categories = {"discovery", "intrusive"}
-- okay, we're interested only in hosts that are on our ethernet lan
hostrule = function(host)
if nmap.address_family() ~= 'inet' then
stdnse.print_debug("%s is IPv4 compatible only.", SCRIPT_NAME)
return false
end
if host.directly_connected == true and
host.mac_addr ~= nil and
host.mac_addr_src ~= nil and
host.interface ~= nil then
local iface = nmap.get_interface_info(host.interface)
if iface and iface.link == 'ethernet' then
return true
end
end
return false
end
local function check (layer2)
return string.sub(layer2, 0, 12)
end
do_test = function(dnet, pcap, host, test)
local status, length, layer2, layer3
local i = 0
-- ARP requests are send with timeouts: 10ms, 40ms, 90ms
-- before each try, we wait at least 100ms
-- in summary, this test takes at least 100ms and at most 440ms
for i=1,3 do
-- flush buffers :), wait quite long.
repeat
pcap:set_timeout(100)
local test = host.mac_addr_src .. host.mac_addr
status, length, layer2, layer3 = pcap:pcap_receive()
while status and test ~= check(layer2) do
status, length, layer2, layer3 = pcap:pcap_receive()
end
until status ~= true
pcap:set_timeout(10 * i*i)
dnet:ethernet_send(test)
local test = host.mac_addr_src .. host.mac_addr
status, length, layer2, layer3 = pcap:pcap_receive()
while status and test ~= check(layer2) do
status, length, layer2, layer3 = pcap:pcap_receive()
end
if status == true then
-- the basic idea, was to inform user about time, when we got packet
-- so that 1 would mean (0-10ms), 2=(10-40ms) and 3=(40ms-90ms)
-- but when we're running this tests on macs, first test is always 2.
-- which means that the first answer is dropped.
-- for now, just return 1 if test was successfull, it's easier
-- return(i)
return(1)
end
end
return('_')
end
action = function(host)
local dnet = nmap.new_dnet()
local pcap = nmap.new_socket()
local _
local status
local results = {
['1_____1_'] = false, -- MacOSX(Tiger.Panther)/Linux/ ?Win98/ WinXP sp2(no pcap)
['1_______'] = false, -- Old Apple/SunOS/3Com
['1___1_1_'] = false, -- MacOSX(Tiger)
['11111111'] = true, -- BSD/Linux/OSX/ (or not promiscous openwrt )
['1_1___1_'] = false, -- WinXP sp2 + pcap|| win98 sniff || win2k sniff (see below)
['111___1_'] = true, -- WinXP sp2 promisc
-- ['1111__1_'] = true, -- ?Win98 promisc + ??win98 no promisc *not confirmed*
}
dnet:ethernet_open(host.interface)
pcap:pcap_open(host.interface, 64, false, "arp")
local test_static = host.mac_addr_src ..
string.char(0x08,0x06, 0x00,0x01, 0x08,0x00, 0x06,0x04, 0x00,0x01) ..
host.mac_addr_src ..
host.bin_ip_src ..
string.char(0x00,0x00, 0x00,0x00, 0x00,0x00) ..
host.bin_ip
local t = {
string.char(0xff,0xff, 0xff,0xff, 0xff,0xff), -- B32 no meaning?
string.char(0xff,0xff, 0xff,0xff, 0xff,0xfe), -- B31
string.char(0xff,0xff, 0x00,0x00, 0x00,0x00), -- B16
string.char(0xff,0x00, 0x00,0x00, 0x00,0x00), -- B8
string.char(0x01,0x00, 0x00,0x00, 0x00,0x00), -- G
string.char(0x01,0x00, 0x5e,0x00, 0x00,0x00), -- M0
string.char(0x01,0x00, 0x5e,0x00, 0x00,0x01), -- M1 no meaning?
string.char(0x01,0x00, 0x5e,0x00, 0x00,0x03), -- M3
}
local v
local out = ""
for _, v in ipairs(t) do
out = out .. do_test(dnet, pcap, host, v .. test_static)
end
dnet:ethernet_close()
pcap:pcap_close()
if out == '1_1___1_' then
return 'Windows with libpcap installed; may or may not be sniffing (tests: "' .. out .. '")'
end
if results[out] == false then
-- probably not sniffing
return
end
if results[out] == true then
-- rather sniffer.
return 'Likely in promiscuous mode (tests: "' .. out .. '")'
end
-- results[out] == nil
return 'Unknown (tests: "' .. out .. '")'
end
|
local SceneDirector = require "controllers.SceneDirector"
local GameDirector = require "controllers.GameDirector"
local ScaleDimension = require "util.ScaleDimension"
function love.load()
scaleDimension = ScaleDimension:new()
gameDirector = GameDirector:new()
gameDirector.enemiesController:createEnemies()
sceneDirector = SceneDirector:new()
end
function love.keypressed(key, scancode, isrepeat)
if key == "escape" then
love.event.quit()
end
sceneDirector:keypressed(key, scancode, isrepeat)
end
function love.keyreleased(key, scancode)
sceneDirector:keyreleased(key, scancode)
end
function love.mousemoved(x, y, dx, dy, istouch)
sceneDirector:mousemoved(x, y, dx, dy, istouch)
end
function love.mousepressed(x, y, button)
sceneDirector:mousepressed(x, y, button)
end
function love.mousereleased(x, y, button)
sceneDirector:mousereleased(x, y, button)
end
function love.wheelmoved(x, y)
sceneDirector:wheelmoved(x, y)
end
function love.update(dt)
sceneDirector:update(dt)
end
function love.draw()
sceneDirector:draw()
end
|
--[[
@ lua debug for vs code
@
@ Author luhengsi
@ Mail luhengsi@163.com
@ Date 2018-06-10
@
@ please check Licence.txt file for licence and legal issues.
]]
local sformat = string.format;
local sfind = string.find;
local ssub = string.sub;
local sgsub = string.gsub
local sgmatch = string.gmatch;
local slower = string.lower;
local dsethook = debug.sethook;
local dgethook = debug.gethook;
local dgetinfo = debug.getinfo;
local dtraceback = debug.traceback;
local dgetupvalue = debug.getupvalue;
local dgetlocal = debug.getlocal;
local iowrite = io.write
local iolines = io.lines
local tconcat = table.concat;
l_debug = l_debug or {};
l_debug.DEBUG_MODE_RUN = "run";
l_debug.DEBUG_MODE_NEXT = "next";
l_debug.DEBUG_MODE_STEP_IN = "step_in";
l_debug.DEBUG_MODE_WAIT = "wait";
l_debug.WRITE_ERROR = 0;
l_debug.WRITE_INFOR = 1;
l_debug.HOOK_CMD_CALL = 1
l_debug.HOOK_CMD_LINE = 2
l_debug.HOOK_CMD_RET = 3
l_debug.HOOK_CMD_TAIL_CALL = 4
l_debug.CMD_2_HOOK =
{
["call"] = l_debug.HOOK_CMD_CALL,
["line"] = l_debug.HOOK_CMD_LINE,
["return"] = l_debug.HOOK_CMD_RET,
["tail return"] = l_debug.HOOK_CMD_RET,
["tail call"] = l_debug.HOOK_CMD_TAIL_CALL,
}
function l_debug:init()
print("l_debug init.")
self:_init();
self:fwrite("l_debug init success.");
end
function l_debug:fwrite(...)
if self._fwrite then
local t_info = {"debug>", ...};
local sinfo = tconcat(t_info, "\t").."\n";
self._fwrite(sinfo);
end
end
function l_debug.freadline(...)
if l_debug._freadline then
l_debug._freadline(...);
end
end
function l_debug:_init()
self._fwrite = nil;
self._freadline = nil;
self.map = {};
self.id_info = {};
self.workingPath = "";
self.count = 0;
self.enable_count = 0;
self:reset_state();
end
function l_debug:reset_state()
self.mode = self.DEBUG_MODE_RUN;
self.call_deep = 0;
self.step_in_deep = -1;
end
function l_debug:release()
self:unhook();
self:_init();
self:reset_state();
self.fwrite("debug> debug finish.\n");
end
function l_debug:set_io_fuc(fwrite, freadline)
self._fwrite = fwrite;
self._freadline = freadline;
end
function l_debug:set_workingPath(workingPath)
workingPath = workingPath or "";
self.workingPath = sgsub(slower(workingPath), '\\', "/");
end
function l_debug:get_real_path(file_path)
local _, _, path = sfind(file_path, "(%w.*)");
file_path = path or "";
file_path = sgsub(file_path, '\\', '/');
file_path = slower(file_path);
return file_path;
end
function l_debug:set_mode(smode)
self.mode = smode or self.DEBUG_MODE_RUN;
local sinfo = sformat("debug mode change to: %s", self.mode);
self:fwrite(sinfo);
return 1;
end
function l_debug:unhook()
dsethook();
end
function l_debug:set_hook_c()
self:reset_state();
dsethook(self.hook_c, "c");
end
function l_debug:set_hook_crl()
dsethook(self.hook_crl, "crl");
end
function l_debug:set_hook_cr()
dsethook(self.hook_cr, "cr");
end
function l_debug:add_break_point(path, line)
if type(path) ~= "string" or type(line) ~= "number" then
return;
end
local info = self.map[path];
if not info then
info = {};
self.map[path] = info;
self.count = self.count + 1;
end
if not info[line] or info[line] ~= 1 then
info[line] = 1;
self.enable_count = self.enable_count + 1;
end
self.id_info[path] = self.id_info[path] or {};
local index = #(self.id_info[path]) + 1;
self.id_info[path][index] = line;
if self.enable_count > 0 and not dgethook() then
self:set_hook_c();
end
end
function l_debug:set_break_points(path, lines)
if type(path) ~= "string" or type(lines) ~= "table" then
return {};
end
local break_points = {};
local info = self.map[path];
if info then
for line, enable in pairs(info) do
self.count = self.count - 1;
if enable == 1 then
self.enable_count = self.enable_count - 1;
end
end
end
info = {};
self.map[path] = info;
local count = 0;
for _, line in ipairs(lines) do
info[line] = 1;
self.count = self.count + 1;
self.enable_count = self.enable_count + 1;
count = count + 1;
break_points[count] = line;
end
self.id_info[path] = break_points;
if self.enable_count > 0 and not dgethook() then
self:set_hook_c();
elseif self.enable_count < 1 and self.mode == self.DEBUG_MODE_RUN then
self:unhook();
end
return break_points;
end
function l_debug:clear_break_point(path)
if type(path) ~= "string" then
return;
end
local info = self.map[path];
if not info then
return;
end
self.map[path] = nil;
self.id_info[path] = nil;
for line_no, enable in pairs(info) do
if enable == 1 then
self.enable_count = self.enable_count - 1;
end
self.count = self.count - 1;
end
if self.enable_count < 1 and self.mode == self.DEBUG_MODE_RUN and dgethook() then
self:unhook();
end
end
function l_debug:del_break_point(path, line)
if type(path) ~= "string" or type(line) ~= "number" then
return;
end
local info = self.map[path];
if not info then
return;
end
if not info[line] then
return;
end
if info[line] == 1 then
self.enable_count = self.enable_count -1;
end
self.count = self.count - 1;
self.id_info[path] = self.id_info[path] or {};
local break_points = {};
local index = 0;
for id, line_no in ipairs(self.id_info[path]) do
if line_no ~= line then
index = index + 1;
break_points[index] = line_no;
end
end
self.id_info[path] = break_points;
if self.enable_count < 1 and dgethook() then
self:unhook();
end
end
function l_debug:disable_break_point(path, line)
if type(path) ~= "string" or type(line) ~= "number" then
return;
end
local info = self.map[path];
if not info then
return;
end
if not info[line] then
return;
end
if info[line] == 1 then
self.enable_count = self.enable_count - 1;
end
if self.enable_count < 1 and dgethook() then
self:unhook();
end
end
function l_debug:enable_break_point(path, line)
if type(path) ~= "string" or type(line) ~= "number" then
return;
end
local info = self.map[path];
if not info then
return;
end
if not info[line] then
return;
end
if info[line] ~= 1 then
info[line] = 1;
self.enable_count = self.enable_count + 1;
end
if self.enable_count > 0 and not dgethook() then
self:set_hook_c();
end
end
local g_count = 0;
function l_debug:test_break_point(path, line, start_line, end_line)
local b_file, b_func, b_line = false, false, false;
local info = self.map[path]
if info then
b_file = true;
if info[line] and info[line] == 1 then
b_func = true;
b_line = true;
elseif type(start_line) == "number" and type(end_line) == "number" then
if start_line == 304 and g_count < 16 then
g_count = g_count + 1;
end
for line_no, enable in pairs(info) do
if line_no > start_line and line_no < end_line and enable == 1 then
b_func = true;
break;
end
end
end
end
return b_file, b_func, b_line;
end
function l_debug:get_stack_info()
return self.straceback or "";
end
function l_debug:get_upvalue_info()
return self.tvariables_upvalue or {};
end
function l_debug:get_local_info()
return self.tvariables_local or {};
end
function l_debug:update_statck_info(nlevel)
nlevel = nlevel or 2;
nlevel = nlevel + 1;
-- save stack trace
self.straceback = dtraceback("stack", nlevel);
-- save upvalue veriables
local func = dgetinfo(nlevel, "f").func;
local index = 1;
local tvariables = {};
self.tvariables_upvalue = tvariables;
local name, val;
local count = 1;
repeat
name, val = dgetupvalue(func, count)
count = count + 1;
if name then
tvariables[name] = val;
end
until not name
-- save local variables
local count = 1;
local tvariables = {};
self.tvariables_local = tvariables;
repeat
name, val = dgetlocal(nlevel, count)
count = count + 1;
if name then
tvariables[name] = val;
end
until not name
local count = 1;
end
function l_debug.hook_c(scmd)
local self = l_debug;
-- local cmd = self.CMD_2_HOOK[scmd];
local info = dgetinfo(2, "S");
local s_source = info["source"];
local s_what = info["what"];
local n_linedefined = info["linedefined"];
local n_lastlinedefined = info["lastlinedefined"];
if s_what ~= "Lua" then
return;
end
local path = self:get_real_path(s_source);
local b_file, b_func = self:test_break_point(path, nil, n_linedefined, n_lastlinedefined);
if b_func then
self:set_hook_crl();
end
end
function l_debug.hook_crl(scmd, line)
local self = l_debug;
local cmd = self.CMD_2_HOOK[scmd];
local info = dgetinfo(2, "Sl");
local n_currentline = info["currentline"];
local n_linedefined = info["linedefined"];
local n_lastlinedefined = info["lastlinedefined"];
local s_what = info["what"] or "";
if s_what ~= "Lua" and s_what ~= "main" then
return;
end
local s_source = info["source"];
local path = self:get_real_path(s_source);
local b_file, b_func, b_line = self:test_break_point(path, n_currentline, n_linedefined, n_lastlinedefined);
if cmd == self.HOOK_CMD_CALL then
self.call_deep = self.call_deep + 1;
if self.mode == self.DEBUG_MODE_STEP_IN then
self.step_in_deep = self.call_deep;
end
if not b_func and self.mode ~= self.DEBUG_MODE_STEP_IN then
self:set_hook_cr();
end
return;
elseif cmd == self.HOOK_CMD_TAIL_CALL then
if self.step_in_deep >= 0 and self.step_in_deep == self.call_deep then
self.step_in_deep = self.step_in_deep - 1;
end
if not b_func and self.mode ~= self.DEBUG_MODE_STEP_IN then
self:set_hook_cr();
end
return;
elseif cmd == self.HOOK_CMD_RET then
self.call_deep = self.call_deep - 1;
return;
end
if not b_func and self.mode == self.DEBUG_MODE_RUN then
if self.call_deep < 1 then
if self.enable_count > 0 then
self:set_hook_c();
else
self:unhook();
end
else
self:set_hook_cr();
end
return;
end
-- if mode is next or find a break then stop
if (b_func and self.mode == self.DEBUG_MODE_NEXT) or
(self.step_in_deep >= 0 and self.step_in_deep >= self.call_deep and self.mode ~= self.DEBUG_MODE_RUN) or
b_line then
local sinfo = sformat("[%s|%s]%s:%s", s_what, cmd, s_source or "nil", n_currentline or "nil");
print("debug>", sinfo)
-- self:fwrite(sinfo);
-- wait for command
if b_line then
ldb_mrg:stop_on_breakpoint();
else
ldb_mrg:stop_on_step();
end
self.step_in_deep = self.call_deep;
self.mode = self.DEBUG_MODE_WAIT;
self:update_statck_info(2);
while (self.mode == self.DEBUG_MODE_WAIT) do
ldb_mrg:on_tick(self.DEBUG_MODE_WAIT);
ldb_mrg:sleep(100);
end
return;
end
end
function l_debug.hook_cr(scmd)
local self = l_debug;
local cmd = self.CMD_2_HOOK[scmd];
local info = dgetinfo(2, "S");
local s_source = info["source"];
local s_what = info["what"];
local n_linedefined = info["linedefined"];
local n_lastlinedefined = info["lastlinedefined"];
if s_what ~= "Lua" and s_what ~= "main" then
return;
end
if cmd == self.HOOK_CMD_CALL then
self.call_deep = self.call_deep + 1;
local path = self:get_real_path(s_source);
local b_file, b_func, b_line = self:test_break_point(path, nil, n_linedefined, n_lastlinedefined);
if b_func then
self:set_hook_crl();
end
return;
elseif cmd == self.HOOK_CMD_TAIL_CALL then
if self.step_in_deep >= 0 and self.step_in_deep == self.call_deep then
self.step_in_deep = self.step_in_deep - 1;
end
local path = self:get_real_path(s_source);
local b_file, b_func, b_line = self:test_break_point(path, nil, n_linedefined, n_lastlinedefined);
if b_func then
self:set_hook_crl();
end
return;
else
self.call_deep = self.call_deep - 1;
self:set_hook_crl();
return;
end
end
-- l_debug:init();
-- l_debug:release();
return l_debug;
|
local orangeButton = {
name = 'orange',
image = love.graphics.newImage('assets/orangeButton.png'),
width = 0,
height = 0,
x = 0,
y = 0
}
orangeButton.width = orangeButton.image:getWidth()
orangeButton.height = orangeButton.image:getHeight()
return orangeButton
|
-- @start
-- @namespace com.github.mounthuaguo.monkeyking.lua
-- @version 0.1
-- @name Random
-- @description Auto generate some random charactors.
-- @author Heramerom
-- @type action
-- @action Insert Random Charactors
-- @action Insert Hex Charactors
-- @action Insert Digital Charactors
-- @action Insert Lowercase Charactors
-- @action Insert Uppercase Charactors
-- @end
local digital = '1234567890'
local lowercase = 'abcdefghijklmnopqrstuvwxyz'
local uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
local special = '!@#$%^&*()'
local hex = '1234567890abcdef'
local date = luajava.newInstance('java.util.Date')
local rand = luajava.newInstance('java.util.Random', date:getTime())
function gen(str, length)
local ret = ''
local bounds = string.len(str)
for i = 1,length do
local offset = rand:nextInt(bounds) + 1
ret = ret .. string.sub(str, offset, offset)
end
return ret
end
function inputLength()
local ret = dialog.show({field = 'Length', type = 'text', default = '32'})
if not ret.success then
return nil
end
return tonumber(ret.data.Length)
end
function insert(str)
event.document.insertString(event.selectionModel.selectionStart, str)
end
local menus = {
{menu = 'Insert Hex Charactors', str = hex},
{menu = 'Insert Digital Charactors', str = digital},
{menu = 'Insert Lowercase Charactors', str = lowercase},
{menu = 'Insert Uppercase Charactors', str = uppercase},
}
for i, m in ipairs(menus) do
if m.menu == menu then
local length = inputLength()
if length == nil then
return
end
local str = gen(m.str, length)
insert(str)
end
end
if menu == 'Insert Random Charactors' then
local r = dialog.show({
field = 'Length',
type = 'text',
default = 32
},
{
field = 'Charactors',
type = 'checkbox',
default = {'Digital', 'Lowercase'},
options = {'Digital', 'Lowercase', 'Uppercase', 'Special Charactors'}
})
if not r.success then
return
end
local length = tonumber(r.data['Length'])
if length == nil then
return
end
if r.data.Charactors == nil then
return
end
local str = ''
for i, v in ipairs(r.data.Charactors) do
if v == 'Digital' then
str = str .. digital
end
if v == 'Lowercase' then
str = str .. lowercase
end
if v == 'Uppercase' then
str = str .. uppercase
end
if v == 'Special Charactors' then
str = str .. special
end
end
insert(gen(str, length))
end
|
local fn = vim.fn
local cmd = vim.api.nvim_command
-- packer.nvim
--
-- Install packer.nvim if it's not ready.
--
-- To know whether packer.nvim is installn or not, check this folder exists:
--
-- $DATA/site/pack/packer/start/packer.nvim
--
local packer_install_path = fn.stdpath('data') ..
'/site/pack/packer/start/packer.nvim'
if fn.empty(fn.glob(packer_install_path)) > 0 then
fn.system({
'git', 'clone', '--depth', '1',
'https://github.com/wbthomason/packer.nvim', packer_install_path
})
end
cmd('packadd packer.nvim')
--
-- Auto recompile plugins when changes in plugin.lua
--
vim.cmd [[
augroup packer_recompile
autocmd!
autocmd BufWritePost */lua/plugins.lua echom "Recompile!" | source <afile> | PackerCompile
augroup END
]]
local pkr = require('packer')
pkr.init({
ensure_dependencies = true,
display = {
auto_clean = false,
open_fn = function()
return require('packer.util').float {border = 'single'}
end
}
})
pkr.startup(function(use)
use 'wbthomason/packer.nvim'
use {
'airblade/vim-rooter',
config = [[
vim.g.rooter_silent_chdir = 1
vim.g.rooter_patterns = {'.git', '.root'}
]],
fn = 'FindRootDirectory'
}
use {
"tami5/sqlite.lua",
config = [[
if vim.fn.has('win32') ~= 0 then
vim.g.sqlite_clib_path = "d:/libs/sqlite/sqlite3.dll"
end
]],
opt = true
}
use {
'nvim-telescope/telescope.nvim',
cmd = "Telescope",
requires = {
{'nvim-lua/plenary.nvim', opt = true},
{
'nvim-telescope/telescope-fzf-native.nvim',
run = "make",
opt = true
}, -- require sqlite: brew install sqlite
{
"nvim-telescope/telescope-frecency.nvim",
opt = true,
wants = 'sqlite.lua',
requires = {
"sqlite.lua"
}
}
},
config = [[
require('config.telescope')
]],
wants = {
"plenary.nvim",
"telescope-fzf-native.nvim",
"telescope-frecency.nvim"
}
}
-- use {
-- 'sainnhe/gruvbox-material',
-- config = [[
-- vim.cmd("colorscheme gruvbox-material")
-- vim.g.gruvbox_material_palette = 'original'
-- ]]
-- }
use {"ellisonleao/gruvbox.nvim", requires = {"rktjmp/lush.nvim"},
config = [[
vim.g.gruvbox_invert_selection=0
vim.cmd("colorscheme gruvbox")
]]}
use {
'windwp/nvim-autopairs',
config = [[
require('nvim-autopairs').setup{}
]]
}
use 'tpope/vim-surround'
use {
'rhysd/vim-clang-format',
cmd = 'ClangFormat',
config = [[
vim.g['clang_format#auto_format'] = 0
vim.g['clang_format#code_style'] = 'chromium'
vim.g['clang_format#style_options'] = {SortIncludes = 'false'}
]],
}
use 'tpope/vim-abolish'
use {'tpope/vim-fugitive', cmd = {'Git', 'G'}}
-- text object
use {'kana/vim-textobj-user',
opt = true,
setup = function()
require('utils').packer_lazy_load 'vim-textobj-user'
end
}
use {
'sgur/vim-textobj-parameter',
opt = true,
requires = 'kana/vim-textobj-user',
after = 'vim-textobj-user'
}
-- skywin3000
use {
'skywind3000/asynctasks.vim',
opt = true,
cmd = {'AsyncRun', 'AsyncStop', 'AsyncTask', 'AsyncTaskEdit'},
requires = {
{
'skywind3000/asyncrun.vim',
opt = true,
config = [[
vim.g.asyncrun_open = 10
]]
}
}
}
use {
'tpope/vim-unimpaired',
opt = true,
setup = function()
require('utils').packer_lazy_load 'vim-unimpaired'
end
}
use {
'neovim/nvim-lspconfig',
event = 'BufReadPre',
config = [[
require('config.nvim-lspconfig')
]]
}
use {
'hrsh7th/nvim-cmp',
config = [[
require('cmp').setup{
sources = {
{ name = 'nvim_lsp'}
}
}
]]
}
use 'hrsh7th/cmp-nvim-lsp'
use {
'dstein64/vim-startuptime',
cmd = 'StartupTime'
}
use {
'kyazdani42/nvim-web-devicons',
config = [[
require'nvim-web-devicons'.setup {}
]]
}
use 'justinmk/vim-dirvish'
-- use({
-- "NTBBloodbath/galaxyline.nvim",
-- -- your statusline
-- config = function()
-- require("galaxyline.themes.spaceline")
-- end,
-- })
use {
'hoob3rt/lualine.nvim',
config = [[
require('config.lualine')
]]
}
use {
"terrortylor/nvim-comment",
config = [[
require('nvim_comment').setup {}
]]
}
use {
"lyokha/vim-xkbswitch",
config = [[
vim.g.XkbSwitchEnabled = 1
]]
}
end)
|
tfm.exec.disableAutoNewGame(true)
tfm.exec.disableAutoShaman(true)
tfm.exec.disableAutoTimeLeft(true)
tfm.exec.disableAfkDeath(true)
tfm.exec.newGame([[<C><P F="0"/><Z><S><S X="79" o="aac4d2" L="162" Y="165" c="4" H="334" P="0,0,0.3,0.2,0,0,0,0" T="12"/><S X="169" o="6d9bb3" L="144" Y="201" c="4" H="285" P="0,0,0.3,0.2,-10,0,0,0" T="12"/><S X="400" o="a18600" L="803" Y="364" H="78" P="0,0,0.3,0.2,0,0,0,0" T="12"/><S X="296" o="285b74" L="52" Y="207" c="4" H="240" P="0,0,0.3,0.2,0,0,0,0" T="12"/><S X="367" o="b5d8ea" L="113" Y="178" c="4" H="300" P="0,0,0.3,0.2,0,0,0,0" T="12"/><S X="528" o="3d657a" L="61" Y="236" c="4" H="182" P="0,0,0.3,0.2,0,0,0,0" T="12"/><S X="653" o="a5c5d6" L="197" Y="164" c="4" H="332" P="0,0,0.3,0.2,0,0,0,0" T="12"/><S X="485" o="dfb218" L="78" Y="293" c="4" H="69" P="0,0,0.3,0.2,0,0,0,0" T="12"/><S X="435" o="5a4c06" L="75" Y="277" c="4" H="104" P="0,0,0.3,0.2,0,0,0,0" T="12"/><S X="338" o="0e67e7" L="12" Y="261" c="4" H="131" P="0,0,0.3,0.2,0,0,0,0" T="12"/><S X="338" o="0fa5f1" L="36" Y="197" c="4" H="10" P="0,0,0.3,0.2,0,0,0,0" T="13"/><S X="337" o="0b56c2" L="28" Y="253" c="4" H="10" P="0,0,0.3,0.2,0,0,0,0" T="12"/><S X="338" o="324650" L="10" Y="155" H="22" P="0,0,0.3,0.2,0,0,0,0" T="12"/><S X="338" o="0b56c2" L="17" Y="150" c="4" H="10" P="0,0,0.3,0.2,0,0,0,0" T="12"/><S X="338" o="0e67e7" L="10" Y="128" c="4" H="38" P="0,0,0.3,0.2,0,0,0,0" T="12"/><S X="721" o="7c99a7" L="111" Y="212" c="4" H="235" P="0,0,0.3,0.2,0,0,0,0" T="12"/><S X="56" o="480312" L="10" Y="310" c="4" H="36" P="0,0,0.3,0.2,0,0,0,0" T="12"/><S X="765" o="480312" L="10" Y="292" c="4" H="71" P="0,0,0.3,0.2,0,0,0,0" T="12"/><S X="592" o="480312" L="10" Y="279" c="4" H="94" P="0,0,0.3,0.2,0,0,0,0" T="12"/><S X="241" o="480312" L="10" Y="295" c="4" H="62" P="0,0,0.3,0.2,0,0,0,0" T="12"/><S X="753" o="055111" L="26" Y="248" c="4" H="10" P="0,0,0.3,0.2,0,0,0,0" T="13"/><S X="755" o="058419" L="10" Y="215" c="4" H="10" P="0,0,0.3,0.2,0,0,0,0" T="13"/><S X="730" o="05be22" L="10" Y="256" c="4" H="10" P="0,0,0.3,0.2,0,0,0,0" T="13"/><S X="560" o="83ae0b" L="20" Y="236" c="4" H="10" P="0,0,0.3,0.2,0,0,0,0" T="13"/><S X="576" o="129226" L="10" Y="195" c="4" H="10" P="0,0,0.3,0.2,0,0,0,0" T="13"/><S X="617" o="129226" L="29" Y="219" c="4" H="10" P="0,0,0.3,0.2,0,0,0,0" T="13"/><S X="595" o="058419" L="35" Y="232" c="4" H="10" P="0,0,0.3,0.2,0,0,0,0" T="13"/><S X="211" o="058419" L="15" Y="253" c="4" H="10" P="0,0,0.3,0.2,0,0,0,0" T="13"/><S X="253" o="05be22" L="15" Y="288" c="4" H="10" P="0,0,0.3,0.2,0,0,0,0" T="13"/><S X="234" o="058419" L="31" Y="272" c="4" H="10" P="0,0,0.3,0.2,0,0,0,0" T="13"/><S X="54" o="05be22" L="20" Y="239" c="4" H="10" P="0,0,0.3,0.2,0,0,0,0" T="13"/><S X="56" o="83ae0b" L="26" Y="266" c="4" H="10" P="0,0,0.3,0.2,0,0,0,0" T="13"/><S X="79" o="05be22" L="10" Y="279" c="4" H="10" P="0,0,0.3,0.2,0,0,0,0" T="13"/><S X="34" o="058419" L="20" Y="264" c="4" H="10" P="0,0,0.3,0.2,0,0,0,0" T="13"/><S X="774" o="058419" L="28" Y="243" c="4" H="10" P="0,0,0.3,0.2,0,0,0,0" T="13"/></S><D><DS X="431" Y="309"/></D><O/></Z></C>]])
--game variables
tips = {}
local CONSTANTS = {
BAR_WIDTH = 735,
BAR_X = 60,
STAT_BAR_Y = 30,
}
local players = {}
local healthPacks = {}
local courses = {}
local jobs = {}
local companies = {}
local tempData = {} --this table stores temporary data of players when they are creating a new job. Generally contains data in this order: tempPlayer = {jobName = 'MouseClick', jobSalary = 1000, jobEnergy = 0, minLvl = 100, qualification = "a pro"}
local closeButton = "<p align='right'><font color='#ff0000' size='13'><b><a href='event:close'>X</a></b></font></p>"
local nothing = "<br><br><br><br><p align='center'><b><R><font size='15'>Nothing to display!"
local cmds = [[
<p align='center'><font size='20'><b><J>Commands</J></b></font></p>
<b>!help:</b> Displays this dialogue
<b>!company <i>[company name]:</i></b> Displays the specified compnay
<b>!p <i>[player name]</i> or !profile <i>[player name]</i></b> Displays information about the specified player
]]
local gameplay = [[
<p align='center'><font size='20'><b><J>Game Play</J></b></font></p>
TFM Clicker is a game <b>clicker</b> which is based on an office/working environment. Your goal is to earn money, buy companies, hire workers and be the best businessman in transformice!
<b><u>Working:</u></b> You have to work to earn money. You just need to click the 'Work' button in the corner! When you work, it will result in reduction of your health. And also increase in your money. Different jobs have different salaries and energy costs!
<b><u>Shop:</u></b> Shop is the place you can buy usesful stuff <font size='8'>(that you all know ^_^)</font>. Bought items are stored temporarily in the inventory. You can use them to increase your health when neaded.
<b><u>Learning:</u></b> Learning is the only way to get qualifications for some jobs. Higher educational qualifications would result in better jobs.
<b><u>Companies:</u></b> You can buy a company when you have enough money for it. You can use your company to create jobs and recruit workers. (And that will increase your profit more and more!!).
]]
--creating the class Player
local Player = {}
Player.__index = Player
Player.__tostring = function(self)
return "[name=" .. self.name .. ",money=" .. self.money .. ", health=" .. self.health .. "]"
end
setmetatable(Player, {
__call = function (cls, name)
return cls.new(name)
end,
})
function Player.new(name)
local self = setmetatable({}, Player)
self.name = name
self.money = 0
self.health = 1.0
self.healthRate = 0.002
self.xp = 0
self.level = 1
self.learning = ""
self.learnProgress = 0
self.eduLvl = 1
self.eduStream = ""
self.degrees = {}
self.job = "Cheese collector"
self.ownedCompanies = {}
self.boss = "shaman"
self.company = "Atelie801"
self.inventory = {}
ui.addTextArea(1000, "", name, CONSTANTS.BAR_X, 340, CONSTANTS.BAR_WIDTH, 20, 0xff0000, 0xee0000, 1, true)
ui.addTextArea(2000, "", name, CONSTANTS.BAR_X, 370, 1, 17, 0x00ff00, 0x00ee00, 1, true)
return self
end
function Player:getName() return self.name end
function Player:getMoney() return self.money end
function Player:getHealth() return self.health end
function Player:getHealthRate() return self.healthRate end
function Player:getXP() return self.xp end
function Player:getLevel() return self.level end
function Player:getLearningCourse() return self.learning end
function Player:getLearningProgress() return self.learnProgress end
function Player:getEducationLevel() return self.eduLvl end
function Player:getEducationStream() return self.eduStream end
function Player:getDegrees() return self.degrees end
function Player:getOwnedCompanies() return self.ownedCompanies end
function Player:getBoss() return self.boss end
function Player:getInventory() return self.inventory end
function Player:getJob() return self.job end
function Player:work()
if self.health - find(self.job, jobs).energy > 0 then
local job = find(self.job, jobs)
self.setHealth(self, -job.energy, true)
self:setMoney(job.salary, true)
self:setXP(1, true)
players[job.owner]:setMoney(job.salary * 0.2, true)
self:levelUp()
end
end
function Player:setHealth(val, add)
if add then
self.health = self.health + val
else
self.health = val
end
self.health = self.health > 1 and 1 or self.health < 0 and 0 or self.health
ui.addTextArea(1000, "", self.name, CONSTANTS.BAR_X, 340, CONSTANTS.BAR_WIDTH * self.health, 20, 0xff0000, 0xee0000, 1, false)
ui.updateTextArea(2, "<p align='center'>" .. math.ceil(self.health * 100) .. "%</p>", self.name)
end
function Player:setMoney(val, add)
if add then
self.money = self.money + val
else
self.money = val
end
self.money = self.money < 0 and 0 or self.money
self:updateStatsBar()
end
function Player:setXP(val, add)
if add then
self.xp = self.xp + val
else
self.xp = val
end
ui.addTextArea(2000, "", self.name, CONSTANTS.BAR_X, 370, ((self.xp - calculateXP(self.level)) / (calculateXP(self.level + 1) - calculateXP(self.level))) * CONSTANTS.BAR_WIDTH, 17, 0x00ff00, 0x00ee00, 1, false)
ui.updateTextArea(3, "<p align='center'>Level " .. self.level .. " - " ..self.xp .. "/" .. calculateXP(self.level + 1) .. "XP", self.name)
end
function Player:setCourse(course)
self.learning = course.name
self.learnProgress = 0
self.eduLvl = course.level
self.eduStream = course.stream
ui.addTextArea(3000, "Lessons left: 0/" .. find(self.learning, courses).lessons, self.name, 5, 100, 50, 50, nil, nil, 0.8, false)
end
function Player:setJob(job)
local jobRef = find(job, jobs)
if jobRef.minLvl <= self.level and (jobRef.qualifications == nil or table.indexOf(self.degrees, jobRef.qualifications) ~= nil) then
find(self.company, companies):removeMember(self.name)
self.job = job
self.boss = jobRef.owner
self.company = jobRef.company
find(self.company, companies):addMember(self.name)
else
end
end
function Player:addOwnedCompanies(comName)
table.insert(self.ownedCompanies, comName)
end
function Player:addDegree(course)
table.insert(self.degrees, course)
end
function Player:learn()
if learning == "" then
else
if self.money > find(self.learning, courses).feePerLesson then
self.learnProgress = self.learnProgress + 1
ui.updateTextArea(3000, "Lessons left:" .. self.learnProgress .. "/" .. find(self.learning, courses).lessons, self.name)
self:setMoney(-find(self.learning, courses).feePerLesson, true)
if self.learnProgress >= find(self.learning, courses).lessons then
self:addDegree(self.learning)
self.learning = ""
self.eduLvl = self.eduLvl + 1
end
end
end
end
function Player:levelUp()
if self.xp >= calculateXP(self.level + 1) then
self.level = self.level + 1
self:setHealth(1.0, false)
self:setMoney(5 * self.level, true)
displayParticles(self.name, tfm.enum.particle.star)
end
end
function Player:useMed(med)
if not (self.health >= 1) then
self:setHealth(med.regainVal, med.adding)
displayParticles(self.name, tfm.enum.particle.heart)
end
end
function Player:updateStatsBar()
ui.updateTextArea(10, "<p align='right'>Money: $" .. self.money .." </p> ", self.name)
ui.updateTextArea(11, " Level: " .. self.level, self.name)
ui.updateTextArea(1, "<br><p align='center'><b>" .. self.name .. "</b></p>", self.name)
end
function Player:grabItem(item)
if self.inventory[item] == nil then
self.inventory[item] = 1
else
self.inventory[item] = self.inventory[item] + 1
end
end
function Player:useItem(item)
if self.inventory[item] ~= nil then
self.inventory[item] = self.inventory[item] - 1
if self.inventory[item] < 1 then
self.inventory[item] = nil
end
end
end
--class creation(Player) ends
--class creation(Company)
local Company = {}
Company.__index = Company
Company.__tostring = function(self)
return "[name=" .. self.name .. ",owner=" .. self.owner .. "]"
end
setmetatable(Company, {
__call = function (cls, ...)
return cls.new(...)
end,
})
function Company.new(name, owner)
local self = setmetatable({}, Company)
self.name = name
self.owner = owner
self.members = {}
self.jobs = {}
self.uid = "com:" .. name
return self
end
function Company:getName() return self.name end
function Company:getOwner() return self.owner end
function Company:getMembers() return self.members end
function Company:getJobs() return self.jobs end
function Company:getUID() return self.uid end
function Company:addMember(name)
local hasThisMember = false
for k, v in ipairs(self.members) do
if v == name then hasThisMember = true end
end
if not hasThisMember then
table.insert(self.members, name)
end
end
function Company:removeMember(name)
for k, v in ipairs(self.members) do
if v == name then
table.remove(self.members, k)
end
end
end
--class creation(Company) ends
--game functions
function displayShop(target, page)
local medicTxt = ""
for id, medic in next, {healthPacks[((page - 1) * 2) + 1], healthPacks[page * 2]} do
medicTxt = medicTxt .. "<b><font size='13'>" .. medic.name .. "</font></b><br><p align='right'><VP><a href='event:buy:" .. medic.uid .."'><b>| Buy |</b></a></VP></p>Price: " .. medic.price .. " Energy: " .. (medic.regainVal * 100) .. "%<br>" .. medic.desc .. "<br><br>"
end
ui.addTextArea(100, closeButton .. "<p align='center'><font size='20'><b><J>Shop</J></b></font></p><br></br>" .. (medicTxt == "" and nothing or medicTxt), target, 200, 90, 400, 200, nil, nil, 1, true)
ui.addTextArea(101, "<p align='center'><a href='event:page:shop:" .. page - 1 .."'>«</a></p>", target, 500, 310, 10, 15, nil, nil, 1, true)
ui.addTextArea(102, "Page " .. page, target, 523, 310, 50, 15, nil, nil, 1, true)
ui.addTextArea(103, "<p align='center'><a href='event:page:shop:" .. page + 1 .."'>»</a></p>", target, 585, 310, 15, 15, nil, nil, 1, true)
end
function displayCourses(target)
local courseTxt = ""
local p = players[target]
for id, course in ipairs(courses) do
if p:getEducationLevel() == course.level and (p:getEducationStream() == course.stream or p:getEducationStream() == "") and learning ~= "" then
courseTxt = courseTxt .. "<b><font size='13'>" .. course.name .. "</font></b><VP><a href='event:" .. course.uid .. "'><b> | Enroll |</b></a></VP><br><font size='10'>(Fee: " .. course.fee .. " Lessons: " .. course.lessons .. ")</font><br>"
end
end
ui.addTextArea(200, closeButton .. "<p align='center'><font size='20'><b><J>Courses</J></b></font></p><br></br>" .. (courseTxt == "" and nothing or courseTxt), target, 200, 90, 400, 200, nil, nil, 1, true)
end
function displayJobs(target, page)
local jobTxt = ""
local p = players[target]
local qJobs = getQualifiedJobs(target)
for id, job in next, {qJobs[((page - 1) * 2) + 1], qJobs[page * 2]} do
jobTxt = jobTxt .. "<b><font size='13'>" .. job.name .. "</font></b><br><p align='right'><b><VP><a href='event:" .. job.uid .. "'> | Choose | </a></VP></b></p>Salary: " .. job.salary .. " Energy: " .. (job.energy * 100) .. "%<br>Offered by <b>" .. job.owner .. "</b> of <b>" .. job.company .. "</b><br><br>"
end
ui.addTextArea(300, closeButton .. "<p align='center'><font size='20'><b><J>Jobs</J></b></font></p><br><br>" .. (jobTxt == "" and nothing or jobTxt), target, 200, 90, 400, 200, nil, nil, 1, true)
ui.addTextArea(301, "<p align='center'><a href='event:page:jobs:" .. page - 1 .."'>«</a></p>", target, 500, 310, 10, 15, nil, nil, 1, true)
ui.addTextArea(302, "Page " .. page, target, 523, 310, 50, 15, nil, nil, 1, true)
ui.addTextArea(303, "<p align='center'><a href='event:page:jobs:" .. page + 1 .."'>»</a></p>", target, 585, 310, 15, 15, nil, nil, 1, true)
end
function displayCompanyDialog(target)
if #players[target]:getOwnedCompanies() == 0 then
ui.addPopup(400, 1, "<p align='center'>No owned companies<br>Do you want to own one?</p>", target, 300, 90, 200, true)
else
local companyTxt = ""
local p = players[target]
for k, v in ipairs(p:getOwnedCompanies()) do
local company = find(v, companies)
companyTxt = companyTxt .. "<b><a href='event:" .. company:getUID() .. "'>" .. company:getName() .. "</a></b><br>Members: " .. (#company:getMembers() == 0 and "-" or string.sub(table.tostring(company:getMembers()), 2, -3))
end
ui.addTextArea(400, closeButton .. "<p align='center'><font size='20'><b><J>My Companies</J></b></font></p><br><br>" .. companyTxt, target, 200, 90, 400, 200, nil, nil, 1, true)
end
end
function displayCompany(name, target)
if find(name, companies) ~= nil then
local com = find(name, companies)
tempData[target].jobCompany = name
local companyTxt = ""
local members = ""
for k, v in ipairs(com:getMembers()) do
members = members .. v .. "<br>"
end
ui.addTextArea(400, closeButton .. "<p align='center'><font size='20'><b><J>" .. name .. "</J></b></font></p><br><br><b>Owner</b>: " .. com:getOwner() .. "<br><b>Members</b>: <br>" .. members, target, 200, 90, 400, 200, nil, nil, 1, true)
if com:getOwner() == target then
ui.addTextArea(401, "<a href='event:createJob'>Create Job</a>", target, 500, 310, 100, 20, nil, nil, 1, true)
end
else
ui.addPopup(404, 0, "<p align='center'><b><font color='#CB546B'>Company doesn't exist!", target, 300, 90, 200, true)
end
end
function displayJobWizard(target)
ui.addTextArea(500, closeButton .. [[<p align='center'><font size='20'><b><J>Job Wizard</J></b></font></p><br><br>
<b>Job Name: </b><a href='event:selectJobName'>]] .. (tempData[target].jobName == nil and "Select" or tempData[target].jobName) .. [[</a>
<b>Salary: </b><a href='event:selectJobSalary'> ]] .. (tempData[target].jobSalary == nil and "Select" or tempData[target].jobSalary) .. [[</a>
<b>Enery: </b><a href='event:selectJobEnergy'> ]] .. (tempData[target].jobEnergy == nil and "Select" or tempData[target].jobEnergy) .. [[</a>
<b>Minimum Level: </b><a href='event:chooseJobMinLvl'>]] .. (tempData[target].minLvl == nil and "Select" or tempData[target].minLvl) .. [[</a>
<b>Qualifcations: </b><a href='event:chooseJobDegree'>]] .. (tempData[target].qualification == nil and "Select" or tempData[target].qualification) .. [[</a><br>
]], target, 200, 90, 400, 200, nil, nil, 1, true)
end
function displayAllDegrees(target)
local degreeTxt = ""
for k, v in ipairs(courses) do
degreeTxt = degreeTxt .. "<a href='event:degree:" .. v.name .. "'>" .. v.name .. "</a><br>"
end
ui.addTextArea(600, closeButton .. "<p align='center'><font size='20'><b><J>Choose a Degree</J></b></font></p>" .. degreeTxt, target, 200, 90, 400, 200, nil, nil, 1, true)
end
function displayInventory(target)
local invTxt = ""
for k, v in pairs(players[target]:getInventory()) do
invTxt = invTxt .. "<b><font size='12'>".. k .. "</font><a href='event:use:" .. k .."'><VP> | Use x" .. v .. " |</VP> </a></b> : <font size='10'>(Energy: " .. (find(k, healthPacks).regainVal * 100) .. "%)</font><br>"
end
ui.addTextArea(700, closeButton .. "<p align='center'><font size='20'><b><J>Inventory</J></b></font></p><br>" .. (invTxt == "" and nothing or invTxt), target, 200, 90, 400, 200, nil, nil, 1, true)
end
function displayTips(target)
ui.addTextArea(800, tips[1], target, 6, 150, 120, 150, 0x324650, 0x000000, 1, true)
ui.addTextArea(801, "«", target, 10, 315, 10, 15, nil, nil, 1, true)
ui.addTextArea(802, "Page 1", target, 35, 315, 50, 15, nil, nil, 1, true)
ui.addTextArea(803, "<p align='center'><a href='event:page:tip:2'>»</a></p>", target, 100, 315, 15, 15, nil, nil, 1, true)
end
function displayProfile(name, target)
local p = players[name] or players[name .. "#0000"]
if p then
ui.addTextArea(900, closeButton .. "<p align='center'><font size='15'><b><BV>" .. p:getName() .."</BV></b></font></p><br><b>Level:</b> " .. tostring(p:getLevel()) .. "<BL><font size='12'> [" .. tostring(p:getXP()) .. "XP / " .. tostring(calculateXP(p:getLevel() + 1)) .. "XP]</font></BL><br><b>Money:</b> $" .. formatNumber(p:getMoney()) .. "<br><br><b>Working as a</b> " .. p:getJob() , target, 300, 100, 200, 130, nil, nil, 1, true)
end
end
function displayHelp(target, mode)
ui.addTextArea(950, "<B><J><a href='event:cmds'>Commands</a>", target, 30, 130, 75, 20, 0x324650, 0x000000, 1, true)
ui.addTextArea(951, "<a href='event:game'><B><J>Gameplay", target, 30, 95, 75, 20, 0x324650, 0x000000, 1, true)
ui.addTextArea(952, closeButton .. (mode == "game" and gameplay or cmds), target, 100, 90, 600, 230, 0x324650, 0x000000, 1, true)
end
function calculateXP(lvl)
return 2.5 * (lvl + 2) * (lvl - 1)
end
function displayParticles(target, particle)
tfm.exec.displayParticle(particle, tfm.get.room.playerList[target].x, tfm.get.room.playerList[target].y, 0, -2, 0, 0, nil)
tfm.exec.displayParticle(particle, tfm.get.room.playerList[target].x - 10, tfm.get.room.playerList[target].y, 0, -3, 0, 0, nil)
tfm.exec.displayParticle(particle, tfm.get.room.playerList[target].x + 10, tfm.get.room.playerList[target].y, 0, -2, 0, 0, nil)
tfm.exec.displayParticle(particle, tfm.get.room.playerList[target].x + math.random(-15, 15) , tfm.get.room.playerList[target].y, 0, -1, 0, 0, nil)
end
function getQualifiedJobs(player)
local p = players[player]
local qjobs = {}
for id, job in ipairs(jobs) do
if p:getLevel() >= job.minLvl and (job.qualifications == nil or table.indexOf(p:getDegrees(), job.qualifications) ~= nil) then
table.insert(qjobs, job)
end
end
return qjobs
end
function find(name, tbl)
for k,v in ipairs(tbl) do
if (v.name == name) then
return v
end
end
return nil
end
function createTip(tip, index)
tips[index] = closeButton .. "<p align='center'><J><b>Tips!</b></J><br><br>" .. tip
end
--[[copied from the internet. lazy to write it by myself :D
Credits: walterlua (https://gist.github.com/walterlua/978150/2742d9479cd5bfb3d08d90cfcb014da94021e271)
jakbyte
]]
function table.indexOf(t, object)
if type(t) ~= "table" then error("table expected, got " .. type(t), 2) end
for i, v in pairs(t) do
if object == v then
return i
end
end
end
--[[copied from stackoverflow
Credits: https://stackoverflow.com/users/1514861/ivo-beckers
Question: https://stackoverflow.com/questions/1426954/split-string-in-lua
]]
function split(s, delimiter)
result = {};
for match in (s..delimiter):gmatch("(.-)"..delimiter) do
table.insert(result, match);
end
return result;
end
function table.tostring(tbl)
s = "["
for k, v in pairs(tbl) do
s = s .. k .. ":" .. v .. ", "
end
return s .. "]"
end
function formatNumber(n)
if n >= 1000000000000 then
return math.floor(n / 100000000000) .. "T"
elseif n >= 1000000000 then
return math.floor(n / 100000000) .. "B"
elseif n >= 1000000 then
return math.floor(n / 100000) .. "M"
elseif n >= 10000 then
return math.floor(n / 1000) .. "K"
end
return n
end
function getTotalPages(type, target)
if type == 'tip' then
return #tips
elseif type == 'shop' then
return #healthPacks / 2 + (#healthPacks % 2)
elseif type == 'jobs' then
return #getQualifiedJobs(target) / 2 + (#getQualifiedJobs(target) % 2)
end
return 0
end
function updatePages(name, type, page)
if not (page < 1 or page > getTotalPages(type, name)) then
if type == 'tip' then
ui.updateTextArea(800, tips[page] or "", name)
ui.updateTextArea(801, "<a href='event:page:tip:" .. (page - 1) .. "'>«</a>", name)
ui.updateTextArea(802, "<p align='center'>Page " .. page .. "</p>", name)
ui.updateTextArea(803, "<a href='event:page:tip:" .. (page + 1) .. "'>»</a>", name)
elseif type == 'shop' then
displayShop(name, page)
elseif type == 'jobs' then
displayJobs(name, page)
end
end
end
function HealthPack(_name, _price, _regainVal, _adding, _desc)
return {
name = _name,
price = _price,
regainVal = _regainVal,
adding = _adding,
uid = "health:" .. _name,
desc = _desc
}
end
function Course(_name, _fee, _lessons, _level, _stream)
return {
name = _name,
fee = _fee,
lessons = _lessons,
level = _level,
stream = _stream,
feePerLesson = _fee / _lessons,
uid = "course:" .. _name
}
end
function Job(_name, _salary, _energy, _minLvl, _qualifications, _owner, _company)
return {
name = _name,
salary = _salary,
energy = _energy,
minLvl = _minLvl,
qualifications = _qualifications,
owner = _owner,
company = _company,
uid = "job:" .. _name
}
end
function setUI(name)
--textAreas
--work
ui.addTextArea(0, "<a href='event:work'><br><p align='center'><b>Work!</b></p>", name, 5, 340, 45, 50, 0x324650, 0x000000, 1, true)
--stats
--ui.addTextArea(1, name .. "<br>Money : $0 | Level 1", name, 6, CONSTANTS.STAT_BAR_Y, 785, 40, 0x324650, 0x000000, 1, true)
ui.addTextArea(10, "<p align='right'>Money: $0 </p> ", name, 200, 25, 120, 20, nil, nil, 1, true)
ui.addTextArea(11, " Level: 1", name, 480, 25, 120, 20, nil, nil, 1, true)
ui.addTextArea(1, "<br><p align='center'><b>" .. name .. "</b></p>", name, 325, 20, 150, 30, nil, nil, 1, true )
--health bar area
ui.addTextArea(2, "<p align='center'>100%</p>", name, CONSTANTS.BAR_X, 340, CONSTANTS.BAR_WIDTH, 20, nil, nil, 0.5, false)
--xp bar area
ui.addTextArea(3, "<p align='center'>Level 1 - 0/" .. calculateXP(2) .. "XP</p>", name, CONSTANTS.BAR_X, 370, CONSTANTS.BAR_WIDTH, 20, nil, nil, 0.5, true)
--shop button
ui.addTextArea(4, "<a href='event:shop'>Shop</a>", name, 740, 300, 36, 20, nil, nil, 1, true)
--school button
ui.addTextArea(5, "<a href='event:courses'>Learn</a>", name, 740, 270, 36, 20, nil, nil, 1, true)
--jobs button
ui.addTextArea(6, "<a href='event:jobs'>Jobs</a>", name, 740, 240, 36, 20, nil, nil, 1, true)
--Company button
ui.addTextArea(7, "<a href='event:company'>Company</a>", name, 740, 210, 36, 20, nil, nil, 1, true)
--Tips buton
ui.addTextArea(8, "<a href='event:tips'>Tips</a>", name, 740, 180, 36, 20, nil, nil, 1, true)
--Inventory button
ui.addTextArea(9, "<a href='event:inv'>Inventory</a>", name, 740, 150, 36, 20, nil, nil, 1, true)
end
--event handling
function eventNewPlayer(name)
players[name] = Player(name)
tempData[name] = {}
setUI(name)
tfm.exec.respawnPlayer(name)
end
--[[Function removed because it affects UX
function eventPlayerLeft(name)
for n, player in ipairs(players) do
if player:getName() == name then
table.remove(players, n)
end
end
end
]]
function eventPlayerDied(name)
tfm.exec.respawnPlayer(name)
end
--function for the money clicker c:
function eventTextAreaCallback(id, name, evt)
if evt == "work" then
players[name]:work()
elseif evt == "tips" then
displayTips(name)
elseif evt == "cmds" then
displayHelp(name, "cmds")
elseif evt == "game" then
displayHelp(name, "game")
elseif string.sub(evt, 1, 4) == "page" then
local args = split(evt, ":")
updatePages(name, args[2], tonumber(args[3]))
elseif evt == "shop" then
displayShop(name, 1)
elseif evt == "courses" then
if players[name]:getLearningCourse() == "" then
displayCourses(name)
else
players[name]:learn()
end
elseif evt == "jobs" then
displayJobs(name, 1)
elseif evt == "inv" then
displayInventory(name)
elseif evt == "close" then
ui.removeTextArea(id, name)
if id == 400 then
ui.removeTextArea(401, name)
elseif id == 800 then
ui.removeTextArea(801, name)
ui.removeTextArea(802, name)
ui.removeTextArea(803, name)
elseif id == 100 then
ui.removeTextArea(101, name)
ui.removeTextArea(102, name)
ui.removeTextArea(103, name)
elseif id == 300 then
ui.removeTextArea(301, name)
ui.removeTextArea(302, name)
ui.removeTextArea(303, name)
elseif id == 952 then
ui.removeTextArea(950, name)
ui.removeTextArea(951, name)
end
elseif evt == "company" then
displayCompanyDialog(name)
elseif evt == "createJob" then
if tempData[name].jobName == nil and tempData[name].jobSalary == nil and tempData[name].jobEnergy == nil and tempData[name].minLvl == nil then
displayJobWizard(name)
else
local tempCompany = tempData[name].jobCompany
table.insert(jobs, Job(tempData[name].jobName, tempData[name].jobSalary, tempData[name].jobEnergy / 100, tempData[name].minLvl, tempData[name].qualification, name, tempData[name].jobCompany))
tempData[name] = {jobCompany = tempCompany}
ui.removeTextArea(500, name)
end
elseif evt == "selectJobName" then
ui.addPopup(601, 2, "<p align='center'>Please choose a name", name, 300, 90, 200, true)
elseif evt == "selectJobSalary" then
ui.addPopup(602, 2, "<p align='center'>Please choose the salary (<i>Should be a number lesser that 1000000</i>)", name, 300, 90, 200, true)
elseif evt == "selectJobEnergy" then
ui.addPopup(603, 2, "<p align='center'>Please select the energy (<i>Should be a number in range 0 - 100</i>)", name, 300, 90, 200, true)
elseif evt == "chooseJobMinLvl" then
ui.addPopup(604, 2, "<p align='center'>Please select the minimum level (<i>Should be a number</i>", name, 300, 90, 200, true)
elseif evt == "chooseJobDegree" then
displayAllDegrees(name)
elseif evt:gmatch("%s+:%s+") then
local type = split(evt, ":")[1]
local val = split(evt, ":")[2]
if type == "buy" and players[name]:getMoney() - find(split(evt, ":")[3], healthPacks).price >= 0 then
local pack = find(split(evt, ":")[3], healthPacks)
players[name]:setMoney(-pack.price, true)
players[name]:grabItem(pack.name)
elseif type == "course" then
players[name]:setCourse(find(val, courses))
ui.removeTextArea(id, name)
elseif type == "job" then
players[name]:setJob(val)
eventTextAreaCallback(id, name, "close")
elseif type == "com" then
displayCompany(val, name)
elseif type == "degree" then
tempData[name].qualification = val
ui.removeTextArea(id, name)
displayJobWizard(name)
elseif type == "use" then
players[name]:useItem(val)
players[name]:useMed(find(val, healthPacks))
displayInventory(name)
end
end
end
function eventPopupAnswer(id, name, answer)
if id == 400 and answer == 'yes' then --for the popup creating a compnay
if players[name]:getMoney() < 5000 then
ui.addPopup(450, 0, "<p align='center'><b><font color='#CB546B'>Not enough money!", name, 300, 90, 200, true)
else
ui.addPopup(450, 2, "<p align='center'>Please choose a name<br>Price: $5000<br>Click submit to buy!</p>", name, 300, 90, 200, true)
end
elseif id == 450 and answer ~= '' then --for the popup to submit a name for the company
table.insert(companies, Company(answer, name))
players[name]:setMoney(-5000, true)
players[name]:addOwnedCompanies(answer)
displayCompany(answer, name)
elseif id == 601 and answer ~= '' then --for the popup to submit the name for a new job
tempData[name].jobName = answer
displayJobWizard(name)
elseif id == 602 and tonumber(answer) and tonumber(answer) < 1000000 then --for the popup to choose the salary for a new job
tempData[name].jobSalary = tonumber(answer)
displayJobWizard(name)
elseif id == 603 and tonumber(answer) and tonumber(answer) > 0 and tonumber(answer) <= 100 then --for the popup to choose the energy for the job
tempData[name].jobEnergy = tonumber(answer)
displayJobWizard(name)
elseif id == 604 and tonumber(answer) then --for the popup to choose the minimum level for the job
tempData[name].minLvl = tonumber(answer)
displayJobWizard(name)
end
end
function eventChatCommand(name, msg)
if string.sub(msg, 1, 7) == "company" then
displayCompany(string.sub(msg, 9), name)
elseif string.sub(msg, 1, 7) == "profile" then
displayProfile(string.sub(msg, 9), name)
elseif string.sub(msg, 1, 1) == "p" then
displayProfile(string.sub(msg, 3), name)
elseif msg == "help" then
displayHelp(name, "game")
end
end
function eventLoop(t,r)
for name, player in pairs(players) do
player:setHealth(player:getHealthRate(), true)
end
end
--event handling ends
--game logic
--creating tips
createTip("You Need $10 To Start A New Company!", 1)
createTip("You Gain Money From Your Workers!", 2)
createTip("Look At The Stats of The Company Before You Apply for it!", 3)
createTip("The Better The Job The Better The Income!", 4)
createTip("Buy Items From The Shop To Gain Health!", 5)
createTip("Some Jobs Needs A Specific Degree", 6)
createTip("To Level Up You Need To Work!", 7)
createTip("The Higher The Level The Higher The Health", 8)
createTip("The Stats Of A Company Can Be Seen By Anyone", 9)
createTip("While Working Your Health Bar Goes Down", 10)
createTip("Patience is The Key To This Game.", 11)
createTip("Your Stats Can Be Seen At The Top Of The Map!", 12)
createTip("You Can Buy Multiple Companies!", 13)
createTip("Once You Have A Job You Can't Quit!", 14)
createTip("Your Health will be Refreshed when You Level Up", 15)
createTip("Recruit More Players to Have More Salary!", 16)
createTip("Try your Best to Own a Company", 17)
createTip("Make Sure You Consider About Energy and Salary When Choosing a Job", 18)
createTip("The Red Bar Displays Your Health, While the Green Bar Displays your XP Percentage", 19)
createTip("Chat With Your Friends When You Are Out of Health", 20)
createTip("Use Your Brain and Take Correct Decisions!", 21)
createTip("If Your Job Seems to Take More Energy, Try to Choose Another!", 22)
createTip("Consider About Your Health When Working", 23)
createTip("When Taking A Course, You will Need to Pay Per Lesson Only. So Try to Enroll For the One With Higher Lessons", 24)
createTip("You Can Apply to Jobs According to Your Level and Degrees", 25)
createTip("The Better Stats You Have The Better The Job You Can Have!", 26)
createTip("Report Bugs To Developers", 27)
createTip("The Game is More Fun with More Players", 28)
createTip("Click Tips When You Need Help", 29)
createTip("The Health Refreshes Every Moment <3", 30)
players["shaman"] = Player("shaman")
table.insert(companies, Company("Atelie801", "shaman"))
--creating and storing HealthPack tables
table.insert(healthPacks, HealthPack("Cheese", 5, 0.01, true, "Just a cheese! to refresh yourself"))
table.insert(healthPacks, HealthPack("Candy", 10, 0.02, true, "Halloween Treat!"))
table.insert(healthPacks, HealthPack("Apple", 15, 0.025, true, "A nutritious diet from shaman"))
table.insert(healthPacks, HealthPack("Pastry", 30, 0.06, true, "King's favourite food"))
table.insert(healthPacks, HealthPack("Lasagne", 100, 0.1, true, "Shh!!! Beware of Garfield :D"))
table.insert(healthPacks, HealthPack("Cheese Pizza", 130, 0.15, true, "Treat from Italy - with lots of cheeese inside !!!"))
table.insert(healthPacks, HealthPack("Magician`s Portion", 250, 0.25, true, "Restores 1/4 th of your health."))
table.insert(healthPacks, HealthPack("Rotten Cheese", 300, 0.35, true, "Gives you the power of vampire <font size='5'>(disclaimer)This won't make you a vampire</font>"))
table.insert(healthPacks, HealthPack("Cheef`s food", 500, 0.5, true, "Restores half of your health (Powered by Shaman)"))
table.insert(healthPacks, HealthPack("Cheese Pizza - Large", 550, 0.55, true, "More Pizza Power!"))
table.insert(healthPacks, HealthPack("Vito`s Pizza", 700, 0.6, true, "World's best pizza!"))
table.insert(healthPacks, HealthPack("Vito`s Lasagne", 750, 0.8, true, "World's best lasagne!"))
table.insert(healthPacks, HealthPack("Ambulance!", 999, 1, false, "Restores your health back! (Powered by Shaman!)"))
--creating and storing Course tables
table.insert(courses, Course("School", 20, 2, 1, ""))
table.insert(courses, Course("Junior Sports Club", 10, 4, 2, ""))
table.insert(courses, Course("High School", 500, 20, 3, ""))
table.insert(courses, Course("Cheese mining", 1000, 30, 4, "admin"))
table.insert(courses, Course("Cheese trading", 2500, 30, 4, "bs"))
table.insert(courses, Course("Cheese developing", 2500, 50, 4, "it"))
table.insert(courses, Course("Law", 35000, 80, 5, "admin"))
table.insert(courses, Course("Cheese trading-II", 90000, 75, 5, "bs"))
table.insert(courses, Course("Fullstack cheese developing", 40000, 70, 5, "it"))
--creating and stofing Job tables
table.insert(jobs, Job("Cheese collector", 10, 0.05, 1, nil, "shaman", "Atelie801"))
table.insert(jobs, Job("Junior miner", 25, 0.1, 3, nil, "shaman", "Atelie801"))
table.insert(jobs, Job("Cheese producer", 50, 0.15, 7, nil, "shaman", "Atelie801"))
table.insert(jobs, Job("Cheese miner", 250, 0.2, 10, "Cheese mining", "shaman", "Atelie801"))
table.insert(jobs, Job("Cheese trader", 200, 0.2, 12, "Cheese trading", "shaman"))
table.insert(jobs, Job("Cheese developer", 300, 0.3, 12, "Cheese developing", "shaman", "Atelie801"))
table.insert(jobs, Job("Cheese wholesaler", 700, 0.2, 15, "Cheese trading-II", "shaman", "Atelie801"))
table.insert(jobs, Job("Fullstack cheeese developer", 9000, 0.4, 15, "Fullstack cheese developing", "shaman", "Atelie801"))
for name, player in pairs(tfm.get.room.playerList) do
players[name] = Player(name)
setUI(name)
tempData[name] = {}
end
for id, cmd in next, {"company", "p", "profile", "help"} do
system.disableChatCommandDisplay(cmd, true)
end
|
local EdgeDropout, Parent = torch.class('nn.EdgeDropout', 'nn.Module')
function EdgeDropout:__init(p,v1,inplace,stochasticInference)
Parent.__init(self)
self.p = p or 0.5
self.train = true
self.inplace = inplace
self.stochastic_inference = stochasticInference or false
-- version 2 scales output during training instead of evaluation
self.v2 = not v1
self.output = {}
if self.p >= 1 or self.p < 0 then
error('<EdgeDropout> illegal percentage, must be 0 <= p < 1')
end
self.noise = torch.Tensor()
end
function EdgeDropout:updateOutput(input)
local A = input[1]
local x = input[2]
if self.inplace then
self.output:set(input)
else
self.output[1] = torch.Tensor():typeAs(A):resizeAs(A):copy(A)
self.output[2] = x
end
if self.p > 0 then
if self.train or self.stochastic_inference then
self.noise:resizeAs(A)
self.noise:bernoulli(1-self.p)
if self.v2 then
self.noise:div(1-self.p)
end
self.output[1]:cmul(self.noise)
elseif not self.v2 then
self.output[1]:mul(1-self.p)
end
end
return self.output
end
function EdgeDropout:updateGradInput(input, gradOutput)
self.gradInput = gradOutput
return self.gradInput
end
function EdgeDropout:setp(p)
self.p = p
end
function EdgeDropout:__tostring__()
return string.format('%s(%f)', torch.type(self), self.p)
end
function EdgeDropout:clearState()
if self.noise then
self.noise:set()
end
return Parent.clearState(self)
end
|
CustomizableWeaponry:addFireSound("K82.FIRE", {"Weapons/K82A3/M82-1.wav","Weapons/K82A3/M82-2.wav","Weapons/K82A3/M82-3.wav",}, 1, 125, CHAN_STATIC)
CustomizableWeaponry:addReloadSound("K82.BOLTB", "Weapons/K82A3/boltb.wav")
CustomizableWeaponry:addReloadSound("K82.CLIPOUT", "Weapons/K82A3/M82_clipout.wav")
CustomizableWeaponry:addReloadSound("K82.CLIPIN", "Weapons/K82A3/M82_clipin.wav")
CustomizableWeaponry:addReloadSound("K82.BOLTF", "Weapons/K82A3/boltf.wav")
CustomizableWeaponry:addReloadSound("K82.DRAW", "Weapons/K82A3/draw.wav")
|
-- string.pack
do
local s = "a"
local s1000 = ("a"):rep(1000)
-- string.pack uses memory to store its output
local ctx = runtime.callcontext({kill={memory=4000}}, string.pack, "ssss", s1000, s, s, s)
print(ctx)
--> =done
print(runtime.callcontext({kill={memory=4000}}, string.pack, "ssss", s1000, s1000, s1000, s1000))
--> =killed
-- string.pack uses cpu to produce its output
ctx = runtime.callcontext({kill={cpu=400}}, string.pack, "ssss", s1000, s, s, s)
print(ctx)
--> =done
print(runtime.callcontext({kill={cpu=400}}, string.pack, "ssss", s1000, s1000, s1000, s1000))
--> =killed
end
-- string.unpack
do
local fmt = "i"
local packed = string.pack(fmt, 100)
print(string.unpack(fmt:rep(5), packed:rep(5)))
--> ~100 100 100 100 100 .*
-- string.unpack uses memory to produce its output
local ctx = runtime.callcontext({kill={memory=1000}}, string.unpack, fmt:rep(20), packed:rep(20))
print(ctx)
--> =done
print(runtime.callcontext({kill={memory=1000}}, string.unpack, fmt:rep(100), packed:rep(100)))
--> =killed
-- string.unpack uses cpu to produce its output
local ctx = runtime.callcontext({kill={cpu=100}}, string.unpack, fmt:rep(50), packed:rep(50))
print(ctx)
--> =done
print(runtime.callcontext({kill={cpu=100}}, string.unpack, fmt:rep(500), packed:rep(500)))
--> =killed
local fmt = "s"
local packed10 = string.pack(fmt, ("a"):rep(10))
local packed1000 = string.pack(fmt, ("a"):rep(1000))
-- big strings need lots of memory
local ctx = runtime.callcontext({kill={memory=2000}}, string.unpack, fmt:rep(20), packed10:rep(20))
print(ctx)
--> =done
print(runtime.callcontext({kill={memory=2000}}, string.unpack, fmt:rep(20), packed1000:rep(20)))
--> =killed
end |
-----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Imperial Whitegate
-- pos: 152, -2, 0, 50
-----------------------------------
require("scripts/globals/missions")
require("scripts/globals/status")
require("scripts/globals/titles")
require("scripts/globals/besieged")
require("scripts/globals/npc_util")
require("scripts/zones/Aht_Urhgan_Whitegate/Shared")
local ID = require("scripts/zones/Aht_Urhgan_Whitegate/IDs")
-----------------------------------
function onTrade(player, npc, trade)
end
function onTrigger(player, npc)
if player:getEquipID(tpz.slot.MAIN) == 0 and player:getEquipID(tpz.slot.SUB) == 0 then
if player:getCurrentMission(TOAU) == tpz.mission.id.toau.GUESTS_OF_THE_EMPIRE and player:getCharVar("AhtUrganStatus") == 1 and
doRoyalPalaceArmorCheck(player) == true then
player:startEvent(3078, 0, 1, 0, 0, 0, 0, 0, 1, 0)
elseif player:getCurrentMission(TOAU) == tpz.mission.id.toau.SEAL_OF_THE_SERPENT then
player:startEvent(3111)
elseif player:getCurrentMission(TOAU) == tpz.mission.id.toau.IMPERIAL_CORONATION and
doRoyalPalaceArmorCheck(player) == true then
player:startEvent(3140, tpz.besieged.getMercenaryRank(player), player:getTitle(), 0, 0, 0, 0, 0, 0, 0)
elseif player:getCurrentMission(TOAU) >= tpz.mission.id.toau.IMPERIAL_CORONATION and
doRoyalPalaceArmorCheck(player) == true then
local ring = player:getCharVar("TOAU_RINGTIME")
local standard = player:hasItem(129)
local ringParam = 0
if ring == 0 then
ringParam = 1
end
local standardParam = 0
if standard == false then
standardParam = 1
end
if ringParam > 0 or standardParam > 0 then
player:startEvent(3155, standardParam, ringParam, 0, 0, 0, 0, 0, 0, 0)
end
end
end
end
function onEventUpdate(player, csid, option)
if csid == 3140 or csid == 3155 then
if option == 1 and npcUtil.giveItem(player, 15807) then
player:setCharVar("TOAU_RINGTIME", os.time())
player:setCharVar("TOAU_RINGRECV", 1)
elseif option == 2 and npcUtil.giveItem(player, 15808) then
player:setCharVar("TOAU_RINGTIME", os.time())
player:setCharVar("TOAU_RINGRECV", 1)
elseif option == 3 and npcUtil.giveItem(player, 15809) then
player:setCharVar("TOAU_RINGTIME", os.time())
player:setCharVar("TOAU_RINGRECV", 1)
elseif option == 4 then
npcUtil.giveItem(player, 129)
elseif option == 99 then
player:updateEvent(15807, 15808, 15809)
end
end
end
function onEventFinish(player, csid, option)
if csid == 3078 and npcUtil.giveItem(player, 2186) then
player:completeMission(TOAU, tpz.mission.id.toau.GUESTS_OF_THE_EMPIRE)
player:setCharVar("AhtUrganStatus", 0)
player:addTitle(tpz.title.OVJANGS_ERRAND_RUNNER)
player:needToZone(true)
player:setCharVar("TOAUM18_STARTDAY", VanadielDayOfTheYear())
player:addMission(TOAU, tpz.mission.id.toau.PASSING_GLORY)
elseif csid == 3111 then
player:completeMission(TOAU, tpz.mission.id.toau.SEAL_OF_THE_SERPENT)
player:addMission(TOAU, tpz.mission.id.toau.MISPLACED_NOBILITY)
elseif csid == 3140 and player:getCharVar("TOAU_RINGRECV") == 1 then
player:completeMission(TOAU, tpz.mission.id.toau.IMPERIAL_CORONATION)
player:addMission(TOAU, tpz.mission.id.toau.THE_EMPRESS_CROWNED)
player:setCharVar("TOAU_RINGRECV", 0)
elseif csid == 3155 and option == 6 then
npcUtil.giveItem(player, 129)
end
end
|
local function rvec(vec)
vec.x = math.Round(vec.x)
vec.y = math.Round(vec.y)
vec.z = math.Round(vec.z)
return vec
end
function EFFECT:Init(data)
self.StartPacket = data:GetStart()
self.Attachment = data:GetAttachment()
local AddVel = vector_origin
if LocalPlayer and IsValid(LocalPlayer()) then
AddVel = LocalPlayer():GetVelocity()
end
if game.SinglePlayer() then
AddVel = Entity(1):GetVelocity()
end
self.Position = data:GetOrigin()
self.Forward = data:GetNormal()
self.Angle = self.Forward:Angle()
self.Right = self.Angle:Right()
local wepent = Entity(math.Round(self.StartPacket.z))
local ownerent = player.GetByID(math.Round(self.StartPacket.x))
local serverside = false
if math.Round(self.StartPacket.y) == 1 then
serverside = true
end
if IsValid(wepent) and (wepent.IsFirstPerson and not wepent:IsFirstPerson()) or serverside then
data:SetEntity(wepent)
self.Position = blankvec
end
--[[
self.Forward = ownerent:EyeAngles():Forward()
self.Angle = self.Forward:Angle()
self.Right = self.Angle:Right()
]]
--
if serverside and IsValid(ownerent) then
if LocalPlayer() == ownerent then return end
AddVel = ownerent:GetVelocity()
end
if (not self.Position) or (rvec(self.Position) == blankvec) then
self.WeaponEnt = data:GetEntity()
self.Attachment = data:GetAttachment()
if self.WeaponEnt and IsValid(self.WeaponEnt) then
local rpos = self.WeaponEnt:GetAttachment(self.Attachment)
if rpos and rpos.Pos then
self.Position = rpos.Pos
if data:GetNormal() == vector_origin then
self.Forward = rpos.Ang:Up()
self.Angle = self.Forward:Angle()
self.Right = self.Angle:Right()
end
end
end
end
self.vOffset = self.Position
dir = self.Forward
AddVel = AddVel * 0.05
local dot = dir:GetNormalized():Dot(EyeAngles():Forward())
local dotang = math.deg(math.acos(math.abs(dot)))
local halofac = math.Clamp(1 - (dotang / 90), 0, 1)
if CLIENT and not IsValid(ownerent) then
ownerent = LocalPlayer()
end
local dlight = DynamicLight(ownerent:EntIndex())
if (dlight) then
dlight.pos = self.vOffset - ownerent:EyeAngles():Right() * 5 + 1.05 * ownerent:GetVelocity() * FrameTime()
dlight.r = 255
dlight.g = 255
dlight.b = 255
dlight.brightness = 5
dlight.Decay = 1750
dlight.Size = 96
dlight.DieTime = CurTime() + 0.3
end
local emitter = ParticleEmitter(self.vOffset)
for i = 1, 2 do
local particle = emitter:Add("effects/splash" .. tostring(math.random(1, 2)), self.vOffset)
if (particle) then
particle:SetVelocity(dir * 4 + 1.05 * AddVel)
particle:SetLifeTime(0)
particle:SetDieTime(0.15)
particle:SetStartAlpha(math.Rand(32, 64))
particle:SetEndAlpha(0)
--particle:SetStartSize( 7.5 * (halofac*0.8+0.2), 0, 1)
--particle:SetEndSize( 0 )
particle:SetStartSize(3 * (halofac * 0.8 + 0.2), 0, 1)
particle:SetEndSize(8 * (halofac * 0.8 + 0.2))
particle:SetRoll(math.rad(math.Rand(0, 360)))
particle:SetRollDelta(math.rad(math.Rand(-40, 40)))
particle:SetColor(255, 255, 255)
particle:SetLighting(false)
particle.FollowEnt = self.WeaponEnt
particle.Att = self.Attachment
TFARegPartThink(particle, TFAMuzzlePartFunc)
end
end
for i = 0, 6 do
local particle = emitter:Add("particles/smokey", self.vOffset + dir * math.Rand(6, 10))
if (particle) then
particle:SetVelocity(VectorRand() * 10 + dir * math.Rand(15, 20) + 1.05 * AddVel)
particle:SetLifeTime(0)
particle:SetDieTime(math.Rand(0.6, 0.7))
particle:SetStartAlpha(math.Rand(6, 10))
particle:SetEndAlpha(0)
particle:SetStartSize(math.Rand(5, 7))
particle:SetEndSize(math.Rand(12, 14))
particle:SetRoll(math.rad(math.Rand(0, 360)))
particle:SetRollDelta(math.Rand(-0.8, 0.8))
particle:SetLighting(true)
particle:SetAirResistance(10)
particle:SetGravity(Vector(0, 0, 60))
particle:SetColor(255, 255, 255)
end
end
if TFA.GetGasEnabled() then
for i = 0, 2 do
local particle = emitter:Add("sprites/heatwave", self.vOffset + (dir * i))
if (particle) then
particle:SetVelocity((dir * 25 * i) + 1.05 * AddVel)
particle:SetLifeTime(0)
particle:SetDieTime(math.Rand(0.05, 0.15))
particle:SetStartAlpha(math.Rand(200, 225))
particle:SetEndAlpha(0)
particle:SetStartSize(math.Rand(3, 5))
particle:SetEndSize(math.Rand(8, 10))
particle:SetRoll(math.Rand(0, 360))
particle:SetRollDelta(math.Rand(-2, 2))
particle:SetAirResistance(5)
particle:SetGravity(Vector(0, 0, 40))
particle:SetColor(255, 255, 255)
end
end
end
emitter:Finish()
end
function EFFECT:Think()
return false
end
function EFFECT:Render()
end
|
require "libstudent"
print( "test lua access C++ class" )
local function main()
--Student是个table, 调用create方法
local s = Student:create() --lua_gettop()=2 1:table, 2:xx
s:setAge(100)
s:print()
s:setName("BeiJing")
s:setAge(1234)
s:print()
end
main() |
local m = {} -- module
local fileutil = require "fileutil"
local SVN = "svn "
local svn = SVN .. "--username %s --password %s --no-auth-cache --non-interactive "
--
-- sourceCtxPath
--
local function sourceCtxPath ()
local property = require "property"
return property.sourceCtxPath or ""
end
--
-- redirectErrorToOutputStream
--
local function redirectErrorToOutputStream ()
local property = require "property"
return property.redirectErrorToOutputStream or ""
end
--
-- logCommand
--
local function logCommand (command)
local property = require "property"
if property.debugRepo then
ngx.log(ngx.ERR, command) -- DEBUG
end
end
--
-- fileHistory
--
local function fileHistory (username, password, fileName)
username = fileutil.quoteCommandlineArgument(username)
password = fileutil.quoteCommandlineArgument(password)
fileName = fileutil.quoteCommandlineArgument(fileName)
return string.format(svn .. [[log -v %s]] .. redirectErrorToOutputStream(), username, password, fileName)
end
function m.fileHistory (username, password, fileName)
fileutil.noBackDirectory(fileName)
local command = fileHistory(username, password, sourceCtxPath() .. fileName)
logCommand(command)
local revisions = {}
local f = assert(io.popen(command, "r"))
for line in f:lines() do
local revision = line:match('^r(%d+)%s+')
if revision then
revisions[#revisions + 1] = {
info = line,
revision = revision
}
elseif #revisions > 0 and not line:find("----------", 1, true) and line ~= "" then
revisions[#revisions].info = revisions[#revisions].info .. [[<br>]] .. line
end
end
f:close()
table.insert(revisions, 1, {
info = "rHEAD | base copy",
revision = "HEAD"
})
table.insert(revisions, 1, {
info = "rLOCAL | working copy",
revision = "LOCAL"
})
return revisions
end
--
-- status
--
local function status (username, password, directoryName)
username = fileutil.quoteCommandlineArgument(username)
password = fileutil.quoteCommandlineArgument(password)
directoryName = fileutil.quoteCommandlineArgument(directoryName)
return string.format(svn .. [[status -u %s]] .. redirectErrorToOutputStream(), username, password, directoryName)
end
function m.status (username, password, directoryName)
fileutil.noBackDirectory(directoryName)
local command = status(username, password, sourceCtxPath() .. directoryName)
logCommand(command)
local statuses = {}
local f = assert(io.popen(command, "r"))
for line in f:lines() do
local fileName = line:match('(%a?:?[/\\].*)')
if fileName then
local newFileName
local i, j = fileName:find(sourceCtxPath(), 1, true)
if i and (i <= j) then
newFileName = fileName:sub(j + 1, #fileName)
else
newFileName = fileName
end
local revertRevisions = false
local newLine
local i = line:find(fileName, 1, true)
if i then
local fileStatus = line:sub(1, i - 1)
newLine = fileStatus .. newFileName
if fileStatus:find("*", 1, true) then revertRevisions = true end
else
newLine = line
end
statuses[#statuses + 1] = {
info = newLine,
oldRevision = "HEAD",
newRevision = "LOCAL",
fileName = newFileName,
revertRevisions = revertRevisions
}
end
end
f:close()
return statuses
end
--
-- logHistory
--
local function logHistory (username, password, directoryName, limit)
username = fileutil.quoteCommandlineArgument(username)
password = fileutil.quoteCommandlineArgument(password)
directoryName = fileutil.quoteCommandlineArgument(directoryName)
fileutil.noCommandlineSpecialCharacters(limit)
if limit then
return string.format(svn .. [[log -v -l %s %s]] .. redirectErrorToOutputStream(),
username, password, limit, directoryName)
else
return string.format(svn .. [[log -v %s]] .. redirectErrorToOutputStream(),
username, password, directoryName)
end
end
function m.logHistory (username, password, directoryName, limit)
fileutil.noBackDirectory(directoryName)
local command = logHistory(username, password, sourceCtxPath() .. directoryName, limit)
logCommand(command)
local f = assert(io.popen(command, "r"))
local content = f:read("*all")
f:close()
return content
end
--
-- commitHistory
--
local function commitHistory (username, password, directoryName, newRevision, oldRevision)
username = fileutil.quoteCommandlineArgument(username)
password = fileutil.quoteCommandlineArgument(password)
directoryName = fileutil.quoteCommandlineArgument(directoryName)
fileutil.noCommandlineSpecialCharacters(newRevision)
fileutil.noCommandlineSpecialCharacters(oldRevision)
return string.format(svn .. [[diff -r %s:%s %s]] .. redirectErrorToOutputStream(),
username, password, oldRevision, newRevision, directoryName)
end
function m.commitHistory (username, password, directoryName, newRevision, oldRevision)
fileutil.noBackDirectory(directoryName)
local command = commitHistory(username, password, sourceCtxPath() .. directoryName, newRevision, oldRevision)
logCommand(command)
local f = assert(io.popen(command, "r"))
local content = f:read("*all")
f:close()
return content, "Index: "
end
--
-- fileRevisionContent
--
local function fileRevisionContent (username, password, revision, fileName)
username = fileutil.quoteCommandlineArgument(username)
password = fileutil.quoteCommandlineArgument(password)
fileName = fileutil.quoteCommandlineArgument(fileName)
fileutil.noCommandlineSpecialCharacters(revision)
return string.format(svn .. [[cat -r %s %s]] .. redirectErrorToOutputStream(), username, password, revision, fileName)
end
function m.fileRevisionContent (username, password, revision, fileName)
fileutil.noBackDirectory(fileName)
local command = fileRevisionContent(username, password, revision, sourceCtxPath() .. fileName)
logCommand(command)
local f = assert(io.popen(command, "r"))
local content = f:read("*all")
f:close()
return content
end
--
-- fileDiff
--
local function fileDiff (username, password, oldRevision, newRevision, fileName)
username = fileutil.quoteCommandlineArgument(username)
password = fileutil.quoteCommandlineArgument(password)
fileName = fileutil.quoteCommandlineArgument(fileName)
fileutil.noCommandlineSpecialCharacters(oldRevision)
fileutil.noCommandlineSpecialCharacters(newRevision)
local command = string.format(svn .. [[diff -r %s:%s %s]] .. redirectErrorToOutputStream(),
username, password, oldRevision, newRevision, fileName)
if newRevision == "LOCAL" then
command = string.format(svn .. [[diff -r %s %s]] .. redirectErrorToOutputStream(),
username, password, oldRevision, fileName)
end
return command
end
function m.fileDiff (username, password, oldRevision, newRevision, fileName)
fileutil.noBackDirectory(fileName)
local command = fileDiff(username, password, oldRevision, newRevision, sourceCtxPath() .. fileName)
logCommand(command)
local f = assert(io.popen(command, "r"))
local content = f:read("*all")
f:close()
return content
end
--
-- add
--
local function add (username, password, path)
username = fileutil.quoteCommandlineArgument(username)
password = fileutil.quoteCommandlineArgument(password)
path = fileutil.quoteCommandlineArgument(path)
return string.format(SVN .. [[add --force %s]] .. redirectErrorToOutputStream(), path)
end
function m.add (username, password, path)
fileutil.noBackDirectory(path)
local command = add(username, password, sourceCtxPath() .. path)
logCommand(command)
local f = assert(io.popen(command, "r"))
local content = f:read("*all")
f:close()
return content
end
--
-- delete
--
local function delete (username, password, path)
username = fileutil.quoteCommandlineArgument(username)
password = fileutil.quoteCommandlineArgument(password)
path = fileutil.quoteCommandlineArgument(path)
return string.format(svn .. [[delete --force %s]] .. redirectErrorToOutputStream(), username, password, path)
end
function m.delete (username, password, path)
fileutil.noBackDirectory(path)
local command = delete(username, password, sourceCtxPath() .. path)
logCommand(command)
local f = assert(io.popen(command, "r"))
local content = f:read("*all")
f:close()
return content
end
--
-- move
--
local function move (username, password, oldName, newName)
username = fileutil.quoteCommandlineArgument(username)
password = fileutil.quoteCommandlineArgument(password)
oldName = fileutil.quoteCommandlineArgument(oldName)
newName = fileutil.quoteCommandlineArgument(newName)
return string.format(svn .. [[move --force %s %s]] .. redirectErrorToOutputStream(), username, password, oldName, newName)
end
function m.move (username, password, oldName, newName)
fileutil.noBackDirectory(oldName)
fileutil.countBackDirectories(newName) -- only here is allowed to have back directory
local command = move(username, password, sourceCtxPath() .. oldName, sourceCtxPath() .. newName)
logCommand(command)
local f = assert(io.popen(command, "r"))
local content = f:read("*all")
f:close()
return content
end
--
-- commit
--
local function commit (username, password, message, list)
username = fileutil.quoteCommandlineArgument(username)
password = fileutil.quoteCommandlineArgument(password)
message = fileutil.quoteCommandlineArgument(message)
local paths = ""
for i=1, #list do
fileutil.noBackDirectory(list[i])
local path = fileutil.quoteCommandlineArgument(sourceCtxPath() .. list[i])
paths = paths .. " " .. path
end
return string.format(svn .. [[commit -m %s %s]] .. redirectErrorToOutputStream(),
username, password, message, paths)
end
function m.commit (username, password, message, list)
local command = commit(username, password, message, list)
logCommand(command)
local f = assert(io.popen(command, "r"))
local content = f:read("*all")
f:close()
return content
end
--
-- update
--
local function update (username, password, revision, path)
username = fileutil.quoteCommandlineArgument(username)
password = fileutil.quoteCommandlineArgument(password)
path = fileutil.quoteCommandlineArgument(path)
fileutil.noCommandlineSpecialCharacters(revision)
if revision then
return string.format(svn .. [[update -r%s %s]] .. redirectErrorToOutputStream(),
username, password, revision, path)
else
return string.format(svn .. [[update %s]] .. redirectErrorToOutputStream(),
username, password, path)
end
end
function m.update (username, password, revision, path)
fileutil.noBackDirectory(path)
local command = update(username, password, revision, sourceCtxPath() .. path)
logCommand(command)
local f = assert(io.popen(command, "r"))
local content = f:read("*all")
f:close()
return content
end
--
-- revert
--
local function revert (username, password, path, recursively)
username = fileutil.quoteCommandlineArgument(username)
password = fileutil.quoteCommandlineArgument(password)
path = fileutil.quoteCommandlineArgument(path)
fileutil.noCommandlineSpecialCharacters(recursively)
if recursively then
return string.format(SVN .. [[revert -R %s]] .. redirectErrorToOutputStream(), path)
else
return string.format(SVN .. [[revert %s]] .. redirectErrorToOutputStream(), path)
end
end
function m.revert (username, password, path, recursively)
fileutil.noBackDirectory(path)
local command = revert(username, password, sourceCtxPath() .. path, recursively)
logCommand(command)
local f = assert(io.popen(command, "r"))
local content = f:read("*all")
f:close()
return content
end
--
-- merge
--
local function merge (username, password, fromRevision, toRevision, path)
username = fileutil.quoteCommandlineArgument(username)
password = fileutil.quoteCommandlineArgument(password)
path = fileutil.quoteCommandlineArgument(path)
fileutil.noCommandlineSpecialCharacters(fromRevision)
fileutil.noCommandlineSpecialCharacters(toRevision)
return string.format([[cd %s && ]] .. svn .. [[merge -r %s:%s .]] .. redirectErrorToOutputStream(),
path, username, password, fromRevision, toRevision)
end
function m.merge (username, password, fromRevision, toRevision, path)
fileutil.noBackDirectory(path)
local command = merge(username, password, fromRevision, toRevision, sourceCtxPath() .. path)
logCommand(command)
local f = assert(io.popen(command, "r"))
local content = f:read("*all")
f:close()
return content
end
--
-- refresh
--
local function refresh (username, password, path)
username = fileutil.quoteCommandlineArgument(username)
password = fileutil.quoteCommandlineArgument(password)
path = fileutil.quoteCommandlineArgument(path)
return string.format(SVN .. [[cleanup %s]] .. redirectErrorToOutputStream(), path)
end
function m.refresh (username, password, path)
fileutil.noBackDirectory(path)
local command = refresh(username, password, sourceCtxPath() .. path)
logCommand(command)
local f = assert(io.popen(command, "r"))
local content = f:read("*all")
f:close()
return content
end
return m -- return module |
local tab = {}
local idleTime = {}
local paymentTimer
local TIMER_HOUR = 3600000
local CHECK_TIMER = 5000
local jobToRanksCount = {
[7] = {"Rescuer Man", "Pilot", "Farmer", "Trucker", "Lumberjack", "Trash Collector", "Diver", "Firefighter"},
[8] = {"Fisherman"},
[10] = {"Iron Miner"},
[11] = {"Taxi Driver"}
}
local paymentTab =
{
[6] = {[1] = 2, [2] = 5, [3] = 10, [4] = 25, [5] = 40, [6] = 60},
[7] = {[1] = 2, [2] = 3.5, [3] = 5, [4] = 12, [5] = 25, [6] = 35, [7] = 85},
[8] = {[1] = 1.5, [2] = 3, [3] = 5, [4] = 10, [5] = 25, [6] = 35, [7] = 80, [8] = 100},
[9] = {[1] = 1.5, [2] = 3, [3] = 5, [4] = 10, [5] = 25, [6] = 35, [7] = 80, [8] = 90, [9] = 100},
[11] = {[1] = 1.5, [2] = 3, [3] = 5, [4] = 10, [5] = 25, [6] = 35, [7] = 80, [8] = 90, [9] = 100, [10] = 120, [11] = 150}
}
function format( n )
local left,num,right = string.match(n,'^([^%d]*%d)(%d*)(.-)$')
return left..(num:reverse():gsub('(%d%d%d)','%1,'):reverse())..right
end
function getJobRanksCount(job)
for k, v in pairs(jobToRanksCount) do
for key, value in pairs(v) do
if (job == value) then
return k
end
end
end
return false
end
function getRankPayment(plr)
local occupation = getElementData(plr, "Occupation")
if (getJobRanksCount(occupation)) then
local rank, number = exports.CSGranks:getRank(plr, occupation)
local ranksCount = getJobRanksCount(occupation)
local money = paymentTab[ranksCount][number]
return (money*1000)
else
return 5000
end
end
function isPartOfPayment(plr)
for k, v in pairs(getElementsByType("player")) do
if (k == plr) then
return true
end
end
return false
end
function initializeValues()
tab = {}
idleTime = {}
for k, v in ipairs(getElementsByType("player")) do
if (getTeamName(getPlayerTeam(v)) == "Civilian Workers") then
table.insert(tab, v)
idleTime[v] = 0
local x1, y1, z1 = getElementPosition(v)
end
end
setTimer(function()
for k, v in ipairs(tab) do
if (getPlayerIdleTime(v) > 1250) then
idleTime[v] = idleTime[v] + CHECK_TIMER
end
end
end, CHECK_TIMER, TIMER_HOUR / CHECK_TIMER)
end
function getPlayerHourlyIdleTime(plr)
return idleTime[plr]
end
function getHourlyPaymentDetail(plr, cmd)
if (isTimer(paymentTimer)) then
if (isPartOfPayment(plr)) then
outputChatBox("Currently you've been idle for "..math.floor((idleTime[plr] / 1000) / 60).." minute(s).", plr, 0, 255, 0)
else
outputChatBox("You're not part of the next payment.", plr, 255, 0, 0)
end
local remaining, executesRemaining, totalExecutes = getTimerDetails(paymentTimer)
outputChatBox(math.ceil((remaining / 1000) / 60).." minute(s) left for the next hourly civilian payment!", plr, 0, 255, 0)
end
end
addCommandHandler("civpayment", getHourlyPaymentDetail)
function startPaymentTimer()
initializeValues()
paymentTimer = setTimer(function()
for k, v in ipairs(tab) do
if (idleTime[v] < 600000) then
local money = getRankPayment(v)
givePlayerMoney(v, money)
outputChatBox("You have been given $"..format(money),v, 0, 255, 0)
end
end
initializeValues()
end, TIMER_HOUR, 0)
end
addEvent("onPlayerJobChange", true)
addEventHandler("onPlayerJobChange", root,
function(newOcc, oldOcc, teamName)
for k, v in ipairs(tab) do
if (v == source) and (teamName ~= "Civilian Workers") then
table.remove(tab, k)
idleTime[source] = nil
end
end
end
)
addEventHandler("onPlayerQuit", root,
function()
for k, v in ipairs(tab) do
if (v == source) then
table.remove(tab, k)
idleTime[source] = nil
end
end
end
)
addEventHandler("onResourceStart", resourceRoot,
function()
outputDebugString("Hourly civil payment is online")
startPaymentTimer()
end
)
|
-- Copyright (C) 2018 The Dota IMBA Development Team
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Editors:
--
-- Author: Shush
-- Date: 28/07/2016
-- Editor: AltiV
-- Date: 22/03/2020, and times before
item_imba_skull_basher = item_imba_skull_basher or class({})
LinkLuaModifier("modifier_imba_skull_basher", "components/items/item_skull_basher", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_imba_skull_basher_bash", "components/items/item_skull_basher", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_imba_skull_basher_skull_crash", "components/items/item_skull_basher", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_imba_skull_basher_skull_break", "components/items/item_skull_basher", LUA_MODIFIER_MOTION_NONE)
function item_imba_skull_basher:GetIntrinsicModifierName()
return "modifier_imba_skull_basher"
end
-- Modifier (stackable, grants stats bonuses)
modifier_imba_skull_basher = modifier_imba_skull_basher or class({})
function modifier_imba_skull_basher:IsHidden() return true end
function modifier_imba_skull_basher:IsPurgable() return false end
function modifier_imba_skull_basher:RemoveOnDeath() return false end
function modifier_imba_skull_basher:GetAttributes() return MODIFIER_ATTRIBUTE_MULTIPLE end
function modifier_imba_skull_basher:DeclareFunctions()
return {
MODIFIER_PROPERTY_STATS_STRENGTH_BONUS,
MODIFIER_PROPERTY_PREATTACK_BONUS_DAMAGE,
MODIFIER_EVENT_ON_ATTACK,
MODIFIER_EVENT_ON_ATTACK_LANDED,
MODIFIER_PROPERTY_PROCATTACK_BONUS_DAMAGE_MAGICAL
}
end
function modifier_imba_skull_basher:GetModifierBonusStats_Strength()
if self:GetAbility() then
return self:GetAbility():GetSpecialValueFor("bonus_strength")
end
end
function modifier_imba_skull_basher:GetModifierPreAttack_BonusDamage()
if self:GetAbility() then
return self:GetAbility():GetSpecialValueFor("bonus_damage")
end
end
function modifier_imba_skull_basher:OnAttack(keys)
if self:GetAbility() and
keys.attacker == self:GetParent() and
keys.attacker:FindAllModifiersByName(self:GetName())[1] == self and
self:GetAbility():IsCooldownReady() and
not keys.attacker:IsIllusion() and
not keys.target:IsBuilding() and
not keys.target:IsOther() and
not keys.attacker:HasModifier("modifier_monkey_king_fur_army_soldier") and
not keys.attacker:HasModifier("modifier_monkey_king_fur_army_soldier_hidden") and
not keys.attacker:HasItemInInventory("item_imba_abyssal_blade") then
if self:GetParent():IsRangedAttacker() then
if RollPseudoRandom(self:GetAbility():GetSpecialValueFor("bash_chance_ranged"), self) then
self.bash_proc = true
end
else
if RollPseudoRandom(self:GetAbility():GetSpecialValueFor("bash_chance_melee"), self) then
self.bash_proc = true
end
end
end
end
function modifier_imba_skull_basher:OnAttackLanded(keys)
if self:GetAbility() and keys.attacker == self:GetParent() and self.bash_proc then
self.bash_proc = false
-- Make the ability go into cooldown
self:GetAbility():UseResources(false, false, true)
-- If the attacker is one of the forbidden heroes, do not proc the bash
if IMBA_DISABLED_SKULL_BASHER == nil or not IMBA_DISABLED_SKULL_BASHER[keys.attacker:GetUnitName()] then
keys.target:EmitSound("DOTA_Item.SkullBasher")
keys.target:AddNewModifier(self:GetCaster(), self:GetAbility(), "modifier_imba_skull_basher_bash", {duration = self:GetAbility():GetSpecialValueFor("stun_duration") * (1 - keys.target:GetStatusResistance())})
end
-- IMBAfication: Skull Crash
-- If the target is not skull crashed yet, CRUSH IT!
if not keys.target:HasModifier("modifier_imba_skull_basher_skull_crash") then
keys.target:AddNewModifier(self:GetCaster(), self:GetAbility(), "modifier_imba_skull_basher_skull_crash", {duration = self:GetAbility():GetSpecialValueFor("skull_break_duration") * (1 - keys.target:GetStatusResistance())})
else
-- Otherwise, it was ALREADY CRUSHED! BREAK IT!!!!!!!!!!!! BREAK IT!!!!!!!!!!!!!!!
-- Consume skull crash modifier
keys.target:RemoveModifierByName("modifier_imba_skull_basher_skull_crash")
-- Apply BREAK!
keys.target:AddNewModifier(self:GetCaster(), self:GetAbility(), "modifier_imba_skull_basher_skull_break", {duration = self:GetAbility():GetSpecialValueFor("actual_break_duration") * (1 - keys.target:GetStatusResistance())})
end
end
end
function modifier_imba_skull_basher:GetModifierProcAttack_BonusDamage_Magical()
if self:GetAbility() and self.bash_proc then
return self:GetAbility():GetSpecialValueFor("bash_damage")
end
end
-- Bash modifier
modifier_imba_skull_basher_bash = modifier_imba_skull_basher_bash or class({})
function modifier_imba_skull_basher_bash:IsHidden() return false end
function modifier_imba_skull_basher_bash:IsPurgeException() return true end
function modifier_imba_skull_basher_bash:IsStunDebuff() return true end
function modifier_imba_skull_basher_bash:CheckState()
return {[MODIFIER_STATE_STUNNED] = true}
end
function modifier_imba_skull_basher_bash:GetEffectName()
return "particles/generic_gameplay/generic_stunned.vpcf"
end
function modifier_imba_skull_basher_bash:GetEffectAttachType()
return PATTACH_OVERHEAD_FOLLOW
end
function modifier_imba_skull_basher_bash:DeclareFunctions()
return {MODIFIER_PROPERTY_OVERRIDE_ANIMATION}
end
function modifier_imba_skull_basher_bash:GetOverrideAnimation()
return ACT_DOTA_DISABLED
end
-- Modifier responsible for showing that the skull has been broken - Next attack will break it for real!
modifier_imba_skull_basher_skull_crash = modifier_imba_skull_basher_skull_crash or class({})
function modifier_imba_skull_basher_skull_crash:IsHidden() return false end
function modifier_imba_skull_basher_skull_crash:IsPurgable() return true end
function modifier_imba_skull_basher_skull_crash:IsDebuff() return true end
-- Modifier responsible for showing BROKEN SKULLS MUHAHHAHA TARGET IS BROKEN PITY IT!
modifier_imba_skull_basher_skull_break = modifier_imba_skull_basher_skull_break or class({})
function modifier_imba_skull_basher_skull_break:IsHidden() return false end
function modifier_imba_skull_basher_skull_break:IsPurgable() return true end
function modifier_imba_skull_basher_skull_break:IsDebuff() return true end
function modifier_imba_skull_basher_skull_break:CheckState()
return {[MODIFIER_STATE_PASSIVES_DISABLED] = true}
end
function modifier_imba_skull_basher_skull_break:OnCreated()
if IsServer() then
if not self:GetAbility() then self:Destroy() end
end
if IsServer() then
local caster = self:GetCaster()
local ability = self:GetAbility()
local parent = self:GetParent()
local particle_break = "particles/item/skull_basher/skull_basher.vpcf"
local particle_break_fx = ParticleManager:CreateParticle(particle_break, PATTACH_ABSORIGIN_FOLLOW, parent)
ParticleManager:SetParticleControl(particle_break_fx, 0, parent:GetAbsOrigin())
ParticleManager:ReleaseParticleIndex(particle_break_fx)
end
end
|
local process = require('process')
local assert = require('assert')
if (process.getgid) then
console.log('gid', process.getgid())
console.log('uid', process.getuid())
end
local tap = require('util/tap')
local test = tap.test
test("test hrtime", function()
assert.equal(type(process.hrtime()), 'number')
assert(process.hrtime())
end)
test("test rootPath", function()
assert.equal(type(process.rootPath), 'string')
assert(process.rootPath)
console.log(process.rootPath)
console.log(process.now(), process.uptime())
end)
test("test argv", function()
assert.equal(type(process.argv), 'table')
assert(process.argv)
end)
test("test arch", function()
assert.equal(type(process.arch()), 'string')
assert(process.arch())
end)
test("test platform", function()
assert.equal(type(process.platform()), 'string')
assert(process.platform())
end)
test("test cwd", function()
assert.equal(type(process.cwd()), 'string')
assert(process.cwd())
end)
test("test execPath", function()
assert.equal(type(process.execPath), 'string')
assert(process.execPath)
end)
test("test pid", function()
assert.equal(type(process.pid), 'number')
assert(process.pid)
end)
test("test version", function()
assert.equal(type(process.version), 'string')
assert(process.version)
end)
test("test versions", function()
assert.equal(type(process.versions), 'table')
assert(process.versions.lua)
assert(process.versions.uv)
end)
test("test title", function()
console.log(process.title)
console.log(process.isTTY)
console.log(process.memoryUsage())
end)
test("test stdin", function()
assert.equal(type(process.stdin), 'table')
end)
test("test stdout", function()
assert.equal(type(process.stdout), 'table')
process.stdout:write("test stdout\r\n")
end)
test("test stderr", function()
assert.equal(type(process.stderr), 'table')
process.stderr:write("test stderr\r\n")
end)
test('signal usr1,usr2,hup', function(expect)
local onHUP, onUSR1, onUSR2
if os.platform() == 'win32' then
assert(true)
return
end
function onHUP() print('sighup'); process:removeListener('sighup', onHUP) end
function onUSR1() print('sigusr1'); process:removeListener('sigusr1', onUSR1) end
function onUSR2() print('sigusr2'); process:removeListener('sigusr2', onUSR2) end
process:on('sighup', expect(onHUP))
process:on('sigusr1', expect(onUSR1))
process:on('sigusr2', expect(onUSR2))
process.kill(process.pid, 'sighup')
process.kill(process.pid, 'sigusr1')
process.kill(process.pid, 'sigusr2')
end)
tap.run()
|
------------------------------------------------------
-- Screen identifier
------------------------------------------------------
SCREEN_OPERATOR_IDENTIFIER = "operator"
------------------------------------------------------
-- Digital input states
------------------------------------------------------
SCREEN_OPERATOR_DI_SELECT_NEXT = 0
SCREEN_OPERATOR_DI_SELECT_PREV = 1
SCREEN_OPERATOR_DI_SELECTED = 2
SCREEN_OPERATOR_DI_NOISE_BACK= 3
SCREEN_OPERATOR_DI_EXIT_APPLICATION = 4
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.