全局函数findPlayer在部分命令中未定义及输出逻辑调整咨询
Let's break down your two issues one by one:
1. Why findPlayer isn't recognized in the admin command
The core problem here is scope access to your global function. When you define global.findPlayer, you're attaching it to the global object—but in module-based environments (like Node.js, which many multiplayer frameworks rely on), individual script files have their own local scope.
You mentioned the first command works, which might be a quirk of how that event handler's execution context resolves global variables. However, the admin command's callback isn't automatically resolving findPlayer to the global object.
The fix is straightforward: explicitly reference the global object when calling the function. Replace findPlayer(targetPlayer) with global.findPlayer(targetPlayer)—this tells the interpreter to look for the function on the global scope instead of the local one.
2. How to make "Banana" only show when there are no errors
Right now, player.outputChatBox("Banana") runs immediately when the command is triggered, before any error checks. To fix this, move that line inside the try block, after all your validation checks. This way, it will only execute if none of the throw statements are triggered (meaning all validation passed without errors).
Revised admin command code
mp.events.addCommand('admin', (player, targetPlayer, targetAdminLevel) => { try { if (player.adminLevel < 8) throw "Este comando só está disponível para administradores de nível superior a 8."; if (!targetPlayer) throw "Uso: /admin <ID/NOME> <NÍVEL DE ADMINISTRADOR>."; if (player.adminLevel <= targetAdminLevel) throw "Não podes promover alguém a um nível superior ao teu."; // Explicitly use global.findPlayer to access the global function if (!global.findPlayer(targetPlayer)) throw "Esse jogador não existe ou não está online."; // Only runs if all validation checks pass (no errors thrown) player.outputChatBox("Banana"); } catch(err) { player.outputChatBox(`!{${corErro}}${err}`); } finally { console.log("Finally"); } });
Quick extra tips:
- For consistency, update your
isplayeronlinecommand to also useglobal.findPlayer—this prevents future scope-related bugs if your environment's behavior changes. - Double-check that
corErrois defined somewhere in your code (it’s used in the catch block), otherwise you’ll hit another reference error there.
内容的提问来源于stack exchange,提问作者Hugo Almeida

