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 .
geocine
Prole
Posts: 16 Joined: Sat Aug 04, 2012 5:17 pm
Post
by geocine » Fri Aug 24, 2012 7:18 am
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?
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
dreadkillz
Party member
Posts: 223 Joined: Sun Mar 04, 2012 2:04 pm
Location: USA
Post
by dreadkillz » Fri Aug 24, 2012 7:52 am
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.
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
Robin
The Omniscient
Posts: 6506 Joined: Fri Feb 20, 2009 4:29 pm
Location: The Netherlands
Contact:
Post
by Robin » Fri Aug 24, 2012 8:44 pm
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
Users browsing this forum: Bing [Bot] , Google [Bot] and 6 guests