Page 1 of 1

Lua associative arrays

Posted: Fri Aug 24, 2012 7:18 am
by geocine
I have this code.

Code: Select all

local colors = {
		red = { r = 255,g = 0,b = 0 },
		green = { r = 0,g = 128,b = 0 },
		blue = { r = 0,g = 0,b = 255},
	}
Why can't I access this using indices? Am I doing something wrong?

Code: Select all

colors[1].r
I could access it through indices using this declaration

Code: Select all

local colors = {
		{ r = 255,g = 0,b = 0 },
		{ r = 0,g = 128,b = 0 },
		{ r = 0,g = 0,b = 255},
	}
However I would like to be able to access it using

Code: Select all

colors[1].r
-- and
color.red.r

Re: Lua associative arrays

Posted: Fri Aug 24, 2012 7:52 am
by dreadkillz
Lua's table contains two parts: The hash and the array. Your first table contains keys in the hash part, (red,green,blue keys). If you want to access your values with numbered indices You'll have to add your value to the array part as well.

Code: Select all

t[key] = value
t[1] = value
This is kinda silly though as you have duplicate values for no reason. If you're planning on iterating through your table in a certain order, I recommend storing your values with indices.

Code: Select all

for i = 1,#t do
... -- do stuff with t
end

Re: Lua associative arrays

Posted: Fri Aug 24, 2012 8:44 pm
by Robin
You could do:

Code: Select all

local colors = {
      { r = 255,g = 0,b = 0 },
      { r = 0,g = 128,b = 0 },
      { r = 0,g = 0,b = 255},
   }

local color_names = {'red', 'green', 'blue'}

for i = 1, #colors do
    colors[color_names[i]] = colors[i]
end