Ir para conteúdo
  • Cadastre-se

Posts Recomendados

Se você já leu o manual de referência já deve ter visto uma função parecida com essa.

 

O que ela faz?

Ela printa uma tabela completa, por exemplo:

 

Executando ela em seu OT:

 

O chamado printTable{1,3,4,[5] = 5, [6] = 1} retorna  2gx1mih.png

Instalação

Crie printTable.lua em data/lib e cole:


function printTable(table, includeIndices,prnt) -- By Killua
    if includeIndices == nil then includeIndices = true end
    if prnt == nil then prnt = true end
    if type(table) ~= "table" then
        error("Argument must be a table")
        return
    end
    local str, c = "{", ""
    for v, b in pairs(table) do
        if type(b) == "table" then
            str = includeIndices and str..c.."["..v.."]".." = "..printTable(b,true,false) or str..c..printTable(b,false,false)
        else
            str = includeIndices and str..c.."["..v.."]".." = "..b or str..c..b
        end
        c = ", "
    end
    str = str.."}"
    if prnt then print(str) end
    return str
 end

Utilização

Basta chamar ela colocoando sua tabela como primeiro argumento, exemplo:

printTable({1,2,3,4})

O segundo parâmetro (includeIndices) define se os indices vão ou não ser mostrados no print. Como padrão, ele tem valor true. Por exemplo:

printTable({1,2,3,4}) ou printTable({1,2,3,4}, true)

Vai printar: {[1] = 1, [2] = 2, [3] = 3, [4] = 4}

 

E

printTable({1,2,3,4}, false)

Vai printar: {1, 2, 3 ,4}

 

 

Além de printar sua tabela, a função ainda retorna ela como string. Sendo assim, você pode usar essa string para oque precisar. Por exemplo:

doPlayerSendTextMessage(cid, 25, printTable{1,2,3,4})

Vai enviar para o player a mensagem: "{[1] = 1, [2] = 2, [3] = 3, [4] = 4}"

 

 

Obrigado, espero que sjea útil.

Editado por Killua (veja o histórico de edições)

 

 

 

 

 

v61snZO.png?129bcx1x.pngiVgTXVz.png?1

 

 

 

 

 

Link para o post
Compartilhar em outros sites
  • 2 weeks later...

Como posso usar de um modo mais prático? Dê um exemplo ... 

 

printTable(getThingFromPos(pos))

printTable(getTopCreature(pos))

printTable(item)

printTable(getThing(uid))

 

vai mostrar como são essas tabelas que nunca vemos

 

 

 

 

 

v61snZO.png?129bcx1x.pngiVgTXVz.png?1

 

 

 

 

 

Link para o post
Compartilhar em outros sites

Participe da conversa

Você pode postar agora e se cadastrar mais tarde. Se você tem uma conta, faça o login para postar com sua conta.

Visitante
Responder

×   Você colou conteúdo com formatação.   Remover formatação

  Apenas 75 emojis são permitidos.

×   Seu link foi automaticamente incorporado.   Mostrar como link

×   Seu conteúdo anterior foi restaurado.   Limpar o editor

×   Não é possível colar imagens diretamente. Carregar ou inserir imagens do URL.

  • Quem Está Navegando   0 membros estão online

    Nenhum usuário registrado visualizando esta página.


  • Conteúdo Similar

    • Por Imperius
      O propósito é criar uma nova função em creaturescripts que será acionada toda vez que um novo report (CTRL + R) for aberto.
       
      Eu implementei para enviar uma notificação no grupo do Telegram, contendo os dados do report.
       
      Isso garantirá que os GMs tenham acesso aos reports dos jogadores mesmo quando não estiverem logados, e também evitará que algum report seja perdido caso o jogador saia do servidor.
      A parte do Telegram é apenas um exemplo. Você pode ajustar o script para executar outras ações desejadas.
       
      creatureevent.cpp:
      Dentro deste arquivo, localize a função:
       
      uint32_t CreatureEvent::executeChannelLeave(Player* player, uint16_t channelId, UsersMap usersMap)  
      abaixo dela, adicione:
       
      uint32_t CreatureEvent::executeOpenRuleViolation(Player* player, std::string message) { if (!m_interface->reserveEnv()) { std::clog << "[Error - CreatureEvent::executeOpenRuleViolation] Call stack overflow." << std::endl; return 0; } ScriptEnviroment* env = m_interface->getEnv(); env->setScriptId(m_scriptId, m_interface); lua_State* L = m_interface->getState(); m_interface->pushFunction(m_scriptId); lua_pushnumber(L, env->addThing(player)); lua_pushstring(L, message.c_str()); bool result = m_interface->callFunction(2); m_interface->releaseEnv(); return result; }  
      Após, procure por:
       
      std::string CreatureEvent::getScriptEventName() const  
      abaixo de:
       
      case CREATURE_EVENT_CHANNEL_LEAVE: return "onLeaveChannel";  
      adicione:
       
      case CREATURE_EVENT_OPEN_RULE_VIOLATION: return "onOpenRuleViolation";  
      Agora, procure por:
       
      std::string CreatureEvent::getScriptEventParams() const  
      abaixo de:
       
      case CREATURE_EVENT_CHANNEL_LEAVE: return "cid, channel, users";  
      adicione:
       
      case CREATURE_EVENT_OPEN_RULE_VIOLATION: return "cid, message";  
      Procure por:
       
      bool CreatureEvent::configureEvent(xmlNodePtr p)  
      abaixo de:
       
      else if(tmpStr == "leavechannel") m_type = CREATURE_EVENT_CHANNEL_LEAVE;  
      adicione:
       
      else if(tmpStr == "openruleviolation") m_type = CREATURE_EVENT_OPEN_RULE_VIOLATION;  
       
      creatureevent.h:
      Dentro deste arquivo, localize:
       
      enum CreatureEventType_t  
      adicione "CREATURE_EVENT_OPEN_RULE_VIOLATION" como o último item de enum CreatureEventType_t
       
      Exemplo:
       
      enum CreatureEventType_t { // ... CREATURE_EVENT_OPEN_RULE_VIOLATION };  
      Agora, procure por:
       
      uint32_t executeChannelLeave(Player* player, uint16_t channelId, UsersMap usersMap);  
      abaixo dela, adicione:
       
      uint32_t executeOpenRuleViolation(Player* player, std::string message);  
      game.cpp:
      Dentro deste arquivo, localize:
       
      bool Game::playerReportRuleViolation(Player* player, const std::string& text)  
      e substitua por:
       
      bool Game::playerReportRuleViolation(Player* player, const std::string& text) { //Do not allow reports on multiclones worlds since reports are name-based if(g_config.getNumber(ConfigManager::ALLOW_CLONES)) { player->sendTextMessage(MSG_INFO_DESCR, "Rule violation reports are disabled."); return false; } cancelRuleViolation(player); boost::shared_ptr<RuleViolation> rvr(new RuleViolation(player, text, time(NULL))); ruleViolations[player->getID()] = rvr; ChatChannel* channel = g_chat.getChannelById(CHANNEL_RVR); if(!channel) return false; for(UsersMap::const_iterator it = channel->getUsers().begin(); it != channel->getUsers().end(); ++it) it->second->sendToChannel(player, SPEAK_RVR_CHANNEL, text, CHANNEL_RVR, rvr->time); CreatureEventList joinEvents = player->getCreatureEvents(CREATURE_EVENT_OPEN_RULE_VIOLATION); for(CreatureEventList::iterator it = joinEvents.begin(); it != joinEvents.end(); ++it) (*it)->executeOpenRuleViolation(player, text); return true; }  
      Agora é só compilar a source.
       
      depois em "data > creaturescripts > creaturescripts.xml", adicione:
       
      <event type="login" name="loginNotifyRuleViolation" script="notifyRuleViolation.lua"/> <event type="openruleviolation" name="openNotifyRuleViolation" script="notifyRuleViolation.lua"/>  
      em "data > creaturescripts > scripts", crie um arquivo notifyRuleViolation.lua e adicione:
       
      function onOpenRuleViolation(cid, message) local config = { token = "", -- Token do seu BOT no Telegram chatId = "" -- ID do chat do Telegram que será enviado a notificação. } local message = "Player: "..getCreatureName(cid).."\n\nReport:\n"..message.."" message = string.gsub(message, "\n", "%%0A") local url = "https://api.telegram.org/bot"..config.token.."/sendMessage" local data = "chat_id="..config.chatId.."&text="..message.."" local curl = io.popen('curl -d "'..data..'" "'..url..'"'):read("*a") return true end function onLogin(cid) registerCreatureEvent(cid, "openNotifyRuleViolation") return true end  
       
      Demonstração:
      1. Jogador abre um novo report (CTRL + R)

      2. notifyRuleViolation.lua, definido em creaturescripts.xml, é acionado para enviar uma notificação ao grupo do Telegram.
       

       
    • Por Anderson Sacani
      Estou criando um servidor com base nos scripts de TFS 1.x e voltado ao público da america latina por causa do baixo ping na VPS... Argentina, Bolívia, Brasil, Chile, entre outros, portanto sei que falamos em português e nossos vizinhos em espanhol.
      Todos os sistemas do meu servidor são pensados para terem traduções e venho por meio deste tópico compartilhar à vocês algumas dessas funções:
       
      Antes de qualquer coisa, você precisará adicionar a seguinte variável em alguma biblioteca:
      USER_LANGUAGE = 1022118443  
      Agora que adicionou essa variável em alguma biblioteca, poderá adicionar as seguintes funções na mesma biblioteca, porém a baixo da variável USER_LANGUAGE.
       
      A primeira função serve para retornar qual idioma o player está usando:
      --[[ getLanguage, how to use: player:getLanguage() ]] function Player.getLanguage(self) if self:isPlayer() then if self:getStorageValue(USER_LANGUAGE) < 1 then return "portuguese" else return "spanish" end else print("getLanguage: Only works on players..") end end Um exemplo de como usar: player:getLanguage()
       
      A segunda função serve para alterar o idioma do player. O ideal é que seja usada na primeira vez em que o player loga no servidor:
      --[[ setLanguage, how to use: player:setLanguage("portuguese") ]] function Player.setLanguage(self, language) local value = 0 if self:isPlayer() then if language == "portuguese" then value = 0 elseif language == "spanish" then value = 1 else print("setLanguage: Only two options available. Choose one of them: 'portuguese' or 'spanish'.") end return self:setStorageValue(USER_LANGUAGE, value) else print("setLanguage: Only works on players..") end end Exemplos de como usar:
      player:setLanguage("portuguese")
      ou
      player:setLanguage("spanish")
       
      A terceira e não menos importante função, serve para mandar uma mensagem de texto ao jogador, porém ele receberá no idioma em que escolheu:
      --[[ sendLanguageTextMessage, how to use: local portugueseMessage = "Ola, tudo bom? Isto aqui é um algoritmo!" local spanishMessage = "Hola todo bien? Esto de aqui es un algoritmo!" player:sendLanguageTextMessage(MESSAGE_EVENT_ADVANCE, portugueseMessage,spanishMessage) ]] function Player.sendLanguageTextMessage(self, type, portugueseMessage, spanishMessage) if self:isPlayer() then if self:getStorageValue(USER_LANGUAGE) < 1 then return self:sendTextMessage(type, portugueseMessage) else return self:sendTextMessage(type, spanishMessage) end else print("sendLanguageTextMessage: Only works on players..") end end Um exemplo de como usar:
      player:sendLanguageTextMessage(MESSAGE_EVENT_ADVANCE, portugueseMessage, spanishMessage)
      O primeiro parâmetro é o tipo de mensagem, o segundo parâmetro será a mensagem em português e o terceiro parâmetro será em espanhol.
    • Por ILex WilL
      Olá, Alguém poderia me ajudar com uns Scripts? nem que seja cobrando, dependendo eu pago para me ajudar...
    • Por danielsort
      A minha poke ball nao esta funcionando como contador aonde consigo ageitar isso?
       
       

    • Por yurikil
      Saudações a todos, venho por meio deste tópico pedir uma ajuda no qual estou tentando fazer a muito tempo. Já vi alguns post aqui mesmo no TK, mas nenhum eu tive êxito. Por isso venho pedir um socorro de como eu consigo aumentar a quantidade de MagicEffects acima de 255 no meu NewClient OTC? Se alguém puder fortalecer ficarei muito grato!!
×
×
  • Criar Novo...

Informação Importante

Confirmação de Termo