View Single Post
05-07-12, 05:56 PM   #1
Ketho
A Pyroguard Emberseer
 
Ketho's Avatar
AddOn Author - Click to view addons
Join Date: Mar 2010
Posts: 1,026
tables, table.unpack and nil values

  • I'm confused why the first example does print the nil values, but the latter does not.
    Aren't these tables the "same"?
    1. Lua Code:
      1. local t = {nil, nil, 3, 7, nil, 4}
      2.  
      3. print(#t) -- 6
      4. print(unpack(t)) -- nil, nil, 3, 7, nil, 4
    2. Lua Code:
      1. local t = {}
      2. t[3] = 3
      3. t[4] = 7
      4. t[6] = 4
      5.  
      6. print(#t) -- 0
      7. print(unpack(t)) -- nil
    I was always thinking that table.unpack can't iterate over "holes" in the same way as an ipairs-loop
    (I'm not a programmer, and I don't know what's the proper terminology)

  • On another note, I'm also wondering about this (4 months old) post from Lur,
    concerning tables with a nil value at the end of a table
    Originally Posted by Lur View Post
    Thanks a lot. But why
    Lua Code:
    1. local t1 = {1, 2, nil, "wwew", nil, 3} -- #t1 = 6
    2. local t2 = {1, 2, nil, "wwew", 3, nil} -- #t2 = 2

    What's wrong with all of that? Why tables with a nil as the last value are truncated to the first nil occurrence while with any non-nil end are counted correct?
  Reply With Quote