LuaTable to array in C#

Nov 18, 2014 at 11:27 PM
Edited Nov 18, 2014 at 11:35 PM
Hello, I need a help again with the tables .

// Lua
test={}
test[1] = 1
test[2] = 20
test[3] = 330
test[4] = 1
test[5] = 5
test[6] = 5

// C#
LuaTable table = (LuaTable)g["test"];
((LuaTable)g["test"]).Length;
string[] arr = new string[] { table[1].ToString(), ... };

Console.Writeline(arr[1].Tostring());
...........


I want to get the length of the table, test = {} and save the values to the "string[] arr". Based on the length of test = {} table , I want to get the values inside the arr[0]... arr[table length] instead of specifying them manually as I showed above { table[1].ToString(), ... .., table[6].Tostring()}.

To be simple, the values of the table and length will vary every time, so need to take the length of table and save the values inside string[] arr = new string[] {.........} and print them !
Coordinator
Nov 19, 2014 at 11:37 AM
.net has a easy to do this: Linq.
And NeoLua supports this feature to.
string[] arr = t.ArrayList.Select(c => c.ToString()).ToArray();
foreach (string s in arr)
  Console.Write("{0}, ", s);
Nov 19, 2014 at 12:25 PM
Edited Nov 19, 2014 at 12:26 PM
Yeah thanks a lot got the answer same way like this:
             List<string> list = new List<string>();
             foreach (object item in t.Values)
             {
                 list.Add(Convert.ToString(item));
             }
             string[] Phase = list.ToArray();
             Console.WriteLine(Phase[0]);
Coordinator
Nov 19, 2014 at 2:24 PM
LuaTable.Values returns all items of a lua table. Not only the array part.
Secondly, it is a Dictionary, so item is a key/value pair.

To access the array part, use ArrayList. For members, Members-Dictionary.

If you want access on all elements they are hashed by an index. Use t.Values.
foreach(var c in t.Values)
{
  if (c.Key is int)
     Console.Write("{0}, "c.Value);
}
Btw. your code is really slow and memory consuming. Alternative:
string[] arr = new string[t.Length];
for(int i = 1; i <= t.Length; i++)
  arr[i - 1] = Convert.ToString(t[i]);