Table Definition Question

Find quick help here to get you started with Hollywood
Post Reply
NathanH
Posts: 128
Joined: Sun Jul 05, 2015 1:29 am
Location: Caldwell, Idaho

Table Definition Question

Post by NathanH »

Hi,

I'm using the following syntax:
t={}
t["Name"]="Nathan"
t["Email"]="myemail@gmail.com"

to define a table. A user specifies a string to access a member of the table. I thought that I could catch invalid field names via Hollywood error checking but it triggers as a syntax error so is uncatchable. As a work around, I make a second table which holds the valid field names. Is it possible to determine via code what the names of the fields are in the table t if it is defined this way? The second table would then be unnecessary. Thanks.

NathanH
Bugala
Posts: 1390
Joined: Sun Feb 14, 2010 7:11 pm

Re: Table Definition Question

Post by Bugala »

not sure what you are aiming at, but do you know HasItem()-command?

Code: Select all

mytable = {}
mytable["name"]
if hasitem(mytable, "name") = true
	debugprint("item exists")
else
	debugprint("item doesnt exist")
endif
NathanH
Posts: 128
Joined: Sun Jul 05, 2015 1:29 am
Location: Caldwell, Idaho

Re: Table Definition Question

Post by NathanH »

Hi,

Thanks, I wasn't aware of that command. It is useful. I was wondering if there was a way to iterate through the names.

NathanH
Bugala
Posts: 1390
Joined: Sun Feb 14, 2010 7:11 pm

Re: Table Definition Question

Post by Bugala »

Basically you can use something like:

Code: Select all

MyTable = {   ["name1"] = {stuff1 = 1, stuff2 = 2}, 
 				["name2"] = {stuff1 = 3, stuff2=4}  }
 
 foreach(MyTable, Function(Id, Content)
 	Debugprint(ID)
 	Debugprint(Content.Stuff1)
 			EndFunction
 		)
This would result in when you are Debugprinting ID, in it printing either "name1" or "name2".

To get access to the rest of the content, you could access them through content.name, like content.stuff2 in this examples case.

Idea is that Foreach goes through every item in MyTable.

Foreach command works in such way that you give it two args/parameters. First arg is the table which contents you wish to go through, second argument is what function to use to go through that table.

In this case I am making that function directly in there. Using Function(ID, Content) makes it in such way that ID contains the name of the ITEM, and Content has the actual ITEM, which in this case contains more items, as the ITEM in itself is a table in this case.

This might not be easiest possible to understand.
Flinx
Posts: 342
Joined: Sun Feb 14, 2021 9:54 am
Location: Germany

Re: Table Definition Question

Post by Flinx »

Another way to access the table without error on missing keys is RawGet().
NathanH
Posts: 128
Joined: Sun Jul 05, 2015 1:29 am
Location: Caldwell, Idaho

Re: Table Definition Question

Post by NathanH »

Thanks for the help guys. I appreciate it.

NathanH
Post Reply