From the manual:
-- The size of a table indexed with sequential 1-based integers:
PRINT(#A) -- 4
Tables indexed in other ways won't behave as you might expect.
I guess pico doesn't allow the use of tables as table Keys.
I was just trying to use a table with an x and y coord as key, So i guess i'll just 'cast' it to a string.
EDIT
My apologies, tbsp. I just read your comment again along by reading the docs and understand what you were pointing out. It seems lua/pico does accept certain kinds of table key types but as you mentioned, the # sign doesn't count non-1-based indexes.
i guess i have to find another way to iterate over non-1-based indexed tables instead of using 'while #t > 0'.
Thanks anyways tho
hey kozie!
you can definitely use tables as table keys.
objects = {} obj = {x=1,y=2} objects[obj] = obj print(objects[obj].x) foreach k,v in pairs(objects) do print(v.x..','..v.y) end |
Hi impbox.
Thanks for the clarification and the example code. Tho, as you can see, I've found out I can use tables as keys. Only problem I found is that I can't get the table length using the # operator.
I managed to get the count using a custom function, iterating over a table using for and pairs() and incrementing a 'count' variable for each iteration.
This way I can still use a while in combination with the table length being higher than 0.
Well, this is an interesting reading..
u = {['@!#'] = 'qbert', [{}] = 1729, [6.28] = 'tau'} -- Key matching is basically by value for numbers and strings, but by identity -- for tables. a = u['@!#'] -- Now a = 'qbert'. b = u[{}] -- We might expect 1729, but it's nil: -- b = nil since the lookup fails. It fails because the key we used is not the -- same object as the one used to store the original value. So strings & -- numbers are more portable keys.d |
Yeah, it's also important to note that tables won't get copied automatically.
Example:
A = {} A[1] = "Hello" A[2] = "World" B = A B[2] = "Mars" Print(A[2] == "Mars") -- true, because B and A point to the same actual table |
If you want to make a copy of a table you can change independently, you need to copy all the values into the new table manually.
[Please log in to post a comment]