Hello Andres99907! Nice to meet you. I am an experienced developer and want to help you become a better Lua scripter. For this purpose I want to give you advice on how to incrementally improve your work.
Did you know about local variables in connection with Lua closures? You can do amazing things with this mechanism like this.
local global_index = 0
index = 0
function CreateClosure()
local index = global_index + 1 -- uses the "global_index" local variable in the up-most script closure
local function callback()
return index -- uses the index variable of line 6
end
global_index = index
return callback
end
index = 42 -- modifies the global variable "index" which is not a local variable
assert( CreateClosure()() == 1 )
assert( CreateClosure()() == 2 )
assert( index == 42 ) -- not changed by CreateClosure function
Lua closures are created each time your script puts a function into a variable/table key. When you call a closure then the function is executed which then does access so called "upvalues", the local variables of closures that enclose this closure. Before you can use a local variable you have to declare it using the local keyword!
Using this technique we can improve your script by remembering the variables you create during your FlarePhys function call, like this:
Flares = {}
Chaffs = {}
function FlarePhys(x, y, z, distance, gz)
local player = client
local index = #Flares + 1
Flares[index] = {
["Vehicles"] = {
getPedOccupiedVehicle(player)
},
["Lights"] = {
createMarker(x,y,z,"corona", 1, 255,0,0)
},
["Flares"] = {
createObject(2060, x,y,z)
}
}
setElementData(Flares[index]["Vehicles"][1], "Dismissile", true)
setElementCollisionsEnabled(Flares[index]["Flares"][1], false)
attachElements(Flares[index]["Lights"][1], Flares[index]["Flares"][1])
moveObject(Flares[index]["Flares"][1], distance*100, x, y, gz +1.5)
setTimer ( function()
if isElement(Flares[index]["Vehicles"][1]) then
removeElementData(Flares[index]["Vehicles"][1], "Dismissile")
else
destroyElement(Flares[index]["Flares"][1])
destroyElement(Flares[index]["Lights"][1])
end
end, 1000, 1 )
setTimer ( function()
outputChatBox(getPlayerName(player))
destroyElement(Flares[index]["Flares"][1])
destroyElement(Flares[index]["Lights"][1])
end, 8000, 1 )
end
addEvent("UseFlares", true)
addEventHandler("UseFlares", getRootElement(), FlarePhys)
This script should work better for you because now the "creator" does not suddenly change anymore.