Page 1 of 1
lua tables
Posted: Wed Feb 04, 2009 11:59 pm
by philnelson
This is a lua question, but I assume it will be of use to new love2d people, also.
In PHP (the language I am most familiar with) I can, for example, create an multidimentional arrays like this:
, and then simply refer to it as
in order to get "a value". How can I accomplish this in lua? I've tried
, which seems to set the value but I cannot then get the value by saying
or similar.
Am I just doing this backwards? Is there a simpler way? I am willing to accept that I'm coming at this the wrong way for this language.
Re: lua tables
Posted: Thu Feb 05, 2009 12:07 am
by osgeld
you dont have to set the number when declaring it so
table = {key = "blah"}
is table.key when retrieving it
now if you did
table = {"foo", "bar"}
you would use table[1] or table[2] cause you didnt assign a variable name, which can be mixed, sorta
table = { {key = "foo", value = "bar"}, {item = "gun", ammo = 100}}
the above has 2 unnamed tables, with named contents all in 1 table, so if i wanted to get ammo
table[2].ammo
Re: lua tables
Posted: Thu Feb 05, 2009 12:10 am
by philnelson
The key is significant to the operation I'm doing. It is a unique ID that is generated elsewhere.
Re: lua tables
Posted: Thu Feb 05, 2009 12:14 am
by osgeld
i added alot since you posted
and heres the big book of plain lua
http://www.lua.org/manual/5.1/
Re: lua tables
Posted: Thu Feb 05, 2009 3:27 am
by Inny
Re: lua tables
Posted: Thu Feb 05, 2009 4:28 am
by osuf oboys
philnelson wrote:This is a lua question, but I assume it will be of use to new love2d people, also.
In PHP (the language I am most familiar with) I can, for example, create an multidimentional arrays like this:
, and then simply refer to it as
in order to get "a value". How can I accomplish this in lua? I've tried
, which seems to set the value but I cannot then get the value by saying
or similar.
Am I just doing this backwards? Is there a simpler way? I am willing to accept that I'm coming at this the wrong way for this language.
t[1] = {key='value1'} is correct but is inconsistent with t[1].key, which seems to indicate that there is a single key. If so, then you can use {key, value} as suggested by other posters. If you wish to store multiple values in t[1], then you may iterate the keys and values of t[1] with for k,v in pairs(t[1]).
Re: lua tables
Posted: Thu Feb 05, 2009 6:59 am
by bartbes
philnelson wrote:, which seems to set the value but I cannot then get the value by saying
or similar.
It works? Copied from lua interactive interpreter:
Code: Select all
> t = {}
> t[1] = { key = "value" }
> print(t[1].key)
value