local Tunnel = module("vrp","lib/tunnel")
local Proxy = module("vrp","lib/proxy")
vRP = Proxy.getInterface("vRP")

Bjorn = Tunnel.getInterface("BjornMedical")



--------- anim revivendo vitima: 'mini@cpr@char_b@cpr_str', 'cpr_pumpchest'
--- TaskPlayAnim(playerPed, 'mini@cpr@char_b@cpr_str', 'cpr_pumpchest', 8.0, 8.0, -1, 0, 0, false, false, false)

--------- anim reviver medico: mini@cpr@char_a@cpr_str','cpr_pumpchest
--- TaskPlayAnim(playerPed, 'mini@cpr@char_a@cpr_str','cpr_pumpchest', 8.0, 8.0, -1, 0, 0, false, false, false)


--[[
RegisterKeyMapping ( 'anime' , 'asdasdadadad' , 'keyboard' , 'E' )

RegisterCommand("anime", function(source,args)
print("1")
if not fazendoanim then
fazendoanim = true
local ped = PlayerPedId()
--vRP._playAnim(true,{{'mini@cpr@char_a@cpr_str','cpr_pumpchest'}},true)
LoadAnimDic("mini@cpr@char_b@cpr_str")	
TaskPlayAnim(ped,"mini@cpr@char_b@cpr_str","cpr_kol_idle",3.0,-3.0,-1,0,0,0,0,0)
else
	
	vRP._stopAnim(false)								
	vRP._DeletarObjeto()
	ClearPedTasks()
	fazendoanim = false
end
end)

]]


CreateThread(function()
LoadAnimDic("anim@heists@box_carry@")
LoadAnimDic("combat@damage@writheidle_c")
LoadAnimDic("anim@heists@box_carry@")
LoadAnimDic("mp_common")
LoadAnimDic("amb@world_human_bum_slumped@male@laying_on_right_side@base")
LoadAnimDic('mini@cpr@char_b@cpr_str')
LoadAnimDic('mini@cpr@char_b@cpr_def')
LoadAnimDic('mini@cpr@char_a@cpr_def')
LoadAnimDic('mini@cpr@char_a@cpr_str')
end)





----------------------------------------------------------------------------------------------------------------------------
------------------------------- VARIAVEIS E THREAD DA MALETA
----------------------------------------------------------------------------------------------------------------------------


local maleta = false
local maletamao = false
local maletachao = false
local cordMaletax,cordMaletay,cordMaletaz = nil

local pegouMaca = false

-- xm_prop_x17_bag_med_01a
-- sm_prop_smug_crate_s_medical


local maletaobj = "xm_prop_x17_bag_med_01a"
local propMaletaChao = nil


local macaobj = "v_med_bed2"
local macachao = nil
local cordMacax,cordMacay,cordMacaz = nil



PacienteNaAmbu = false
playerNaMacaAmbu = nil
morto = false


Citizen.CreateThread(function()
Wait(2000)
if Bjorn.chkAuth() then
	while true do
	local Sleep = 500	
		
		local ped = PlayerPedId()
		local coordA = GetEntityCoords(GetPlayerPed(-1), 1)
		local vehicle = GetClosestVehicle(coordA.x,coordA.y,coordA.z,5.0,0,71)
		
		--print(config.animacaomorto[1],config.animacaomorto[2])
		if GetEntityHealth(ped) <= config.vidamorte then
		--print(config.animacaomorto[1],config.animacaomorto[2])
		
			local Ultimodano, Ultimodano2 = GetPedLastDamageBone(ped,31086)
			if Ultimodano == 1 and Ultimodano2 == 31086 then --------------------------- ANIMACAO HS
			
				if not IsEntityPlayingAnim(ped,config.animacaomortoHS[1],config.animacaomortoHS[2],3) and not sendocarregado and not PacienteNaAmbu and not sendoreanimado then
					if not HasAnimDictLoaded(config.animacaomortoHS[1]) then
					LoadAnimDic(config.animacaomortoHS[1])
					end
					TaskPlayAnim(ped,config.animacaomortoHS[1],config.animacaomortoHS[2],3.0,-3.0,-1,1,0,0,0,0)
				end
			
			else        --------------------------- ANIMACAO NAO HS
			
				if not IsEntityPlayingAnim(ped,config.animacaomorto[1],config.animacaomorto[2],3) and not sendocarregado and not PacienteNaAmbu and not sendoreanimado then
					if not HasAnimDictLoaded(config.animacaomorto[1]) then
					LoadAnimDic(config.animacaomorto[1])
					end
					TaskPlayAnim(ped,config.animacaomorto[1],config.animacaomorto[2],3.0,-3.0,-1,1,0,0,0,0)
				end
				
			end
		end
		
		
		for k, v in pairs(config.veiculo) do
		vehicletow = IsVehicleModel(vehicle,GetHashKey(k))		 
		if DoesEntityExist(vehicle) and IsEntityAVehicle(vehicle) and vehicletow then
		Sleep = 4		
			--local ped = PlayerPedId()			
			local cdtest = { ["x"] = v["X"],["y"] = v["Y"],["z"] = v["Z"] }
			local data = {cdtest, vector3(0.0, 0.0,0.0)}
			local rightDir, fwdDir, upDir, pos = GetEntityMatrix(vehicle)
            local x = pos.x + (fwdDir.x * data[1].x) + (rightDir.x * data[1].y) + (upDir.x * data[1].z)
            local y = pos.y + (fwdDir.y * data[1].x) + (rightDir.y * data[1].y) + (upDir.y * data[1].z)
            local z = pos.z + (fwdDir.z * data[1].x) + (rightDir.z * data[1].y) + (upDir.z * data[1].z)
			
			
            local controllerPos = vector3(x, y, z)
			local distanceToTrunk = GetDistanceBetweenCoords(controllerPos, coordA, 1)
			
			if distanceToTrunk < 1.5 then
			if not pegouPlayer then
			if GetSelectedPedWeapon(ped) == GetHashKey('WEAPON_UNARMED') and not IsPedInAnyVehicle(ped) then
                DrawText3D(x, y, z, config.lang["menu"])
			else
				DrawText3D(x, y, z, config.lang["noweapon"])
			end
			end
			if IsControlJustPressed(0,38) and GetSelectedPedWeapon(ped) == GetHashKey('WEAPON_UNARMED') and not IsPedInAnyVehicle(ped) and Bjorn.chkAuth() and not pegouPlayer then
			if Bjorn.chkPerm() then					
				TriggerServerEvent("BjornMedical:MedicalMenu")					
			else
				TriggerEvent("Notify","negado",config.lang["warn11"])
			end	
			end
			
			if pegouPlayer or PacienteNaAmbu then
			if not PacienteNaAmbu then
			DrawText3D(x, y, z-0.3, config.lang["cmaca"])
			else
			DrawText3D(x, y, z-0.3, config.lang["rmaca"])
			end
			if IsControlJustPressed(0,20) then
			if not PacienteNaAmbu then
			if PlayerColo ~= nil then
			PacienteNaAmbu = true
			playerNaMacaAmbu = PlayerColo
			TriggerServerEvent("BjornMedical:SyncAnimationColo",GetPlayerServerId(playerNaMacaAmbu))
			pegouPlayer = false
			PlayerColo = nil
			ClearPedTasks(ped)
			TriggerEvent("Bjorn:cancelando",false)
			TriggerServerEvent("BjornMedical:PacienteMacaAmbu",GetPlayerServerId(playerNaMacaAmbu),VehToNet(vehicle),v["MACA"]["X"],v["MACA"]["Y"],v["MACA"]["Z"], v["MACA"]["RotX"],v["MACA"]["RotY"],v["MACA"]["RotZ"])
			else
			TriggerEvent("Notify","negado",config.lang["warn1"])
			end
			else
			PacienteNaAmbu = false			
			TriggerServerEvent("BjornMedical:PacienteMacaAmbu",GetPlayerServerId(playerNaMacaAmbu),VehToNet(vehicle),coordA.x,coordA.y,coordA.z)
			pegouPlayer = true
			PlayerColo = playerNaMacaAmbu
			LoadAnimDic("anim@heists@box_carry@")
			TaskPlayAnim(ped, 'anim@heists@box_carry@', 'idle', 8.0, 8.0, -1, 50, 0, false, false, false)
			TriggerServerEvent("BjornMedical:SyncAnimationColo",GetPlayerServerId(playerNaMacaAmbu))
			TriggerEvent('BjornMedical:RetirarPlayerColo')
			TriggerEvent("Bjorn:cancelando",true)
			playerNaMacaAmbu = nil
			end			
			end
			end		
			end
			end
		end
		Wait(Sleep)
		end
	end
end)




----------------------------------------------------------------------------------------------------------------------------
------------------------------- EVENTO PARA RETIRAR O PLAYER DO COLO APOS TIRAR ELE DA AMBULANCIA
----------------------------------------------------------------------------------------------------------------------------
RegisterNetEvent('BjornMedical:RetirarPlayerColo')
AddEventHandler('BjornMedical:RetirarPlayerColo',function()
local ped = PlayerPedId()
while not maletachao and pegouPlayer do
Wait(4)
	if not sendocarregado and not PacienteNaAmbu then
	local cordPlayer = GetEntityCoords(ped)
	DrawText3D(cordPlayer.x,cordPlayer.y,cordPlayer.z+1, config.lang["droplayer"])
	end
	
	if IsControlJustPressed(0,44) or IsDisabledControlJustPressed(0,44) and not reanimando then	
	pegouPlayer = false	
	ClearPedTasks(ped)
	TriggerEvent("Bjorn:cancelando",false)
	TriggerServerEvent("BjornMedical:SyncAnimationColo",GetPlayerServerId(PlayerColo))
	PlayerColo = nil
	end
end
end)

----------------------------------------------------------------------------------------------------------------------------
------------------------------- THREAD PARA QUANDO O PLAYER PEGAR A MALETA
----------------------------------------------------------------------------------------------------------------------------
tempmaleta = nil
object = nil


RegisterNetEvent('BjornMedical:Pegando/GuardandoMaleta')
AddEventHandler('BjornMedical:Pegando/GuardandoMaleta',function()
local ped = PlayerPedId()
	if not macamao then
	if not maleta and not maletamao then	
		maleta = true
		maletamao = true
		--vRP.playAnim(false,{{"mp_common","givetake1_a"}},false)		
		LoadAnimDic("mp_common")	
		TaskPlayAnim(ped,"mp_common","givetake1_a",3.0,-3.0,-1,0,0,0,0,0)
		
		Wait(1000)
		--vRP.CarregarObjeto("","",maletaobj,50, 57005 , 0.45, 0, 0.05 , 0, tonumber("260.0") , tonumber("60.0"))
		
		RequestModel(GetHashKey(maletaobj))
			while not HasModelLoaded(GetHashKey(maletaobj)) do
				Citizen.Wait(300)
			end
			
		local coords = GetOffsetFromEntityInWorldCoords(ped,0.0,0.0,-5.0)
		object = CreateObject(GetHashKey(maletaobj),coords.x,coords.y,coords.z,true,true,true)
		SetEntityCollision(object,false,false)
		AttachEntityToEntity(object,ped,GetPedBoneIndex(ped,57005),0.45, 0, 0.05,0, tonumber("260.0") , tonumber("60.0"),true,true,false,true,1,true)
		
		TriggerEvent("BjornMedical:PegouMaleta")
	else
	if not maletachao then
		maleta = false
		maletamao = false
		LoadAnimDic("mp_common")
		TaskPlayAnim(ped,"mp_common","givetake1_a",3.0,-3.0,-1,0,0,0,0,0)
		Wait(1000)
		DeleteEntity(tempmaleta)
		DeleteEntity(object)
		object = nil
		tempmaleta = nil				
	else
		TriggerEvent("Notify","negado",config.lang["warn2"])
	end	
	end
	else
		TriggerEvent("Notify","negado",config.lang["warn3"])
	end
end)




RegisterNetEvent('BjornMedical:PegouMaleta')
AddEventHandler('BjornMedical:PegouMaleta',function()
	while maletamao do
	Wait(4)
	local ped = PlayerPedId()
	local ui = GetMinimapAnchor()
	drawTxt(ui.right_x+0.200,ui.bottom_y-0.085,tonumber("1.0"),tonumber("1.0"),0.40,config.lang["dsuitcase"],255,255,255,200)
	
	local coords = GetPedBoneCoords(PlayerPedId(), GetHashKey('SKEL_R_Hand'), tonumber("0.0"), tonumber("1.0"), tonumber("0.0"))
	local x,y,z = table.unpack(coords)
	DrawMarker(27,x,y,z-0.9,0,0,0,0,0,0,tonumber("1.0"),tonumber("1.0"),tonumber("1.0"),200,0,0,50,0,0,2,1,nil,nil,false)	
	
	--[[
	if tempmaleta == nil then
	RequestModel(maletaobj)
	while not HasModelLoaded(maletaobj) do
		Wait(300)
	end
	tempmaleta = CreateObject(GetHashKey(maletaobj),x,y,z,1,1,1)	
	AttachEntityToEntity(tempmaleta,ped, GetHashKey('SKEL_R_Hand'),tonumber("0.0"),tonumber("1.0"),tonumber("-1.0"),tonumber("0.0"),tonumber("0.0"),tonumber("0.0"),1,1,0,0,2,1) 
	SetEntityAlpha(tempmaleta, 150)
	SetEntityVisible(tempmaleta,false)
	end
	]]
	
	if IsControlJustPressed(0,47) and maletamao and GetSelectedPedWeapon(ped) == GetHashKey('WEAPON_UNARMED') and not IsPedInAnyVehicle(ped) and Bjorn.chkAuth() then	
	maletamao = false
	maletachao = true
		--vRP.playAnim(false,{{"pickup_object","pickup_low"}},false)
		LoadAnimDic("pickup_object")	
		TaskPlayAnim(ped,"pickup_object","pickup_low",3.0,-3.0,-1,0,0,0,0,0)	
			Wait(1000)
		
		DeleteEntity(tempmaleta)
		tempmaleta = nil
		DeleteEntity(object)
		object = nil
		--vRP._DeletarObjeto(maletaobj)
		cordMaletax,cordMaletay,cordMaletaz = x,y,z-1		
		TriggerEvent("BjornMedical:PegarMaletaChao")
		--TriggerEvent("BjornMedical:MaletaChao")
		TriggerServerEvent("BjornMedical:ColocarMaletaChaoServer",cordMaletax,cordMaletay,cordMaletaz)		
	end
	end
end)

----------------------------------------------------------------------------------------------------------------------------
------------------------------- EVENTO PARA CRIAR A MALETA NO CHAO
----------------------------------------------------------------------------------------------------------------------------

RegisterNetEvent('BjornMedical:ColocarMaletaChao')
AddEventHandler('BjornMedical:ColocarMaletaChao',function(x,y,z)
RequestModel(maletaobj)
	while not HasModelLoaded(maletaobj) do
		Citizen.Wait(10)
	end
propMaletaChao = CreateObject(GetHashKey(maletaobj),x,y,z,1,1,1)
SetEntityCollision(propMaletaChao,true,false)
SetEntityAsMissionEntity(propMaletaChao,true,true)
FreezeEntityPosition(propMaletaChao,true)
end)

----------------------------------------------------------------------------------------------------------------------------
------------------------------- THREAD PRA QUEM COLOCOU A MALETA PODER TIRAR TAMBEM
----------------------------------------------------------------------------------------------------------------------------
playerProx = nil
pegouPlayer = false
PlayerColo = nil
reanimando = false


RegisterNetEvent('BjornMedical:PegarMaletaChao')
AddEventHandler('BjornMedical:PegarMaletaChao',function()
playerProx = GetClosestPlayer()
while maletachao do
	local Sleep = 500
	local ped = PlayerPedId()
	
	local pedCord = GetEntityCoords(ped)
	local vecMaletachao = vec3(cordMaletax,cordMaletay,cordMaletaz)
	local distance = #(pedCord-vecMaletachao)
	
	if distance < 5 then
	if not pegouPlayer and not reanimando then
	Sleep = 4
	if not macamao then
	if GetSelectedPedWeapon(ped) == GetHashKey('WEAPON_UNARMED') and not IsPedInAnyVehicle(ped) then
	if distance < 2 then
	if not tratando then
	DrawText3D(cordMaletax,cordMaletay,cordMaletaz+1, config.lang["tsuitcase"])
	DrawText3D(cordMaletax,cordMaletay,cordMaletaz+0.8, config.lang["attplayer"])
	end
	end
	else
	DrawText3D(cordMaletax,cordMaletay,cordMaletaz+1, config.lang["noweapon"])
	end
		if IsControlJustPressed(0,47) and maletachao and distance < 2 and GetSelectedPedWeapon(ped) == GetHashKey('WEAPON_UNARMED') and not IsPedInAnyVehicle(ped) and not tratando then	
			maletamao = true
			maletachao = false
			--vRP.playAnim(false,{{"pickup_object","pickup_low"}},false)	
			LoadAnimDic("pickup_object")	
			TaskPlayAnim(ped,"pickup_object","pickup_low",3.0,-3.0,-1,0,0,0,0,0)
			Wait(1000)
			--vRP.CarregarObjeto("","",maletaobj,50, 57005 , 0.45, 0, 0.05 , 0, tonumber("260.0"), tonumber("60.0"))		
			RequestModel(GetHashKey(maletaobj))
			while not HasModelLoaded(GetHashKey(maletaobj)) do
				Citizen.Wait(300)
			end
			local coords = GetOffsetFromEntityInWorldCoords(ped,0.0,0.0,-5.0)
			object = CreateObject(GetHashKey(maletaobj),coords.x,coords.y,coords.z,true,true,true)
			SetEntityCollision(object,false,false)
			AttachEntityToEntity(object,ped,GetPedBoneIndex(ped,57005),0.45, 0, 0.05,0, tonumber("260.0") , tonumber("60.0"),true,true,false,true,1,true)
			
			TriggerEvent("BjornMedical:PegouMaleta")
			TriggerServerEvent('BjornMedical:DeletarMaletaChaoServer',propMaletaChao)
		end		
	else
		DrawText3D(cordMaletax,cordMaletay,cordMaletaz+1, config.lang["warn4"])
	end
	
	if IsControlJustPressed(0,301) and maletachao and distance < 2 and not tratando then
		playerProx = GetClosestPlayer()
	end
	end
	else
	Sleep = 4
	local ui = GetMinimapAnchor()
	drawTxt(ui.right_x+0.300,ui.bottom_y-0.1,tonumber("1.0"),tonumber("1.0"),0.40,config.lang["warn5"],255,255,255,200)
    end
	
	
	local PedPlayer = GetPlayerPed(playerProx)
	local cordPlayer = GetEntityCoords(PedPlayer)
	local distPlayer = #(cordPlayer-pedCord)
	
	if distPlayer < 3 then	
	Sleep = 4
	
	if not reanimando then
	if not PacienteNaAmbu and not pacientenamaca then
	if not pegouPlayer and pid ~= playerProx then
	if not sendocarregado and not macamao and not maletamao then
	DrawText3D(cordPlayer.x,cordPlayer.y,cordPlayer.z+1, config.lang["takeplayer"])
	end
	else
	DrawText3D(cordPlayer.x,cordPlayer.y,cordPlayer.z+1, config.lang["droplayer"])
	end
	end
	end
	
	if IsControlJustPressed(0,44) or IsDisabledControlJustPressed(0,44) and not reanimando and pid ~= playerProx then
	if not PacienteNaAmbu and not pacientenamaca and not macamao and not maletamao then
	if not pegouPlayer and not sendocarregado  then
	pegouPlayer = true
	PlayerColo = playerProx
	LoadAnimDic("anim@heists@box_carry@")
	TaskPlayAnim(ped, 'anim@heists@box_carry@', 'idle', 8.0, 8.0, -1, 50, 0, false, false, false)
	TriggerServerEvent("BjornMedical:SyncAnimationColo",GetPlayerServerId(playerProx))
	TriggerEvent("Bjorn:cancelando",true)
	else
	TriggerServerEvent("BjornMedical:SyncAnimationColo",GetPlayerServerId(playerProx))
	pegouPlayer = false
	PlayerColo = nil
	ClearPedTasks(ped)
	TriggerEvent("Bjorn:cancelando",false)
	end
	end
	end
	
	local vidaPaciente = GetEntityHealth(PedPlayer)
	if distance < 5 and not pegouPlayer and not PacienteNaAmbu then
	if not reanimando and vidaPaciente <= config.vidamorte then
	if pacientemacasolta ~= playerProx then
	DrawText3D(cordPlayer.x,cordPlayer.y,cordPlayer.z+0.8, config.lang["reanim"])
	end
	if IsControlJustPressed(0,38) or IsDisabledControlJustPressed(0,38) and pacientemacasolta ~= playerProx then
	reanimando = true
	FreezeEntityPosition(ped,true)
	local playerlocation = GetEntityForwardVector(PlayerPedId())
	local playerheading = GetEntityHeading(GetPlayerPed(-1))
	local pCoords = GetEntityCoords(GetPlayerPed(-1))	
	TriggerServerEvent("BjornMedical:Reanimando",GetPlayerServerId(playerProx), playerheading, pCoords, playerlocation)
	Wait(2000)
	FreezeEntityPosition(ped,false)
	end	
	end
	end	
	end
	Wait(Sleep)
	end
end)


----------------------------------------------------------------------------------------------------------------------------
------------------------------- EVENTO QUE SYNCA O PACIENTE NA ANIMAÇÃO AO SER CARREGADO
----------------------------------------------------------------------------------------------------------------------------

---- TaskPlayAnim(ped, "amb@code_human_in_car_idles@generic@ps@base", "base", 8.0, -8, -1, 33, 0, 0, 40, 0)


sendocarregado = false

RegisterNetEvent('BjornMedical:SyncAnimationColo')
AddEventHandler('BjornMedical:SyncAnimationColo',function(Medico)

local ped = PlayerPedId()
local MedPed = GetPlayerPed(GetPlayerFromServerId(Medico))

if not sendocarregado then
	sendocarregado = true
	LoadAnimDic("amb@world_human_bum_slumped@male@laying_on_right_side@base")	
	--AttachEntityToEntity(ped, MedPed, 9816, 0.015, 0.38, 0.11, 0.9, 0.30, 90.0, false, false, false, false, 2, false)
	AttachEntityToEntity(ped, MedPed, GetPedBoneIndex(MedPed, 57005), -0.32, -0.6, -0.35, 240.0, 35.0, 149.0, true, true, false, true, 1, true)
	TaskPlayAnim(ped, "amb@world_human_bum_slumped@male@laying_on_right_side@base", "base", 8.0, -8, -1, 33, 0, 0, 40, 0)

	else
	sendocarregado = false
	DetachEntity(ped,true,false)
	ClearPedTasks(ped)
	end
end)

----------------------------------------------------------------------------------------------------------------------------
------------------------------- ANIMAÇÃO DO PACIENTE SENDO REANIMADO
----------------------------------------------------------------------------------------------------------------------------
sendoreanimado = false


RegisterNetEvent('BjornMedical:AnimacaoMorto')
AddEventHandler('BjornMedical:AnimacaoMorto',function(head, coord, loc)
sendoreanimado = true
local ped = PlayerPedId()
	FreezeEntityPosition(ped,true)
	TriggerEvent("Bjorn:cancelando",true)
	LoadAnimDic('mini@cpr@char_b@cpr_str')
	LoadAnimDic('mini@cpr@char_b@cpr_def')

	SetCurrentPedWeapon(ped, GetHashKey('WEAPON_UNARMED'), true)

	local x, y, z   = table.unpack(coord + loc * 1.0)
	SetEntityCoords(ped, x, y, z-1)
	SetEntityHeading(ped, head - 270.0) 

	TaskPlayAnim(ped, 'mini@cpr@char_b@cpr_def',  'cpr_intro', 8.0, 8.0, -1, 0, 0, false, false, false)
		Citizen.Wait(14900)
	for i=1, 15, 1 do
		Citizen.Wait(900)
		TaskPlayAnim(ped, 'mini@cpr@char_b@cpr_str', 'cpr_pumpchest', 8.0, 8.0, -1, 0, 0, false, false, false)
	end
		StopScreenEffect("DeathFailOut")
		TaskPlayAnim(ped, 'mini@cpr@char_b@cpr_str', 'cpr_success', 8.0, 8.0, 27590, 0, 0, false, false, false)	
		Citizen.Wait(24590)
	while GetEntityHealth(ped) <= config.vidamorte do
	TriggerServerEvent("Bjorn:ReanimarSe")
	Citizen.Wait(1000)
	end
	TriggerEvent("Bjorn:cancelando",false)
	FreezeEntityPosition(ped,false)
	sendoreanimado = false
end)

----------------------------------------------------------------------------------------------------------------------------
------------------------------- ANIMACAO DO MEDICO REANIMANDO
----------------------------------------------------------------------------------------------------------------------------


RegisterNetEvent('BjornMedical:AnimacaoMedico')
AddEventHandler('BjornMedical:AnimacaoMedico',function()
TriggerEvent("Bjorn:cancelando",true)

local ped = PlayerPedId()

	SetCurrentPedWeapon(ped, GetHashKey('WEAPON_UNARMED'), true)

	LoadAnimDic('mini@cpr@char_a@cpr_def')
	LoadAnimDic('mini@cpr@char_a@cpr_str')

	TaskPlayAnim(ped, 'mini@cpr@char_a@cpr_def', 'cpr_intro', 8.0, 8.0, -1, 0, 0, false, false, false)    
						
	Citizen.Wait(14900)
		for i=1, 15, 1 do
			Citizen.Wait(900)
			TaskPlayAnim(ped, 'mini@cpr@char_a@cpr_str','cpr_pumpchest', 8.0, 8.0, -1, 0, 0, false, false, false)
		end
	TaskPlayAnim(ped,'mini@cpr@char_a@cpr_str', 'cpr_success', 8.0, 8.0, 27590, 0, 0, false, false, false)
	Citizen.Wait(28590)
	TriggerEvent("Bjorn:cancelando",false)
	--FreezeEntityPosition(ped,false)
	Citizen.Wait(2000)
	reanimando = false
	
end)


----------------------------------------------------------------------------------------------------------------------------
------------------------------- COLOCAR NA MACA
----------------------------------------------------------------------------------------------------------------------------


dentrodaambu = false

RegisterNetEvent('BjornMedical:PacienteMacaAmbu')
AddEventHandler('BjornMedical:PacienteMacaAmbu',function(veh,x,y,z,rx,ry,rz)
local ped = PlayerPedId()
	if not dentrodaambu then
		dentrodaambu = true	
		AttachEntityToEntity(ped, NetToVeh(veh),  NetToVeh(veh), x,y,z,rx,ry,rz, true, true, false, true, 1, true)
		--vRP.playAnim(false,{{"mini@cpr@char_b@cpr_str","cpr_kol_idle"}},true)		
		LoadAnimDic("mini@cpr@char_b@cpr_str")	
		TaskPlayAnim(ped,"mini@cpr@char_b@cpr_str","cpr_kol_idle",3.0,-3.0,-1,1,0,0,0,0)
		--while dentrodaambu do
		--Wait(100)
		--if not IsEntityPlayingAnim(ped,"mini@cpr@char_b@cpr_str","cpr_kol_idle",3) then
		--TaskPlayAnim(ped,"mini@cpr@char_b@cpr_str","cpr_kol_idle",3.0,-3.0,-1,0,0,0,0,0)
		--end
		if not IsEntityAttachedToAnyVehicle(ped) then
		AttachEntityToEntity(ped, NetToVeh(veh),  NetToVeh(veh), x,y,z,rx,ry,rz, true, true, false, true, 1, true)
		end	
	else		
		dentrodaambu = false
		--Wait(500)
		DetachEntity(ped,true,false)
		SetEntityCoords(ped,x,y,z)		
		ClearPedTasks(ped)	
	end	
end)
----------------------------------------------------------------------------------------------------------------------------
------------------------------- DELETAR MALETA
----------------------------------------------------------------------------------------------------------------------------
RegisterNetEvent('BjornMedical:DeletarMaletaChao')
AddEventHandler('BjornMedical:DeletarMaletaChao',function(prop)
	if DoesEntityExist(prop) then
		DetachEntity(prop,true,true)
		Citizen.InvokeNative(0xAD738C3085FE7E11,prop,true,true)
		SetEntityAsNoLongerNeeded(Citizen.PointerValueIntInitialized(prop))
		DeleteEntity(prop)
		prop = nil
	end
end)


-----------------------------------------------------------------------------------------------------------------------------------------
-- MACA
-----------------------------------------------------------------------------------------------------------------------------------------
macamao = false
macaid = nil


-------- v_med_emptybed

RegisterNetEvent('BjornMedical:TakeMaca')
AddEventHandler('BjornMedical:TakeMaca',function()

local ped = PlayerPedId()
	if not maletamao then 
	if not macamao and not macachao then
		macamao = true
		--LoadAnimDic("mp_common")	
		--TaskPlayAnim(ped,"mp_common","givetake1_a",3.0,-3.0,-1,0,0,0,0,0)		
		
		LoadAnimDic("anim@heists@box_carry@")					
		RequestModel(GetHashKey(macaobj))
			while not HasModelLoaded(GetHashKey(macaobj)) do
				Citizen.Wait(300)
			end
		local coords = GetOffsetFromEntityInWorldCoords(ped,0.0,0.0,-5.0)
		macaid = CreateObject(GetHashKey(macaobj),coords.x,coords.y,coords.z,true,true,true)
		--SetEntityCollision(macaid,false,false)
		AttachEntityToEntity(macaid, GetPlayerPed(-1), GetPlayerPed(-1), 0.0, 1.6, -0.43 , 180.0, 180.0, 180.0, 0.0, false, false, true, false, 2, true)
		TaskPlayAnim(ped, 'anim@heists@box_carry@', 'idle', 8.0, 8.0, -1, 50, 0, false, false, false)
		TriggerEvent("BjornMedical:PegouMaca")
	else
	if not macachao then
		macamao = false
		ClearPedTasks(ped)
		DeleteEntity(macaid)
		
		
	if pacientenamaca then
	local coordA = GetEntityCoords(GetPlayerPed(-1), 1)
	local vehicle = GetClosestVehicle(coordA.x,coordA.y,coordA.z,5.0,0,71)
	for k, v in pairs(config.veiculo) do
	vehicletow = IsVehicleModel(vehicle,GetHashKey(k))		 
	if DoesEntityExist(vehicle) and IsEntityAVehicle(vehicle) and vehicletow then
	TriggerServerEvent("BjornMedical:SyncPlayerMacaSolta",GetPlayerServerId(pacientemacasolta),ObjToNet(macaid))
	ClearPedTasks(ped)	
	TriggerServerEvent("BjornMedical:PacienteMacaAmbu",GetPlayerServerId(pacientemacasolta),VehToNet(vehicle),v["MACA"]["X"],v["MACA"]["Y"],v["MACA"]["Z"], v["MACA"]["RotX"],v["MACA"]["RotY"],v["MACA"]["RotZ"])
	pacientenamaca = false
	----print("essa porra aq")
	PacienteNaAmbu = true
	playerNaMacaAmbu = pacientemacasolta
	pacientemacasolta = nil
	end
	end
	end	
	macaid = nil	
	else
		TriggerEvent("Notify","negado",config.lang["warn6"])
	end	
	end
	else
		TriggerEvent("Notify","negado",config.lang["warn7"])
	end
end)

----------------------------------------------------------------------------------------------------------------------------
------------------------------- EVENTO DE QUANDO O PLAYER PEGA A MACA DA AMBULANCIA
----------------------------------------------------------------------------------------------------------------------------
pacientenamaca = false
pacientemacasolta = nil
tratando = false

RegisterNetEvent('BjornMedical:PegouMaca')
AddEventHandler('BjornMedical:PegouMaca',function()
	while macamao or macachao do
	Wait(4)
	local ped = PlayerPedId()
	local coords = GetEntityCoords(ped)
	local x,y,z = table.unpack(coords)
	local ui = GetMinimapAnchor()
	
	if macamao then
	drawTxt(ui.right_x+0.200,ui.bottom_y-0.200,tonumber("1.0"),tonumber("1.0"),0.40,config.lang["dmaca"],255,255,255,200)
	elseif macachao then
	local maca = GetClosestObjectOfType(coords, 2.0, GetHashKey(macaobj))
	local macacord = GetEntityCoords(maca,1)
	--print(maca,macaid)
	if maca == macaid then
	if not pegouPlayer then
	if not maletamao then
	--drawTxt(ui.right_x+0.200,ui.bottom_y-0.200,tonumber("1.0"),tonumber("1.0"),0.40,"PRESSIONE ~b~G~w~ PARA PEGAR A ~y~MACA",255,255,255,200)
	if not tratando and not reanimando then
	DrawText3D(macacord.x,macacord.y,macacord.z+1, config.lang["tmaca"])
	end
	else
	DrawText3D(macacord.x,macacord.y,macacord.z+1, config.lang["warn8"])
	end
	end
	end
	end
	
	if pegouPlayer and not macamao and not pacientenamaca then 
	local maca = GetClosestObjectOfType(coords, 2.0, GetHashKey(macaobj))
	local macacord = GetEntityCoords(maca,1)
	DrawText3D(macacord.x,macacord.y,macacord.z+1.2, config.lang["putonplayermaca"])
	if IsControlJustPressed(0,38) or IsDisabledControlJustPressed(0,38) and GetSelectedPedWeapon(ped) == GetHashKey('WEAPON_UNARMED') then
	pacientenamaca = true
	pacientemacasolta = PlayerColo
	TriggerServerEvent("BjornMedical:SyncAnimationColo",GetPlayerServerId(PlayerColo))
	--Wait(500)
	TriggerServerEvent("BjornMedical:SyncPlayerMacaSolta",GetPlayerServerId(pacientemacasolta),ObjToNet(macaid))
	pegouPlayer = false
	PlayerColo = nil
	ClearPedTasks(ped)
	TriggerEvent("Bjorn:cancelando",false)
	Wait(1000)
	--else
	--pacientemacasolta = nil
	--pacientenamaca = false
	--TriggerServerEvent("BjornMedical:SyncPlayerMacaSolta",GetPlayerServerId(pacientemacasolta),ObjToNet(macaid))
	end
	end
	
	if pacientenamaca and not maletamao and not macamao then
	local maca = GetClosestObjectOfType(coords, 2.0, GetHashKey(macaobj))
	local macacord = GetEntityCoords(maca,1)
	if not tratando then
	DrawText3D(macacord.x,macacord.y,macacord.z+1.2, config.lang["rplayermaca"])
	end
	if IsControlJustPressed(0,44) or IsDisabledControlJustPressed(0,44) and GetSelectedPedWeapon(ped) == GetHashKey('WEAPON_UNARMED') and not tratando and not reanimando then	
	TriggerServerEvent("BjornMedical:SyncPlayerMacaSolta",GetPlayerServerId(pacientemacasolta),ObjToNet(macaid))
	--Wait(1000)
	pegouPlayer = true
	PlayerColo = pacientemacasolta
	LoadAnimDic("anim@heists@box_carry@")
	TaskPlayAnim(ped, 'anim@heists@box_carry@', 'idle', 8.0, 8.0, -1, 1, 0, false, false, false)
	TriggerServerEvent("BjornMedical:SyncAnimationColo",GetPlayerServerId(PlayerColo))
	TriggerEvent("Bjorn:cancelando",true)
	pacientemacasolta = nil
	pacientenamaca = false
	if not maletachao then
	TriggerEvent('BjornMedical:RetirarPlayerColo')
	end
	end
	end
	
	
	if pacientenamaca and not maletamao and not macamao and not tratando then
	local maca = GetClosestObjectOfType(coords, 2.0, GetHashKey(macaobj))
	local macacord = GetEntityCoords(maca,1)
	local vecMaletachao = vec3(cordMaletax,cordMaletay,cordMaletaz)
	local distance = #(coords-vecMaletachao)
	local vidapacientemaca = GetEntityHealth(GetPlayerPed(pacientemacasolta))
	--print(pacientemacasolta,vidapacientemaca,GetPlayerIndex(pacientemacasolta))
	
	--if IsEntityAPed(GetPlayerPed(pacientemacasolta)) then
	--print("11111111")
	--end
	--local b = PlayerPedId(pacientemacasolta)
	--local vidapacientemaca2 = GetEntityHealth(b)

	
	if vidapacientemaca < config.vidafull then
	--print(vidaPaciente,config.vidamorte)
	if vidapacientemaca > config.vidamorte then
	if maletachao and distance < 5 then
	DrawText3D(macacord.x,macacord.y,macacord.z+1.4, config.lang["treatment"])
	else
	DrawText3D(macacord.x,macacord.y,macacord.z+1.4, config.lang["warn5"])
	end
	if not maletachao then
	DrawText3D(macacord.x,macacord.y,macacord.z+1.4, config.lang["warn9"])
	end
	else
	DrawText3D(macacord.x,macacord.y,macacord.z+1.4, config.lang["warn12"])
	end
	
	if IsControlJustPressed(0,38) or IsDisabledControlJustPressed(0,38) and GetSelectedPedWeapon(ped) == GetHashKey('WEAPON_UNARMED') and maletachao and distance < 5 then	
	tratando = true
	FreezeEntityPosition(ped,true)
	TriggerEvent("Notify","aviso",config.lang["warn13"])
	LoadAnimDic("mini@repair")
	TaskPlayAnim(ped, 'mini@repair', 'fixing_a_ped', 8.0, 8.0, -1, 50, 0, false, false, false)	
	--TriggerEvent("Bjorn:cancelando",true)
	Wait(30000)
	ClearPedTasks(ped)
	tratando = false
	TriggerServerEvent("BjornMedical:SyncTreatMent",GetPlayerServerId(pacientemacasolta))
	TriggerEvent("Notify","sucesso",config.lang["warn14"])
	FreezeEntityPosition(ped,false)
	end
	else
	DrawText3D(macacord.x,macacord.y,macacord.z+1.4, config.lang["treated"])
	end
	end
	
	
	
	if IsControlJustPressed(0,47)  and GetSelectedPedWeapon(ped) == GetHashKey('WEAPON_UNARMED') and not IsPedInAnyVehicle(ped) and Bjorn.chkAuth() and not tratando then
	if not pegouPlayer then
	if macamao then
	macamao = false
	macachao = true
	cordMacax,cordMacay,cordMacaz = x,y,z-1
	ClearPedTasks(ped)
	DetachEntity(macaid, true, true)
	
	elseif macachao then
	local maca = GetClosestObjectOfType(coords, 2.0, GetHashKey(macaobj))	
	if maca == macaid then
	if not maletamao then
	macamao = true
	macachao = false
	AttachEntityToEntity(macaid, GetPlayerPed(-1), GetPlayerPed(-1), 0.0, 1.6, -0.43 , 180.0, 180.0, 180.0, 0.0, false, false, true, false, 2, true)
	TaskPlayAnim(ped, 'anim@heists@box_carry@', 'idle', 8.0, 8.0, -1, 50, 0, false, false, false)	
	else
	TriggerEvent("Notify","negado",config.lang["warn7"])
	end
	end
	end
	end
	end	
	end
end)


namaca = false

RegisterNetEvent('BjornMedical:SyncPlayerMacaSolta')
AddEventHandler('BjornMedical:SyncPlayerMacaSolta',function(macaid)
local ped = PlayerPedId()
if not namaca then
	namaca = true
	AttachEntityToEntity(ped,NetToObj(macaid),NetToObj(macaid), 0.0, 0.0, 1.4 , 180.0, 180.0, 0.0, 0.0, false, false, true, false, 2, true)
	
	--TaskPlayAnim(ped,"mini@cpr@char_b@cpr_str","cpr_kol_idle",3.0,-3.0,-1,1,0,0,0,0)
	
	--LoadAnimDic("combat@damage@writheidle_c")		
	--TaskPlayAnim(ped,'combat@damage@writheidle_c','writhe_idle_g', 8.0, 8.0, -1, 33, 0, 0, 0, 0)
	
	
	LoadAnimDic("mini@cpr@char_b@cpr_str")	
	TaskPlayAnim(ped,"mini@cpr@char_b@cpr_str","cpr_kol_idle",3.0,-3.0,-1,1,0,0,0,0)
	
else
	namaca = false
	DetachEntity(ped,true,false)	
	ClearPedTasks(ped)	
end
end)


----------------------------------------------------------------------------------------------------------------------------
------------------------------- EVENTO PARA ABRIR FECHAR AS PORTAS DO VEICULO
----------------------------------------------------------------------------------------------------------------------------

RegisterNetEvent("BjornMedical:SyncTreatMent")
AddEventHandler("BjornMedical:SyncTreatMent",function()
local ped = PlayerPedId()
	while GetEntityHealth(ped) < config.vidafull do
	TriggerServerEvent("Bjorn:Tratamento")
	Citizen.Wait(1000)
	end
end)

----------------------------------------------------------------------------------------------------------------------------
------------------------------- EVENTO PARA ABRIR FECHAR AS PORTAS DO VEICULO
----------------------------------------------------------------------------------------------------------------------------

RegisterNetEvent('BjornMedical:OpenAndCloseDoorsSource')
AddEventHandler('BjornMedical:OpenAndCloseDoorsSource',function()
local cord = GetEntityCoords(GetPlayerPed(-1), 1)
local vehicle = GetClosestVehicle(cord.x,cord.y,cord.z,5.0,0,71)
	if vehicle then
		TriggerServerEvent("BjornMedical:OpenAndCloseDoors",VehToNet(vehicle))
	end
end)

RegisterNetEvent('BjornMedical:OpenAndCloseDoors')
AddEventHandler('BjornMedical:OpenAndCloseDoors',function(index)
if NetworkDoesNetworkIdExist(index) then
		local v = NetToVeh(index)
		local isopen = GetVehicleDoorAngleRatio(v,3)
		local isopen2 = GetVehicleDoorAngleRatio(v,4)
		if DoesEntityExist(v) then
			if IsEntityAVehicle(v) then
				if isopen == 0 and isopen2 == 0 then
					SetVehicleDoorOpen(v,3,0,0)
					SetVehicleDoorOpen(v,2,0,0)
				else
					SetVehicleDoorShut(v,3,0)
					SetVehicleDoorShut(v,2,0)
				end
			end
		end
	end
end)


----------------------------------------------------------------------------------------------------------------------------
------------------------------- EVENTO PARA ENTRAR NA AMBULANCIA
----------------------------------------------------------------------------------------------------------------------------

RegisterNetEvent('BjornMedical:EnterAmbulance')
AddEventHandler('BjornMedical:EnterAmbulance',function(acento)   ------- ACENTO 1 É O ESQUERDO 2 É O DIREITO
	local ped = PlayerPedId()
	local cord = GetEntityCoords(ped,1)
	local vehicle = GetClosestVehicle(cord.x,cord.y,cord.z,5.0,0,71)
	if vehicle then
	if GetVehicleDoorLockStatus(vehicle) == 1 then
	if acento == 1 then
	TaskEnterVehicle(ped,vehicle,20000,1,1.0,1,0)
	elseif acento == 2 then
	TaskEnterVehicle(ped,vehicle,20000,2,1.0,1,0)
	end
	else
	TriggerEvent("Notify","negado",config.lang["warn10"])
	end
	end
end)



----------------------------------------------------------------------------------------------------------------------------
------------------------------- TD
----------------------------------------------------------------------------------------------------------------------------

function tD(n)
    n = math.ceil(n * 10) / 10
    return n
end

----------------------------------------------------------------------------------------------------------------------------
------------------------------- FUNCOES
----------------------------------------------------------------------------------------------------------------------------

function drawTxt(x,y,width,height,scale,text,r,g,b,a)
    SetTextFont(10)
    SetTextScale(scale,scale)
    SetTextColour(r,g,b,a)
    SetTextOutline()
    SetTextEntry("STRING")
    AddTextComponentString(text)
    DrawText(x,y)
end

function DrawText3D(x,y,z,text)
    local onScreen,_x,_y=World3dToScreen2d(x,y,z)
    local px,py,pz=table.unpack(GetGameplayCamCoords())   
    SetTextScale(0.34, 0.34)
    SetTextFont(4)
    SetTextProportional(1)
    SetTextColour(255, 255, 255, 215)
    SetTextEntry("STRING")
    SetTextCentre(1)
    AddTextComponentString(text)
    DrawText(_x,_y)
    local factor = (string.len(text)) / 330
    DrawRect(_x,_y+0.0125, 0.001+ factor, 0.028, 0, 0, 0, 150)
end

-----------------------------------------------------------------------------------------------------------------------------------------
--[ FUNCAO PARA PEGAR A CDS DO MINIMAPA A REALIZAR O DRAW 2D ]------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------------------

function GetMinimapAnchor()
    local safezone = GetSafeZoneSize()
    local safezone_x = 1.0 / tonumber("20.0")
    local safezone_y = 1.0 / tonumber("20.0")
    local aspect_ratio = GetAspectRatio(0)
    local res_x, res_y = GetActiveScreenResolution()
    local xscale = 1.0 / res_x
    local yscale = 1.0 / res_y
    local Minimap = {}
    Minimap.width = xscale * (res_x / (4 * aspect_ratio))
    Minimap.height = yscale * (res_y / 5.674)
    Minimap.left_x = xscale * (res_x * (safezone_x * ((math.abs(safezone - tonumber("1.0"))) * 10)))
    Minimap.bottom_y = tonumber("1.0") - yscale * (res_y * (safezone_y * ((math.abs(safezone - tonumber("1.0"))) * 10)))
    Minimap.right_x = Minimap.left_x + Minimap.width
    Minimap.top_y = Minimap.bottom_y - Minimap.height
    Minimap.x = Minimap.left_x
    Minimap.y = Minimap.top_y
    Minimap.xunit = xscale
    Minimap.yunit = yscale
    return Minimap
end	

-----------------------------------------------------------------------------------------------------------------------------------------
--[ CARREGA ANIM ]--------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------------------

function LoadAnimDic(dict)
	RequestAnimDict(dict)
	while not HasAnimDictLoaded(dict) do
		Citizen.Wait(300)
	end
end

-----------------------------------------------------------------------------------------------------------------------------------------
--[ FUNCAO QUE PEGA PLAYER PROX ]--------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------------------
function GetClosestPlayer()
    local players = GetPlayers()
    local closestDistance = -1
    local closestPlayer = -1
    local ply = GetPlayerPed(-1)
    local plyCoords = GetEntityCoords(ply, 0)
    
    for index,value in ipairs(players) do
        local target = GetPlayerPed(value)
        if(target ~= ply) then
            local targetCoords = GetEntityCoords(GetPlayerPed(value), 0)
            local distance = Vdist(targetCoords["x"], targetCoords["y"], targetCoords["z"], plyCoords["x"], plyCoords["y"], plyCoords["z"])
            if(closestDistance == -1 or closestDistance > distance) then
                closestPlayer = value
                closestDistance = distance
            end
        end
    end
    if closestPlayer ~= -1 then
    return closestPlayer
	end
end

function GetPlayers()
	local pedId = PlayerId()
    local players = {}

    for i = 0, 256 do	
        if NetworkIsPlayerActive(i) and i ~= pedId then
            table.insert(players, i)
        end
    end

    return players
end


-----------------------------------------------------------------------------------------------------------------------------------------
--[ CANCELANDO O F6 ]--------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------------------
local cancelando = false
RegisterNetEvent('Bjorn:cancelando')
AddEventHandler('Bjorn:cancelando',function(status)
local ped = PlayerPedId()
cancelando = status
while cancelando do
	if cancelando then
			BlockWeaponWheelThisFrame()
			DisablePlayerFiring(ped,true)
			DisableControlAction(0,29,true)
			DisableControlAction(0,38,true)
			DisableControlAction(0,47,true)
			DisableControlAction(0,56,true)
			DisableControlAction(0,57,true)
			DisableControlAction(0,73,true)
			DisableControlAction(0,137,true)
			DisableControlAction(0,166,true)
			DisableControlAction(0,167,true)
			DisableControlAction(0,169,true)
			DisableControlAction(0,170,true)
			DisableControlAction(0,182,true)
			DisableControlAction(0,187,true)
			DisableControlAction(0,188,true)
			DisableControlAction(0,189,true)
			DisableControlAction(0,190,true)
			DisableControlAction(0,243,true)
			DisableControlAction(0,245,true)
			DisableControlAction(0,257,true)
			DisableControlAction(0,288,true)
			DisableControlAction(0,289,true)
			DisableControlAction(0,311,true)
			DisableControlAction(0,344,true)							
	else
		break
	end
	Wait(4)
end	
end)
 

Lua online compiler

Write, Run & Share Lua code online using OneCompiler's Lua online compiler for free. It's one of the robust, feature-rich online compilers for Lua language, running the latest Lua version 5.4. Getting started with the OneCompiler's Lua editor is easy and fast. The editor shows sample boilerplate code when you choose language as Lua and start coding.

Taking inputs (stdin)

OneCompiler's Lua online editor supports stdin and users can give inputs to programs using the STDIN textbox under the I/O tab. Following is a sample Lua program which takes name as input and prints hello message with your name.

name = io.read("*a")
print ("Hello ", name)

About Lua

Lua is a light weight embeddable scripting language which is built on top of C. It is used in almost all kind of applications like games, web applications, mobile applications, image processing etc. It's a very powerful, fast, easy to learn, open-source scripting language.

Syntax help

Variables

  • By default all the variables declared are global variables
  • If the variables are explicitly mentioned as local then they are local variables.
  • Lua is a dynamically typed language and hence only the values will have types not the variables.

Examples

-- global variables
a = 10

-- local variables

local x = 30
Value TypeDescription
numberRepresents numbers
stringRepresents text
nilDifferentiates values whether it has data or not
booleanValue can be either true or false
functionRepresents a sub-routine
userdataRepresents arbitary C data
threadRepresents independent threads of execution.
tableCan hold any value except nil

Loops

1. While:

While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.

while(condition)
do
--code
end

2. Repeat-Until:

Repeat-Until is also used to iterate a set of statements based on a condition. It is very similar to Do-While, it is mostly used when you need to execute the statements atleast once.

repeat
   --code
until( condition )

3. For:

For loop is used to iterate a set of statements based on a condition.

for init,max/min value, increment
do
   --code
end

Functions

Function is a sub-routine which contains set of statements. Usually functions are written when multiple calls are required to same set of statements which increase re-usuability and modularity.

optional_function_scope function function_name( argument1, argument2, argument3........, argumentn)
--code
return params with comma seperated
end