Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

adding a key value pair in table.insert

edited March 2013 in Questions Posts: 58

Is there any way to add a key value pair to a table? Whenevery I try, it gives me a syntax error. I tried to get around this by setting the value manually after the table was made, using ~ myTable["myKey"] = myValue ~ but it never actually saves this value (as far as I can tell.) Is adding a key value pair to a table even possible using table.insert? Should my manual way still work? Thanks in advance,
edat44

Comments

  • Jmv38Jmv38 Mod
    Posts: 3,295

    myTable["myKey"] = myValue works. The error is elsewhere, check your code.

  • Posts: 202

    A table can serve different purposes.

    If you use table.insert then you use is as a list, the contained elements start at index 1, advancing by 1 without a gap. You can iterate over a list with both pairs() and ipairs().

    If you say myTable["myKey"] = myValue then you use the table as a hash. You can only properly iterate over a hash table with pairs().

    There are similarities between the two so both are handled by the same data structure, but you shall take care and not mix the modes.

Sign In or Register to comment.