I tried making a weapon command that would give you a pistol but it didn’t work.
AddEventHandler("chatMessage", function(s, n, m)
local message = string.lower(m) -- This prevents it from NOT recognizing /WEAPON as the command (just in case the user has caps lock on)
if message == "/weapon" then
CancelEvent() -- Hide the message from user chat
GiveWeaponToPed(s, "WEAPON_PISTOL", 1000, false, false)
end
end)
It just gives me this error and gives me no pistol
Error running system event handling function for resource script: citizen:/scripting/lua/scheduler.lua:39: Failed to execute thread: sv.lua:5: attempt to call a nil value (global 'GiveWeaponToPed')
stack traceback:
sv.lua:5: in upvalue 'handler'
citizen:/scripting/lua/scheduler.lua:124: in function <citizen:/scripting/lua/scheduler.lua:123>
stack traceback:
[C]: in function 'error'
citizen:/scripting/lua/scheduler.lua:39: in field 'CreateThreadNow'
citizen:/scripting/lua/scheduler.lua:123: in function <citizen:/scripting/lua/scheduler.lua:92>
This handler is on the server (assuming from the sv.lua filename). You will then need to trigger a client event to give the ped the weapon. The server can’t execute game natives. The server can only tell the client(s) (by events) what to do.
Error running call reference function for resource script: sv.lua:2: attempt to call a nil value (global 'PlayerId')
stack traceback:
sv.lua:2: in local 'ref'
citizen:/scripting/lua/scheduler.lua:277: in function <citizen:/scripting/lua/scheduler.lua:268>
Let me explain further. Anything to do with natives has to be done on a client script. So you have 2 options for commands. You can create the command on the client and put the weapons natives like I did above or you can create a client event to do it for you and use the server command to trigger the client event.
do you want it bound to a job and for multi different commands you would need jobs or some deciding factor so you didn’t pick up other weapons in the command
Sorry I am not really on FiveM much anymore so I could be rusty or uniformed of a propery way to handle things now (between client and server) but maybe something like this?
UNTESTED CODE
--[[ SERVER SCRIPT ]]--
local AllowedWeapons = {
["pistol"] = "WEAPON_PISTOL"
}
RegisterCommand("weapon", function(source, args, string)
local ammo = 9999
if not args[1] and type(args[1]) ~= "string" then return end
if args[2] and type(tonumber(args[2])) ~= "number" then
return
else
ammo = tonumber(args[2])
end
local Weapon = AllowedWeapons[args[1]]
if not Weapon then return end
TriggerClientEvent("GivePedWeapon", source, Weapon, ammo)
end, false)
--[[ CLIENT SCRIPT ]]--
RegisterNetEvent("GivePedWeapon")
AddEventHandler("GivePedWeapon", function(weapon, ammo)
local weaponHash = GetHashKey(weapon)
if not IsWeaponValid(weaponHash) then
return
end
local ped = GetPlayerPed(PlayerId())
GiveWeaponToPed(ped, weaponHash, ammo, false, false)
end)