Log In  

I know i can add entries to a table using the add function but it seems i can't add using keys.

For example:

local key = {1,2}
local t = {}
t[key] = true

print(#t)

this seems to return 0. Any clues?

P#14940 2015-10-03 18:22 ( Edited 2015-10-06 06:29)

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.

P#14941 2015-10-03 19:04 ( Edited 2015-10-03 23:04)

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

P#14959 2015-10-04 10:16 ( Edited 2015-10-04 21:16)

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
P#14985 2015-10-04 23:23 ( Edited 2015-10-05 03:23)

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.

P#14992 2015-10-05 04:48 ( Edited 2015-10-05 08:48)

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

Source

P#15010 2015-10-05 15:30 ( Edited 2015-10-05 19:30)

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.

P#15011 2015-10-05 16:52 ( Edited 2015-10-05 20:52)

Ah! Thanks for that info :)

P#15024 2015-10-06 02:29 ( Edited 2015-10-06 06:29)

[Please log in to post a comment]

Follow Lexaloffle:          
Generated 2024-04-19 20:57:51 | 0.010s | Q:17