Lua associative arrays

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
geocine
Prole
Posts: 16
Joined: Sat Aug 04, 2012 5:17 pm

Lua associative arrays

Post 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
User avatar
dreadkillz
Party member
Posts: 223
Joined: Sun Mar 04, 2012 2:04 pm
Location: USA

Re: Lua associative arrays

Post 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
User avatar
Robin
The Omniscient
Posts: 6506
Joined: Fri Feb 20, 2009 4:29 pm
Location: The Netherlands
Contact:

Re: Lua associative arrays

Post 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
Help us help you: attach a .love.
Post Reply

Who is online

Users browsing this forum: Google [Bot] and 5 guests