Jump to content

Como acessar o valor de um array?


Recommended Posts

Posted

Estou com um problema, não estou conseguindo acessar o valor de uma tabela, Estou tentando comparar se o marker que o player entrou é o marker criado pra ele (markers.thePlayer["startMarker"] = createMarker...) 

if marker == markers.source["startMarker"] -- Só que é como se eu estivesse tentando indexar um valor e não comparar, como eu faço para fazer essa comparação?

Debugscript = attempt to index a field 'source' ( a nil value )

Server-side

veh = {}
markers = {
    
}

-- Cria os veiculos e coloca na table veh
for i=1,6 do
	veh[createVehicle(459, 1700.75781 + 3*i, -1806.09680, 13.54688, 0,0,0)] = true
end

-- Quando o player entra no vehicle
addEventHandler ( "onVehicleEnter", getRootElement(), function(thePlayer, seat)
    if not markers.thePlayer then
        markers.thePlayer = {}
    end
    -- Se o veiculo que o player entrou pertence ao trabalho entao
    if veh[getPedOccupiedVehicle(thePlayer)] then
        -- Cria um marker para o player
        print(tostring(thePlayer))
        markers.thePlayer["StartMarker"] = createMarker(1683.57776, -1811.70239, 13.54688 - 0.8, "cylinder", 3, 255, 0, 0, 255, thePlayer)
    end   
end)

addEventHandler("onPlayerMarkerHit", getRootElement(), function(marker, dim)
    if dim then
        if marker == markers.source["StartMarker"] then print ("entrou") end -- ERRO Eu meio que estou tentando colocar algo no index ao inves de comparar
    end
end)

-- Otimização 
addEventHandler( "onPlayerQuit", root,
	function()
		if markers[source] then
			for k,v in pairs(markers[source]) do
				if isElement(v) then destroyElement(v) end
			end
			markers[source] = nil
		end
	end
)
Posted

Uma dúvida, não seria melhor eu passar para o client, no caso quando criar novos marker no client, não vai ser exclusivo para ele? Esse é meu objetivo fazer marker só para um player especifico. 

Posted

Tive que refazer o mod completamente, passei para o client, eu tenho uma tara por fazer server-side, eh um trabalho, esta funcionando parcialmente, sim teria mais de um marker

Posted
4 hours ago, Developer. said:

troque o ponto ( . ) por colchetes ( [ )


markers[thePlayer]["StartMarker"] = createMarker(...)

if marker == markers[source]["StartMarker"] then

 

Acho, que fazendo dessa maneira markers[thePlayer]["StartMarker"], vai retorna em nil value.

" Se eu te ajudei, deixe sua avaliação, obrigado ! "

Joinha!

 

Posted (edited)

 

10 hours ago, Gaimo said:

Uma dúvida, não seria melhor eu passar para o client, no caso quando criar novos marker no client, não vai ser exclusivo para ele? Esse é meu objetivo fazer marker só para um player especifico. 

Na função createMarker(server-side) tem um argumento que você pode especificar para qual elemento o marker deve ser visível, e também há uma função chamada setElementVisibleTo que você pode usar para definir quem poderá ver o marker.

Edited by KronoS Lettify
Correção

Dê um THANKS se minha ajuda ou comentário foi útil para você.   spacer.png 

Posted (edited)

Bom questionamento, porém acredito eu que não. Pois no if eu estou comparando a "data" da marker hitada, com a "data" salva na tabela.

Quando o gaimo salva a marker na tabela acredito eu que seja algo mais ou menos assim:

markers = { -- a tabela nomeada
	userdata = { -- uma segunda tabela(sub-tabela), que seria a userdata ([thePlayer])
		["StartData"] = markerData -- e por fim ele salva a "data" do marker.
	},
};

Seguindo a lógica acima, o que me importa é a markerData, então quando eu faço assim:

if marker == markers[source]["StartMarker"] then 

Eu to querendo dizer:

SE a data da marker hitada é equivalente a data que esta dentro da sub-tabela(source, que no caso é a userdata) com index de ["StartMarker"] então faça:

Abaixo o código, testado:

veh = {};
markers = {};

for i=1,6 do
	veh[createVehicle(459, 1700.75781 + 3*i, -1806.09680, 13.54688, 0,0,0)] = true;
	createBlip(1700.75781, -1806.09680, 13.54688);
end

addEventHandler ( "onVehicleEnter", getRootElement(), 
function(thePlayer, seat)
    if not markers[thePlayer] then
        markers[thePlayer] = {};
    end
    if veh[getPedOccupiedVehicle(thePlayer)] then
		markers[thePlayer]["StartMarker"] = createMarker(1683.57776, -1811.70239, 13.54688 - 0.8, "cylinder", 3, 255, 0, 0, 255, thePlayer);
		createMarker(1683.57776, -1811.70239 + 5, 13.54688 - 0.8, "cylinder", 3, 0, 255, 0, 255, thePlayer);
		createBlipAttachedTo(markers[thePlayer]["StartMarker"]);
		outputChatBox("marker table: "..tostring(markers[thePlayer]), thePlayer, 255, 255, 0); -- debug
		outputChatBox("marker data: "..tostring(markers[thePlayer]["StartMarker"]), thePlayer, 255, 255, 0); -- debug
    end   
end)

addEventHandler("onPlayerMarkerHit", getRootElement(), 
function(marker, dim)
	if dim then
	outputChatBox("onHit: "..tostring(marker), source, 0, 255, 0); -- debug
		if marker ~= markers[source]["StartMarker"] then -- se for diferente
			outputChatBox("o marker é diferente", source, 255, 0, 0); 
		else -- se for igual
			outputChatBox("o marker é igual", source, 0, 255, 0);
		end
    end
end)

addCommandHandler("teste",
	function(player)
		for index, value in pairs(markers) do -- se fizer com ipairs não irá funcionar, por causa do "StartMarker"
			outputChatBox(" #ff0000indexado: #ffffff"..tostring(index).." #ff0000tabela: #ffffff"..tostring(value).." #ff0000valorReal: #ffffff"..tostring(value["StartMarker"]),player, 255, 0, 255, true);
		end
	end
)

Abaixo mais uma "prova" dessa explicação, agora com tudo declarado:

test = { -- tabela nomeada
	test2 = { -- "sub-tabela"
		["value"] = 10, -- index contendo o valor desejado.
	},
};

for i, v in pairs(test) do
	outputChatBox(tostring(v["value"]));
end

OBS (muito importante): Eu tenho absoluta certeza do que estou falando?

R: Nem um pouco, provavelmente posso estar falando groselha, e se estiver quem souber melhor por favor comente xD. Porém os códigos acima foram testados e funcionou!

@Angelo Pereira

Edited by Developer.

9hTejIE.gif

<New Dream's ℠/>

our discord: https://discord.gg/xwzYeAT

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...