How to InsertItem [cell] = data?

Find quick help here to get you started with Hollywood
Post Reply
Bugala
Posts: 1178
Joined: Sun Feb 14, 2010 7:11 pm

How to InsertItem [cell] = data?

Post by Bugala »

I have an empty table:

Code: Select all

mytable={}
what i want it to look like in the end is:

Code: Select all

mytable = {
          ["name1"] = variable1,
          ["name2"] = variable2
               }
But I am creating this list on the fly as needed, and I am planning to use InsertItem and RemoveItem commands to achieve it, but I am having trouble how to actually do it?

For example:

Code: Select all

temptable = { ["name1"] = variable1 }

insertitem(mytable, temptable)
would result in:

Code: Select all

mytable = {
                   {   ["name1"] = variable1 },
                   {   ["name2"] = variable2 }
                         }
I can get it done this way:

Code: Select all

temptable["name1"] = variable1
But i would rather use insertitem instead, so how do i actually do it the way i am wainting to?
Should be simplest of thing to achieve, but i just cant figure out how to.
SamuraiCrow
Posts: 475
Joined: Fri May 15, 2015 5:15 pm
Location: Waterville, Minnesota USA

Re: How to InsertItem [cell] = data?

Post by SamuraiCrow »

For a result that will look like this:

Code: Select all

setItem(mytable,"name1",variable1)
variable2=getItem(mytable,"name2")
Implementing it will involve inserting the function into the table as a member:

Code: Select all

mytable={}

function setItem(table,key,value)
  table[key]=value
endfunction

function getItem(table,key)
  return(table[key])
endfunction
The main reason for doing this is so you can add sanity checks and overwrite checks to the set method and empty field checks to the get method. Normally with an object-oriented language you could add a set and get method for every field in a class but with tables this is unnecessary.

-edit-
Using the __index and __newindex metamethods would allow you to keep the original syntax with the square brackets while adding the checks to the reads and writes. See http://hollywood-mal.com/docs/html/holl ... OprMM.html for how to do metamethods on tables.
I'm on registered MorphOS using FlowStudio.
Bugala
Posts: 1178
Joined: Sun Feb 14, 2010 7:11 pm

Re: How to InsertItem [cell] = data?

Post by Bugala »

Thanks from idea. SetItem didnt even cross my mind.
Post Reply