Jump to content

Table order


manawydan

Recommended Posts

Posted

so iam try make this:

local t = {5,nil,2,nil,3} change to this t = {5,2,3}

i try make this but no work

function orderTable(t) 
local nt = {} 
local c = 0 
for k,v in ipairs(t) do 
if(v ~= nil)then 
c = c +1 
print(c) 
table.insert(nt,v) 
end 
end 
return nt 
end 
  
  
addCommandHandler("ta", 
function() 
local t = {5,nil,2,nil,3} 
j = orderTable(t) 
for k,v in ipairs(j)do 
print(tostring(v)) 
end 
end) 

any help?

560x95_FFFFFF_09FF00_050505_000000.png

"Querer não é poder, mas tentar é avançar"!

Posted

Check if the value is nil. If it is, use table.remove.

table.remove(theTable, theIndex); 

If I help you in a thread and you need further assistance, please don't PM me - use the thread you created instead. This way everyone on the forum can take advantage of it.

  • MTA Team
Posted

Yes, the solution is to use pairs as ipairs uses an iterator that only returns pairs of values attributed to numerical keys. This means that they can only return values defined in list format. In addition, if ipairs encounters any nil value, it will stop in its tracks, pairs, on the other hand, iterates through the entire table and returns keys that are non-numerical as well, so that's why you can't use ipairs to do the job.

Hope it helps.

DevOps Engineer, Cloud Advocate & Security Engineer(Red Team) | Coffee, Containers & Burp

 
Posted

i try make one new code and work

function orderTable(t) 
local nt = {} 
for i=1,#t do 
if(t[i] ~= nil)then 
table.insert(nt,t[i]) 
end 
end 
return nt 
end 

560x95_FFFFFF_09FF00_050505_000000.png

"Querer não é poder, mas tentar é avançar"!

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...