rain_gloom Posted September 2, 2014 Share Posted September 2, 2014 Unpack uses the length of the array part by default, so if your table has a "hole" in it, the unpacking will stop before that hole. eg.: print(unpack{1,2,3,nil,5}) will give you 1,2,3 That is because 5 is not stored in the array part. If you do not know what that is, I recommend googling it. You could learn a few things about optimizing Lua code as well. Bottom line: unpack does not like nils. There are quite a few ways to deal with this (as there are to everything in Lua), but many of them implement metamethods and some placeholder for nil, which is not really flexible. Simplest solution: define an explicit 'n' field and use that with unpack. This is also how vararg functions work, they also define such a field i their 'arg' table. eg.: unpack(t,1,t.n) This also means that you must store the table in some way, but that's not quite as big an overhead as calling through a metamethod. It is also portable through MTA calls and exportable to JSON and other common formats. (metatables are not) Link to comment
qaisjp Posted September 27, 2014 Share Posted September 27, 2014 rain, this is because unpack is defined for indexed tables, not dictionary tables. You're essentially writing a "tutorial" to make unpack support the wrong syntax You're also using tables wrong. Tables don't have nil values. It might sound like it does. But it doesn't. When t[key] == nil, it denotes the absence of a value. t[key] = nil removes the value. Link to comment
Feche1320 Posted October 29, 2014 Share Posted October 29, 2014 Instead of nil use a value of eg -1 so you know that there is 'no value' in there. Link to comment
rain_gloom Posted November 16, 2014 Author Share Posted November 16, 2014 rain, this is because unpack is defined for indexed tables, not dictionary tables. You're essentially writing a "tutorial" to make unpack support the wrong syntaxYou're also using tables wrong. Tables don't have nil values. It might sound like it does. But it doesn't. When t[key] == nil, it denotes the absence of a value. t[key] = nil removes the value. Instead of nil use a value of eg -1 so you know that there is 'no value' in there. Sounds good actually. While we are at tables, here is how I know it: A table in Lua has two parts (implementation-wise): an array part and a hash (or dictionary or whatever you want to call it) part. The array part of table 't' is from t[1] to t[#t] and if the table only has an array part, it is called a sequence. Anyways, using a substitute value would actually be faster, but I'm not sure if that's true for decoding the substitute. I'll test it sometime. Maybe. Anyways, I preferred this method because the code reading the table does not need to know what the substitute value is, but maybe it would be bad for larger scale usage. Link to comment
Recommended Posts