Problems with tables

Posted by Katherina on Wed 30 Jul 2008 04:37 PM — 3 posts, 17,041 views.

#0
Hi,
I have read what I can find in the forum, gone to lua.org, gone to other lua forums and I can't figure out what I'm doing wrong or how to do what I want to.
I'm rewriting my combat system for aetolia, what I'm trying to do is have an alias that allows you to add certain data to a table. In this case it's keeping track of weapons. The fields are character name, weapon type, which hand and weapon number. I can enter these into the table fine but if I go to add a second weapon it's not appending to the table but overwriting it. I tried working with insert and get all kinds of errors, what is working is with the table name being weapons.
weapons.name = charname
weapons.type = temptype
weapons.hand = weaponhand
weapons.number = tempnumber
that adds it fine but it's overwriting the other records. Now in my script file I have weapons = { } to initialize the table, is it erasing the contents of the table? If so how do I keep the data in the table and load it when I start mushclient?

The second issue is, if the data is being over written my buffer tables are no use to me and I just spent three days coding for nothing. I have afflictions, defenses and so forth going into a table to temporarily store the variable, then on the prompt set the variables and clear the table, however there may be up to four afflictions before a new prompt so if it's over writing i'm only going to be storing the last affliction I need all of them.

Please help I'm very frustrated and having a hard time finding examples I can understand or anything that really relates.
USA #1
What you actually want is a table of tables, not just one table. The outer table is a list of tables, each of which is a weapon record.

So, you want something like this:


-- create the list of weapons
weapons = {}

-- create one weapon record
weapon = {}

-- add it to the list
table.insert(weapons, weapon)

-- populate its values
weapon.field1 = val1
weapon.field2 = val2
weapon.field3 = val3
-- etc.


Every time you run "weapons = {}" you are clearing the list of weapons, which is probably not what you want to do.

As for saving and loading the data, Nick has some serialization functions that do the job very nicely. I don't remember the link off-hand, but there's a page in the forums that gives several examples on how to save/load data from/into Lua.
Australia Forum Administrator #2
See this post about serializing Lua tables into a string:

http://www.gammon.com.au/forum/?id=4960

It only take a few lines of code, and a huge table can be saved and reloaded next time.