1

I was trying to write a function with a variable number of arguments which do something for all its number entries. so I came up with something like this:

function luaFunc (...)
   for i,v in ipairs{...} do
      if type(v)=='number' then
         --do something
      end
   end
end

but when i run this, it stops right on first non-number argument. whats the problem?

4
  • 3
    It stops at the first nil argument not at the first non-number argument. Commented Mar 25, 2013 at 12:25
  • thats right, thank you lhf. Commented Mar 25, 2013 at 13:36
  • 1
    if you read the docs for ipairs, it specifically tells you that it does this. i think what you are looking for here is the pairs function, which iterates all keys in a table (not necessarily in order). Commented Mar 25, 2013 at 16:26
  • @MikeCorcoran, thank you. that's simply the solution. Commented Mar 25, 2013 at 21:35

2 Answers 2

1
local function luaFunc (...)
   for i = 1, select('#',...) do
      local v = select(i,...)
      if type(v)=='number' then
         --do something
         print(v)
      end
   end
end
luaFunc (1,'a',nil,2)     ]

-- Output
1
2
Sign up to request clarification or add additional context in comments.

Comments

1

Try also this:

function luaFunc (...)
   local t=table.pack(...)
   for i=1,t.n do
      local v=t[i]
      if type(v)=='number' then
         print(i,v)
      end
   end
end

luaFunc(10,20,"hello",40,nil,60,print,99)

4 Comments

also useful. thank you. btw why should the iteration with ipairs not work? the element has a key and has a value which is nil ..
@VahidM, ipairs uses the # operator on the table to determine how many elements it has but # is not useful for tables with holes (nil entries).
I've just tested # operator for a table with nil entries and it worked fine. It must be something else. thank you anyway.
@VahidM, try N=100; t={}; for i=1,N do t[i]=i end; t[64]=nil; print(#t).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.