Page 1 of 1
Table Definition Question
Posted: Sun Jun 08, 2025 6:04 pm
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
Re: Table Definition Question
Posted: Sun Jun 08, 2025 11:04 pm
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
Re: Table Definition Question
Posted: Mon Jun 09, 2025 6:50 am
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
Re: Table Definition Question
Posted: Mon Jun 09, 2025 5:41 pm
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.
Re: Table Definition Question
Posted: Mon Jun 09, 2025 6:04 pm
by Flinx
Another way to access the table without error on missing keys is
RawGet().
Re: Table Definition Question
Posted: Mon Jun 09, 2025 7:35 pm
by NathanH
Thanks for the help guys. I appreciate it.
NathanH