• Using tables...
    4 replies, posted
Hello FP, I'm wondering if anyone can help me, I'm wanting to store 2 vars inside 1 index, so it'd print like this... [CODE] MyTable = {} Output: -> MyTable[1] = var1, var2 [/CODE] Any way how i can do this?
[QUOTE=Chickengbs;51775482]Hello FP, I'm wondering if anyone can help me, I'm wanting to store 2 vars inside 1 index, so it'd print like this... [CODE] MyTable = {} Output: -> MyTable[1] = var1, var2 [/CODE] Any way how i can do this?[/QUOTE] You can do: [CODE] MyTable ={} MyTable[1] = {} MyTable[1][1] = var1 MyTable[1][2] = var2 [/CODE] [B]Same as above, but differently laid out:[/B] [CODE] MyTable= { [1] = { var1, var2 } } [/CODE] [CODE] PrintTable(MyTable) [1] [1] = var1 [2] = var2 [/CODE]
So essentially this is called a table in a table right? [editline]4th February 2017[/editline] How would i lets say insert a value using table.insert with your method? [editline]4th February 2017[/editline] As an example would be, if I wanted to insert some variables automatically like so... [CODE] table.insert(MyTable, var1, var2) ??????? [/CODE]
you would have to wrap it in a table using the {} syntax. [lua] table.insert(MyTable, { var1, var2} ) [/lua] this is because table.insert only takes 2 arguments by default, there's ways using varargs that you can do it using custom functions such as the one below: [lua] function table.insertFew( tab, ... ) table.insert( tab, { ... } ) end [/lua] if you use a custom function such as table.insertFew, you can place objects in tables the way you proposed before. eg [lua] table.insertFew( MyTable, var1, var2, var3 ) etc [/lua]
Ah, so that's what I can do! Thanks!! [editline]4th February 2017[/editline] So if I wanted to print or access an index would I do print(MyTable[1][1])? -- that'd print var 1 in index 1?
Sorry, you need to Log In to post a reply to this thread.