Lua unpack bug?

北战南征 提交于 2019-11-29 09:30:55

The problem can be resolved simply by specifying the beginning and ending indexes to unpack() and using the table.maxn() as the ending index:

table1 = {true, nil, true, false, nil, true, nil}

a1,b1,c1,d1,e1,f1,g1 = unpack( table1, 1, table.maxn(table1) )
print ("table1:",a1,b1,c1,d1,e1,f1,g1)
-->table1: true    nil     true    false   nil     true    nil

The true reason for the discrepancy on how the two tables are handled is in the logic of determining the length of the array portion of the table.

The luaB_unpack() function uses luaL_getn() which is defined in terms of lua_objlen() which calls luaH_getn() for tables. The luaH_getn() looks at the last position of the array, and if it is nil performs a binary search for a boundary in the table ("such that t[i] is non-nil and t[i+1] is nil"). The binary search for the end of the array is the reason that table1 is handled differently then table2.

This should only be an issue if the last entry in the array is nil.

From Programming in Lua (pg.16) (You should buy this book.): When an array has holes--nil elements inside it--the length operator may assume any of these nil elements as the end marker. Therefore, you should avoid using the length operator on arrays that may contain holes.

The unpack() is using the length operator lua_objlen(), which "may assume any of [the] nil elements as the end" of the array.

2.2 - Values and Types

[...] The type table implements associative arrays, that is, arrays that can be indexed not only with numbers, but with any value (except nil). Tables can be heterogeneous; that is, they can contain values of all types (except nil). [...]

Given nil to an entry will break the table enumeration and your variables wont be init properly.

Here is a simple example that demonstrates a problematic behavior:

table1 = {true, false, nil, false, nil, true, nil}
for k,v in ipairs(table1) do
  print(k, v)
end

output:

1   true
2   false
>Exit code: 0
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!